@h1r-ai/croche-react-native 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +475 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/android/build.gradle +47 -0
  5. package/android/src/main/AndroidManifest.xml +8 -0
  6. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +836 -0
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
  9. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  11. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  12. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  13. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  16. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  17. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  18. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  32. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  33. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  34. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  35. package/croche-react-native.podspec +28 -0
  36. package/ios/CrocheRuntimeBridge.swift +986 -0
  37. package/ios/RNCrocheRuntime.mm +221 -0
  38. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  39. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  40. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  41. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
  42. package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
  43. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  44. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  45. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  48. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
  49. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  50. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
  51. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  52. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  53. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  54. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  55. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  56. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  57. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  58. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  59. package/package.json +40 -4
  60. package/scripts/vendor-native.sh +56 -0
  61. package/src/NativeCrocheRuntime.ts +162 -0
  62. package/src/index.ts +660 -0
  63. package/src/project-types.ts +35 -0
  64. package/src/project.ts +426 -0
  65. package/src/protocol.ts +28 -0
  66. package/src/types.ts +9 -0
@@ -0,0 +1,178 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import java.net.URI
5
+ import java.util.UUID
6
+ import java.util.concurrent.*
7
+ import java.util.concurrent.atomic.AtomicBoolean
8
+
9
+ fun interface ControlSend { fun send(input: JsonObject, cancellation: RuntimeCancellation): JsonElement }
10
+ fun interface ControlCancel { fun cancel(): Boolean }
11
+
12
+ /** Explicit local attachment, independent of Cloud credentials and Runtime ownership.
13
+ * Close this connection separately; it never opens/closes the Runtime's private store. */
14
+ class RuntimeControl private constructor(
15
+ private val runtime: CrocheRuntime, private val url: String, private val token: String,
16
+ private val http: RuntimeHTTP, private val sendAdapter: ControlSend?, private val cancelAdapter: ControlCancel?,
17
+ private val onError: ((String) -> Unit)?
18
+ ) : AutoCloseable {
19
+ val runtimeInstanceId = runtime.inspect().at("status").at("runtimeInstanceId").text()
20
+ val capabilities: List<String> = listOf("status", "history", "send", "cancel", "sync", "budget.get", "budget.set", "tools")
21
+ private val clientId = UUID.randomUUID().toString()
22
+ private val lifetime = RuntimeCancellation()
23
+ private val effects = EffectExecutor()
24
+ private val closed = AtomicBoolean(false)
25
+ private val handled = ConcurrentHashMap.newKeySet<String>()
26
+ private val results = ConcurrentHashMap<String, JsonObject>()
27
+ private val active = ConcurrentHashMap<String, RuntimeCancellation>()
28
+ private val tasks = ConcurrentHashMap.newKeySet<String>()
29
+ private val workers = ThreadPoolExecutor(0, 16, 30, TimeUnit.SECONDS, SynchronousQueue(),
30
+ ThreadFactory { task -> Thread(task, "croche-control-command").apply { isDaemon = true } })
31
+ private var poller: Thread? = null
32
+ companion object {
33
+ fun attach(runtime: CrocheRuntime, token: String, url: String = "http://127.0.0.1:8791",
34
+ http: RuntimeHTTP = RuntimeHttpURLConnection(), send: ControlSend? = null,
35
+ cancel: ControlCancel? = null, onError: ((String) -> Unit)? = null): RuntimeControl {
36
+ val parsed = try { URI(url) } catch (_: Exception) { throw CrocheException("invalid_configuration", "Invalid local control URL") }
37
+ if (parsed.scheme != "http" || parsed.host !in listOf("127.0.0.1", "localhost", "[::1]", "::1") ||
38
+ parsed.userInfo != null || parsed.query != null || parsed.fragment != null || parsed.path !in listOf("", "/") ||
39
+ !Regex("^[A-Za-z0-9._~-]{24,4096}$").matches(token)) {
40
+ throw CrocheException("invalid_configuration", "Control needs a loopback HTTP origin and explicit local token")
41
+ }
42
+ val control = RuntimeControl(runtime, url.removeSuffix("/"), token, http, send, cancel, onError)
43
+ try { control.register(); control.start() }
44
+ catch (error: Exception) { control.release(); throw error }
45
+ return control
46
+ }
47
+ }
48
+ private fun identity() = obj("client_id" to str(clientId), "runtime_instance_id" to str(runtimeInstanceId))
49
+ private fun register() {
50
+ val caps = JsonArray(); capabilities.forEach { caps.add(it) }
51
+ post("register", obj("client_id" to str(clientId), "runtime" to runtime.inspect().at("status"), "capabilities" to caps))
52
+ }
53
+ private fun post(path: String, body: JsonObject): JsonObject {
54
+ if (body.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("control_capacity", "Control request exceeds 1MiB")
55
+ val effect = obj("url" to str("$url/v1/control/$path"), "method" to str("POST"),
56
+ "headers" to obj("Authorization" to str("Bearer $token"), "Content-Type" to str("application/json")),
57
+ "body" to body, "timeoutMs" to num(5000))
58
+ val response = effects.run(5000, lifetime) { signal -> http.execute(effect, signal) {} }
59
+ val data = response.at("body")
60
+ if (!data.isJsonObject || data.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("invalid_response", "Invalid bounded control response")
61
+ if (response.at("status").asInt !in 200..299) {
62
+ val code = data.at("error").at("code").text()
63
+ throw CrocheException(if (code in setOf("attachment_lost", "not_found", "unauthorized", "runtime_already_attached")) code else "control_error", "Local control broker rejected the request")
64
+ }
65
+ return data.asJsonObject
66
+ }
67
+ private fun start() {
68
+ poller = Thread({
69
+ while (!closed.get()) {
70
+ try {
71
+ results.entries.take(8).forEach { (id, result) ->
72
+ try { post("results", result); results.remove(id) }
73
+ catch (error: CrocheException) { if (error.code in listOf("not_found", "attachment_lost")) results.remove(id); throw error }
74
+ }
75
+ if (results.size < 32 && tasks.size < 16) {
76
+ val data = post("poll", identity())
77
+ if (!data.at("commands").isJsonArray) throw CrocheException("invalid_response", "Invalid broker command list")
78
+ data.at("commands").asJsonArray.take(8).forEach { accept(it) }
79
+ }
80
+ } catch (error: Exception) {
81
+ if (!closed.get()) {
82
+ try { onError?.invoke("Local control could not complete a request") } catch (_: Exception) {}
83
+ if (error is CrocheException && error.code == "attachment_lost") try { register() } catch (_: Exception) {}
84
+ }
85
+ }
86
+ try { Thread.sleep(100) } catch (_: InterruptedException) { if (closed.get()) break }
87
+ }
88
+ }, "croche-control-poll").apply { isDaemon = true; start() }
89
+ }
90
+ private fun accept(value: JsonElement) {
91
+ val id = value.at("request_id").text(); val command = value.at("command").text(); val payload = value.at("payload")
92
+ if (!validId(id) || command !in capabilities || !payload.isJsonObject) throw CrocheException("invalid_command", "Invalid broker command envelope")
93
+ if (handled.contains(id)) return
94
+ if (handled.size >= 1000) throw CrocheException("control_capacity", "Reattach after 1000 control requests")
95
+ handled.add(id); tasks.add(id)
96
+ val work = Runnable {
97
+ val reply = identity().apply { addProperty("request_id", id) }
98
+ try {
99
+ val result = execute(command, payload.asJsonObject.deepCopy(), id)
100
+ if (result.toString().toByteArray(Charsets.UTF_8).size > 900000) throw CrocheException("result_too_large", "Request a smaller result page")
101
+ reply.add("result", result.deepCopy())
102
+ } catch (error: Exception) {
103
+ val code = (error as? CrocheException)?.code
104
+ reply.add("error", obj("code" to str(if (code in publicCodes) code!! else "runtime_error"),
105
+ "message" to str("The Runtime command failed. Inspect it before retrying."),
106
+ "uncertain" to bool(command == "send" || command == "budget.set")))
107
+ } finally { tasks.remove(id) }
108
+ if (!closed.get()) results[id] = reply
109
+ }
110
+ try { workers.execute(work) }
111
+ catch (_: RejectedExecutionException) {
112
+ tasks.remove(id)
113
+ results[id] = identity().apply {
114
+ addProperty("request_id", id)
115
+ add("error", obj("code" to str("control_capacity"), "message" to str("Control workers are occupied"), "uncertain" to bool(false)))
116
+ }
117
+ }
118
+ }
119
+ private fun execute(command: String, payload: JsonObject, id: String): JsonElement {
120
+ if (closed.get()) throw CrocheException("control_closed", "Control is closed")
121
+ fun keys(allowed: Set<String>) { if (!allowed.containsAll(payload.keySet())) throw CrocheException("invalid_command", "Unsupported command fields") }
122
+ if (command == "send") {
123
+ keys(setOf("id", "text"))
124
+ val text = payload.at("text").text()
125
+ if (!validId(payload.at("id").text()) || text.isBlank() || text.length > 32000) throw CrocheException("invalid_command", "send needs immutable id and text only")
126
+ val signal = RuntimeCancellation(); active[id] = signal
127
+ try { return sendAdapter?.send(payload, signal) ?: runtime.send(payload, signal) }
128
+ finally { active.remove(id) }
129
+ }
130
+ if (command == "history") {
131
+ keys(setOf("offset", "limit"))
132
+ fun integer(key: String, default: Int, min: Int, max: Int): Int {
133
+ if (!payload.has(key)) return default
134
+ val value = payload[key]
135
+ if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber) throw CrocheException("invalid_command", "Invalid history page")
136
+ val number = value.asDouble
137
+ if (!number.isFinite() || number < min || number > max || number != kotlin.math.floor(number)) throw CrocheException("invalid_command", "Invalid history page")
138
+ return number.toInt()
139
+ }
140
+ val offset = integer("offset", 0, 0, 1000000); val limit = integer("limit", 100, 1, 200)
141
+ val history = runtime.inspect().at("history").asJsonArray; val page = JsonArray()
142
+ history.drop(offset).take(limit).forEach { page.add(it.deepCopy()) }
143
+ return obj("messages" to page, "total" to num(history.size()), "offset" to num(offset), "limit" to num(limit))
144
+ }
145
+ if (command == "budget.set") {
146
+ keys(setOf("amount")); val value = payload.at("amount")
147
+ if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber || !value.asDouble.isFinite() || value.asDouble < 0) throw CrocheException("invalid_command", "Budget requires a finite non-negative amount")
148
+ return runtime.adjustBudget(value.asDouble, absolute = true)
149
+ }
150
+ keys(emptySet())
151
+ if (command == "cancel") {
152
+ val pending = active.isNotEmpty(); active.values.forEach { it.cancel() }
153
+ val host = cancelAdapter?.cancel() ?: false
154
+ return obj("requested" to bool(pending || host), "scope" to str(if (cancelAdapter != null) "host" else "control_client"), "rollback" to bool(false))
155
+ }
156
+ if (command == "sync") runtime.sync()
157
+ val view = runtime.inspect()
158
+ return when (command) {
159
+ "status" -> view.at("status").deepCopy().asJsonObject.apply {
160
+ add("control", obj("cancellation_scope" to str(if (cancelAdapter != null) "host" else "control_client")))
161
+ }
162
+ "sync" -> view.at("status")
163
+ "tools" -> view.at("tools")
164
+ "budget.get" -> view.at("budget")
165
+ else -> throw CrocheException("unsupported_capability", "Unsupported Runtime command")
166
+ }
167
+ }
168
+ override fun close() {
169
+ if (!closed.compareAndSet(false, true)) return
170
+ active.values.forEach { it.cancel() }
171
+ try { post("unregister", identity()) } catch (_: Exception) {}
172
+ release()
173
+ if (Thread.currentThread() != poller) poller?.join(6000)
174
+ }
175
+ private fun release() { closed.set(true); lifetime.cancel(); effects.close(); workers.shutdown(); poller?.interrupt() }
176
+ }
177
+ private fun validId(value: String) = Regex("^[A-Za-z0-9_.:-]{1,200}$").matches(value)
178
+ private val publicCodes = setOf("invalid_command", "control_closed", "unsupported_capability", "result_too_large", "busy", "closed", "storage_error", "context_limit", "budget_limit")
@@ -0,0 +1,12 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+
5
+ class CrocheException(val code: String, override val message: String, val receipt: Receipt? = null) : RuntimeException("$code: $message")
6
+
7
+ internal fun obj(vararg fields: Pair<String, JsonElement>): JsonObject = JsonObject().apply { fields.forEach { add(it.first, it.second) } }
8
+ internal fun str(value: String): JsonElement = JsonPrimitive(value)
9
+ internal fun num(value: Number): JsonElement = JsonPrimitive(value)
10
+ internal fun bool(value: Boolean): JsonElement = JsonPrimitive(value)
11
+ internal fun JsonElement.at(key: String): JsonElement = if (isJsonObject) asJsonObject.get(key) ?: JsonNull.INSTANCE else JsonNull.INSTANCE
12
+ internal fun JsonElement.text(): String = if (isJsonPrimitive && asJsonPrimitive.isString) asString else ""
@@ -0,0 +1,405 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.CancelToken
5
+ import dev.croche.ffi.CoreRuntime
6
+ import dev.croche.ffi.PendingSend
7
+ import dev.croche.ffi.RuntimeOpenOptions
8
+ import kotlin.coroutines.suspendCoroutine
9
+ import java.io.File
10
+
11
+ /** Grouped command invocation, already parsed/validated by Rust. */
12
+ data class CommandInvocation(val tool: String, val command: String?, val key: String, val args: JsonObject)
13
+ data class ToolContext(val callId: String, val messageId: String, val userId: String, val cancellation: RuntimeCancellation,
14
+ /** Present when the Runtime config has an agentId. Last, with a default, so existing destructuring is unchanged. */
15
+ val agentId: String? = null,
16
+ /** Where a [withResult] handler leaves its images for this call (set by the Runtime). */
17
+ val images: ToolImages? = null)
18
+ fun interface ToolHandler { fun execute(invocation: CommandInvocation, context: ToolContext): JsonElement }
19
+
20
+ /** One wiki document: a path such as `menu/stew.md` and its markdown (at most 64 KB; 2,000
21
+ * documents and 8 MB in all). The title is the first `#` heading; optional frontmatter may set
22
+ * `summary`, `keywords` and `agents` (only those agents see the document); `agents` given here
23
+ * overrides the frontmatter's. An agent's own path globs are config: `"wiki": {"include": [...],
24
+ * "exclude": [...]}`. */
25
+ data class WikiDocument(val path: String, val markdown: String, val agents: List<String>? = null) {
26
+ companion object {
27
+ private const val MAX_DOCUMENTS = 2000
28
+
29
+ /** The `.md` files under `dir`, paths relative to it with `/` (`menu/stew.md`), in name
30
+ * order. Subfolders are read; symbolic links and other files are skipped, as the other
31
+ * SDKs' loaders do. */
32
+ fun fromDirectory(dir: java.io.File): List<WikiDocument> {
33
+ val root = dir.toPath()
34
+ if (!java.nio.file.Files.isDirectory(root, java.nio.file.LinkOption.NOFOLLOW_LINKS))
35
+ throw CrocheException("invalid_wiki", "${dir.path}: not a folder")
36
+ return fromTree(
37
+ list = { path ->
38
+ val at = if (path.isEmpty()) root else root.resolve(path)
39
+ if (java.nio.file.Files.isDirectory(at, java.nio.file.LinkOption.NOFOLLOW_LINKS))
40
+ java.nio.file.Files.list(at).use { s -> s.map { it.fileName.toString() }.toList() }.toTypedArray()
41
+ else null
42
+ },
43
+ read = { path ->
44
+ val at = root.resolve(path)
45
+ if (java.nio.file.Files.isRegularFile(at, java.nio.file.LinkOption.NOFOLLOW_LINKS)) String(java.nio.file.Files.readAllBytes(at), Charsets.UTF_8) else null
46
+ },
47
+ )
48
+ }
49
+
50
+ /** The documents in any tree the app can list and read, such as Android assets
51
+ * (`dev.croche.android.wikiFromAssets`). `list(path)` gives the names in a folder, or
52
+ * null or empty for a file; `read(path)` gives a file's text, or null to skip it. Paths
53
+ * are relative to the tree's root, with `/`; the root itself is `""`. */
54
+ fun fromTree(list: (String) -> Array<String>?, read: (String) -> String?): List<WikiDocument> {
55
+ val out = mutableListOf<WikiDocument>()
56
+ fun walk(prefix: String) {
57
+ for (name in (list(prefix) ?: emptyArray()).sorted()) {
58
+ val path = if (prefix.isEmpty()) name else "$prefix/$name"
59
+ val children = list(path)
60
+ if (!children.isNullOrEmpty()) walk(path)
61
+ else if (name.endsWith(".md")) {
62
+ val markdown = read(path) ?: continue
63
+ if (out.size >= MAX_DOCUMENTS) throw CrocheException("invalid_wiki", "The wiki holds at most $MAX_DOCUMENTS documents")
64
+ out.add(WikiDocument(path, markdown))
65
+ }
66
+ }
67
+ }
68
+ walk("")
69
+ return out
70
+ }
71
+ }
72
+ }
73
+
74
+ /** The Croche Runtime for Kotlin. The Rust Core (crates/croche-ffi) is the Runtime: it holds
75
+ * the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
76
+ * Kotlin types; `KotlinHost` performs what only the platform can (the PAL).
77
+ * Blocking: call from an IO executor/coroutine, never Android's main thread. Methods return
78
+ * detached JSON values. */
79
+ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, private val nativeHost: KotlinHost?,
80
+ private val subscription: StreamHub? = null, private val subscriptionPort: CoreStreamPort? = null) : AutoCloseable {
81
+ private val core: CoreRuntime get() = checkNotNull(nativeCore) { "Legacy API requires native Core" }
82
+ internal val host: KotlinHost get() = checkNotNull(nativeHost) { "Legacy host requires native Core" }
83
+ /** Fake-port host seam; create() installs NativeCoreStreamPort. */
84
+ internal constructor(port: CoreStreamPort) : this(null, null, StreamHub(port), port)
85
+ internal val boundStreamPort: CoreStreamPort get() = checkNotNull(subscriptionPort)
86
+ private fun subscriptions(): StreamHub = subscription ?: throw CrocheException(
87
+ "invalid_configuration", "Subscription binding is not installed")
88
+ suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt = subscriptions().send(input, options)
89
+ fun events(initialMessages: Int = 50): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(initialMessages)
90
+ fun events(after: Cursor): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(null, after)
91
+ suspend fun request(input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = null): RequestResult = subscriptions().request(input, options, wait)
92
+ suspend fun cancel(id: String) { subscriptions().cancel(id) }
93
+ suspend fun history(before: Long? = null, limit: Int) { subscriptions().history(before, limit) }
94
+ val logId: String get() = subscriptions().logId
95
+ internal val state: RuntimeEvent.State get() = subscriptions().state
96
+ @Volatile private var closed = false
97
+ @Volatile private var onDelivery: ((JsonElement) -> Unit)? = null
98
+ companion object {
99
+ /** Test-only gate-10 probe; called on the thread that invokes each native stream-port call. */
100
+ @Volatile internal var offloadStarting: (() -> Unit)? = null
101
+
102
+ /** `secrets` keeps the Runtime credential apart from `storage`: KeystoreSecretStore on
103
+ * Android. `attestor` proves the genuine app to Cloud when the project requires it:
104
+ * PlayIntegrityAttestor on a device; null on an emulator or a host that cannot attest.
105
+ * Events may be delivered on an effect worker thread while a reply streams.
106
+ * `libraryName` names the native Runtime library (libcroche_ffi by default).
107
+ * `wiki` is the documents, set at open; this agent's path filter is the config's
108
+ * `"wiki": {"include": [...], "exclude": [...]}`.
109
+ * `onEvent` hears one `turn.started` per turn; a send carried into a running turn at a
110
+ * later model call is `{type:"turn.joined", turnId, inputIds}` (the ids newly carried).
111
+ * `onUsage` receives every paid call's cost (`{type:"usage", operationId, purpose, causedBy, instance,
112
+ * model, costUsd, costStatus, tokens?}`; `tokens` holds the reported counts, e.g. `prompt`,
113
+ * `cached`); `instance` is the named/generated instance key, or null for the main agent.
114
+ * `model` is the gateway-reported answering model (`modelSource: "response"`), or the
115
+ * request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
116
+ * present only when different. Reported cost is unchanged by a model substitution.
117
+ * At least once, from the start: open itself reports a call
118
+ * the process died during. It runs on a Runtime thread; do not call the Runtime from it.
119
+ * `scheduler` registers the agent's scheduled notes with the OS for when the app is not
120
+ * running: `WorkManagerScheduler` on Android; null on a JVM host, where an in-process
121
+ * timer delivers them while it runs and the next open delivers what fell due meanwhile.
122
+ * A scheduler whose name another open Runtime holds refuses this one (`scheduler_conflict`).
123
+ * `projectDirectory` is required on a plain JVM and refused on Android, which always uses
124
+ * app-private filesDir. It is a host option, never part of the Core config. */
125
+ fun create(config: JsonObject, storage: RuntimeStorage, secrets: RuntimeSecretStore,
126
+ attestor: RuntimeAttestor? = null, tools: Map<String, ToolHandler> = emptyMap(),
127
+ http: RuntimeHTTP = RuntimeHttpURLConnection(), onEvent: ((JsonElement) -> Unit)? = null,
128
+ onDebugEvent: ((JsonElement) -> Unit)? = null, libraryName: String = LIBRARY,
129
+ backgroundSync: Boolean = true, maintenanceIntervalMs: Long = 60_000,
130
+ wiki: List<WikiDocument>? = null, onUsage: ((JsonElement) -> Unit)? = null,
131
+ scheduler: RuntimeScheduler? = null, projectDirectory: File? = null): CrocheRuntime {
132
+ useLibrary(libraryName)
133
+ val bound = config.deepCopy().apply {
134
+ if (attestor != null) addProperty("attestationPlatform", attestor.platform) else add("attestationPlatform", JsonNull.INSTANCE)
135
+ }
136
+ // This host can feed deltas, so it asks for a stream unless the app opted out.
137
+ val streaming = config.at("streaming").let { if (it.isJsonPrimitive && it.asJsonPrimitive.isBoolean) it.asBoolean else true }
138
+ scheduler?.attach()
139
+ // From here the host's stop (close, or a failed open) detaches the scheduler.
140
+ val host = KotlinHost(storage, secrets, attestor, http, tools.toMap(), backgroundSync, scheduler, projectDirectory)
141
+ // The app chose the store, so the Runtime binds its identity to it (a custom storage key).
142
+ val options = RuntimeOpenOptions("croche.kotlin", streaming, backgroundSync, maintenanceInterval(maintenanceIntervalMs).toDouble())
143
+ val core = try { CoreRuntime.open(host, bound.toString(), options, onEvent?.let { EventHook(it) }, onUsage?.let { EventHook(it) }) }
144
+ catch (error: Exception) { host.release(); throw crocheError(error) }
145
+ if (onDebugEvent != null) try { core.setDebugObserver(EventHook(onDebugEvent), false) } catch (_: Exception) {}
146
+ val port = NativeCoreStreamPort(core, host)
147
+ val hub = try { StreamHub(port) } catch (error: Exception) { port.close(); throw crocheError(error) }
148
+ val runtime = CrocheRuntime(core, host, hub, port)
149
+ host.deliver = { runtime.deliverDue() }
150
+ host.attach(core)
151
+ if (wiki != null) try { runtime.wiki.set(wiki) } catch (error: Exception) { runtime.close(); throw error }
152
+ return runtime
153
+ }
154
+ fun identity(config: JsonObject, libraryName: String = LIBRARY): JsonElement {
155
+ useLibrary(libraryName)
156
+ return try { JsonParser.parseString(dev.croche.ffi.identity(config.toString())) } catch (error: Exception) { throw crocheError(error) }
157
+ }
158
+ private const val LIBRARY = "croche_ffi"
159
+ private fun useLibrary(name: String) {
160
+ if (name != LIBRARY) System.setProperty("uniffi.component.croche_ffi.libraryOverride", name)
161
+ }
162
+ }
163
+ private fun run(body: (CoreRuntime) -> String?): JsonElement {
164
+ if (closed) throw CrocheException("closed", "Runtime is closed")
165
+ return try { body(core)?.let { JsonParser.parseString(it) } ?: JsonNull.INSTANCE } catch (error: Exception) { throw crocheError(error) }
166
+ }
167
+ /** Runs one turn. `cancellation` cancels this turn only, from any thread; one fired before
168
+ * the send starts throws `cancelled` here, and one fired while it runs is never missed.
169
+ * `responseFormat`: structured output, OpenAI's shape (`{"type":"json_schema",...}` or
170
+ * `{"type":"json_object"}`); the result's `output` is the reply as JSON the Core checked. */
171
+ fun send(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
172
+ /** For every image that does not name its own `"resolution"` (default standard). */
173
+ imageResolution: ImageResolution? = null): JsonElement =
174
+ beginSend(input, cancellation, responseFormat, imageResolution).result()
175
+ /** Admits a send at once on the calling thread, without waiting for its turn: sends are
176
+ * admitted in the order they are called (their place among held sends, and in a turn they
177
+ * share), whatever thread then waits. For a host that hops threads after (React Native). */
178
+ internal fun beginSend(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
179
+ imageResolution: ImageResolution? = null): PendingTurn {
180
+ cancellation.check()
181
+ if (closed) throw CrocheException("closed", "Runtime is closed")
182
+ // Standard images are re-encoded here, before admission, so sends keep their order.
183
+ val prepared = CrocheImages.prepareInput(input, imageResolution)
184
+ val token = CancelToken()
185
+ val listener = cancellation.observe { token.cancel() }
186
+ val pending = try { core.beginSend(prepared.toString(), token, responseFormat?.toString()) }
187
+ catch (error: Exception) { cancellation.remove(listener); token.close(); throw crocheError(error) }
188
+ return PendingTurn(pending, token) { cancellation.remove(listener) }
189
+ }
190
+ fun sync(): JsonElement = run { it.sync(); null }
191
+ /**
192
+ * One round of background upkeep: deliver the outbox of call reports, then sync balances,
193
+ * policy and the model key. The Core does work only when some is due and backs off after
194
+ * a failure. It runs by itself after each turn and on a timer (backgroundSync); call it
195
+ * when the app returns to the foreground. It never delays a turn: a send takes over while
196
+ * it waits on Cloud. Never throws; the result says what happened. Blocking.
197
+ */
198
+ fun maintain(force: Boolean = false): JsonElement =
199
+ try { run { it.maintain(force) } } catch (_: Exception) { obj("ran" to bool(false)) }
200
+ /** Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
201
+ * is (no turn, no cost) or one is already being delivered, else `{ran, ids, delivered, turn}`.
202
+ * Never before a note's time. Call it at every foreground. Blocking.
203
+ *
204
+ * `cancellation` cancels this delivery only, from any thread: waiting behind another turn, it
205
+ * leaves without running; running, its turn stops. Either way its notes stay pending. Fired
206
+ * after the delivery ended, it does nothing: never another turn (`cancel()` stops whatever
207
+ * turn runs).
208
+ *
209
+ * Afterwards the pending set is handed to the OS scheduler again (a refusal is reported as
210
+ * `schedule.degraded`): the OS spends a request when it runs it, and a delivery cut short
211
+ * leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
212
+ * ends, and registering its past-due note again would only start another run at once. A
213
+ * failed delivery that answers `retryAt` waits until then. */
214
+ fun deliverDue(cancellation: RuntimeCancellation = RuntimeCancellation()): JsonElement {
215
+ host.attempted()
216
+ val token = CancelToken()
217
+ val listener = cancellation.observe { token.cancel() }
218
+ val result = try { run { it.deliverDue(token) } }
219
+ catch (error: Exception) { resync(); throw error }
220
+ finally { cancellation.remove(listener); token.close() }
221
+ if (result.at("inFlight").let { it.isJsonPrimitive && it.asBoolean }) return result
222
+ retryAt(result.at("retryAt"))?.let { host.retryAfter(it) }
223
+ resync()
224
+ if (result.at("ran").let { it.isJsonPrimitive && it.asBoolean }) onDelivery?.let { notify -> try { notify(result) } catch (_: Exception) {} }
225
+ return result
226
+ }
227
+ /** INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
228
+ * module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
229
+ * delivery turn (`ran: true`), whoever called it (the timer, a background run, the foreground,
230
+ * the app), once the turn is in `inspect()`'s history. Interim: the public subscription for
231
+ * agent-initiated messages (F25 on #264: `onBackgroundMessage` with replay on open) replaces it.
232
+ * It runs on that delivery's thread. */
233
+ @CrocheBridgeApi
234
+ fun observeDeliveries(observer: ((JsonElement) -> Unit)?) { onDelivery = observer }
235
+ /** Hands the pending set to the OS scheduler again, through the Core, which reports a refusal
236
+ * as `schedule.degraded`. */
237
+ private fun resync() {
238
+ if (closed) return
239
+ try { core.reschedule() } catch (_: Exception) { /* reported as schedule.degraded */ }
240
+ }
241
+ /** The agent's pending scheduled notes: `{pending: [{id, at, note}], due}`. */
242
+ fun schedules(): JsonElement = run { it.schedules() }
243
+ fun flush(): JsonElement = run { it.flush(); null }
244
+ /** Forgets this user's conversation and memory and starts over (money and identity stay).
245
+ * The clear takes its place on the calling thread, as `send` does: behind a running turn,
246
+ * ahead of every send called after this. It then suspends until the clear is done; only that
247
+ * wait is on a thread of its own, so calling it from the main thread does not block it. */
248
+ suspend fun clearHistory() {
249
+ subscription?.let { it.clearHistory(); return }
250
+ if (closed) throw CrocheException("closed", "Runtime is closed")
251
+ val pending = try { core.beginClearHistory() } catch (error: Exception) { throw crocheError(error) }
252
+ offload {
253
+ try { pending.finish(); Unit } catch (error: Exception) { throw crocheError(error) } finally { pending.close() }
254
+ }
255
+ }
256
+ /** Runs a blocking Core call on a thread of its own and resumes the caller with its outcome. */
257
+ private suspend fun <T> offload(body: () -> T): T = suspendCoroutine { continuation ->
258
+ Thread({ OffloadSeam.starting?.invoke(); continuation.resumeWith(runCatching(body)) }, "croche-offload")
259
+ .apply { isDaemon = true }.start()
260
+ }
261
+ /** Asks Cloud to raise (or, `absolute`, set) this user's allowance within the project's
262
+ * ceilings. Pass `id` (e.g. the purchase id) to make a retry safe: Cloud applies it once.
263
+ * Called while another operation runs, it answers `{deferred: true}` at once instead (see
264
+ * [WriteResult]). */
265
+ fun adjustBudget(amount: Double, absolute: Boolean = false, id: String? = null): JsonElement =
266
+ run { it.adjustBudget(amount, absolute, id) }
267
+ /** Internal until `memory history` (B3): turns `from..to` from the turn archive, as
268
+ * `{"records":[...]}`; `archive_unavailable` when the storage keeps none. */
269
+ internal fun archiveRead(from: Long, to: Long): JsonElement = run { it.archiveRead(from.toULong(), to.toULong()) }
270
+ /** Internal: deletes archived turns, every one without a range. */
271
+ internal fun archiveClear(from: Long? = null, to: Long? = null) { run { it.archiveClear(from?.toULong(), to?.toULong()); null } }
272
+ fun inspect(): JsonElement = run { it.inspect() }
273
+ /** Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
274
+ * The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
275
+ * its place in the queue, so turns sent before it still offer the old list. A removed or
276
+ * changed command answers `withdrawn` once the swap applies. A handler given here also
277
+ * serves turns already queued under the same name. */
278
+ fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) = synchronized(toolChange) {
279
+ subscription?.let { it.setTools(tools, handlers); return@synchronized }
280
+ // One change at a time (Swift gets this from its actor): two threads' acceptances must
281
+ // install handlers in the order the Core accepted the lists.
282
+ if (closed) throw CrocheException("closed", "Runtime is closed")
283
+ // New names first: the Core cannot call them before it accepts the list. Replacements
284
+ // only after it accepts; a refusal removes what it staged, so every handler is as it was.
285
+ val stamp = host.stageTools(handlers)
286
+ try { run { it.setToolDeclarations(tools.toString()); null } }
287
+ catch (error: Exception) { host.unstageTools(handlers.keys, stamp); throw error }
288
+ host.acceptTools(handlers)
289
+ }
290
+ private val toolChange = Any()
291
+ /** The tool list the model is offered (metadata only). */
292
+ fun tools(): JsonArray = inspect().at("tools").let { if (it.isJsonArray) it.asJsonArray else JsonArray() }
293
+
294
+ /** Long-term memory: call it for a read-only snapshot, use its methods to manage it. */
295
+ val memory = Memory()
296
+ inner class Memory {
297
+ operator fun invoke(): JsonElement = inspect().at("memory")
298
+ /** AI-written facts with ids, turn/time stamps, refs and replacement links. */
299
+ fun list(): JsonArray = this@CrocheRuntime.run { it.memoryList() }.asJsonArray
300
+ /** `{deleted}`, or `{deferred: true}` (see [WriteResult]). */
301
+ fun delete(id: String): JsonObject = this@CrocheRuntime.run { it.memoryDelete(id) }.asJsonObject
302
+ /** Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
303
+ * `{deferred: true}` (see [WriteResult]). */
304
+ fun clear(): JsonObject = this@CrocheRuntime.run { it.memoryClear() }.asJsonObject
305
+ /** Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied,
306
+ * it carries the setting now in force. */
307
+ fun enabled(on: Boolean): WriteResult<Boolean> = WriteResult.of(this@CrocheRuntime.run { it.memorySetEnabled(on) }) { on }
308
+ /** Current and replaced AI-written facts: `{enabled, items}`, not the summary. */
309
+ fun export(): JsonObject = this@CrocheRuntime.run { it.memoryExport() }.asJsonObject
310
+ /** Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's). */
311
+ fun onChanged(listener: ((JsonElement) -> Unit)?) {
312
+ if (closed) throw CrocheException("closed", "Runtime is closed")
313
+ core.setMemoryObserver(listener?.let { EventHook(it) })
314
+ }
315
+ }
316
+
317
+ /** The app's knowledge documents, held by the Rust Core in memory (never stored: load them
318
+ * on each open). The model searches and reads them with the built-in `wiki` command;
319
+ * `list`, `read` and `search` here are that same view. */
320
+ val wiki = Wiki()
321
+ inner class Wiki {
322
+ private fun encode(docs: List<WikiDocument>): String = JsonArray().apply {
323
+ docs.forEach { doc ->
324
+ add(obj("path" to str(doc.path), "markdown" to str(doc.markdown)).apply {
325
+ doc.agents?.let { a -> add("agents", JsonArray().apply { a.forEach { add(it) } }) }
326
+ })
327
+ }
328
+ }.toString()
329
+ /** Replaces every document and answers what it installed: `{documents, bytes, digest}`.
330
+ * On an error nothing changes. */
331
+ fun set(docs: List<WikiDocument>): JsonObject = this@CrocheRuntime.run { it.wikiSet(encode(docs)) }.asJsonObject
332
+ /** `set`, without the digest. */
333
+ fun load(docs: List<WikiDocument>) { set(docs) }
334
+ /** This user's own documents (saved recipes, lesson notes): stored with their state (at
335
+ * most 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable
336
+ * when this returns. `clearHistory` keeps them. To share one with another character, put it to that character's
337
+ * Runtime too. Answers `{documents, bytes}`, or `{deferred: true}` (see [WriteResult]). */
338
+ fun putUser(docs: List<WikiDocument>): JsonObject = this@CrocheRuntime.run { it.wikiPutUser(encode(docs)) }.asJsonObject
339
+ /** Removes one of this user's own documents; whether it existed. */
340
+ fun removeUser(path: String): WriteResult<Boolean> =
341
+ WriteResult.of(this@CrocheRuntime.run { it.wikiRemoveUser(path) }) { r -> r.at("removed").let { it.isJsonPrimitive && it.asBoolean } }
342
+ /** Removes every one of this user's own documents; how many. */
343
+ fun clearUser(): WriteResult<Int> =
344
+ WriteResult.of(this@CrocheRuntime.run { it.wikiClearUser() }) { r -> r.at("cleared").let { if (it.isJsonPrimitive) it.asInt else 0 } }
345
+ /** Adds documents or replaces those with the same path, atomically. */
346
+ fun put(docs: List<WikiDocument>) { this@CrocheRuntime.run { it.wikiPut(encode(docs)); null } }
347
+ fun put(doc: WikiDocument) = put(listOf(doc))
348
+ /** Whether the document existed. */
349
+ fun remove(path: String): Boolean = this@CrocheRuntime.run { JsonPrimitive(it.wikiRemove(path)).toString() }.asBoolean
350
+ /** `[{path, title, summary?, characters, parts}]` under `folder` (every document when null). */
351
+ fun list(folder: String? = null): JsonArray = this@CrocheRuntime.run { it.wikiList(folder) }.asJsonArray
352
+ /** One part (1-based) of a document, `{path, title, part, parts, text}`; JsonNull when none. */
353
+ fun read(path: String, part: Int = 1): JsonElement = this@CrocheRuntime.run { it.wikiRead(path, part.coerceAtLeast(0).toUInt()) }
354
+ /** The best matches, best first: at most `limit` (and 5). */
355
+ fun search(query: String, limit: Int = 5): JsonArray = this@CrocheRuntime.run { it.wikiSearch(query, limit.coerceIn(0, 5).toUInt()) }.asJsonArray
356
+ }
357
+ /** Stops the running turn only: messages sent while it ran still go, together, as the next turn. */
358
+ fun cancel() { if (!closed) core.cancelTurn() }
359
+ /** Drops the messages held behind the running turn (each send ends `cancelled`); returns how many. */
360
+ fun clearQueued(): Int = if (closed) 0 else try { core.clearQueued().toInt() } catch (error: Exception) { throw crocheError(error) }
361
+ /** Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
362
+ * call upkeep has in flight is finished and settled first.
363
+ * The Core projection fence does not await buffered Flow/UI consumers.
364
+ * An app callback that waits for work on the closer's thread deadlocks under any
365
+ * wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
366
+ override fun close() {
367
+ if (closed) return
368
+ closed = true
369
+ subscription?.let { it.close(); return }
370
+ host.stop()
371
+ try { core.shutdown() } finally { core.destroy(); host.release() }
372
+ }
373
+ }
374
+
375
+ /** What a write (memory, this user's own documents, the allowance) answers: [Applied], with what
376
+ * it did, or [Deferred]: it was called while another operation ran, was accepted, and applies in
377
+ * call order when that operation ends. A message sent after the write sees it; one sent before
378
+ * does not. It is held in this process until then: closing first drops it, and a write that
379
+ * cannot apply then is reported as a `write.failed` debug event. */
380
+ sealed class WriteResult<out T> {
381
+ data class Applied<out T>(val value: T) : WriteResult<T>()
382
+ object Deferred : WriteResult<Nothing>() { override fun toString() = "Deferred" }
383
+ internal companion object {
384
+ fun <T> of(answer: JsonElement, applied: (JsonElement) -> T): WriteResult<T> =
385
+ if (answer.at("deferred").let { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean && it.asBoolean }) Deferred
386
+ else Applied(applied(answer))
387
+ }
388
+ }
389
+
390
+ /** A send [CrocheRuntime.beginSend] admitted: [result] blocks until its outcome, once. */
391
+ /** Croche's own tests: runs first on each offload thread, so a test can delay it the way the OS
392
+ * may (#346). Null in every app. */
393
+ internal object OffloadSeam { @Volatile var starting: (() -> Unit)? = null }
394
+ internal class PendingTurn(private val pending: PendingSend, private val token: CancelToken, private val done: () -> Unit) {
395
+ private val lock = Any()
396
+ private var ended = false
397
+ fun result(): JsonElement = try {
398
+ JsonParser.parseString(pending.wait())
399
+ } catch (error: Exception) { throw crocheError(error) } finally {
400
+ done()
401
+ synchronized(lock) { ended = true; pending.close(); token.close() }
402
+ }
403
+ /** Cancels this send only: held, it is dropped; running, its turn stops. */
404
+ fun cancel() = synchronized(lock) { if (!ended) token.cancel() }
405
+ }