@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,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,79 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonArray
4
+ import dev.croche.ffi.CoreProject
5
+ import dev.croche.ffi.CoreRuntime
6
+ import dev.croche.ffi.HostPal
7
+ import dev.croche.ffi.HostPalFactory
8
+ import java.util.concurrent.ConcurrentHashMap
9
+ import java.util.concurrent.CopyOnWriteArrayList
10
+
11
+ /** Same lifetime rule as RN AgentPals: a fresh host each time Core asks, including record/GC PALs. */
12
+ internal class ProjectPals(private val makeHost: (String) -> KotlinHost) : HostPalFactory {
13
+ private val all = CopyOnWriteArrayList<KotlinHost>()
14
+ private val agents = ConcurrentHashMap<String, KotlinHost>()
15
+ override fun pal(agent: String): HostPal {
16
+ keepAttached()
17
+ return makeHost(agent).also {
18
+ all.add(it)
19
+ if (!projectPalRoute(agent).maintenance) agents[agent] = it
20
+ }
21
+ }
22
+ internal val cachedAgentSlots: Set<String> get() = agents.keys.toSet()
23
+ fun host(core: CoreRuntime): KotlinHost = agents[slot(core)]
24
+ ?: throw CrocheException("core_error", "Core opened an agent without requesting its host")
25
+ fun release() {
26
+ all.forEach { it.deliver = null; it.stop(); it.release() }
27
+ all.clear(); agents.clear()
28
+ }
29
+ companion object {
30
+ fun slot(core: CoreRuntime): String = core.instance()?.let { instance ->
31
+ JsonArray().apply { add(core.agentId()); add(instance) }.toString()
32
+ } ?: core.agentId()
33
+ }
34
+ }
35
+
36
+ /** Core admission runs even for a cached wrapper, to validate overrides and instance identity. */
37
+ internal class ProjectBinding(private val core: CoreProject, private val pals: ProjectPals) {
38
+ private val agents = linkedMapOf<String, Pair<CoreRuntime, CrocheRuntime>>()
39
+ @Volatile private var closed = false
40
+ val agentIds: List<String> get() = call { core.agentIds() }
41
+ val user: String? get() = call { core.user() }
42
+ val installationId: String? get() = call { core.installationId() }
43
+ @Volatile private var cachedUserId: String? = null
44
+ val crocheUserId: String? get() = call { core.crocheUserId() }.also { if (it != null) cachedUserId = it }
45
+ /** Final paid-call usage can arrive while shutdown runs, after public getters are closed. */
46
+ internal val usageUserId: String? get() = try { core.crocheUserId() ?: cachedUserId }
47
+ catch (_: Exception) { cachedUserId }
48
+ private fun <T> call(body: () -> T): T {
49
+ if (closed) throw CrocheException("closed", "The project is closed")
50
+ return try { body() } catch (error: Exception) { throw crocheError(error) }
51
+ }
52
+ @Synchronized fun agent(id: String?, options: String): Pair<CoreRuntime, CrocheRuntime> = call {
53
+ val opened = core.agentWithOptions(id, options, null)
54
+ try {
55
+ core.crocheUserId()?.let { cachedUserId = it }
56
+ val slot = ProjectPals.slot(opened)
57
+ val existing = agents[slot]
58
+ if (existing != null && !existing.second.isClosed) {
59
+ opened.destroy()
60
+ return@call existing
61
+ }
62
+ val runtime = CrocheRuntime.adopt(opened, pals.host(opened))
63
+ (opened to runtime).also { agents[slot] = it }
64
+ } catch (error: Exception) { if (!opened.uniffiIsDestroyed) opened.destroy(); throw error }
65
+ }
66
+ fun close() {
67
+ synchronized(this) { if (closed) return; closed = true }
68
+ try { core.shutdown() }
69
+ catch (error: Exception) { throw crocheError(error) }
70
+ finally {
71
+ try {
72
+ var failed: Exception? = null
73
+ agents.values.forEach { try { it.second.close() } catch (error: Exception) { if (failed == null) failed = error } }
74
+ failed?.let { throw it }
75
+ }
76
+ finally { agents.clear(); core.destroy(); pals.release() }
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,25 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonObject
4
+ import com.google.gson.JsonParser
5
+
6
+ /** Core's PAL labels are routing metadata, never an agentId to hash literally. */
7
+ internal data class ProjectPalRoute(val agent: String, val instance: String? = null, val maintenance: Boolean = false) {
8
+ // OPEN(Keel/Atlas): install-wide GC labels omit the target user; binding by Core lock key is proposed.
9
+ fun identity(host: JsonObject, user: String?): JsonObject = host.deepCopy().apply {
10
+ addProperty("agentId", agent)
11
+ remove("agentInstance")
12
+ instance?.let { addProperty("agentInstance", it) }
13
+ user?.let { addProperty("user", it) }
14
+ }
15
+ }
16
+ internal fun projectPalRoute(label: String): ProjectPalRoute {
17
+ if (!label.startsWith("[")) return ProjectPalRoute(label)
18
+ val parts = JsonParser.parseString(label).asJsonArray.map { it.asString }
19
+ return when {
20
+ parts == listOf("\$gc", "pass") -> ProjectPalRoute("default", maintenance = true)
21
+ parts.size == 3 && parts[0] == "\$gc" -> ProjectPalRoute(parts[1], parts[2], maintenance = true)
22
+ parts.size == 2 -> ProjectPalRoute(parts[0], parts[1])
23
+ else -> throw CrocheException("invalid_configuration", "Invalid project PAL label")
24
+ }
25
+ }
@@ -0,0 +1,46 @@
1
+ package dev.croche
2
+
3
+ import java.io.File
4
+ import java.util.Locale
5
+
6
+ /** Android is discovered through its existing provider; the JVM artifact has no Android dependency. */
7
+ internal data class ProjectPlatform(
8
+ val directory: File,
9
+ val secretStorage: (String) -> RuntimeSecretStore,
10
+ val attestor: RuntimeAttestor?,
11
+ )
12
+ internal fun projectDeviceLanguage(): String = try {
13
+ Class.forName("dev.croche.android.CrocheProjectRecordProvider")
14
+ .getMethod("language").invoke(null) as String
15
+ } catch (_: ClassNotFoundException) { Locale.getDefault().toLanguageTag() }
16
+
17
+ internal fun projectPlatform(options: OpenOptions): ProjectPlatform {
18
+ val android = try { Class.forName("dev.croche.android.CrocheProjectRecordProvider") }
19
+ catch (_: ClassNotFoundException) { null }
20
+ val default = defaultProjectDirectory()
21
+ val directory = projectRecordDirectory(options.projectDirectory, default)
22
+ ?: throw CrocheException("storage_error", "Croche.open requires projectDirectory on this platform")
23
+ if (android == null) return ProjectPlatform(directory,
24
+ { name -> FileRuntimeSecretStore(File(directory, "$name.secrets")) }, null)
25
+ val attestor = if (options.attestation != Attestation.OFF) options.android?.cloudProjectNumber?.let { number ->
26
+ android.getMethod("attestor", java.lang.Long.TYPE).invoke(null, number) as RuntimeAttestor
27
+ } else null
28
+ return ProjectPlatform(File(directory, "croche"), { name ->
29
+ android.getMethod("secretStorage", String::class.java).invoke(null, name) as RuntimeSecretStore
30
+ }, attestor)
31
+ }
32
+
33
+ internal fun OpenOptions.hostJson(attestor: RuntimeAttestor?) = com.google.gson.JsonObject().apply {
34
+ cloudUrl?.let { addProperty("cloudUrl", it) }; addProperty("projectKey", projectKey)
35
+ debugKey?.let { addProperty("debugKey", it) }
36
+ requestTimeoutMs?.let { addProperty("requestTimeoutMs", it) }
37
+ maxPendingEvents?.let { addProperty("maxPendingEvents", it) }
38
+ syncIntervalMs?.let { addProperty("syncIntervalMs", it) }
39
+ maintenanceBackoffMs?.let { addProperty("maintenanceBackoffMs", it) }
40
+ retentionBytes?.let { addProperty("retentionBytes", it) }
41
+ debugVisibility?.let { addProperty("debugVisibility", "runtime") }
42
+ attestor?.let { addProperty("attestationPlatform", it.platform) }
43
+ }
44
+
45
+ internal fun OpenOptions.owned(): OpenOptions = copy(config = config.deepCopy(), handlers = handlers.toMap(),
46
+ language = language ?: projectDeviceLanguage())
@@ -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,44 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonObject
4
+ import java.io.File
5
+
6
+ data class OpenOptions(
7
+ val cloudUrl: String? = null,
8
+ val projectKey: String,
9
+ val config: JsonObject,
10
+ val user: String? = null,
11
+ val handlers: Map<String, ToolHandler> = emptyMap(),
12
+ val language: String? = null,
13
+ val timeZone: String? = null,
14
+ val streaming: Boolean? = null,
15
+ val backgroundSync: Boolean? = null,
16
+ val maintenanceIntervalMs: Long? = null,
17
+ val debugKey: String? = null,
18
+ val requestTimeoutMs: Long? = null,
19
+ val maxPendingEvents: Int? = null,
20
+ val syncIntervalMs: Long? = null,
21
+ val maintenanceBackoffMs: Long? = null,
22
+ val retentionBytes: Long? = null,
23
+ val onUsage: ((ProjectUsageEvent) -> Unit)? = null,
24
+ val onDebugEvent: ((RuntimeDebugEvent) -> Unit)? = null,
25
+ val debugVisibility: DebugVisibility? = null,
26
+ val attestation: Attestation? = null,
27
+ val android: AndroidOptions? = null,
28
+ val projectDirectory: File? = null,
29
+ val http: RuntimeHTTP? = null,
30
+ )
31
+ enum class DebugVisibility { RUNTIME }
32
+ enum class Attestation { PLATFORM, OFF }
33
+ data class AndroidOptions(val cloudProjectNumber: Long? = null)
34
+ typealias ProjectUsageEvent = JsonObject
35
+ typealias RuntimeDebugEvent = JsonObject
36
+ typealias MemoryChangedEvent = JsonObject
37
+ typealias ProjectToolContext = ToolContext
38
+
39
+ data class AgentOptions(val instance: String? = null, val fresh: Boolean? = null, val config: JsonObject? = null)
40
+ data class RequestOptions(val responseFormat: JsonObject? = null, val wait: RequestWait? = null)
41
+ data class SubscribeOptions(val initialMessages: Int? = null, val after: Cursor? = null,
42
+ val onEvent: suspend (RuntimeEvent) -> Unit)
43
+ data class HistoryOptions(val before: Long? = null, val limit: Int)
44
+ data class AppStreamEnd(val code: String)
@@ -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
+ }