@h1r-ai/croche-react-native 0.5.4 → 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,56 @@
|
|
|
1
|
+
package dev.croche.s7
|
|
2
|
+
|
|
3
|
+
import com.google.gson.*
|
|
4
|
+
import java.util.Collections
|
|
5
|
+
import java.util.IdentityHashMap
|
|
6
|
+
|
|
7
|
+
/** Mechanical JSON serialization only. Core owns all numeric limits and result interpretation. */
|
|
8
|
+
internal object PlainToolJson {
|
|
9
|
+
private val number = Regex("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?")
|
|
10
|
+
fun encode(value: Any?): JsonElement? = encode(value, Collections.newSetFromMap(IdentityHashMap<Any, Boolean>()))
|
|
11
|
+
|
|
12
|
+
private fun jsonNumber(value: Number): JsonElement? {
|
|
13
|
+
val token = value.toString() // Capture once, without a lossy Double/Long conversion.
|
|
14
|
+
if (!number.matches(token)) return null
|
|
15
|
+
return JsonParser.parseString(token)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
private fun encode(value: Any?, visiting: MutableSet<Any>): JsonElement? {
|
|
19
|
+
when (value) {
|
|
20
|
+
null, is JsonNull -> return JsonNull.INSTANCE
|
|
21
|
+
is JsonPrimitive -> return if (value.isNumber) jsonNumber(value.asNumber) else value.deepCopy()
|
|
22
|
+
is String -> return JsonPrimitive(value)
|
|
23
|
+
is Number -> return jsonNumber(value)
|
|
24
|
+
is Boolean -> return JsonPrimitive(value)
|
|
25
|
+
is Map<*, *>, is List<*>, is JsonObject, is JsonArray -> Unit
|
|
26
|
+
else -> return null // Unsupported objects are not reflected or stringified.
|
|
27
|
+
}
|
|
28
|
+
// A cyclic container has no JSON representation. Repeated non-cyclic values are fine.
|
|
29
|
+
if (!visiting.add(value)) return null
|
|
30
|
+
try {
|
|
31
|
+
return when (value) {
|
|
32
|
+
is Map<*, *> -> fields(value.entries, visiting)
|
|
33
|
+
is JsonObject -> fields(value.entrySet(), visiting)
|
|
34
|
+
is JsonArray -> items(value, visiting)
|
|
35
|
+
else -> items(value as List<*>, visiting)
|
|
36
|
+
}
|
|
37
|
+
} finally {
|
|
38
|
+
visiting.remove(value)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private fun fields(entries: Iterable<Map.Entry<*, *>>, visiting: MutableSet<Any>): JsonObject? {
|
|
43
|
+
val result = JsonObject()
|
|
44
|
+
for ((key, item) in entries) {
|
|
45
|
+
if (key !is String) return null
|
|
46
|
+
result.add(key, encode(item, visiting) ?: return null)
|
|
47
|
+
}
|
|
48
|
+
return result
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private fun items(values: Iterable<*>, visiting: MutableSet<Any>): JsonArray? {
|
|
52
|
+
val result = JsonArray()
|
|
53
|
+
for (item in values) result.add(encode(item, visiting) ?: return null)
|
|
54
|
+
return result
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
package dev.croche.s7
|
|
2
|
+
|
|
3
|
+
import dev.croche.CrocheError
|
|
4
|
+
import dev.croche.ErrorCategory
|
|
5
|
+
import dev.croche.ffi.CancelToken
|
|
6
|
+
import dev.croche.ffi.CoreApiException
|
|
7
|
+
import kotlinx.coroutines.*
|
|
8
|
+
import kotlin.coroutines.resumeWithException
|
|
9
|
+
|
|
10
|
+
/** No result/default/code policy: only translate Core's supplied public error envelope. */
|
|
11
|
+
internal fun publicFailure(error: Throwable): Throwable = when (error) {
|
|
12
|
+
is CrocheError -> error
|
|
13
|
+
is CoreApiException.Failure -> CrocheError(error.code, error.detail,
|
|
14
|
+
ErrorCategory.entries.firstOrNull { it.name.equals(error.category, ignoreCase = true) } ?: ErrorCategory.INTERNAL, error.path, error.retryAfter)
|
|
15
|
+
else -> CrocheError("internal", error.message ?: "Core binding failed.", ErrorCategory.INTERNAL)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
private val calls = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
|
19
|
+
|
|
20
|
+
/** One off-thread native call; cancellation fires the Core token, never Agent.cancel(). */
|
|
21
|
+
@OptIn(ExperimentalCoroutinesApi::class)
|
|
22
|
+
internal suspend fun <T> publicCall(discard: (T) -> Unit = {}, block: (CancelToken) -> T): T = suspendCancellableCoroutine { continuation ->
|
|
23
|
+
val token = CancelToken()
|
|
24
|
+
continuation.invokeOnCancellation { token.cancel() }
|
|
25
|
+
calls.launch {
|
|
26
|
+
val answer: Result<T> = runCatching { publicSync { block(token) } }
|
|
27
|
+
answer.fold(
|
|
28
|
+
{ value -> continuation.resume(value) { _, unreceived, _ -> discard(unreceived) } },
|
|
29
|
+
{ error -> continuation.resumeWithException(error) },
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
internal fun <T> publicSync(block: () -> T): T = try { block() } catch (error: Throwable) { throw publicFailure(error) }
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
package dev.croche.s7
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonArray
|
|
4
|
+
import com.google.gson.JsonElement
|
|
5
|
+
import com.google.gson.JsonObject
|
|
6
|
+
import com.google.gson.JsonPrimitive
|
|
7
|
+
|
|
8
|
+
/** Internal staging for APP-API at dcf068ed; not a second public SDK surface. */
|
|
9
|
+
internal sealed interface ScopeSelection {
|
|
10
|
+
data object All : ScopeSelection
|
|
11
|
+
// Keep list order and duplicates. Core validates and resolves the entries.
|
|
12
|
+
data class Entries(val entries: List<JsonElement>) : ScopeSelection
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
internal fun ScopeSelection.toJson(): JsonElement = when (this) {
|
|
16
|
+
ScopeSelection.All -> JsonPrimitive("all")
|
|
17
|
+
is ScopeSelection.Entries -> JsonArray().also { array -> entries.forEach { array.add(it) } }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Null selectors are omitted; nulls inside JSON values, including binds, are preserved. */
|
|
21
|
+
internal fun agentOptionsJson(
|
|
22
|
+
instance: JsonObject? = null,
|
|
23
|
+
tools: ScopeSelection? = null,
|
|
24
|
+
wiki: ScopeSelection? = null,
|
|
25
|
+
): String = JsonObject().apply {
|
|
26
|
+
instance?.let { add("instance", it) }
|
|
27
|
+
tools?.let { add("tools", it.toJson()) }
|
|
28
|
+
wiki?.let { add("wiki", it.toJson()) }
|
|
29
|
+
}.toString()
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
package dev.croche.s7
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonElement
|
|
4
|
+
import com.google.gson.JsonObject
|
|
5
|
+
import dev.croche.ToolResult
|
|
6
|
+
|
|
7
|
+
/** Syntax only: Core classifies branded content, including strings, arrays and null.
|
|
8
|
+
* A plain object containing a content key never becomes a branded result by inspection.
|
|
9
|
+
*/
|
|
10
|
+
internal object ToolCompletionEncoding {
|
|
11
|
+
private const val invalidResult = """{"type":"invalid_result"}"""
|
|
12
|
+
|
|
13
|
+
/** Only serialization failures become invalid_result; handler throws are caught by the caller. */
|
|
14
|
+
fun returned(value: Any?): String = try {
|
|
15
|
+
when (value) {
|
|
16
|
+
null -> """{"type":"empty"}"""
|
|
17
|
+
is ToolResult -> PlainToolJson.encode(value.content)?.let(::result) ?: invalidResult
|
|
18
|
+
else -> PlainToolJson.encode(value)?.let(::json) ?: invalidResult
|
|
19
|
+
}
|
|
20
|
+
} catch (_: Throwable) { invalidResult }
|
|
21
|
+
|
|
22
|
+
fun result(content: JsonElement): String = tagged("result", "content", content)
|
|
23
|
+
fun json(value: JsonElement): String = tagged("json", "value", value)
|
|
24
|
+
|
|
25
|
+
private fun tagged(type: String, key: String, value: JsonElement): String = JsonObject().also {
|
|
26
|
+
it.addProperty("type", type)
|
|
27
|
+
it.add(key, value.deepCopy())
|
|
28
|
+
}.toString()
|
|
29
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
package dev.croche.s7.pal
|
|
2
|
+
|
|
3
|
+
import java.io.File
|
|
4
|
+
import java.io.FileOutputStream
|
|
5
|
+
import java.io.RandomAccessFile
|
|
6
|
+
import java.nio.channels.FileLock
|
|
7
|
+
import java.nio.channels.OverlappingFileLockException
|
|
8
|
+
import java.nio.file.Files
|
|
9
|
+
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
|
|
10
|
+
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
|
|
11
|
+
import java.util.Base64
|
|
12
|
+
|
|
13
|
+
/** Physical encoding only: Core owns keys, values, segmentation and recovery. No legacy probing.
|
|
14
|
+
* Segments stay below filesystem filename limits even for Core's longest keys. */
|
|
15
|
+
internal class AtomicKeyFiles(private val root: File, private val syncDirectory: (File) -> Unit) {
|
|
16
|
+
private val held = mutableMapOf<String, Pair<RandomAccessFile, FileLock>>()
|
|
17
|
+
internal var beforeReplace: (() -> Unit)? = null
|
|
18
|
+
private fun encoded(key: String) = Base64.getUrlEncoder().withoutPadding()
|
|
19
|
+
.encodeToString(key.toByteArray(Charsets.UTF_8)).ifEmpty { "_" }
|
|
20
|
+
private fun path(key: String, area: String): File = encoded(key).chunked(100)
|
|
21
|
+
.fold(File(root, area)) { parent, part -> File(parent, part) }.resolve("value")
|
|
22
|
+
private fun mkdirs(directory: File) {
|
|
23
|
+
if (directory.isDirectory) return
|
|
24
|
+
directory.parentFile?.let { mkdirs(it) }
|
|
25
|
+
if (!directory.mkdir() && !directory.isDirectory) throw java.io.IOException("Cannot create PAL directory")
|
|
26
|
+
directory.parentFile?.let(syncDirectory)
|
|
27
|
+
}
|
|
28
|
+
fun read(key: String): String? = storage {
|
|
29
|
+
val file = path(key, "values")
|
|
30
|
+
try { file.readText(Charsets.UTF_8) } catch (e: java.io.FileNotFoundException) {
|
|
31
|
+
if (file.exists()) throw e else null
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
fun write(key: String, value: String) = storage {
|
|
35
|
+
val target = path(key, "values")
|
|
36
|
+
mkdirs(target.parentFile!!)
|
|
37
|
+
val temporary = File.createTempFile("pending-", ".tmp", target.parentFile)
|
|
38
|
+
try {
|
|
39
|
+
FileOutputStream(temporary).use { it.write(value.toByteArray(Charsets.UTF_8)); it.fd.sync() }
|
|
40
|
+
beforeReplace?.invoke()
|
|
41
|
+
Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
|
|
42
|
+
syncDirectory(target.parentFile!!)
|
|
43
|
+
} finally { temporary.delete() }
|
|
44
|
+
Unit
|
|
45
|
+
}
|
|
46
|
+
fun remove(key: String) = storage {
|
|
47
|
+
val file = path(key, "values")
|
|
48
|
+
if (Files.deleteIfExists(file.toPath())) syncDirectory(file.parentFile!!)
|
|
49
|
+
Unit
|
|
50
|
+
}
|
|
51
|
+
fun list(prefix: String): List<String> = storage {
|
|
52
|
+
val directory = File(root, "values")
|
|
53
|
+
if (!directory.exists()) return@storage emptyList()
|
|
54
|
+
directory.walkTopDown().filter { it.isFile && it.name == "value" }.map { file ->
|
|
55
|
+
val parts = file.parentFile!!.relativeTo(directory).invariantSeparatorsPath.replace("/", "")
|
|
56
|
+
if (parts == "_") "" else String(Base64.getUrlDecoder().decode(parts), Charsets.UTF_8)
|
|
57
|
+
}.filter { it.startsWith(prefix) }.toList()
|
|
58
|
+
}
|
|
59
|
+
@Synchronized fun lock(key: String): Boolean {
|
|
60
|
+
if (held.containsKey(key)) return false
|
|
61
|
+
return storage {
|
|
62
|
+
val file = path(key, "locks")
|
|
63
|
+
mkdirs(file.parentFile!!)
|
|
64
|
+
val opened = RandomAccessFile(file, "rw")
|
|
65
|
+
try {
|
|
66
|
+
val lock = try { opened.channel.tryLock() } catch (_: OverlappingFileLockException) { null }
|
|
67
|
+
if (lock == null) { opened.close(); false }
|
|
68
|
+
else { held[key] = opened to lock; true }
|
|
69
|
+
} catch (e: Throwable) { opened.close(); throw e }
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
@Synchronized fun unlock(key: String) = storage {
|
|
73
|
+
held.remove(key)?.let { (file, lock) -> try { lock.release() } finally { file.close() } }
|
|
74
|
+
// Never unlink the lock inode: another process may already hold it.
|
|
75
|
+
Unit
|
|
76
|
+
}
|
|
77
|
+
// Exceptions remain raw facts; the Core callback boundary assigns storage_error.
|
|
78
|
+
private inline fun <T> storage(block: () -> T): T = block()
|
|
79
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
package dev.croche.s7.pal
|
|
2
|
+
|
|
3
|
+
import dev.croche.CrocheError
|
|
4
|
+
import dev.croche.ResponseSink
|
|
5
|
+
import dev.croche.RuntimeCancellation
|
|
6
|
+
import dev.croche.ffi.PalHeader
|
|
7
|
+
import dev.croche.ffi.PalHttpRequest
|
|
8
|
+
import java.io.BufferedInputStream
|
|
9
|
+
import java.io.EOFException
|
|
10
|
+
import java.io.InputStream
|
|
11
|
+
import java.io.IOException
|
|
12
|
+
import java.net.InetAddress
|
|
13
|
+
import java.net.InetSocketAddress
|
|
14
|
+
import java.net.Socket
|
|
15
|
+
import java.net.URI
|
|
16
|
+
import java.util.concurrent.ExecutionException
|
|
17
|
+
import java.util.concurrent.Executors
|
|
18
|
+
import java.util.concurrent.TimeUnit
|
|
19
|
+
import java.util.concurrent.TimeoutException
|
|
20
|
+
import javax.net.ssl.SSLSocket
|
|
21
|
+
import javax.net.ssl.SSLSocketFactory
|
|
22
|
+
|
|
23
|
+
/** One direct HTTP/1.1 transport for pinned and ordinary effects. No proxy, connection pool,
|
|
24
|
+
* cookies, cache or redirect machinery. Core supplies policy; this adapter supplies bytes.
|
|
25
|
+
* The sole connection pin is the generated request.connectTo field. */
|
|
26
|
+
internal class DirectHttpPal(
|
|
27
|
+
private val tlsFactory: SSLSocketFactory = SSLSocketFactory.getDefault() as SSLSocketFactory,
|
|
28
|
+
private val resolveAddresses: (String) -> List<String> = { host ->
|
|
29
|
+
InetAddress.getAllByName(host).map { it.hostAddress!! }
|
|
30
|
+
},
|
|
31
|
+
) {
|
|
32
|
+
fun resolve(host: String, cancellation: RuntimeCancellation): List<String> = resolveBefore(host, cancellation, null)
|
|
33
|
+
|
|
34
|
+
private fun resolveBefore(host: String, cancellation: RuntimeCancellation, deadline: Long?): List<String> {
|
|
35
|
+
cancellation.check()
|
|
36
|
+
val lookup = resolver.submit<List<String>> { resolveAddresses(host) }
|
|
37
|
+
try {
|
|
38
|
+
while (true) {
|
|
39
|
+
cancellation.check()
|
|
40
|
+
if (deadline != null && System.nanoTime() >= deadline) throw CrocheError("network_error", "DNS resolution timed out")
|
|
41
|
+
try { return lookup.get(50, TimeUnit.MILLISECONDS).also { cancellation.check() } }
|
|
42
|
+
catch (_: TimeoutException) { /* Core owns the deadline and cancellation. */ }
|
|
43
|
+
}
|
|
44
|
+
} catch (e: CrocheError) { throw e }
|
|
45
|
+
catch (error: ExecutionException) {
|
|
46
|
+
cancellation.check()
|
|
47
|
+
// Future.get wraps the resolver's failure: classify its cause, not the wrapper.
|
|
48
|
+
val code = if (error.cause is IOException) "network_error" else "internal"
|
|
49
|
+
throw CrocheError(code, "DNS resolution failed")
|
|
50
|
+
} catch (_: Exception) {
|
|
51
|
+
cancellation.check()
|
|
52
|
+
throw CrocheError("internal", "DNS resolution failed")
|
|
53
|
+
}
|
|
54
|
+
finally { lookup.cancel(true) }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
fun http(request: PalHttpRequest, sink: ResponseSink, cancellation: RuntimeCancellation) {
|
|
58
|
+
cancellation.check()
|
|
59
|
+
val uri = URI(request.url)
|
|
60
|
+
val host = uri.host?.removeSurrounding("[", "]") ?: throw CrocheError("invalid_abi", "HTTP URL needs a host")
|
|
61
|
+
val tls = when (uri.scheme) {
|
|
62
|
+
"https" -> true
|
|
63
|
+
"http" -> false
|
|
64
|
+
else -> throw CrocheError("invalid_abi", "Invalid HTTP scheme")
|
|
65
|
+
}
|
|
66
|
+
val port = if (uri.port >= 0) uri.port else if (tls) 443 else 80
|
|
67
|
+
val timeout = request.timeoutMs.coerceIn(1uL, Int.MAX_VALUE.toULong()).toInt()
|
|
68
|
+
val address = request.connectTo?.let(::numericAddress)
|
|
69
|
+
if (uri.rawUserInfo != null) throw CrocheError("invalid_abi", "HTTP user info is unsupported")
|
|
70
|
+
val expires = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout.toLong())
|
|
71
|
+
val raw = Socket()
|
|
72
|
+
val cancelled = cancellation.observe { try { raw.close() } catch (_: Exception) {} }
|
|
73
|
+
val deadline = timer.schedule({ try { raw.close() } catch (_: Exception) {} }, timeout.toLong(), TimeUnit.MILLISECONDS)
|
|
74
|
+
try {
|
|
75
|
+
val resolved = address ?: numericAddress(resolveBefore(host, cancellation, expires).firstOrNull()
|
|
76
|
+
?: throw CrocheError("network_error", "DNS returned no address"))
|
|
77
|
+
val destination = InetSocketAddress(resolved, port)
|
|
78
|
+
raw.connect(destination, timeout)
|
|
79
|
+
raw.soTimeout = timeout
|
|
80
|
+
val socket = if (tls) {
|
|
81
|
+
(tlsFactory.createSocket(raw, host, port, true) as SSLSocket).apply {
|
|
82
|
+
sslParameters = sslParameters.apply { endpointIdentificationAlgorithm = "HTTPS" }
|
|
83
|
+
startHandshake()
|
|
84
|
+
}
|
|
85
|
+
} else raw
|
|
86
|
+
socket.use {
|
|
87
|
+
cancellation.check()
|
|
88
|
+
writeRequest(it, uri, request)
|
|
89
|
+
readResponse(it.getInputStream(), request, sink, cancellation)
|
|
90
|
+
}
|
|
91
|
+
} catch (e: CrocheError) { throw e }
|
|
92
|
+
catch (_: IOException) {
|
|
93
|
+
cancellation.check()
|
|
94
|
+
throw CrocheError("network_error", "HTTP transport failed")
|
|
95
|
+
} catch (_: Exception) {
|
|
96
|
+
cancellation.check()
|
|
97
|
+
throw CrocheError("internal", "HTTP transport failed")
|
|
98
|
+
} finally {
|
|
99
|
+
deadline.cancel(false)
|
|
100
|
+
cancellation.remove(cancelled)
|
|
101
|
+
raw.close()
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private fun writeRequest(socket: Socket, uri: URI, request: PalHttpRequest) {
|
|
106
|
+
val body = request.body?.toByteArray(Charsets.UTF_8)
|
|
107
|
+
val target = (uri.rawPath?.ifEmpty { "/" } ?: "/") + (uri.rawQuery?.let { "?$it" } ?: "")
|
|
108
|
+
requireLine(request.method); requireLine(target)
|
|
109
|
+
val lines = StringBuilder("${request.method} $target HTTP/1.1\r\nHost: ${uri.rawAuthority}\r\nConnection: close\r\n")
|
|
110
|
+
for (header in request.headers) {
|
|
111
|
+
requireLine(header.name); requireLine(header.value)
|
|
112
|
+
if (header.name.lowercase() !in setOf("host", "connection", "content-length", "transfer-encoding"))
|
|
113
|
+
lines.append("${header.name}: ${header.value}\r\n")
|
|
114
|
+
}
|
|
115
|
+
if (body != null) lines.append("Content-Length: ${body.size}\r\n")
|
|
116
|
+
lines.append("\r\n")
|
|
117
|
+
socket.getOutputStream().apply {
|
|
118
|
+
write(lines.toString().toByteArray(Charsets.ISO_8859_1))
|
|
119
|
+
if (body != null) write(body)
|
|
120
|
+
flush()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
private fun requireLine(value: String) {
|
|
124
|
+
if (value.any { it == '\r' || it == '\n' }) throw CrocheError("invalid_abi", "Invalid HTTP request line")
|
|
125
|
+
}
|
|
126
|
+
private fun numericAddress(pin: String): InetAddress {
|
|
127
|
+
// Guard before InetAddress: a malformed pin MUST NOT trigger DNS or an unpinned fallback.
|
|
128
|
+
if (pin.contains(':')) {
|
|
129
|
+
if (!pin.matches(Regex("[0-9a-fA-F:.]+"))) throw CrocheError("invalid_abi", "Invalid HTTP connectTo")
|
|
130
|
+
} else {
|
|
131
|
+
val parts = pin.split('.')
|
|
132
|
+
if (parts.size != 4 || parts.any { part ->
|
|
133
|
+
part.isEmpty() || part.any { !it.isDigit() } || part.toIntOrNull()?.let { it in 0..255 } != true
|
|
134
|
+
}) throw CrocheError("invalid_abi", "Invalid HTTP connectTo")
|
|
135
|
+
}
|
|
136
|
+
return try { InetAddress.getByName(pin) }
|
|
137
|
+
catch (_: Exception) { throw CrocheError("invalid_abi", "Invalid HTTP connectTo") }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private fun readResponse(source: InputStream, request: PalHttpRequest, sink: ResponseSink, cancellation: RuntimeCancellation) {
|
|
141
|
+
val input = BufferedInputStream(source)
|
|
142
|
+
var status: Int
|
|
143
|
+
var headers: List<PalHeader>
|
|
144
|
+
var informational = 0
|
|
145
|
+
do {
|
|
146
|
+
val statusLine = line(input)
|
|
147
|
+
status = statusLine.split(' ').getOrNull(1)?.toIntOrNull()
|
|
148
|
+
?: throw java.io.IOException("Invalid HTTP status")
|
|
149
|
+
if (!statusLine.startsWith("HTTP/1.") || status !in 100..599) throw java.io.IOException("Invalid HTTP status")
|
|
150
|
+
val fields = mutableListOf<PalHeader>()
|
|
151
|
+
var bytes = statusLine.length
|
|
152
|
+
while (true) {
|
|
153
|
+
val field = line(input)
|
|
154
|
+
bytes += field.length + 2
|
|
155
|
+
if (bytes > 65536) throw java.io.IOException("HTTP headers exceed bound")
|
|
156
|
+
if (field.isEmpty()) break
|
|
157
|
+
val colon = field.indexOf(':')
|
|
158
|
+
if (colon <= 0 || field.first().isWhitespace()) throw java.io.IOException("Invalid HTTP header")
|
|
159
|
+
fields += PalHeader(field.substring(0, colon), field.substring(colon + 1).trim())
|
|
160
|
+
}
|
|
161
|
+
headers = fields
|
|
162
|
+
if (++informational > 16) throw java.io.IOException("Too many interim responses")
|
|
163
|
+
} while (status in 100..199 && status != 101)
|
|
164
|
+
sink.head(status, headers)
|
|
165
|
+
if (request.method == "HEAD" || status in 100..199 || status == 204 || status == 304) return
|
|
166
|
+
val lengths = headers.filter { it.name.equals("content-length", true) }.map { it.value }
|
|
167
|
+
if (lengths.distinct().size > 1) throw java.io.IOException("Conflicting HTTP lengths")
|
|
168
|
+
val transfer = headers.filter { it.name.equals("transfer-encoding", true) }.map { it.value.lowercase() }
|
|
169
|
+
if (transfer.isNotEmpty() && transfer != listOf("chunked")) throw java.io.IOException("Unsupported HTTP transfer coding")
|
|
170
|
+
var received = 0uL
|
|
171
|
+
fun copy(count: Long?): Boolean {
|
|
172
|
+
var remaining = count
|
|
173
|
+
val buffer = ByteArray(8192)
|
|
174
|
+
while (remaining == null || remaining > 0) {
|
|
175
|
+
cancellation.check()
|
|
176
|
+
val n = input.read(buffer, 0, remaining?.coerceAtMost(buffer.size.toLong())?.toInt() ?: buffer.size)
|
|
177
|
+
if (n < 0) { if (remaining != null) throw EOFException(); return true }
|
|
178
|
+
received += n.toULong()
|
|
179
|
+
if (received > request.maxResponseBytes) throw CrocheError("invalid_response", "HTTP response exceeds bound")
|
|
180
|
+
if (!sink.chunk(buffer.copyOf(n))) return false
|
|
181
|
+
remaining = remaining?.minus(n)
|
|
182
|
+
}
|
|
183
|
+
return true
|
|
184
|
+
}
|
|
185
|
+
if (transfer.isNotEmpty()) {
|
|
186
|
+
while (true) {
|
|
187
|
+
val size = line(input).substringBefore(';').trim().toLongOrNull(16)
|
|
188
|
+
?: throw java.io.IOException("Invalid HTTP chunk")
|
|
189
|
+
if (size < 0) throw java.io.IOException("Invalid HTTP chunk")
|
|
190
|
+
if (size == 0L) {
|
|
191
|
+
var trailerBytes = 0
|
|
192
|
+
while (true) {
|
|
193
|
+
val trailer = line(input); trailerBytes += trailer.length + 2
|
|
194
|
+
if (trailerBytes > 65536) throw java.io.IOException("HTTP trailers exceed bound")
|
|
195
|
+
if (trailer.isEmpty()) return
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (!copy(size)) return
|
|
199
|
+
if (line(input).isNotEmpty()) throw java.io.IOException("Invalid chunk terminator")
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
val length = lengths.firstOrNull()?.toLongOrNull()
|
|
203
|
+
if (lengths.isNotEmpty() && (length == null || length < 0)) throw java.io.IOException("Invalid HTTP length")
|
|
204
|
+
copy(length)
|
|
205
|
+
}
|
|
206
|
+
private fun line(input: InputStream): String {
|
|
207
|
+
val bytes = java.io.ByteArrayOutputStream()
|
|
208
|
+
while (bytes.size() <= 8192) {
|
|
209
|
+
val next = input.read()
|
|
210
|
+
if (next < 0) throw EOFException()
|
|
211
|
+
if (next == 13) {
|
|
212
|
+
if (input.read() != 10) throw java.io.IOException("Invalid HTTP line ending")
|
|
213
|
+
return bytes.toString("ISO-8859-1")
|
|
214
|
+
}
|
|
215
|
+
bytes.write(next)
|
|
216
|
+
}
|
|
217
|
+
throw java.io.IOException("HTTP line exceeds bound")
|
|
218
|
+
}
|
|
219
|
+
private companion object {
|
|
220
|
+
val timer = Executors.newSingleThreadScheduledExecutor { Thread(it, "croche-http-deadline").apply { isDaemon = true } }
|
|
221
|
+
val resolver = Executors.newFixedThreadPool(4) { Thread(it, "croche-resolve").apply { isDaemon = true } }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { TurboModule } from 'react-native';
|
|
2
|
+
export type OwnedImage = {
|
|
3
|
+
element: number;
|
|
4
|
+
bytes: ReadonlyArray<number>;
|
|
5
|
+
};
|
|
6
|
+
export interface Spec extends TurboModule {
|
|
7
|
+
coreCall(handle: string, method: string, argsJson: string, images: ReadonlyArray<OwnedImage>): Promise<string>;
|
|
8
|
+
coreCallSync(handle: string, method: string, argsJson: string): string;
|
|
9
|
+
coreReply(call: string, completionJson: string): void;
|
|
10
|
+
platformCall(method: string, argsJson: string): Promise<string>;
|
|
11
|
+
platformCallSync(method: string, argsJson: string): string;
|
|
12
|
+
addListener(eventName: string): void;
|
|
13
|
+
removeListeners(count: number): void;
|
|
14
|
+
}
|
|
15
|
+
declare const _default: Spec;
|
|
16
|
+
export default _default;
|