@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,161 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonElement
4
+ import com.google.gson.JsonNull
5
+ import com.google.gson.JsonObject
6
+ import com.google.gson.JsonPrimitive
7
+ import dev.croche.ffi.ToolImage
8
+ import java.util.Base64
9
+
10
+ /** How an image is sent (F30, H3). STANDARD (the default): at most 512 px on its longest side, never
11
+ * upscaled, as PNG or JPEG, whichever is smaller (transparency kept as PNG; a GIF becomes its
12
+ * first frame). HIGH: as given, within the limits (3 MB each, 6 MB together), for text,
13
+ * screenshots and dense detail. An https `url` image is never changed. An image's own
14
+ * `"resolution"` (`"standard"` or `"high"`) wins over the send's or the tool result's. */
15
+ enum class ImageResolution { STANDARD, HIGH }
16
+
17
+ /** A tool's result with images beside its value (H3): the same image kinds and limits as a
18
+ * message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4); a violation fails that call with
19
+ * `invalid_tool_result`, and the turn goes on. Return it from a handler made with [withResult]. */
20
+ data class ToolResult(val value: JsonElement = JsonNull.INSTANCE, val images: List<JsonObject> = emptyList(),
21
+ /** For every image that does not name its own `"resolution"`. */
22
+ val imageResolution: ImageResolution? = null)
23
+ fun interface ToolResultHandler { fun execute(invocation: CommandInvocation, context: ToolContext): ToolResult }
24
+
25
+ /** The one way to return a [ToolResult] (its value, plus images): `"room" to withResult { invocation, context -> ToolResult(...) }`.
26
+ * The images go to the Runtime beside the value; a plain [ToolHandler]'s JSON is never looked inside. */
27
+ fun withResult(handler: ToolResultHandler): ToolHandler = ToolHandler { invocation, context ->
28
+ val result = handler.execute(invocation, context)
29
+ // The handler ran: what it returned is read once, here. Anything that cannot be read fails
30
+ // this call alone with our own invalid_tool_result, never another error (Atlas, #351 P1-2).
31
+ try {
32
+ val images = result.images.toList()
33
+ context.images?.images = images.map { CrocheImages.prepare(it, result.imageResolution) }
34
+ result.value
35
+ } catch (failed: Throwable) {
36
+ if (failed is InterruptedException) throw failed
37
+ throw CrocheException("invalid_tool_result", "The tool returned a result that could not be read. Its effects may have completed.")
38
+ }
39
+ }
40
+
41
+ /** Where a [withResult] handler leaves its images for the call that ran it. */
42
+ class ToolImages internal constructor() {
43
+ @Volatile internal var images: List<JsonObject> = emptyList()
44
+ }
45
+
46
+ /** Decodes and re-encodes images on this platform. */
47
+ interface ImageCodec {
48
+ /** The image drawn upright, at most `maxSide` px on its longest side and never larger than it
49
+ * is (a GIF's first frame): PNG, and JPEG unless a pixel can be transparent. Null when this
50
+ * platform cannot decode it. `changed`: resized or turned upright. */
51
+ fun render(bytes: ByteArray, maxSide: Int): Rendered?
52
+ class Rendered(val png: ByteArray, val jpeg: ByteArray?, val changed: Boolean)
53
+ }
54
+
55
+ object CrocheImages {
56
+ const val STANDARD_MAX_SIDE = 512
57
+ /** The codec standard images go through: on Android, the SDK's Bitmap codec; on a plain JVM
58
+ * none, and images are sent as given. */
59
+ @Volatile var codec: ImageCodec? = try {
60
+ Class.forName("dev.croche.android.BitmapImageCodec").getDeclaredConstructor().newInstance() as ImageCodec
61
+ } catch (_: Throwable) { null }
62
+
63
+ /** A send's input with its single or stacked images prepared. */
64
+ fun prepareInput(input: JsonObject, fallback: ImageResolution?): JsonObject {
65
+ val out = input.deepCopy()
66
+ fun prepareImages(item: JsonObject) {
67
+ val images = item.get("images")?.takeIf { it.isJsonArray }?.asJsonArray ?: return
68
+ for (j in 0 until images.size()) {
69
+ val image = images[j]
70
+ if (image.isJsonObject) images[j] = prepare(image.asJsonObject, fallback)
71
+ }
72
+ }
73
+ val stack = out.get("inputs")?.takeIf { it.isJsonArray }?.asJsonArray
74
+ if (stack == null) prepareImages(out)
75
+ else for (item in stack) {
76
+ if (item.isJsonObject) prepareImages(item.asJsonObject)
77
+ }
78
+ return out
79
+ }
80
+
81
+ /** The image as it is sent: its resolution resolved and removed. Anything it cannot read
82
+ * passes unchanged, for the Core to judge. */
83
+ fun prepare(image: JsonObject, fallback: ImageResolution?): JsonObject {
84
+ // Malformed: exactly as given, for the Core to refuse (never rebuilt into a clean image).
85
+ if (wellFormed(image) == null) return image.deepCopy()
86
+ val given = image.deepCopy()
87
+ val named = given.remove("resolution")?.takeIf { it.isJsonPrimitive }?.asString
88
+ val resolution = when (named) { "high" -> ImageResolution.HIGH; "standard" -> ImageResolution.STANDARD; else -> fallback ?: ImageResolution.STANDARD }
89
+ val codec = codec ?: return given
90
+ val data = given.get("data")?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }?.asString
91
+ if (resolution != ImageResolution.STANDARD || data == null) return given
92
+ val (mime, bytes) = decoded(data, given.get("mime")?.takeIf { it.isJsonPrimitive }?.asString) ?: return given
93
+ val rendered = try { codec.render(bytes, STANDARD_MAX_SIDE) } catch (_: Throwable) { null } ?: return given
94
+ val candidates = mutableListOf("image/png" to rendered.png)
95
+ rendered.jpeg?.let { candidates.add("image/jpeg" to it) }
96
+ val best = candidates.minBy { it.second.size }
97
+ // Already upright and within the size: the original stays when it is the smallest
98
+ // (a GIF always becomes its first frame).
99
+ if (!rendered.changed && mime != "image/gif" && bytes.size <= best.second.size) return given
100
+ return JsonObject().apply {
101
+ add("data", JsonPrimitive(Base64.getEncoder().encodeToString(best.second)))
102
+ add("mime", JsonPrimitive(best.first))
103
+ given.get("alt")?.let { add("alt", it) }
104
+ }
105
+ }
106
+
107
+ private val MIMES = setOf("image/png", "image/jpeg", "image/webp", "image/gif")
108
+ private val BASE64 = Regex("^[A-Za-z0-9+/]+$")
109
+ /** A base64 image the Core would accept as given, by its shape (the Core's own rules: `data`
110
+ * and no `url`, its mime one of the four and agreeing with a data URL's, base64 text, an `alt`
111
+ * of at most 500 characters): its mime, or null. Only such an image is re-encoded (Atlas,
112
+ * #351 P1-3); anything else passes unchanged, so the Core refuses it as it would with no
113
+ * codec. Sizes are judged on what is sent, after re-encoding. */
114
+ internal fun wellFormed(image: JsonObject): String? {
115
+ fun text(key: String): String? = image.get(key)?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }?.asString
116
+ fun absent(key: String) = image.get(key).let { it == null || it.isJsonNull }
117
+ if (image.has("url")) return null
118
+ val data = text("data") ?: return null
119
+ var mime = if (absent("mime")) null else (text("mime")?.takeIf { it in MIMES } ?: return null)
120
+ if (!absent("alt") && (text("alt")?.length ?: Int.MAX_VALUE) > 500) return null
121
+ var body = data
122
+ if (data.startsWith("data:")) {
123
+ val comma = data.indexOf(',')
124
+ if (comma < 0) return null
125
+ val head = data.substring(5, comma)
126
+ if (!head.endsWith(";base64")) return null
127
+ val given = head.removeSuffix(";base64")
128
+ if (mime != null && mime != given) return null
129
+ mime = given
130
+ body = data.substring(comma + 1)
131
+ }
132
+ if (mime == null || mime !in MIMES) return null
133
+ val bare = body.trimEnd('=')
134
+ if (bare.isEmpty() || body.length - bare.length > 2 || !BASE64.matches(bare)) return null
135
+ return mime
136
+ }
137
+
138
+ private fun decoded(data: String, mime: String?): Pair<String, ByteArray>? {
139
+ var body = data
140
+ var type = mime
141
+ if (data.startsWith("data:")) {
142
+ val comma = data.indexOf(',')
143
+ if (comma < 0 || !data.substring(0, comma).endsWith(";base64")) return null
144
+ type = data.substring(5, comma - ";base64".length)
145
+ body = data.substring(comma + 1)
146
+ }
147
+ return try { (type ?: return null) to Base64.getDecoder().decode(body) } catch (_: IllegalArgumentException) { null }
148
+ }
149
+
150
+ /** The FFI's image record; a field present but not text fails the call, as the Core would. */
151
+ internal fun record(image: JsonObject): ToolImage {
152
+ fun text(key: String): String? {
153
+ val v = image.get(key) ?: return null
154
+ if (v.isJsonNull) return null
155
+ if (!v.isJsonPrimitive || !v.asJsonPrimitive.isString)
156
+ throw CrocheException("invalid_tool_result", "A tool result image's $key is text. Its effects may have completed.")
157
+ return v.asString
158
+ }
159
+ return ToolImage(text("data"), text("url"), text("mime") ?: "", text("alt"))
160
+ }
161
+ }
@@ -0,0 +1,173 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.CoreRuntime
5
+ import dev.croche.ffi.EventListener
6
+ import kotlinx.coroutines.Dispatchers
7
+ import kotlinx.coroutines.withContext
8
+ import java.time.Instant
9
+ import java.util.concurrent.atomic.AtomicBoolean
10
+ import kotlin.coroutines.suspendCoroutine
11
+
12
+ /** The only native subscription boundary. Core owns projection, capture and durable ordering. */
13
+ internal class NativeCoreStreamPort(private val core: CoreRuntime, private val host: KotlinHost) : CoreStreamPort {
14
+ private val closed = AtomicBoolean()
15
+ private val observationDetached = AtomicBoolean()
16
+ /** Test-only pause after Core dispatch/decoding, before forwarding to the SDK branch. */
17
+ @Volatile internal var projectionDeliveryStarting: ((RuntimeEvent) -> Unit)? = null
18
+ @Volatile internal var projectionDeliveryFinished: ((RuntimeEvent) -> Unit)? = null
19
+ @Volatile internal var projectionCloseFenced: (() -> Unit)? = null
20
+ @Volatile private var currentState = RuntimeEvent.State(AgentStatus.IDLE, 0, false)
21
+ override val state get() = currentState
22
+ override val logId get() = call { core.logId() }
23
+ private fun <T> call(body: () -> T): T {
24
+ if (closed.get()) throw CrocheException("closed", "Runtime is closed")
25
+ return try { nativeCall(body) } catch (error: Exception) { throw crocheError(error) }
26
+ }
27
+ private fun <T> nativeCall(body: () -> T): T {
28
+ CrocheRuntime.offloadStarting?.invoke()
29
+ return body()
30
+ }
31
+ private suspend fun <T> blocking(body: () -> T): T = withContext(Dispatchers.IO) { call(body) }
32
+ private fun listener(callback: (JsonObject) -> Unit) = object : EventListener {
33
+ override fun onEvent(event: String) { keepAttached(); callback(JsonParser.parseString(event).asJsonObject) }
34
+ }
35
+ override fun observe(event: (RuntimeEvent) -> Unit, end: (Throwable?) -> Unit): AutoCloseable {
36
+ call {
37
+ core.observe(listener { value ->
38
+ // Core's consuming-unit record is internal, never projected as an app event.
39
+ if (value.at("type").text() != "unit.end") {
40
+ val decoded = nativeEvent(value)
41
+ if (decoded is RuntimeEvent.State) currentState = decoded
42
+ event(decoded)
43
+ }
44
+ }, listener { value ->
45
+ end(CoreStreamFailure(value.at("code").text(), value.at("message").text(), value.flag("poisoned")))
46
+ })
47
+ }
48
+ observationDetached.set(false)
49
+ return AutoCloseable { unobserve() }
50
+ }
51
+ internal fun unobserve() {
52
+ if (observationDetached.compareAndSet(false, true) && !closed.get()) call { core.unobserve() }
53
+ }
54
+ override fun select(initialMessages: Int?, after: Cursor?, event: (RuntimeEvent) -> Unit): CoreStreamPort.Projection {
55
+ val selection = JsonObject().apply {
56
+ if (after != null) add("after", JsonObject().apply { addProperty("logId", after.logId); add("seq", JsonParser.parseString(coreSequence(after.seq).toString())) })
57
+ else initialMessages?.let { addProperty("initialMessages", it) }
58
+ }
59
+ val delivery = Any()
60
+ val detached = AtomicBoolean()
61
+ val id = call { core.select(selection.toString(), listener {
62
+ val decoded = nativeEvent(it)
63
+ projectionDeliveryStarting?.invoke(decoded)
64
+ // Stop forwarding once detached. Core close then joins the complete callback,
65
+ // including decoding and these hooks, unless it is this callback's own close.
66
+ try { synchronized(delivery) { if (!detached.get()) event(decoded) } }
67
+ finally { projectionDeliveryFinished?.invoke(decoded) }
68
+ }) }
69
+ return object : CoreStreamPort.Projection {
70
+ override fun close() {
71
+ val first = synchronized(delivery) { detached.compareAndSet(false, true) }
72
+ // The callback may still need delivery. Never hold its monitor across the
73
+ // Core listener-completion wait; a self-close stays on the callback thread.
74
+ if (first && !closed.get()) {
75
+ projectionCloseFenced?.invoke()
76
+ call { core.closeProjection(id) }
77
+ }
78
+ }
79
+ override suspend fun history(before: Long?, limit: Int) {
80
+ blocking { core.history(id, before?.let(::coreSequence), limit.toUInt()) }
81
+ }
82
+ }
83
+ }
84
+ override suspend fun send(input: JsonObject, options: SendOptions): Receipt = blocking {
85
+ // The only receipt-send FFI call site.
86
+ val value = JsonParser.parseString(core.send(input.toString(), null, options.responseFormat?.toString())).asJsonObject
87
+ Receipt(value.at("id").text(), nativeEnum(value.at("status")), value.optionalLong("seq"))
88
+ }
89
+ override suspend fun readOutcome(id: String, fromSeq: Long, captured: (CapturedOutcome) -> Unit): RetainedEnds = blocking {
90
+ val value = JsonParser.parseString(core.readOutcome(id, coreSequence(fromSeq), listener { at ->
91
+ captured(CapturedOutcome(at.number("head"), at.number("floor"), nativeEnum(at.at("status")), at.flag("idle")))
92
+ })).asJsonObject
93
+ RetainedEnds(value.list("messages").map { nativeEvent(it.asJsonObject) as RuntimeEvent.MessageEnd }, value.flag("gap"))
94
+ }
95
+ override suspend fun cancel(id: String) = blocking { core.cancel(id) }
96
+ override suspend fun clearHistory() {
97
+ // Take the Core's admission place on the caller before offloading only the wait.
98
+ val pending = call { core.beginClearHistory() }
99
+ suspendCoroutine<Unit> { continuation ->
100
+ Thread({
101
+ OffloadSeam.starting?.invoke()
102
+ continuation.resumeWith(runCatching { try { call { pending.finish() }; Unit } finally { nativeCall { pending.close() } } })
103
+ }, "croche-offload").apply { isDaemon = true }.start()
104
+ }
105
+ }
106
+ override fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) {
107
+ val stamp = host.stageTools(handlers)
108
+ try { call { core.setToolDeclarations(tools.toString()) } }
109
+ catch (error: Exception) { host.unstageTools(handlers.keys, stamp); throw error }
110
+ host.acceptTools(handlers)
111
+ }
112
+ override fun close() {
113
+ if (!closed.compareAndSet(false, true)) return
114
+ host.stop()
115
+ try { nativeCall { core.shutdown() } } catch (error: Exception) { throw crocheError(error) } finally { nativeCall { core.destroy() }; host.release() }
116
+ }
117
+ }
118
+
119
+ internal fun publicSequence(value: ULong): Long {
120
+ if (value > Long.MAX_VALUE.toULong()) throw CrocheException("invalid_input", "Core sequence exceeds Long.MAX_VALUE")
121
+ return value.toLong()
122
+ }
123
+ internal fun coreSequence(value: Long): ULong {
124
+ if (value < 0) throw CrocheException("invalid_input", "Sequence must not be negative")
125
+ return value.toULong()
126
+ }
127
+ private fun JsonElement.sequence(): Long {
128
+ val value = asString.toULongOrNull() ?: throw CrocheException("invalid_input", "Core sequence is not an unsigned integer")
129
+ return publicSequence(value)
130
+ }
131
+ private fun JsonObject.number(name: String) = get(name).sequence()
132
+ private fun JsonObject.optionalLong(name: String) = get(name)?.takeUnless { it.isJsonNull }?.sequence()
133
+ private fun JsonObject.flag(name: String) = get(name)?.takeUnless { it.isJsonNull }?.asBoolean ?: false
134
+ private fun JsonObject.list(name: String): List<JsonElement> = get(name)?.takeIf { it.isJsonArray }?.asJsonArray?.toList() ?: emptyList()
135
+ private fun JsonObject.strings(name: String) = list(name).map { it.asString }
136
+ private inline fun <reified E : Enum<E>> nativeEnum(value: JsonElement): E =
137
+ enumValues<E>().firstOrNull { it.name.equals(value.text(), ignoreCase = true) } ?: enumValueOf("UNKNOWN")
138
+ private fun JsonObject.error() = get("error")?.takeIf { it.isJsonObject }?.asJsonObject?.let { RuntimeError(it.at("code").text(), it.at("message").text()) }
139
+
140
+ /** Decode the Core's tagged JSON; omission stays omission, unknown enum values stay UNKNOWN. */
141
+ internal fun nativeEvent(value: JsonObject): RuntimeEvent {
142
+ fun at() = Instant.parse(value.at("at").text())
143
+ fun state(v: JsonObject) = RuntimeEvent.State(nativeEnum(v.at("status")), v.number("queued").toInt(), v.flag("typing"),
144
+ v.get("activity")?.takeUnless { it.isJsonNull }?.let { nativeEnum<AgentActivity>(it) },
145
+ v.get("tools")?.takeIf { it.isJsonArray }?.asJsonArray?.map { it.asString })
146
+ return when (val type = value.at("type").text()) {
147
+ "input" -> RuntimeEvent.Input(value.number("seq"), value.number("firstSeq"), value.at("id").text(), nativeEnum(value.at("kind")),
148
+ value.get("text")?.takeUnless { it.isJsonNull }?.asString, value.list("images").map { image -> image.asJsonObject.let {
149
+ ImageSummary(it.get("alt")?.asString, it.get("mime")?.asString, it.optionalLong("bytes"))
150
+ } }, nativeEnum(value.at("status")), value.error(), at())
151
+ "message.start" -> RuntimeEvent.MessageStart(value.number("seq"), value.number("firstSeq"), value.at("id").text(), at())
152
+ "message.delta" -> RuntimeEvent.MessageDelta(value.at("id").text(), value.at("text").text())
153
+ "message.end" -> RuntimeEvent.MessageEnd(value.number("seq"), value.number("firstSeq"), value.at("id").text(), nativeEnum(value.at("status")),
154
+ value.at("text").text(), value.strings("markers"), value.get("output")?.takeUnless { it.isJsonNull }?.deepCopy(),
155
+ value.strings("inReplyTo"), value.strings("causedBy"), value.error(), at())
156
+ "state" -> state(value)
157
+ "snapshot" -> RuntimeEvent.Snapshot(value.at("logId").text(), state(value.getAsJsonObject("state")), value.get("streaming")?.takeIf { it.isJsonObject }?.asJsonObject?.let {
158
+ Streaming(it.at("messageId").text(), it.number("firstSeq"), it.at("text").text())
159
+ })
160
+ "page" -> RuntimeEvent.Page(value.list("messages").map { nativeEvent(it.asJsonObject) }, value.flag("reachedFloor"), value.at("logId").text(), value.number("clearedSeq"))
161
+ "gap" -> RuntimeEvent.Gap(value.number("afterSeq"), value.number("throughSeq"), nativeEnum(value.at("reason")))
162
+ "cleared" -> RuntimeEvent.Cleared(value.number("seq"), value.at("id").text(), at())
163
+ "turn" -> RuntimeEvent.Turn(value.number("seq"), value.at("id").text(), value.strings("causedBy"), value.strings("inputs"), value.at("purpose").text(),
164
+ value.get("usage")?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet()?.associate { it.key to it.value.asLong } ?: emptyMap(),
165
+ value.get("costUsd")?.asDouble ?: 0.0, nativeEnum(value.at("costStatus")), value.at("model").text(), value.optionalLong("imagesOmitted")?.toInt(), at())
166
+ "app" -> value.getAsJsonObject("source").let { RuntimeEvent.App(value.number("seq"), value.at("id").text(), value.at("name").text(), value.get("data").deepCopy(),
167
+ ToolSource(it.at("command").text(), it.at("callId").text()), at()) }
168
+ "error" -> if (value.has("seq")) RuntimeEvent.Error(value.number("seq"), value.at("id").text(), value.at("code").text(), value.at("message").text(), value.strings("inputs"), at())
169
+ else RuntimeEvent.StreamError(value.at("code").text(), value.at("message").text(), value.flag("poisoned"))
170
+ "replaced" -> RuntimeEvent.Replaced
171
+ else -> RuntimeEvent.Unknown(type)
172
+ }
173
+ }
@@ -0,0 +1,105 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import java.io.File
5
+ import java.io.FileOutputStream
6
+ import java.nio.file.Files
7
+ import java.nio.file.StandardCopyOption.*
8
+ import java.nio.file.attribute.PosixFilePermissions
9
+
10
+ // Platform Abstraction Layer. The Rust Core decides; these perform what only the platform
11
+ // can: keep a credential in hardware-backed storage, and vouch for the app binary.
12
+ // See docs/MOBILE-SDK-AND-PAL.md. Android implementations live in the android module.
13
+
14
+ /** Where the Runtime credential lives, apart from the general state file. load returns an
15
+ * object (empty when nothing is stored); save replaces the whole object atomically. */
16
+ interface RuntimeSecretStore {
17
+ fun load(): JsonObject
18
+ fun save(secrets: JsonObject)
19
+ /** Delete the credential item for real; an absent item is already removed. */
20
+ fun remove()
21
+ }
22
+
23
+ /** The platform's attestation of this app binary, bound to the client data hash. */
24
+ data class RuntimeAttestation(val token: String, val keyId: String? = null)
25
+
26
+ interface RuntimeAttestor {
27
+ /** "android-play-integrity" or "ios-app-attest"; declared to the Core in config. */
28
+ val platform: String
29
+ /** `clientDataHash` is base64url(SHA-256(clientData)), exactly as Cloud recomputes it.
30
+ * Blocking; called on an effect worker thread with the effect's deadline. */
31
+ fun attest(clientData: String, clientDataHash: String, cancellation: RuntimeCancellation): RuntimeAttestation
32
+ }
33
+
34
+ /**
35
+ * The OS's deferred work for the agent's scheduled notes while the app is not running (founder
36
+ * 17:14Z): WorkManager on Android (`dev.croche.android.WorkManagerScheduler`). The Runtime calls
37
+ * it with the earliest pending note after every change, at every open, and after every
38
+ * `deliverDue()`. The work it registers runs `deliverDue()`: inexact, never before that time. No
39
+ * exact alarms, notifications or permissions.
40
+ */
41
+ interface RuntimeScheduler {
42
+ /** Replaces any earlier request with one at or after `earliestAtMs` (epoch ms). Idempotent:
43
+ * one request at a time, by a unique name. Throw `CrocheException("not_configured", ...)` when
44
+ * the app is not set up for it: the Runtime reports `schedule.degraded` with that code and
45
+ * still delivers while running and at the next open. */
46
+ fun schedule(earliestAtMs: Long)
47
+ /** Nothing is pending: withdraw the request. */
48
+ fun cancel()
49
+ /** A Runtime is opening with this scheduler. Throw `CrocheException("scheduler_conflict",
50
+ * ...)` to refuse it when its request name is already another open Runtime's: that name's
51
+ * runs could deliver through only one of them, including when the same scheduler object is
52
+ * given to a second Runtime. */
53
+ fun attach() {}
54
+ /** That Runtime closed (or failed to open): the name is free again. The Runtime calls this at
55
+ * most once per successful `attach`, however often it is closed. */
56
+ fun detach() {}
57
+ }
58
+
59
+ /** A private file beside the state file. For hosts without a secret store (JVM servers,
60
+ * tests). On Android, use KeystoreSecretStore from the android module. */
61
+ class FileRuntimeSecretStore(private val file: File) : RuntimeSecretStore {
62
+ @Synchronized override fun load(): JsonObject {
63
+ if (!file.exists()) return JsonObject()
64
+ val saved = try { JsonParser.parseString(file.readText(Charsets.UTF_8)) }
65
+ catch (_: Exception) { throw CrocheException("corrupt_store", "Runtime credentials are unreadable; remove them to register again") }
66
+ if (!saved.isJsonObject) throw CrocheException("corrupt_store", "Runtime credentials must be an object")
67
+ return saved.asJsonObject
68
+ }
69
+ @Synchronized override fun remove() { Files.deleteIfExists(file.toPath()) }
70
+ @Synchronized override fun save(secrets: JsonObject) {
71
+ file.absoluteFile.parentFile.mkdirs()
72
+ val temporary = File.createTempFile("croche-secrets-", ".tmp", file.absoluteFile.parentFile)
73
+ try {
74
+ try { Files.setPosixFilePermissions(temporary.toPath(), PosixFilePermissions.fromString("rw-------")) }
75
+ catch (_: UnsupportedOperationException) {}
76
+ FileOutputStream(temporary).use { output -> output.write(secrets.toString().toByteArray(Charsets.UTF_8)); output.fd.sync() }
77
+ Files.move(temporary.toPath(), file.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
78
+ } finally { temporary.delete() }
79
+ }
80
+ }
81
+
82
+ /** One open Runtime per OS identity (a WorkManager name): the rule the OS schedulers share, kept
83
+ * in one place so the tests' schedulers run the same code as `WorkManagerScheduler` (Atlas, #323
84
+ * P1-2 and the NO at dc38bf0). `claim` is refused while the identity is held by anyone, the
85
+ * claiming object included: `create` claims once per Runtime, so one object given to two
86
+ * Runtimes is refused the second time. `release` frees it only for its holder. */
87
+ internal class SchedulerClaims(private val what: String) {
88
+ private val holders = HashMap<String, Any>()
89
+ @Synchronized fun claim(identity: String, by: Any) {
90
+ if (holders[identity] != null) {
91
+ throw CrocheException("scheduler_conflict", "Another open Runtime uses the $what \"$identity\"; give each Runtime its own, or close it first")
92
+ }
93
+ holders[identity] = by
94
+ }
95
+ @Synchronized fun release(identity: String, by: Any) { if (holders[identity] === by) holders.remove(identity) }
96
+ @Synchronized fun held(identity: String) = holders[identity] != null
97
+ }
98
+
99
+ /** Marks the React Native bridge's internal hooks: not part of the SDK's public API, not frozen,
100
+ * and replaced without notice. Interim until the public subscription for agent-initiated
101
+ * messages (F25 on #264) lands. */
102
+ @RequiresOptIn(message = "Internal to the Croche React Native bridge; not public API and not frozen.", level = RequiresOptIn.Level.ERROR)
103
+ @Retention(AnnotationRetention.BINARY)
104
+ @Target(AnnotationTarget.FUNCTION)
105
+ annotation class CrocheBridgeApi
@@ -0,0 +1,87 @@
1
+ package dev.croche
2
+
3
+ import java.io.File
4
+ import java.io.FileOutputStream
5
+ import java.io.RandomAccessFile
6
+ import java.nio.channels.FileLock
7
+ import java.nio.file.Files
8
+ import java.nio.file.StandardCopyOption.*
9
+
10
+ /** Android supplies filesDir at app startup. A plain JVM has no implicit install directory. */
11
+ internal fun defaultProjectDirectory(): File? = try {
12
+ Class.forName("dev.croche.android.CrocheProjectRecordProvider")
13
+ .getMethod("directory").invoke(null) as? File
14
+ } catch (_: ClassNotFoundException) { null }
15
+
16
+ /** Explicit locations are allowed only on hosts without an app-private default. */
17
+ internal fun projectRecordDirectory(option: File?, default: File?): File? {
18
+ if (option != null && default != null)
19
+ throw CrocheException("invalid_configuration", "this platform keeps the project record in the app's private storage")
20
+ return option ?: default
21
+ }
22
+
23
+ internal fun isProjectKey(key: String) = key.startsWith("croche.project.")
24
+
25
+ /** Raw project records, never the app's RuntimeStorage or its snapshot/entry namespace. */
26
+ internal class ProjectRecords(private val directory: () -> File?) {
27
+ private data class Ownership(val file: RandomAccessFile, val lock: FileLock)
28
+ private val owned = mutableMapOf<String, Ownership>()
29
+
30
+ private fun record(key: String): File {
31
+ if (!Regex("croche\\.project\\.v1\\.[0-9a-f]{64}").matches(key))
32
+ throw CrocheException("storage_error", "Invalid project record key")
33
+ val location = directory() ?: throw CrocheException("storage_error",
34
+ "Project records require projectDirectory on this platform; no app-private default exists")
35
+ return File(location, "$key.json")
36
+ }
37
+
38
+ @Synchronized fun acquire(key: String) {
39
+ val target = record(key)
40
+ if (key in owned) throw CrocheException("store_busy", "Project record is already owned")
41
+ target.parentFile.mkdirs()
42
+ val opened = RandomAccessFile(File(target.path + ".lock"), "rw")
43
+ try {
44
+ val lock = opened.channel.tryLock() ?: throw CrocheException("store_busy", "Project record is already owned")
45
+ owned[key] = Ownership(opened, lock)
46
+ } catch (failure: Exception) {
47
+ opened.close()
48
+ if (failure is CrocheException) throw failure
49
+ if (failure is java.nio.channels.OverlappingFileLockException)
50
+ throw CrocheException("store_busy", "Project record is already owned")
51
+ throw CrocheException("storage_error", "Could not lock the project record")
52
+ }
53
+ }
54
+
55
+ @Synchronized fun read(key: String): String? {
56
+ requireOwnership(key)
57
+ val target = record(key)
58
+ return if (target.exists()) target.readText(Charsets.UTF_8) else null
59
+ }
60
+
61
+ @Synchronized fun write(key: String, value: String) {
62
+ requireOwnership(key)
63
+ val target = record(key)
64
+ val temporary = File.createTempFile("croche-project-", ".tmp", target.parentFile)
65
+ try {
66
+ FileOutputStream(temporary).use { output ->
67
+ output.write(value.toByteArray(Charsets.UTF_8)); output.fd.sync()
68
+ }
69
+ Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
70
+ } finally { temporary.delete() }
71
+ }
72
+
73
+ @Synchronized fun remove(key: String) {
74
+ requireOwnership(key)
75
+ Files.deleteIfExists(record(key).toPath())
76
+ }
77
+
78
+ private fun requireOwnership(key: String) {
79
+ if (key !in owned) throw CrocheException("storage_error", "Project record is not locked")
80
+ }
81
+
82
+ @Synchronized fun release(key: String) {
83
+ val ownership = owned.remove(key) ?: return
84
+ try { ownership.lock.release() } finally { ownership.file.close() }
85
+ }
86
+ @Synchronized fun releaseAll() { owned.keys.toList().forEach(::release) }
87
+ }
@@ -0,0 +1,27 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonArray
4
+ import com.google.gson.JsonObject
5
+
6
+ /** One encoding boundary for send and request; Core owns normalization and stack limits. */
7
+ internal fun SendInput.encoded(options: SendOptions = SendOptions()): JsonObject {
8
+ val out = JsonObject().apply { addProperty("id", id) }
9
+ if (inputs.isNotEmpty()) {
10
+ if (text.isNotEmpty() || images.isNotEmpty() || kind != InputKind.USER) {
11
+ throw CrocheException("invalid_input", "Send either text and kind (one input) or inputs (a stack), not both")
12
+ }
13
+ out.add("inputs", JsonArray().apply {
14
+ inputs.forEach { part -> add(JsonObject().apply {
15
+ addProperty("kind", part.kind.name.lowercase())
16
+ part.text?.let { addProperty("text", it) }
17
+ if (part.images.isNotEmpty()) add("images", JsonArray().apply { part.images.forEach { add(it.json.deepCopy()) } })
18
+ }) }
19
+ })
20
+ } else {
21
+ out.addProperty("text", text)
22
+ out.addProperty("kind", kind.name.lowercase())
23
+ if (images.isNotEmpty()) out.add("images", JsonArray().apply { images.forEach { add(it.json.deepCopy()) } })
24
+ }
25
+ context?.let { out.add("context", it.deepCopy()) }
26
+ return CrocheImages.prepareInput(out, options.imageResolution)
27
+ }