Files
goose/bindings/kotlin/uniffi/goose_llm/goose_llm.kt

3097 lines
97 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// This file was autogenerated by some hot garbage in the `uniffi` crate.
// Trust me, you don't want to mess with it!
@file:Suppress("NAME_SHADOWING")
package uniffi.goose_llm
// Common helper code.
//
// Ideally this would live in a separate .kt file where it can be unittested etc
// in isolation, and perhaps even published as a re-useable package.
//
// However, it's important that the details of how this helper code works (e.g. the
// way that different builtin types are passed across the FFI) exactly match what's
// expected by the Rust code on the other side of the interface. In practice right
// now that means coming from the exact some version of `uniffi` that was used to
// compile the Rust component. The easiest way to ensure this is to bundle the Kotlin
// helpers directly inline like we're doing here.
import com.sun.jna.Callback
import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.Structure
import com.sun.jna.ptr.*
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.suspendCancellableCoroutine
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.CharBuffer
import java.nio.charset.CodingErrorAction
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
// This is a helper for safely working with byte buffers returned from the Rust code.
// A rust-owned buffer is represented by its capacity, its current length, and a
// pointer to the underlying data.
/**
* @suppress
*/
@Structure.FieldOrder("capacity", "len", "data")
open class RustBuffer : Structure() {
// Note: `capacity` and `len` are actually `ULong` values, but JVM only supports signed values.
// When dealing with these fields, make sure to call `toULong()`.
@JvmField var capacity: Long = 0
@JvmField var len: Long = 0
@JvmField var data: Pointer? = null
class ByValue :
RustBuffer(),
Structure.ByValue
class ByReference :
RustBuffer(),
Structure.ByReference
internal fun setValue(other: RustBuffer) {
capacity = other.capacity
len = other.len
data = other.data
}
companion object {
internal fun alloc(size: ULong = 0UL) =
uniffiRustCall { status ->
// Note: need to convert the size to a `Long` value to make this work with JVM.
UniffiLib.INSTANCE.ffi_goose_llm_rustbuffer_alloc(size.toLong(), status)
}.also {
if (it.data == null) {
throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=$size)")
}
}
internal fun create(
capacity: ULong,
len: ULong,
data: Pointer?,
): RustBuffer.ByValue {
var buf = RustBuffer.ByValue()
buf.capacity = capacity.toLong()
buf.len = len.toLong()
buf.data = data
return buf
}
internal fun free(buf: RustBuffer.ByValue) =
uniffiRustCall { status ->
UniffiLib.INSTANCE.ffi_goose_llm_rustbuffer_free(buf, status)
}
}
@Suppress("TooGenericExceptionThrown")
fun asByteBuffer() =
this.data?.getByteBuffer(0, this.len.toLong())?.also {
it.order(ByteOrder.BIG_ENDIAN)
}
}
/**
* The equivalent of the `*mut RustBuffer` type.
* Required for callbacks taking in an out pointer.
*
* Size is the sum of all values in the struct.
*
* @suppress
*/
class RustBufferByReference : ByReference(16) {
/**
* Set the pointed-to `RustBuffer` to the given value.
*/
fun setValue(value: RustBuffer.ByValue) {
// NOTE: The offsets are as they are in the C-like struct.
val pointer = getPointer()
pointer.setLong(0, value.capacity)
pointer.setLong(8, value.len)
pointer.setPointer(16, value.data)
}
/**
* Get a `RustBuffer.ByValue` from this reference.
*/
fun getValue(): RustBuffer.ByValue {
val pointer = getPointer()
val value = RustBuffer.ByValue()
value.writeField("capacity", pointer.getLong(0))
value.writeField("len", pointer.getLong(8))
value.writeField("data", pointer.getLong(16))
return value
}
}
// This is a helper for safely passing byte references into the rust code.
// It's not actually used at the moment, because there aren't many things that you
// can take a direct pointer to in the JVM, and if we're going to copy something
// then we might as well copy it into a `RustBuffer`. But it's here for API
// completeness.
@Structure.FieldOrder("len", "data")
internal open class ForeignBytes : Structure() {
@JvmField var len: Int = 0
@JvmField var data: Pointer? = null
class ByValue :
ForeignBytes(),
Structure.ByValue
}
/**
* The FfiConverter interface handles converter types to and from the FFI
*
* All implementing objects should be public to support external types. When a
* type is external we need to import it's FfiConverter.
*
* @suppress
*/
public interface FfiConverter<KotlinType, FfiType> {
// Convert an FFI type to a Kotlin type
fun lift(value: FfiType): KotlinType
// Convert an Kotlin type to an FFI type
fun lower(value: KotlinType): FfiType
// Read a Kotlin type from a `ByteBuffer`
fun read(buf: ByteBuffer): KotlinType
// Calculate bytes to allocate when creating a `RustBuffer`
//
// This must return at least as many bytes as the write() function will
// write. It can return more bytes than needed, for example when writing
// Strings we can't know the exact bytes needed until we the UTF-8
// encoding, so we pessimistically allocate the largest size possible (3
// bytes per codepoint). Allocating extra bytes is not really a big deal
// because the `RustBuffer` is short-lived.
fun allocationSize(value: KotlinType): ULong
// Write a Kotlin type to a `ByteBuffer`
fun write(
value: KotlinType,
buf: ByteBuffer,
)
// Lower a value into a `RustBuffer`
//
// This method lowers a value into a `RustBuffer` rather than the normal
// FfiType. It's used by the callback interface code. Callback interface
// returns are always serialized into a `RustBuffer` regardless of their
// normal FFI type.
fun lowerIntoRustBuffer(value: KotlinType): RustBuffer.ByValue {
val rbuf = RustBuffer.alloc(allocationSize(value))
try {
val bbuf =
rbuf.data!!.getByteBuffer(0, rbuf.capacity).also {
it.order(ByteOrder.BIG_ENDIAN)
}
write(value, bbuf)
rbuf.writeField("len", bbuf.position().toLong())
return rbuf
} catch (e: Throwable) {
RustBuffer.free(rbuf)
throw e
}
}
// Lift a value from a `RustBuffer`.
//
// This here mostly because of the symmetry with `lowerIntoRustBuffer()`.
// It's currently only used by the `FfiConverterRustBuffer` class below.
fun liftFromRustBuffer(rbuf: RustBuffer.ByValue): KotlinType {
val byteBuf = rbuf.asByteBuffer()!!
try {
val item = read(byteBuf)
if (byteBuf.hasRemaining()) {
throw RuntimeException("junk remaining in buffer after lifting, something is very wrong!!")
}
return item
} finally {
RustBuffer.free(rbuf)
}
}
}
/**
* FfiConverter that uses `RustBuffer` as the FfiType
*
* @suppress
*/
public interface FfiConverterRustBuffer<KotlinType> : FfiConverter<KotlinType, RustBuffer.ByValue> {
override fun lift(value: RustBuffer.ByValue) = liftFromRustBuffer(value)
override fun lower(value: KotlinType) = lowerIntoRustBuffer(value)
}
// A handful of classes and functions to support the generated data structures.
// This would be a good candidate for isolating in its own ffi-support lib.
internal const val UNIFFI_CALL_SUCCESS = 0.toByte()
internal const val UNIFFI_CALL_ERROR = 1.toByte()
internal const val UNIFFI_CALL_UNEXPECTED_ERROR = 2.toByte()
@Structure.FieldOrder("code", "error_buf")
internal open class UniffiRustCallStatus : Structure() {
@JvmField var code: Byte = 0
@JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue()
class ByValue :
UniffiRustCallStatus(),
Structure.ByValue
fun isSuccess(): Boolean = code == UNIFFI_CALL_SUCCESS
fun isError(): Boolean = code == UNIFFI_CALL_ERROR
fun isPanic(): Boolean = code == UNIFFI_CALL_UNEXPECTED_ERROR
companion object {
fun create(
code: Byte,
errorBuf: RustBuffer.ByValue,
): UniffiRustCallStatus.ByValue {
val callStatus = UniffiRustCallStatus.ByValue()
callStatus.code = code
callStatus.error_buf = errorBuf
return callStatus
}
}
}
class InternalException(
message: String,
) : kotlin.Exception(message)
/**
* Each top-level error class has a companion object that can lift the error from the call status's rust buffer
*
* @suppress
*/
interface UniffiRustCallStatusErrorHandler<E> {
fun lift(error_buf: RustBuffer.ByValue): E
}
// Helpers for calling Rust
// In practice we usually need to be synchronized to call this safely, so it doesn't
// synchronize itself
// Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err
private inline fun <U, E : kotlin.Exception> uniffiRustCallWithError(
errorHandler: UniffiRustCallStatusErrorHandler<E>,
callback: (UniffiRustCallStatus) -> U,
): U {
var status = UniffiRustCallStatus()
val return_value = callback(status)
uniffiCheckCallStatus(errorHandler, status)
return return_value
}
// Check UniffiRustCallStatus and throw an error if the call wasn't successful
private fun <E : kotlin.Exception> uniffiCheckCallStatus(
errorHandler: UniffiRustCallStatusErrorHandler<E>,
status: UniffiRustCallStatus,
) {
if (status.isSuccess()) {
return
} else if (status.isError()) {
throw errorHandler.lift(status.error_buf)
} else if (status.isPanic()) {
// when the rust code sees a panic, it tries to construct a rustbuffer
// with the message. but if that code panics, then it just sends back
// an empty buffer.
if (status.error_buf.len > 0) {
throw InternalException(FfiConverterString.lift(status.error_buf))
} else {
throw InternalException("Rust panic")
}
} else {
throw InternalException("Unknown rust call status: $status.code")
}
}
/**
* UniffiRustCallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR
*
* @suppress
*/
object UniffiNullRustCallStatusErrorHandler : UniffiRustCallStatusErrorHandler<InternalException> {
override fun lift(error_buf: RustBuffer.ByValue): InternalException {
RustBuffer.free(error_buf)
return InternalException("Unexpected CALL_ERROR")
}
}
// Call a rust function that returns a plain value
private inline fun <U> uniffiRustCall(callback: (UniffiRustCallStatus) -> U): U =
uniffiRustCallWithError(UniffiNullRustCallStatusErrorHandler, callback)
internal inline fun <T> uniffiTraitInterfaceCall(
callStatus: UniffiRustCallStatus,
makeCall: () -> T,
writeReturn: (T) -> Unit,
) {
try {
writeReturn(makeCall())
} catch (e: kotlin.Exception) {
callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
callStatus.error_buf = FfiConverterString.lower(e.toString())
}
}
internal inline fun <T, reified E : Throwable> uniffiTraitInterfaceCallWithError(
callStatus: UniffiRustCallStatus,
makeCall: () -> T,
writeReturn: (T) -> Unit,
lowerError: (E) -> RustBuffer.ByValue,
) {
try {
writeReturn(makeCall())
} catch (e: kotlin.Exception) {
if (e is E) {
callStatus.code = UNIFFI_CALL_ERROR
callStatus.error_buf = lowerError(e)
} else {
callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
callStatus.error_buf = FfiConverterString.lower(e.toString())
}
}
}
// Map handles to objects
//
// This is used pass an opaque 64-bit handle representing a foreign object to the Rust code.
internal class UniffiHandleMap<T : Any> {
private val map = ConcurrentHashMap<Long, T>()
private val counter =
java.util.concurrent.atomic
.AtomicLong(0)
val size: Int
get() = map.size
// Insert a new object into the handle map and get a handle for it
fun insert(obj: T): Long {
val handle = counter.getAndAdd(1)
map.put(handle, obj)
return handle
}
// Get an object from the handle map
fun get(handle: Long): T = map.get(handle) ?: throw InternalException("UniffiHandleMap.get: Invalid handle")
// Remove an entry from the handlemap and get the Kotlin object back
fun remove(handle: Long): T = map.remove(handle) ?: throw InternalException("UniffiHandleMap: Invalid handle")
}
// Contains loading, initialization code,
// and the FFI Function declarations in a com.sun.jna.Library.
@Synchronized
private fun findLibraryName(componentName: String): String {
val libOverride = System.getProperty("uniffi.component.$componentName.libraryOverride")
if (libOverride != null) {
return libOverride
}
return "goose_llm"
}
private inline fun <reified Lib : Library> loadIndirect(componentName: String): Lib =
Native.load<Lib>(findLibraryName(componentName), Lib::class.java)
// Define FFI callback types
internal interface UniffiRustFutureContinuationCallback : com.sun.jna.Callback {
fun callback(
`data`: Long,
`pollResult`: Byte,
)
}
internal interface UniffiForeignFutureFree : com.sun.jna.Callback {
fun callback(`handle`: Long)
}
internal interface UniffiCallbackInterfaceFree : com.sun.jna.Callback {
fun callback(`handle`: Long)
}
@Structure.FieldOrder("handle", "free")
internal open class UniffiForeignFuture(
@JvmField internal var `handle`: Long = 0.toLong(),
@JvmField internal var `free`: UniffiForeignFutureFree? = null,
) : Structure() {
class UniffiByValue(
`handle`: Long = 0.toLong(),
`free`: UniffiForeignFutureFree? = null,
) : UniffiForeignFuture(`handle`, `free`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFuture) {
`handle` = other.`handle`
`free` = other.`free`
}
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructU8(
@JvmField internal var `returnValue`: Byte = 0.toByte(),
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Byte = 0.toByte(),
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructU8(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructU8) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteU8 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructU8.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructI8(
@JvmField internal var `returnValue`: Byte = 0.toByte(),
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Byte = 0.toByte(),
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructI8(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructI8) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteI8 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructI8.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructU16(
@JvmField internal var `returnValue`: Short = 0.toShort(),
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Short = 0.toShort(),
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructU16(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructU16) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteU16 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructU16.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructI16(
@JvmField internal var `returnValue`: Short = 0.toShort(),
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Short = 0.toShort(),
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructI16(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructI16) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteI16 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructI16.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructU32(
@JvmField internal var `returnValue`: Int = 0,
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Int = 0,
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructU32(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructU32) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteU32 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructU32.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructI32(
@JvmField internal var `returnValue`: Int = 0,
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Int = 0,
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructI32(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructI32) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteI32 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructI32.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructU64(
@JvmField internal var `returnValue`: Long = 0.toLong(),
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Long = 0.toLong(),
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructU64(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructU64) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteU64 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructU64.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructI64(
@JvmField internal var `returnValue`: Long = 0.toLong(),
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Long = 0.toLong(),
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructI64(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructI64) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteI64 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructI64.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructF32(
@JvmField internal var `returnValue`: Float = 0.0f,
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Float = 0.0f,
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructF32(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructF32) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteF32 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructF32.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructF64(
@JvmField internal var `returnValue`: Double = 0.0,
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Double = 0.0,
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructF64(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructF64) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteF64 : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructF64.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructPointer(
@JvmField internal var `returnValue`: Pointer = Pointer.NULL,
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: Pointer = Pointer.NULL,
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructPointer(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructPointer) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompletePointer : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructPointer.UniffiByValue,
)
}
@Structure.FieldOrder("returnValue", "callStatus")
internal open class UniffiForeignFutureStructRustBuffer(
@JvmField internal var `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructRustBuffer(`returnValue`, `callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructRustBuffer) {
`returnValue` = other.`returnValue`
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteRustBuffer : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructRustBuffer.UniffiByValue,
)
}
@Structure.FieldOrder("callStatus")
internal open class UniffiForeignFutureStructVoid(
@JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : Structure() {
class UniffiByValue(
`callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
) : UniffiForeignFutureStructVoid(`callStatus`),
Structure.ByValue
internal fun uniffiSetValue(other: UniffiForeignFutureStructVoid) {
`callStatus` = other.`callStatus`
}
}
internal interface UniffiForeignFutureCompleteVoid : com.sun.jna.Callback {
fun callback(
`callbackData`: Long,
`result`: UniffiForeignFutureStructVoid.UniffiByValue,
)
}
// For large crates we prevent `MethodTooLargeException` (see #2340)
// N.B. the name of the extension is very misleading, since it is
// rather `InterfaceTooLargeException`, caused by too many methods
// in the interface for large crates.
//
// By splitting the otherwise huge interface into two parts
// * UniffiLib
// * IntegrityCheckingUniffiLib (this)
// we allow for ~2x as many methods in the UniffiLib interface.
//
// The `ffi_uniffi_contract_version` method and all checksum methods are put
// into `IntegrityCheckingUniffiLib` and these methods are called only once,
// when the library is loaded.
internal interface IntegrityCheckingUniffiLib : Library {
// Integrity check functions only
fun uniffi_goose_llm_checksum_func_completion(): Short
fun uniffi_goose_llm_checksum_func_create_completion_request(): Short
fun uniffi_goose_llm_checksum_func_create_tool_config(): Short
fun uniffi_goose_llm_checksum_func_generate_session_name(): Short
fun uniffi_goose_llm_checksum_func_generate_structured_outputs(): Short
fun uniffi_goose_llm_checksum_func_generate_tooltip(): Short
fun uniffi_goose_llm_checksum_func_print_messages(): Short
fun ffi_goose_llm_uniffi_contract_version(): Int
}
// A JNA Library to expose the extern-C FFI definitions.
// This is an implementation detail which will be called internally by the public API.
internal interface UniffiLib : Library {
companion object {
internal val INSTANCE: UniffiLib by lazy {
val componentName = "goose_llm"
// For large crates we prevent `MethodTooLargeException` (see #2340)
// N.B. the name of the extension is very misleading, since it is
// rather `InterfaceTooLargeException`, caused by too many methods
// in the interface for large crates.
//
// By splitting the otherwise huge interface into two parts
// * UniffiLib (this)
// * IntegrityCheckingUniffiLib
// And all checksum methods are put into `IntegrityCheckingUniffiLib`
// we allow for ~2x as many methods in the UniffiLib interface.
//
// Thus we first load the library with `loadIndirect` as `IntegrityCheckingUniffiLib`
// so that we can (optionally!) call `uniffiCheckApiChecksums`...
loadIndirect<IntegrityCheckingUniffiLib>(componentName)
.also { lib: IntegrityCheckingUniffiLib ->
uniffiCheckContractApiVersion(lib)
uniffiCheckApiChecksums(lib)
}
// ... and then we load the library as `UniffiLib`
// N.B. we cannot use `loadIndirect` once and then try to cast it to `UniffiLib`
// => results in `java.lang.ClassCastException: com.sun.proxy.$Proxy cannot be cast to ...`
// error. So we must call `loadIndirect` twice. For crates large enough
// to trigger this issue, the performance impact is negligible, running on
// a macOS M1 machine the `loadIndirect` call takes ~50ms.
val lib = loadIndirect<UniffiLib>(componentName)
// No need to check the contract version and checksums, since
// we already did that with `IntegrityCheckingUniffiLib` above.
// Loading of library with integrity check done.
lib
}
}
// FFI functions
fun uniffi_goose_llm_fn_func_completion(`req`: RustBuffer.ByValue): Long
fun uniffi_goose_llm_fn_func_create_completion_request(
`providerName`: RustBuffer.ByValue,
`providerConfig`: RustBuffer.ByValue,
`modelConfig`: RustBuffer.ByValue,
`systemPreamble`: RustBuffer.ByValue,
`systemPromptOverride`: RustBuffer.ByValue,
`messages`: RustBuffer.ByValue,
`extensions`: RustBuffer.ByValue,
`requestId`: RustBuffer.ByValue,
uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
fun uniffi_goose_llm_fn_func_create_tool_config(
`name`: RustBuffer.ByValue,
`description`: RustBuffer.ByValue,
`inputSchema`: RustBuffer.ByValue,
`approvalMode`: RustBuffer.ByValue,
uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
fun uniffi_goose_llm_fn_func_generate_session_name(
`providerName`: RustBuffer.ByValue,
`providerConfig`: RustBuffer.ByValue,
`messages`: RustBuffer.ByValue,
`requestId`: RustBuffer.ByValue,
): Long
fun uniffi_goose_llm_fn_func_generate_structured_outputs(
`providerName`: RustBuffer.ByValue,
`providerConfig`: RustBuffer.ByValue,
`systemPrompt`: RustBuffer.ByValue,
`messages`: RustBuffer.ByValue,
`schema`: RustBuffer.ByValue,
`requestId`: RustBuffer.ByValue,
): Long
fun uniffi_goose_llm_fn_func_generate_tooltip(
`providerName`: RustBuffer.ByValue,
`providerConfig`: RustBuffer.ByValue,
`messages`: RustBuffer.ByValue,
`requestId`: RustBuffer.ByValue,
): Long
fun uniffi_goose_llm_fn_func_print_messages(
`messages`: RustBuffer.ByValue,
uniffi_out_err: UniffiRustCallStatus,
): Unit
fun ffi_goose_llm_rustbuffer_alloc(
`size`: Long,
uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
fun ffi_goose_llm_rustbuffer_from_bytes(
`bytes`: ForeignBytes.ByValue,
uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
fun ffi_goose_llm_rustbuffer_free(
`buf`: RustBuffer.ByValue,
uniffi_out_err: UniffiRustCallStatus,
): Unit
fun ffi_goose_llm_rustbuffer_reserve(
`buf`: RustBuffer.ByValue,
`additional`: Long,
uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
fun ffi_goose_llm_rust_future_poll_u8(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_u8(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_u8(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_u8(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Byte
fun ffi_goose_llm_rust_future_poll_i8(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_i8(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_i8(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_i8(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Byte
fun ffi_goose_llm_rust_future_poll_u16(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_u16(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_u16(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_u16(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Short
fun ffi_goose_llm_rust_future_poll_i16(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_i16(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_i16(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_i16(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Short
fun ffi_goose_llm_rust_future_poll_u32(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_u32(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_u32(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_u32(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Int
fun ffi_goose_llm_rust_future_poll_i32(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_i32(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_i32(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_i32(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Int
fun ffi_goose_llm_rust_future_poll_u64(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_u64(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_u64(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_u64(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Long
fun ffi_goose_llm_rust_future_poll_i64(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_i64(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_i64(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_i64(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Long
fun ffi_goose_llm_rust_future_poll_f32(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_f32(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_f32(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_f32(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Float
fun ffi_goose_llm_rust_future_poll_f64(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_f64(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_f64(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_f64(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Double
fun ffi_goose_llm_rust_future_poll_pointer(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_pointer(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_pointer(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_pointer(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Pointer
fun ffi_goose_llm_rust_future_poll_rust_buffer(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_rust_buffer(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_rust_buffer(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_rust_buffer(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): RustBuffer.ByValue
fun ffi_goose_llm_rust_future_poll_void(
`handle`: Long,
`callback`: UniffiRustFutureContinuationCallback,
`callbackData`: Long,
): Unit
fun ffi_goose_llm_rust_future_cancel_void(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_free_void(`handle`: Long): Unit
fun ffi_goose_llm_rust_future_complete_void(
`handle`: Long,
uniffi_out_err: UniffiRustCallStatus,
): Unit
}
private fun uniffiCheckContractApiVersion(lib: IntegrityCheckingUniffiLib) {
// Get the bindings contract version from our ComponentInterface
val bindings_contract_version = 29
// Get the scaffolding contract version by calling the into the dylib
val scaffolding_contract_version = lib.ffi_goose_llm_uniffi_contract_version()
if (bindings_contract_version != scaffolding_contract_version) {
throw RuntimeException("UniFFI contract version mismatch: try cleaning and rebuilding your project")
}
}
@Suppress("UNUSED_PARAMETER")
private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_goose_llm_checksum_func_completion() != 47457.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_goose_llm_checksum_func_create_completion_request() != 15391.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_goose_llm_checksum_func_create_tool_config() != 49910.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_goose_llm_checksum_func_generate_session_name() != 34350.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_goose_llm_checksum_func_generate_structured_outputs() != 4576.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_goose_llm_checksum_func_generate_tooltip() != 36439.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_goose_llm_checksum_func_print_messages() != 30278.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
}
/**
* @suppress
*/
public fun uniffiEnsureInitialized() {
UniffiLib.INSTANCE
}
// Async support
// Async return type handlers
internal const val UNIFFI_RUST_FUTURE_POLL_READY = 0.toByte()
internal const val UNIFFI_RUST_FUTURE_POLL_MAYBE_READY = 1.toByte()
internal val uniffiContinuationHandleMap = UniffiHandleMap<CancellableContinuation<Byte>>()
// FFI type for Rust future continuations
internal object uniffiRustFutureContinuationCallbackImpl : UniffiRustFutureContinuationCallback {
override fun callback(
data: Long,
pollResult: Byte,
) {
uniffiContinuationHandleMap.remove(data).resume(pollResult)
}
}
internal suspend fun <T, F, E : kotlin.Exception> uniffiRustCallAsync(
rustFuture: Long,
pollFunc: (Long, UniffiRustFutureContinuationCallback, Long) -> Unit,
completeFunc: (Long, UniffiRustCallStatus) -> F,
freeFunc: (Long) -> Unit,
liftFunc: (F) -> T,
errorHandler: UniffiRustCallStatusErrorHandler<E>,
): T {
try {
do {
val pollResult =
suspendCancellableCoroutine<Byte> { continuation ->
pollFunc(
rustFuture,
uniffiRustFutureContinuationCallbackImpl,
uniffiContinuationHandleMap.insert(continuation),
)
}
} while (pollResult != UNIFFI_RUST_FUTURE_POLL_READY)
return liftFunc(
uniffiRustCallWithError(errorHandler, { status -> completeFunc(rustFuture, status) }),
)
} finally {
freeFunc(rustFuture)
}
}
// Public interface members begin here.
// Interface implemented by anything that can contain an object reference.
//
// Such types expose a `destroy()` method that must be called to cleanly
// dispose of the contained objects. Failure to call this method may result
// in memory leaks.
//
// The easiest way to ensure this method is called is to use the `.use`
// helper method to execute a block and destroy the object at the end.
interface Disposable {
fun destroy()
companion object {
fun destroy(vararg args: Any?) {
for (arg in args) {
when (arg) {
is Disposable -> arg.destroy()
is ArrayList<*> -> {
for (idx in arg.indices) {
val element = arg[idx]
if (element is Disposable) {
element.destroy()
}
}
}
is Map<*, *> -> {
for (element in arg.values) {
if (element is Disposable) {
element.destroy()
}
}
}
is Iterable<*> -> {
for (element in arg) {
if (element is Disposable) {
element.destroy()
}
}
}
}
}
}
}
}
/**
* @suppress
*/
inline fun <T : Disposable?, R> T.use(block: (T) -> R) =
try {
block(this)
} finally {
try {
// N.B. our implementation is on the nullable type `Disposable?`.
this?.destroy()
} catch (e: Throwable) {
// swallow
}
}
/**
* Used to instantiate an interface without an actual pointer, for fakes in tests, mostly.
*
* @suppress
* */
object NoPointer
/**
* @suppress
*/
public object FfiConverterUInt : FfiConverter<UInt, Int> {
override fun lift(value: Int): UInt = value.toUInt()
override fun read(buf: ByteBuffer): UInt = lift(buf.getInt())
override fun lower(value: UInt): Int = value.toInt()
override fun allocationSize(value: UInt) = 4UL
override fun write(
value: UInt,
buf: ByteBuffer,
) {
buf.putInt(value.toInt())
}
}
/**
* @suppress
*/
public object FfiConverterInt : FfiConverter<Int, Int> {
override fun lift(value: Int): Int = value
override fun read(buf: ByteBuffer): Int = buf.getInt()
override fun lower(value: Int): Int = value
override fun allocationSize(value: Int) = 4UL
override fun write(
value: Int,
buf: ByteBuffer,
) {
buf.putInt(value)
}
}
/**
* @suppress
*/
public object FfiConverterLong : FfiConverter<Long, Long> {
override fun lift(value: Long): Long = value
override fun read(buf: ByteBuffer): Long = buf.getLong()
override fun lower(value: Long): Long = value
override fun allocationSize(value: Long) = 8UL
override fun write(
value: Long,
buf: ByteBuffer,
) {
buf.putLong(value)
}
}
/**
* @suppress
*/
public object FfiConverterFloat : FfiConverter<Float, Float> {
override fun lift(value: Float): Float = value
override fun read(buf: ByteBuffer): Float = buf.getFloat()
override fun lower(value: Float): Float = value
override fun allocationSize(value: Float) = 4UL
override fun write(
value: Float,
buf: ByteBuffer,
) {
buf.putFloat(value)
}
}
/**
* @suppress
*/
public object FfiConverterDouble : FfiConverter<Double, Double> {
override fun lift(value: Double): Double = value
override fun read(buf: ByteBuffer): Double = buf.getDouble()
override fun lower(value: Double): Double = value
override fun allocationSize(value: Double) = 8UL
override fun write(
value: Double,
buf: ByteBuffer,
) {
buf.putDouble(value)
}
}
/**
* @suppress
*/
public object FfiConverterString : FfiConverter<String, RustBuffer.ByValue> {
// Note: we don't inherit from FfiConverterRustBuffer, because we use a
// special encoding when lowering/lifting. We can use `RustBuffer.len` to
// store our length and avoid writing it out to the buffer.
override fun lift(value: RustBuffer.ByValue): String {
try {
val byteArr = ByteArray(value.len.toInt())
value.asByteBuffer()!!.get(byteArr)
return byteArr.toString(Charsets.UTF_8)
} finally {
RustBuffer.free(value)
}
}
override fun read(buf: ByteBuffer): String {
val len = buf.getInt()
val byteArr = ByteArray(len)
buf.get(byteArr)
return byteArr.toString(Charsets.UTF_8)
}
fun toUtf8(value: String): ByteBuffer {
// Make sure we don't have invalid UTF-16, check for lone surrogates.
return Charsets.UTF_8.newEncoder().run {
onMalformedInput(CodingErrorAction.REPORT)
encode(CharBuffer.wrap(value))
}
}
override fun lower(value: String): RustBuffer.ByValue {
val byteBuf = toUtf8(value)
// Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us
// to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`.
val rbuf = RustBuffer.alloc(byteBuf.limit().toULong())
rbuf.asByteBuffer()!!.put(byteBuf)
return rbuf
}
// We aren't sure exactly how many bytes our string will be once it's UTF-8
// encoded. Allocate 3 bytes per UTF-16 code unit which will always be
// enough.
override fun allocationSize(value: String): ULong {
val sizeForLength = 4UL
val sizeForString = value.length.toULong() * 3UL
return sizeForLength + sizeForString
}
override fun write(
value: String,
buf: ByteBuffer,
) {
val byteBuf = toUtf8(value)
buf.putInt(byteBuf.limit())
buf.put(byteBuf)
}
}
data class CompletionResponse(
var `message`: Message,
var `model`: kotlin.String,
var `usage`: Usage,
var `runtimeMetrics`: RuntimeMetrics,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeCompletionResponse : FfiConverterRustBuffer<CompletionResponse> {
override fun read(buf: ByteBuffer): CompletionResponse =
CompletionResponse(
FfiConverterTypeMessage.read(buf),
FfiConverterString.read(buf),
FfiConverterTypeUsage.read(buf),
FfiConverterTypeRuntimeMetrics.read(buf),
)
override fun allocationSize(value: CompletionResponse) =
(
FfiConverterTypeMessage.allocationSize(value.`message`) +
FfiConverterString.allocationSize(value.`model`) +
FfiConverterTypeUsage.allocationSize(value.`usage`) +
FfiConverterTypeRuntimeMetrics.allocationSize(value.`runtimeMetrics`)
)
override fun write(
value: CompletionResponse,
buf: ByteBuffer,
) {
FfiConverterTypeMessage.write(value.`message`, buf)
FfiConverterString.write(value.`model`, buf)
FfiConverterTypeUsage.write(value.`usage`, buf)
FfiConverterTypeRuntimeMetrics.write(value.`runtimeMetrics`, buf)
}
}
data class ExtensionConfig(
var `name`: kotlin.String,
var `instructions`: kotlin.String?,
var `tools`: List<ToolConfig>,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeExtensionConfig : FfiConverterRustBuffer<ExtensionConfig> {
override fun read(buf: ByteBuffer): ExtensionConfig =
ExtensionConfig(
FfiConverterString.read(buf),
FfiConverterOptionalString.read(buf),
FfiConverterSequenceTypeToolConfig.read(buf),
)
override fun allocationSize(value: ExtensionConfig) =
(
FfiConverterString.allocationSize(value.`name`) +
FfiConverterOptionalString.allocationSize(value.`instructions`) +
FfiConverterSequenceTypeToolConfig.allocationSize(value.`tools`)
)
override fun write(
value: ExtensionConfig,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`name`, buf)
FfiConverterOptionalString.write(value.`instructions`, buf)
FfiConverterSequenceTypeToolConfig.write(value.`tools`, buf)
}
}
data class ImageContent(
var `data`: kotlin.String,
var `mimeType`: kotlin.String,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeImageContent : FfiConverterRustBuffer<ImageContent> {
override fun read(buf: ByteBuffer): ImageContent =
ImageContent(
FfiConverterString.read(buf),
FfiConverterString.read(buf),
)
override fun allocationSize(value: ImageContent) =
(
FfiConverterString.allocationSize(value.`data`) +
FfiConverterString.allocationSize(value.`mimeType`)
)
override fun write(
value: ImageContent,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`data`, buf)
FfiConverterString.write(value.`mimeType`, buf)
}
}
/**
* A message to or from an LLM
*/
data class Message(
var `role`: Role,
var `created`: kotlin.Long,
var `content`: Contents,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeMessage : FfiConverterRustBuffer<Message> {
override fun read(buf: ByteBuffer): Message =
Message(
FfiConverterTypeRole.read(buf),
FfiConverterLong.read(buf),
FfiConverterTypeContents.read(buf),
)
override fun allocationSize(value: Message) =
(
FfiConverterTypeRole.allocationSize(value.`role`) +
FfiConverterLong.allocationSize(value.`created`) +
FfiConverterTypeContents.allocationSize(value.`content`)
)
override fun write(
value: Message,
buf: ByteBuffer,
) {
FfiConverterTypeRole.write(value.`role`, buf)
FfiConverterLong.write(value.`created`, buf)
FfiConverterTypeContents.write(value.`content`, buf)
}
}
/**
* Configuration for model-specific settings and limits
*/
data class ModelConfig(
/**
* The name of the model to use
*/
var `modelName`: kotlin.String,
/**
* Optional explicit context limit that overrides any defaults
*/
var `contextLimit`: kotlin.UInt?,
/**
* Optional temperature setting (0.0 - 1.0)
*/
var `temperature`: kotlin.Float?,
/**
* Optional maximum tokens to generate
*/
var `maxTokens`: kotlin.Int?,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeModelConfig : FfiConverterRustBuffer<ModelConfig> {
override fun read(buf: ByteBuffer): ModelConfig =
ModelConfig(
FfiConverterString.read(buf),
FfiConverterOptionalUInt.read(buf),
FfiConverterOptionalFloat.read(buf),
FfiConverterOptionalInt.read(buf),
)
override fun allocationSize(value: ModelConfig) =
(
FfiConverterString.allocationSize(value.`modelName`) +
FfiConverterOptionalUInt.allocationSize(value.`contextLimit`) +
FfiConverterOptionalFloat.allocationSize(value.`temperature`) +
FfiConverterOptionalInt.allocationSize(value.`maxTokens`)
)
override fun write(
value: ModelConfig,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`modelName`, buf)
FfiConverterOptionalUInt.write(value.`contextLimit`, buf)
FfiConverterOptionalFloat.write(value.`temperature`, buf)
FfiConverterOptionalInt.write(value.`maxTokens`, buf)
}
}
data class ProviderCompleteResponse(
var `message`: Message,
var `model`: kotlin.String,
var `usage`: Usage,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeProviderCompleteResponse : FfiConverterRustBuffer<ProviderCompleteResponse> {
override fun read(buf: ByteBuffer): ProviderCompleteResponse =
ProviderCompleteResponse(
FfiConverterTypeMessage.read(buf),
FfiConverterString.read(buf),
FfiConverterTypeUsage.read(buf),
)
override fun allocationSize(value: ProviderCompleteResponse) =
(
FfiConverterTypeMessage.allocationSize(value.`message`) +
FfiConverterString.allocationSize(value.`model`) +
FfiConverterTypeUsage.allocationSize(value.`usage`)
)
override fun write(
value: ProviderCompleteResponse,
buf: ByteBuffer,
) {
FfiConverterTypeMessage.write(value.`message`, buf)
FfiConverterString.write(value.`model`, buf)
FfiConverterTypeUsage.write(value.`usage`, buf)
}
}
/**
* Response from a structuredextraction call
*/
data class ProviderExtractResponse(
/**
* The extracted JSON object
*/
var `data`: Value,
/**
* Which model produced it
*/
var `model`: kotlin.String,
/**
* Token usage stats
*/
var `usage`: Usage,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeProviderExtractResponse : FfiConverterRustBuffer<ProviderExtractResponse> {
override fun read(buf: ByteBuffer): ProviderExtractResponse =
ProviderExtractResponse(
FfiConverterTypeValue.read(buf),
FfiConverterString.read(buf),
FfiConverterTypeUsage.read(buf),
)
override fun allocationSize(value: ProviderExtractResponse) =
(
FfiConverterTypeValue.allocationSize(value.`data`) +
FfiConverterString.allocationSize(value.`model`) +
FfiConverterTypeUsage.allocationSize(value.`usage`)
)
override fun write(
value: ProviderExtractResponse,
buf: ByteBuffer,
) {
FfiConverterTypeValue.write(value.`data`, buf)
FfiConverterString.write(value.`model`, buf)
FfiConverterTypeUsage.write(value.`usage`, buf)
}
}
data class RedactedThinkingContent(
var `data`: kotlin.String,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeRedactedThinkingContent : FfiConverterRustBuffer<RedactedThinkingContent> {
override fun read(buf: ByteBuffer): RedactedThinkingContent =
RedactedThinkingContent(
FfiConverterString.read(buf),
)
override fun allocationSize(value: RedactedThinkingContent) =
(
FfiConverterString.allocationSize(value.`data`)
)
override fun write(
value: RedactedThinkingContent,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`data`, buf)
}
}
data class RuntimeMetrics(
var `totalTimeSec`: kotlin.Float,
var `totalTimeSecProvider`: kotlin.Float,
var `tokensPerSecond`: kotlin.Double?,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeRuntimeMetrics : FfiConverterRustBuffer<RuntimeMetrics> {
override fun read(buf: ByteBuffer): RuntimeMetrics =
RuntimeMetrics(
FfiConverterFloat.read(buf),
FfiConverterFloat.read(buf),
FfiConverterOptionalDouble.read(buf),
)
override fun allocationSize(value: RuntimeMetrics) =
(
FfiConverterFloat.allocationSize(value.`totalTimeSec`) +
FfiConverterFloat.allocationSize(value.`totalTimeSecProvider`) +
FfiConverterOptionalDouble.allocationSize(value.`tokensPerSecond`)
)
override fun write(
value: RuntimeMetrics,
buf: ByteBuffer,
) {
FfiConverterFloat.write(value.`totalTimeSec`, buf)
FfiConverterFloat.write(value.`totalTimeSecProvider`, buf)
FfiConverterOptionalDouble.write(value.`tokensPerSecond`, buf)
}
}
data class TextContent(
var `text`: kotlin.String,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeTextContent : FfiConverterRustBuffer<TextContent> {
override fun read(buf: ByteBuffer): TextContent =
TextContent(
FfiConverterString.read(buf),
)
override fun allocationSize(value: TextContent) =
(
FfiConverterString.allocationSize(value.`text`)
)
override fun write(
value: TextContent,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`text`, buf)
}
}
data class ThinkingContent(
var `thinking`: kotlin.String,
var `signature`: kotlin.String,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeThinkingContent : FfiConverterRustBuffer<ThinkingContent> {
override fun read(buf: ByteBuffer): ThinkingContent =
ThinkingContent(
FfiConverterString.read(buf),
FfiConverterString.read(buf),
)
override fun allocationSize(value: ThinkingContent) =
(
FfiConverterString.allocationSize(value.`thinking`) +
FfiConverterString.allocationSize(value.`signature`)
)
override fun write(
value: ThinkingContent,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`thinking`, buf)
FfiConverterString.write(value.`signature`, buf)
}
}
data class ToolConfig(
var `name`: kotlin.String,
var `description`: kotlin.String,
var `inputSchema`: Value,
var `approvalMode`: ToolApprovalMode,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeToolConfig : FfiConverterRustBuffer<ToolConfig> {
override fun read(buf: ByteBuffer): ToolConfig =
ToolConfig(
FfiConverterString.read(buf),
FfiConverterString.read(buf),
FfiConverterTypeValue.read(buf),
FfiConverterTypeToolApprovalMode.read(buf),
)
override fun allocationSize(value: ToolConfig) =
(
FfiConverterString.allocationSize(value.`name`) +
FfiConverterString.allocationSize(value.`description`) +
FfiConverterTypeValue.allocationSize(value.`inputSchema`) +
FfiConverterTypeToolApprovalMode.allocationSize(value.`approvalMode`)
)
override fun write(
value: ToolConfig,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`name`, buf)
FfiConverterString.write(value.`description`, buf)
FfiConverterTypeValue.write(value.`inputSchema`, buf)
FfiConverterTypeToolApprovalMode.write(value.`approvalMode`, buf)
}
}
data class ToolRequest(
var `id`: kotlin.String,
var `toolCall`: ToolRequestToolCall,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeToolRequest : FfiConverterRustBuffer<ToolRequest> {
override fun read(buf: ByteBuffer): ToolRequest =
ToolRequest(
FfiConverterString.read(buf),
FfiConverterTypeToolRequestToolCall.read(buf),
)
override fun allocationSize(value: ToolRequest) =
(
FfiConverterString.allocationSize(value.`id`) +
FfiConverterTypeToolRequestToolCall.allocationSize(value.`toolCall`)
)
override fun write(
value: ToolRequest,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`id`, buf)
FfiConverterTypeToolRequestToolCall.write(value.`toolCall`, buf)
}
}
data class ToolResponse(
var `id`: kotlin.String,
var `toolResult`: ToolResponseToolResult,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeToolResponse : FfiConverterRustBuffer<ToolResponse> {
override fun read(buf: ByteBuffer): ToolResponse =
ToolResponse(
FfiConverterString.read(buf),
FfiConverterTypeToolResponseToolResult.read(buf),
)
override fun allocationSize(value: ToolResponse) =
(
FfiConverterString.allocationSize(value.`id`) +
FfiConverterTypeToolResponseToolResult.allocationSize(value.`toolResult`)
)
override fun write(
value: ToolResponse,
buf: ByteBuffer,
) {
FfiConverterString.write(value.`id`, buf)
FfiConverterTypeToolResponseToolResult.write(value.`toolResult`, buf)
}
}
data class Usage(
var `inputTokens`: kotlin.Int?,
var `outputTokens`: kotlin.Int?,
var `totalTokens`: kotlin.Int?,
) {
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeUsage : FfiConverterRustBuffer<Usage> {
override fun read(buf: ByteBuffer): Usage =
Usage(
FfiConverterOptionalInt.read(buf),
FfiConverterOptionalInt.read(buf),
FfiConverterOptionalInt.read(buf),
)
override fun allocationSize(value: Usage) =
(
FfiConverterOptionalInt.allocationSize(value.`inputTokens`) +
FfiConverterOptionalInt.allocationSize(value.`outputTokens`) +
FfiConverterOptionalInt.allocationSize(value.`totalTokens`)
)
override fun write(
value: Usage,
buf: ByteBuffer,
) {
FfiConverterOptionalInt.write(value.`inputTokens`, buf)
FfiConverterOptionalInt.write(value.`outputTokens`, buf)
FfiConverterOptionalInt.write(value.`totalTokens`, buf)
}
}
sealed class CompletionException(
message: String,
) : kotlin.Exception(message) {
class UnknownProvider(
message: String,
) : CompletionException(message)
class Provider(
message: String,
) : CompletionException(message)
class Template(
message: String,
) : CompletionException(message)
class Json(
message: String,
) : CompletionException(message)
class ToolNotFound(
message: String,
) : CompletionException(message)
companion object ErrorHandler : UniffiRustCallStatusErrorHandler<CompletionException> {
override fun lift(error_buf: RustBuffer.ByValue): CompletionException = FfiConverterTypeCompletionError.lift(error_buf)
}
}
/**
* @suppress
*/
public object FfiConverterTypeCompletionError : FfiConverterRustBuffer<CompletionException> {
override fun read(buf: ByteBuffer): CompletionException =
when (buf.getInt()) {
1 -> CompletionException.UnknownProvider(FfiConverterString.read(buf))
2 -> CompletionException.Provider(FfiConverterString.read(buf))
3 -> CompletionException.Template(FfiConverterString.read(buf))
4 -> CompletionException.Json(FfiConverterString.read(buf))
5 -> CompletionException.ToolNotFound(FfiConverterString.read(buf))
else -> throw RuntimeException("invalid error enum value, something is very wrong!!")
}
override fun allocationSize(value: CompletionException): ULong = 4UL
override fun write(
value: CompletionException,
buf: ByteBuffer,
) {
when (value) {
is CompletionException.UnknownProvider -> {
buf.putInt(1)
Unit
}
is CompletionException.Provider -> {
buf.putInt(2)
Unit
}
is CompletionException.Template -> {
buf.putInt(3)
Unit
}
is CompletionException.Json -> {
buf.putInt(4)
Unit
}
is CompletionException.ToolNotFound -> {
buf.putInt(5)
Unit
}
}.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
}
}
sealed class Content {
data class Text(
val v1: TextContent,
) : Content() {
companion object
}
data class Image(
val v1: ImageContent,
) : Content() {
companion object
}
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeContent : FfiConverterRustBuffer<Content> {
override fun read(buf: ByteBuffer): Content =
when (buf.getInt()) {
1 ->
Content.Text(
FfiConverterTypeTextContent.read(buf),
)
2 ->
Content.Image(
FfiConverterTypeImageContent.read(buf),
)
else -> throw RuntimeException("invalid enum value, something is very wrong!!")
}
override fun allocationSize(value: Content) =
when (value) {
is Content.Text -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeTextContent.allocationSize(value.v1)
)
}
is Content.Image -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeImageContent.allocationSize(value.v1)
)
}
}
override fun write(
value: Content,
buf: ByteBuffer,
) {
when (value) {
is Content.Text -> {
buf.putInt(1)
FfiConverterTypeTextContent.write(value.v1, buf)
Unit
}
is Content.Image -> {
buf.putInt(2)
FfiConverterTypeImageContent.write(value.v1, buf)
Unit
}
}.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
}
}
/**
* Content passed inside a message, which can be both simple content and tool content
*/
sealed class MessageContent {
data class Text(
val v1: TextContent,
) : MessageContent() {
companion object
}
data class Image(
val v1: ImageContent,
) : MessageContent() {
companion object
}
data class ToolReq(
val v1: ToolRequest,
) : MessageContent() {
companion object
}
data class ToolResp(
val v1: ToolResponse,
) : MessageContent() {
companion object
}
data class Thinking(
val v1: ThinkingContent,
) : MessageContent() {
companion object
}
data class RedactedThinking(
val v1: RedactedThinkingContent,
) : MessageContent() {
companion object
}
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeMessageContent : FfiConverterRustBuffer<MessageContent> {
override fun read(buf: ByteBuffer): MessageContent =
when (buf.getInt()) {
1 ->
MessageContent.Text(
FfiConverterTypeTextContent.read(buf),
)
2 ->
MessageContent.Image(
FfiConverterTypeImageContent.read(buf),
)
3 ->
MessageContent.ToolReq(
FfiConverterTypeToolRequest.read(buf),
)
4 ->
MessageContent.ToolResp(
FfiConverterTypeToolResponse.read(buf),
)
5 ->
MessageContent.Thinking(
FfiConverterTypeThinkingContent.read(buf),
)
6 ->
MessageContent.RedactedThinking(
FfiConverterTypeRedactedThinkingContent.read(buf),
)
else -> throw RuntimeException("invalid enum value, something is very wrong!!")
}
override fun allocationSize(value: MessageContent) =
when (value) {
is MessageContent.Text -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeTextContent.allocationSize(value.v1)
)
}
is MessageContent.Image -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeImageContent.allocationSize(value.v1)
)
}
is MessageContent.ToolReq -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeToolRequest.allocationSize(value.v1)
)
}
is MessageContent.ToolResp -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeToolResponse.allocationSize(value.v1)
)
}
is MessageContent.Thinking -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeThinkingContent.allocationSize(value.v1)
)
}
is MessageContent.RedactedThinking -> {
// Add the size for the Int that specifies the variant plus the size needed for all fields
(
4UL +
FfiConverterTypeRedactedThinkingContent.allocationSize(value.v1)
)
}
}
override fun write(
value: MessageContent,
buf: ByteBuffer,
) {
when (value) {
is MessageContent.Text -> {
buf.putInt(1)
FfiConverterTypeTextContent.write(value.v1, buf)
Unit
}
is MessageContent.Image -> {
buf.putInt(2)
FfiConverterTypeImageContent.write(value.v1, buf)
Unit
}
is MessageContent.ToolReq -> {
buf.putInt(3)
FfiConverterTypeToolRequest.write(value.v1, buf)
Unit
}
is MessageContent.ToolResp -> {
buf.putInt(4)
FfiConverterTypeToolResponse.write(value.v1, buf)
Unit
}
is MessageContent.Thinking -> {
buf.putInt(5)
FfiConverterTypeThinkingContent.write(value.v1, buf)
Unit
}
is MessageContent.RedactedThinking -> {
buf.putInt(6)
FfiConverterTypeRedactedThinkingContent.write(value.v1, buf)
Unit
}
}.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
}
}
sealed class ProviderException : kotlin.Exception() {
class Authentication(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
class ContextLengthExceeded(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
class RateLimitExceeded(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
class ServerException(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
class RequestFailed(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
class ExecutionException(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
class UsageException(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
class ResponseParseException(
val v1: kotlin.String,
) : ProviderException() {
override val message
get() = "v1=${ v1 }"
}
companion object ErrorHandler : UniffiRustCallStatusErrorHandler<ProviderException> {
override fun lift(error_buf: RustBuffer.ByValue): ProviderException = FfiConverterTypeProviderError.lift(error_buf)
}
}
/**
* @suppress
*/
public object FfiConverterTypeProviderError : FfiConverterRustBuffer<ProviderException> {
override fun read(buf: ByteBuffer): ProviderException =
when (buf.getInt()) {
1 ->
ProviderException.Authentication(
FfiConverterString.read(buf),
)
2 ->
ProviderException.ContextLengthExceeded(
FfiConverterString.read(buf),
)
3 ->
ProviderException.RateLimitExceeded(
FfiConverterString.read(buf),
)
4 ->
ProviderException.ServerException(
FfiConverterString.read(buf),
)
5 ->
ProviderException.RequestFailed(
FfiConverterString.read(buf),
)
6 ->
ProviderException.ExecutionException(
FfiConverterString.read(buf),
)
7 ->
ProviderException.UsageException(
FfiConverterString.read(buf),
)
8 ->
ProviderException.ResponseParseException(
FfiConverterString.read(buf),
)
else -> throw RuntimeException("invalid error enum value, something is very wrong!!")
}
override fun allocationSize(value: ProviderException): ULong =
when (value) {
is ProviderException.Authentication -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ProviderException.ContextLengthExceeded -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ProviderException.RateLimitExceeded -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ProviderException.ServerException -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ProviderException.RequestFailed -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ProviderException.ExecutionException -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ProviderException.UsageException -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ProviderException.ResponseParseException -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
}
override fun write(
value: ProviderException,
buf: ByteBuffer,
) {
when (value) {
is ProviderException.Authentication -> {
buf.putInt(1)
FfiConverterString.write(value.v1, buf)
Unit
}
is ProviderException.ContextLengthExceeded -> {
buf.putInt(2)
FfiConverterString.write(value.v1, buf)
Unit
}
is ProviderException.RateLimitExceeded -> {
buf.putInt(3)
FfiConverterString.write(value.v1, buf)
Unit
}
is ProviderException.ServerException -> {
buf.putInt(4)
FfiConverterString.write(value.v1, buf)
Unit
}
is ProviderException.RequestFailed -> {
buf.putInt(5)
FfiConverterString.write(value.v1, buf)
Unit
}
is ProviderException.ExecutionException -> {
buf.putInt(6)
FfiConverterString.write(value.v1, buf)
Unit
}
is ProviderException.UsageException -> {
buf.putInt(7)
FfiConverterString.write(value.v1, buf)
Unit
}
is ProviderException.ResponseParseException -> {
buf.putInt(8)
FfiConverterString.write(value.v1, buf)
Unit
}
}.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
}
}
enum class Role {
USER,
ASSISTANT,
;
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeRole : FfiConverterRustBuffer<Role> {
override fun read(buf: ByteBuffer) =
try {
Role.values()[buf.getInt() - 1]
} catch (e: IndexOutOfBoundsException) {
throw RuntimeException("invalid enum value, something is very wrong!!", e)
}
override fun allocationSize(value: Role) = 4UL
override fun write(
value: Role,
buf: ByteBuffer,
) {
buf.putInt(value.ordinal + 1)
}
}
enum class ToolApprovalMode {
AUTO,
MANUAL,
SMART,
;
companion object
}
/**
* @suppress
*/
public object FfiConverterTypeToolApprovalMode : FfiConverterRustBuffer<ToolApprovalMode> {
override fun read(buf: ByteBuffer) =
try {
ToolApprovalMode.values()[buf.getInt() - 1]
} catch (e: IndexOutOfBoundsException) {
throw RuntimeException("invalid enum value, something is very wrong!!", e)
}
override fun allocationSize(value: ToolApprovalMode) = 4UL
override fun write(
value: ToolApprovalMode,
buf: ByteBuffer,
) {
buf.putInt(value.ordinal + 1)
}
}
sealed class ToolException : kotlin.Exception() {
class InvalidParameters(
val v1: kotlin.String,
) : ToolException() {
override val message
get() = "v1=${ v1 }"
}
class ExecutionException(
val v1: kotlin.String,
) : ToolException() {
override val message
get() = "v1=${ v1 }"
}
class SchemaException(
val v1: kotlin.String,
) : ToolException() {
override val message
get() = "v1=${ v1 }"
}
class NotFound(
val v1: kotlin.String,
) : ToolException() {
override val message
get() = "v1=${ v1 }"
}
companion object ErrorHandler : UniffiRustCallStatusErrorHandler<ToolException> {
override fun lift(error_buf: RustBuffer.ByValue): ToolException = FfiConverterTypeToolError.lift(error_buf)
}
}
/**
* @suppress
*/
public object FfiConverterTypeToolError : FfiConverterRustBuffer<ToolException> {
override fun read(buf: ByteBuffer): ToolException =
when (buf.getInt()) {
1 ->
ToolException.InvalidParameters(
FfiConverterString.read(buf),
)
2 ->
ToolException.ExecutionException(
FfiConverterString.read(buf),
)
3 ->
ToolException.SchemaException(
FfiConverterString.read(buf),
)
4 ->
ToolException.NotFound(
FfiConverterString.read(buf),
)
else -> throw RuntimeException("invalid error enum value, something is very wrong!!")
}
override fun allocationSize(value: ToolException): ULong =
when (value) {
is ToolException.InvalidParameters -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ToolException.ExecutionException -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ToolException.SchemaException -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
is ToolException.NotFound -> (
// Add the size for the Int that specifies the variant plus the size needed for all fields
4UL +
FfiConverterString.allocationSize(value.v1)
)
}
override fun write(
value: ToolException,
buf: ByteBuffer,
) {
when (value) {
is ToolException.InvalidParameters -> {
buf.putInt(1)
FfiConverterString.write(value.v1, buf)
Unit
}
is ToolException.ExecutionException -> {
buf.putInt(2)
FfiConverterString.write(value.v1, buf)
Unit
}
is ToolException.SchemaException -> {
buf.putInt(3)
FfiConverterString.write(value.v1, buf)
Unit
}
is ToolException.NotFound -> {
buf.putInt(4)
FfiConverterString.write(value.v1, buf)
Unit
}
}.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
}
}
/**
* @suppress
*/
public object FfiConverterOptionalUInt : FfiConverterRustBuffer<kotlin.UInt?> {
override fun read(buf: ByteBuffer): kotlin.UInt? {
if (buf.get().toInt() == 0) {
return null
}
return FfiConverterUInt.read(buf)
}
override fun allocationSize(value: kotlin.UInt?): ULong {
if (value == null) {
return 1UL
} else {
return 1UL + FfiConverterUInt.allocationSize(value)
}
}
override fun write(
value: kotlin.UInt?,
buf: ByteBuffer,
) {
if (value == null) {
buf.put(0)
} else {
buf.put(1)
FfiConverterUInt.write(value, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterOptionalInt : FfiConverterRustBuffer<kotlin.Int?> {
override fun read(buf: ByteBuffer): kotlin.Int? {
if (buf.get().toInt() == 0) {
return null
}
return FfiConverterInt.read(buf)
}
override fun allocationSize(value: kotlin.Int?): ULong {
if (value == null) {
return 1UL
} else {
return 1UL + FfiConverterInt.allocationSize(value)
}
}
override fun write(
value: kotlin.Int?,
buf: ByteBuffer,
) {
if (value == null) {
buf.put(0)
} else {
buf.put(1)
FfiConverterInt.write(value, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterOptionalFloat : FfiConverterRustBuffer<kotlin.Float?> {
override fun read(buf: ByteBuffer): kotlin.Float? {
if (buf.get().toInt() == 0) {
return null
}
return FfiConverterFloat.read(buf)
}
override fun allocationSize(value: kotlin.Float?): ULong {
if (value == null) {
return 1UL
} else {
return 1UL + FfiConverterFloat.allocationSize(value)
}
}
override fun write(
value: kotlin.Float?,
buf: ByteBuffer,
) {
if (value == null) {
buf.put(0)
} else {
buf.put(1)
FfiConverterFloat.write(value, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterOptionalDouble : FfiConverterRustBuffer<kotlin.Double?> {
override fun read(buf: ByteBuffer): kotlin.Double? {
if (buf.get().toInt() == 0) {
return null
}
return FfiConverterDouble.read(buf)
}
override fun allocationSize(value: kotlin.Double?): ULong {
if (value == null) {
return 1UL
} else {
return 1UL + FfiConverterDouble.allocationSize(value)
}
}
override fun write(
value: kotlin.Double?,
buf: ByteBuffer,
) {
if (value == null) {
buf.put(0)
} else {
buf.put(1)
FfiConverterDouble.write(value, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterOptionalString : FfiConverterRustBuffer<kotlin.String?> {
override fun read(buf: ByteBuffer): kotlin.String? {
if (buf.get().toInt() == 0) {
return null
}
return FfiConverterString.read(buf)
}
override fun allocationSize(value: kotlin.String?): ULong {
if (value == null) {
return 1UL
} else {
return 1UL + FfiConverterString.allocationSize(value)
}
}
override fun write(
value: kotlin.String?,
buf: ByteBuffer,
) {
if (value == null) {
buf.put(0)
} else {
buf.put(1)
FfiConverterString.write(value, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterSequenceTypeExtensionConfig : FfiConverterRustBuffer<List<ExtensionConfig>> {
override fun read(buf: ByteBuffer): List<ExtensionConfig> {
val len = buf.getInt()
return List<ExtensionConfig>(len) {
FfiConverterTypeExtensionConfig.read(buf)
}
}
override fun allocationSize(value: List<ExtensionConfig>): ULong {
val sizeForLength = 4UL
val sizeForItems = value.map { FfiConverterTypeExtensionConfig.allocationSize(it) }.sum()
return sizeForLength + sizeForItems
}
override fun write(
value: List<ExtensionConfig>,
buf: ByteBuffer,
) {
buf.putInt(value.size)
value.iterator().forEach {
FfiConverterTypeExtensionConfig.write(it, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterSequenceTypeMessage : FfiConverterRustBuffer<List<Message>> {
override fun read(buf: ByteBuffer): List<Message> {
val len = buf.getInt()
return List<Message>(len) {
FfiConverterTypeMessage.read(buf)
}
}
override fun allocationSize(value: List<Message>): ULong {
val sizeForLength = 4UL
val sizeForItems = value.map { FfiConverterTypeMessage.allocationSize(it) }.sum()
return sizeForLength + sizeForItems
}
override fun write(
value: List<Message>,
buf: ByteBuffer,
) {
buf.putInt(value.size)
value.iterator().forEach {
FfiConverterTypeMessage.write(it, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterSequenceTypeToolConfig : FfiConverterRustBuffer<List<ToolConfig>> {
override fun read(buf: ByteBuffer): List<ToolConfig> {
val len = buf.getInt()
return List<ToolConfig>(len) {
FfiConverterTypeToolConfig.read(buf)
}
}
override fun allocationSize(value: List<ToolConfig>): ULong {
val sizeForLength = 4UL
val sizeForItems = value.map { FfiConverterTypeToolConfig.allocationSize(it) }.sum()
return sizeForLength + sizeForItems
}
override fun write(
value: List<ToolConfig>,
buf: ByteBuffer,
) {
buf.putInt(value.size)
value.iterator().forEach {
FfiConverterTypeToolConfig.write(it, buf)
}
}
}
/**
* @suppress
*/
public object FfiConverterSequenceTypeMessageContent : FfiConverterRustBuffer<List<MessageContent>> {
override fun read(buf: ByteBuffer): List<MessageContent> {
val len = buf.getInt()
return List<MessageContent>(len) {
FfiConverterTypeMessageContent.read(buf)
}
}
override fun allocationSize(value: List<MessageContent>): ULong {
val sizeForLength = 4UL
val sizeForItems = value.map { FfiConverterTypeMessageContent.allocationSize(it) }.sum()
return sizeForLength + sizeForItems
}
override fun write(
value: List<MessageContent>,
buf: ByteBuffer,
) {
buf.putInt(value.size)
value.iterator().forEach {
FfiConverterTypeMessageContent.write(it, buf)
}
}
}
/**
* Typealias from the type name used in the UDL file to the builtin type. This
* is needed because the UDL type name is used in function/method signatures.
* It's also what we have an external type that references a custom type.
*/
public typealias CompletionRequest = kotlin.String
public typealias FfiConverterTypeCompletionRequest = FfiConverterString
/**
* Typealias from the type name used in the UDL file to the builtin type. This
* is needed because the UDL type name is used in function/method signatures.
* It's also what we have an external type that references a custom type.
*/
public typealias Contents = List<MessageContent>
public typealias FfiConverterTypeContents = FfiConverterSequenceTypeMessageContent
/**
* Typealias from the type name used in the UDL file to the builtin type. This
* is needed because the UDL type name is used in function/method signatures.
* It's also what we have an external type that references a custom type.
*/
public typealias ToolRequestToolCall = kotlin.String
public typealias FfiConverterTypeToolRequestToolCall = FfiConverterString
/**
* Typealias from the type name used in the UDL file to the builtin type. This
* is needed because the UDL type name is used in function/method signatures.
* It's also what we have an external type that references a custom type.
*/
public typealias ToolResponseToolResult = kotlin.String
public typealias FfiConverterTypeToolResponseToolResult = FfiConverterString
/**
* Typealias from the type name used in the UDL file to the builtin type. This
* is needed because the UDL type name is used in function/method signatures.
* It's also what we have an external type that references a custom type.
*/
public typealias Value = kotlin.String
public typealias FfiConverterTypeValue = FfiConverterString
/**
* Public API for the Goose LLM completion function
*/
@Throws(CompletionException::class)
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
suspend fun `completion`(`req`: CompletionRequest): CompletionResponse =
uniffiRustCallAsync(
UniffiLib.INSTANCE.uniffi_goose_llm_fn_func_completion(FfiConverterTypeCompletionRequest.lower(`req`)),
{ future, callback, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_poll_rust_buffer(future, callback, continuation) },
{ future, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_complete_rust_buffer(future, continuation) },
{ future -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_free_rust_buffer(future) },
// lift function
{ FfiConverterTypeCompletionResponse.lift(it) },
// Error FFI converter
CompletionException.ErrorHandler,
)
fun `createCompletionRequest`(
`providerName`: kotlin.String,
`providerConfig`: Value,
`modelConfig`: ModelConfig,
`systemPreamble`: kotlin.String? = null,
`systemPromptOverride`: kotlin.String? = null,
`messages`: List<Message>,
`extensions`: List<ExtensionConfig>,
`requestId`: kotlin.String? = null,
): CompletionRequest =
FfiConverterTypeCompletionRequest.lift(
uniffiRustCall { _status ->
UniffiLib.INSTANCE.uniffi_goose_llm_fn_func_create_completion_request(
FfiConverterString.lower(`providerName`),
FfiConverterTypeValue.lower(`providerConfig`),
FfiConverterTypeModelConfig.lower(`modelConfig`),
FfiConverterOptionalString.lower(`systemPreamble`),
FfiConverterOptionalString.lower(`systemPromptOverride`),
FfiConverterSequenceTypeMessage.lower(`messages`),
FfiConverterSequenceTypeExtensionConfig.lower(`extensions`),
FfiConverterOptionalString.lower(`requestId`),
_status,
)
},
)
fun `createToolConfig`(
`name`: kotlin.String,
`description`: kotlin.String,
`inputSchema`: Value,
`approvalMode`: ToolApprovalMode,
): ToolConfig =
FfiConverterTypeToolConfig.lift(
uniffiRustCall { _status ->
UniffiLib.INSTANCE.uniffi_goose_llm_fn_func_create_tool_config(
FfiConverterString.lower(`name`),
FfiConverterString.lower(`description`),
FfiConverterTypeValue.lower(`inputSchema`),
FfiConverterTypeToolApprovalMode.lower(`approvalMode`),
_status,
)
},
)
/**
* Generates a short (≤4 words) session name
*/
@Throws(ProviderException::class)
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
suspend fun `generateSessionName`(
`providerName`: kotlin.String,
`providerConfig`: Value,
`messages`: List<Message>,
`requestId`: kotlin.String? = null,
): kotlin.String =
uniffiRustCallAsync(
UniffiLib.INSTANCE.uniffi_goose_llm_fn_func_generate_session_name(
FfiConverterString.lower(`providerName`),
FfiConverterTypeValue.lower(`providerConfig`),
FfiConverterSequenceTypeMessage.lower(`messages`),
FfiConverterOptionalString.lower(`requestId`),
),
{ future, callback, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_poll_rust_buffer(future, callback, continuation) },
{ future, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_complete_rust_buffer(future, continuation) },
{ future -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_free_rust_buffer(future) },
// lift function
{ FfiConverterString.lift(it) },
// Error FFI converter
ProviderException.ErrorHandler,
)
/**
* Generates a structured output based on the provided schema,
* system prompt and user messages.
*/
@Throws(ProviderException::class)
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
suspend fun `generateStructuredOutputs`(
`providerName`: kotlin.String,
`providerConfig`: Value,
`systemPrompt`: kotlin.String,
`messages`: List<Message>,
`schema`: Value,
`requestId`: kotlin.String? = null,
): ProviderExtractResponse =
uniffiRustCallAsync(
UniffiLib.INSTANCE.uniffi_goose_llm_fn_func_generate_structured_outputs(
FfiConverterString.lower(`providerName`),
FfiConverterTypeValue.lower(`providerConfig`),
FfiConverterString.lower(`systemPrompt`),
FfiConverterSequenceTypeMessage.lower(`messages`),
FfiConverterTypeValue.lower(`schema`),
FfiConverterOptionalString.lower(`requestId`),
),
{ future, callback, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_poll_rust_buffer(future, callback, continuation) },
{ future, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_complete_rust_buffer(future, continuation) },
{ future -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_free_rust_buffer(future) },
// lift function
{ FfiConverterTypeProviderExtractResponse.lift(it) },
// Error FFI converter
ProviderException.ErrorHandler,
)
/**
* Generates a tooltip summarizing the last two messages in the session,
* including any tool calls or results.
*/
@Throws(ProviderException::class)
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
suspend fun `generateTooltip`(
`providerName`: kotlin.String,
`providerConfig`: Value,
`messages`: List<Message>,
`requestId`: kotlin.String? = null,
): kotlin.String =
uniffiRustCallAsync(
UniffiLib.INSTANCE.uniffi_goose_llm_fn_func_generate_tooltip(
FfiConverterString.lower(`providerName`),
FfiConverterTypeValue.lower(`providerConfig`),
FfiConverterSequenceTypeMessage.lower(`messages`),
FfiConverterOptionalString.lower(`requestId`),
),
{ future, callback, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_poll_rust_buffer(future, callback, continuation) },
{ future, continuation -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_complete_rust_buffer(future, continuation) },
{ future -> UniffiLib.INSTANCE.ffi_goose_llm_rust_future_free_rust_buffer(future) },
// lift function
{ FfiConverterString.lift(it) },
// Error FFI converter
ProviderException.ErrorHandler,
)
fun `printMessages`(`messages`: List<Message>) =
uniffiRustCall { _status ->
UniffiLib.INSTANCE.uniffi_goose_llm_fn_func_print_messages(
FfiConverterSequenceTypeMessage.lower(`messages`),
_status,
)
}