@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,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
+ }
@@ -0,0 +1,368 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.*
5
+ import java.lang.ref.WeakReference
6
+ import java.util.Collections
7
+ import java.util.TimeZone
8
+ import java.util.UUID
9
+ import java.util.WeakHashMap
10
+ import java.util.concurrent.Executors
11
+ import java.util.concurrent.ScheduledExecutorService
12
+ import java.util.concurrent.ScheduledFuture
13
+ import java.util.concurrent.TimeUnit
14
+ import java.util.concurrent.atomic.AtomicBoolean
15
+
16
+ // The Kotlin PAL: what only the platform can do. The Rust Runtime (crates/croche-ffi) decides
17
+ // everything else, including SSE framing, response bounds, persistence order, upkeep and
18
+ // cancellation rules. Its calls into this host block a background thread.
19
+
20
+ /** The code the Runtime reads as "nothing ran" (croche_core::NOT_DISPATCHED). */
21
+ private const val NOT_DISPATCHED = "tool_not_dispatched"
22
+
23
+ internal fun failure(error: Throwable): FfiException = when (error) {
24
+ is FfiException -> error
25
+ is CrocheException -> FfiException.Failure(error.code, error.message)
26
+ else -> FfiException.Failure("host_error", "The host operation failed")
27
+ }
28
+ /** `request_timeout.SocketTimeoutException`, `network_error.SocketException`, …: a call code and the class. */
29
+ internal fun transportCode(error: java.io.IOException): String {
30
+ val base = if (error is java.net.SocketTimeoutException) "request_timeout" else "network_error"
31
+ val name = error.javaClass.simpleName.filter { it.isLetterOrDigit() || it == '_' }.take(60)
32
+ return if (name.isEmpty()) base else "$base.$name"
33
+ }
34
+ internal fun crocheError(error: Throwable): CrocheException = when (error) {
35
+ is CrocheException -> error
36
+ is FfiException.Failure -> CrocheException(error.code, error.detail)
37
+ else -> CrocheException("host_error", "The host operation failed")
38
+ }
39
+
40
+ /** The Runtime calls this host on its own worker threads, which JNA attaches for the length of
41
+ * one callback. A callback that calls back into the Runtime (a sink fed on the callback's stack,
42
+ * an observer that inspects) nests a second callback on that thread, and JNA's default detaches
43
+ * after the inner one while the outer one is still running: "JNA: could not detach thread".
44
+ * Keeping the thread attached until it exits avoids that; the worker threads are short-lived. */
45
+ internal fun keepAttached() = com.sun.jna.Native.detach(false)
46
+
47
+ /** A Runtime cancellation, tied to the token the Runtime handed this effect. */
48
+ private fun signal(token: CancelToken): RuntimeCancellation = RuntimeCancellation().also { signal ->
49
+ token.onCancel(object : CancelCallback { override fun cancelled() = signal.cancel() })
50
+ }
51
+
52
+ internal class EventHook(private val callback: (JsonElement) -> Unit) : EventListener {
53
+ override fun onEvent(event: String) {
54
+ keepAttached()
55
+ val value = try { JsonParser.parseString(event) } catch (_: Exception) { return }
56
+ try { callback(value) } catch (_: Exception) {}
57
+ }
58
+ }
59
+
60
+ /** The `at`s (epoch ms) of a schedule set `[{id, at}]`. */
61
+ internal fun times(entries: JsonElement): List<Long> =
62
+ (if (entries.isJsonArray) entries.asJsonArray else JsonArray()).mapNotNull { entry ->
63
+ try { java.time.Instant.parse(entry.at("at").text()).toEpochMilli() } catch (_: Exception) { null }
64
+ }
65
+
66
+ /** A delivery's `retryAt` (epoch ms, or an ISO time), or null. */
67
+ internal fun retryAt(value: JsonElement): Long? = try {
68
+ when {
69
+ !value.isJsonPrimitive -> null
70
+ value.asJsonPrimitive.isNumber -> value.asDouble.toLong()
71
+ else -> java.time.Instant.parse(value.asString).toEpochMilli()
72
+ }
73
+ } catch (_: Exception) { null }
74
+
75
+ /** Each store object is one store; two Runtimes on it in a process are refused. */
76
+ private val identities: MutableMap<Any, String> = Collections.synchronizedMap(WeakHashMap())
77
+
78
+ /** The Kotlin PAL handed to the Rust Runtime. */
79
+ internal class KotlinHost(
80
+ private val storage: RuntimeStorage, private val secretStore: RuntimeSecretStore,
81
+ private val attestor: RuntimeAttestor?, private val transport: RuntimeHTTP,
82
+ tools: Map<String, ToolHandler>, private val background: Boolean,
83
+ private val osScheduler: RuntimeScheduler? = null,
84
+ projectDirectory: java.io.File? = null,
85
+ defaultDirectory: () -> java.io.File? = ::defaultProjectDirectory
86
+ ) : HostPal {
87
+ private val projectRecords = ProjectRecords { projectRecordDirectory(projectDirectory, defaultDirectory()) }
88
+ internal var beforeProjectLock: (() -> Unit)? = null
89
+ internal var afterProjectRead: ((String?) -> Unit)? = null
90
+ internal var beforeProjectWrite: (() -> Unit)? = null
91
+ // Accepted tools are never removed: a tool change waits its turn in the Core's queue, and turns queued before it
92
+ // still run the old list. The Core alone decides which commands a turn may call.
93
+ @Volatile private var handlers: Map<String, ToolHandler> = tools
94
+ private val staged = HashMap<String, Int>() // names whose only handler is from a call in flight
95
+ private var stamp = 0
96
+ /** Stages the handlers for names with none yet, or with one only staged by a call still in
97
+ * flight (a later call wins). Returns the stamp that [unstageTools] needs. */
98
+ fun stageTools(tools: Map<String, ToolHandler>): Int = synchronized(lock) {
99
+ stamp += 1
100
+ val names = tools.keys.filter { it !in handlers || it in staged }
101
+ handlers = handlers + tools.filterKeys { it in names }
102
+ names.forEach { staged[it] = stamp }
103
+ stamp
104
+ }
105
+ /** A refused call: removes what it staged, unless a later call has staged the name since. */
106
+ fun unstageTools(names: Set<String>, stamp: Int) = synchronized(lock) {
107
+ val mine = names.filter { staged[it] == stamp }
108
+ handlers = handlers - mine.toSet(); mine.forEach { staged.remove(it) }
109
+ }
110
+ /** An accepted call: its handlers serve every name it passed. */
111
+ fun acceptTools(tools: Map<String, ToolHandler>) = synchronized(lock) {
112
+ handlers = handlers + tools; tools.keys.forEach { staged.remove(it) }
113
+ }
114
+ private val effects = EffectExecutor()
115
+ private val tools = ToolExecutor()
116
+ private val identity = identities.getOrPut(storage) { "kotlin:" + UUID.randomUUID() }
117
+ private val lock = Any()
118
+ private var core: WeakReference<CoreRuntime>? = null
119
+ private var wakeTarget: Double? = null
120
+ private var timer: ScheduledFuture<*>? = null
121
+ private var scheduler: ScheduledExecutorService? = null
122
+ private var stopped = false
123
+ /** This Runtime's attachment to `osScheduler` (attached before the host is built), released
124
+ * once: a second stop, or a stale close after the scheduler was attached again for another
125
+ * Runtime, must not free a name someone else holds. Guarded by `lock`. */
126
+ private var osAttached = osScheduler != null
127
+ /** The wall clock (epoch ms) the Runtime and its timers read. Tests move it. */
128
+ @Volatile internal var clock: () -> Long = { System.currentTimeMillis() }
129
+ /** Runs `deliverDue()` on the Runtime when the earliest note's time comes. */
130
+ @Volatile internal var deliver: (() -> Unit)? = null
131
+ private var dueAt: Long? = null
132
+ private var fired: Long? = null
133
+ private var dueTimer: ScheduledFuture<*>? = null
134
+ private var deliveries: ScheduledExecutorService? = null
135
+
136
+ private inline fun <T> host(body: () -> T): T = try { keepAttached(); body() } catch (error: Exception) { throw failure(error) }
137
+
138
+ // HTTP
139
+ override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) = host {
140
+ try {
141
+ effects.run(request.timeoutMs.toLong(), signal(cancel)) { local ->
142
+ if (transport is RuntimeHttpURLConnection) transport.stream(request, sink, local) else adapt(request, sink, local)
143
+ JsonNull.INSTANCE
144
+ }
145
+ } catch (error: java.io.IOException) {
146
+ // The call keeps a Runtime code; what failed underneath rides along as its class name
147
+ // (never the message, which may name hosts): Logs then say why (dev, 2026-10-05).
148
+ throw CrocheException(transportCode(error), "The HTTP transport failed")
149
+ }
150
+ Unit
151
+ }
152
+
153
+ /** An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
154
+ * a response, and its stream deltas as server-sent events. */
155
+ internal fun adapt(request: PalHttpRequest, sink: HttpSink, signal: RuntimeCancellation) {
156
+ keepAttached()
157
+ val headers = JsonObject().apply { request.headers.forEach { addProperty(it.name, it.value) } }
158
+ val body = try { JsonParser.parseString(request.body) } catch (_: Exception) { str(request.body) }
159
+ val effect = obj("url" to str(request.url), "method" to str(request.method), "headers" to headers,
160
+ "body" to body, "timeoutMs" to num(request.timeoutMs.toLong()))
161
+ val started = AtomicBoolean(false)
162
+ val eventStream = listOf(PalHeader("content-type", "text/event-stream"))
163
+ val reply = transport.execute(effect, signal) { data ->
164
+ if (started.compareAndSet(false, true)) sink.head(200u, eventStream)
165
+ val frame = data.split("\n").joinToString("") { "data: $it\n" } + "\n"
166
+ sink.chunk(frame.toByteArray(Charsets.UTF_8))
167
+ }
168
+ val status = reply.at("status").let { if (it.isJsonPrimitive) it.asInt else 0 }.toUShort()
169
+ if (reply.at("streamed").let { it.isJsonPrimitive && it.asBoolean }) {
170
+ if (started.compareAndSet(false, true)) sink.head(status, eventStream)
171
+ return
172
+ }
173
+ val fields = reply.at("headers").let { if (it.isJsonObject) it.asJsonObject.entrySet() else emptySet() }
174
+ .filter { (key, value) -> value.text().isNotEmpty() && !key.equals("content-type", ignoreCase = true) }
175
+ .map { (key, value) -> PalHeader(key, value.text()) } + PalHeader("content-type", "application/json")
176
+ sink.head(status, fields)
177
+ val data = if (!reply.at("body").isJsonNull) reply.at("body").toString() else reply.at("raw").text()
178
+ if (data.isNotEmpty()) sink.chunk(data.toByteArray(Charsets.UTF_8))
179
+ }
180
+
181
+ // Storage
182
+ /** The Core names its snapshot by the key it locks, and other records `<key>.<entry>` (F19's
183
+ * held sends: `<key>.held`). Each goes to its own place: an entry never replaces the snapshot. */
184
+ @Volatile private var snapshotKey: String? = null
185
+ private fun entry(key: String): String? {
186
+ val main = snapshotKey ?: return null
187
+ if (key == main) return null
188
+ if (!key.startsWith("$main.") || key.length <= main.length + 1) throw CrocheException("storage_error", "Unknown storage key")
189
+ return key.substring(main.length + 1)
190
+ }
191
+ private inline fun <T> projectIO(body: () -> T): T = try { body() }
192
+ catch (_: java.io.IOException) { throw CrocheException("storage_error", "Could not access the project record") }
193
+ override fun read(key: String): String? = host {
194
+ if (isProjectKey(key)) return@host projectIO { projectRecords.read(key) }.also { afterProjectRead?.invoke(it) }
195
+ val name = entry(key)
196
+ val state = when {
197
+ name == null -> storage.load()
198
+ // A storage without entries never stored one.
199
+ storage is KeyedRuntimeStorage -> storage.load(name)
200
+ else -> JsonNull.INSTANCE
201
+ }
202
+ if (state.isJsonNull) null else state.toString()
203
+ }
204
+ override fun write(key: String, value: String) = persist {
205
+ if (isProjectKey(key)) { beforeProjectWrite?.invoke(); projectRecords.write(key, value); return@persist }
206
+ val name = entry(key)
207
+ when {
208
+ name == null -> storage.save(JsonParser.parseString(value))
209
+ storage is KeyedRuntimeStorage -> storage.save(name, JsonParser.parseString(value))
210
+ else -> throw CrocheException("storage_error", "This RuntimeStorage keeps only its snapshot")
211
+ }
212
+ }
213
+ override fun remove(key: String) = persist {
214
+ if (isProjectKey(key)) throw CrocheException("storage_error", "The project record is kept when agent data is removed")
215
+ val name = entry(key)
216
+ when {
217
+ name == null -> storage.remove()
218
+ storage is KeyedRuntimeStorage -> storage.remove(name)
219
+ storage is ArchiveRuntimeStorage && isLineStorageEntry(name) -> storage.remove(name)
220
+ else -> Unit // A snapshot-only storage has never held named entries.
221
+ }
222
+ }
223
+ override fun removeSecret(key: String) = persist { secretStore.remove() }
224
+ override fun readSecret(key: String): String? = host { secretStore.load().toString() }
225
+ override fun writeSecret(key: String, value: String) = persist { secretStore.save(JsonParser.parseString(value).asJsonObject) }
226
+ private fun persist(body: () -> Unit) = try { body() } catch (error: Exception) {
227
+ throw if (error is CrocheException) failure(error) else FfiException.Failure("storage_error", "Could not persist Runtime state")
228
+ }
229
+ override fun lock(key: String) = host {
230
+ if (isProjectKey(key)) projectIO { beforeProjectLock?.invoke(); projectRecords.acquire(key) }
231
+ else { storage.acquire(); snapshotKey = key }
232
+ }
233
+ override fun unlock(key: String) {
234
+ if (isProjectKey(key)) { projectRecords.release(key); return }
235
+ stop(); try { storage.release() } catch (_: Exception) {}
236
+ }
237
+ override fun storeIdentity(): String = identity
238
+
239
+ // The turn archive (F20.6)
240
+ /** The storage's archive, or the typed "no archive": the Runtime then keeps none, and every
241
+ * turn, clearHistory and memory work as before. */
242
+ private fun <T> archive(body: (ArchiveRuntimeStorage) -> T): T = try {
243
+ val archive = storage as? ArchiveRuntimeStorage ?: throw CrocheException("archive_unavailable", "This host keeps no turn archive.")
244
+ body(archive)
245
+ } catch (error: Exception) {
246
+ throw if (error is CrocheException) failure(error) else FfiException.Failure("storage_error", "The turn archive could not be read or written")
247
+ }
248
+ override fun archiveAppendLine(entry: String, line: String) = archive { it.appendLine(entry, line) }
249
+ override fun archiveReadLines(entry: String): List<String> = archive { it.readLines(entry) }
250
+ override fun archiveReplaceLines(entry: String, lines: List<String>) = archive { it.replaceLines(entry, lines) }
251
+ override fun archiveRemove(entry: String) = archive { it.remove(entry) }
252
+ override fun archiveEntries(prefix: String): List<ArchiveEntry> =
253
+ archive { a -> a.entries(prefix).toSortedMap().map { (entry, bytes) -> ArchiveEntry(entry, bytes.toULong()) } }
254
+
255
+ /** Where the message log goes (S1, rev 4 §17.13): in lines when the storage appends them, in
256
+ * entries when it keeps entries, else inside the snapshot. Never refused. */
257
+ override fun storageCapability(): StorageCapability = when (storage) {
258
+ is ArchiveRuntimeStorage -> StorageCapability.LINES
259
+ is KeyedRuntimeStorage -> StorageCapability.KEYED
260
+ else -> StorageCapability.SNAPSHOT
261
+ }
262
+
263
+ // Tools and attestation
264
+ override fun tool(invocation: String, cancel: CancelToken): ToolOutput = host {
265
+ val call = JsonParser.parseString(invocation)
266
+ val name = call.at("tool").text()
267
+ val handler = handlers[name] ?: throw CrocheException(NOT_DISPATCHED, "The host tool is not available")
268
+ val context = call.at("context")
269
+ val request = CommandInvocation(name, call.at("command").text().ifEmpty { null }, call.at("key").text(),
270
+ call.at("args").let { if (it.isJsonObject) it.asJsonObject.deepCopy() else JsonObject() })
271
+ // No deadline here: the Runtime times the call and cancels it (H4). This returns when
272
+ // the handler does, so a stuck one keeps its slot (H1).
273
+ val sink = ToolImages()
274
+ val value = tools.run(signal(cancel)) { local ->
275
+ handler.execute(request, ToolContext(context.at("callId").text(),
276
+ context.at("messageId").text(), context.at("userId").text(), local,
277
+ context.at("agentId").text().ifEmpty { null }, sink))
278
+ }
279
+ // A plain handler's JSON is the value as it was; a `withResult` one's images ride beside
280
+ // it, one sink per call (never shared between concurrent calls).
281
+ ToolOutput(value.toString(), sink.images.map { CrocheImages.record(it) })
282
+ }
283
+ override fun attest(request: String, timeoutMs: ULong): String = host {
284
+ val platform = attestor ?: throw CrocheException("attestation_unsupported", "This host has no attestor")
285
+ val effect = JsonParser.parseString(request)
286
+ val clientData = effect.at("clientData").text()
287
+ val hash = effect.at("clientDataHash").text()
288
+ if (clientData.isEmpty() || hash.isEmpty()) throw CrocheException("invalid_abi", "Malformed attest effect")
289
+ effects.run(timeoutMs.toLong(), RuntimeCancellation()) { signal ->
290
+ val proof = platform.attest(clientData, hash, signal)
291
+ obj("platform" to str(platform.platform), "token" to str(proof.token),
292
+ "keyId" to (proof.keyId?.let { str(it) } ?: JsonNull.INSTANCE))
293
+ }.toString()
294
+ }
295
+
296
+ // Clock, entropy, timer
297
+ override fun nowMs(): Double = clock().toDouble()
298
+ override fun utcOffsetMinutes(atMs: Double): Long = TimeZone.getDefault().getOffset(atMs.toLong()).toLong() / 60_000
299
+ override fun random(): String = UUID.randomUUID().toString()
300
+ override fun wake(atMs: Double?) {
301
+ synchronized(lock) { wakeTarget = atMs }
302
+ arm()
303
+ }
304
+ /** The agent's whole pending schedule set (JSON `[{id, at}]`), after each durable change and
305
+ * at open: a timer while running, and the OS's deferred work (`osScheduler`) for after. A
306
+ * refused registration fails this acknowledgement, which the Core reports as
307
+ * `schedule.degraded` with its code. */
308
+ override fun schedule(entries: String) = host { applySchedule(target(times(JsonParser.parseString(entries)))) }
309
+ @Volatile private var retryFloor: Long? = null
310
+ /** A failed delivery answered `retryAt`: a note already due waits until then. */
311
+ internal fun retryAfter(atMs: Long) { retryFloor = atMs }
312
+ /** When to wake for these notes: the earliest `at`, except that a note already due waits for
313
+ * a later `retryAt` (a delivery failed). */
314
+ internal fun target(times: List<Long>): Long? {
315
+ val now = clock()
316
+ val floor = retryFloor?.takeIf { it > now }
317
+ return times.map { if (floor != null && it <= now) floor else it }.minOrNull()
318
+ }
319
+ /** Arms the timer for `at` (null: nothing pending) and registers it with the OS. */
320
+ internal fun applySchedule(at: Long?) {
321
+ synchronized(lock) { dueAt = at }
322
+ armDelivery()
323
+ val os = osScheduler ?: return
324
+ try { if (at == null) os.cancel() else os.schedule(at) }
325
+ catch (error: CrocheException) { throw error }
326
+ catch (_: Exception) { throw CrocheException("schedule_failed", "The OS scheduler refused the request") }
327
+ }
328
+ /** The Runtime is open: a wake it asked for while opening can now fire. */
329
+ fun attach(core: CoreRuntime) { synchronized(lock) { this.core = WeakReference(core) }; arm(); armDelivery() }
330
+ fun stop() {
331
+ synchronized(lock) {
332
+ stopped = true; timer?.cancel(false); timer = null; scheduler?.shutdown()
333
+ dueTimer?.cancel(false); dueTimer = null; deliveries?.shutdown()
334
+ }
335
+ val release = synchronized(lock) { osAttached.also { osAttached = false } }
336
+ if (release) try { osScheduler?.detach() } catch (_: Exception) {}
337
+ }
338
+ /** One timer at the earliest note, never firing a delivery before its time (a timer that
339
+ * ends early re-arms), and at most once per time: a delivery that was cut short leaves its
340
+ * notes for the next open, foreground or OS run rather than retrying at once. */
341
+ private fun armDelivery() = synchronized(lock) {
342
+ dueTimer?.cancel(false); dueTimer = null
343
+ val target = dueAt
344
+ if (stopped || core == null || target == null || fired?.let { target <= it } == true) return@synchronized
345
+ val pool = deliveries ?: Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "croche-schedule").apply { isDaemon = true } }
346
+ .also { deliveries = it }
347
+ val delay = (target - clock()).coerceAtLeast(0)
348
+ dueTimer = pool.schedule({ due(target) }, delay, TimeUnit.MILLISECONDS)
349
+ }
350
+ /** A delivery is starting: it covers every note due now, so the timer never retries one. */
351
+ internal fun attempted() = synchronized(lock) { fired = maxOf(fired ?: Long.MIN_VALUE, clock()) }
352
+ private fun due(target: Long) {
353
+ if (clock() < target) { armDelivery(); return }
354
+ synchronized(lock) { if (stopped) return; fired = target }
355
+ try { deliver?.invoke() } catch (_: Exception) {}
356
+ }
357
+ fun release() { stop(); projectRecords.releaseAll(); effects.close(); tools.close() }
358
+ private fun arm() = synchronized(lock) {
359
+ timer?.cancel(false); timer = null
360
+ val target = wakeTarget
361
+ val runtime = core
362
+ if (!background || stopped || target == null || runtime == null) return@synchronized
363
+ val pool = scheduler ?: Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "croche-upkeep").apply { isDaemon = true } }
364
+ .also { scheduler = it }
365
+ val delay = (target - System.currentTimeMillis()).toLong().coerceAtLeast(0)
366
+ timer = pool.schedule({ try { runtime.get()?.tick() } catch (_: Exception) {} }, delay, TimeUnit.MILLISECONDS)
367
+ }
368
+ }