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