@h1r-ai/croche-react-native 0.5.0 → 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/README.md +12 -1
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +6 -5
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +8 -1
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +1 -1
- 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 +13 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +14 -3
- 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/ProjectTypes.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +27 -11
- 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/ios/CrocheRuntimeBridge.swift +26 -4
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +4 -1
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +2 -1
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
- package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +57 -10
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +103 -9
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +22 -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/libcroche_ffi.a +0 -0
- package/package.json +3 -3
- package/src/project.ts +9 -1
package/README.md
CHANGED
|
@@ -189,7 +189,10 @@ result to another as an app event, `send({ id, text, kind: 'event' })`, or as tr
|
|
|
189
189
|
- `send({ id, text, kind: 'event' })` is a turn your app starts ("night fell", "the quest
|
|
190
190
|
is complete"). It costs a model call like any turn.
|
|
191
191
|
- `send({ id, text, context: { screen: 'cart', items: 3 } })` gives the model the current
|
|
192
|
-
app state
|
|
192
|
+
app state, kept apart from the person's words. It is useful when the request needs app
|
|
193
|
+
state: a command or button acting on app data, or after that state changed. Without it,
|
|
194
|
+
an input carries only the message; earlier states remain in history as sent until folded.
|
|
195
|
+
They are not a live view of the app. Tools must check authoritative app data themselves.
|
|
193
196
|
|
|
194
197
|
## Documents the character can look up
|
|
195
198
|
|
|
@@ -323,6 +326,10 @@ while the app runs, and at each return to the foreground. `runtime.deliverDue()`
|
|
|
323
326
|
registers the earliest note with the OS, so it can come while the app is not running:
|
|
324
327
|
BGTaskScheduler on iOS, WorkManager on Android.
|
|
325
328
|
|
|
329
|
+
`Croche.open` does not offer `backgroundDelivery` yet: a project refuses it with
|
|
330
|
+
`invalid_configuration`, and its agents deliver due notes while the app runs and at each return
|
|
331
|
+
to the foreground.
|
|
332
|
+
|
|
326
333
|
iOS app setup:
|
|
327
334
|
1. Info.plist: add the identifier to `BGTaskSchedulerPermittedIdentifiers`.
|
|
328
335
|
2. Background Modes: check **Background fetch**.
|
|
@@ -384,6 +391,10 @@ cargo-ndk and the Android NDK. The JavaScript side is tested against the real Co
|
|
|
384
391
|
|
|
385
392
|
## Cancel, retry, restart
|
|
386
393
|
|
|
394
|
+
On a project agent, `agent.cancel()` without an id stops the running turn and resolves at once:
|
|
395
|
+
unlike TypeScript, where it resolves once the stop is saved, the stop is not yet durable when it
|
|
396
|
+
resolves on React Native (and on native Swift and Kotlin).
|
|
397
|
+
|
|
387
398
|
- A `send` made while a turn runs is held, never refused as busy: the sends held behind a turn
|
|
388
399
|
go together as the next turn, each in its own channel.
|
|
389
400
|
- Held sends keep the order your `send` calls were made in: their `input.queued` positions and
|
|
@@ -23,6 +23,7 @@ import dev.croche.ffi.CancelCallback
|
|
|
23
23
|
import dev.croche.ffi.CancelToken
|
|
24
24
|
import dev.croche.ffi.HostPal
|
|
25
25
|
import dev.croche.ffi.HostPalFactory
|
|
26
|
+
import dev.croche.projectPalRoute
|
|
26
27
|
import dev.croche.KotlinHost
|
|
27
28
|
import dev.croche.RuntimeHttpURLConnection
|
|
28
29
|
import dev.croche.keepAttached
|
|
@@ -611,14 +612,14 @@ class CrocheRuntimeModule(context: ReactApplicationContext) : NativeCrocheRuntim
|
|
|
611
612
|
private val runtimeOptions = options.get("runtime")?.takeIf { it.isJsonObject }?.asJsonObject ?: options
|
|
612
613
|
private val hostConfig = options.getAsJsonObject("host")
|
|
613
614
|
private val user = options.get("user")?.takeUnless { it.isJsonNull }?.asString
|
|
615
|
+
private val timeZone = projectZone(options)
|
|
614
616
|
private val tools = options.getAsJsonArray("handlers")?.map { it.asString } ?: emptyList()
|
|
615
617
|
val attestor = projectAttestor(options) { PlayIntegrityAttestor(reactApplicationContext, it) }
|
|
616
618
|
override fun pal(agent: String): HostPal {
|
|
617
619
|
keepAttached()
|
|
618
620
|
val id = agent
|
|
619
|
-
val
|
|
620
|
-
|
|
621
|
-
}
|
|
621
|
+
val route = projectPalRoute(id)
|
|
622
|
+
val identity = route.identity(hostConfig, user)
|
|
622
623
|
val key = CrocheRuntime.identity(identity).asJsonObject.get("storageKey").asString
|
|
623
624
|
val safe = key.replace(Regex("[^A-Za-z0-9._-]"), "_")
|
|
624
625
|
val pending = ConcurrentHashMap<String, CompletableFuture<JsonElement>>()
|
|
@@ -626,8 +627,8 @@ class CrocheRuntimeModule(context: ReactApplicationContext) : NativeCrocheRuntim
|
|
|
626
627
|
KeystoreSecretStore(reactApplicationContext, safe), attestor, RuntimeHttpURLConnection(),
|
|
627
628
|
tools.associateWith { withResult { _, context ->
|
|
628
629
|
projectToolResult(pending[context.callId] ?: throw ToolNotDispatched())
|
|
629
|
-
} }, runtimeOptions.get("backgroundSync")?.asBoolean ?: true)
|
|
630
|
-
.also { hosts[id] = it; allHosts.add(it) }
|
|
630
|
+
} }, runtimeOptions.get("backgroundSync")?.asBoolean ?: true, timeZone = timeZone)
|
|
631
|
+
.also { if (!route.maintenance) hosts[id] = it; allHosts.add(it) }
|
|
631
632
|
return object : HostPal by host {
|
|
632
633
|
override fun tool(invocation: String, cancel: CancelToken): dev.croche.ffi.ToolOutput {
|
|
633
634
|
keepAttached()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonObject
|
|
4
|
+
import dev.croche.CrocheException
|
|
5
|
+
import dev.croche.projectTimeZone
|
|
6
|
+
import java.util.TimeZone
|
|
7
|
+
|
|
8
|
+
/** Parse before CoreProject.open; never silently fall back to GMT for an unknown zone. */
|
|
9
|
+
internal fun projectZone(options: JsonObject): TimeZone? =
|
|
10
|
+
projectTimeZone(options.get("timeZone")?.takeUnless { it.isJsonNull }?.let {
|
|
11
|
+
if (!it.isJsonPrimitive || !it.asJsonPrimitive.isString)
|
|
12
|
+
throw CrocheException("invalid_configuration", "timeZone must be an IANA time zone")
|
|
13
|
+
it.asString
|
|
14
|
+
})
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonParser
|
|
4
|
+
import dev.croche.CrocheException
|
|
5
|
+
import org.junit.Assert.*
|
|
6
|
+
import org.junit.Test
|
|
7
|
+
|
|
8
|
+
class ProjectTimeZoneTest {
|
|
9
|
+
private fun options(json: String) = JsonParser.parseString(json).asJsonObject
|
|
10
|
+
|
|
11
|
+
@Test fun passedZoneChangesTheOffset() {
|
|
12
|
+
assertEquals(-600, projectZone(options("""{"timeZone":"Pacific/Honolulu"}"""))!!.getOffset(0) / 60_000)
|
|
13
|
+
}
|
|
14
|
+
@Test fun absentAndNullKeepTheDeviceZone() {
|
|
15
|
+
assertNull(projectZone(options("{}")))
|
|
16
|
+
assertNull(projectZone(options("""{"timeZone":null}""")))
|
|
17
|
+
}
|
|
18
|
+
@Test fun badZoneAndNonStringAreInvalidConfiguration() {
|
|
19
|
+
for (json in listOf("""{"timeZone":"Not/AZone"}""", """{"timeZone":42}""")) {
|
|
20
|
+
try { projectZone(options(json)); fail("Invalid timeZone accepted") }
|
|
21
|
+
catch (error: CrocheException) { assertEquals("invalid_configuration", error.code) }
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt
CHANGED
|
@@ -9,7 +9,8 @@ import java.io.File
|
|
|
9
9
|
/** Internal Android startup hook: the install's records use filesDir, regardless of its stores. */
|
|
10
10
|
internal class CrocheProjectRecordProvider : ContentProvider() {
|
|
11
11
|
override fun onCreate(): Boolean {
|
|
12
|
-
|
|
12
|
+
app = context?.applicationContext
|
|
13
|
+
location = app?.filesDir
|
|
13
14
|
return true
|
|
14
15
|
}
|
|
15
16
|
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
|
@@ -19,7 +20,13 @@ internal class CrocheProjectRecordProvider : ContentProvider() {
|
|
|
19
20
|
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
|
20
21
|
|
|
21
22
|
companion object {
|
|
23
|
+
@Volatile private var app: android.content.Context? = null
|
|
22
24
|
@Volatile private var location: File? = null
|
|
23
25
|
@JvmStatic fun directory(): File? = location
|
|
26
|
+
@JvmStatic fun language(): String = android.os.LocaleList.getDefault()[0].toLanguageTag()
|
|
27
|
+
@JvmStatic fun secretStorage(name: String): dev.croche.RuntimeSecretStore =
|
|
28
|
+
KeystoreSecretStore(checkNotNull(app) { "Croche startup provider is not initialized" }, name)
|
|
29
|
+
@JvmStatic fun attestor(number: Long): dev.croche.RuntimeAttestor =
|
|
30
|
+
PlayIntegrityAttestor(checkNotNull(app) { "Croche startup provider is not initialized" }, number)
|
|
24
31
|
}
|
|
25
32
|
}
|
|
@@ -6,4 +6,4 @@
|
|
|
6
6
|
-keep class dev.croche.ffi.** { *; }
|
|
7
7
|
|
|
8
8
|
# The JVM host discovers Android's app-private project location through this startup hook.
|
|
9
|
-
-keep class dev.croche.android.CrocheProjectRecordProvider { public static java.io.File directory(); }
|
|
9
|
+
-keep class dev.croche.android.CrocheProjectRecordProvider { public static java.io.File directory(); public static java.lang.String language(); public static dev.croche.RuntimeSecretStore secretStorage(java.lang.String); public static dev.croche.RuntimeAttestor attestor(long); }
|
|
@@ -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
|
+
}
|
|
@@ -14,7 +14,9 @@ data class ToolContext(val callId: String, val messageId: String, val userId: St
|
|
|
14
14
|
/** Present when the Runtime config has an agentId. Last, with a default, so existing destructuring is unchanged. */
|
|
15
15
|
val agentId: String? = null,
|
|
16
16
|
/** Where a [withResult] handler leaves its images for this call (set by the Runtime). */
|
|
17
|
-
val images: ToolImages? = null
|
|
17
|
+
val images: ToolImages? = null,
|
|
18
|
+
val user: String? = null, val crocheUserId: String? = null,
|
|
19
|
+
val causedBy: List<String> = emptyList(), val origin: String = "app")
|
|
18
20
|
fun interface ToolHandler { fun execute(invocation: CommandInvocation, context: ToolContext): JsonElement }
|
|
19
21
|
|
|
20
22
|
/** One wiki document: a path such as `menu/stew.md` and its markdown (at most 64 KB; 2,000
|
|
@@ -94,6 +96,8 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
|
|
|
94
96
|
val logId: String get() = subscriptions().logId
|
|
95
97
|
internal val state: RuntimeEvent.State get() = subscriptions().state
|
|
96
98
|
@Volatile private var closed = false
|
|
99
|
+
internal val isClosed: Boolean get() = closed
|
|
100
|
+
internal fun openSubscription(initial: Int?, after: Cursor?) = subscriptions().openCollection(initial, after)
|
|
97
101
|
@Volatile private var onDelivery: ((JsonElement) -> Unit)? = null
|
|
98
102
|
companion object {
|
|
99
103
|
/** Test-only gate-10 probe; called on the thread that invokes each native stream-port call. */
|
|
@@ -143,12 +147,18 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
|
|
|
143
147
|
val core = try { CoreRuntime.open(host, bound.toString(), options, onEvent?.let { EventHook(it) }, onUsage?.let { EventHook(it) }) }
|
|
144
148
|
catch (error: Exception) { host.release(); throw crocheError(error) }
|
|
145
149
|
if (onDebugEvent != null) try { core.setDebugObserver(EventHook(onDebugEvent), false) } catch (_: Exception) {}
|
|
150
|
+
val runtime = adopt(core, host)
|
|
151
|
+
if (wiki != null) try { runtime.wiki.set(wiki) } catch (error: Exception) { runtime.close(); throw error }
|
|
152
|
+
return runtime
|
|
153
|
+
}
|
|
154
|
+
/** Adopts a project-owned Runtime through the same production stream boundary as create. */
|
|
155
|
+
internal fun adopt(core: CoreRuntime, host: KotlinHost): CrocheRuntime {
|
|
146
156
|
val port = NativeCoreStreamPort(core, host)
|
|
147
157
|
val hub = try { StreamHub(port) } catch (error: Exception) { port.close(); throw crocheError(error) }
|
|
148
158
|
val runtime = CrocheRuntime(core, host, hub, port)
|
|
149
|
-
|
|
159
|
+
val weak = java.lang.ref.WeakReference(runtime)
|
|
160
|
+
host.deliver = { weak.get()?.deliverDue(); Unit }
|
|
150
161
|
host.attach(core)
|
|
151
|
-
if (wiki != null) try { runtime.wiki.set(wiki) } catch (error: Exception) { runtime.close(); throw error }
|
|
152
162
|
return runtime
|
|
153
163
|
}
|
|
154
164
|
fun identity(config: JsonObject, libraryName: String = LIBRARY): JsonElement {
|
|
@@ -20,6 +20,12 @@ import java.util.concurrent.atomic.AtomicBoolean
|
|
|
20
20
|
/** The code the Runtime reads as "nothing ran" (croche_core::NOT_DISPATCHED). */
|
|
21
21
|
private const val NOT_DISPATCHED = "tool_not_dispatched"
|
|
22
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
|
+
|
|
23
29
|
internal fun failure(error: Throwable): FfiException = when (error) {
|
|
24
30
|
is FfiException -> error
|
|
25
31
|
is CrocheException -> FfiException.Failure(error.code, error.message)
|
|
@@ -82,7 +88,9 @@ internal class KotlinHost(
|
|
|
82
88
|
tools: Map<String, ToolHandler>, private val background: Boolean,
|
|
83
89
|
private val osScheduler: RuntimeScheduler? = null,
|
|
84
90
|
projectDirectory: java.io.File? = null,
|
|
85
|
-
defaultDirectory: () -> java.io.File? = ::defaultProjectDirectory
|
|
91
|
+
defaultDirectory: () -> java.io.File? = ::defaultProjectDirectory,
|
|
92
|
+
private val user: String? = null,
|
|
93
|
+
private val timeZone: TimeZone? = null
|
|
86
94
|
) : HostPal {
|
|
87
95
|
private val projectRecords = ProjectRecords { projectRecordDirectory(projectDirectory, defaultDirectory()) }
|
|
88
96
|
internal var beforeProjectLock: (() -> Unit)? = null
|
|
@@ -274,7 +282,10 @@ internal class KotlinHost(
|
|
|
274
282
|
val value = tools.run(signal(cancel)) { local ->
|
|
275
283
|
handler.execute(request, ToolContext(context.at("callId").text(),
|
|
276
284
|
context.at("messageId").text(), context.at("userId").text(), local,
|
|
277
|
-
context.at("agentId").text().ifEmpty { null }, sink
|
|
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" }))
|
|
278
289
|
}
|
|
279
290
|
// A plain handler's JSON is the value as it was; a `withResult` one's images ride beside
|
|
280
291
|
// it, one sink per call (never shared between concurrent calls).
|
|
@@ -295,7 +306,7 @@ internal class KotlinHost(
|
|
|
295
306
|
|
|
296
307
|
// Clock, entropy, timer
|
|
297
308
|
override fun nowMs(): Double = clock().toDouble()
|
|
298
|
-
override fun utcOffsetMinutes(atMs: Double): Long = TimeZone.getDefault().getOffset(atMs.toLong()).toLong() / 60_000
|
|
309
|
+
override fun utcOffsetMinutes(atMs: Double): Long = (timeZone ?: TimeZone.getDefault()).getOffset(atMs.toLong()).toLong() / 60_000
|
|
299
310
|
override fun random(): String = UUID.randomUUID().toString()
|
|
300
311
|
override fun wake(atMs: Double?) {
|
|
301
312
|
synchronized(lock) { wakeTarget = atMs }
|
|
@@ -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())
|