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

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 (77) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +486 -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 +837 -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/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
  11. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  12. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  16. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +32 -0
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  18. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +415 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +379 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +227 -0
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  40. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  41. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  42. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  43. package/croche-react-native.podspec +28 -0
  44. package/ios/CrocheRuntimeBridge.swift +1008 -0
  45. package/ios/RNCrocheRuntime.mm +221 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  48. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  49. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +215 -0
  50. package/ios/vendor/CrocheRuntimeSDK/Host.swift +562 -0
  51. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  52. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  53. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
  54. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  55. package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
  56. package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
  57. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +558 -0
  58. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  59. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +453 -0
  60. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  61. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +345 -0
  62. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  63. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  64. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  65. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  66. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  67. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  68. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  69. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  70. package/package.json +40 -4
  71. package/scripts/vendor-native.sh +56 -0
  72. package/src/NativeCrocheRuntime.ts +162 -0
  73. package/src/index.ts +660 -0
  74. package/src/project-types.ts +35 -0
  75. package/src/project.ts +434 -0
  76. package/src/protocol.ts +28 -0
  77. package/src/types.ts +9 -0
@@ -0,0 +1,415 @@
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
+ val user: String? = null, val crocheUserId: String? = null,
19
+ val causedBy: List<String> = emptyList(), val origin: String = "app")
20
+ fun interface ToolHandler { fun execute(invocation: CommandInvocation, context: ToolContext): JsonElement }
21
+
22
+ /** One wiki document: a path such as `menu/stew.md` and its markdown (at most 64 KB; 2,000
23
+ * documents and 8 MB in all). The title is the first `#` heading; optional frontmatter may set
24
+ * `summary`, `keywords` and `agents` (only those agents see the document); `agents` given here
25
+ * overrides the frontmatter's. An agent's own path globs are config: `"wiki": {"include": [...],
26
+ * "exclude": [...]}`. */
27
+ data class WikiDocument(val path: String, val markdown: String, val agents: List<String>? = null) {
28
+ companion object {
29
+ private const val MAX_DOCUMENTS = 2000
30
+
31
+ /** The `.md` files under `dir`, paths relative to it with `/` (`menu/stew.md`), in name
32
+ * order. Subfolders are read; symbolic links and other files are skipped, as the other
33
+ * SDKs' loaders do. */
34
+ fun fromDirectory(dir: java.io.File): List<WikiDocument> {
35
+ val root = dir.toPath()
36
+ if (!java.nio.file.Files.isDirectory(root, java.nio.file.LinkOption.NOFOLLOW_LINKS))
37
+ throw CrocheException("invalid_wiki", "${dir.path}: not a folder")
38
+ return fromTree(
39
+ list = { path ->
40
+ val at = if (path.isEmpty()) root else root.resolve(path)
41
+ if (java.nio.file.Files.isDirectory(at, java.nio.file.LinkOption.NOFOLLOW_LINKS))
42
+ java.nio.file.Files.list(at).use { s -> s.map { it.fileName.toString() }.toList() }.toTypedArray()
43
+ else null
44
+ },
45
+ read = { path ->
46
+ val at = root.resolve(path)
47
+ 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
48
+ },
49
+ )
50
+ }
51
+
52
+ /** The documents in any tree the app can list and read, such as Android assets
53
+ * (`dev.croche.android.wikiFromAssets`). `list(path)` gives the names in a folder, or
54
+ * null or empty for a file; `read(path)` gives a file's text, or null to skip it. Paths
55
+ * are relative to the tree's root, with `/`; the root itself is `""`. */
56
+ fun fromTree(list: (String) -> Array<String>?, read: (String) -> String?): List<WikiDocument> {
57
+ val out = mutableListOf<WikiDocument>()
58
+ fun walk(prefix: String) {
59
+ for (name in (list(prefix) ?: emptyArray()).sorted()) {
60
+ val path = if (prefix.isEmpty()) name else "$prefix/$name"
61
+ val children = list(path)
62
+ if (!children.isNullOrEmpty()) walk(path)
63
+ else if (name.endsWith(".md")) {
64
+ val markdown = read(path) ?: continue
65
+ if (out.size >= MAX_DOCUMENTS) throw CrocheException("invalid_wiki", "The wiki holds at most $MAX_DOCUMENTS documents")
66
+ out.add(WikiDocument(path, markdown))
67
+ }
68
+ }
69
+ }
70
+ walk("")
71
+ return out
72
+ }
73
+ }
74
+ }
75
+
76
+ /** The Croche Runtime for Kotlin. The Rust Core (crates/croche-ffi) is the Runtime: it holds
77
+ * the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
78
+ * Kotlin types; `KotlinHost` performs what only the platform can (the PAL).
79
+ * Blocking: call from an IO executor/coroutine, never Android's main thread. Methods return
80
+ * detached JSON values. */
81
+ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, private val nativeHost: KotlinHost?,
82
+ private val subscription: StreamHub? = null, private val subscriptionPort: CoreStreamPort? = null) : AutoCloseable {
83
+ private val core: CoreRuntime get() = checkNotNull(nativeCore) { "Legacy API requires native Core" }
84
+ internal val host: KotlinHost get() = checkNotNull(nativeHost) { "Legacy host requires native Core" }
85
+ /** Fake-port host seam; create() installs NativeCoreStreamPort. */
86
+ internal constructor(port: CoreStreamPort) : this(null, null, StreamHub(port), port)
87
+ internal val boundStreamPort: CoreStreamPort get() = checkNotNull(subscriptionPort)
88
+ private fun subscriptions(): StreamHub = subscription ?: throw CrocheException(
89
+ "invalid_configuration", "Subscription binding is not installed")
90
+ suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt = subscriptions().send(input, options)
91
+ fun events(initialMessages: Int = 50): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(initialMessages)
92
+ fun events(after: Cursor): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(null, after)
93
+ suspend fun request(input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = null): RequestResult = subscriptions().request(input, options, wait)
94
+ suspend fun cancel(id: String) { subscriptions().cancel(id) }
95
+ suspend fun history(before: Long? = null, limit: Int) { subscriptions().history(before, limit) }
96
+ val logId: String get() = subscriptions().logId
97
+ internal val state: RuntimeEvent.State get() = subscriptions().state
98
+ @Volatile private var closed = false
99
+ internal val isClosed: Boolean get() = closed
100
+ internal fun openSubscription(initial: Int?, after: Cursor?) = subscriptions().openCollection(initial, after)
101
+ @Volatile private var onDelivery: ((JsonElement) -> Unit)? = null
102
+ companion object {
103
+ /** Test-only gate-10 probe; called on the thread that invokes each native stream-port call. */
104
+ @Volatile internal var offloadStarting: (() -> Unit)? = null
105
+
106
+ /** `secrets` keeps the Runtime credential apart from `storage`: KeystoreSecretStore on
107
+ * Android. `attestor` proves the genuine app to Cloud when the project requires it:
108
+ * PlayIntegrityAttestor on a device; null on an emulator or a host that cannot attest.
109
+ * Events may be delivered on an effect worker thread while a reply streams.
110
+ * `libraryName` names the native Runtime library (libcroche_ffi by default).
111
+ * `wiki` is the documents, set at open; this agent's path filter is the config's
112
+ * `"wiki": {"include": [...], "exclude": [...]}`.
113
+ * `onEvent` hears one `turn.started` per turn; a send carried into a running turn at a
114
+ * later model call is `{type:"turn.joined", turnId, inputIds}` (the ids newly carried).
115
+ * `onUsage` receives every paid call's cost (`{type:"usage", operationId, purpose, causedBy, instance,
116
+ * model, costUsd, costStatus, tokens?}`; `tokens` holds the reported counts, e.g. `prompt`,
117
+ * `cached`); `instance` is the named/generated instance key, or null for the main agent.
118
+ * `model` is the gateway-reported answering model (`modelSource: "response"`), or the
119
+ * request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
120
+ * present only when different. Reported cost is unchanged by a model substitution.
121
+ * At least once, from the start: open itself reports a call
122
+ * the process died during. It runs on a Runtime thread; do not call the Runtime from it.
123
+ * `scheduler` registers the agent's scheduled notes with the OS for when the app is not
124
+ * running: `WorkManagerScheduler` on Android; null on a JVM host, where an in-process
125
+ * timer delivers them while it runs and the next open delivers what fell due meanwhile.
126
+ * A scheduler whose name another open Runtime holds refuses this one (`scheduler_conflict`).
127
+ * `projectDirectory` is required on a plain JVM and refused on Android, which always uses
128
+ * app-private filesDir. It is a host option, never part of the Core config. */
129
+ fun create(config: JsonObject, storage: RuntimeStorage, secrets: RuntimeSecretStore,
130
+ attestor: RuntimeAttestor? = null, tools: Map<String, ToolHandler> = emptyMap(),
131
+ http: RuntimeHTTP = RuntimeHttpURLConnection(), onEvent: ((JsonElement) -> Unit)? = null,
132
+ onDebugEvent: ((JsonElement) -> Unit)? = null, libraryName: String = LIBRARY,
133
+ backgroundSync: Boolean = true, maintenanceIntervalMs: Long = 60_000,
134
+ wiki: List<WikiDocument>? = null, onUsage: ((JsonElement) -> Unit)? = null,
135
+ scheduler: RuntimeScheduler? = null, projectDirectory: File? = null): CrocheRuntime {
136
+ useLibrary(libraryName)
137
+ val bound = config.deepCopy().apply {
138
+ if (attestor != null) addProperty("attestationPlatform", attestor.platform) else add("attestationPlatform", JsonNull.INSTANCE)
139
+ }
140
+ // This host can feed deltas, so it asks for a stream unless the app opted out.
141
+ val streaming = config.at("streaming").let { if (it.isJsonPrimitive && it.asJsonPrimitive.isBoolean) it.asBoolean else true }
142
+ scheduler?.attach()
143
+ // From here the host's stop (close, or a failed open) detaches the scheduler.
144
+ val host = KotlinHost(storage, secrets, attestor, http, tools.toMap(), backgroundSync, scheduler, projectDirectory)
145
+ // The app chose the store, so the Runtime binds its identity to it (a custom storage key).
146
+ val options = RuntimeOpenOptions("croche.kotlin", streaming, backgroundSync, maintenanceInterval(maintenanceIntervalMs).toDouble())
147
+ val core = try { CoreRuntime.open(host, bound.toString(), options, onEvent?.let { EventHook(it) }, onUsage?.let { EventHook(it) }) }
148
+ catch (error: Exception) { host.release(); throw crocheError(error) }
149
+ if (onDebugEvent != null) try { core.setDebugObserver(EventHook(onDebugEvent), false) } catch (_: Exception) {}
150
+ val runtime = adopt(core, host)
151
+ if (wiki != null) try { runtime.wiki.set(wiki) } catch (error: Exception) { runtime.close(); throw error }
152
+ return runtime
153
+ }
154
+ /** Adopts a project-owned Runtime through the same production stream boundary as create. */
155
+ internal fun adopt(core: CoreRuntime, host: KotlinHost): CrocheRuntime {
156
+ val port = NativeCoreStreamPort(core, host)
157
+ val hub = try { StreamHub(port) } catch (error: Exception) { port.close(); throw crocheError(error) }
158
+ val runtime = CrocheRuntime(core, host, hub, port)
159
+ val weak = java.lang.ref.WeakReference(runtime)
160
+ host.deliver = { weak.get()?.deliverDue(); Unit }
161
+ host.attach(core)
162
+ return runtime
163
+ }
164
+ fun identity(config: JsonObject, libraryName: String = LIBRARY): JsonElement {
165
+ useLibrary(libraryName)
166
+ return try { JsonParser.parseString(dev.croche.ffi.identity(config.toString())) } catch (error: Exception) { throw crocheError(error) }
167
+ }
168
+ private const val LIBRARY = "croche_ffi"
169
+ private fun useLibrary(name: String) {
170
+ if (name != LIBRARY) System.setProperty("uniffi.component.croche_ffi.libraryOverride", name)
171
+ }
172
+ }
173
+ private fun run(body: (CoreRuntime) -> String?): JsonElement {
174
+ if (closed) throw CrocheException("closed", "Runtime is closed")
175
+ return try { body(core)?.let { JsonParser.parseString(it) } ?: JsonNull.INSTANCE } catch (error: Exception) { throw crocheError(error) }
176
+ }
177
+ /** Runs one turn. `cancellation` cancels this turn only, from any thread; one fired before
178
+ * the send starts throws `cancelled` here, and one fired while it runs is never missed.
179
+ * `responseFormat`: structured output, OpenAI's shape (`{"type":"json_schema",...}` or
180
+ * `{"type":"json_object"}`); the result's `output` is the reply as JSON the Core checked. */
181
+ fun send(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
182
+ /** For every image that does not name its own `"resolution"` (default standard). */
183
+ imageResolution: ImageResolution? = null): JsonElement =
184
+ beginSend(input, cancellation, responseFormat, imageResolution).result()
185
+ /** Admits a send at once on the calling thread, without waiting for its turn: sends are
186
+ * admitted in the order they are called (their place among held sends, and in a turn they
187
+ * share), whatever thread then waits. For a host that hops threads after (React Native). */
188
+ internal fun beginSend(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
189
+ imageResolution: ImageResolution? = null): PendingTurn {
190
+ cancellation.check()
191
+ if (closed) throw CrocheException("closed", "Runtime is closed")
192
+ // Standard images are re-encoded here, before admission, so sends keep their order.
193
+ val prepared = CrocheImages.prepareInput(input, imageResolution)
194
+ val token = CancelToken()
195
+ val listener = cancellation.observe { token.cancel() }
196
+ val pending = try { core.beginSend(prepared.toString(), token, responseFormat?.toString()) }
197
+ catch (error: Exception) { cancellation.remove(listener); token.close(); throw crocheError(error) }
198
+ return PendingTurn(pending, token) { cancellation.remove(listener) }
199
+ }
200
+ fun sync(): JsonElement = run { it.sync(); null }
201
+ /**
202
+ * One round of background upkeep: deliver the outbox of call reports, then sync balances,
203
+ * policy and the model key. The Core does work only when some is due and backs off after
204
+ * a failure. It runs by itself after each turn and on a timer (backgroundSync); call it
205
+ * when the app returns to the foreground. It never delays a turn: a send takes over while
206
+ * it waits on Cloud. Never throws; the result says what happened. Blocking.
207
+ */
208
+ fun maintain(force: Boolean = false): JsonElement =
209
+ try { run { it.maintain(force) } } catch (_: Exception) { obj("ran" to bool(false)) }
210
+ /** Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
211
+ * is (no turn, no cost) or one is already being delivered, else `{ran, ids, delivered, turn}`.
212
+ * Never before a note's time. Call it at every foreground. Blocking.
213
+ *
214
+ * `cancellation` cancels this delivery only, from any thread: waiting behind another turn, it
215
+ * leaves without running; running, its turn stops. Either way its notes stay pending. Fired
216
+ * after the delivery ended, it does nothing: never another turn (`cancel()` stops whatever
217
+ * turn runs).
218
+ *
219
+ * Afterwards the pending set is handed to the OS scheduler again (a refusal is reported as
220
+ * `schedule.degraded`): the OS spends a request when it runs it, and a delivery cut short
221
+ * leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
222
+ * ends, and registering its past-due note again would only start another run at once. A
223
+ * failed delivery that answers `retryAt` waits until then. */
224
+ fun deliverDue(cancellation: RuntimeCancellation = RuntimeCancellation()): JsonElement {
225
+ host.attempted()
226
+ val token = CancelToken()
227
+ val listener = cancellation.observe { token.cancel() }
228
+ val result = try { run { it.deliverDue(token) } }
229
+ catch (error: Exception) { resync(); throw error }
230
+ finally { cancellation.remove(listener); token.close() }
231
+ if (result.at("inFlight").let { it.isJsonPrimitive && it.asBoolean }) return result
232
+ retryAt(result.at("retryAt"))?.let { host.retryAfter(it) }
233
+ resync()
234
+ if (result.at("ran").let { it.isJsonPrimitive && it.asBoolean }) onDelivery?.let { notify -> try { notify(result) } catch (_: Exception) {} }
235
+ return result
236
+ }
237
+ /** INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
238
+ * module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
239
+ * delivery turn (`ran: true`), whoever called it (the timer, a background run, the foreground,
240
+ * the app), once the turn is in `inspect()`'s history. Interim: the public subscription for
241
+ * agent-initiated messages (F25 on #264: `onBackgroundMessage` with replay on open) replaces it.
242
+ * It runs on that delivery's thread. */
243
+ @CrocheBridgeApi
244
+ fun observeDeliveries(observer: ((JsonElement) -> Unit)?) { onDelivery = observer }
245
+ /** Hands the pending set to the OS scheduler again, through the Core, which reports a refusal
246
+ * as `schedule.degraded`. */
247
+ private fun resync() {
248
+ if (closed) return
249
+ try { core.reschedule() } catch (_: Exception) { /* reported as schedule.degraded */ }
250
+ }
251
+ /** The agent's pending scheduled notes: `{pending: [{id, at, note}], due}`. */
252
+ fun schedules(): JsonElement = run { it.schedules() }
253
+ fun flush(): JsonElement = run { it.flush(); null }
254
+ /** Forgets this user's conversation and memory and starts over (money and identity stay).
255
+ * The clear takes its place on the calling thread, as `send` does: behind a running turn,
256
+ * ahead of every send called after this. It then suspends until the clear is done; only that
257
+ * wait is on a thread of its own, so calling it from the main thread does not block it. */
258
+ suspend fun clearHistory() {
259
+ subscription?.let { it.clearHistory(); return }
260
+ if (closed) throw CrocheException("closed", "Runtime is closed")
261
+ val pending = try { core.beginClearHistory() } catch (error: Exception) { throw crocheError(error) }
262
+ offload {
263
+ try { pending.finish(); Unit } catch (error: Exception) { throw crocheError(error) } finally { pending.close() }
264
+ }
265
+ }
266
+ /** Runs a blocking Core call on a thread of its own and resumes the caller with its outcome. */
267
+ private suspend fun <T> offload(body: () -> T): T = suspendCoroutine { continuation ->
268
+ Thread({ OffloadSeam.starting?.invoke(); continuation.resumeWith(runCatching(body)) }, "croche-offload")
269
+ .apply { isDaemon = true }.start()
270
+ }
271
+ /** Asks Cloud to raise (or, `absolute`, set) this user's allowance within the project's
272
+ * ceilings. Pass `id` (e.g. the purchase id) to make a retry safe: Cloud applies it once.
273
+ * Called while another operation runs, it answers `{deferred: true}` at once instead (see
274
+ * [WriteResult]). */
275
+ fun adjustBudget(amount: Double, absolute: Boolean = false, id: String? = null): JsonElement =
276
+ run { it.adjustBudget(amount, absolute, id) }
277
+ /** Internal until `memory history` (B3): turns `from..to` from the turn archive, as
278
+ * `{"records":[...]}`; `archive_unavailable` when the storage keeps none. */
279
+ internal fun archiveRead(from: Long, to: Long): JsonElement = run { it.archiveRead(from.toULong(), to.toULong()) }
280
+ /** Internal: deletes archived turns, every one without a range. */
281
+ internal fun archiveClear(from: Long? = null, to: Long? = null) { run { it.archiveClear(from?.toULong(), to?.toULong()); null } }
282
+ fun inspect(): JsonElement = run { it.inspect() }
283
+ /** Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
284
+ * The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
285
+ * its place in the queue, so turns sent before it still offer the old list. A removed or
286
+ * changed command answers `withdrawn` once the swap applies. A handler given here also
287
+ * serves turns already queued under the same name. */
288
+ fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) = synchronized(toolChange) {
289
+ subscription?.let { it.setTools(tools, handlers); return@synchronized }
290
+ // One change at a time (Swift gets this from its actor): two threads' acceptances must
291
+ // install handlers in the order the Core accepted the lists.
292
+ if (closed) throw CrocheException("closed", "Runtime is closed")
293
+ // New names first: the Core cannot call them before it accepts the list. Replacements
294
+ // only after it accepts; a refusal removes what it staged, so every handler is as it was.
295
+ val stamp = host.stageTools(handlers)
296
+ try { run { it.setToolDeclarations(tools.toString()); null } }
297
+ catch (error: Exception) { host.unstageTools(handlers.keys, stamp); throw error }
298
+ host.acceptTools(handlers)
299
+ }
300
+ private val toolChange = Any()
301
+ /** The tool list the model is offered (metadata only). */
302
+ fun tools(): JsonArray = inspect().at("tools").let { if (it.isJsonArray) it.asJsonArray else JsonArray() }
303
+
304
+ /** Long-term memory: call it for a read-only snapshot, use its methods to manage it. */
305
+ val memory = Memory()
306
+ inner class Memory {
307
+ operator fun invoke(): JsonElement = inspect().at("memory")
308
+ /** AI-written facts with ids, turn/time stamps, refs and replacement links. */
309
+ fun list(): JsonArray = this@CrocheRuntime.run { it.memoryList() }.asJsonArray
310
+ /** `{deleted}`, or `{deferred: true}` (see [WriteResult]). */
311
+ fun delete(id: String): JsonObject = this@CrocheRuntime.run { it.memoryDelete(id) }.asJsonObject
312
+ /** Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
313
+ * `{deferred: true}` (see [WriteResult]). */
314
+ fun clear(): JsonObject = this@CrocheRuntime.run { it.memoryClear() }.asJsonObject
315
+ /** Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied,
316
+ * it carries the setting now in force. */
317
+ fun enabled(on: Boolean): WriteResult<Boolean> = WriteResult.of(this@CrocheRuntime.run { it.memorySetEnabled(on) }) { on }
318
+ /** Current and replaced AI-written facts: `{enabled, items}`, not the summary. */
319
+ fun export(): JsonObject = this@CrocheRuntime.run { it.memoryExport() }.asJsonObject
320
+ /** Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's). */
321
+ fun onChanged(listener: ((JsonElement) -> Unit)?) {
322
+ if (closed) throw CrocheException("closed", "Runtime is closed")
323
+ core.setMemoryObserver(listener?.let { EventHook(it) })
324
+ }
325
+ }
326
+
327
+ /** The app's knowledge documents, held by the Rust Core in memory (never stored: load them
328
+ * on each open). The model searches and reads them with the built-in `wiki` command;
329
+ * `list`, `read` and `search` here are that same view. */
330
+ val wiki = Wiki()
331
+ inner class Wiki {
332
+ private fun encode(docs: List<WikiDocument>): String = JsonArray().apply {
333
+ docs.forEach { doc ->
334
+ add(obj("path" to str(doc.path), "markdown" to str(doc.markdown)).apply {
335
+ doc.agents?.let { a -> add("agents", JsonArray().apply { a.forEach { add(it) } }) }
336
+ })
337
+ }
338
+ }.toString()
339
+ /** Replaces every document and answers what it installed: `{documents, bytes, digest}`.
340
+ * On an error nothing changes. */
341
+ fun set(docs: List<WikiDocument>): JsonObject = this@CrocheRuntime.run { it.wikiSet(encode(docs)) }.asJsonObject
342
+ /** `set`, without the digest. */
343
+ fun load(docs: List<WikiDocument>) { set(docs) }
344
+ /** This user's own documents (saved recipes, lesson notes): stored with their state (at
345
+ * most 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable
346
+ * when this returns. `clearHistory` keeps them. To share one with another character, put it to that character's
347
+ * Runtime too. Answers `{documents, bytes}`, or `{deferred: true}` (see [WriteResult]). */
348
+ fun putUser(docs: List<WikiDocument>): JsonObject = this@CrocheRuntime.run { it.wikiPutUser(encode(docs)) }.asJsonObject
349
+ /** Removes one of this user's own documents; whether it existed. */
350
+ fun removeUser(path: String): WriteResult<Boolean> =
351
+ WriteResult.of(this@CrocheRuntime.run { it.wikiRemoveUser(path) }) { r -> r.at("removed").let { it.isJsonPrimitive && it.asBoolean } }
352
+ /** Removes every one of this user's own documents; how many. */
353
+ fun clearUser(): WriteResult<Int> =
354
+ WriteResult.of(this@CrocheRuntime.run { it.wikiClearUser() }) { r -> r.at("cleared").let { if (it.isJsonPrimitive) it.asInt else 0 } }
355
+ /** Adds documents or replaces those with the same path, atomically. */
356
+ fun put(docs: List<WikiDocument>) { this@CrocheRuntime.run { it.wikiPut(encode(docs)); null } }
357
+ fun put(doc: WikiDocument) = put(listOf(doc))
358
+ /** Whether the document existed. */
359
+ fun remove(path: String): Boolean = this@CrocheRuntime.run { JsonPrimitive(it.wikiRemove(path)).toString() }.asBoolean
360
+ /** `[{path, title, summary?, characters, parts}]` under `folder` (every document when null). */
361
+ fun list(folder: String? = null): JsonArray = this@CrocheRuntime.run { it.wikiList(folder) }.asJsonArray
362
+ /** One part (1-based) of a document, `{path, title, part, parts, text}`; JsonNull when none. */
363
+ fun read(path: String, part: Int = 1): JsonElement = this@CrocheRuntime.run { it.wikiRead(path, part.coerceAtLeast(0).toUInt()) }
364
+ /** The best matches, best first: at most `limit` (and 5). */
365
+ fun search(query: String, limit: Int = 5): JsonArray = this@CrocheRuntime.run { it.wikiSearch(query, limit.coerceIn(0, 5).toUInt()) }.asJsonArray
366
+ }
367
+ /** Stops the running turn only: messages sent while it ran still go, together, as the next turn. */
368
+ fun cancel() { if (!closed) core.cancelTurn() }
369
+ /** Drops the messages held behind the running turn (each send ends `cancelled`); returns how many. */
370
+ fun clearQueued(): Int = if (closed) 0 else try { core.clearQueued().toInt() } catch (error: Exception) { throw crocheError(error) }
371
+ /** Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
372
+ * call upkeep has in flight is finished and settled first.
373
+ * The Core projection fence does not await buffered Flow/UI consumers.
374
+ * An app callback that waits for work on the closer's thread deadlocks under any
375
+ * wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
376
+ override fun close() {
377
+ if (closed) return
378
+ closed = true
379
+ subscription?.let { it.close(); return }
380
+ host.stop()
381
+ try { core.shutdown() } finally { core.destroy(); host.release() }
382
+ }
383
+ }
384
+
385
+ /** What a write (memory, this user's own documents, the allowance) answers: [Applied], with what
386
+ * it did, or [Deferred]: it was called while another operation ran, was accepted, and applies in
387
+ * call order when that operation ends. A message sent after the write sees it; one sent before
388
+ * does not. It is held in this process until then: closing first drops it, and a write that
389
+ * cannot apply then is reported as a `write.failed` debug event. */
390
+ sealed class WriteResult<out T> {
391
+ data class Applied<out T>(val value: T) : WriteResult<T>()
392
+ object Deferred : WriteResult<Nothing>() { override fun toString() = "Deferred" }
393
+ internal companion object {
394
+ fun <T> of(answer: JsonElement, applied: (JsonElement) -> T): WriteResult<T> =
395
+ if (answer.at("deferred").let { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean && it.asBoolean }) Deferred
396
+ else Applied(applied(answer))
397
+ }
398
+ }
399
+
400
+ /** A send [CrocheRuntime.beginSend] admitted: [result] blocks until its outcome, once. */
401
+ /** Croche's own tests: runs first on each offload thread, so a test can delay it the way the OS
402
+ * may (#346). Null in every app. */
403
+ internal object OffloadSeam { @Volatile var starting: (() -> Unit)? = null }
404
+ internal class PendingTurn(private val pending: PendingSend, private val token: CancelToken, private val done: () -> Unit) {
405
+ private val lock = Any()
406
+ private var ended = false
407
+ fun result(): JsonElement = try {
408
+ JsonParser.parseString(pending.wait())
409
+ } catch (error: Exception) { throw crocheError(error) } finally {
410
+ done()
411
+ synchronized(lock) { ended = true; pending.close(); token.close() }
412
+ }
413
+ /** Cancels this send only: held, it is dropped; running, its turn stops. */
414
+ fun cancel() = synchronized(lock) { if (!ended) token.cancel() }
415
+ }
@@ -0,0 +1,195 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.HttpSink
5
+ import dev.croche.ffi.PalHeader
6
+ import dev.croche.ffi.PalHttpRequest
7
+ import java.io.ByteArrayOutputStream
8
+ import java.net.CookieHandler
9
+ import java.net.HttpURLConnection
10
+ import java.net.URI
11
+ import java.util.concurrent.*
12
+ import java.util.concurrent.atomic.AtomicBoolean
13
+
14
+ /** Handlers must check this before committing an effect. Cancellation cannot undo a commit. */
15
+ class RuntimeCancellation {
16
+ private val cancelled = AtomicBoolean(false)
17
+ private val callbacks = ConcurrentHashMap<Any, () -> Unit>()
18
+ val isCancelled: Boolean get() = cancelled.get()
19
+ fun check() { if (isCancelled) throw CrocheException("cancelled", "The operation was cancelled") }
20
+ fun cancel() { if (cancelled.compareAndSet(false, true)) { callbacks.values.forEach { it() }; callbacks.clear() } }
21
+ internal fun observe(callback: () -> Unit): Any {
22
+ val key = Any(); callbacks[key] = callback
23
+ if (isCancelled && callbacks.remove(key) != null) callback()
24
+ return key
25
+ }
26
+ internal fun remove(key: Any) { callbacks.remove(key) }
27
+ }
28
+
29
+ /** A whole-request transport an app can supply instead of the default. `onDelta` receives each
30
+ * server-sent event's data while a streamed response arrives, in order, on the calling thread;
31
+ * the Rust Core assembles them. A transport that cannot stream never calls it. */
32
+ fun interface RuntimeHTTP { fun execute(effect: JsonObject, cancellation: RuntimeCancellation, onDelta: (String) -> Unit): JsonObject }
33
+
34
+ private const val MAX_RESPONSE_BYTES = 2 * 1024 * 1024
35
+
36
+ /** Where `stream` delivers a response: the Runtime's sink, or a test's recorder. */
37
+ internal interface ResponseSink {
38
+ fun head(status: Int, headers: List<PalHeader>)
39
+ /** False: the receiver wants no more, so reading stops. */
40
+ fun chunk(bytes: ByteArray): Boolean
41
+ }
42
+
43
+ /** Android-safe HTTP implementation. No java.net.http dependency, redirect following or
44
+ * response cache. A process-global CookieHandler is refused, because HttpURLConnection
45
+ * cannot disable it reliably per request. Inject RuntimeHTTP if your app requires one.
46
+ * The Runtime uses it as its PAL transport: the response goes to the Rust Core as it arrives,
47
+ * and the Core frames, bounds and interprets it. `execute` answers whole requests (2MiB). */
48
+ class RuntimeHttpURLConnection : RuntimeHTTP {
49
+ override fun execute(effect: JsonObject, cancellation: RuntimeCancellation, onDelta: (String) -> Unit): JsonObject {
50
+ val headers = effect.at("headers").asJsonObject.entrySet().map { (name, value) -> name to value.asString }
51
+ val body = effect.at("body").toString().toByteArray(Charsets.UTF_8)
52
+ return request(effect.at("url").text(), effect.at("method").text(), headers, body, effect.at("timeoutMs").asInt, cancellation) { connection, status ->
53
+ val fields = JsonObject()
54
+ connection.headerFields.forEach { (key, values) -> if (key != null) fields.addProperty(key, values.joinToString(", ")) }
55
+ if (connection.contentLengthLong > MAX_RESPONSE_BYTES) throw CrocheException("invalid_response", "HTTP response exceeds 2MiB")
56
+ val data = ByteArrayOutputStream()
57
+ read(connection, status, cancellation) { buffer, count ->
58
+ if (data.size() + count > MAX_RESPONSE_BYTES) throw CrocheException("invalid_response", "HTTP response exceeds 2MiB")
59
+ data.write(buffer, 0, count); true
60
+ }
61
+ val result = obj("status" to num(status), "headers" to fields)
62
+ val raw = data.toString("UTF-8")
63
+ try { result.add("body", JsonParser.parseString(raw)) } catch (_: Exception) { result.addProperty("raw", raw) }
64
+ result
65
+ }
66
+ }
67
+ /** The PAL transport: head, then each piece of body into the Runtime's sink as it arrives. */
68
+ internal fun stream(request: PalHttpRequest, sink: HttpSink, cancellation: RuntimeCancellation) =
69
+ stream(request, object : ResponseSink {
70
+ override fun head(status: Int, headers: List<PalHeader>) = sink.head(status.toUShort(), headers)
71
+ override fun chunk(bytes: ByteArray) = sink.chunk(bytes)
72
+ }, cancellation)
73
+ internal fun stream(request: PalHttpRequest, sink: ResponseSink, cancellation: RuntimeCancellation) {
74
+ request(request.url, request.method, request.headers.map { it.name to it.value }, request.body.toByteArray(Charsets.UTF_8),
75
+ request.timeoutMs.coerceAtMost(Int.MAX_VALUE.toULong()).toInt(), cancellation) { connection, status ->
76
+ val fields = connection.headerFields.mapNotNull { (key, values) -> key?.let { PalHeader(it, values.joinToString(", ")) } }
77
+ sink.head(status, fields)
78
+ // The Runtime wants no more (a bound was exceeded): stop reading.
79
+ read(connection, status, cancellation) { buffer, count -> sink.chunk(buffer.copyOf(count)) }
80
+ }
81
+ }
82
+ private fun <T> request(url: String, method: String, headers: List<Pair<String, String>>, body: ByteArray, timeoutMs: Int,
83
+ cancellation: RuntimeCancellation, respond: (HttpURLConnection, Int) -> T): T {
84
+ cancellation.check()
85
+ if (CookieHandler.getDefault() != null) throw CrocheException("network_error", "Default transport requires no process CookieHandler")
86
+ val connection = URI(url).toURL().openConnection() as HttpURLConnection
87
+ if (CookieHandler.getDefault() != null) { connection.disconnect(); throw CrocheException("network_error", "Process CookieHandler changed during request creation") }
88
+ val listener = cancellation.observe { connection.disconnect() }
89
+ try {
90
+ connection.instanceFollowRedirects = false
91
+ connection.useCaches = false
92
+ connection.requestMethod = method
93
+ val timeout = timeoutMs.coerceIn(1, 180000)
94
+ connection.connectTimeout = timeout; connection.readTimeout = timeout
95
+ headers.forEach { (name, value) -> connection.setRequestProperty(name, value) }
96
+ connection.setRequestProperty("Cookie", ""); connection.setRequestProperty("Cookie2", "")
97
+ if (connection.requestMethod !in listOf("GET", "HEAD")) {
98
+ connection.doOutput = true
99
+ connection.setFixedLengthStreamingMode(body.size)
100
+ connection.outputStream.use { it.write(body) }
101
+ }
102
+ cancellation.check()
103
+ return respond(connection, connection.responseCode)
104
+ } finally { cancellation.remove(listener); connection.disconnect() }
105
+ }
106
+ private fun read(connection: HttpURLConnection, status: Int, cancellation: RuntimeCancellation, accept: (ByteArray, Int) -> Boolean) {
107
+ val stream = if (status >= 400) connection.errorStream else connection.inputStream
108
+ stream?.use { input ->
109
+ val buffer = ByteArray(8192)
110
+ while (true) {
111
+ cancellation.check()
112
+ val count = input.read(buffer); if (count < 0) break
113
+ if (count > 0 && !accept(buffer, count)) break
114
+ }
115
+ }
116
+ cancellation.check()
117
+ }
118
+ }
119
+
120
+ internal class EffectExecutor : AutoCloseable {
121
+ // Bounded concurrency: an uncooperative handler cannot spawn unlimited abandoned workers.
122
+ private val pool = ThreadPoolExecutor(0, 8, 30, TimeUnit.SECONDS, SynchronousQueue(),
123
+ ThreadFactory { task -> Thread(task, "croche-effect").apply { isDaemon = true } })
124
+ /** `timeoutMs` null: no deadline here, only `cancellation`. Either way this returns once it
125
+ * fires, whether or not the block stops (app commands: `ToolExecutor`). */
126
+ fun run(timeoutMs: Long?, cancellation: RuntimeCancellation, block: (RuntimeCancellation) -> JsonElement): JsonElement {
127
+ cancellation.check()
128
+ val local = RuntimeCancellation()
129
+ val future = try { pool.submit(Callable { local.check(); block(local).also { local.check() } }) }
130
+ catch (_: RejectedExecutionException) { throw CrocheException("effect_failed", "Host effect workers are occupied") }
131
+ val listener = cancellation.observe { local.cancel(); future.cancel(true) }
132
+ try { return if (timeoutMs == null) future.get() else future.get(timeoutMs.coerceAtLeast(1), TimeUnit.MILLISECONDS) }
133
+ catch (_: TimeoutException) { local.cancel(); future.cancel(true); throw CrocheException("timeout", "The effect deadline expired") }
134
+ catch (_: CancellationException) { throw CrocheException("cancelled", "The operation was cancelled") }
135
+ catch (_: InterruptedException) {
136
+ local.cancel(); future.cancel(true)
137
+ // Clear interruption so the following required durable write is not aborted.
138
+ Thread.interrupted(); throw CrocheException("cancelled", "The operation was cancelled")
139
+ }
140
+ catch (error: ExecutionException) { throw (error.cause as? Exception ?: CrocheException("effect_failed", "The host effect failed")) }
141
+ finally { cancellation.remove(listener) }
142
+ }
143
+ override fun close() { pool.shutdownNow() }
144
+ }
145
+
146
+ /** The app's commands (H1), apart from HTTP and storage so stuck handlers never hold their
147
+ * workers. One per Runtime, like the Runtime's command slots (`HOST_TOOL_SLOTS`, 8): the Runtime
148
+ * starts no more than that at once, and a slot is free again only when `run` returns, which is
149
+ * when the handler returns. A cancel (the turn's, or the command's deadline) reaches the handler
150
+ * through its cancellation and an interrupt; `run` then still waits for it, on a worker the
151
+ * Runtime has already stopped waiting for. */
152
+ internal class ToolExecutor : AutoCloseable {
153
+ private val pool = ThreadPoolExecutor(8, 8, 30, TimeUnit.SECONDS, LinkedBlockingQueue(),
154
+ ThreadFactory { task -> Thread(task, "croche-tool").apply { isDaemon = true } }).apply { allowCoreThreadTimeOut(true) }
155
+ fun run(cancellation: RuntimeCancellation, block: (RuntimeCancellation) -> JsonElement): JsonElement {
156
+ cancellation.check()
157
+ val local = RuntimeCancellation()
158
+ val lock = Any()
159
+ var runner: Thread? = null
160
+ val future = try {
161
+ pool.submit(Callable {
162
+ synchronized(lock) { runner = Thread.currentThread() }
163
+ try { local.check(); block(local).also { local.check() } }
164
+ finally { synchronized(lock) { runner = null }; Thread.interrupted() }
165
+ })
166
+ } catch (_: RejectedExecutionException) { throw CrocheException("host_unresponsive", "The application's command workers are closed") }
167
+ val listener = cancellation.observe { local.cancel(); synchronized(lock) { runner?.interrupt() } }
168
+ try {
169
+ while (true) {
170
+ try { return future.get() }
171
+ catch (_: InterruptedException) { local.cancel(); synchronized(lock) { runner?.interrupt() } }
172
+ }
173
+ }
174
+ catch (error: ExecutionException) {
175
+ if (local.isCancelled) throw CrocheException("cancelled", "The operation was cancelled")
176
+ throw handlerError(error.cause)
177
+ }
178
+ finally { cancellation.remove(listener) }
179
+ }
180
+ override fun close() { pool.shutdownNow() }
181
+ }
182
+
183
+ /** Thrown by an SDK bridge's own handler (React Native, compiled into this module) when it has
184
+ * no handler of its own to run, before anything ran. Internal: app code cannot claim it. */
185
+ internal class ToolNotDispatched : RuntimeException("No handler ran for this tool")
186
+
187
+ /** An error from a tool handler. "Nothing ran" is the host's to say, never a handler's: a
188
+ * handler that throws `tool_not_dispatched` or `host_unresponsive` (perhaps passing on another
189
+ * Runtime's error) may already have had its effect, so the call fails as `tool_failed`. */
190
+ internal fun handlerError(error: Throwable?): Exception = when {
191
+ error is ToolNotDispatched -> CrocheException("tool_not_dispatched", "No handler ran for this tool")
192
+ error is CrocheException && error.code in setOf("tool_not_dispatched", "host_unresponsive") -> CrocheException("tool_failed", error.message)
193
+ error is Exception -> error
194
+ else -> CrocheException("effect_failed", "The host effect failed")
195
+ }