@h1r-ai/croche-react-native 0.5.5 → 0.7.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/LICENSE +1 -1
- package/README.md +90 -451
- package/THIRD-PARTY-NOTICES +906 -14
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -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/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -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/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 +116 -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/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -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 +30 -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 +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -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 +43 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +1 -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 +6 -0
- package/dist/react-native/src/core-native.js +316 -0
- package/dist/react-native/src/core-wire.d.ts +55 -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/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +91 -0
- package/dist/runtime/src/agent.js +137 -0
- package/dist/runtime/src/app-api.d.ts +572 -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 +27 -0
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +247 -0
- package/dist/runtime/src/core/port.js +1 -0
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -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 +97 -0
- package/dist/runtime/src/croche.js +172 -0
- package/dist/runtime/src/errors.d.ts +33 -0
- package/dist/runtime/src/errors.js +63 -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 +328 -0
- package/dist/runtime/src/generated/app-stream.js +127 -0
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -0
- package/dist/runtime/src/index.native.js +2 -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 +30 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +60 -0
- package/dist/runtime/src/pal/platform.d.ts +21 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -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 +35 -0
- package/dist/runtime/src/tools.js +94 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +98 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +122 -0
- package/ios/CoreWireSupport.swift +286 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +49 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
- 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 +899 -608
- 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/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +8 -6
- 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/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
- 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
|
@@ -1,837 +1,61 @@
|
|
|
1
1
|
package dev.croche.reactnative
|
|
2
2
|
|
|
3
|
-
import
|
|
4
|
-
import android.util.Log
|
|
5
|
-
import com.facebook.react.bridge.Arguments
|
|
6
|
-
import com.facebook.react.bridge.LifecycleEventListener
|
|
7
|
-
import com.facebook.react.bridge.Promise
|
|
8
|
-
import com.facebook.react.bridge.ReactApplicationContext
|
|
3
|
+
import com.facebook.react.bridge.*
|
|
9
4
|
import com.facebook.react.modules.core.DeviceEventManagerModule
|
|
10
|
-
import com.google.gson
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
import
|
|
14
|
-
import
|
|
15
|
-
import
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
import dev.croche.CrocheImages
|
|
32
|
-
import dev.croche.CrocheException
|
|
33
|
-
import dev.croche.CrocheRuntime
|
|
34
|
-
import dev.croche.FileRuntimeStorage
|
|
35
|
-
import dev.croche.RuntimeAttestor
|
|
36
|
-
import dev.croche.RuntimeCancellation
|
|
37
|
-
import dev.croche.ImageResolution
|
|
38
|
-
import dev.croche.ToolResult
|
|
39
|
-
import dev.croche.withResult
|
|
40
|
-
import dev.croche.ToolNotDispatched
|
|
41
|
-
import dev.croche.WikiDocument
|
|
42
|
-
import dev.croche.WriteResult
|
|
43
|
-
import dev.croche.android.wikiFromAssets
|
|
44
|
-
import dev.croche.android.KeystoreSecretStore
|
|
45
|
-
import dev.croche.android.PlayIntegrityAttestor
|
|
46
|
-
import dev.croche.android.WorkManagerScheduler
|
|
47
|
-
import java.io.File
|
|
48
|
-
import java.lang.ref.WeakReference
|
|
49
|
-
import java.util.concurrent.CompletableFuture
|
|
50
|
-
import java.util.concurrent.ConcurrentHashMap
|
|
51
|
-
import java.util.concurrent.Executors
|
|
52
|
-
import java.util.concurrent.ExecutorService
|
|
53
|
-
import kotlin.coroutines.Continuation
|
|
54
|
-
import kotlin.coroutines.EmptyCoroutineContext
|
|
55
|
-
import kotlin.coroutines.startCoroutine
|
|
56
|
-
|
|
57
|
-
// The React Native bridge over the Android SDK (sdk/kotlin). It holds one CrocheRuntime per
|
|
58
|
-
// JS handle and carries calls, events and tool round-trips; every decision stays in the Rust
|
|
59
|
-
// Core. The protocol is packages/react-native/src/protocol.ts, and tests/mock-native.ts is
|
|
60
|
-
// its executable reference. Host compile evidence is recorded in the builder status.
|
|
61
|
-
class CrocheRuntimeModule(context: ReactApplicationContext) : NativeCrocheRuntimeSpec(context) {
|
|
62
|
-
private class ProjectEntry(val core: CoreProject, val pals: AgentPals)
|
|
63
|
-
private class AgentEntry(val core: CoreRuntime, val host: KotlinHost, val project: String) {
|
|
64
|
-
@Volatile var closed = false
|
|
65
|
-
@Volatile var cachedState = JsonObject()
|
|
66
|
-
val retired = CompletableFuture<Unit>()
|
|
67
|
-
var retiring = false
|
|
68
|
-
}
|
|
69
|
-
private val projects = ConcurrentHashMap<String, ProjectEntry>()
|
|
70
|
-
private val agents = ConcurrentHashMap<String, AgentEntry>()
|
|
71
|
-
private fun agent(handle: String) = agents[handle]?.takeUnless { it.closed }
|
|
72
|
-
?: throw CrocheException("closed", "Agent is closed")
|
|
73
|
-
private fun project(id: String) = projects[id] ?: throw CrocheException("closed", "Project is closed")
|
|
74
|
-
private fun streamCore(handle: String) = agent(handle).core
|
|
75
|
-
private val agentWorkers = ConcurrentHashMap<String, ExecutorService>()
|
|
76
|
-
/** FIFO admissions, including void unobserve/closeProjection before the next call. */
|
|
77
|
-
private fun dispatch(handle: String, body: () -> Unit) {
|
|
78
|
-
val entry = agents[handle]
|
|
79
|
-
if (entry == null) { executor.execute(body); return }
|
|
80
|
-
synchronized(entry) {
|
|
81
|
-
if (entry.retiring) { executor.execute(body); return }
|
|
82
|
-
agentWorkers.computeIfAbsent(handle) {
|
|
83
|
-
Executors.newSingleThreadExecutor { task -> Thread(task, "croche-rn-agent").apply { isDaemon = true } }
|
|
84
|
-
}.execute(body)
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
private val callbackQueues = ConcurrentHashMap<String, ExecutorService>()
|
|
88
|
-
/** One queue across observation, projections, captures and their promise barriers. */
|
|
89
|
-
private fun callbackQueue(handle: String) = callbackQueues.computeIfAbsent(handle) {
|
|
90
|
-
Executors.newSingleThreadExecutor { task -> Thread(task, "croche-rn-events").apply { isDaemon = true } }
|
|
91
|
-
}
|
|
92
|
-
private fun enqueue(handle: String, body: () -> Unit) {
|
|
93
|
-
try {
|
|
94
|
-
callbackQueue(handle).execute {
|
|
95
|
-
// A torn-down JS runtime must not kill a Core callback thread.
|
|
96
|
-
try { body() } catch (_: Exception) {}
|
|
97
|
-
}
|
|
98
|
-
} catch (_: java.util.concurrent.RejectedExecutionException) {}
|
|
99
|
-
}
|
|
100
|
-
/** Drain admitted calls and callbacks before releasing their FFI wrapper and queues. */
|
|
101
|
-
private fun retireAgent(handle: String, entry: AgentEntry): CompletableFuture<Unit> {
|
|
102
|
-
if (entry.retiring) return entry.retired
|
|
103
|
-
entry.retiring = true
|
|
104
|
-
entry.closed = true
|
|
105
|
-
agents.remove(handle, entry)
|
|
106
|
-
entry.host.deliver = null
|
|
107
|
-
entry.host.stop()
|
|
108
|
-
val worker = agentWorkers.remove(handle)
|
|
109
|
-
worker?.shutdown()
|
|
110
|
-
val callbacks = callbackQueues[handle]
|
|
111
|
-
executor.execute {
|
|
112
|
-
try {
|
|
113
|
-
worker?.awaitTermination(Long.MAX_VALUE, java.util.concurrent.TimeUnit.NANOSECONDS)
|
|
114
|
-
entry.core.destroy()
|
|
115
|
-
entry.host.release()
|
|
116
|
-
entry.retired.complete(Unit)
|
|
117
|
-
} catch (error: Exception) { entry.retired.completeExceptionally(error) }
|
|
118
|
-
finally {
|
|
119
|
-
callbacks?.shutdown()
|
|
120
|
-
if (callbacks != null) callbackQueues.remove(handle, callbacks)
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
return entry.retired
|
|
124
|
-
}
|
|
125
|
-
private fun streamMessage(handle: String, type: String, payload: String,
|
|
126
|
-
projection: Double? = null, readId: String? = null) {
|
|
127
|
-
// Embed the Core JSON verbatim, without parsing or re-encoding it.
|
|
128
|
-
val json = when (type) {
|
|
129
|
-
"projection" -> "{\"projection\":${projection!!.toLong()},\"event\":$payload}"
|
|
130
|
-
"captured" -> "{\"readId\":${JsonPrimitive(readId).toString()},\"state\":$payload}"
|
|
131
|
-
else -> payload
|
|
132
|
-
}
|
|
133
|
-
emit(handle, type, json)
|
|
134
|
-
}
|
|
135
|
-
private fun listener(body: (String) -> Unit) = object : EventListener {
|
|
136
|
-
override fun onEvent(event: String) { keepAttached(); body(event) }
|
|
137
|
-
}
|
|
138
|
-
private val runtimes = ConcurrentHashMap<String, CrocheRuntime>()
|
|
139
|
-
private val waiters = ConcurrentHashMap<String, CompletableFuture<JsonElement>>()
|
|
140
|
-
/** Each send call's cancellation, by handle and call id (a retry of an input is its own call). */
|
|
141
|
-
private val sending = ConcurrentHashMap<String, RuntimeCancellation>()
|
|
142
|
-
/** Calls cancelled before their send registered: they start cancelled (Atlas, #278). */
|
|
143
|
-
private val early: MutableSet<String> = ConcurrentHashMap.newKeySet()
|
|
144
|
-
// The SDK is blocking by design; never run it on the JS or UI thread.
|
|
145
|
-
private val executor = Executors.newCachedThreadPool { task -> Thread(task, "croche-rn").apply { isDaemon = true } }
|
|
146
|
-
|
|
147
|
-
/** The Runtimes JavaScript opened with background delivery, by WorkManager name (one per
|
|
148
|
-
* store): what that name's runs reach. */
|
|
149
|
-
private val backgrounds = ConcurrentHashMap<String, CrocheRuntime>()
|
|
150
|
-
|
|
151
|
-
// Each return to the foreground delivers the notes that came due meanwhile, off the UI thread.
|
|
152
|
-
init {
|
|
153
|
-
context.addLifecycleEventListener(object : LifecycleEventListener {
|
|
154
|
-
override fun onHostResume() {
|
|
155
|
-
runtimes.values.forEach { runtime -> executor.execute { try { runtime.deliverDue() } catch (_: Exception) {} } }
|
|
156
|
-
}
|
|
157
|
-
override fun onHostPause() {}
|
|
158
|
-
override fun onHostDestroy() {}
|
|
159
|
-
})
|
|
160
|
-
}
|
|
161
|
-
|
|
5
|
+
import com.google.gson.*
|
|
6
|
+
import dev.croche.SelectedAdapters
|
|
7
|
+
import dev.croche.ffi.*
|
|
8
|
+
import dev.croche.s7.ensureNativeCoreInitialized
|
|
9
|
+
import dev.croche.s7.nativePlatform
|
|
10
|
+
import kotlinx.coroutines.*
|
|
11
|
+
|
|
12
|
+
// Thin RN transport over S7's Android PAL and S1's public Core factory. No
|
|
13
|
+
// KotlinHost/legacy engine, app defaults, second scheduler or second stream queue.
|
|
14
|
+
class CrocheRuntimeModule(private val context: ReactApplicationContext) : NativeCrocheRuntimeSpec(context) {
|
|
15
|
+
companion object { const val NAME = "CrocheRuntime" }
|
|
16
|
+
init { ensureNativeCoreInitialized() }
|
|
17
|
+
private val worker = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
|
18
|
+
private val pals by lazy { nativePlatform(context, SelectedAdapters()) }
|
|
19
|
+
private fun host(): HostPal = rnHostPal(pals.host)
|
|
20
|
+
private fun emit(name: String, packet: String) {
|
|
21
|
+
check(context.hasActiveReactInstance()) { "JavaScript runtime unavailable" }
|
|
22
|
+
context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java).emit(name, packet)
|
|
23
|
+
}
|
|
24
|
+
private val core = CoreDispatch(::host, { pals.storage }) { emit("CrocheCoreEvent", it) }
|
|
25
|
+
private val pal by lazy { NativePal(pals.storage, host()) { emit("CrochePalEvent", it) } }
|
|
162
26
|
override fun getName() = NAME
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
val handlers = config.getAsJsonArray("tools")?.mapNotNull { it.asJsonObject.get("name")?.asString }
|
|
181
|
-
?.associateWith { toolHandler(handle) } ?: emptyMap()
|
|
182
|
-
val key = options.get("storageKey")?.asString?.takeIf { it.isNotEmpty() }
|
|
183
|
-
?: CrocheRuntime.identity(config).asJsonObject.get("storageKey").asString
|
|
184
|
-
val safe = key.replace(Regex("[^A-Za-z0-9._-]"), "_")
|
|
185
|
-
val number = options.getAsJsonObject("android")?.get("cloudProjectNumber")?.asLong
|
|
186
|
-
val attestor: RuntimeAttestor? = if (options.get("attestation")?.asString != "off" && number != null)
|
|
187
|
-
PlayIntegrityAttestor(reactApplicationContext, number) else null
|
|
188
|
-
// The founder's condition for debug keys: never silent in a shipped build.
|
|
189
|
-
val debuggable = (reactApplicationContext.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
|
|
190
|
-
if (config.has("debugKey") && !config.get("debugKey").isJsonNull && !debuggable) {
|
|
191
|
-
Log.e("Croche", "A debug key (debugKey) is set in a RELEASE build. It admits any install of this project without Play Integrity and must not ship.")
|
|
192
|
-
}
|
|
193
|
-
val delivery = options.get("backgroundDelivery")?.isJsonObject == true
|
|
194
|
-
// Each store's Runtime has its own requests and runs (Atlas, #323 P1-2).
|
|
195
|
-
val name = "${WorkManagerScheduler.DEFAULT_NAME}:$safe"
|
|
196
|
-
val runtime = CrocheRuntime.create(config,
|
|
197
|
-
FileRuntimeStorage(File(reactApplicationContext.filesDir, "croche/$safe.json")),
|
|
198
|
-
KeystoreSecretStore(reactApplicationContext, safe), attestor, handlers,
|
|
199
|
-
onEvent = { event -> emit(handle, "event", event.toString()) },
|
|
200
|
-
backgroundSync = options.get("backgroundSync")?.takeIf { it.isJsonPrimitive }?.asBoolean ?: true,
|
|
201
|
-
maintenanceIntervalMs = options.get("maintenanceIntervalMs")?.takeIf { it.isJsonPrimitive }?.asLong ?: 60_000,
|
|
202
|
-
onUsage = if (options.get("usage")?.takeIf { it.isJsonPrimitive }?.asBoolean == true) { event -> emit(handle, "usage", event.toString()) } else null,
|
|
203
|
-
scheduler = if (delivery) WorkManagerScheduler(reactApplicationContext, name) else null)
|
|
204
|
-
// Whoever delivered (the timer, a WorkManager run, the foreground), JavaScript hears
|
|
205
|
-
// of it and refreshes its cached history (rook, #323 E). The SDK's internal hook:
|
|
206
|
-
// interim, until the public subscription (F25 on #264) replaces it.
|
|
207
|
-
@OptIn(CrocheBridgeApi::class)
|
|
208
|
-
runtime.observeDeliveries { result -> emit(handle, "delivered", result.toString()) }
|
|
209
|
-
runtimes[handle] = runtime
|
|
210
|
-
if (delivery) {
|
|
211
|
-
// A run delivers through the Runtime JavaScript opened; in a process WorkManager
|
|
212
|
-
// started without JavaScript there is none, and the next foreground delivers.
|
|
213
|
-
backgrounds[name] = runtime
|
|
214
|
-
WorkManagerScheduler.deliverThrough(name) { backgrounds[name] }
|
|
215
|
-
}
|
|
216
|
-
promise.resolve(runtime.inspect().toString())
|
|
217
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/** Blocks the effect worker until JavaScript answers; a cancel or deadline interrupts it. */
|
|
222
|
-
/** JavaScript answers `{value, images?, imageResolution?}`; the images go beside the value
|
|
223
|
-
* through the SDK's withResult, which prepares them (H3). */
|
|
224
|
-
private fun toolHandler(handle: String) = withResult { invocation, context ->
|
|
225
|
-
val callId = "$handle:${context.callId}"
|
|
226
|
-
val future = CompletableFuture<JsonElement>()
|
|
227
|
-
waiters[callId] = future
|
|
228
|
-
val request = JsonObject().apply {
|
|
229
|
-
addProperty("callId", callId)
|
|
230
|
-
add("invocation", JsonObject().apply {
|
|
231
|
-
addProperty("tool", invocation.tool)
|
|
232
|
-
if (invocation.command != null) addProperty("command", invocation.command) else add("command", JsonNull.INSTANCE)
|
|
233
|
-
addProperty("key", invocation.key); add("args", invocation.args)
|
|
234
|
-
})
|
|
235
|
-
add("context", JsonObject().apply {
|
|
236
|
-
addProperty("callId", context.callId)
|
|
237
|
-
addProperty("messageId", context.messageId); addProperty("userId", context.userId)
|
|
238
|
-
if (context.agentId != null) addProperty("agentId", context.agentId) else add("agentId", JsonNull.INSTANCE)
|
|
239
|
-
})
|
|
240
|
-
}
|
|
241
|
-
emit(handle, "tool", request.toString())
|
|
242
|
-
val answer = try { future.get() }
|
|
243
|
-
catch (_: InterruptedException) {
|
|
244
|
-
emit(handle, "toolCancel", JsonObject().apply { addProperty("callId", callId) }.toString())
|
|
245
|
-
Thread.currentThread().interrupt()
|
|
246
|
-
throw CrocheException("cancelled", "The tool was cancelled")
|
|
247
|
-
} catch (failed: java.util.concurrent.ExecutionException) {
|
|
248
|
-
// resolveTool completes it with the bridge's own exceptions only: they keep their
|
|
249
|
-
// meaning (not dispatched, invalid result); nothing else reaches here.
|
|
250
|
-
when (val cause = failed.cause) {
|
|
251
|
-
is ToolNotDispatched, is CrocheException -> throw cause
|
|
252
|
-
else -> throw CrocheException("effect_failed", "The JavaScript tool failed")
|
|
253
|
-
}
|
|
254
|
-
} finally { waiters.remove(callId) }
|
|
255
|
-
toolResult(answer)
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/** A JavaScript tool's answer as a ToolResult. Images that are not a list of objects fail the
|
|
259
|
-
* call loudly (invalid_tool_result: that call alone), never silently dropped. */
|
|
260
|
-
private fun toolResult(answer: JsonElement): ToolResult {
|
|
261
|
-
val body = answer.takeIf { it.isJsonObject }?.asJsonObject ?: JsonObject()
|
|
262
|
-
val given = body.get("images")
|
|
263
|
-
val images = when {
|
|
264
|
-
given == null || given.isJsonNull -> emptyList()
|
|
265
|
-
given.isJsonArray && given.asJsonArray.all { it.isJsonObject } -> given.asJsonArray.map { it.asJsonObject }
|
|
266
|
-
else -> throw CrocheException("invalid_tool_result", "A tool result's images are a list of images. Its effects may have completed.")
|
|
267
|
-
}
|
|
268
|
-
val resolution = when (body.get("imageResolution")?.takeIf { it.isJsonPrimitive }?.asString) {
|
|
269
|
-
"high" -> ImageResolution.HIGH; "standard" -> ImageResolution.STANDARD; else -> null
|
|
270
|
-
}
|
|
271
|
-
return ToolResult(body.get("value") ?: JsonNull.INSTANCE, images, resolution)
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
override fun resolveTool(callId: String, ok: Boolean, resultJson: String) {
|
|
275
|
-
val future = waiters[callId] ?: return
|
|
276
|
-
if (ok) future.complete(try { JsonParser.parseString(resultJson) } catch (_: Exception) { JsonNull.INSTANCE })
|
|
277
|
-
// The bridge's own refusal: no JavaScript handler ran (an app error could not say so).
|
|
278
|
-
else if (bridgeCode(resultJson) == "tool_not_dispatched") future.completeExceptionally(ToolNotDispatched())
|
|
279
|
-
// The bridge's own: the handler ran and returned something unreadable (that call alone).
|
|
280
|
-
else if (bridgeCode(resultJson) == "invalid_tool_result")
|
|
281
|
-
future.completeExceptionally(CrocheException("invalid_tool_result", "The JavaScript tool returned an unreadable result. Its effects may have completed."))
|
|
282
|
-
else future.completeExceptionally(CrocheException("effect_failed", "The JavaScript tool failed"))
|
|
283
|
-
}
|
|
284
|
-
/** The code this bridge's JavaScript set on a refusal (never an app error's). */
|
|
285
|
-
private fun bridgeCode(resultJson: String) = try {
|
|
286
|
-
JsonParser.parseString(resultJson).asJsonObject.get("code")?.asString
|
|
287
|
-
} catch (_: Exception) { null }
|
|
288
|
-
|
|
289
|
-
override fun send(handle: String, inputJson: String, responseFormatJson: String, callId: String, promise: Promise) {
|
|
290
|
-
// Sends made while a turn runs are held by the Runtime and run together next: several may
|
|
291
|
-
// be in flight per handle, each cancellable by its call. Registered here, before the worker
|
|
292
|
-
// runs, so a cancelSend that follows is never a miss.
|
|
293
|
-
val key = sendKey(handle, callId)
|
|
294
|
-
val cancellation = RuntimeCancellation()
|
|
295
|
-
sending[key] = cancellation
|
|
296
|
-
if (early.remove(key)) cancellation.cancel()
|
|
297
|
-
// Admitted here, on the module's thread, in the order JS made the calls; only the wait goes
|
|
298
|
-
// to the pool. Submitting the whole send admitted them in whatever order the pool ran them
|
|
299
|
-
// (#264 F19.4, the RN run of 2026-10-06).
|
|
300
|
-
val pending = try {
|
|
301
|
-
val format = JsonParser.parseString(responseFormatJson).takeUnless { it.isJsonNull }?.asJsonObject
|
|
302
|
-
runtime(handle).beginSend(JsonParser.parseString(inputJson).asJsonObject, cancellation, format)
|
|
303
|
-
} catch (error: Exception) { sending.remove(key, cancellation); fail(promise, error); return }
|
|
304
|
-
executor.execute {
|
|
305
|
-
try { promise.resolve(pending.result().toString()) } catch (error: Exception) { fail(promise, error) }
|
|
306
|
-
finally { sending.remove(key, cancellation) }
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
private fun sendKey(handle: String, callId: String) = "$handle\u0000$callId"
|
|
311
|
-
|
|
312
|
-
override fun cancel(handle: String) { runtimes[handle]?.cancel() }
|
|
313
|
-
|
|
314
|
-
override fun cancelSend(handle: String, callId: String) {
|
|
315
|
-
val key = sendKey(handle, callId)
|
|
316
|
-
sending[key]?.let { it.cancel(); return }
|
|
317
|
-
// Not registered yet: remembered, and re-checked in case the send registered meanwhile.
|
|
318
|
-
early.add(key)
|
|
319
|
-
sending[key]?.let { if (early.remove(key)) it.cancel() }
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
override fun clearQueued(handle: String, promise: Promise) {
|
|
323
|
-
executor.execute {
|
|
324
|
-
try { promise.resolve(runtime(handle).clearQueued().toDouble()) } catch (error: Exception) { fail(promise, error) }
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
override fun inspect(handle: String, promise: Promise) {
|
|
329
|
-
executor.execute {
|
|
330
|
-
try { promise.resolve(if (agents.containsKey(handle)) streamCore(handle).inspect() else runtime(handle).inspect().toString()) } catch (error: Exception) { fail(promise, error) }
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
override fun deliverDue(handle: String, promise: Promise) {
|
|
335
|
-
executor.execute {
|
|
336
|
-
try { promise.resolve(runtime(handle).deliverDue().toString()) } catch (error: Exception) { fail(promise, error) }
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
override fun schedules(handle: String, promise: Promise) {
|
|
341
|
-
executor.execute {
|
|
342
|
-
try { promise.resolve(runtime(handle).schedules().toString()) } catch (error: Exception) { fail(promise, error) }
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
override fun maintain(handle: String, force: Boolean, promise: Promise) {
|
|
347
|
-
executor.execute {
|
|
348
|
-
try { promise.resolve(runtime(handle).maintain(force).toString()) } catch (error: Exception) { fail(promise, error) }
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
override fun adjustBudget(handle: String, amount: Double, absolute: Boolean, id: String, promise: Promise) {
|
|
353
|
-
executor.execute {
|
|
354
|
-
try { promise.resolve(runtime(handle).adjustBudget(amount, absolute, id.ifEmpty { null }).toString()) }
|
|
355
|
-
catch (error: Exception) { fail(promise, error) }
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
/** One `runtime.wiki` operation; see NativeCrocheRuntime.ts `wiki` for the ops and shapes. */
|
|
360
|
-
override fun wiki(handle: String, op: String, argsJson: String, promise: Promise) {
|
|
361
|
-
executor.execute {
|
|
362
|
-
try {
|
|
363
|
-
val args = JsonParser.parseString(argsJson).asJsonObject
|
|
364
|
-
fun text(key: String) = args.get(key)?.takeIf { it.isJsonPrimitive }?.asString
|
|
365
|
-
fun docs(): List<WikiDocument> {
|
|
366
|
-
val list = args.get("docs")?.takeIf { it.isJsonArray }?.asJsonArray
|
|
367
|
-
?: throw CrocheException("invalid_wiki", "Wiki documents are [{path, markdown, agents?}].")
|
|
368
|
-
return list.map { d ->
|
|
369
|
-
val o = d.takeIf { it.isJsonObject }?.asJsonObject
|
|
370
|
-
val path = o?.get("path")?.takeIf { it.isJsonPrimitive }?.asString
|
|
371
|
-
val markdown = o?.get("markdown")?.takeIf { it.isJsonPrimitive }?.asString
|
|
372
|
-
if (path == null || markdown == null) throw CrocheException("invalid_wiki", "Wiki documents are [{path, markdown, agents?}].")
|
|
373
|
-
WikiDocument(path, markdown, o.get("agents")?.takeIf { it.isJsonArray }?.asJsonArray?.map { it.asString })
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
val wiki by lazy { runtime(handle).wiki }
|
|
377
|
-
val out: JsonElement = when (op) {
|
|
378
|
-
"bundled" -> JsonArray().apply {
|
|
379
|
-
wikiFromAssets(reactApplicationContext.assets, text("folder") ?: "wiki").forEach {
|
|
380
|
-
add(JsonObject().apply { addProperty("path", it.path); addProperty("markdown", it.markdown) })
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
"set" -> wiki.set(docs())
|
|
384
|
-
"put" -> { wiki.put(docs()); JsonNull.INSTANCE }
|
|
385
|
-
"remove" -> JsonPrimitive(wiki.remove(text("path") ?: ""))
|
|
386
|
-
"list" -> wiki.list(text("folder"))
|
|
387
|
-
"read" -> wiki.read(text("path") ?: "", args.get("part")?.asInt ?: 1)
|
|
388
|
-
"search" -> wiki.search(text("query") ?: "", args.get("limit")?.asInt ?: 5)
|
|
389
|
-
"putUser" -> wiki.putUser(docs())
|
|
390
|
-
"removeUser" -> answer(wiki.removeUser(text("path") ?: "")) { JsonPrimitive(it) }
|
|
391
|
-
"clearUser" -> answer(wiki.clearUser()) { JsonPrimitive(it) }
|
|
392
|
-
else -> throw CrocheException("invalid_wiki", "Unknown wiki operation $op")
|
|
393
|
-
}
|
|
394
|
-
promise.resolve(out.toString())
|
|
395
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
/** One `runtime.memory` operation; see NativeCrocheRuntime.ts `memory` for the ops and shapes. */
|
|
400
|
-
override fun memory(handle: String, op: String, argsJson: String, promise: Promise) {
|
|
401
|
-
executor.execute {
|
|
402
|
-
try {
|
|
403
|
-
val args = JsonParser.parseString(argsJson).asJsonObject
|
|
404
|
-
fun text(key: String) = args.get(key)?.takeIf { it.isJsonPrimitive }?.asString
|
|
405
|
-
fun flag(key: String) = args.get(key)?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean }?.asBoolean
|
|
406
|
-
if (agents.containsKey(handle)) {
|
|
407
|
-
// Bypass the agent call queue: Core must return deferred while a turn runs.
|
|
408
|
-
val core = streamCore(handle)
|
|
409
|
-
val out = agentMemory(core, op, args) { event ->
|
|
410
|
-
enqueue(handle) { emit(handle, "memoryChanged", event) }
|
|
411
|
-
}
|
|
412
|
-
enqueue(handle) { promise.resolve(out) }
|
|
413
|
-
return@execute
|
|
414
|
-
}
|
|
415
|
-
val memory = runtime(handle).memory
|
|
416
|
-
val out: JsonElement = when (op) {
|
|
417
|
-
"list" -> memory.list()
|
|
418
|
-
"set" -> throw CrocheException("invalid_memory", "memory.set was removed: only the AI writes memories.")
|
|
419
|
-
"delete" -> memory.delete(text("id") ?: "")
|
|
420
|
-
"clear" -> memory.clear()
|
|
421
|
-
"enabled" -> answer(memory.enabled(flag("on") == true)) { JsonNull.INSTANCE }
|
|
422
|
-
"export" -> memory.export()
|
|
423
|
-
"observe" -> {
|
|
424
|
-
memory.onChanged(if (flag("on") == true) { event -> emit(handle, "memoryChanged", event.toString()) } else null)
|
|
425
|
-
JsonNull.INSTANCE
|
|
426
|
-
}
|
|
427
|
-
else -> throw CrocheException("invalid_memory", "Unknown memory operation $op")
|
|
428
|
-
}
|
|
429
|
-
promise.resolve(out.toString())
|
|
430
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
override fun setTools(handle: String, toolsJson: String, promise: Promise) {
|
|
435
|
-
executor.execute {
|
|
436
|
-
try {
|
|
437
|
-
val tools = JsonParser.parseString(toolsJson).asJsonArray
|
|
438
|
-
val names = tools.mapNotNull { it.asJsonObject.get("name")?.asString }
|
|
439
|
-
runtime(handle).setTools(tools, names.associateWith { toolHandler(handle) })
|
|
440
|
-
promise.resolve(null)
|
|
441
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
override fun clearHistory(handle: String, promise: Promise) {
|
|
446
|
-
if (agents.containsKey(handle)) {
|
|
447
|
-
dispatch(handle) {
|
|
448
|
-
try { streamCore(handle).clearHistory(); enqueue(handle) { promise.resolve(null) } }
|
|
449
|
-
catch (error: Exception) { fail(promise, error) }
|
|
450
|
-
}
|
|
451
|
-
return
|
|
452
|
-
}
|
|
453
|
-
val runtime = try { runtime(handle) } catch (error: Exception) { return fail(promise, error) }
|
|
454
|
-
// The SDK's clearHistory suspends on a thread of its own; this only waits for it.
|
|
455
|
-
suspend { runtime.clearHistory() }.startCoroutine(Continuation(EmptyCoroutineContext) { outcome ->
|
|
456
|
-
outcome.fold({ promise.resolve(null) }, { error -> fail(promise, error as? Exception ?: RuntimeException(error)) })
|
|
457
|
-
})
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
override fun close(handle: String, promise: Promise) {
|
|
461
|
-
agents[handle]?.let { agent ->
|
|
462
|
-
// Shutdown must interrupt a long history/send, rather than wait behind it.
|
|
463
|
-
executor.execute {
|
|
464
|
-
try {
|
|
465
|
-
synchronized(agent) {
|
|
466
|
-
if (!agent.closed) { agent.closed = true; agent.core.shutdown() }
|
|
467
|
-
enqueue(handle) { promise.resolve(null) }
|
|
468
|
-
retireAgent(handle, agent)
|
|
469
|
-
}
|
|
470
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
471
|
-
}
|
|
472
|
-
return
|
|
473
|
-
}
|
|
474
|
-
val runtime = runtimes.remove(handle) ?: return promise.resolve(null)
|
|
475
|
-
backgrounds.values.remove(runtime)
|
|
476
|
-
sending.keys.filter { it.startsWith("$handle\u0000") }.forEach { sending[it]?.cancel() }
|
|
477
|
-
early.removeIf { it.startsWith("$handle\u0000") }
|
|
478
|
-
executor.execute {
|
|
479
|
-
try { runtime.close(); promise.resolve(null) } catch (error: Exception) { fail(promise, error) }
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
override fun observe(handle: String, promise: Promise) {
|
|
484
|
-
dispatch(handle) {
|
|
485
|
-
try {
|
|
486
|
-
streamCore(handle).observe(
|
|
487
|
-
listener { event -> enqueue(handle) { streamMessage(handle, "observe", event) } },
|
|
488
|
-
listener { error ->
|
|
489
|
-
agents[handle]?.closed = true
|
|
490
|
-
enqueue(handle) { streamMessage(handle, "observeEnd", error) }
|
|
491
|
-
})
|
|
492
|
-
enqueue(handle) { promise.resolve(null) }
|
|
493
|
-
} catch (error: Exception) { enqueue(handle) { fail(promise, error) } }
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
override fun unobserve(handle: String) { dispatch(handle) { agents[handle]?.takeUnless { it.closed }?.core?.unobserve() } }
|
|
497
|
-
private fun safeInteger(value: Double): ULong {
|
|
498
|
-
if (!value.isFinite() || value < 0 || value > 9_007_199_254_740_991.0 || value % 1.0 != 0.0)
|
|
499
|
-
throw CrocheException("invalid_input", "Value must be a non-negative safe integer")
|
|
500
|
-
return value.toLong().toULong()
|
|
501
|
-
}
|
|
502
|
-
private fun projectionNumber(value: ULong): Double {
|
|
503
|
-
if (value > 9_007_199_254_740_991uL) throw CrocheException("invalid_input", "Projection id exceeds the safe integer range")
|
|
504
|
-
return value.toDouble()
|
|
505
|
-
}
|
|
506
|
-
override fun select(handle: String, selectionJson: String, promise: Promise) {
|
|
507
|
-
dispatch(handle) {
|
|
508
|
-
val assigned = CompletableFuture<Double>()
|
|
509
|
-
try {
|
|
510
|
-
val core = streamCore(handle)
|
|
511
|
-
val id = core.select(selectionJson, listener { event ->
|
|
512
|
-
// Core invokes initial projection callbacks before select returns its id.
|
|
513
|
-
enqueue(handle) {
|
|
514
|
-
val projection = try { assigned.get() } catch (_: Exception) { return@enqueue }
|
|
515
|
-
streamMessage(handle, "projection", event, projection)
|
|
516
|
-
}
|
|
517
|
-
})
|
|
518
|
-
val number = try { projectionNumber(id) } catch (error: Exception) { core.closeProjection(id); throw error }
|
|
519
|
-
assigned.complete(number)
|
|
520
|
-
enqueue(handle) { promise.resolve(number) }
|
|
521
|
-
} catch (error: Exception) {
|
|
522
|
-
assigned.completeExceptionally(error)
|
|
523
|
-
enqueue(handle) { fail(promise, error) }
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
override fun closeProjection(handle: String, projection: Double) {
|
|
528
|
-
val id = try { safeInteger(projection) } catch (_: CrocheException) { return }
|
|
529
|
-
dispatch(handle) { agents[handle]?.takeUnless { it.closed }?.core?.closeProjection(id) }
|
|
530
|
-
}
|
|
531
|
-
override fun history(handle: String, projection: Double, before: Double, limit: Double, promise: Promise) {
|
|
532
|
-
dispatch(handle) {
|
|
533
|
-
try {
|
|
534
|
-
val count = safeInteger(limit)
|
|
535
|
-
if (count > UInt.MAX_VALUE.toULong()) throw CrocheException("invalid_input", "History limit exceeds UInt")
|
|
536
|
-
streamCore(handle).history(safeInteger(projection), if (before == -1.0) null else safeInteger(before), count.toUInt())
|
|
537
|
-
enqueue(handle) { promise.resolve(null) }
|
|
538
|
-
} catch (error: Exception) { enqueue(handle) { fail(promise, error) } }
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
override fun readOutcome(handle: String, id: String, fromSeq: Double, readId: String, promise: Promise) {
|
|
542
|
-
dispatch(handle) {
|
|
543
|
-
try {
|
|
544
|
-
val result = streamCore(handle).readOutcome(id, safeInteger(fromSeq), listener { state ->
|
|
545
|
-
enqueue(handle) { streamMessage(handle, "captured", state, readId = readId) }
|
|
546
|
-
})
|
|
547
|
-
enqueue(handle) { promise.resolve(result) }
|
|
548
|
-
} catch (error: Exception) { enqueue(handle) { fail(promise, error) } }
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
override fun sendReceipt(handle: String, inputJson: String, responseFormatJson: String, callId: String, promise: Promise) {
|
|
552
|
-
val key = sendKey(handle, callId)
|
|
553
|
-
val cancellation = RuntimeCancellation()
|
|
554
|
-
sending[key] = cancellation
|
|
555
|
-
if (early.remove(key)) cancellation.cancel()
|
|
556
|
-
dispatch(handle) {
|
|
557
|
-
val token = CancelToken()
|
|
558
|
-
val hook = cancellation.observe { token.cancel() }
|
|
559
|
-
try {
|
|
560
|
-
val format = responseFormatJson.takeUnless { it == "null" }
|
|
561
|
-
val input = CrocheImages.prepareInput(JsonParser.parseString(inputJson).asJsonObject, null)
|
|
562
|
-
val result = streamCore(handle).send(input.toString(), token, format)
|
|
563
|
-
enqueue(handle) { promise.resolve(result) }
|
|
564
|
-
} catch (error: Exception) { enqueue(handle) { fail(promise, error) } }
|
|
565
|
-
finally { sending.remove(key, cancellation); cancellation.remove(hook); token.close() }
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
override fun cancelInput(handle: String, id: String, promise: Promise) {
|
|
569
|
-
dispatch(handle) {
|
|
570
|
-
try { streamCore(handle).cancel(id); enqueue(handle) { promise.resolve(null) } }
|
|
571
|
-
catch (error: Exception) { enqueue(handle) { fail(promise, error) } }
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
/** Forward one project's raw Core tool context; JS adds project user identities. */
|
|
575
|
-
private fun projectTool(handle: String, call: JsonObject, cancel: CancelToken): CompletableFuture<JsonElement> {
|
|
576
|
-
val context = call.getAsJsonObject("context")
|
|
577
|
-
val callId = "$handle:${context.get("callId").asString}"
|
|
578
|
-
val future = CompletableFuture<JsonElement>()
|
|
579
|
-
waiters[callId] = future
|
|
580
|
-
val invocation = call.deepCopy().apply { remove("context") }
|
|
581
|
-
val request = JsonObject().apply {
|
|
582
|
-
addProperty("callId", callId); add("invocation", invocation); add("context", context.deepCopy())
|
|
583
|
-
}
|
|
584
|
-
enqueue(handle) { emit(handle, "tool", request.toString()) }
|
|
585
|
-
cancel.onCancel(object : CancelCallback {
|
|
586
|
-
override fun cancelled() {
|
|
587
|
-
keepAttached()
|
|
588
|
-
enqueue(handle) { emit(handle, "toolCancel", JsonObject().apply { addProperty("callId", callId) }.toString()) }
|
|
589
|
-
}
|
|
590
|
-
})
|
|
591
|
-
return future
|
|
592
|
-
}
|
|
593
|
-
private fun projectToolResult(future: CompletableFuture<JsonElement>): ToolResult {
|
|
594
|
-
val answer = try { future.get() }
|
|
595
|
-
catch (_: InterruptedException) {
|
|
596
|
-
Thread.currentThread().interrupt()
|
|
597
|
-
throw CrocheException("cancelled", "The tool was cancelled")
|
|
598
|
-
} catch (failed: java.util.concurrent.ExecutionException) {
|
|
599
|
-
when (val cause = failed.cause) {
|
|
600
|
-
is ToolNotDispatched, is CrocheException -> throw cause
|
|
601
|
-
else -> throw CrocheException("effect_failed", "The JavaScript tool failed")
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
return toolResult(answer)
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
/** Existing SDK PAL, one physical namespace per project/user/agent. */
|
|
608
|
-
private inner class AgentPals(private val options: JsonObject) : HostPalFactory {
|
|
609
|
-
val hosts = ConcurrentHashMap<String, KotlinHost>()
|
|
610
|
-
private val allHosts = java.util.concurrent.CopyOnWriteArrayList<KotlinHost>()
|
|
611
|
-
val handles = ConcurrentHashMap<String, String>()
|
|
612
|
-
private val runtimeOptions = options.get("runtime")?.takeIf { it.isJsonObject }?.asJsonObject ?: options
|
|
613
|
-
private val hostConfig = options.getAsJsonObject("host")
|
|
614
|
-
private val user = options.get("user")?.takeUnless { it.isJsonNull }?.asString
|
|
615
|
-
private val timeZone = projectZone(options)
|
|
616
|
-
private val tools = options.getAsJsonArray("handlers")?.map { it.asString } ?: emptyList()
|
|
617
|
-
val attestor = projectAttestor(options) { PlayIntegrityAttestor(reactApplicationContext, it) }
|
|
618
|
-
override fun pal(agent: String): HostPal {
|
|
619
|
-
keepAttached()
|
|
620
|
-
val id = agent
|
|
621
|
-
val route = projectPalRoute(id)
|
|
622
|
-
val identity = route.identity(hostConfig, user)
|
|
623
|
-
val key = CrocheRuntime.identity(identity).asJsonObject.get("storageKey").asString
|
|
624
|
-
val safe = key.replace(Regex("[^A-Za-z0-9._-]"), "_")
|
|
625
|
-
val pending = ConcurrentHashMap<String, CompletableFuture<JsonElement>>()
|
|
626
|
-
val host = KotlinHost(FileRuntimeStorage(File(reactApplicationContext.filesDir, "croche/$safe.json")),
|
|
627
|
-
KeystoreSecretStore(reactApplicationContext, safe), attestor, RuntimeHttpURLConnection(),
|
|
628
|
-
tools.associateWith { withResult { _, context ->
|
|
629
|
-
projectToolResult(pending[context.callId] ?: throw ToolNotDispatched())
|
|
630
|
-
} }, runtimeOptions.get("backgroundSync")?.asBoolean ?: true, timeZone = timeZone)
|
|
631
|
-
.also { if (!route.maintenance) hosts[id] = it; allHosts.add(it) }
|
|
632
|
-
return object : HostPal by host {
|
|
633
|
-
override fun tool(invocation: String, cancel: CancelToken): dev.croche.ffi.ToolOutput {
|
|
634
|
-
keepAttached()
|
|
635
|
-
val call = JsonParser.parseString(invocation).asJsonObject
|
|
636
|
-
val callId = call.getAsJsonObject("context").get("callId").asString
|
|
637
|
-
val handle = handles[id] ?: throw FfiException.Failure("tool_not_dispatched", "The host tool is not available")
|
|
638
|
-
pending[callId] = projectTool(handle, call, cancel)
|
|
639
|
-
try { return host.tool(invocation, cancel) }
|
|
640
|
-
finally { pending.remove(callId); waiters.remove("$handle:$callId") }
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
fun release() { allHosts.forEach { it.deliver = null; it.stop(); it.release() }; allHosts.clear(); hosts.clear() }
|
|
645
|
-
}
|
|
646
|
-
private fun projectInfoJson(entry: ProjectEntry) = JsonObject().apply {
|
|
647
|
-
fun nullable(name: String, value: String?) { if (value == null) add(name, JsonNull.INSTANCE) else addProperty(name, value) }
|
|
648
|
-
nullable("user", entry.core.user()); nullable("installationId", entry.core.installationId())
|
|
649
|
-
nullable("crocheUserId", entry.core.crocheUserId())
|
|
650
|
-
add("agentIds", JsonArray().apply { entry.core.agentIds().forEach { add(it) } })
|
|
651
|
-
add("applied", JsonParser.parseString(entry.core.applied()))
|
|
652
|
-
}.toString()
|
|
653
|
-
private fun agentStateJson(entry: AgentEntry): JsonObject {
|
|
654
|
-
if (entry.closed) return entry.cachedState.deepCopy().apply { addProperty("closed", true) }
|
|
655
|
-
return JsonObject().apply {
|
|
656
|
-
addProperty("id", entry.core.agentId())
|
|
657
|
-
entry.core.name()?.let { addProperty("name", it) } ?: add("name", JsonNull.INSTANCE)
|
|
658
|
-
entry.core.mode()?.let { addProperty("mode", it) } ?: add("mode", JsonNull.INSTANCE)
|
|
659
|
-
val visible = entry.core.visibleTools()
|
|
660
|
-
add("visibleTools", visible?.let { JsonArray().apply { it.forEach { name -> add(name) } } } ?: JsonNull.INSTANCE)
|
|
661
|
-
addProperty("closed", entry.closed)
|
|
662
|
-
}.also { entry.cachedState = it.deepCopy() }
|
|
663
|
-
}
|
|
664
|
-
/**
|
|
665
|
-
* `Croche.deleteStore` (R8), as TypeScript: `{host, user?, config, agent?}`. The stores are the
|
|
666
|
-
* ones projectOpen with the same host and user would use; Core locks them all first and rejects
|
|
667
|
-
* `store_busy` with nothing deleted when one is open.
|
|
668
|
-
*/
|
|
669
|
-
override fun projectDeleteStore(optionsJson: String, promise: Promise) {
|
|
670
|
-
executor.execute {
|
|
671
|
-
var pals: AgentPals? = null
|
|
672
|
-
try {
|
|
673
|
-
val options = JsonParser.parseString(optionsJson).asJsonObject.apply {
|
|
674
|
-
addProperty("attestation", "off") // no agent registers or attests
|
|
675
|
-
add("runtime", JsonObject().apply { addProperty("backgroundSync", false) })
|
|
676
|
-
}
|
|
677
|
-
pals = AgentPals(options)
|
|
678
|
-
deleteStore(pals, options.get("host").toString(), options.get("user")?.takeUnless { it.isJsonNull }?.asString,
|
|
679
|
-
options.get("config").toString(), options.get("agent")?.takeUnless { it.isJsonNull }?.asString)
|
|
680
|
-
promise.resolve(null)
|
|
681
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
682
|
-
finally { pals?.release() }
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
override fun projectOpen(project: String, optionsJson: String, promise: Promise) {
|
|
686
|
-
executor.execute {
|
|
687
|
-
var pals: AgentPals? = null
|
|
688
|
-
var opened: CoreProject? = null
|
|
689
|
-
var registered: ProjectEntry? = null
|
|
690
|
-
try {
|
|
691
|
-
if (projects.containsKey(project)) throw CrocheException("invalid_configuration", "Project handle is already open")
|
|
692
|
-
val options = JsonParser.parseString(optionsJson).asJsonObject
|
|
693
|
-
pals = AgentPals(options)
|
|
694
|
-
val runtimeOptions = options.get("runtime")?.takeIf { it.isJsonObject }?.asJsonObject ?: options
|
|
695
|
-
val ffiOptions = ProjectOpenOptions(projectHost(options, pals.attestor).toString(),
|
|
696
|
-
options.get("user")?.takeUnless { it.isJsonNull }?.asString, options.get("config").toString(),
|
|
697
|
-
options.getAsJsonArray("handlers").map { it.asString },
|
|
698
|
-
options.get("language")?.takeUnless { it.isJsonNull }?.asString,
|
|
699
|
-
runtimeOptions.get("streaming")?.asBoolean ?: true, runtimeOptions.get("backgroundSync")?.asBoolean ?: true,
|
|
700
|
-
runtimeOptions.get("maintenanceIntervalMs")?.asDouble ?: 60_000.0)
|
|
701
|
-
// Debug entries only when JS passed onDebugEvent (`debug: true`); what they show is the
|
|
702
|
-
// Core's `debugVisibility`; public builds offer only `runtime`.
|
|
703
|
-
val onDebug = if (options.get("debug")?.takeIf { it.isJsonPrimitive }?.asBoolean == true)
|
|
704
|
-
listener { event -> enqueue(project) { emit(project, "debug", event) } } else null
|
|
705
|
-
opened = CoreProject.open(pals, ffiOptions, listener { event -> enqueue(project) {
|
|
706
|
-
emit(project, "usage", event)
|
|
707
|
-
} }, onDebug)
|
|
708
|
-
val entry = ProjectEntry(opened, pals)
|
|
709
|
-
if (projects.putIfAbsent(project, entry) != null) throw CrocheException("invalid_configuration", "Project handle is already open")
|
|
710
|
-
registered = entry
|
|
711
|
-
val info = projectInfoJson(entry)
|
|
712
|
-
enqueue(project) { promise.resolve(info) }
|
|
713
|
-
} catch (error: Exception) { registered?.let { projects.remove(project, it) }; opened?.shutdown(); opened?.destroy(); pals?.release(); fail(promise, error) }
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
/** RN discards codes on synchronous throws; JS unwraps this coded JSON envelope. */
|
|
717
|
-
private fun syncGetter(body: () -> String): String = try { body() } catch (error: Exception) {
|
|
718
|
-
val (code, message) = when (error) {
|
|
719
|
-
is CrocheException -> error.code to (error.message ?: "The native Runtime failed")
|
|
720
|
-
is FfiException.Failure -> error.code to error.detail
|
|
721
|
-
else -> "native_error" to "The native Runtime failed"
|
|
722
|
-
}
|
|
723
|
-
JsonObject().apply {
|
|
724
|
-
add("error", JsonObject().apply { addProperty("code", code); addProperty("message", message) })
|
|
725
|
-
}.toString()
|
|
726
|
-
}
|
|
727
|
-
override fun projectInfo(project: String): String = syncGetter { projectInfoJson(project(project)) }
|
|
728
|
-
override fun agentState(handle: String): String = syncGetter {
|
|
729
|
-
agents[handle]?.let { agentStateJson(it).toString() }
|
|
730
|
-
?: "{\"id\":\"\",\"name\":null,\"mode\":null,\"visibleTools\":null,\"closed\":true}"
|
|
731
|
-
}
|
|
732
|
-
/** The Core's name for an agent's PAL and store (`agent_slot`): its id, or `["id","instance"]`. */
|
|
733
|
-
private fun slot(core: CoreRuntime): String =
|
|
734
|
-
core.instance()?.let { JsonArray().apply { add(core.agentId()); add(it) }.toString() } ?: core.agentId()
|
|
735
|
-
/** `optionsJson`: `{instance?, fresh?, config?}` (#406), passed to Core as is. */
|
|
736
|
-
override fun projectAgent(project: String, handle: String, id: String, optionsJson: String, promise: Promise) {
|
|
737
|
-
executor.execute {
|
|
738
|
-
try {
|
|
739
|
-
val entry = project(project)
|
|
740
|
-
val options = JsonParser.parseString(optionsJson).asJsonObject
|
|
741
|
-
// Known before the open unless it is fresh; set again from Core's answer below.
|
|
742
|
-
if (options.get("fresh")?.asBoolean != true) {
|
|
743
|
-
val named = options.get("instance")?.takeUnless { it.isJsonNull }?.asString
|
|
744
|
-
val agentId = id.ifEmpty { "default" }
|
|
745
|
-
entry.pals.handles[named?.let { JsonArray().apply { add(agentId); add(it) }.toString() } ?: agentId] = handle
|
|
746
|
-
}
|
|
747
|
-
val core = entry.core.agentWithOptions(id.ifEmpty { null }, optionsJson, null)
|
|
748
|
-
val agentId = slot(core)
|
|
749
|
-
entry.pals.handles[agentId] = handle
|
|
750
|
-
val host = entry.pals.hosts.getValue(agentId)
|
|
751
|
-
val bound = AgentEntry(core, host, project)
|
|
752
|
-
agents.put(handle, bound)?.let { previous -> previous.core.destroy() }
|
|
753
|
-
val weakCore = WeakReference(core)
|
|
754
|
-
host.deliver = { weakCore.get()?.deliverDue(null); Unit }
|
|
755
|
-
host.attach(core)
|
|
756
|
-
val result = agentStateJson(bound).apply {
|
|
757
|
-
remove("closed"); addProperty("logId", core.logId())
|
|
758
|
-
core.instance()?.let { addProperty("instance", it) } ?: add("instance", JsonNull.INSTANCE)
|
|
759
|
-
addProperty("created", core.created())
|
|
760
|
-
}
|
|
761
|
-
promise.resolve(result.toString())
|
|
762
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
override fun projectClose(project: String, promise: Promise) {
|
|
766
|
-
executor.execute {
|
|
767
|
-
val entry = projects.remove(project)
|
|
768
|
-
if (entry == null) { promise.resolve(null); return@execute }
|
|
769
|
-
try {
|
|
770
|
-
entry.core.shutdown()
|
|
771
|
-
val retiring = agents.entries.filter { it.value.project == project }.map { (handle, agent) ->
|
|
772
|
-
synchronized(agent) { retireAgent(handle, agent) }
|
|
773
|
-
}
|
|
774
|
-
retiring.forEach { it.get() }
|
|
775
|
-
entry.core.destroy(); entry.pals.release()
|
|
776
|
-
enqueue(project) { promise.resolve(null) }
|
|
777
|
-
callbackQueues.remove(project)?.shutdown()
|
|
778
|
-
} catch (error: Exception) { fail(promise, error) }
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
override fun agentControl(handle: String, op: String, argsJson: String, promise: Promise) {
|
|
782
|
-
dispatch(handle) {
|
|
783
|
-
try {
|
|
784
|
-
val entry = agent(handle)
|
|
785
|
-
val args = JsonParser.parseString(argsJson).asJsonObject
|
|
786
|
-
val result = when (op) {
|
|
787
|
-
"setTools" -> {
|
|
788
|
-
val visible = args.get("visible")?.takeUnless { it.isJsonNull }
|
|
789
|
-
if (visible != null && (!visible.isJsonArray || visible.asJsonArray.any {
|
|
790
|
-
!it.isJsonPrimitive || !it.asJsonPrimitive.isString
|
|
791
|
-
})) throw CrocheException("invalid_input", "visible must be an array of strings or null")
|
|
792
|
-
streamCore(handle).setTools(visible?.asJsonArray?.map { it.asString }); "null"
|
|
793
|
-
}
|
|
794
|
-
"setMode" -> { streamCore(handle).setMode(args.get("mode")?.takeUnless { it.isJsonNull }?.asString); "null" }
|
|
795
|
-
"sync" -> { streamCore(handle).sync(); "null" }
|
|
796
|
-
else -> throw CrocheException("invalid_input", "Unknown agent control $op")
|
|
797
|
-
}
|
|
798
|
-
agentStateJson(entry)
|
|
27
|
+
private fun envelope(body: () -> Any?): String = try { json(mapOf("value" to body())) }
|
|
28
|
+
catch (e: CoreApiException.Failure) {
|
|
29
|
+
json(mapOf("error" to buildMap { put("code", e.code); put("message", e.detail); put("category", e.category); e.path?.let { put("path", it) }; e.retryAfter?.let { put("retryAfter", it.toLong()) } }))
|
|
30
|
+
}
|
|
31
|
+
override fun coreCall(handle: String, method: String, argsJson: String, images: ReadableArray, promise: Promise) {
|
|
32
|
+
// Copy owned bytes on entry, before handing work to another thread.
|
|
33
|
+
val bytes = (0 until images.size()).map { i ->
|
|
34
|
+
val row = images.getMap(i)!!; val input = row.getArray("bytes")!!
|
|
35
|
+
CoreAttachmentInput(row.getDouble("element").toLong().toUInt(), ByteArray(input.size()) { input.getDouble(it).toInt().toByte() })
|
|
36
|
+
}
|
|
37
|
+
worker.launch {
|
|
38
|
+
try {
|
|
39
|
+
val a = args(argsJson)
|
|
40
|
+
val result = if (method == "open" && handle.isEmpty()) {
|
|
41
|
+
try { json(mapOf("value" to core.open(a))) }
|
|
42
|
+
catch (e: CoreApiException.Failure) { envelope { throw e } }
|
|
43
|
+
} else envelope { core.call(handle, method, a, bytes) }
|
|
799
44
|
promise.resolve(result)
|
|
800
|
-
} catch (
|
|
45
|
+
} catch (e: Throwable) { promise.reject("native_transport", e.message, e) }
|
|
801
46
|
}
|
|
802
47
|
}
|
|
803
|
-
override fun
|
|
804
|
-
|
|
48
|
+
override fun coreCallSync(handle: String, method: String, argsJson: String): String = envelope { core.call(handle, method, args(argsJson)) }
|
|
49
|
+
override fun coreReply(call: String, completionJson: String) { core.callbacks.reply(call, completionJson) }
|
|
50
|
+
override fun platformCall(method: String, argsJson: String, promise: Promise) {
|
|
51
|
+
worker.launch { try { promise.resolve(platformCallSync(method, argsJson)) } catch (e: Throwable) { promise.reject("native_transport", e.message, e) } }
|
|
805
52
|
}
|
|
806
|
-
|
|
53
|
+
override fun platformCallSync(method: String, argsJson: String): String = try { json(mapOf("value" to pal.call(method, args(argsJson)))) }
|
|
54
|
+
catch (e: CoreStorageFailure.Failure) { json(mapOf("error" to mapOf("detail" to e.detail))) }
|
|
55
|
+
catch (e: CorePalException.Failure) { json(mapOf("error" to mapOf("code" to e.code, "detail" to e.detail))) }
|
|
807
56
|
override fun addListener(eventName: String) {}
|
|
808
57
|
override fun removeListeners(count: Double) {}
|
|
809
|
-
|
|
810
58
|
override fun invalidate() {
|
|
811
|
-
|
|
812
|
-
val openedAgents = agents.values.toList()
|
|
813
|
-
projects.clear(); agents.clear()
|
|
814
|
-
executor.execute {
|
|
815
|
-
openedProjects.forEach { entry -> try { entry.core.shutdown() } catch (_: Exception) {} }
|
|
816
|
-
agentWorkers.values.forEach { it.shutdown() }
|
|
817
|
-
agentWorkers.values.forEach { it.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS) }
|
|
818
|
-
openedProjects.forEach { entry -> try { entry.core.destroy(); entry.pals.release() } catch (_: Exception) {} }
|
|
819
|
-
openedAgents.forEach { entry -> try { entry.core.destroy() } catch (_: Exception) {} }
|
|
820
|
-
callbackQueues.values.forEach { it.shutdown() }
|
|
821
|
-
}
|
|
822
|
-
runtimes.values.forEach { runtime -> try { runtime.close() } catch (_: Exception) {} }
|
|
823
|
-
runtimes.clear(); backgrounds.clear(); executor.shutdown()
|
|
824
|
-
super.invalidate()
|
|
59
|
+
core.callbacks.invalidate(); core.handles.clear(); worker.cancel(); super.invalidate()
|
|
825
60
|
}
|
|
826
|
-
|
|
827
|
-
companion object {
|
|
828
|
-
const val NAME = "CrocheRuntime"
|
|
829
|
-
const val EVENT = "CrocheRuntimeEvent"
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
/** A write's answer as the JS side reads it: what it did, or `{deferred: true}`. */
|
|
834
|
-
private fun <T> answer(result: WriteResult<T>, applied: (T) -> JsonElement): JsonElement = when (result) {
|
|
835
|
-
is WriteResult.Applied -> applied(result.value)
|
|
836
|
-
WriteResult.Deferred -> JsonObject().apply { addProperty("deferred", true) }
|
|
837
61
|
}
|