@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
|
@@ -2,6 +2,8 @@ package dev.croche
|
|
|
2
2
|
|
|
3
3
|
import com.google.gson.*
|
|
4
4
|
import dev.croche.ffi.*
|
|
5
|
+
import dev.croche.s7.attached
|
|
6
|
+
import dev.croche.s7.hostCallback
|
|
5
7
|
import java.lang.ref.WeakReference
|
|
6
8
|
import java.util.Collections
|
|
7
9
|
import java.util.TimeZone
|
|
@@ -20,15 +22,9 @@ import java.util.concurrent.atomic.AtomicBoolean
|
|
|
20
22
|
/** The code the Runtime reads as "nothing ran" (croche_core::NOT_DISPATCHED). */
|
|
21
23
|
private const val NOT_DISPATCHED = "tool_not_dispatched"
|
|
22
24
|
|
|
23
|
-
/** Shared SDK/RN parser: TimeZone.getTimeZone(String) silently accepts unknown ids as GMT. */
|
|
24
|
-
internal fun projectTimeZone(id: String?): TimeZone? = id?.let {
|
|
25
|
-
try { TimeZone.getTimeZone(java.time.ZoneId.of(it)) }
|
|
26
|
-
catch (_: Exception) { throw CrocheException("invalid_configuration", "timeZone must be an IANA time zone") }
|
|
27
|
-
}
|
|
28
|
-
|
|
29
25
|
internal fun failure(error: Throwable): FfiException = when (error) {
|
|
30
26
|
is FfiException -> error
|
|
31
|
-
is
|
|
27
|
+
is CrocheError -> FfiException.Failure(error.code, error.message)
|
|
32
28
|
else -> FfiException.Failure("host_error", "The host operation failed")
|
|
33
29
|
}
|
|
34
30
|
/** `request_timeout.SocketTimeoutException`, `network_error.SocketException`, …: a call code and the class. */
|
|
@@ -37,31 +33,19 @@ internal fun transportCode(error: java.io.IOException): String {
|
|
|
37
33
|
val name = error.javaClass.simpleName.filter { it.isLetterOrDigit() || it == '_' }.take(60)
|
|
38
34
|
return if (name.isEmpty()) base else "$base.$name"
|
|
39
35
|
}
|
|
40
|
-
internal fun crocheError(error: Throwable):
|
|
41
|
-
is
|
|
42
|
-
is FfiException.Failure ->
|
|
43
|
-
else ->
|
|
36
|
+
internal fun crocheError(error: Throwable): CrocheError = when (error) {
|
|
37
|
+
is CrocheError -> error
|
|
38
|
+
is FfiException.Failure -> CrocheError(error.code, error.detail)
|
|
39
|
+
else -> CrocheError("host_error", "The host operation failed")
|
|
44
40
|
}
|
|
45
41
|
|
|
46
|
-
/** The Runtime calls this host on its own worker threads, which JNA attaches for the length of
|
|
47
|
-
* one callback. A callback that calls back into the Runtime (a sink fed on the callback's stack,
|
|
48
|
-
* an observer that inspects) nests a second callback on that thread, and JNA's default detaches
|
|
49
|
-
* after the inner one while the outer one is still running: "JNA: could not detach thread".
|
|
50
|
-
* Keeping the thread attached until it exits avoids that; the worker threads are short-lived. */
|
|
51
|
-
internal fun keepAttached() = com.sun.jna.Native.detach(false)
|
|
52
42
|
|
|
53
43
|
/** A Runtime cancellation, tied to the token the Runtime handed this effect. */
|
|
54
44
|
private fun signal(token: CancelToken): RuntimeCancellation = RuntimeCancellation().also { signal ->
|
|
55
|
-
token.onCancel(object : CancelCallback { override fun cancelled() = signal.cancel() })
|
|
45
|
+
token.onCancel(attached(object : CancelCallback { override fun cancelled() = signal.cancel() }))
|
|
56
46
|
}
|
|
57
47
|
|
|
58
|
-
|
|
59
|
-
override fun onEvent(event: String) {
|
|
60
|
-
keepAttached()
|
|
61
|
-
val value = try { JsonParser.parseString(event) } catch (_: Exception) { return }
|
|
62
|
-
try { callback(value) } catch (_: Exception) {}
|
|
63
|
-
}
|
|
64
|
-
}
|
|
48
|
+
|
|
65
49
|
|
|
66
50
|
/** The `at`s (epoch ms) of a schedule set `[{id, at}]`. */
|
|
67
51
|
internal fun times(entries: JsonElement): List<Long> =
|
|
@@ -80,300 +64,3 @@ internal fun retryAt(value: JsonElement): Long? = try {
|
|
|
80
64
|
|
|
81
65
|
/** Each store object is one store; two Runtimes on it in a process are refused. */
|
|
82
66
|
private val identities: MutableMap<Any, String> = Collections.synchronizedMap(WeakHashMap())
|
|
83
|
-
|
|
84
|
-
/** The Kotlin PAL handed to the Rust Runtime. */
|
|
85
|
-
internal class KotlinHost(
|
|
86
|
-
private val storage: RuntimeStorage, private val secretStore: RuntimeSecretStore,
|
|
87
|
-
private val attestor: RuntimeAttestor?, private val transport: RuntimeHTTP,
|
|
88
|
-
tools: Map<String, ToolHandler>, private val background: Boolean,
|
|
89
|
-
private val osScheduler: RuntimeScheduler? = null,
|
|
90
|
-
projectDirectory: java.io.File? = null,
|
|
91
|
-
defaultDirectory: () -> java.io.File? = ::defaultProjectDirectory,
|
|
92
|
-
private val user: String? = null,
|
|
93
|
-
private val timeZone: TimeZone? = null
|
|
94
|
-
) : HostPal {
|
|
95
|
-
private val projectRecords = ProjectRecords { projectRecordDirectory(projectDirectory, defaultDirectory()) }
|
|
96
|
-
internal var beforeProjectLock: (() -> Unit)? = null
|
|
97
|
-
internal var afterProjectRead: ((String?) -> Unit)? = null
|
|
98
|
-
internal var beforeProjectWrite: (() -> Unit)? = null
|
|
99
|
-
// Accepted tools are never removed: a tool change waits its turn in the Core's queue, and turns queued before it
|
|
100
|
-
// still run the old list. The Core alone decides which commands a turn may call.
|
|
101
|
-
@Volatile private var handlers: Map<String, ToolHandler> = tools
|
|
102
|
-
private val staged = HashMap<String, Int>() // names whose only handler is from a call in flight
|
|
103
|
-
private var stamp = 0
|
|
104
|
-
/** Stages the handlers for names with none yet, or with one only staged by a call still in
|
|
105
|
-
* flight (a later call wins). Returns the stamp that [unstageTools] needs. */
|
|
106
|
-
fun stageTools(tools: Map<String, ToolHandler>): Int = synchronized(lock) {
|
|
107
|
-
stamp += 1
|
|
108
|
-
val names = tools.keys.filter { it !in handlers || it in staged }
|
|
109
|
-
handlers = handlers + tools.filterKeys { it in names }
|
|
110
|
-
names.forEach { staged[it] = stamp }
|
|
111
|
-
stamp
|
|
112
|
-
}
|
|
113
|
-
/** A refused call: removes what it staged, unless a later call has staged the name since. */
|
|
114
|
-
fun unstageTools(names: Set<String>, stamp: Int) = synchronized(lock) {
|
|
115
|
-
val mine = names.filter { staged[it] == stamp }
|
|
116
|
-
handlers = handlers - mine.toSet(); mine.forEach { staged.remove(it) }
|
|
117
|
-
}
|
|
118
|
-
/** An accepted call: its handlers serve every name it passed. */
|
|
119
|
-
fun acceptTools(tools: Map<String, ToolHandler>) = synchronized(lock) {
|
|
120
|
-
handlers = handlers + tools; tools.keys.forEach { staged.remove(it) }
|
|
121
|
-
}
|
|
122
|
-
private val effects = EffectExecutor()
|
|
123
|
-
private val tools = ToolExecutor()
|
|
124
|
-
private val identity = identities.getOrPut(storage) { "kotlin:" + UUID.randomUUID() }
|
|
125
|
-
private val lock = Any()
|
|
126
|
-
private var core: WeakReference<CoreRuntime>? = null
|
|
127
|
-
private var wakeTarget: Double? = null
|
|
128
|
-
private var timer: ScheduledFuture<*>? = null
|
|
129
|
-
private var scheduler: ScheduledExecutorService? = null
|
|
130
|
-
private var stopped = false
|
|
131
|
-
/** This Runtime's attachment to `osScheduler` (attached before the host is built), released
|
|
132
|
-
* once: a second stop, or a stale close after the scheduler was attached again for another
|
|
133
|
-
* Runtime, must not free a name someone else holds. Guarded by `lock`. */
|
|
134
|
-
private var osAttached = osScheduler != null
|
|
135
|
-
/** The wall clock (epoch ms) the Runtime and its timers read. Tests move it. */
|
|
136
|
-
@Volatile internal var clock: () -> Long = { System.currentTimeMillis() }
|
|
137
|
-
/** Runs `deliverDue()` on the Runtime when the earliest note's time comes. */
|
|
138
|
-
@Volatile internal var deliver: (() -> Unit)? = null
|
|
139
|
-
private var dueAt: Long? = null
|
|
140
|
-
private var fired: Long? = null
|
|
141
|
-
private var dueTimer: ScheduledFuture<*>? = null
|
|
142
|
-
private var deliveries: ScheduledExecutorService? = null
|
|
143
|
-
|
|
144
|
-
private inline fun <T> host(body: () -> T): T = try { keepAttached(); body() } catch (error: Exception) { throw failure(error) }
|
|
145
|
-
|
|
146
|
-
// HTTP
|
|
147
|
-
override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) = host {
|
|
148
|
-
try {
|
|
149
|
-
effects.run(request.timeoutMs.toLong(), signal(cancel)) { local ->
|
|
150
|
-
if (transport is RuntimeHttpURLConnection) transport.stream(request, sink, local) else adapt(request, sink, local)
|
|
151
|
-
JsonNull.INSTANCE
|
|
152
|
-
}
|
|
153
|
-
} catch (error: java.io.IOException) {
|
|
154
|
-
// The call keeps a Runtime code; what failed underneath rides along as its class name
|
|
155
|
-
// (never the message, which may name hosts): Logs then say why (dev, 2026-10-05).
|
|
156
|
-
throw CrocheException(transportCode(error), "The HTTP transport failed")
|
|
157
|
-
}
|
|
158
|
-
Unit
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/** An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
|
|
162
|
-
* a response, and its stream deltas as server-sent events. */
|
|
163
|
-
internal fun adapt(request: PalHttpRequest, sink: HttpSink, signal: RuntimeCancellation) {
|
|
164
|
-
keepAttached()
|
|
165
|
-
val headers = JsonObject().apply { request.headers.forEach { addProperty(it.name, it.value) } }
|
|
166
|
-
val body = try { JsonParser.parseString(request.body) } catch (_: Exception) { str(request.body) }
|
|
167
|
-
val effect = obj("url" to str(request.url), "method" to str(request.method), "headers" to headers,
|
|
168
|
-
"body" to body, "timeoutMs" to num(request.timeoutMs.toLong()))
|
|
169
|
-
val started = AtomicBoolean(false)
|
|
170
|
-
val eventStream = listOf(PalHeader("content-type", "text/event-stream"))
|
|
171
|
-
val reply = transport.execute(effect, signal) { data ->
|
|
172
|
-
if (started.compareAndSet(false, true)) sink.head(200u, eventStream)
|
|
173
|
-
val frame = data.split("\n").joinToString("") { "data: $it\n" } + "\n"
|
|
174
|
-
sink.chunk(frame.toByteArray(Charsets.UTF_8))
|
|
175
|
-
}
|
|
176
|
-
val status = reply.at("status").let { if (it.isJsonPrimitive) it.asInt else 0 }.toUShort()
|
|
177
|
-
if (reply.at("streamed").let { it.isJsonPrimitive && it.asBoolean }) {
|
|
178
|
-
if (started.compareAndSet(false, true)) sink.head(status, eventStream)
|
|
179
|
-
return
|
|
180
|
-
}
|
|
181
|
-
val fields = reply.at("headers").let { if (it.isJsonObject) it.asJsonObject.entrySet() else emptySet() }
|
|
182
|
-
.filter { (key, value) -> value.text().isNotEmpty() && !key.equals("content-type", ignoreCase = true) }
|
|
183
|
-
.map { (key, value) -> PalHeader(key, value.text()) } + PalHeader("content-type", "application/json")
|
|
184
|
-
sink.head(status, fields)
|
|
185
|
-
val data = if (!reply.at("body").isJsonNull) reply.at("body").toString() else reply.at("raw").text()
|
|
186
|
-
if (data.isNotEmpty()) sink.chunk(data.toByteArray(Charsets.UTF_8))
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// Storage
|
|
190
|
-
/** The Core names its snapshot by the key it locks, and other records `<key>.<entry>` (F19's
|
|
191
|
-
* held sends: `<key>.held`). Each goes to its own place: an entry never replaces the snapshot. */
|
|
192
|
-
@Volatile private var snapshotKey: String? = null
|
|
193
|
-
private fun entry(key: String): String? {
|
|
194
|
-
val main = snapshotKey ?: return null
|
|
195
|
-
if (key == main) return null
|
|
196
|
-
if (!key.startsWith("$main.") || key.length <= main.length + 1) throw CrocheException("storage_error", "Unknown storage key")
|
|
197
|
-
return key.substring(main.length + 1)
|
|
198
|
-
}
|
|
199
|
-
private inline fun <T> projectIO(body: () -> T): T = try { body() }
|
|
200
|
-
catch (_: java.io.IOException) { throw CrocheException("storage_error", "Could not access the project record") }
|
|
201
|
-
override fun read(key: String): String? = host {
|
|
202
|
-
if (isProjectKey(key)) return@host projectIO { projectRecords.read(key) }.also { afterProjectRead?.invoke(it) }
|
|
203
|
-
val name = entry(key)
|
|
204
|
-
val state = when {
|
|
205
|
-
name == null -> storage.load()
|
|
206
|
-
// A storage without entries never stored one.
|
|
207
|
-
storage is KeyedRuntimeStorage -> storage.load(name)
|
|
208
|
-
else -> JsonNull.INSTANCE
|
|
209
|
-
}
|
|
210
|
-
if (state.isJsonNull) null else state.toString()
|
|
211
|
-
}
|
|
212
|
-
override fun write(key: String, value: String) = persist {
|
|
213
|
-
if (isProjectKey(key)) { beforeProjectWrite?.invoke(); projectRecords.write(key, value); return@persist }
|
|
214
|
-
val name = entry(key)
|
|
215
|
-
when {
|
|
216
|
-
name == null -> storage.save(JsonParser.parseString(value))
|
|
217
|
-
storage is KeyedRuntimeStorage -> storage.save(name, JsonParser.parseString(value))
|
|
218
|
-
else -> throw CrocheException("storage_error", "This RuntimeStorage keeps only its snapshot")
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
override fun remove(key: String) = persist {
|
|
222
|
-
if (isProjectKey(key)) throw CrocheException("storage_error", "The project record is kept when agent data is removed")
|
|
223
|
-
val name = entry(key)
|
|
224
|
-
when {
|
|
225
|
-
name == null -> storage.remove()
|
|
226
|
-
storage is KeyedRuntimeStorage -> storage.remove(name)
|
|
227
|
-
storage is ArchiveRuntimeStorage && isLineStorageEntry(name) -> storage.remove(name)
|
|
228
|
-
else -> Unit // A snapshot-only storage has never held named entries.
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
override fun removeSecret(key: String) = persist { secretStore.remove() }
|
|
232
|
-
override fun readSecret(key: String): String? = host { secretStore.load().toString() }
|
|
233
|
-
override fun writeSecret(key: String, value: String) = persist { secretStore.save(JsonParser.parseString(value).asJsonObject) }
|
|
234
|
-
private fun persist(body: () -> Unit) = try { body() } catch (error: Exception) {
|
|
235
|
-
throw if (error is CrocheException) failure(error) else FfiException.Failure("storage_error", "Could not persist Runtime state")
|
|
236
|
-
}
|
|
237
|
-
override fun lock(key: String) = host {
|
|
238
|
-
if (isProjectKey(key)) projectIO { beforeProjectLock?.invoke(); projectRecords.acquire(key) }
|
|
239
|
-
else { storage.acquire(); snapshotKey = key }
|
|
240
|
-
}
|
|
241
|
-
override fun unlock(key: String) {
|
|
242
|
-
if (isProjectKey(key)) { projectRecords.release(key); return }
|
|
243
|
-
stop(); try { storage.release() } catch (_: Exception) {}
|
|
244
|
-
}
|
|
245
|
-
override fun storeIdentity(): String = identity
|
|
246
|
-
|
|
247
|
-
// The turn archive (F20.6)
|
|
248
|
-
/** The storage's archive, or the typed "no archive": the Runtime then keeps none, and every
|
|
249
|
-
* turn, clearHistory and memory work as before. */
|
|
250
|
-
private fun <T> archive(body: (ArchiveRuntimeStorage) -> T): T = try {
|
|
251
|
-
val archive = storage as? ArchiveRuntimeStorage ?: throw CrocheException("archive_unavailable", "This host keeps no turn archive.")
|
|
252
|
-
body(archive)
|
|
253
|
-
} catch (error: Exception) {
|
|
254
|
-
throw if (error is CrocheException) failure(error) else FfiException.Failure("storage_error", "The turn archive could not be read or written")
|
|
255
|
-
}
|
|
256
|
-
override fun archiveAppendLine(entry: String, line: String) = archive { it.appendLine(entry, line) }
|
|
257
|
-
override fun archiveReadLines(entry: String): List<String> = archive { it.readLines(entry) }
|
|
258
|
-
override fun archiveReplaceLines(entry: String, lines: List<String>) = archive { it.replaceLines(entry, lines) }
|
|
259
|
-
override fun archiveRemove(entry: String) = archive { it.remove(entry) }
|
|
260
|
-
override fun archiveEntries(prefix: String): List<ArchiveEntry> =
|
|
261
|
-
archive { a -> a.entries(prefix).toSortedMap().map { (entry, bytes) -> ArchiveEntry(entry, bytes.toULong()) } }
|
|
262
|
-
|
|
263
|
-
/** Where the message log goes (S1, rev 4 §17.13): in lines when the storage appends them, in
|
|
264
|
-
* entries when it keeps entries, else inside the snapshot. Never refused. */
|
|
265
|
-
override fun storageCapability(): StorageCapability = when (storage) {
|
|
266
|
-
is ArchiveRuntimeStorage -> StorageCapability.LINES
|
|
267
|
-
is KeyedRuntimeStorage -> StorageCapability.KEYED
|
|
268
|
-
else -> StorageCapability.SNAPSHOT
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
// Tools and attestation
|
|
272
|
-
override fun tool(invocation: String, cancel: CancelToken): ToolOutput = host {
|
|
273
|
-
val call = JsonParser.parseString(invocation)
|
|
274
|
-
val name = call.at("tool").text()
|
|
275
|
-
val handler = handlers[name] ?: throw CrocheException(NOT_DISPATCHED, "The host tool is not available")
|
|
276
|
-
val context = call.at("context")
|
|
277
|
-
val request = CommandInvocation(name, call.at("command").text().ifEmpty { null }, call.at("key").text(),
|
|
278
|
-
call.at("args").let { if (it.isJsonObject) it.asJsonObject.deepCopy() else JsonObject() })
|
|
279
|
-
// No deadline here: the Runtime times the call and cancels it (H4). This returns when
|
|
280
|
-
// the handler does, so a stuck one keeps its slot (H1).
|
|
281
|
-
val sink = ToolImages()
|
|
282
|
-
val value = tools.run(signal(cancel)) { local ->
|
|
283
|
-
handler.execute(request, ToolContext(context.at("callId").text(),
|
|
284
|
-
context.at("messageId").text(), context.at("userId").text(), local,
|
|
285
|
-
context.at("agentId").text().ifEmpty { null }, sink,
|
|
286
|
-
user, context.at("userId").text().ifEmpty { null },
|
|
287
|
-
context.at("causedBy").let { if (it.isJsonArray) it.asJsonArray.map { id -> id.asString } else emptyList() },
|
|
288
|
-
context.at("origin").text().ifEmpty { "app" }))
|
|
289
|
-
}
|
|
290
|
-
// A plain handler's JSON is the value as it was; a `withResult` one's images ride beside
|
|
291
|
-
// it, one sink per call (never shared between concurrent calls).
|
|
292
|
-
ToolOutput(value.toString(), sink.images.map { CrocheImages.record(it) })
|
|
293
|
-
}
|
|
294
|
-
override fun attest(request: String, timeoutMs: ULong): String = host {
|
|
295
|
-
val platform = attestor ?: throw CrocheException("attestation_unsupported", "This host has no attestor")
|
|
296
|
-
val effect = JsonParser.parseString(request)
|
|
297
|
-
val clientData = effect.at("clientData").text()
|
|
298
|
-
val hash = effect.at("clientDataHash").text()
|
|
299
|
-
if (clientData.isEmpty() || hash.isEmpty()) throw CrocheException("invalid_abi", "Malformed attest effect")
|
|
300
|
-
effects.run(timeoutMs.toLong(), RuntimeCancellation()) { signal ->
|
|
301
|
-
val proof = platform.attest(clientData, hash, signal)
|
|
302
|
-
obj("platform" to str(platform.platform), "token" to str(proof.token),
|
|
303
|
-
"keyId" to (proof.keyId?.let { str(it) } ?: JsonNull.INSTANCE))
|
|
304
|
-
}.toString()
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
// Clock, entropy, timer
|
|
308
|
-
override fun nowMs(): Double = clock().toDouble()
|
|
309
|
-
override fun utcOffsetMinutes(atMs: Double): Long = (timeZone ?: TimeZone.getDefault()).getOffset(atMs.toLong()).toLong() / 60_000
|
|
310
|
-
override fun random(): String = UUID.randomUUID().toString()
|
|
311
|
-
override fun wake(atMs: Double?) {
|
|
312
|
-
synchronized(lock) { wakeTarget = atMs }
|
|
313
|
-
arm()
|
|
314
|
-
}
|
|
315
|
-
/** The agent's whole pending schedule set (JSON `[{id, at}]`), after each durable change and
|
|
316
|
-
* at open: a timer while running, and the OS's deferred work (`osScheduler`) for after. A
|
|
317
|
-
* refused registration fails this acknowledgement, which the Core reports as
|
|
318
|
-
* `schedule.degraded` with its code. */
|
|
319
|
-
override fun schedule(entries: String) = host { applySchedule(target(times(JsonParser.parseString(entries)))) }
|
|
320
|
-
@Volatile private var retryFloor: Long? = null
|
|
321
|
-
/** A failed delivery answered `retryAt`: a note already due waits until then. */
|
|
322
|
-
internal fun retryAfter(atMs: Long) { retryFloor = atMs }
|
|
323
|
-
/** When to wake for these notes: the earliest `at`, except that a note already due waits for
|
|
324
|
-
* a later `retryAt` (a delivery failed). */
|
|
325
|
-
internal fun target(times: List<Long>): Long? {
|
|
326
|
-
val now = clock()
|
|
327
|
-
val floor = retryFloor?.takeIf { it > now }
|
|
328
|
-
return times.map { if (floor != null && it <= now) floor else it }.minOrNull()
|
|
329
|
-
}
|
|
330
|
-
/** Arms the timer for `at` (null: nothing pending) and registers it with the OS. */
|
|
331
|
-
internal fun applySchedule(at: Long?) {
|
|
332
|
-
synchronized(lock) { dueAt = at }
|
|
333
|
-
armDelivery()
|
|
334
|
-
val os = osScheduler ?: return
|
|
335
|
-
try { if (at == null) os.cancel() else os.schedule(at) }
|
|
336
|
-
catch (error: CrocheException) { throw error }
|
|
337
|
-
catch (_: Exception) { throw CrocheException("schedule_failed", "The OS scheduler refused the request") }
|
|
338
|
-
}
|
|
339
|
-
/** The Runtime is open: a wake it asked for while opening can now fire. */
|
|
340
|
-
fun attach(core: CoreRuntime) { synchronized(lock) { this.core = WeakReference(core) }; arm(); armDelivery() }
|
|
341
|
-
fun stop() {
|
|
342
|
-
synchronized(lock) {
|
|
343
|
-
stopped = true; timer?.cancel(false); timer = null; scheduler?.shutdown()
|
|
344
|
-
dueTimer?.cancel(false); dueTimer = null; deliveries?.shutdown()
|
|
345
|
-
}
|
|
346
|
-
val release = synchronized(lock) { osAttached.also { osAttached = false } }
|
|
347
|
-
if (release) try { osScheduler?.detach() } catch (_: Exception) {}
|
|
348
|
-
}
|
|
349
|
-
/** One timer at the earliest note, never firing a delivery before its time (a timer that
|
|
350
|
-
* ends early re-arms), and at most once per time: a delivery that was cut short leaves its
|
|
351
|
-
* notes for the next open, foreground or OS run rather than retrying at once. */
|
|
352
|
-
private fun armDelivery() = synchronized(lock) {
|
|
353
|
-
dueTimer?.cancel(false); dueTimer = null
|
|
354
|
-
val target = dueAt
|
|
355
|
-
if (stopped || core == null || target == null || fired?.let { target <= it } == true) return@synchronized
|
|
356
|
-
val pool = deliveries ?: Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "croche-schedule").apply { isDaemon = true } }
|
|
357
|
-
.also { deliveries = it }
|
|
358
|
-
val delay = (target - clock()).coerceAtLeast(0)
|
|
359
|
-
dueTimer = pool.schedule({ due(target) }, delay, TimeUnit.MILLISECONDS)
|
|
360
|
-
}
|
|
361
|
-
/** A delivery is starting: it covers every note due now, so the timer never retries one. */
|
|
362
|
-
internal fun attempted() = synchronized(lock) { fired = maxOf(fired ?: Long.MIN_VALUE, clock()) }
|
|
363
|
-
private fun due(target: Long) {
|
|
364
|
-
if (clock() < target) { armDelivery(); return }
|
|
365
|
-
synchronized(lock) { if (stopped) return; fired = target }
|
|
366
|
-
try { deliver?.invoke() } catch (_: Exception) {}
|
|
367
|
-
}
|
|
368
|
-
fun release() { stop(); projectRecords.releaseAll(); effects.close(); tools.close() }
|
|
369
|
-
private fun arm() = synchronized(lock) {
|
|
370
|
-
timer?.cancel(false); timer = null
|
|
371
|
-
val target = wakeTarget
|
|
372
|
-
val runtime = core
|
|
373
|
-
if (!background || stopped || target == null || runtime == null) return@synchronized
|
|
374
|
-
val pool = scheduler ?: Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "croche-upkeep").apply { isDaemon = true } }
|
|
375
|
-
.also { scheduler = it }
|
|
376
|
-
val delay = (target - System.currentTimeMillis()).toLong().coerceAtLeast(0)
|
|
377
|
-
timer = pool.schedule({ try { runtime.get()?.tick() } catch (_: Exception) {} }, delay, TimeUnit.MILLISECONDS)
|
|
378
|
-
}
|
|
379
|
-
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
package dev.croche
|
|
2
|
+
|
|
3
|
+
import dev.croche.ffi.CancelToken
|
|
4
|
+
import dev.croche.ffi.PalImageBytes
|
|
5
|
+
import dev.croche.ffi.PalImagePreparePlan
|
|
6
|
+
import dev.croche.ffi.PalImageReadRequest
|
|
7
|
+
import dev.croche.ffi.PalImageReadSource
|
|
8
|
+
import java.security.MessageDigest
|
|
9
|
+
import java.util.UUID
|
|
10
|
+
import kotlin.math.max
|
|
11
|
+
import kotlin.math.min
|
|
12
|
+
import kotlin.math.roundToInt
|
|
13
|
+
import kotlin.math.sqrt
|
|
14
|
+
|
|
15
|
+
/** A platform decoder for the private image PAL. Android supplies `dev.croche.android.BitmapPalCodec`;
|
|
16
|
+
* a plain JVM has none, so Core refuses image inputs with `image_unsupported` before acquiring. */
|
|
17
|
+
internal interface PalImageCodec {
|
|
18
|
+
/** Upright dimensions from the header only, or null when this platform cannot decode it or it
|
|
19
|
+
* has more than [maxPixels] pixels. No full decode happens here. */
|
|
20
|
+
fun open(bytes: ByteArray, maxPixels: Long): Opened?
|
|
21
|
+
interface Opened : AutoCloseable {
|
|
22
|
+
val width: Int
|
|
23
|
+
val height: Int
|
|
24
|
+
/** EXIF turns the stored pixels, so the unchanged source is not upright as encoded. */
|
|
25
|
+
val reoriented: Boolean
|
|
26
|
+
/** Upright, exactly [width]×[height] given: PNG, and JPEG (quality 70) unless a pixel can be
|
|
27
|
+
* have alpha (an alpha channel, as TypeScript's sharp codec). Decodes downsampled when it can. */
|
|
28
|
+
fun render(width: Int, height: Int): Rendered
|
|
29
|
+
override fun close() {}
|
|
30
|
+
}
|
|
31
|
+
class Rendered(val png: ByteArray, val jpeg: ByteArray?)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Private native image PAL (Rev 4a), the Kotlin twin of the TypeScript and Swift `ImagePal`. Core
|
|
35
|
+
* owns admission, sizing plans, budgets, deadlines and every URL; this only holds owned captures
|
|
36
|
+
* and decodes/encodes to Core's plan. Names, codes and messages match TypeScript. */
|
|
37
|
+
internal class NativeImagePal(
|
|
38
|
+
private val codec: PalImageCodec? = defaultCodec(),
|
|
39
|
+
/** Native platform limit (TypeScript has none), checked from the header before any decode. */
|
|
40
|
+
val maxInputPixels: Long = DEFAULT_MAX_INPUT_PIXELS,
|
|
41
|
+
) {
|
|
42
|
+
companion object {
|
|
43
|
+
const val SOURCE_MAX_BYTES = 16 * 1024 * 1024
|
|
44
|
+
const val PREPARED_MAX_BYTES = 3 * 1024 * 1024
|
|
45
|
+
const val DEFAULT_MAX_INPUT_PIXELS = 50_000_000L
|
|
46
|
+
fun defaultCodec(): PalImageCodec? = try {
|
|
47
|
+
Class.forName("dev.croche.android.BitmapPalCodec").getDeclaredConstructor().newInstance() as PalImageCodec
|
|
48
|
+
} catch (_: Throwable) { null }
|
|
49
|
+
|
|
50
|
+
fun failure(code: String) = CrocheError(code,
|
|
51
|
+
if (code == "image_fetch_failed") "The image could not be read." else "The image could not be prepared.")
|
|
52
|
+
|
|
53
|
+
/** Core's token is authoritative; its own terminal code wins over this one. */
|
|
54
|
+
fun check(cancel: CancelToken) {
|
|
55
|
+
if (cancel.isCancelled()) throw CrocheError("cancelled", "Image preparation was cancelled.")
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
fun mime(bytes: ByteArray): String? {
|
|
59
|
+
fun at(vararg values: Int) = bytes.size >= values.size && values.indices.all { bytes[it].toInt() and 0xFF == values[it] }
|
|
60
|
+
return when {
|
|
61
|
+
at(137, 80, 78, 71, 13, 10, 26, 10) -> "image/png"
|
|
62
|
+
at(255, 216, 255) -> "image/jpeg"
|
|
63
|
+
at(71, 73, 70, 56) && bytes.size >= 6 && (bytes[4].toInt() == 55 || bytes[4].toInt() == 57) && bytes[5].toInt() == 97 -> "image/gif"
|
|
64
|
+
bytes.size >= 12 && at(82, 73, 70, 70) && bytes[8].toInt() == 87 && bytes[9].toInt() == 69 && bytes[10].toInt() == 66 && bytes[11].toInt() == 80 -> "image/webp"
|
|
65
|
+
else -> null
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Platform decoders draw a truncated JPEG or PNG with filler; TypeScript codecs refuse it. A
|
|
70
|
+
* JPEG must carry its end-of-image marker near the end (trailing camera data is allowed), a
|
|
71
|
+
* PNG its IEND chunk. */
|
|
72
|
+
fun complete(bytes: ByteArray, mime: String): Boolean {
|
|
73
|
+
val marker = when (mime) {
|
|
74
|
+
"image/jpeg" -> byteArrayOf(0xFF.toByte(), 0xD9.toByte())
|
|
75
|
+
"image/png" -> byteArrayOf(0x49, 0x45, 0x4E, 0x44, 0xAE.toByte(), 0x42, 0x60, 0x82.toByte())
|
|
76
|
+
else -> return true
|
|
77
|
+
}
|
|
78
|
+
val from = max(0, bytes.size - 64 * 1024)
|
|
79
|
+
for (i in bytes.size - marker.size downTo from) {
|
|
80
|
+
if (marker.indices.all { bytes[i + it] == marker[it] }) return true
|
|
81
|
+
}
|
|
82
|
+
return false
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
fun sha256(bytes: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(bytes)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private val lock = Any()
|
|
89
|
+
private val captures = HashMap<String, ByteArray>()
|
|
90
|
+
private var closed = false
|
|
91
|
+
|
|
92
|
+
/** A platform decoder is present. No I/O. */
|
|
93
|
+
val codecAvailable: Boolean get() = codec != null
|
|
94
|
+
|
|
95
|
+
/** Snapshot encoded bytes at the reserved entry boundary; returns the capture token. */
|
|
96
|
+
fun capture(bytes: ByteArray): String {
|
|
97
|
+
if (bytes.isEmpty() || bytes.size > SOURCE_MAX_BYTES) throw failure("image_fetch_failed")
|
|
98
|
+
val owned = bytes.copyOf()
|
|
99
|
+
val token = UUID.randomUUID().toString()
|
|
100
|
+
synchronized(lock) {
|
|
101
|
+
if (closed) throw CrocheError("closed", "The Runtime is closed.")
|
|
102
|
+
captures[token] = owned
|
|
103
|
+
}
|
|
104
|
+
return token
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Current PAL: owned bytes only; Core sniffs the format and computes the source digest. */
|
|
108
|
+
fun readBytes(request: PalImageReadRequest, cancel: CancelToken): ByteArray {
|
|
109
|
+
check(cancel)
|
|
110
|
+
val maxBytes = request.maxBytes.toLong()
|
|
111
|
+
if (maxBytes < 1 || maxBytes > SOURCE_MAX_BYTES) throw failure("image_fetch_failed")
|
|
112
|
+
// Local URIs are not a native input form; https/data belong to Core's transport.
|
|
113
|
+
val source = request.source as? PalImageReadSource.Capture ?: throw failure("image_fetch_failed")
|
|
114
|
+
// A capture is taken once; a second read finds nothing.
|
|
115
|
+
val bytes = synchronized(lock) { captures.remove(source.token) }
|
|
116
|
+
if (bytes == null || bytes.size > maxBytes) throw failure("image_fetch_failed")
|
|
117
|
+
check(cancel)
|
|
118
|
+
return bytes
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Retained prepare-fixture helper; the HostPal readImage entry never uses its metadata.
|
|
122
|
+
fun read(request: PalImageReadRequest, cancel: CancelToken): PalImageBytes {
|
|
123
|
+
val bytes = readBytes(request, cancel)
|
|
124
|
+
return PalImageBytes(bytes, mime(bytes) ?: "", sha256(bytes))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
fun prepare(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken): PalImageBytes {
|
|
128
|
+
check(cancel)
|
|
129
|
+
val maxSide = plan.maxSide?.toLong()
|
|
130
|
+
val maxBytes = plan.maxBytes.toLong()
|
|
131
|
+
if (maxSide != null && maxSide < 1 || maxBytes < 1 || maxBytes > PREPARED_MAX_BYTES || codec == null) throw failure("image_unsupported")
|
|
132
|
+
return try {
|
|
133
|
+
prepareVerified(source, maxSide?.toInt(), maxBytes.toInt(), codec, cancel)
|
|
134
|
+
} catch (error: Throwable) {
|
|
135
|
+
if (error is InterruptedException) Thread.currentThread().interrupt()
|
|
136
|
+
check(cancel)
|
|
137
|
+
throw failure("image_unsupported")
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Idempotent. */
|
|
142
|
+
fun release(token: String) { synchronized(lock) { captures.remove(token) } }
|
|
143
|
+
|
|
144
|
+
fun close() { synchronized(lock) { closed = true; captures.clear() } }
|
|
145
|
+
|
|
146
|
+
// Same steps as TypeScript `prepareImageBytes`.
|
|
147
|
+
private fun prepareVerified(asset: PalImageBytes, maxSide: Int?, maxBytes: Int, codec: PalImageCodec, cancel: CancelToken): PalImageBytes {
|
|
148
|
+
val bytes = asset.bytes.copyOf()
|
|
149
|
+
val mime = mime(bytes)
|
|
150
|
+
if (bytes.isEmpty() || bytes.size > SOURCE_MAX_BYTES || mime == null || !complete(bytes, mime)) throw failure("image_unsupported")
|
|
151
|
+
val digest = sha256(bytes)
|
|
152
|
+
if (!asset.sha256.contentEquals(digest)) throw failure("image_unsupported")
|
|
153
|
+
check(cancel)
|
|
154
|
+
val opened = codec.open(bytes, maxInputPixels) ?: throw failure("image_unsupported")
|
|
155
|
+
opened.use {
|
|
156
|
+
val sourceWidth = opened.width; val sourceHeight = opened.height
|
|
157
|
+
if (sourceWidth < 1 || sourceHeight < 1) throw failure("image_unsupported")
|
|
158
|
+
val scale = maxSide?.let { min(1.0, it.toDouble() / max(sourceWidth, sourceHeight)) } ?: 1.0
|
|
159
|
+
var width = max(1, (sourceWidth * scale).roundToInt())
|
|
160
|
+
var height = max(1, (sourceHeight * scale).roundToInt())
|
|
161
|
+
for (attempt in 0 until 8) {
|
|
162
|
+
check(cancel)
|
|
163
|
+
val rendered = opened.render(width, height)
|
|
164
|
+
check(cancel)
|
|
165
|
+
val candidates = ArrayList<PalImageBytes>(3)
|
|
166
|
+
if (rendered.png.size <= maxBytes) candidates += PalImageBytes(rendered.png, "image/png", sha256(rendered.png))
|
|
167
|
+
rendered.jpeg?.takeIf { it.size <= maxBytes }?.let { candidates += PalImageBytes(it, "image/jpeg", sha256(it)) }
|
|
168
|
+
if (width == sourceWidth && height == sourceHeight && mime != "image/gif" && !opened.reoriented) {
|
|
169
|
+
candidates += PalImageBytes(bytes, mime, digest)
|
|
170
|
+
}
|
|
171
|
+
val best = candidates.minByOrNull { it.bytes.size }
|
|
172
|
+
if (best != null && best.bytes.size <= maxBytes) return best
|
|
173
|
+
if (width == 1 && height == 1) break
|
|
174
|
+
// As TypeScript: an oversized source candidate also guides the shrink.
|
|
175
|
+
val bestLength = minOf(rendered.png.size, rendered.jpeg?.size ?: Int.MAX_VALUE, best?.bytes?.size ?: Int.MAX_VALUE).toDouble()
|
|
176
|
+
val shrink = max(0.1, min(0.8, sqrt(maxBytes / bestLength) * 0.9))
|
|
177
|
+
width = if (attempt == 6) 1 else max(1, (width * shrink).toInt())
|
|
178
|
+
height = if (attempt == 6) 1 else max(1, (height * shrink).toInt())
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
throw failure("image_unsupported")
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
package dev.croche
|
|
2
2
|
|
|
3
|
-
import com.google.gson.JsonElement
|
|
4
|
-
import com.google.gson.JsonNull
|
|
5
3
|
import com.google.gson.JsonObject
|
|
6
4
|
import com.google.gson.JsonPrimitive
|
|
7
5
|
import dev.croche.ffi.ToolImage
|
|
@@ -12,33 +10,14 @@ import java.util.Base64
|
|
|
12
10
|
* first frame). HIGH: as given, within the limits (3 MB each, 6 MB together), for text,
|
|
13
11
|
* screenshots and dense detail. An https `url` image is never changed. An image's own
|
|
14
12
|
* `"resolution"` (`"standard"` or `"high"`) wins over the send's or the tool result's. */
|
|
15
|
-
enum class ImageResolution {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
data class ToolResult(val value: JsonElement = JsonNull.INSTANCE, val images: List<JsonObject> = emptyList(),
|
|
21
|
-
/** For every image that does not name its own `"resolution"`. */
|
|
22
|
-
val imageResolution: ImageResolution? = null)
|
|
23
|
-
fun interface ToolResultHandler { fun execute(invocation: CommandInvocation, context: ToolContext): ToolResult }
|
|
24
|
-
|
|
25
|
-
/** The one way to return a [ToolResult] (its value, plus images): `"room" to withResult { invocation, context -> ToolResult(...) }`.
|
|
26
|
-
* The images go to the Runtime beside the value; a plain [ToolHandler]'s JSON is never looked inside. */
|
|
27
|
-
fun withResult(handler: ToolResultHandler): ToolHandler = ToolHandler { invocation, context ->
|
|
28
|
-
val result = handler.execute(invocation, context)
|
|
29
|
-
// The handler ran: what it returned is read once, here. Anything that cannot be read fails
|
|
30
|
-
// this call alone with our own invalid_tool_result, never another error (Atlas, #351 P1-2).
|
|
31
|
-
try {
|
|
32
|
-
val images = result.images.toList()
|
|
33
|
-
context.images?.images = images.map { CrocheImages.prepare(it, result.imageResolution) }
|
|
34
|
-
result.value
|
|
35
|
-
} catch (failed: Throwable) {
|
|
36
|
-
if (failed is InterruptedException) throw failed
|
|
37
|
-
throw CrocheException("invalid_tool_result", "The tool returned a result that could not be read. Its effects may have completed.")
|
|
38
|
-
}
|
|
13
|
+
enum class ImageResolution {
|
|
14
|
+
/** Use the standard size preparation path where supported. */
|
|
15
|
+
STANDARD,
|
|
16
|
+
/** Keep original encoded detail within Core's image input limits. */
|
|
17
|
+
HIGH
|
|
39
18
|
}
|
|
40
19
|
|
|
41
|
-
/**
|
|
20
|
+
/** Image buffer used by the former tool handler. */
|
|
42
21
|
class ToolImages internal constructor() {
|
|
43
22
|
@Volatile internal var images: List<JsonObject> = emptyList()
|
|
44
23
|
}
|
|
@@ -49,10 +28,19 @@ interface ImageCodec {
|
|
|
49
28
|
* is (a GIF's first frame): PNG, and JPEG unless a pixel can be transparent. Null when this
|
|
50
29
|
* platform cannot decode it. `changed`: resized or turned upright. */
|
|
51
30
|
fun render(bytes: ByteArray, maxSide: Int): Rendered?
|
|
31
|
+
/**
|
|
32
|
+
* Encoded outputs from the platform rendering step.
|
|
33
|
+
*
|
|
34
|
+
* @property changed Whether orientation or dimensions changed during rendering.
|
|
35
|
+
* @property jpeg JPEG candidate when the rendered image can be encoded without losing transparency.
|
|
36
|
+
* @property png Rendered PNG bytes.
|
|
37
|
+
*/
|
|
52
38
|
class Rendered(val png: ByteArray, val jpeg: ByteArray?, val changed: Boolean)
|
|
53
39
|
}
|
|
54
40
|
|
|
41
|
+
/** Helpers for preparing encoded images using the platform codec. */
|
|
55
42
|
object CrocheImages {
|
|
43
|
+
/** Longest side in pixels used for standard image preparation by these helpers. */
|
|
56
44
|
const val STANDARD_MAX_SIDE = 512
|
|
57
45
|
/** The codec standard images go through: on Android, the SDK's Bitmap codec; on a plain JVM
|
|
58
46
|
* none, and images are sent as given. */
|
|
@@ -153,7 +141,7 @@ object CrocheImages {
|
|
|
153
141
|
val v = image.get(key) ?: return null
|
|
154
142
|
if (v.isJsonNull) return null
|
|
155
143
|
if (!v.isJsonPrimitive || !v.asJsonPrimitive.isString)
|
|
156
|
-
throw
|
|
144
|
+
throw CrocheError("invalid_tool_result", "A tool result image's $key is text. Its effects may have completed.")
|
|
157
145
|
return v.asString
|
|
158
146
|
}
|
|
159
147
|
return ToolImage(text("data"), text("url"), text("mime") ?: "", text("alt"))
|