@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.
Files changed (248) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +90 -451
  3. package/THIRD-PARTY-NOTICES +906 -14
  4. package/android/build.gradle +6 -1
  5. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
  6. package/android/src/main/AndroidManifest.xml +0 -5
  7. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
  8. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
  9. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
  10. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
  11. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  12. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
  13. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
  14. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  15. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  16. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -0
  17. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  18. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  19. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  20. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  21. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  22. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  33. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  34. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
  35. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  36. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  37. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  38. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  39. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
  40. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  82. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  83. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
  84. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  85. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  86. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
  87. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  88. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  89. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  90. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  91. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
  92. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  93. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  94. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  95. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  96. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  97. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  98. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  99. package/croche-react-native.podspec +1 -0
  100. package/dist/package.json +1 -0
  101. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  102. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  103. package/dist/react-native/src/core-native.d.ts +6 -0
  104. package/dist/react-native/src/core-native.js +316 -0
  105. package/dist/react-native/src/core-wire.d.ts +55 -0
  106. package/dist/react-native/src/core-wire.js +1 -0
  107. package/dist/react-native/src/native-module.d.ts +8 -0
  108. package/dist/react-native/src/native-module.js +53 -0
  109. package/dist/rn-shared-build.json +16 -0
  110. package/dist/runtime/src/adapters.d.ts +8 -0
  111. package/dist/runtime/src/adapters.js +29 -0
  112. package/dist/runtime/src/agent.d.ts +91 -0
  113. package/dist/runtime/src/agent.js +137 -0
  114. package/dist/runtime/src/app-api.d.ts +572 -0
  115. package/dist/runtime/src/app-api.js +1 -0
  116. package/dist/runtime/src/cancel.d.ts +9 -0
  117. package/dist/runtime/src/cancel.js +27 -0
  118. package/dist/runtime/src/core/foreground.d.ts +3 -0
  119. package/dist/runtime/src/core/foreground.js +40 -0
  120. package/dist/runtime/src/core/port.d.ts +247 -0
  121. package/dist/runtime/src/core/port.js +1 -0
  122. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  123. package/dist/runtime/src/core/wasm-owner.js +237 -0
  124. package/dist/runtime/src/core/wasm.d.ts +1 -0
  125. package/dist/runtime/src/core/wasm.js +2 -0
  126. package/dist/runtime/src/croche.d.ts +97 -0
  127. package/dist/runtime/src/croche.js +172 -0
  128. package/dist/runtime/src/errors.d.ts +33 -0
  129. package/dist/runtime/src/errors.js +63 -0
  130. package/dist/runtime/src/events.d.ts +5 -0
  131. package/dist/runtime/src/events.js +31 -0
  132. package/dist/runtime/src/generated/app-stream.d.ts +328 -0
  133. package/dist/runtime/src/generated/app-stream.js +127 -0
  134. package/dist/runtime/src/image-input.d.ts +5 -0
  135. package/dist/runtime/src/image-input.js +60 -0
  136. package/dist/runtime/src/index.d.ts +6 -0
  137. package/dist/runtime/src/index.js +5 -0
  138. package/dist/runtime/src/index.native.d.ts +1 -0
  139. package/dist/runtime/src/index.native.js +2 -0
  140. package/dist/runtime/src/json.d.ts +13 -0
  141. package/dist/runtime/src/json.js +120 -0
  142. package/dist/runtime/src/native-adapter.d.ts +3 -0
  143. package/dist/runtime/src/native-adapter.js +30 -0
  144. package/dist/runtime/src/pal/host.d.ts +5 -0
  145. package/dist/runtime/src/pal/host.js +60 -0
  146. package/dist/runtime/src/pal/platform.d.ts +21 -0
  147. package/dist/runtime/src/pal/platform.js +7 -0
  148. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  149. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  150. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  151. package/dist/runtime/src/pal/state-store.js +1 -0
  152. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  153. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  154. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  155. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  156. package/dist/runtime/src/rn-entry.d.ts +1 -0
  157. package/dist/runtime/src/rn-entry.js +4 -0
  158. package/dist/runtime/src/run-tool.d.ts +33 -0
  159. package/dist/runtime/src/run-tool.js +7 -0
  160. package/dist/runtime/src/tools.d.ts +35 -0
  161. package/dist/runtime/src/tools.js +94 -0
  162. package/ios/CoreAgentTransport.swift +14 -0
  163. package/ios/CoreDeliveryTransport.swift +58 -0
  164. package/ios/CoreNativePal.swift +98 -0
  165. package/ios/CorePlatformTransport.swift +44 -0
  166. package/ios/CoreWireDispatch.swift +122 -0
  167. package/ios/CoreWireSupport.swift +286 -0
  168. package/ios/CrocheRuntimeBridge.swift +34 -994
  169. package/ios/ProjectPal.swift +49 -0
  170. package/ios/RNCrocheRuntime.mm +18 -201
  171. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  172. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  173. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
  174. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  175. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  176. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  177. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
  178. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
  179. package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
  180. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  181. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  182. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  183. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
  184. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  185. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
  186. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
  187. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
  188. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
  189. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  190. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
  191. package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
  192. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
  193. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  194. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  195. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
  196. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  197. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  198. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
  199. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
  200. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  201. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
  202. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  203. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
  204. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
  205. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
  206. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
  207. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
  208. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  209. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  210. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  211. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
  212. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
  213. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  214. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
  215. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
  216. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  217. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +899 -608
  218. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  219. package/package.json +18 -8
  220. package/scripts/README.md +11 -0
  221. package/scripts/build-shared.mjs +46 -0
  222. package/scripts/build.mjs +11 -0
  223. package/scripts/check-swift-vendor-modules.sh +15 -0
  224. package/scripts/vendor-native.sh +8 -6
  225. package/src/NativeCrocheRuntime.ts +12 -159
  226. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  227. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  228. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  229. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  230. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  231. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
  232. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  233. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
  234. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  235. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  236. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  237. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  238. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  239. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
  240. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  241. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  242. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
  243. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
  244. package/src/index.ts +0 -664
  245. package/src/project-types.ts +0 -35
  246. package/src/project.ts +0 -434
  247. package/src/protocol.ts +0 -28
  248. package/src/types.ts +0 -9
@@ -0,0 +1,125 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.Gson
4
+ import com.google.gson.JsonParser
5
+ import dev.croche.StateCommitResult
6
+ import dev.croche.StateCondition
7
+ import dev.croche.StateEntry
8
+ import dev.croche.StateListOptions
9
+ import dev.croche.StateOp
10
+ import dev.croche.StatePage
11
+ import dev.croche.VersionedValue
12
+ import dev.croche.WriteOutcome
13
+ import dev.croche.s7.pal.AtomicKeyFiles
14
+ import java.io.File
15
+ import java.io.RandomAccessFile
16
+ import java.util.UUID
17
+
18
+ /** The desktop JVM's dependency-free file backend. One atomic replacement publishes a batch. */
19
+ internal class JvmStateStore(private val root: File, private val prepareRoot: () -> Unit, sync: (File) -> Unit) {
20
+ private data class Row(val value: String, val version: String)
21
+ private val directory = File(root, "state-batches")
22
+ private val files = AtomicKeyFiles(directory, sync)
23
+ private val gson = Gson()
24
+
25
+ private fun snapshot(): MutableMap<String, Row> {
26
+ val value = files.readRaw(SNAPSHOT) ?: return mutableMapOf()
27
+ return JsonParser.parseString(value).asJsonObject.entrySet().associateTo(mutableMapOf()) { (key, item) ->
28
+ val row = item.asJsonObject
29
+ val stored = row.getAsJsonPrimitive("value")
30
+ val version = row.getAsJsonPrimitive("version")
31
+ require(stored.isString && version.isString)
32
+ stateKey(key) to Row(stored.asString, requireNotNull(storageVersion(version.asString)))
33
+ }
34
+ }
35
+
36
+ private fun save(rows: Map<String, Row>) = files.writeRaw(SNAPSHOT, gson.toJson(rows))
37
+
38
+ private inline fun <T> transaction(block: () -> T): T {
39
+ prepareRoot()
40
+ val gate = File(root, "state-batch.lock").canonicalFile
41
+ // Java rejects overlapping locks in the same JVM, even on separate channels.
42
+ return synchronized(gate.path.intern()) {
43
+ RandomAccessFile(gate, "rw").use { handle ->
44
+ handle.channel.lock().use { block() }
45
+ }
46
+ }
47
+ }
48
+
49
+ fun get(key: String): VersionedValue {
50
+ stateKey(key)
51
+ val row = snapshot()[key]
52
+ return VersionedValue(row?.value, row?.version)
53
+ }
54
+
55
+ fun list(prefix: String, options: StateListOptions): StatePage {
56
+ val range = StateRange(prefix, options)
57
+ // The walk seeks to the page. The snapshot itself is still loaded whole: this standalone
58
+ // JVM store is not a bounded backend yet (HLD storage, As Is gaps).
59
+ // A start key past the prefix leaves an empty interval; a sorted map refuses one that is inverted.
60
+ val rows = java.util.TreeMap(snapshot())
61
+ val page = if (range.from < range.to) rows.subMap(range.from, !range.fromExclusive, range.to, false) else java.util.TreeMap()
62
+ val ordered = if (range.reverse) page.descendingMap() else page
63
+ val entries = ordered.asSequence()
64
+ .take(range.limit + 1)
65
+ .map { (key, row) -> StateEntry(key, row.value) }
66
+ .toList()
67
+ return range.page(entries)
68
+ }
69
+
70
+ private fun MutableMap<String, Row>.apply(op: StateOp): String? = when (op) {
71
+ is StateOp.Put -> UUID.randomUUID().toString().also { this[op.key] = Row(op.value, it) }
72
+ is StateOp.Delete -> { remove(op.key); null }
73
+ }
74
+
75
+ fun commit(ops: List<StateOp>, condition: StateCondition): StateCommitResult {
76
+ validateStateBatch(ops, condition)
77
+ return transaction {
78
+ val rows = snapshot()
79
+ if (rows[condition.key]?.version != condition.version) return@transaction StateCommitResult.Conflict
80
+ for (op in ops) rows.apply(op)
81
+ save(rows)
82
+ StateCommitResult.Committed(rows[condition.key]?.version)
83
+ }
84
+ }
85
+
86
+ fun write(key: String, value: String) {
87
+ stateKey(key)
88
+ transaction { val rows = snapshot(); rows.apply(StateOp.Put(key, value)); save(rows) }
89
+ }
90
+
91
+ fun remove(key: String) {
92
+ stateKey(key)
93
+ if (!directory.exists()) return
94
+ transaction { val rows = snapshot(); if (rows.remove(key) != null) save(rows) }
95
+ }
96
+
97
+ fun writeIf(key: String, value: String?, expect: String?): WriteOutcome {
98
+ stateKey(key)
99
+ storageVersion(expect)
100
+ return transaction {
101
+ val rows = snapshot()
102
+ val current = rows[key]?.version
103
+ if (current != expect) return@transaction WriteOutcome.Conflict(current)
104
+ val written = rows.apply(if (value == null) StateOp.Delete(key) else StateOp.Put(key, value))
105
+ save(rows)
106
+ WriteOutcome.Written(written)
107
+ }
108
+ }
109
+
110
+ fun purge(prefix: String) {
111
+ require(prefix.length > 1 && prefix.endsWith('/'))
112
+ stateKey(prefix)
113
+ if (!directory.exists()) return
114
+ transaction {
115
+ // An interrupted publication may have left a whole unpublished snapshot.
116
+ val plan = files.instancePurgePlan("rows/")
117
+ plan.erase(plan.temporaries)
118
+ plan.durable()
119
+ val rows = snapshot()
120
+ if (rows.keys.removeAll { it.startsWith(prefix) }) save(rows)
121
+ }
122
+ }
123
+
124
+ private companion object { const val SNAPSHOT = "rows/current" }
125
+ }
@@ -0,0 +1,64 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.StateListOptions
4
+ import dev.croche.ffi.*
5
+ import dev.croche.s7.pal.AtomicKeyFiles
6
+ import dev.croche.s7.pal.BlobFiles
7
+ import dev.croche.s7.pal.purgeInstanceFiles
8
+ import java.io.File
9
+ import java.nio.channels.FileChannel
10
+ import java.nio.file.StandardOpenOption
11
+ import java.nio.file.attribute.PosixFilePermissions
12
+ import java.nio.file.Files
13
+
14
+ /** Plain JVM file PAL; Android uses Keystore instead. The private root contains separate
15
+ * opaque state and secret areas. No project identity or store layout is resolved here. */
16
+ internal class JvmStoragePal(root: File = File(System.getProperty("user.home"), ".croche/pal-v1")) : LocalStoragePal {
17
+ private val root = root
18
+ internal val blobs = BlobFiles(root, ::prepareRoot, ::sync)
19
+ private val state = JvmStateStore(root, ::prepareRoot, ::sync)
20
+ private val values = AtomicKeyFiles(File(root, "state"), ::sync)
21
+ private val secrets = AtomicKeyFiles(File(root, "secrets"), ::sync)
22
+ private fun prepareRoot() {
23
+ Files.createDirectories(root.toPath())
24
+ try { Files.setPosixFilePermissions(root.toPath(), PosixFilePermissions.fromString("rwx------")) }
25
+ catch (_: UnsupportedOperationException) { /* Windows uses the user's profile ACL. */ }
26
+ }
27
+ override fun read(key: String) = storageCallback { state.get(logicalStorageKey(key)).value }
28
+ override fun readVersioned(key: String) = storageCallback { state.get(versionedStorageKey(key)).toCore() }
29
+ override fun writeIf(key: String, value: String?, expect: String?) = storageCallback {
30
+ state.writeIf(versionedStorageKey(key), value, expect).toCore(value)
31
+ }
32
+ override fun commitState(ops: List<CoreStateOp>, condition: CoreStateCondition) = storageCallback {
33
+ state.commit(ops.map { it.toApp() }, condition.toApp()).toCore()
34
+ }
35
+ override fun listState(prefix: String, options: CoreStateListOptions) = storageCallback {
36
+ state.list(prefix, options.toApp()).toCore()
37
+ }
38
+ override fun write(key: String, value: String) = storageCallback { state.write(logicalStorageKey(key), value) }
39
+ override fun remove(key: String) = storageCallback { state.remove(logicalStorageKey(key)) }
40
+ override fun purgeInstance(prefix: String, secretKey: String?) = purgeStorage(prefix, true, true)
41
+ override fun purgeStorage(
42
+ prefix: String, localState: Boolean, localSecret: Boolean, deleteSecret: () -> Unit, deleteState: () -> Unit,
43
+ ) = storageCallback {
44
+ purgeInstanceFiles(values.takeIf { localState }, secrets.takeIf { localSecret }, prefix, deleteSecret, deleteState)
45
+ if (localState) state.purge(prefix)
46
+ }
47
+ override fun list(prefix: String): List<String> = storageCallback {
48
+ logicalStorageKey(prefix)
49
+ buildList {
50
+ var cursor: String? = null
51
+ do {
52
+ val page = state.list(prefix, StateListOptions(cursor = cursor))
53
+ addAll(page.entries.map { it.key })
54
+ cursor = page.nextCursor
55
+ } while (cursor != null)
56
+ }
57
+ }
58
+ override fun lock(name: String) = storageCallback { prepareRoot(); if (values.lock(name)) PalLockOutcome.ACQUIRED else PalLockOutcome.HELD }
59
+ override fun unlock(name: String) = storageCallback { values.unlock(name) }
60
+ override fun readSecret(key: String) = storageCallback { secrets.read(key) }
61
+ override fun writeSecret(key: String, value: String) = storageCallback { prepareRoot(); secrets.write(key, value) }
62
+ override fun removeSecret(key: String) = storageCallback { secrets.remove(key) }
63
+ private fun sync(directory: File) { FileChannel.open(directory.toPath(), StandardOpenOption.READ).use { it.force(true) } }
64
+ }
@@ -0,0 +1,18 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.ffi.*
4
+
5
+ /** Hale's L1/R1 ABI. No reflection, static-deletion fallback, recovery policy or mutable global hook. */
6
+ internal interface LifecycleBinding {
7
+ fun open(openJson: String, registrations: List<CoreToolRegistration>, storage: CoreStoragePal?, host: HostPal,
8
+ bindingFactsJson: String, recoveryJson: String?): CoreCrocheInterface
9
+ fun deleteData(owner: CoreCrocheInterface, scopeJson: String?)
10
+ }
11
+
12
+ /** Compilation intentionally depends on #1144's regenerated bindings; never emulate recovery in the SDK. */
13
+ internal object GeneratedLifecycleBinding : LifecycleBinding {
14
+ override fun open(openJson: String, registrations: List<CoreToolRegistration>, storage: CoreStoragePal?, host: HostPal,
15
+ bindingFactsJson: String, recoveryJson: String?): CoreCroche =
16
+ CoreCroche.open(openJson, registrations, storage, host, bindingFactsJson, recoveryJson)
17
+ override fun deleteData(owner: CoreCrocheInterface, scopeJson: String?) = owner.deleteData(scopeJson)
18
+ }
@@ -0,0 +1,21 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.ffi.uniffiEnsureInitialized
4
+
5
+ // Cache a failed load too, so later calls retain the original mismatch diagnostic.
6
+ private val nativeInitializationFailure: LinkageError? by lazy {
7
+ try {
8
+ uniffiEnsureInitialized()
9
+ null
10
+ } catch (failure: LinkageError) {
11
+ failure
12
+ }
13
+ }
14
+
15
+ // Native-backed SDK methods go through publicSync/publicCall. Entry points that start a
16
+ // native lifetime directly (RN module and Android worker) must call this before using FFI.
17
+ internal fun ensureNativeCoreInitialized() {
18
+ val failure = nativeInitializationFailure ?: return
19
+ val reason = (failure as? ExceptionInInitializerError)?.cause ?: failure
20
+ throw IllegalStateException("Croche native Core initialization failed: ${reason.message ?: reason.javaClass.simpleName}", failure)
21
+ }
@@ -0,0 +1,60 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.ffi.*
4
+ import dev.croche.SelectedAdapters
5
+ import kotlinx.coroutines.CoroutineDispatcher
6
+ import kotlinx.coroutines.Dispatchers
7
+ import java.lang.reflect.InvocationTargetException
8
+
9
+ internal data class NativePlatformPals(val storage: CoreStoragePal, val host: HostPal,
10
+ val eventDispatcher: CoroutineDispatcher, val platformStorage: CoreStoragePal? = null)
11
+ internal interface NativePlatformProvider {
12
+ fun create(platform: Any?, adapters: SelectedAdapters): NativePlatformPals
13
+ }
14
+
15
+ /** The second carrier exists only for Core's private custom-backend enrollment marker. */
16
+ internal fun backgroundStorage(custom: CoreStoragePal?, platform: () -> CoreStoragePal): Pair<CoreStoragePal, CoreStoragePal?> {
17
+ val default = platform()
18
+ return Pair(custom ?: default, default.takeIf { custom != null })
19
+ }
20
+
21
+ internal fun backgroundStorage(adapters: SelectedAdapters, platform: LocalStoragePal): Pair<CoreStoragePal, CoreStoragePal?> {
22
+ val custom = adapters.state?.let { appStorage(platform, it) }
23
+ return backgroundStorage(custom) { platform }
24
+ }
25
+
26
+ /** Android ships the provider in its AAR; plain JVM uses file effects. No Core-side default. */
27
+ internal fun nativePlatform(platform: Any?, adapters: SelectedAdapters): NativePlatformPals {
28
+ val android = try { Class.forName("dev.croche.android.pal.AndroidPublicPlatform") } catch (_: ClassNotFoundException) { null }
29
+ if (android != null) {
30
+ try {
31
+ return (android.getDeclaredConstructor().newInstance() as NativePlatformProvider).create(platform, adapters)
32
+ } catch (error: InvocationTargetException) { throw error.targetException }
33
+ }
34
+ val default = JvmStoragePal()
35
+ val (storage, platformStorage) = backgroundStorage(adapters, default)
36
+ val host = JvmCoreHost(storage, default.blobs)
37
+ return NativePlatformPals(storage, host, Dispatchers.Unconfined, platformStorage)
38
+ }
39
+
40
+ /** App storage throws facts only, just like platform storage. A supplied code is not copied. */
41
+ internal fun storageFacts(storage: CoreStoragePal): CoreStoragePal = object : CoreStoragePal {
42
+ override fun commitState(ops: List<CoreStateOp>, condition: CoreStateCondition) = storageCallback {
43
+ storage.commitState(ops, condition)
44
+ }
45
+ override fun listState(prefix: String, options: CoreStateListOptions) = storageCallback {
46
+ storage.listState(prefix, options)
47
+ }
48
+ override fun readVersioned(key: String) = storageCallback { storage.readVersioned(key) }
49
+ override fun writeIf(key: String, value: String?, expect: String?) = storageCallback { storage.writeIf(key, value, expect) }
50
+ override fun read(key: String) = storageCallback { storage.read(key) }
51
+ override fun write(key: String, value: String) = storageCallback { storage.write(key, value) }
52
+ override fun remove(key: String) = storageCallback { storage.remove(key) }
53
+ override fun purgeInstance(prefix: String, secretKey: String?) = storageCallback { storage.purgeInstance(prefix, secretKey) }
54
+ override fun list(prefix: String) = storageCallback { storage.list(prefix) }
55
+ override fun lock(name: String) = storageCallback { storage.lock(name) }
56
+ override fun unlock(name: String) = storageCallback { storage.unlock(name) }
57
+ override fun readSecret(key: String) = storageCallback { storage.readSecret(key) }
58
+ override fun writeSecret(key: String, value: String) = storageCallback { storage.writeSecret(key, value) }
59
+ override fun removeSecret(key: String) = storageCallback { storage.removeSecret(key) }
60
+ }
@@ -0,0 +1,27 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.CrocheError
4
+ import dev.croche.ffi.CorePalException
5
+ import dev.croche.ffi.CoreStorageFailure
6
+
7
+ /** Storage carries exception detail only, regardless of the exception's class or any code. */
8
+ internal inline fun <T> storageCallback(block: () -> T): T = try {
9
+ block()
10
+ } catch (error: CoreStorageFailure) {
11
+ throw error
12
+ } catch (error: Throwable) {
13
+ throw CoreStorageFailure.Failure(error.message ?: error.javaClass.simpleName)
14
+ }
15
+
16
+ /** A supplied effect fact is never reclassified here. Core validates it for that effect.
17
+ * An unexpected uncoded failure has the literal internal code, never a platform fallback.
18
+ */
19
+ internal inline fun <T> effectCallback(block: () -> T): T = try {
20
+ block()
21
+ } catch (error: CorePalException) {
22
+ throw error
23
+ } catch (error: CrocheError) {
24
+ throw CorePalException.Failure(error.code, error.message)
25
+ } catch (error: Throwable) {
26
+ throw CorePalException.Failure("internal", error.message ?: error.javaClass.simpleName)
27
+ }
@@ -0,0 +1,56 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.*
4
+ import java.util.Collections
5
+ import java.util.IdentityHashMap
6
+
7
+ /** Mechanical JSON serialization only. Core owns all numeric limits and result interpretation. */
8
+ internal object PlainToolJson {
9
+ private val number = Regex("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?")
10
+ fun encode(value: Any?): JsonElement? = encode(value, Collections.newSetFromMap(IdentityHashMap<Any, Boolean>()))
11
+
12
+ private fun jsonNumber(value: Number): JsonElement? {
13
+ val token = value.toString() // Capture once, without a lossy Double/Long conversion.
14
+ if (!number.matches(token)) return null
15
+ return JsonParser.parseString(token)
16
+ }
17
+
18
+ private fun encode(value: Any?, visiting: MutableSet<Any>): JsonElement? {
19
+ when (value) {
20
+ null, is JsonNull -> return JsonNull.INSTANCE
21
+ is JsonPrimitive -> return if (value.isNumber) jsonNumber(value.asNumber) else value.deepCopy()
22
+ is String -> return JsonPrimitive(value)
23
+ is Number -> return jsonNumber(value)
24
+ is Boolean -> return JsonPrimitive(value)
25
+ is Map<*, *>, is List<*>, is JsonObject, is JsonArray -> Unit
26
+ else -> return null // Unsupported objects are not reflected or stringified.
27
+ }
28
+ // A cyclic container has no JSON representation. Repeated non-cyclic values are fine.
29
+ if (!visiting.add(value)) return null
30
+ try {
31
+ return when (value) {
32
+ is Map<*, *> -> fields(value.entries, visiting)
33
+ is JsonObject -> fields(value.entrySet(), visiting)
34
+ is JsonArray -> items(value, visiting)
35
+ else -> items(value as List<*>, visiting)
36
+ }
37
+ } finally {
38
+ visiting.remove(value)
39
+ }
40
+ }
41
+
42
+ private fun fields(entries: Iterable<Map.Entry<*, *>>, visiting: MutableSet<Any>): JsonObject? {
43
+ val result = JsonObject()
44
+ for ((key, item) in entries) {
45
+ if (key !is String) return null
46
+ result.add(key, encode(item, visiting) ?: return null)
47
+ }
48
+ return result
49
+ }
50
+
51
+ private fun items(values: Iterable<*>, visiting: MutableSet<Any>): JsonArray? {
52
+ val result = JsonArray()
53
+ for (item in values) result.add(encode(item, visiting) ?: return null)
54
+ return result
55
+ }
56
+ }
@@ -0,0 +1,43 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.CrocheError
4
+ import dev.croche.ErrorCategory
5
+ import dev.croche.ffi.CancelToken
6
+ import dev.croche.ffi.CoreApiException
7
+ import kotlinx.coroutines.*
8
+ import kotlin.coroutines.resumeWithException
9
+
10
+ /** No result/default/code policy: only translate Core's supplied public error envelope. */
11
+ internal fun publicFailure(error: Throwable): Throwable = when (error) {
12
+ is java.lang.reflect.UndeclaredThrowableException -> publicFailure(error.undeclaredThrowable)
13
+ is CrocheError -> error
14
+ is CoreApiException.Failure -> CrocheError(error.code, error.detail,
15
+ ErrorCategory.entries.firstOrNull { it.name.equals(error.category, ignoreCase = true) } ?: ErrorCategory.INTERNAL, error.path, error.retryAfter)
16
+ else -> CrocheError("internal", error.message ?: "Core binding failed.", ErrorCategory.INTERNAL)
17
+ }
18
+
19
+ private val calls = CoroutineScope(SupervisorJob() + Dispatchers.IO)
20
+
21
+ /** One off-thread native call; cancellation fires the Core token, never Agent.cancel(). */
22
+ @OptIn(ExperimentalCoroutinesApi::class)
23
+ internal suspend fun <T> publicCall(discard: (T) -> Unit = {}, block: (CancelToken) -> T): T = suspendCancellableCoroutine { continuation ->
24
+ ensureNativeCoreInitialized()
25
+ val token = CancelToken()
26
+ val tokenLock = Any()
27
+ var tokenLive = true
28
+ continuation.invokeOnCancellation { synchronized(tokenLock) { if (tokenLive) token.cancel() } }
29
+ calls.launch {
30
+ try {
31
+ val answer: Result<T> = runCatching { publicSync { block(token) } }
32
+ answer.fold(
33
+ { value -> continuation.resume(value) { _, unreceived, _ -> discard(unreceived) } },
34
+ { error -> continuation.resumeWithException(error) },
35
+ )
36
+ } finally { synchronized(tokenLock) { tokenLive = false; token.destroy() } }
37
+ }
38
+ }
39
+
40
+ internal fun <T> publicSync(block: () -> T): T {
41
+ ensureNativeCoreInitialized()
42
+ return try { block() } catch (error: Throwable) { throw publicFailure(error) }
43
+ }
@@ -0,0 +1,29 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.JsonArray
4
+ import com.google.gson.JsonElement
5
+ import com.google.gson.JsonObject
6
+ import com.google.gson.JsonPrimitive
7
+
8
+ /** Internal staging for APP-API at dcf068ed; not a second public SDK surface. */
9
+ internal sealed interface ScopeSelection {
10
+ data object All : ScopeSelection
11
+ // Keep list order and duplicates. Core validates and resolves the entries.
12
+ data class Entries(val entries: List<JsonElement>) : ScopeSelection
13
+ }
14
+
15
+ internal fun ScopeSelection.toJson(): JsonElement = when (this) {
16
+ ScopeSelection.All -> JsonPrimitive("all")
17
+ is ScopeSelection.Entries -> JsonArray().also { array -> entries.forEach { array.add(it) } }
18
+ }
19
+
20
+ /** Null selectors are omitted; nulls inside JSON values, including binds, are preserved. */
21
+ internal fun agentOptionsJson(
22
+ instance: JsonObject? = null,
23
+ tools: ScopeSelection? = null,
24
+ wiki: ScopeSelection? = null,
25
+ ): String = JsonObject().apply {
26
+ instance?.let { add("instance", it) }
27
+ tools?.let { add("tools", it.toJson()) }
28
+ wiki?.let { add("wiki", it.toJson()) }
29
+ }.toString()
@@ -0,0 +1,103 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.JsonArray
4
+ import com.google.gson.JsonNull
5
+ import com.google.gson.JsonParser
6
+ import dev.croche.StateCommitResult
7
+ import dev.croche.StateCondition
8
+ import dev.croche.StateEntry
9
+ import dev.croche.StateListOptions
10
+ import dev.croche.StateOp
11
+ import dev.croche.StatePage
12
+ import dev.croche.ffi.CoreStateCommit
13
+ import dev.croche.ffi.CoreStateCondition
14
+ import dev.croche.ffi.CoreStateEntry
15
+ import dev.croche.ffi.CoreStateListOptions
16
+ import dev.croche.ffi.CoreStateOp
17
+ import dev.croche.ffi.CoreStatePage
18
+
19
+ private val stateKeyPattern = Regex("[A-Za-z0-9._/-]{1,200}")
20
+ internal fun stateKey(key: String): String {
21
+ require(stateKeyPattern.matches(key)) { "Invalid StateStore key" }
22
+ return key
23
+ }
24
+
25
+ internal fun validateStateBatch(ops: List<StateOp>, condition: StateCondition) {
26
+ stateKey(condition.key)
27
+ storageVersion(condition.version)
28
+ require(ops.isNotEmpty()) { "Invalid StateStore batch" }
29
+ val keys = mutableSetOf<String>()
30
+ for (op in ops) {
31
+ stateKey(op.key)
32
+ require(keys.add(op.key)) { "Invalid StateStore batch" }
33
+ }
34
+ }
35
+
36
+ /** Bounds use Core's ASCII key grammar, so SQLite BINARY is the same UTF-8 order. */
37
+ internal class StateRange(private val prefix: String, private val options: StateListOptions) {
38
+ val lower: String
39
+ val upper: String
40
+ val after: String
41
+ val limit: Int
42
+ val reverse = options.reverse
43
+
44
+ // The two key bounds of this page (HLD storage, "Range reads"). A cursor replaces a bound.
45
+ // Written as a third predicate it makes SQLite seek to the range start and filter every
46
+ // earlier page again.
47
+ private val resumed = options.cursor != null
48
+ /** Lower bound: exclusive when an ascending walk resumes after its cursor, else inclusive. */
49
+ val from: String get() = if (!reverse && resumed) after else lower
50
+ val fromExclusive: Boolean get() = !reverse && resumed
51
+ /** Upper bound, always exclusive: the cursor when a descending walk resumes. */
52
+ val to: String get() = if (reverse && resumed) after else upper
53
+ /** The key bounds and order of the page statement; binds `from`, `to`, then the row limit. */
54
+ val bounds: String get() =
55
+ "FROM state WHERE key ${if (fromExclusive) ">" else ">="} ? AND key < ? ORDER BY key ${if (reverse) "DESC" else "ASC"} LIMIT ?"
56
+
57
+ init {
58
+ if (prefix.isNotEmpty()) stateKey(prefix)
59
+ options.start?.let(::stateKey)
60
+ val size = options.limit ?: 128u
61
+ require(size > 0u) { "Invalid StateStore list limit" }
62
+ limit = minOf(size, 128u).toInt()
63
+ lower = maxOf(prefix, options.start ?: prefix)
64
+ upper = if (prefix.isEmpty()) "\u007f" else prefix.dropLast(1) + (prefix.last() + 1)
65
+ after = options.cursor?.let { cursor ->
66
+ try {
67
+ val fields = JsonParser.parseString(cursor).asJsonArray
68
+ require(fields.size() == 4 && fields[0].asJsonPrimitive.isString && fields[0].asString == prefix)
69
+ require(if (options.start == null) fields[1].isJsonNull else
70
+ fields[1].asJsonPrimitive.isString && fields[1].asString == options.start)
71
+ require(fields[2].asJsonPrimitive.isBoolean && fields[2].asBoolean == reverse)
72
+ require(fields[3].asJsonPrimitive.isString)
73
+ stateKey(fields[3].asString).also { require(it >= lower && it < upper) }
74
+ } catch (_: RuntimeException) {
75
+ throw IllegalArgumentException("Invalid StateStore cursor")
76
+ }
77
+ } ?: if (reverse) upper else ""
78
+ }
79
+
80
+ /** `more`: the adapter stopped before the range ended, so a short page still carries a cursor. */
81
+ fun page(rows: List<StateEntry>, more: Boolean = false): StatePage {
82
+ val entries = rows.take(limit)
83
+ val cursor = if (rows.size > limit || (more && entries.isNotEmpty())) JsonArray().apply {
84
+ add(prefix)
85
+ if (options.start == null) add(JsonNull.INSTANCE) else add(options.start)
86
+ add(reverse)
87
+ add(entries.last().key)
88
+ }.toString() else null
89
+ return StatePage(entries, cursor)
90
+ }
91
+ }
92
+
93
+ internal fun CoreStateCondition.toApp() = StateCondition(key, version)
94
+ internal fun CoreStateListOptions.toApp() = StateListOptions(start, reverse, limit, cursor)
95
+ internal fun CoreStateOp.toApp(): StateOp = when (this) {
96
+ is CoreStateOp.Put -> StateOp.Put(key, value)
97
+ is CoreStateOp.Delete -> StateOp.Delete(key)
98
+ }
99
+ internal fun StateCommitResult.toCore(): CoreStateCommit = when (this) {
100
+ is StateCommitResult.Committed -> CoreStateCommit.Committed(storageVersion(version))
101
+ StateCommitResult.Conflict -> CoreStateCommit.Conflict
102
+ }
103
+ internal fun StatePage.toCore() = CoreStatePage(entries.map { CoreStateEntry(it.key, it.value) }, nextCursor)
@@ -0,0 +1,40 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.VersionedValue
4
+ import dev.croche.WriteOutcome
5
+ import dev.croche.ffi.CoreVersionedValue
6
+ import dev.croche.ffi.CoreWriteOutcome
7
+ import java.io.IOException
8
+
9
+ internal fun logicalStorageKey(key: String): String {
10
+ if (key.trimEnd('/').substringAfterLast('/') == ".p1") throw IOException("Reserved storage sibling")
11
+ return key
12
+ }
13
+ internal fun versionedStorageKey(key: String): String {
14
+ logicalStorageKey(key)
15
+ if (!Regex("[A-Za-z0-9._/-]{1,196}").matches(key) || key.split('/').contains("secret-index")) {
16
+ throw IOException("Invalid versioned storage key")
17
+ }
18
+ return key
19
+ }
20
+ internal fun storageVersion(token: String?): String? {
21
+ if (token != null && (token.isEmpty() || token.length > 128 || token.any { it.code !in 0x21..0x7e })) {
22
+ throw IOException("Invalid storage version")
23
+ }
24
+ return token
25
+ }
26
+ internal fun VersionedValue.toCore(): CoreVersionedValue {
27
+ val token = storageVersion(version)
28
+ if ((value == null) != (token == null)) throw IOException("Unpaired storage value and version")
29
+ return CoreVersionedValue(value, token)
30
+ }
31
+ /** Pair with the immutable request value, never a later read/current request. */
32
+ internal fun WriteOutcome.toCore(requestedValue: String?): CoreWriteOutcome = when (this) {
33
+ is WriteOutcome.Conflict -> CoreWriteOutcome.Conflict(storageVersion(version))
34
+ is WriteOutcome.Written -> {
35
+ val token = storageVersion(version)
36
+ if ((requestedValue == null) != (token == null)) throw IOException("Written version does not match request")
37
+ if (token == "legacy") throw IOException("Written must return a new storage version")
38
+ CoreWriteOutcome.Written(token)
39
+ }
40
+ }
@@ -0,0 +1,29 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.JsonElement
4
+ import com.google.gson.JsonObject
5
+ import dev.croche.ToolResult
6
+
7
+ /** Syntax only: Core classifies branded content, including strings, arrays and null.
8
+ * A plain object containing a content key never becomes a branded result by inspection.
9
+ */
10
+ internal object ToolCompletionEncoding {
11
+ private const val invalidResult = """{"type":"invalid_result"}"""
12
+
13
+ /** Only serialization failures become invalid_result; handler throws are caught by the caller. */
14
+ fun returned(value: Any?): String = try {
15
+ when (value) {
16
+ null -> """{"type":"empty"}"""
17
+ is ToolResult -> PlainToolJson.encode(value.content)?.let(::result) ?: invalidResult
18
+ else -> PlainToolJson.encode(value)?.let(::json) ?: invalidResult
19
+ }
20
+ } catch (_: Throwable) { invalidResult }
21
+
22
+ fun result(content: JsonElement): String = tagged("result", "content", content)
23
+ fun json(value: JsonElement): String = tagged("json", "value", value)
24
+
25
+ private fun tagged(type: String, key: String, value: JsonElement): String = JsonObject().also {
26
+ it.addProperty("type", type)
27
+ it.add(key, value.deepCopy())
28
+ }.toString()
29
+ }