@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,110 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import com.google.gson.GsonBuilder
|
|
4
|
-
import com.google.gson.TypeAdapter
|
|
5
|
-
import com.google.gson.stream.JsonReader
|
|
6
|
-
import com.google.gson.stream.JsonWriter
|
|
7
|
-
import kotlinx.coroutines.channels.Channel
|
|
8
|
-
import java.time.Instant
|
|
9
|
-
|
|
10
|
-
/** Isolated serial delivery, bounded including the event currently in the collector. */
|
|
11
|
-
internal class AppStreamBranch {
|
|
12
|
-
private data class Item(val event: RuntimeEvent, val bytes: Int)
|
|
13
|
-
private val lock = Any()
|
|
14
|
-
private val wake = Channel<Unit>(Channel.CONFLATED)
|
|
15
|
-
private val queue = ArrayDeque<Item>()
|
|
16
|
-
private var count = 0
|
|
17
|
-
private var bytes = 0
|
|
18
|
-
private var ended = false
|
|
19
|
-
private var terminal: RuntimeEvent? = null
|
|
20
|
-
val isEnded get() = synchronized(lock) { ended }
|
|
21
|
-
|
|
22
|
-
/** Core-delivered events stay ordered, including a final StreamError behind the backlog. */
|
|
23
|
-
fun push(event: RuntimeEvent) = synchronized(lock) {
|
|
24
|
-
if (ended) return@synchronized
|
|
25
|
-
val item = try {
|
|
26
|
-
val json = event.serialized()
|
|
27
|
-
Item(event.owned(), json.toByteArray(Charsets.UTF_8).size)
|
|
28
|
-
} catch (failure: Exception) {
|
|
29
|
-
end(RuntimeEvent.StreamError("handler_failed", "Event could not be queued", false))
|
|
30
|
-
return@synchronized
|
|
31
|
-
}
|
|
32
|
-
if (count + 1 > 256 || bytes.toLong() + item.bytes > 1_048_576) {
|
|
33
|
-
end(RuntimeEvent.StreamError("subscriber_overflow", "Collector fell behind", false))
|
|
34
|
-
return@synchronized
|
|
35
|
-
}
|
|
36
|
-
queue.addLast(item)
|
|
37
|
-
count++
|
|
38
|
-
bytes += item.bytes
|
|
39
|
-
if (event is RuntimeEvent.StreamError || event === RuntimeEvent.Replaced) ended = true
|
|
40
|
-
wake.trySend(Unit)
|
|
41
|
-
}
|
|
42
|
-
/** SDK-side termination drops queued work; an in-flight delivery settles before last. */
|
|
43
|
-
fun end(last: RuntimeEvent? = null) = synchronized(lock) {
|
|
44
|
-
if (ended) return@synchronized
|
|
45
|
-
ended = true
|
|
46
|
-
queue.clear()
|
|
47
|
-
terminal = last
|
|
48
|
-
wake.trySend(Unit)
|
|
49
|
-
}
|
|
50
|
-
fun close() = end()
|
|
51
|
-
|
|
52
|
-
suspend fun deliver(emit: suspend (RuntimeEvent) -> Unit) {
|
|
53
|
-
while (true) {
|
|
54
|
-
val delivery = synchronized(lock) { Triple(queue.removeFirstOrNull(), ended, terminal) }
|
|
55
|
-
val item = delivery.first
|
|
56
|
-
if (item != null) {
|
|
57
|
-
// Flow's downstream exception/cancellation belongs to the collecting coroutine.
|
|
58
|
-
// The Kotlin page explicitly requires a downstream collector exception to
|
|
59
|
-
// leave collect and detach only this branch; never emit after that exception.
|
|
60
|
-
try { emit(item.event) }
|
|
61
|
-
finally { synchronized(lock) { count--; bytes -= item.bytes } }
|
|
62
|
-
continue
|
|
63
|
-
}
|
|
64
|
-
if (delivery.second) {
|
|
65
|
-
delivery.third?.let { emit(it) }
|
|
66
|
-
return
|
|
67
|
-
}
|
|
68
|
-
wake.receive()
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
private val eventJson = GsonBuilder().disableHtmlEscaping().registerTypeAdapter(Instant::class.java, object : TypeAdapter<Instant>() {
|
|
74
|
-
override fun write(out: JsonWriter, value: Instant?) { if (value == null) out.nullValue() else out.value(value.toString()) }
|
|
75
|
-
override fun read(input: JsonReader): Instant = Instant.parse(input.nextString())
|
|
76
|
-
}).create()
|
|
77
|
-
|
|
78
|
-
/** Copy nested app-owned containers; Page requires recursive copying of polymorphic messages. */
|
|
79
|
-
internal fun RuntimeEvent.owned(): RuntimeEvent = when (this) {
|
|
80
|
-
is RuntimeEvent.Input -> copy(images = images.toList())
|
|
81
|
-
is RuntimeEvent.MessageEnd -> copy(markers = markers.toList(), output = output?.deepCopy(), inReplyTo = inReplyTo.toList(), causedBy = causedBy.toList())
|
|
82
|
-
is RuntimeEvent.App -> copy(data = data.deepCopy())
|
|
83
|
-
is RuntimeEvent.Turn -> copy(causedBy = causedBy.toList(), inputs = inputs.toList(), usage = usage.toMap())
|
|
84
|
-
is RuntimeEvent.Error -> copy(inputs = inputs.toList())
|
|
85
|
-
is RuntimeEvent.Page -> copy(messages = messages.map { it.owned() })
|
|
86
|
-
else -> this
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** Tagged delivery payload, UTF-8 bytes including event structure as in S2's queue. */
|
|
90
|
-
internal fun RuntimeEvent.serialized(): String {
|
|
91
|
-
val json = eventJson.toJsonTree(this).asJsonObject
|
|
92
|
-
val type = when (this) {
|
|
93
|
-
is RuntimeEvent.Input -> "input"
|
|
94
|
-
is RuntimeEvent.MessageStart -> "message.start"
|
|
95
|
-
is RuntimeEvent.MessageDelta -> "message.delta"
|
|
96
|
-
is RuntimeEvent.MessageEnd -> "message.end"
|
|
97
|
-
is RuntimeEvent.Cleared -> "cleared"
|
|
98
|
-
is RuntimeEvent.App -> "app"
|
|
99
|
-
is RuntimeEvent.Turn -> "turn"
|
|
100
|
-
is RuntimeEvent.Error, is RuntimeEvent.StreamError -> "error"
|
|
101
|
-
is RuntimeEvent.State -> "state"
|
|
102
|
-
is RuntimeEvent.Page -> "page"
|
|
103
|
-
is RuntimeEvent.Gap -> "gap"
|
|
104
|
-
is RuntimeEvent.Snapshot -> "snapshot"
|
|
105
|
-
RuntimeEvent.Replaced -> "replaced"
|
|
106
|
-
is RuntimeEvent.Unknown -> this.type
|
|
107
|
-
}
|
|
108
|
-
json.addProperty("type", type)
|
|
109
|
-
return eventJson.toJson(json)
|
|
110
|
-
}
|
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import com.google.gson.*
|
|
4
|
-
import java.net.URI
|
|
5
|
-
import java.util.UUID
|
|
6
|
-
import java.util.concurrent.*
|
|
7
|
-
import java.util.concurrent.atomic.AtomicBoolean
|
|
8
|
-
|
|
9
|
-
fun interface ControlSend { fun send(input: JsonObject, cancellation: RuntimeCancellation): JsonElement }
|
|
10
|
-
fun interface ControlCancel { fun cancel(): Boolean }
|
|
11
|
-
|
|
12
|
-
/** Explicit local attachment, independent of Cloud credentials and Runtime ownership.
|
|
13
|
-
* Close this connection separately; it never opens/closes the Runtime's private store. */
|
|
14
|
-
class RuntimeControl private constructor(
|
|
15
|
-
private val runtime: CrocheRuntime, private val url: String, private val token: String,
|
|
16
|
-
private val http: RuntimeHTTP, private val sendAdapter: ControlSend?, private val cancelAdapter: ControlCancel?,
|
|
17
|
-
private val onError: ((String) -> Unit)?
|
|
18
|
-
) : AutoCloseable {
|
|
19
|
-
val runtimeInstanceId = runtime.inspect().at("status").at("runtimeInstanceId").text()
|
|
20
|
-
val capabilities: List<String> = listOf("status", "history", "send", "cancel", "sync", "budget.get", "budget.set", "tools")
|
|
21
|
-
private val clientId = UUID.randomUUID().toString()
|
|
22
|
-
private val lifetime = RuntimeCancellation()
|
|
23
|
-
private val effects = EffectExecutor()
|
|
24
|
-
private val closed = AtomicBoolean(false)
|
|
25
|
-
private val handled = ConcurrentHashMap.newKeySet<String>()
|
|
26
|
-
private val results = ConcurrentHashMap<String, JsonObject>()
|
|
27
|
-
private val active = ConcurrentHashMap<String, RuntimeCancellation>()
|
|
28
|
-
private val tasks = ConcurrentHashMap.newKeySet<String>()
|
|
29
|
-
private val workers = ThreadPoolExecutor(0, 16, 30, TimeUnit.SECONDS, SynchronousQueue(),
|
|
30
|
-
ThreadFactory { task -> Thread(task, "croche-control-command").apply { isDaemon = true } })
|
|
31
|
-
private var poller: Thread? = null
|
|
32
|
-
companion object {
|
|
33
|
-
fun attach(runtime: CrocheRuntime, token: String, url: String = "http://127.0.0.1:8791",
|
|
34
|
-
http: RuntimeHTTP = RuntimeHttpURLConnection(), send: ControlSend? = null,
|
|
35
|
-
cancel: ControlCancel? = null, onError: ((String) -> Unit)? = null): RuntimeControl {
|
|
36
|
-
val parsed = try { URI(url) } catch (_: Exception) { throw CrocheException("invalid_configuration", "Invalid local control URL") }
|
|
37
|
-
if (parsed.scheme != "http" || parsed.host !in listOf("127.0.0.1", "localhost", "[::1]", "::1") ||
|
|
38
|
-
parsed.userInfo != null || parsed.query != null || parsed.fragment != null || parsed.path !in listOf("", "/") ||
|
|
39
|
-
!Regex("^[A-Za-z0-9._~-]{24,4096}$").matches(token)) {
|
|
40
|
-
throw CrocheException("invalid_configuration", "Control needs a loopback HTTP origin and explicit local token")
|
|
41
|
-
}
|
|
42
|
-
val control = RuntimeControl(runtime, url.removeSuffix("/"), token, http, send, cancel, onError)
|
|
43
|
-
try { control.register(); control.start() }
|
|
44
|
-
catch (error: Exception) { control.release(); throw error }
|
|
45
|
-
return control
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
private fun identity() = obj("client_id" to str(clientId), "runtime_instance_id" to str(runtimeInstanceId))
|
|
49
|
-
private fun register() {
|
|
50
|
-
val caps = JsonArray(); capabilities.forEach { caps.add(it) }
|
|
51
|
-
post("register", obj("client_id" to str(clientId), "runtime" to runtime.inspect().at("status"), "capabilities" to caps))
|
|
52
|
-
}
|
|
53
|
-
private fun post(path: String, body: JsonObject): JsonObject {
|
|
54
|
-
if (body.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("control_capacity", "Control request exceeds 1MiB")
|
|
55
|
-
val effect = obj("url" to str("$url/v1/control/$path"), "method" to str("POST"),
|
|
56
|
-
"headers" to obj("Authorization" to str("Bearer $token"), "Content-Type" to str("application/json")),
|
|
57
|
-
"body" to body, "timeoutMs" to num(5000))
|
|
58
|
-
val response = effects.run(5000, lifetime) { signal -> http.execute(effect, signal) {} }
|
|
59
|
-
val data = response.at("body")
|
|
60
|
-
if (!data.isJsonObject || data.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("invalid_response", "Invalid bounded control response")
|
|
61
|
-
if (response.at("status").asInt !in 200..299) {
|
|
62
|
-
val code = data.at("error").at("code").text()
|
|
63
|
-
throw CrocheException(if (code in setOf("attachment_lost", "not_found", "unauthorized", "runtime_already_attached")) code else "control_error", "Local control broker rejected the request")
|
|
64
|
-
}
|
|
65
|
-
return data.asJsonObject
|
|
66
|
-
}
|
|
67
|
-
private fun start() {
|
|
68
|
-
poller = Thread({
|
|
69
|
-
while (!closed.get()) {
|
|
70
|
-
try {
|
|
71
|
-
results.entries.take(8).forEach { (id, result) ->
|
|
72
|
-
try { post("results", result); results.remove(id) }
|
|
73
|
-
catch (error: CrocheException) { if (error.code in listOf("not_found", "attachment_lost")) results.remove(id); throw error }
|
|
74
|
-
}
|
|
75
|
-
if (results.size < 32 && tasks.size < 16) {
|
|
76
|
-
val data = post("poll", identity())
|
|
77
|
-
if (!data.at("commands").isJsonArray) throw CrocheException("invalid_response", "Invalid broker command list")
|
|
78
|
-
data.at("commands").asJsonArray.take(8).forEach { accept(it) }
|
|
79
|
-
}
|
|
80
|
-
} catch (error: Exception) {
|
|
81
|
-
if (!closed.get()) {
|
|
82
|
-
try { onError?.invoke("Local control could not complete a request") } catch (_: Exception) {}
|
|
83
|
-
if (error is CrocheException && error.code == "attachment_lost") try { register() } catch (_: Exception) {}
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
try { Thread.sleep(100) } catch (_: InterruptedException) { if (closed.get()) break }
|
|
87
|
-
}
|
|
88
|
-
}, "croche-control-poll").apply { isDaemon = true; start() }
|
|
89
|
-
}
|
|
90
|
-
private fun accept(value: JsonElement) {
|
|
91
|
-
val id = value.at("request_id").text(); val command = value.at("command").text(); val payload = value.at("payload")
|
|
92
|
-
if (!validId(id) || command !in capabilities || !payload.isJsonObject) throw CrocheException("invalid_command", "Invalid broker command envelope")
|
|
93
|
-
if (handled.contains(id)) return
|
|
94
|
-
if (handled.size >= 1000) throw CrocheException("control_capacity", "Reattach after 1000 control requests")
|
|
95
|
-
handled.add(id); tasks.add(id)
|
|
96
|
-
val work = Runnable {
|
|
97
|
-
val reply = identity().apply { addProperty("request_id", id) }
|
|
98
|
-
try {
|
|
99
|
-
val result = execute(command, payload.asJsonObject.deepCopy(), id)
|
|
100
|
-
if (result.toString().toByteArray(Charsets.UTF_8).size > 900000) throw CrocheException("result_too_large", "Request a smaller result page")
|
|
101
|
-
reply.add("result", result.deepCopy())
|
|
102
|
-
} catch (error: Exception) {
|
|
103
|
-
val code = (error as? CrocheException)?.code
|
|
104
|
-
reply.add("error", obj("code" to str(if (code in publicCodes) code!! else "runtime_error"),
|
|
105
|
-
"message" to str("The Runtime command failed. Inspect it before retrying."),
|
|
106
|
-
"uncertain" to bool(command == "send" || command == "budget.set")))
|
|
107
|
-
} finally { tasks.remove(id) }
|
|
108
|
-
if (!closed.get()) results[id] = reply
|
|
109
|
-
}
|
|
110
|
-
try { workers.execute(work) }
|
|
111
|
-
catch (_: RejectedExecutionException) {
|
|
112
|
-
tasks.remove(id)
|
|
113
|
-
results[id] = identity().apply {
|
|
114
|
-
addProperty("request_id", id)
|
|
115
|
-
add("error", obj("code" to str("control_capacity"), "message" to str("Control workers are occupied"), "uncertain" to bool(false)))
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
private fun execute(command: String, payload: JsonObject, id: String): JsonElement {
|
|
120
|
-
if (closed.get()) throw CrocheException("control_closed", "Control is closed")
|
|
121
|
-
fun keys(allowed: Set<String>) { if (!allowed.containsAll(payload.keySet())) throw CrocheException("invalid_command", "Unsupported command fields") }
|
|
122
|
-
if (command == "send") {
|
|
123
|
-
keys(setOf("id", "text"))
|
|
124
|
-
val text = payload.at("text").text()
|
|
125
|
-
if (!validId(payload.at("id").text()) || text.isBlank() || text.length > 32000) throw CrocheException("invalid_command", "send needs immutable id and text only")
|
|
126
|
-
val signal = RuntimeCancellation(); active[id] = signal
|
|
127
|
-
try { return sendAdapter?.send(payload, signal) ?: runtime.send(payload, signal) }
|
|
128
|
-
finally { active.remove(id) }
|
|
129
|
-
}
|
|
130
|
-
if (command == "history") {
|
|
131
|
-
keys(setOf("offset", "limit"))
|
|
132
|
-
fun integer(key: String, default: Int, min: Int, max: Int): Int {
|
|
133
|
-
if (!payload.has(key)) return default
|
|
134
|
-
val value = payload[key]
|
|
135
|
-
if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber) throw CrocheException("invalid_command", "Invalid history page")
|
|
136
|
-
val number = value.asDouble
|
|
137
|
-
if (!number.isFinite() || number < min || number > max || number != kotlin.math.floor(number)) throw CrocheException("invalid_command", "Invalid history page")
|
|
138
|
-
return number.toInt()
|
|
139
|
-
}
|
|
140
|
-
val offset = integer("offset", 0, 0, 1000000); val limit = integer("limit", 100, 1, 200)
|
|
141
|
-
val history = runtime.inspect().at("history").asJsonArray; val page = JsonArray()
|
|
142
|
-
history.drop(offset).take(limit).forEach { page.add(it.deepCopy()) }
|
|
143
|
-
return obj("messages" to page, "total" to num(history.size()), "offset" to num(offset), "limit" to num(limit))
|
|
144
|
-
}
|
|
145
|
-
if (command == "budget.set") {
|
|
146
|
-
keys(setOf("amount")); val value = payload.at("amount")
|
|
147
|
-
if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber || !value.asDouble.isFinite() || value.asDouble < 0) throw CrocheException("invalid_command", "Budget requires a finite non-negative amount")
|
|
148
|
-
return runtime.adjustBudget(value.asDouble, absolute = true)
|
|
149
|
-
}
|
|
150
|
-
keys(emptySet())
|
|
151
|
-
if (command == "cancel") {
|
|
152
|
-
val pending = active.isNotEmpty(); active.values.forEach { it.cancel() }
|
|
153
|
-
val host = cancelAdapter?.cancel() ?: false
|
|
154
|
-
return obj("requested" to bool(pending || host), "scope" to str(if (cancelAdapter != null) "host" else "control_client"), "rollback" to bool(false))
|
|
155
|
-
}
|
|
156
|
-
if (command == "sync") runtime.sync()
|
|
157
|
-
val view = runtime.inspect()
|
|
158
|
-
return when (command) {
|
|
159
|
-
"status" -> view.at("status").deepCopy().asJsonObject.apply {
|
|
160
|
-
add("control", obj("cancellation_scope" to str(if (cancelAdapter != null) "host" else "control_client")))
|
|
161
|
-
}
|
|
162
|
-
"sync" -> view.at("status")
|
|
163
|
-
"tools" -> view.at("tools")
|
|
164
|
-
"budget.get" -> view.at("budget")
|
|
165
|
-
else -> throw CrocheException("unsupported_capability", "Unsupported Runtime command")
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
override fun close() {
|
|
169
|
-
if (!closed.compareAndSet(false, true)) return
|
|
170
|
-
active.values.forEach { it.cancel() }
|
|
171
|
-
try { post("unregister", identity()) } catch (_: Exception) {}
|
|
172
|
-
release()
|
|
173
|
-
if (Thread.currentThread() != poller) poller?.join(6000)
|
|
174
|
-
}
|
|
175
|
-
private fun release() { closed.set(true); lifetime.cancel(); effects.close(); workers.shutdown(); poller?.interrupt() }
|
|
176
|
-
}
|
|
177
|
-
private fun validId(value: String) = Regex("^[A-Za-z0-9_.:-]{1,200}$").matches(value)
|
|
178
|
-
private val publicCodes = setOf("invalid_command", "control_closed", "unsupported_capability", "result_too_large", "busy", "closed", "storage_error", "context_limit", "budget_limit")
|
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import com.google.gson.*
|
|
4
|
-
import dev.croche.ffi.CoreRuntime
|
|
5
|
-
import dev.croche.ffi.EventListener
|
|
6
|
-
import kotlinx.coroutines.Dispatchers
|
|
7
|
-
import kotlinx.coroutines.withContext
|
|
8
|
-
import java.time.Instant
|
|
9
|
-
import java.util.concurrent.atomic.AtomicBoolean
|
|
10
|
-
import kotlin.coroutines.suspendCoroutine
|
|
11
|
-
|
|
12
|
-
/** The only native subscription boundary. Core owns projection, capture and durable ordering. */
|
|
13
|
-
internal class NativeCoreStreamPort(private val core: CoreRuntime, private val host: KotlinHost) : CoreStreamPort {
|
|
14
|
-
private val closed = AtomicBoolean()
|
|
15
|
-
private val observationDetached = AtomicBoolean()
|
|
16
|
-
/** Test-only pause after Core dispatch/decoding, before forwarding to the SDK branch. */
|
|
17
|
-
@Volatile internal var projectionDeliveryStarting: ((RuntimeEvent) -> Unit)? = null
|
|
18
|
-
@Volatile internal var projectionDeliveryFinished: ((RuntimeEvent) -> Unit)? = null
|
|
19
|
-
@Volatile internal var projectionCloseFenced: (() -> Unit)? = null
|
|
20
|
-
@Volatile private var currentState = RuntimeEvent.State(AgentStatus.IDLE, 0, false)
|
|
21
|
-
override val state get() = currentState
|
|
22
|
-
override val logId get() = call { core.logId() }
|
|
23
|
-
private fun <T> call(body: () -> T): T {
|
|
24
|
-
if (closed.get()) throw CrocheException("closed", "Runtime is closed")
|
|
25
|
-
return try { nativeCall(body) } catch (error: Exception) { throw crocheError(error) }
|
|
26
|
-
}
|
|
27
|
-
private fun <T> nativeCall(body: () -> T): T {
|
|
28
|
-
CrocheRuntime.offloadStarting?.invoke()
|
|
29
|
-
return body()
|
|
30
|
-
}
|
|
31
|
-
private suspend fun <T> blocking(body: () -> T): T = withContext(Dispatchers.IO) { call(body) }
|
|
32
|
-
private fun listener(callback: (JsonObject) -> Unit) = object : EventListener {
|
|
33
|
-
override fun onEvent(event: String) { keepAttached(); callback(JsonParser.parseString(event).asJsonObject) }
|
|
34
|
-
}
|
|
35
|
-
override fun observe(event: (RuntimeEvent) -> Unit, end: (Throwable?) -> Unit): AutoCloseable {
|
|
36
|
-
call {
|
|
37
|
-
core.observe(listener { value ->
|
|
38
|
-
// Core's consuming-unit record is internal, never projected as an app event.
|
|
39
|
-
if (value.at("type").text() != "unit.end") {
|
|
40
|
-
val decoded = nativeEvent(value)
|
|
41
|
-
if (decoded is RuntimeEvent.State) currentState = decoded
|
|
42
|
-
event(decoded)
|
|
43
|
-
}
|
|
44
|
-
}, listener { value ->
|
|
45
|
-
end(CoreStreamFailure(value.at("code").text(), value.at("message").text(), value.flag("poisoned")))
|
|
46
|
-
})
|
|
47
|
-
}
|
|
48
|
-
observationDetached.set(false)
|
|
49
|
-
return AutoCloseable { unobserve() }
|
|
50
|
-
}
|
|
51
|
-
internal fun unobserve() {
|
|
52
|
-
if (observationDetached.compareAndSet(false, true) && !closed.get()) call { core.unobserve() }
|
|
53
|
-
}
|
|
54
|
-
override fun select(initialMessages: Int?, after: Cursor?, event: (RuntimeEvent) -> Unit): CoreStreamPort.Projection {
|
|
55
|
-
val selection = JsonObject().apply {
|
|
56
|
-
if (after != null) add("after", JsonObject().apply { addProperty("logId", after.logId); add("seq", JsonParser.parseString(coreSequence(after.seq).toString())) })
|
|
57
|
-
else initialMessages?.let { addProperty("initialMessages", it) }
|
|
58
|
-
}
|
|
59
|
-
val delivery = Any()
|
|
60
|
-
val detached = AtomicBoolean()
|
|
61
|
-
val id = call { core.select(selection.toString(), listener {
|
|
62
|
-
val decoded = nativeEvent(it)
|
|
63
|
-
projectionDeliveryStarting?.invoke(decoded)
|
|
64
|
-
// Stop forwarding once detached. Core close then joins the complete callback,
|
|
65
|
-
// including decoding and these hooks, unless it is this callback's own close.
|
|
66
|
-
try { synchronized(delivery) { if (!detached.get()) event(decoded) } }
|
|
67
|
-
finally { projectionDeliveryFinished?.invoke(decoded) }
|
|
68
|
-
}) }
|
|
69
|
-
return object : CoreStreamPort.Projection {
|
|
70
|
-
override fun close() {
|
|
71
|
-
val first = synchronized(delivery) { detached.compareAndSet(false, true) }
|
|
72
|
-
// The callback may still need delivery. Never hold its monitor across the
|
|
73
|
-
// Core listener-completion wait; a self-close stays on the callback thread.
|
|
74
|
-
if (first && !closed.get()) {
|
|
75
|
-
projectionCloseFenced?.invoke()
|
|
76
|
-
call { core.closeProjection(id) }
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
override suspend fun history(before: Long?, limit: Int) {
|
|
80
|
-
blocking { core.history(id, before?.let(::coreSequence), limit.toUInt()) }
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
override suspend fun send(input: JsonObject, options: SendOptions): Receipt = blocking {
|
|
85
|
-
// The only receipt-send FFI call site.
|
|
86
|
-
val value = JsonParser.parseString(core.send(input.toString(), null, options.responseFormat?.toString())).asJsonObject
|
|
87
|
-
Receipt(value.at("id").text(), nativeEnum(value.at("status")), value.optionalLong("seq"))
|
|
88
|
-
}
|
|
89
|
-
override suspend fun readOutcome(id: String, fromSeq: Long, captured: (CapturedOutcome) -> Unit): RetainedEnds = blocking {
|
|
90
|
-
val value = JsonParser.parseString(core.readOutcome(id, coreSequence(fromSeq), listener { at ->
|
|
91
|
-
captured(CapturedOutcome(at.number("head"), at.number("floor"), nativeEnum(at.at("status")), at.flag("idle")))
|
|
92
|
-
})).asJsonObject
|
|
93
|
-
RetainedEnds(value.list("messages").map { nativeEvent(it.asJsonObject) as RuntimeEvent.MessageEnd }, value.flag("gap"))
|
|
94
|
-
}
|
|
95
|
-
override suspend fun cancel(id: String) = blocking { core.cancel(id) }
|
|
96
|
-
override suspend fun clearHistory() {
|
|
97
|
-
// Take the Core's admission place on the caller before offloading only the wait.
|
|
98
|
-
val pending = call { core.beginClearHistory() }
|
|
99
|
-
suspendCoroutine<Unit> { continuation ->
|
|
100
|
-
Thread({
|
|
101
|
-
OffloadSeam.starting?.invoke()
|
|
102
|
-
continuation.resumeWith(runCatching { try { call { pending.finish() }; Unit } finally { nativeCall { pending.close() } } })
|
|
103
|
-
}, "croche-offload").apply { isDaemon = true }.start()
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
override fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) {
|
|
107
|
-
val stamp = host.stageTools(handlers)
|
|
108
|
-
try { call { core.setToolDeclarations(tools.toString()) } }
|
|
109
|
-
catch (error: Exception) { host.unstageTools(handlers.keys, stamp); throw error }
|
|
110
|
-
host.acceptTools(handlers)
|
|
111
|
-
}
|
|
112
|
-
override fun close() {
|
|
113
|
-
if (!closed.compareAndSet(false, true)) return
|
|
114
|
-
host.stop()
|
|
115
|
-
try { nativeCall { core.shutdown() } } catch (error: Exception) { throw crocheError(error) } finally { nativeCall { core.destroy() }; host.release() }
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
internal fun publicSequence(value: ULong): Long {
|
|
120
|
-
if (value > Long.MAX_VALUE.toULong()) throw CrocheException("invalid_input", "Core sequence exceeds Long.MAX_VALUE")
|
|
121
|
-
return value.toLong()
|
|
122
|
-
}
|
|
123
|
-
internal fun coreSequence(value: Long): ULong {
|
|
124
|
-
if (value < 0) throw CrocheException("invalid_input", "Sequence must not be negative")
|
|
125
|
-
return value.toULong()
|
|
126
|
-
}
|
|
127
|
-
private fun JsonElement.sequence(): Long {
|
|
128
|
-
val value = asString.toULongOrNull() ?: throw CrocheException("invalid_input", "Core sequence is not an unsigned integer")
|
|
129
|
-
return publicSequence(value)
|
|
130
|
-
}
|
|
131
|
-
private fun JsonObject.number(name: String) = get(name).sequence()
|
|
132
|
-
private fun JsonObject.optionalLong(name: String) = get(name)?.takeUnless { it.isJsonNull }?.sequence()
|
|
133
|
-
private fun JsonObject.flag(name: String) = get(name)?.takeUnless { it.isJsonNull }?.asBoolean ?: false
|
|
134
|
-
private fun JsonObject.list(name: String): List<JsonElement> = get(name)?.takeIf { it.isJsonArray }?.asJsonArray?.toList() ?: emptyList()
|
|
135
|
-
private fun JsonObject.strings(name: String) = list(name).map { it.asString }
|
|
136
|
-
private inline fun <reified E : Enum<E>> nativeEnum(value: JsonElement): E =
|
|
137
|
-
enumValues<E>().firstOrNull { it.name.equals(value.text(), ignoreCase = true) } ?: enumValueOf("UNKNOWN")
|
|
138
|
-
private fun JsonObject.error() = get("error")?.takeIf { it.isJsonObject }?.asJsonObject?.let { RuntimeError(it.at("code").text(), it.at("message").text()) }
|
|
139
|
-
|
|
140
|
-
/** Decode the Core's tagged JSON; omission stays omission, unknown enum values stay UNKNOWN. */
|
|
141
|
-
internal fun nativeEvent(value: JsonObject): RuntimeEvent {
|
|
142
|
-
fun at() = Instant.parse(value.at("at").text())
|
|
143
|
-
fun state(v: JsonObject) = RuntimeEvent.State(nativeEnum(v.at("status")), v.number("queued").toInt(), v.flag("typing"),
|
|
144
|
-
v.get("activity")?.takeUnless { it.isJsonNull }?.let { nativeEnum<AgentActivity>(it) },
|
|
145
|
-
v.get("tools")?.takeIf { it.isJsonArray }?.asJsonArray?.map { it.asString })
|
|
146
|
-
return when (val type = value.at("type").text()) {
|
|
147
|
-
"input" -> RuntimeEvent.Input(value.number("seq"), value.number("firstSeq"), value.at("id").text(), nativeEnum(value.at("kind")),
|
|
148
|
-
value.get("text")?.takeUnless { it.isJsonNull }?.asString, value.list("images").map { image -> image.asJsonObject.let {
|
|
149
|
-
ImageSummary(it.get("alt")?.asString, it.get("mime")?.asString, it.optionalLong("bytes"))
|
|
150
|
-
} }, nativeEnum(value.at("status")), value.error(), at())
|
|
151
|
-
"message.start" -> RuntimeEvent.MessageStart(value.number("seq"), value.number("firstSeq"), value.at("id").text(), at())
|
|
152
|
-
"message.delta" -> RuntimeEvent.MessageDelta(value.at("id").text(), value.at("text").text())
|
|
153
|
-
"message.end" -> RuntimeEvent.MessageEnd(value.number("seq"), value.number("firstSeq"), value.at("id").text(), nativeEnum(value.at("status")),
|
|
154
|
-
value.at("text").text(), value.strings("markers"), value.get("output")?.takeUnless { it.isJsonNull }?.deepCopy(),
|
|
155
|
-
value.strings("inReplyTo"), value.strings("causedBy"), value.error(), at())
|
|
156
|
-
"state" -> state(value)
|
|
157
|
-
"snapshot" -> RuntimeEvent.Snapshot(value.at("logId").text(), state(value.getAsJsonObject("state")), value.get("streaming")?.takeIf { it.isJsonObject }?.asJsonObject?.let {
|
|
158
|
-
Streaming(it.at("messageId").text(), it.number("firstSeq"), it.at("text").text())
|
|
159
|
-
})
|
|
160
|
-
"page" -> RuntimeEvent.Page(value.list("messages").map { nativeEvent(it.asJsonObject) }, value.flag("reachedFloor"), value.at("logId").text(), value.number("clearedSeq"))
|
|
161
|
-
"gap" -> RuntimeEvent.Gap(value.number("afterSeq"), value.number("throughSeq"), nativeEnum(value.at("reason")))
|
|
162
|
-
"cleared" -> RuntimeEvent.Cleared(value.number("seq"), value.at("id").text(), at())
|
|
163
|
-
"turn" -> RuntimeEvent.Turn(value.number("seq"), value.at("id").text(), value.strings("causedBy"), value.strings("inputs"), value.at("purpose").text(),
|
|
164
|
-
value.get("usage")?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet()?.associate { it.key to it.value.asLong } ?: emptyMap(),
|
|
165
|
-
value.get("costUsd")?.asDouble ?: 0.0, nativeEnum(value.at("costStatus")), value.at("model").text(), value.optionalLong("imagesOmitted")?.toInt(), at())
|
|
166
|
-
"app" -> value.getAsJsonObject("source").let { RuntimeEvent.App(value.number("seq"), value.at("id").text(), value.at("name").text(), value.get("data").deepCopy(),
|
|
167
|
-
ToolSource(it.at("command").text(), it.at("callId").text()), at()) }
|
|
168
|
-
"error" -> if (value.has("seq")) RuntimeEvent.Error(value.number("seq"), value.at("id").text(), value.at("code").text(), value.at("message").text(), value.strings("inputs"), at())
|
|
169
|
-
else RuntimeEvent.StreamError(value.at("code").text(), value.at("message").text(), value.flag("poisoned"))
|
|
170
|
-
"replaced" -> RuntimeEvent.Replaced
|
|
171
|
-
else -> RuntimeEvent.Unknown(type)
|
|
172
|
-
}
|
|
173
|
-
}
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import com.google.gson.JsonArray
|
|
4
|
-
import dev.croche.ffi.CoreProject
|
|
5
|
-
import dev.croche.ffi.CoreRuntime
|
|
6
|
-
import dev.croche.ffi.HostPal
|
|
7
|
-
import dev.croche.ffi.HostPalFactory
|
|
8
|
-
import java.util.concurrent.ConcurrentHashMap
|
|
9
|
-
import java.util.concurrent.CopyOnWriteArrayList
|
|
10
|
-
|
|
11
|
-
/** Same lifetime rule as RN AgentPals: a fresh host each time Core asks, including record/GC PALs. */
|
|
12
|
-
internal class ProjectPals(private val makeHost: (String) -> KotlinHost) : HostPalFactory {
|
|
13
|
-
private val all = CopyOnWriteArrayList<KotlinHost>()
|
|
14
|
-
private val agents = ConcurrentHashMap<String, KotlinHost>()
|
|
15
|
-
override fun pal(agent: String): HostPal {
|
|
16
|
-
keepAttached()
|
|
17
|
-
return makeHost(agent).also {
|
|
18
|
-
all.add(it)
|
|
19
|
-
if (!projectPalRoute(agent).maintenance) agents[agent] = it
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
internal val cachedAgentSlots: Set<String> get() = agents.keys.toSet()
|
|
23
|
-
fun host(core: CoreRuntime): KotlinHost = agents[slot(core)]
|
|
24
|
-
?: throw CrocheException("core_error", "Core opened an agent without requesting its host")
|
|
25
|
-
fun release() {
|
|
26
|
-
all.forEach { it.deliver = null; it.stop(); it.release() }
|
|
27
|
-
all.clear(); agents.clear()
|
|
28
|
-
}
|
|
29
|
-
companion object {
|
|
30
|
-
fun slot(core: CoreRuntime): String = core.instance()?.let { instance ->
|
|
31
|
-
JsonArray().apply { add(core.agentId()); add(instance) }.toString()
|
|
32
|
-
} ?: core.agentId()
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Core admission runs even for a cached wrapper, to validate overrides and instance identity. */
|
|
37
|
-
internal class ProjectBinding(private val core: CoreProject, private val pals: ProjectPals) {
|
|
38
|
-
private val agents = linkedMapOf<String, Pair<CoreRuntime, CrocheRuntime>>()
|
|
39
|
-
@Volatile private var closed = false
|
|
40
|
-
val agentIds: List<String> get() = call { core.agentIds() }
|
|
41
|
-
val user: String? get() = call { core.user() }
|
|
42
|
-
val installationId: String? get() = call { core.installationId() }
|
|
43
|
-
@Volatile private var cachedUserId: String? = null
|
|
44
|
-
val crocheUserId: String? get() = call { core.crocheUserId() }.also { if (it != null) cachedUserId = it }
|
|
45
|
-
/** Final paid-call usage can arrive while shutdown runs, after public getters are closed. */
|
|
46
|
-
internal val usageUserId: String? get() = try { core.crocheUserId() ?: cachedUserId }
|
|
47
|
-
catch (_: Exception) { cachedUserId }
|
|
48
|
-
private fun <T> call(body: () -> T): T {
|
|
49
|
-
if (closed) throw CrocheException("closed", "The project is closed")
|
|
50
|
-
return try { body() } catch (error: Exception) { throw crocheError(error) }
|
|
51
|
-
}
|
|
52
|
-
@Synchronized fun agent(id: String?, options: String): Pair<CoreRuntime, CrocheRuntime> = call {
|
|
53
|
-
val opened = core.agentWithOptions(id, options, null)
|
|
54
|
-
try {
|
|
55
|
-
core.crocheUserId()?.let { cachedUserId = it }
|
|
56
|
-
val slot = ProjectPals.slot(opened)
|
|
57
|
-
val existing = agents[slot]
|
|
58
|
-
if (existing != null && !existing.second.isClosed) {
|
|
59
|
-
opened.destroy()
|
|
60
|
-
return@call existing
|
|
61
|
-
}
|
|
62
|
-
val runtime = CrocheRuntime.adopt(opened, pals.host(opened))
|
|
63
|
-
(opened to runtime).also { agents[slot] = it }
|
|
64
|
-
} catch (error: Exception) { if (!opened.uniffiIsDestroyed) opened.destroy(); throw error }
|
|
65
|
-
}
|
|
66
|
-
fun close() {
|
|
67
|
-
synchronized(this) { if (closed) return; closed = true }
|
|
68
|
-
try { core.shutdown() }
|
|
69
|
-
catch (error: Exception) { throw crocheError(error) }
|
|
70
|
-
finally {
|
|
71
|
-
try {
|
|
72
|
-
var failed: Exception? = null
|
|
73
|
-
agents.values.forEach { try { it.second.close() } catch (error: Exception) { if (failed == null) failed = error } }
|
|
74
|
-
failed?.let { throw it }
|
|
75
|
-
}
|
|
76
|
-
finally { agents.clear(); core.destroy(); pals.release() }
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import com.google.gson.JsonObject
|
|
4
|
-
import com.google.gson.JsonParser
|
|
5
|
-
|
|
6
|
-
/** Core's PAL labels are routing metadata, never an agentId to hash literally. */
|
|
7
|
-
internal data class ProjectPalRoute(val agent: String, val instance: String? = null, val maintenance: Boolean = false) {
|
|
8
|
-
// OPEN(Keel/Atlas): install-wide GC labels omit the target user; binding by Core lock key is proposed.
|
|
9
|
-
fun identity(host: JsonObject, user: String?): JsonObject = host.deepCopy().apply {
|
|
10
|
-
addProperty("agentId", agent)
|
|
11
|
-
remove("agentInstance")
|
|
12
|
-
instance?.let { addProperty("agentInstance", it) }
|
|
13
|
-
user?.let { addProperty("user", it) }
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
internal fun projectPalRoute(label: String): ProjectPalRoute {
|
|
17
|
-
if (!label.startsWith("[")) return ProjectPalRoute(label)
|
|
18
|
-
val parts = JsonParser.parseString(label).asJsonArray.map { it.asString }
|
|
19
|
-
return when {
|
|
20
|
-
parts == listOf("\$gc", "pass") -> ProjectPalRoute("default", maintenance = true)
|
|
21
|
-
parts.size == 3 && parts[0] == "\$gc" -> ProjectPalRoute(parts[1], parts[2], maintenance = true)
|
|
22
|
-
parts.size == 2 -> ProjectPalRoute(parts[0], parts[1])
|
|
23
|
-
else -> throw CrocheException("invalid_configuration", "Invalid project PAL label")
|
|
24
|
-
}
|
|
25
|
-
}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import java.io.File
|
|
4
|
-
import java.util.Locale
|
|
5
|
-
|
|
6
|
-
/** Android is discovered through its existing provider; the JVM artifact has no Android dependency. */
|
|
7
|
-
internal data class ProjectPlatform(
|
|
8
|
-
val directory: File,
|
|
9
|
-
val secretStorage: (String) -> RuntimeSecretStore,
|
|
10
|
-
val attestor: RuntimeAttestor?,
|
|
11
|
-
)
|
|
12
|
-
internal fun projectDeviceLanguage(): String = try {
|
|
13
|
-
Class.forName("dev.croche.android.CrocheProjectRecordProvider")
|
|
14
|
-
.getMethod("language").invoke(null) as String
|
|
15
|
-
} catch (_: ClassNotFoundException) { Locale.getDefault().toLanguageTag() }
|
|
16
|
-
|
|
17
|
-
internal fun projectPlatform(options: OpenOptions): ProjectPlatform {
|
|
18
|
-
val android = try { Class.forName("dev.croche.android.CrocheProjectRecordProvider") }
|
|
19
|
-
catch (_: ClassNotFoundException) { null }
|
|
20
|
-
val default = defaultProjectDirectory()
|
|
21
|
-
val directory = projectRecordDirectory(options.projectDirectory, default)
|
|
22
|
-
?: throw CrocheException("storage_error", "Croche.open requires projectDirectory on this platform")
|
|
23
|
-
if (android == null) return ProjectPlatform(directory,
|
|
24
|
-
{ name -> FileRuntimeSecretStore(File(directory, "$name.secrets")) }, null)
|
|
25
|
-
val attestor = if (options.attestation != Attestation.OFF) options.android?.cloudProjectNumber?.let { number ->
|
|
26
|
-
android.getMethod("attestor", java.lang.Long.TYPE).invoke(null, number) as RuntimeAttestor
|
|
27
|
-
} else null
|
|
28
|
-
return ProjectPlatform(File(directory, "croche"), { name ->
|
|
29
|
-
android.getMethod("secretStorage", String::class.java).invoke(null, name) as RuntimeSecretStore
|
|
30
|
-
}, attestor)
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
internal fun OpenOptions.hostJson(attestor: RuntimeAttestor?) = com.google.gson.JsonObject().apply {
|
|
34
|
-
cloudUrl?.let { addProperty("cloudUrl", it) }; addProperty("projectKey", projectKey)
|
|
35
|
-
debugKey?.let { addProperty("debugKey", it) }
|
|
36
|
-
requestTimeoutMs?.let { addProperty("requestTimeoutMs", it) }
|
|
37
|
-
maxPendingEvents?.let { addProperty("maxPendingEvents", it) }
|
|
38
|
-
syncIntervalMs?.let { addProperty("syncIntervalMs", it) }
|
|
39
|
-
maintenanceBackoffMs?.let { addProperty("maintenanceBackoffMs", it) }
|
|
40
|
-
retentionBytes?.let { addProperty("retentionBytes", it) }
|
|
41
|
-
debugVisibility?.let { addProperty("debugVisibility", "runtime") }
|
|
42
|
-
attestor?.let { addProperty("attestationPlatform", it.platform) }
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
internal fun OpenOptions.owned(): OpenOptions = copy(config = config.deepCopy(), handlers = handlers.toMap(),
|
|
46
|
-
language = language ?: projectDeviceLanguage())
|