@h1r-ai/croche-react-native 0.5.5 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -458
- package/THIRD-PARTY-NOTICES +7 -8
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
- package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -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/dist/package.json +1 -0
- package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
- package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
- package/dist/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +193 -0
- package/dist/react-native/src/core-wire.d.ts +38 -0
- package/dist/react-native/src/core-wire.js +1 -0
- package/dist/react-native/src/native-module.d.ts +8 -0
- package/dist/react-native/src/native-module.js +53 -0
- package/dist/rn-shared-build.json +16 -0
- package/dist/runtime/src/agent.d.ts +43 -0
- package/dist/runtime/src/agent.js +75 -0
- package/dist/runtime/src/app-api.d.ts +284 -0
- package/dist/runtime/src/app-api.js +1 -0
- package/dist/runtime/src/cancel.d.ts +9 -0
- package/dist/runtime/src/cancel.js +24 -0
- package/dist/runtime/src/core/port.d.ts +234 -0
- package/dist/runtime/src/core/port.js +1 -0
- package/dist/runtime/src/core/wasm.d.ts +1 -0
- package/dist/runtime/src/core/wasm.js +2 -0
- package/dist/runtime/src/croche.d.ts +42 -0
- package/dist/runtime/src/croche.js +111 -0
- package/dist/runtime/src/errors.d.ts +26 -0
- package/dist/runtime/src/errors.js +49 -0
- package/dist/runtime/src/events.d.ts +5 -0
- package/dist/runtime/src/events.js +31 -0
- package/dist/runtime/src/generated/app-stream.d.ts +174 -0
- package/dist/runtime/src/generated/app-stream.js +124 -0
- package/dist/runtime/src/index.native.d.ts +21 -0
- package/dist/runtime/src/index.native.js +8 -0
- package/dist/runtime/src/json.d.ts +13 -0
- package/dist/runtime/src/json.js +120 -0
- package/dist/runtime/src/native-adapter.d.ts +3 -0
- package/dist/runtime/src/native-adapter.js +24 -0
- package/dist/runtime/src/pal/codec.d.ts +15 -0
- package/dist/runtime/src/pal/codec.js +52 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +35 -0
- package/dist/runtime/src/pal/platform.d.ts +16 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- package/dist/runtime/src/rn-entry.d.ts +1 -0
- package/dist/runtime/src/rn-entry.js +4 -0
- package/dist/runtime/src/run-tool.d.ts +33 -0
- package/dist/runtime/src/run-tool.js +7 -0
- package/dist/runtime/src/tools.d.ts +19 -0
- package/dist/runtime/src/tools.js +70 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +93 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +92 -0
- package/ios/CoreWireSupport.swift +111 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +46 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
- 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 +1342 -218
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +18 -8
- package/scripts/README.md +11 -0
- package/scripts/build-shared.mjs +46 -0
- package/scripts/build.mjs +11 -0
- package/scripts/vendor-native.sh +5 -4
- package/src/NativeCrocheRuntime.ts +12 -159
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/src/index.ts +0 -664
- package/src/project-types.ts +0 -35
- package/src/project.ts +0 -434
- package/src/protocol.ts +0 -28
- package/src/types.ts +0 -9
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import androidx.test.ext.junit.runners.AndroidJUnit4
|
|
4
|
+
import androidx.test.platform.app.InstrumentationRegistry
|
|
5
|
+
import com.google.gson.JsonArray
|
|
6
|
+
import com.google.gson.JsonParser
|
|
7
|
+
import dev.croche.ffi.*
|
|
8
|
+
import dev.croche.s7.CoreFactoryCalls
|
|
9
|
+
import dev.croche.s7.attached
|
|
10
|
+
import dev.croche.s7.nativePlatform
|
|
11
|
+
import java.io.File
|
|
12
|
+
import java.net.URI
|
|
13
|
+
import java.util.UUID
|
|
14
|
+
import java.util.concurrent.CopyOnWriteArrayList
|
|
15
|
+
import java.util.concurrent.CountDownLatch
|
|
16
|
+
import java.util.concurrent.TimeUnit
|
|
17
|
+
import kotlinx.coroutines.Dispatchers
|
|
18
|
+
import kotlinx.coroutines.runBlocking
|
|
19
|
+
import kotlinx.coroutines.withContext
|
|
20
|
+
import org.junit.Assert.*
|
|
21
|
+
import org.junit.Test
|
|
22
|
+
import org.junit.runner.RunWith
|
|
23
|
+
|
|
24
|
+
private const val CONFIG = """{"schema":7,"project":{"defaults":{"model":"google/gemini-3.8-flash"},
|
|
25
|
+
"languages":{"default":"en","supported":["en"]}},"agents":{"helper":{"instructions":"Reply briefly."}}}"""
|
|
26
|
+
private const val REGISTER = """{"runtime_token":"synthetic_______________________________________________________","project_id":"prj_test","user_id":"usr_test","gateway_key":{"gateway":"openrouter","base_url":"https://openrouter.ai/api/v1","key_id":"local","api_key":"synthetic","limit":1,"models":["google/gemini-3.8-flash"]}}"""
|
|
27
|
+
private const val SYNC = """{"protocol_version":1,"control_version":1,"project_id":"prj_test","host_budget_control":{"enabled":true,"currency":"USD","version":1,"expires_at":"2099-01-01T00:00:00Z","limits":{"max_user_allowance":2,"max_single_adjustment":0.5,"max_positive_adjustment_per_window":1},"window":{"type":"daily"}},"user_allowance":{"user_id":"usr_test","allowance":1,"policy_version":1},"runtime_policy":{}}"""
|
|
28
|
+
private fun frame(delta: String, finish: String = "null", usage: String = "") =
|
|
29
|
+
"data: {\"id\":\"gen-local\",\"model\":\"google/gemini-3.8-flash\",\"choices\":[{\"index\":0,\"delta\":$delta,\"finish_reason\":$finish}]$usage}\n\n"
|
|
30
|
+
private const val USAGE = ",\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":3,\"total_tokens\":13,\"cost\":0}"
|
|
31
|
+
private fun runs(command: String) = listOf(
|
|
32
|
+
frame("""{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"run_tool","arguments":"{\"cmd\":\"$command\"}"}}]}"""),
|
|
33
|
+
frame("{}", "\"tool_calls\"", USAGE), "data: [DONE]\n\n")
|
|
34
|
+
private val REPLY = listOf(frame("""{"role":"assistant","content":"Done."}"""), frame("{}", "\"stop\"", USAGE), "data: [DONE]\n\n")
|
|
35
|
+
|
|
36
|
+
/** Real asset path underneath; HTTP is answered in-process, never sent. The next model call runs `command`. */
|
|
37
|
+
private class WikiFakeHost(base: HostPal) : HostPal by base {
|
|
38
|
+
private val assets = base
|
|
39
|
+
val reads = CopyOnWriteArrayList<String>()
|
|
40
|
+
val bodies = CopyOnWriteArrayList<String>()
|
|
41
|
+
@Volatile var command: String? = null
|
|
42
|
+
override fun readAsset(path: String): ByteArray? { reads += path; return assets.readAsset(path) }
|
|
43
|
+
override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) {
|
|
44
|
+
val path = URI(request.url).path
|
|
45
|
+
if (path.endsWith("/chat/completions")) {
|
|
46
|
+
bodies += request.body ?: ""
|
|
47
|
+
val next = command; command = null
|
|
48
|
+
sink.head(200u, listOf(PalHeader("content-type", "text/event-stream")))
|
|
49
|
+
for (line in next?.let(::runs) ?: REPLY) if (!sink.chunk(line.toByteArray())) return
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
val body = when {
|
|
53
|
+
path.endsWith("/challenge") -> """{"challenge":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","attestation":"off"}"""
|
|
54
|
+
path.endsWith("/register") -> REGISTER
|
|
55
|
+
path.endsWith("/sync") -> SYNC
|
|
56
|
+
path.endsWith("/batch") -> {
|
|
57
|
+
val events = JsonParser.parseString(request.body ?: "{}").asJsonObject
|
|
58
|
+
.getAsJsonObject("payload")?.getAsJsonArray("events")
|
|
59
|
+
val accepted = events?.map { row ->
|
|
60
|
+
val o = row.asJsonObject; val p = o.getAsJsonObject("payload")
|
|
61
|
+
(p?.get("operation_id") ?: p?.get("adjustment_id") ?: o.get("message_id")).toString()
|
|
62
|
+
} ?: emptyList()
|
|
63
|
+
"""{"accepted":[${accepted.joinToString(",")}],"duplicate":[],"rejected":[]}"""
|
|
64
|
+
}
|
|
65
|
+
else -> throw CorePalException.Failure("network_error", "Refused unplanned request $path")
|
|
66
|
+
}
|
|
67
|
+
sink.head(200u, listOf(PalHeader("content-type", "application/json")))
|
|
68
|
+
sink.chunk(body.toByteArray())
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* A `{path, description, file}` document through RN Android's host (rnHostPal over the S7 AndroidCoreHost,
|
|
74
|
+
* the module's real pair) and its dispatch, with the real native Core. Storage is the platform store: the
|
|
75
|
+
* JS callback storage has no JS here and is not under test.
|
|
76
|
+
*/
|
|
77
|
+
@RunWith(AndroidJUnit4::class)
|
|
78
|
+
class WikiFileBridgeTest {
|
|
79
|
+
@Test fun aFileIsListedAtOpenReadOnFirstModelAccessAndMissingFailsOnRead() = runBlocking {
|
|
80
|
+
val file = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "wiki-${UUID.randomUUID()}.md")
|
|
81
|
+
val absent = File(file.parentFile, "absent-${UUID.randomUUID()}.md").toURI().toString()
|
|
82
|
+
file.writeText("Written before open.")
|
|
83
|
+
val uri = file.toURI().toString()
|
|
84
|
+
val pals = nativePlatform(InstrumentationRegistry.getInstrumentation().targetContext, null)
|
|
85
|
+
val host = WikiFakeHost(rnHostPal(pals.host))
|
|
86
|
+
val dispatch = CoreDispatch({ host }, { pals.storage },
|
|
87
|
+
openFactory = { json, registrations, _, actual, recoveryJson -> CoreFactoryCalls.open(json, registrations, pals.storage, actual, recoveryJson = recoveryJson) },
|
|
88
|
+
emit = { })
|
|
89
|
+
val options = """{"projectKey":"pk_wiki_file_fixture","user":"${UUID.randomUUID()}","bundledConfig":$CONFIG,"wiki":[
|
|
90
|
+
{"path":"policy.md","description":"Refund policy","file":"$uri"},{"path":"absent.md","description":"Gone","file":"$absent"}]}"""
|
|
91
|
+
val root = withContext(Dispatchers.IO) { dispatch.open(JsonArray().apply { add(options); add(JsonArray()); add("storage"); add("host") }) }
|
|
92
|
+
try {
|
|
93
|
+
val listed = JsonParser.parseString(dispatch.call(root, "wikiList", JsonArray()) as String).asJsonArray
|
|
94
|
+
assertEquals(setOf("policy.md", "absent.md"), listed.map { it.asJsonObject.get("path").asString }.toSet())
|
|
95
|
+
assertEquals(emptyList<String>(), host.reads.toList())
|
|
96
|
+
file.writeText("Written after open.")
|
|
97
|
+
val handle = dispatch.call(root, "agent", JsonArray().apply { add("helper"); add(com.google.gson.JsonNull.INSTANCE) }) as String
|
|
98
|
+
val agent: CoreAgent = dispatch.handles.get(handle)
|
|
99
|
+
val codes = CopyOnWriteArrayList<String>(); val failed = CountDownLatch(1)
|
|
100
|
+
val subscription = agent.subscribe("""{"initialMessages":0}""", attached(object : CoreEventSink {
|
|
101
|
+
override fun deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) {
|
|
102
|
+
val event = JsonParser.parseString(eventJson).asJsonObject
|
|
103
|
+
if (event.get("type")?.asString == "input") event.getAsJsonObject("error")?.get("code")?.asString?.let { codes += it; failed.countDown() }
|
|
104
|
+
// As the SDK's own sink: enter the delivery, then complete it, off Core's delivery call.
|
|
105
|
+
Thread { if (delivery.tryEnter()) delivery.complete("""{"outcome":"returned"}""") }.start()
|
|
106
|
+
}
|
|
107
|
+
}))
|
|
108
|
+
suspend fun read(path: String) = withContext(Dispatchers.IO) {
|
|
109
|
+
host.command = "wiki read $path"
|
|
110
|
+
agent.request("""{"id":"${UUID.randomUUID()}","input":[{"type":"text","text":"Read it"}]}""", emptyList(), null, null)
|
|
111
|
+
}
|
|
112
|
+
read("policy.md")
|
|
113
|
+
assertEquals(listOf(uri), host.reads.toList())
|
|
114
|
+
assertTrue(host.bodies.first().contains("Refund policy"))
|
|
115
|
+
assertTrue(host.bodies.last(), host.bodies.last().contains("Written after open."))
|
|
116
|
+
assertFalse(host.bodies.last(), host.bodies.last().contains("Written before open."))
|
|
117
|
+
assertEquals(emptyList<String>(), codes.toList())
|
|
118
|
+
read("absent.md")
|
|
119
|
+
assertTrue("no failed input event", failed.await(10, TimeUnit.SECONDS))
|
|
120
|
+
assertEquals(listOf("invalid_wiki"), codes.toList())
|
|
121
|
+
assertEquals(absent, host.reads.last())
|
|
122
|
+
subscription.shutdown()
|
|
123
|
+
} finally { dispatch.call(root, "shutdown", JsonArray()); file.delete() }
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import com.google.gson.*
|
|
4
|
+
import dev.croche.BindingFacts
|
|
5
|
+
import dev.croche.ffi.*
|
|
6
|
+
import dev.croche.s7.CoreFactoryCalls
|
|
7
|
+
import dev.croche.s7.attached
|
|
8
|
+
|
|
9
|
+
internal class CoreDispatch(
|
|
10
|
+
private val host: () -> HostPal,
|
|
11
|
+
private val platformStorage: () -> CoreStoragePal,
|
|
12
|
+
private val openFactory: suspend (String, List<CoreToolRegistration>, CoreStoragePal, HostPal, String?) -> CoreCroche =
|
|
13
|
+
{ json, registrations, storage, host, recovery -> CoreFactoryCalls.open(json, registrations, storage, host, rnBindingFacts, recovery) },
|
|
14
|
+
emit: (String) -> Unit,
|
|
15
|
+
) {
|
|
16
|
+
val handles = CoreHandles()
|
|
17
|
+
val callbacks = CoreCallbacks(emit)
|
|
18
|
+
private fun storage(a: JsonArray) = CallbackStorage(a.text(2), a.text(3), callbacks)
|
|
19
|
+
suspend fun open(a: JsonArray): String {
|
|
20
|
+
val registrations = a[1].asJsonArray.map {
|
|
21
|
+
val row = it.asJsonObject
|
|
22
|
+
CoreToolRegistration(handles.get(row.get("tool").asString), row.get("optionsJson")?.asString)
|
|
23
|
+
}
|
|
24
|
+
return handles.hold(openFactory(a.text(0), registrations, storage(a), host(), a.optional(4)))
|
|
25
|
+
}
|
|
26
|
+
fun call(id: String, method: String, a: JsonArray, images: List<CoreImageInput> = emptyList()): Any? {
|
|
27
|
+
if (method == "release") { handles.forget(id); return null }
|
|
28
|
+
if (id.isEmpty()) return when (method) {
|
|
29
|
+
"newCancel" -> handles.hold(CancelToken())
|
|
30
|
+
"defineTool" -> handles.hold(CoreToolDefinition(a.text(0), attached(NativeExecute(a.text(1), callbacks, handles))))
|
|
31
|
+
"webSearch" -> handles.hold(coreWebSearch())
|
|
32
|
+
"wakeTimes" -> coreWakeTimes(a.text(0), a.optional(1), attached(storage(a)), attached(host()))
|
|
33
|
+
// The same CoreEventSink/CoreDelivery protocol as subscribe; no fake ack.
|
|
34
|
+
"registerBackground" -> coreRegisterBackground(a.text(0), a.optional(1)?.let { attached(NativeSink(it, callbacks, handles)) }, attached(storage(a)), a.optional(4)?.let { attached(platformStorage()) }, attached(host()), rnBindingFacts).let { null }
|
|
35
|
+
else -> error("Unknown native module method")
|
|
36
|
+
}
|
|
37
|
+
val owner = handles.value(id)
|
|
38
|
+
if (owner is CancelToken) return when (method) { "cancel" -> owner.cancel().let { null }; "isCancelled" -> owner.isCancelled(); else -> error("Unknown cancel method") }
|
|
39
|
+
if (owner is CoreDelivery) return when (method) {
|
|
40
|
+
"tryEnter" -> owner.tryEnter().also { if (!it) handles.forget(id) }
|
|
41
|
+
"complete" -> owner.complete(a.text(0)).also { handles.forget(id) }.let { null }
|
|
42
|
+
else -> error("Unknown delivery method")
|
|
43
|
+
}
|
|
44
|
+
if (owner is CoreToolDefinition) { check(method == "name"); return owner.name() }
|
|
45
|
+
if (owner is CoreCroche) return when (method) {
|
|
46
|
+
"runTool" -> owner.runTool(a.text(0), a.text(1), a.text(2), handles.get(a.text(3)))
|
|
47
|
+
"agent" -> handles.hold(owner.agent(a.text(0), a.optional(1)))
|
|
48
|
+
"deleteData" -> owner.deleteData(a.optional(0)).let { null }
|
|
49
|
+
"agentIds" -> owner.agentIds()
|
|
50
|
+
"deliverDue" -> owner.deliverDue(a.optional(0), handles.get(a.text(1)))
|
|
51
|
+
"wikiList" -> owner.wikiList()
|
|
52
|
+
"wikiPut" -> owner.wikiPut(a.text(0)).let { null }
|
|
53
|
+
"wikiRemove" -> owner.wikiRemove(a.text(0)).let { null }
|
|
54
|
+
"debugAttach" -> owner.debugAttach(a.text(0))
|
|
55
|
+
"debugDetach" -> owner.debugDetach().let { null }
|
|
56
|
+
"shutdown" -> owner.shutdown().let { null }
|
|
57
|
+
else -> error("Unknown project method")
|
|
58
|
+
}
|
|
59
|
+
if (owner is CoreAgentInterface) return when (method) {
|
|
60
|
+
"id" -> owner.id(); "instance" -> owner.instance()
|
|
61
|
+
"send" -> owner.send(a.text(0), images, a.optional(1), handles.get(a.text(2)))
|
|
62
|
+
"request" -> owner.request(a.text(0), images, a.optional(1), handles.get(a.text(2)))
|
|
63
|
+
"subscribe" -> handles.hold(owner.subscribe(a.text(0), attached(NativeSink(a.text(1), callbacks, handles))))
|
|
64
|
+
"cancel" -> owner.cancel(a.optional(0)).let { null }
|
|
65
|
+
"clearHistory" -> owner.clearHistory().let { null }
|
|
66
|
+
"memoryList" -> owner.memoryList(); "memoryDelete" -> owner.memoryDelete(a.text(0)).let { null }
|
|
67
|
+
"memoryClear" -> owner.memoryClear().let { null }; "memoryEnabled" -> owner.memoryEnabled(a[0].asBoolean).let { null }
|
|
68
|
+
"setTools" -> owner.setTools(a.text(0)).let { null }; "resetTools" -> owner.resetTools().let { null }
|
|
69
|
+
"setWiki" -> owner.setWiki(a.text(0)).let { null }; "resetWiki" -> owner.resetWiki().let { null }
|
|
70
|
+
"shutdown" -> owner.shutdown().let { null }; else -> error("Unknown agent method")
|
|
71
|
+
}
|
|
72
|
+
if (owner is CoreSubscription) return when (method) {
|
|
73
|
+
"history" -> owner.history(a.text(0)).let { null }; "ended" -> owner.ended(); "shutdown" -> owner.shutdown().let { null }
|
|
74
|
+
else -> error("Unknown subscription method")
|
|
75
|
+
}
|
|
76
|
+
error("Unknown native handle type")
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The bridge's own binding facts: sdk "react-native" (BindingFacts, from the SDK sources it builds). */
|
|
81
|
+
internal val rnBindingFacts: String = BindingFacts.json("react-native")
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
package dev.croche.reactnative
|
|
2
|
+
|
|
3
|
+
import com.google.gson.*
|
|
4
|
+
import dev.croche.ffi.*
|
|
5
|
+
import dev.croche.s7.attached
|
|
6
|
+
import java.util.UUID
|
|
7
|
+
import java.util.concurrent.ConcurrentHashMap
|
|
8
|
+
import java.util.concurrent.CountDownLatch
|
|
9
|
+
|
|
10
|
+
internal val rnGson = Gson()
|
|
11
|
+
internal fun json(value: Any?): String = rnGson.toJson(value)
|
|
12
|
+
internal fun args(text: String): JsonArray = JsonParser.parseString(text).asJsonArray
|
|
13
|
+
internal fun JsonArray.text(i: Int): String = get(i).asString
|
|
14
|
+
internal fun JsonArray.optional(i: Int): String? = if (size() > i && !get(i).isJsonNull) get(i).asString else null
|
|
15
|
+
|
|
16
|
+
// Opaque FFI references only, never an SDK project/agent registry.
|
|
17
|
+
internal class CoreHandles {
|
|
18
|
+
private val handles = ConcurrentHashMap<String, Any>()
|
|
19
|
+
fun hold(value: Any): String = UUID.randomUUID().toString().also { handles[it] = value }
|
|
20
|
+
inline fun <reified T> get(id: String): T = value(id) as T
|
|
21
|
+
fun value(id: String): Any = handles[id] ?: error("Unknown native transport handle")
|
|
22
|
+
fun forget(id: String) { handles.remove(id) }
|
|
23
|
+
fun clear() { handles.clear() }
|
|
24
|
+
}
|
|
25
|
+
internal class CoreCallbacks(private val emit: (String) -> Unit) {
|
|
26
|
+
private class Reply { val done = CountDownLatch(1); @Volatile var json: String? = null }
|
|
27
|
+
private val pending = ConcurrentHashMap<String, Reply>()
|
|
28
|
+
@Volatile private var alive = true
|
|
29
|
+
fun post(packet: Map<String, Any?>) { check(alive); emit(json(packet)) }
|
|
30
|
+
fun invoke(packet: Map<String, Any?>): String {
|
|
31
|
+
val id = UUID.randomUUID().toString(); val reply = Reply(); pending[id] = reply
|
|
32
|
+
try {
|
|
33
|
+
check(alive); post(packet + ("call" to id)); reply.done.await()
|
|
34
|
+
return reply.json ?: error("JavaScript callback unavailable")
|
|
35
|
+
} finally { pending.remove(id) }
|
|
36
|
+
}
|
|
37
|
+
fun reply(id: String, text: String) { pending[id]?.let { it.json = text; it.done.countDown() } }
|
|
38
|
+
fun invalidate() { alive = false; pending.values.forEach { it.done.countDown() } }
|
|
39
|
+
}
|
|
40
|
+
internal class CallbackStorage(private val id: String, private val host: String, private val callbacks: CoreCallbacks) : CoreStoragePal {
|
|
41
|
+
private fun call(method: String, vararg arguments: Any?): JsonElement = try {
|
|
42
|
+
val result = JsonParser.parseString(callbacks.invoke(mapOf("type" to "storage", "storage" to id, "method" to method, "args" to arguments))).asJsonObject
|
|
43
|
+
if (result.has("error")) throw CoreStorageFailure.Failure(result.getAsJsonObject("error").get("detail").asString)
|
|
44
|
+
result.get("value") ?: error("Missing storage reply")
|
|
45
|
+
} catch (error: CoreStorageFailure) { throw error }
|
|
46
|
+
catch (error: Throwable) { throw CoreStorageFailure.Failure(error.message ?: "") }
|
|
47
|
+
override fun read(key: String) = call("read", key).let { if (it.isJsonNull) null else it.asString }
|
|
48
|
+
override fun write(key: String, value: String) { call("write", key, value) }
|
|
49
|
+
override fun remove(key: String) { call("remove", key) }
|
|
50
|
+
override fun list(prefix: String) = call("list", prefix).asJsonArray.map { it.asString }
|
|
51
|
+
override fun lock(name: String) = when (call("lock", name).asString) {
|
|
52
|
+
"acquired" -> PalLockOutcome.ACQUIRED; "held" -> PalLockOutcome.HELD
|
|
53
|
+
else -> throw CoreStorageFailure.Failure("Invalid lock transport reply")
|
|
54
|
+
}
|
|
55
|
+
override fun unlock(name: String) { call("unlock", name) }
|
|
56
|
+
override fun readSecret(key: String) = call("readSecret", key).let { if (it.isJsonNull) null else it.asString }
|
|
57
|
+
override fun writeSecret(key: String, value: String) { call("writeSecret", key, value) }
|
|
58
|
+
override fun removeSecret(key: String) { call("removeSecret", key) }
|
|
59
|
+
// Like the UniFFI handle cleaner: retirement follows the native callback's
|
|
60
|
+
// lifetime, not bounded public close or an SDK timeout.
|
|
61
|
+
@Suppress("deprecation")
|
|
62
|
+
protected fun finalize() { runCatching { callbacks.post(mapOf("type" to "retired", "storages" to listOf(id), "hosts" to listOf(host), "sinks" to emptyList<String>(), "executors" to emptyList<String>(), "tokens" to emptyList<String>())) } }
|
|
63
|
+
}
|
|
64
|
+
internal class NativeExecute(private val execute: String, private val callbacks: CoreCallbacks, private val handles: CoreHandles) : CoreToolExecute {
|
|
65
|
+
@Suppress("deprecation")
|
|
66
|
+
protected fun finalize() { runCatching { callbacks.post(mapOf("type" to "retired", "executors" to listOf(execute), "hosts" to emptyList<String>(), "storages" to emptyList<String>(), "sinks" to emptyList<String>(), "tokens" to emptyList<String>())) } }
|
|
67
|
+
override fun execute(callJson: String, contextJson: String, cancel: CancelToken): String {
|
|
68
|
+
val token = handles.hold(cancel)
|
|
69
|
+
cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { callbacks.post(mapOf("type" to "cancel", "token" to token)) } }))
|
|
70
|
+
return try { callbacks.invoke(mapOf("type" to "execute", "execute" to execute, "callJson" to callJson, "contextJson" to contextJson, "cancel" to token)) }
|
|
71
|
+
catch (_: Throwable) { "{\"type\":\"unavailable\"}" }
|
|
72
|
+
finally { handles.forget(token) }
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
internal class NativeSink(private val sink: String, private val callbacks: CoreCallbacks, private val handles: CoreHandles) : CoreEventSink {
|
|
76
|
+
@Suppress("deprecation")
|
|
77
|
+
protected fun finalize() { runCatching { callbacks.post(mapOf("type" to "retired", "sinks" to listOf(sink), "hosts" to emptyList<String>(), "storages" to emptyList<String>(), "executors" to emptyList<String>(), "tokens" to emptyList<String>())) } }
|
|
78
|
+
override fun deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) {
|
|
79
|
+
val id = handles.hold(delivery)
|
|
80
|
+
try { callbacks.post(mapOf("type" to "event", "sink" to sink, "id" to deliveryId, "eventJson" to eventJson, "delivery" to id)) }
|
|
81
|
+
catch (error: Throwable) { delivery.complete("{\"outcome\":\"unavailable\"}"); handles.forget(id); throw error }
|
|
82
|
+
}
|
|
83
|
+
}
|