@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,178 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import java.net.URI
5
+ import java.util.UUID
6
+ import java.util.concurrent.*
7
+ import java.util.concurrent.atomic.AtomicBoolean
8
+
9
+ fun interface ControlSend { fun send(input: JsonObject, cancellation: RuntimeCancellation): JsonElement }
10
+ fun interface ControlCancel { fun cancel(): Boolean }
11
+
12
+ /** Explicit local attachment, independent of Cloud credentials and Runtime ownership.
13
+ * Close this connection separately; it never opens/closes the Runtime's private store. */
14
+ class RuntimeControl private constructor(
15
+ private val runtime: CrocheRuntime, private val url: String, private val token: String,
16
+ private val http: RuntimeHTTP, private val sendAdapter: ControlSend?, private val cancelAdapter: ControlCancel?,
17
+ private val onError: ((String) -> Unit)?
18
+ ) : AutoCloseable {
19
+ val runtimeInstanceId = runtime.inspect().at("status").at("runtimeInstanceId").text()
20
+ val capabilities: List<String> = listOf("status", "history", "send", "cancel", "sync", "budget.get", "budget.set", "tools")
21
+ private val clientId = UUID.randomUUID().toString()
22
+ private val lifetime = RuntimeCancellation()
23
+ private val effects = EffectExecutor()
24
+ private val closed = AtomicBoolean(false)
25
+ private val handled = ConcurrentHashMap.newKeySet<String>()
26
+ private val results = ConcurrentHashMap<String, JsonObject>()
27
+ private val active = ConcurrentHashMap<String, RuntimeCancellation>()
28
+ private val tasks = ConcurrentHashMap.newKeySet<String>()
29
+ private val workers = ThreadPoolExecutor(0, 16, 30, TimeUnit.SECONDS, SynchronousQueue(),
30
+ ThreadFactory { task -> Thread(task, "croche-control-command").apply { isDaemon = true } })
31
+ private var poller: Thread? = null
32
+ companion object {
33
+ fun attach(runtime: CrocheRuntime, token: String, url: String = "http://127.0.0.1:8791",
34
+ http: RuntimeHTTP = RuntimeHttpURLConnection(), send: ControlSend? = null,
35
+ cancel: ControlCancel? = null, onError: ((String) -> Unit)? = null): RuntimeControl {
36
+ val parsed = try { URI(url) } catch (_: Exception) { throw CrocheException("invalid_configuration", "Invalid local control URL") }
37
+ if (parsed.scheme != "http" || parsed.host !in listOf("127.0.0.1", "localhost", "[::1]", "::1") ||
38
+ parsed.userInfo != null || parsed.query != null || parsed.fragment != null || parsed.path !in listOf("", "/") ||
39
+ !Regex("^[A-Za-z0-9._~-]{24,4096}$").matches(token)) {
40
+ throw CrocheException("invalid_configuration", "Control needs a loopback HTTP origin and explicit local token")
41
+ }
42
+ val control = RuntimeControl(runtime, url.removeSuffix("/"), token, http, send, cancel, onError)
43
+ try { control.register(); control.start() }
44
+ catch (error: Exception) { control.release(); throw error }
45
+ return control
46
+ }
47
+ }
48
+ private fun identity() = obj("client_id" to str(clientId), "runtime_instance_id" to str(runtimeInstanceId))
49
+ private fun register() {
50
+ val caps = JsonArray(); capabilities.forEach { caps.add(it) }
51
+ post("register", obj("client_id" to str(clientId), "runtime" to runtime.inspect().at("status"), "capabilities" to caps))
52
+ }
53
+ private fun post(path: String, body: JsonObject): JsonObject {
54
+ if (body.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("control_capacity", "Control request exceeds 1MiB")
55
+ val effect = obj("url" to str("$url/v1/control/$path"), "method" to str("POST"),
56
+ "headers" to obj("Authorization" to str("Bearer $token"), "Content-Type" to str("application/json")),
57
+ "body" to body, "timeoutMs" to num(5000))
58
+ val response = effects.run(5000, lifetime) { signal -> http.execute(effect, signal) {} }
59
+ val data = response.at("body")
60
+ if (!data.isJsonObject || data.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("invalid_response", "Invalid bounded control response")
61
+ if (response.at("status").asInt !in 200..299) {
62
+ val code = data.at("error").at("code").text()
63
+ throw CrocheException(if (code in setOf("attachment_lost", "not_found", "unauthorized", "runtime_already_attached")) code else "control_error", "Local control broker rejected the request")
64
+ }
65
+ return data.asJsonObject
66
+ }
67
+ private fun start() {
68
+ poller = Thread({
69
+ while (!closed.get()) {
70
+ try {
71
+ results.entries.take(8).forEach { (id, result) ->
72
+ try { post("results", result); results.remove(id) }
73
+ catch (error: CrocheException) { if (error.code in listOf("not_found", "attachment_lost")) results.remove(id); throw error }
74
+ }
75
+ if (results.size < 32 && tasks.size < 16) {
76
+ val data = post("poll", identity())
77
+ if (!data.at("commands").isJsonArray) throw CrocheException("invalid_response", "Invalid broker command list")
78
+ data.at("commands").asJsonArray.take(8).forEach { accept(it) }
79
+ }
80
+ } catch (error: Exception) {
81
+ if (!closed.get()) {
82
+ try { onError?.invoke("Local control could not complete a request") } catch (_: Exception) {}
83
+ if (error is CrocheException && error.code == "attachment_lost") try { register() } catch (_: Exception) {}
84
+ }
85
+ }
86
+ try { Thread.sleep(100) } catch (_: InterruptedException) { if (closed.get()) break }
87
+ }
88
+ }, "croche-control-poll").apply { isDaemon = true; start() }
89
+ }
90
+ private fun accept(value: JsonElement) {
91
+ val id = value.at("request_id").text(); val command = value.at("command").text(); val payload = value.at("payload")
92
+ if (!validId(id) || command !in capabilities || !payload.isJsonObject) throw CrocheException("invalid_command", "Invalid broker command envelope")
93
+ if (handled.contains(id)) return
94
+ if (handled.size >= 1000) throw CrocheException("control_capacity", "Reattach after 1000 control requests")
95
+ handled.add(id); tasks.add(id)
96
+ val work = Runnable {
97
+ val reply = identity().apply { addProperty("request_id", id) }
98
+ try {
99
+ val result = execute(command, payload.asJsonObject.deepCopy(), id)
100
+ if (result.toString().toByteArray(Charsets.UTF_8).size > 900000) throw CrocheException("result_too_large", "Request a smaller result page")
101
+ reply.add("result", result.deepCopy())
102
+ } catch (error: Exception) {
103
+ val code = (error as? CrocheException)?.code
104
+ reply.add("error", obj("code" to str(if (code in publicCodes) code!! else "runtime_error"),
105
+ "message" to str("The Runtime command failed. Inspect it before retrying."),
106
+ "uncertain" to bool(command == "send" || command == "budget.set")))
107
+ } finally { tasks.remove(id) }
108
+ if (!closed.get()) results[id] = reply
109
+ }
110
+ try { workers.execute(work) }
111
+ catch (_: RejectedExecutionException) {
112
+ tasks.remove(id)
113
+ results[id] = identity().apply {
114
+ addProperty("request_id", id)
115
+ add("error", obj("code" to str("control_capacity"), "message" to str("Control workers are occupied"), "uncertain" to bool(false)))
116
+ }
117
+ }
118
+ }
119
+ private fun execute(command: String, payload: JsonObject, id: String): JsonElement {
120
+ if (closed.get()) throw CrocheException("control_closed", "Control is closed")
121
+ fun keys(allowed: Set<String>) { if (!allowed.containsAll(payload.keySet())) throw CrocheException("invalid_command", "Unsupported command fields") }
122
+ if (command == "send") {
123
+ keys(setOf("id", "text"))
124
+ val text = payload.at("text").text()
125
+ if (!validId(payload.at("id").text()) || text.isBlank() || text.length > 32000) throw CrocheException("invalid_command", "send needs immutable id and text only")
126
+ val signal = RuntimeCancellation(); active[id] = signal
127
+ try { return sendAdapter?.send(payload, signal) ?: runtime.send(payload, signal) }
128
+ finally { active.remove(id) }
129
+ }
130
+ if (command == "history") {
131
+ keys(setOf("offset", "limit"))
132
+ fun integer(key: String, default: Int, min: Int, max: Int): Int {
133
+ if (!payload.has(key)) return default
134
+ val value = payload[key]
135
+ if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber) throw CrocheException("invalid_command", "Invalid history page")
136
+ val number = value.asDouble
137
+ if (!number.isFinite() || number < min || number > max || number != kotlin.math.floor(number)) throw CrocheException("invalid_command", "Invalid history page")
138
+ return number.toInt()
139
+ }
140
+ val offset = integer("offset", 0, 0, 1000000); val limit = integer("limit", 100, 1, 200)
141
+ val history = runtime.inspect().at("history").asJsonArray; val page = JsonArray()
142
+ history.drop(offset).take(limit).forEach { page.add(it.deepCopy()) }
143
+ return obj("messages" to page, "total" to num(history.size()), "offset" to num(offset), "limit" to num(limit))
144
+ }
145
+ if (command == "budget.set") {
146
+ keys(setOf("amount")); val value = payload.at("amount")
147
+ if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber || !value.asDouble.isFinite() || value.asDouble < 0) throw CrocheException("invalid_command", "Budget requires a finite non-negative amount")
148
+ return runtime.adjustBudget(value.asDouble, absolute = true)
149
+ }
150
+ keys(emptySet())
151
+ if (command == "cancel") {
152
+ val pending = active.isNotEmpty(); active.values.forEach { it.cancel() }
153
+ val host = cancelAdapter?.cancel() ?: false
154
+ return obj("requested" to bool(pending || host), "scope" to str(if (cancelAdapter != null) "host" else "control_client"), "rollback" to bool(false))
155
+ }
156
+ if (command == "sync") runtime.sync()
157
+ val view = runtime.inspect()
158
+ return when (command) {
159
+ "status" -> view.at("status").deepCopy().asJsonObject.apply {
160
+ add("control", obj("cancellation_scope" to str(if (cancelAdapter != null) "host" else "control_client")))
161
+ }
162
+ "sync" -> view.at("status")
163
+ "tools" -> view.at("tools")
164
+ "budget.get" -> view.at("budget")
165
+ else -> throw CrocheException("unsupported_capability", "Unsupported Runtime command")
166
+ }
167
+ }
168
+ override fun close() {
169
+ if (!closed.compareAndSet(false, true)) return
170
+ active.values.forEach { it.cancel() }
171
+ try { post("unregister", identity()) } catch (_: Exception) {}
172
+ release()
173
+ if (Thread.currentThread() != poller) poller?.join(6000)
174
+ }
175
+ private fun release() { closed.set(true); lifetime.cancel(); effects.close(); workers.shutdown(); poller?.interrupt() }
176
+ }
177
+ private fun validId(value: String) = Regex("^[A-Za-z0-9_.:-]{1,200}$").matches(value)
178
+ private val publicCodes = setOf("invalid_command", "control_closed", "unsupported_capability", "result_too_large", "busy", "closed", "storage_error", "context_limit", "budget_limit")
@@ -0,0 +1,12 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+
5
+ class CrocheException(val code: String, override val message: String, val receipt: Receipt? = null) : RuntimeException("$code: $message")
6
+
7
+ internal fun obj(vararg fields: Pair<String, JsonElement>): JsonObject = JsonObject().apply { fields.forEach { add(it.first, it.second) } }
8
+ internal fun str(value: String): JsonElement = JsonPrimitive(value)
9
+ internal fun num(value: Number): JsonElement = JsonPrimitive(value)
10
+ internal fun bool(value: Boolean): JsonElement = JsonPrimitive(value)
11
+ internal fun JsonElement.at(key: String): JsonElement = if (isJsonObject) asJsonObject.get(key) ?: JsonNull.INSTANCE else JsonNull.INSTANCE
12
+ internal fun JsonElement.text(): String = if (isJsonPrimitive && asJsonPrimitive.isString) asString else ""
@@ -0,0 +1,120 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.CoreProject
5
+ import dev.croche.ffi.ProjectOpenOptions
6
+ import kotlinx.coroutines.Dispatchers
7
+ import kotlinx.coroutines.withContext
8
+ import kotlinx.coroutines.sync.Mutex
9
+ import kotlinx.coroutines.sync.withLock
10
+ import java.io.File
11
+
12
+ /** Project census, config selection, overrides, instances and durable ownership belong to Core. */
13
+ class Croche private constructor(private val binding: ProjectBinding) {
14
+ private val agents = mutableMapOf<CrocheRuntime, CrocheAgent>()
15
+ private val admission = Mutex()
16
+ val user: String? get() = binding.user
17
+ val installationId: String? get() = binding.installationId
18
+ val crocheUserId: String? get() = binding.crocheUserId
19
+ val agentIds: List<String> get() = binding.agentIds
20
+ suspend fun agent(id: String? = null, options: AgentOptions = AgentOptions()): CrocheAgent {
21
+ val encoded = JsonObject().apply {
22
+ options.instance?.let { addProperty("instance", it) }
23
+ options.fresh?.let { addProperty("fresh", it) }
24
+ options.config?.let { add("config", it.deepCopy()) }
25
+ }.toString()
26
+ return admission.withLock {
27
+ projectIO {
28
+ agents.entries.removeIf { it.key.isClosed }
29
+ val (core, runtime) = binding.agent(id, encoded)
30
+ agents.getOrPut(runtime) { CrocheAgent.adopt(core, runtime) }
31
+ }
32
+ }
33
+ }
34
+ suspend fun close() = admission.withLock {
35
+ projectIO { try { binding.close() } finally { agents.clear() } }
36
+ }
37
+ companion object {
38
+ suspend fun open(options: OpenOptions): Croche {
39
+ val owned = options.owned()
40
+ var created: Croche? = null
41
+ return try { projectIO {
42
+ val platform = projectPlatform(owned)
43
+ val pals = factory(owned, platform)
44
+ val pending = mutableListOf<JsonObject>()
45
+ val lock = Any()
46
+ var binding: ProjectBinding? = null
47
+ fun usage(event: JsonElement) = synchronized(lock) {
48
+ val value = event.asJsonObject.deepCopy()
49
+ val project = binding
50
+ if (project == null) pending.add(value)
51
+ else notifyUsage(owned, project, value)
52
+ }
53
+ try {
54
+ val core = CoreProject.open(pals,
55
+ ProjectOpenOptions(owned.hostJson(platform.attestor).toString(), owned.user,
56
+ owned.config.toString(), owned.handlers.keys.toList(), owned.language,
57
+ owned.streaming ?: true, owned.backgroundSync ?: true,
58
+ (owned.maintenanceIntervalMs ?: 60_000).toDouble()),
59
+ owned.onUsage?.let { EventHook(::usage) },
60
+ owned.onDebugEvent?.let { callback -> EventHook { event -> try { callback(event.asJsonObject) } catch (_: Throwable) {} } })
61
+ val bound = ProjectBinding(core, pals)
62
+ synchronized(lock) { binding = bound; pending.forEach { notifyUsage(owned, bound, it) }; pending.clear() }
63
+ Croche(bound).also { created = it; ProjectOpenSeam.opened?.invoke(it) }
64
+ } catch (error: Exception) { pals.release(); throw crocheError(error) }
65
+ } } catch (cancelled: kotlinx.coroutines.CancellationException) {
66
+ // IO's cancellable return must not strand a project the caller never received.
67
+ withContext(kotlinx.coroutines.NonCancellable) { created?.close() }
68
+ throw cancelled
69
+ }
70
+ }
71
+ suspend fun deleteStore(options: OpenOptions, agent: String? = null) {
72
+ val owned = options.copy(config = options.config.deepCopy(), handlers = emptyMap(),
73
+ backgroundSync = false, attestation = Attestation.OFF)
74
+ projectIO {
75
+ val platform = projectPlatform(owned)
76
+ val pals = factory(owned, platform)
77
+ try { dev.croche.ffi.deleteStore(pals, owned.hostJson(null).toString(), owned.user, owned.config.toString(), agent) }
78
+ finally { pals.release() }
79
+ }
80
+ }
81
+ private fun notifyUsage(options: OpenOptions, binding: ProjectBinding, event: JsonObject) {
82
+ try {
83
+ ProjectUsageSeam.beforeObserver?.invoke()
84
+ event.add("user", options.user?.let(::JsonPrimitive) ?: JsonNull.INSTANCE)
85
+ event.add("crocheUserId", binding.usageUserId?.let(::JsonPrimitive) ?: JsonNull.INSTANCE)
86
+ options.onUsage?.invoke(event)
87
+ } catch (_: Throwable) { /* observers cannot break Core */ }
88
+ }
89
+ private fun factory(options: OpenOptions, platform: ProjectPlatform): ProjectPals {
90
+ val host = options.hostJson(platform.attestor)
91
+ val zone = projectTimeZone(options.timeZone)
92
+ return ProjectPals { slot ->
93
+ val identity = projectPalRoute(slot).identity(host, options.user)
94
+ val key = CrocheRuntime.identity(identity).asJsonObject["storageKey"].asString
95
+ val safe = key.replace(Regex("[^A-Za-z0-9._-]"), "_")
96
+ KotlinHost(FileRuntimeStorage(File(platform.directory, "$safe.json")), platform.secretStorage(safe),
97
+ platform.attestor, options.http ?: RuntimeHttpURLConnection(), options.handlers.mapValues { (_, handler) ->
98
+ ToolHandler { invocation, context ->
99
+ try { handler.execute(invocation, context) }
100
+ catch (error: Throwable) {
101
+ if (error is CrocheException && error.code == "invalid_tool_result") throw error
102
+ throw CrocheException("effect_failed", "The application tool failed")
103
+ }
104
+ }
105
+ },
106
+ options.backgroundSync ?: true, projectDirectory = options.projectDirectory,
107
+ user = options.user, timeZone = zone)
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ internal suspend fun <T> projectIO(body: () -> T): T = withContext(Dispatchers.IO) {
114
+ try { body() } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } catch (error: Exception) { throw crocheError(error) }
115
+ }
116
+
117
+ /** Host-only race gate at IO's cancellable return; never set by an app. */
118
+ internal object ProjectOpenSeam { @Volatile var opened: ((Croche) -> Unit)? = null }
119
+
120
+ internal object ProjectUsageSeam { @Volatile var beforeObserver: (() -> Unit)? = null }
@@ -0,0 +1,116 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.CoreRuntime
5
+ import kotlinx.coroutines.*
6
+ import java.util.concurrent.atomic.AtomicBoolean
7
+
8
+ /** One project agent; the existing Runtime owns its production PAL and subscription kernel. */
9
+ class CrocheAgent private constructor(private val core: CoreRuntime, private val runtime: CrocheRuntime) {
10
+ private val lifecycle = kotlinx.coroutines.sync.Mutex()
11
+ private val retired = AtomicBoolean()
12
+ private val callbacks = CoroutineScope(SupervisorJob() + Dispatchers.Default)
13
+ val id: String = core.agentId()
14
+ val instance: String? = core.instance()
15
+ val created: Boolean = core.created()
16
+ val logId: String = core.logId()
17
+ @Volatile private var lastName = core.name()
18
+ @Volatile private var lastMode = core.mode()
19
+ @Volatile private var lastVisible = core.visibleTools()
20
+ val closed: Boolean get() = retired.get() || runtime.isClosed
21
+ val name: String? get() = if (closed) lastName else native { core.name() }.also { lastName = it }
22
+ val mode: String? get() = if (closed) lastMode else native { core.mode() }.also { lastMode = it }
23
+ val visibleTools: List<String>? get() = if (closed) lastVisible?.toList() else native { core.visibleTools() }.also { lastVisible = it }
24
+ private fun requireOpen() { if (closed) throw CrocheException("closed", "The agent is closed") }
25
+ private fun <T> native(body: () -> T): T {
26
+ requireOpen()
27
+ return try { body() } catch (error: Exception) { throw crocheError(error) }
28
+ }
29
+ suspend fun setTools(visible: List<String>?) {
30
+ val owned = visible?.toList()
31
+ projectIO { native { core.setTools(owned) }; lastVisible = core.visibleTools() }
32
+ }
33
+ suspend fun setMode(mode: String?) { projectIO { native { core.setMode(mode) }; lastMode = core.mode() } }
34
+ suspend fun sync() { projectIO { native { core.sync() } } }
35
+ suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt {
36
+ requireOpen(); return runtime.send(input, options)
37
+ }
38
+ suspend fun request(input: SendInput, options: RequestOptions = RequestOptions()): RequestResult {
39
+ requireOpen()
40
+ return runtime.request(input, SendOptions(options.responseFormat), options.wait).also { memory.refreshQuietly() }
41
+ }
42
+ fun subscribe(options: SubscribeOptions): AgentSubscription {
43
+ // Opening synchronously preserves replacement order and an immediate history call's generation.
44
+ val collection = runtime.openSubscription(options.initialMessages ?: if (options.after == null) 50 else null, options.after)
45
+ return AgentSubscription(collection, options.onEvent, callbacks)
46
+ }
47
+ suspend fun history(options: HistoryOptions) { requireOpen(); runtime.history(options.before, options.limit) }
48
+ suspend fun clearHistory() { requireOpen(); runtime.clearHistory(); memory.refreshQuietly() }
49
+ suspend fun cancel(id: String? = null) {
50
+ requireOpen()
51
+ if (id != null) runtime.cancel(id) else projectIO { native { core.cancelTurn() } }
52
+ }
53
+ suspend fun close() {
54
+ lifecycle.lock()
55
+ try {
56
+ if (!retired.compareAndSet(false, true)) return
57
+ projectIO { runtime.close() }
58
+ } finally { lifecycle.unlock() }
59
+ }
60
+ val memory = Memory()
61
+ inner class Memory {
62
+ @Volatile private var snapshot = runtime.memory().asJsonObject.deepCopy()
63
+ operator fun invoke(): JsonObject = snapshot.deepCopy()
64
+ private suspend fun <T> operation(body: () -> T): T {
65
+ requireOpen()
66
+ return projectIO { body() }.also { result ->
67
+ val deferred = result === WriteResult.Deferred ||
68
+ (result is JsonObject && result.at("deferred").let { it.isJsonPrimitive && it.asBoolean })
69
+ if (!deferred) refreshQuietly()
70
+ }
71
+ }
72
+ internal suspend fun refreshQuietly() {
73
+ if (closed) return
74
+ try { snapshot = projectIO { runtime.memory().asJsonObject.deepCopy() } } catch (_: CrocheException) {}
75
+ }
76
+ suspend fun list(): JsonArray = operation { runtime.memory.list() }
77
+ suspend fun delete(id: String): JsonObject = operation { runtime.memory.delete(id) }
78
+ suspend fun clear(): JsonObject = operation { runtime.memory.clear() }
79
+ suspend fun enabled(on: Boolean): WriteResult<Boolean> = operation { runtime.memory.enabled(on) }
80
+ suspend fun export(): JsonObject = operation { runtime.memory.export() }
81
+ fun onChanged(listener: ((MemoryChangedEvent) -> Unit)?) {
82
+ requireOpen()
83
+ try { runtime.memory.onChanged(listener?.let { callback -> { value -> try { callback(value.asJsonObject) } catch (_: Throwable) {} } }) }
84
+ catch (error: Exception) { throw crocheError(error) }
85
+ }
86
+ }
87
+ internal companion object { fun adopt(core: CoreRuntime, runtime: CrocheRuntime) = CrocheAgent(core, runtime) }
88
+ }
89
+
90
+ /** A generation-pinned subscription; closing it leaves canonical request observation alive. */
91
+ class AgentSubscription internal constructor(
92
+ private val collection: StreamHub.Collection,
93
+ private val onEvent: suspend (RuntimeEvent) -> Unit,
94
+ scope: CoroutineScope,
95
+ ) {
96
+ private val completion = CompletableDeferred<AppStreamEnd>()
97
+ val ended: Deferred<AppStreamEnd> get() = completion
98
+ init {
99
+ scope.launch {
100
+ var code = "closed"
101
+ try {
102
+ collection.deliver { event ->
103
+ if (event is RuntimeEvent.StreamError) code = event.code
104
+ if (event === RuntimeEvent.Replaced) code = "replaced"
105
+ onEvent(event)
106
+ }
107
+ } catch (failure: Throwable) {
108
+ code = "handler_failed"
109
+ collection.close()
110
+ try { onEvent(RuntimeEvent.StreamError(code, "Event handler failed", false)) } catch (_: Throwable) {}
111
+ } finally { completion.complete(AppStreamEnd(code)) }
112
+ }
113
+ }
114
+ fun close() = collection.close()
115
+ suspend fun history(options: HistoryOptions) = collection.history(options.before, options.limit)
116
+ }