@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,170 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+
5
+ /** The TS question union with native carriers; validation stays in Core. */
6
+ sealed interface DecisionQuestion {
7
+ /** Identifier used to look up the answer in a decision result. */
8
+ val id: String
9
+ /** Instructions presented for answering this question. */
10
+ val instructions: String
11
+ /**
12
+ * Question with true and false outcomes.
13
+ *
14
+ * @property falseDescription Optional description of when the answer should be false.
15
+ * @property id Question ID used in the result's answer map.
16
+ * @property instructions Instructions for evaluating the boolean question.
17
+ * @property trueDescription Optional description of when the answer should be true.
18
+ */
19
+ data class Noul(override val id: String, override val instructions: String, val trueDescription: String? = null, val falseDescription: String? = null) : DecisionQuestion
20
+ /**
21
+ * Question that selects one option from a list.
22
+ *
23
+ * @property criteria Options available to the decision model.
24
+ * @property id Question ID used in the result's answer map.
25
+ * @property instructions Instructions supplied for selecting an option.
26
+ */
27
+ data class Choice(override val id: String, override val instructions: String, val criteria: List<Option>) : DecisionQuestion {
28
+ /**
29
+ * One valid answer supplied for a choice question.
30
+ *
31
+ * @property description Optional explanation of when to select the option.
32
+ * @property id Identifier returned when this option is selected.
33
+ */
34
+ data class Option(val id: String, val description: String? = null)
35
+ }
36
+ /**
37
+ * Question whose criteria describe ordered score levels.
38
+ *
39
+ * @property criteria Descriptions of the score levels in order, starting at zero.
40
+ * @property id Question ID used in the result's answer map.
41
+ * @property instructions Instructions for assigning a score.
42
+ */
43
+ data class Score(override val id: String, override val instructions: String, val criteria: List<String>) : DecisionQuestion
44
+ /** Encode the question and its criteria in the form accepted by Core. */
45
+ fun json() = JsonObject().apply {
46
+ addProperty("id", id); addProperty("instructions", instructions)
47
+ when (val question = this@DecisionQuestion) {
48
+ is Noul -> {
49
+ addProperty("type", "noul")
50
+ if (question.trueDescription != null || question.falseDescription != null) add("criteria", JsonObject().apply {
51
+ question.trueDescription?.let { addProperty("true", it) }; question.falseDescription?.let { addProperty("false", it) }
52
+ })
53
+ }
54
+ is Choice -> { addProperty("type", "choice"); add("criteria", JsonArray().apply { question.criteria.forEach { option -> add(JsonObject().apply {
55
+ addProperty("id", option.id); option.description?.let { addProperty("description", it) }
56
+ }) } }) }
57
+ is Score -> { addProperty("type", "score"); add("criteria", JsonArray().apply { question.criteria.forEach(::add) }) }
58
+ }
59
+ }
60
+ }
61
+ /** A configured question ID or a question defined for this call. */
62
+ sealed interface DecisionQuestionRef {
63
+ /**
64
+ * Selects a question from the decision agent configuration.
65
+ *
66
+ * @property id Configured question ID.
67
+ */
68
+ data class Named(val id: String) : DecisionQuestionRef
69
+ /**
70
+ * Supplies a question directly with the call.
71
+ *
72
+ * @property question Definition used for this question.
73
+ */
74
+ data class Inline(val question: DecisionQuestion) : DecisionQuestionRef
75
+ /** Encode a configured question as its ID, or an inline question as a JSON object. */
76
+ fun json(): JsonElement = when (this) { is Named -> JsonPrimitive(id); is Inline -> question.json() }
77
+ }
78
+ /**
79
+ * Evidence and question selection for a decision call.
80
+ *
81
+ * @property id Optional correlation ID for this decision call. Reusing it after completion can make another paid call.
82
+ * @property questions Question references for this call. Null uses the configured questions.
83
+ * @property state JSON evidence presented to the decision model.
84
+ */
85
+ data class DecideInput(val state: JsonElement, val id: String? = null, val questions: List<DecisionQuestionRef>? = null) {
86
+ internal fun json() = JsonObject().apply {
87
+ add("state", state.deepCopy()); id?.let { addProperty("id", it) }
88
+ questions?.let { list -> add("questions", JsonArray().apply { list.forEach { add(it.json()) } }) }
89
+ }
90
+ }
91
+ /**
92
+ * Confidence value with the method used to obtain it.
93
+ *
94
+ * @property method Method label accompanying the confidence.
95
+ * @property value Numeric confidence reported with the answer.
96
+ */
97
+ data class DecisionConfidence(val value: Double, val method: String)
98
+ /** Answer or refusal associated with one question in a decision result. */
99
+ sealed interface DecisionAnswer {
100
+ /**
101
+ * Boolean answer to a two-outcome question.
102
+ *
103
+ * @property confidence Confidence and its method, when the result includes them.
104
+ * @property probability Reported probability of the true outcome, when supplied.
105
+ * @property value Boolean answer selected for the question.
106
+ */
107
+ data class Noul(val value: Boolean, val probability: Double?, val confidence: DecisionConfidence?) : DecisionAnswer
108
+ /**
109
+ * Selection of one of the supplied options.
110
+ *
111
+ * @property confidence Confidence and its method, when the result includes them.
112
+ * @property probabilities Reported probabilities by option ID, when supplied.
113
+ * @property value ID of the selected option.
114
+ */
115
+ data class Choice(val value: String, val probabilities: Map<String, Double>?, val confidence: DecisionConfidence?) : DecisionAnswer
116
+ /**
117
+ * Numeric answer for an ordered set of levels.
118
+ *
119
+ * @property confidence Confidence and its method, when the result includes them.
120
+ * @property probabilities Reported probabilities indexed by level, when supplied.
121
+ * @property value Numeric score returned for the question.
122
+ */
123
+ data class Score(val value: Double, val probabilities: List<Double>?, val confidence: DecisionConfidence?) : DecisionAnswer
124
+ /**
125
+ * The decision model did not supply an answer to this question.
126
+ *
127
+ * @property reason Reason for the refusal, when supplied.
128
+ */
129
+ data class Refusal(val reason: String?) : DecisionAnswer
130
+ /**
131
+ * A decision answer of a type this SDK does not recognize.
132
+ *
133
+ * @property fields JSON payload retained for the unrecognized answer.
134
+ * @property originalType Original answer type.
135
+ */
136
+ data class Unknown(val originalType: String, val fields: JsonElement) : DecisionAnswer
137
+ }
138
+ /**
139
+ * Answers and usage information returned by a decision call.
140
+ *
141
+ * @property answers Answers and refusals keyed by question ID.
142
+ * @property costStatus Status of the cost observation.
143
+ * @property cost Recorded call cost in credits, or null when unavailable.
144
+ * @property id Correlation ID for the decision call.
145
+ * @property model Model recorded for the decision.
146
+ * @property provider Serving provider, when available.
147
+ * @property usage Usage information recorded for this call.
148
+ */
149
+ data class DecisionResult(val id: String, val model: String, val answers: Map<String, DecisionAnswer>, val provider: String?, val usage: JsonElement, val cost: Double?, val costStatus: String) {
150
+ internal companion object {
151
+ fun read(json: String): DecisionResult {
152
+ val row = JsonParser.parseString(json).asJsonObject
153
+ val answers = row.getAsJsonObject("answers").entrySet().associate { (id, value) ->
154
+ val answer = value.asJsonObject
155
+ fun confidence() = answer.optional("confidence")?.asJsonObject?.let { DecisionConfidence(it.get("value").asDouble, it.get("method").asString) }
156
+ id to when (val type = answer.get("type").asString) {
157
+ "noul" -> DecisionAnswer.Noul(answer.get("value").asBoolean, answer.optional("probability")?.asDouble, confidence())
158
+ "choice" -> DecisionAnswer.Choice(answer.get("value").asString, answer.optional("probabilities")?.asJsonObject?.entrySet()?.associate { it.key to it.value.asDouble }, confidence())
159
+ "score" -> DecisionAnswer.Score(answer.get("value").asDouble, answer.optional("probabilities")?.asJsonArray?.map { it.asDouble }, confidence())
160
+ "refusal" -> DecisionAnswer.Refusal(answer.optional("reason")?.asString)
161
+ "unknown" -> DecisionAnswer.Unknown(answer.get("originalType").asString, answer.get("fields").deepCopy())
162
+ else -> DecisionAnswer.Unknown(type, value.deepCopy())
163
+ }
164
+ }
165
+ return DecisionResult(row.get("id").asString, row.get("model").asString, answers, row.optional("provider")?.asString,
166
+ row.get("usage").deepCopy(), row.optional("cost")?.asDouble, row.get("costStatus").asString)
167
+ }
168
+ private fun JsonObject.optional(key: String) = get(key)?.takeUnless { it.isJsonNull }
169
+ }
170
+ }
@@ -0,0 +1,23 @@
1
+ package dev.croche
2
+
3
+ import dev.croche.ffi.CancelToken
4
+
5
+ // Private platform pixel helpers, not records in the encoded-file PAL ABI.
6
+ internal data class DecodedImage(val handle: String, val width: UInt, val height: UInt, val hasAlpha: Boolean?)
7
+ internal data class ImageDecodeOptions(val frame: UInt, val applyOrientation: Boolean)
8
+ internal enum class ImageFormat { PNG, JPEG }
9
+ internal data class ImageRenderRequest(val handle: String, val width: UInt, val height: UInt, val format: ImageFormat, val quality: Double?)
10
+
11
+ /** Native codec effects only. All sizing, formats, limits and candidate selection are Core's. */
12
+ internal interface DecodedImageCodec : AutoCloseable {
13
+ fun decode(bytes: ByteArray, options: ImageDecodeOptions, cancel: CancelToken): DecodedImage
14
+ fun render(request: ImageRenderRequest, cancel: CancelToken): ByteArray
15
+ fun release(handle: String)
16
+ }
17
+
18
+ /** A JVM without the Android platform artifact has no decoder, with no acquisition fallback. */
19
+ internal fun platformDecodedImageCodec(): DecodedImageCodec? = try {
20
+ Class.forName("dev.croche.android.BitmapDecodedImageCodec").getDeclaredConstructor().newInstance() as DecodedImageCodec
21
+ } catch (_: ClassNotFoundException) {
22
+ null
23
+ }
@@ -15,8 +15,11 @@ import java.util.concurrent.atomic.AtomicBoolean
15
15
  class RuntimeCancellation {
16
16
  private val cancelled = AtomicBoolean(false)
17
17
  private val callbacks = ConcurrentHashMap<Any, () -> Unit>()
18
+ /** Whether cancellation has been requested. */
18
19
  val isCancelled: Boolean get() = cancelled.get()
19
- fun check() { if (isCancelled) throw CrocheException("cancelled", "The operation was cancelled") }
20
+ /** Throw a cancellation error if cancellation has been requested. */
21
+ fun check() { if (isCancelled) throw CrocheError("cancelled", "The operation was cancelled") }
22
+ /** Mark the operation cancelled and notify its registered cancellation listeners. */
20
23
  fun cancel() { if (cancelled.compareAndSet(false, true)) { callbacks.values.forEach { it() }; callbacks.clear() } }
21
24
  internal fun observe(callback: () -> Unit): Any {
22
25
  val key = Any(); callbacks[key] = callback
@@ -29,7 +32,10 @@ class RuntimeCancellation {
29
32
  /** A whole-request transport an app can supply instead of the default. `onDelta` receives each
30
33
  * server-sent event's data while a streamed response arrives, in order, on the calling thread;
31
34
  * the Rust Core assembles them. A transport that cannot stream never calls it. */
32
- fun interface RuntimeHTTP { fun execute(effect: JsonObject, cancellation: RuntimeCancellation, onDelta: (String) -> Unit): JsonObject }
35
+ fun interface RuntimeHTTP {
36
+ /** Execute an HTTP effect and return its response object. A streaming implementation can forward event data through the supplied callback. */
37
+ fun execute(effect: JsonObject, cancellation: RuntimeCancellation, onDelta: (String) -> Unit): JsonObject
38
+ }
33
39
 
34
40
  private const val MAX_RESPONSE_BYTES = 2 * 1024 * 1024
35
41
 
@@ -46,16 +52,17 @@ internal interface ResponseSink {
46
52
  * The Runtime uses it as its PAL transport: the response goes to the Rust Core as it arrives,
47
53
  * and the Core frames, bounds and interprets it. `execute` answers whole requests (2MiB). */
48
54
  class RuntimeHttpURLConnection : RuntimeHTTP {
55
+ /** Run a whole HTTP effect and return status, headers and the JSON body or raw text, subject to the response limit. */
49
56
  override fun execute(effect: JsonObject, cancellation: RuntimeCancellation, onDelta: (String) -> Unit): JsonObject {
50
57
  val headers = effect.at("headers").asJsonObject.entrySet().map { (name, value) -> name to value.asString }
51
58
  val body = effect.at("body").toString().toByteArray(Charsets.UTF_8)
52
59
  return request(effect.at("url").text(), effect.at("method").text(), headers, body, effect.at("timeoutMs").asInt, cancellation) { connection, status ->
53
60
  val fields = JsonObject()
54
61
  connection.headerFields.forEach { (key, values) -> if (key != null) fields.addProperty(key, values.joinToString(", ")) }
55
- if (connection.contentLengthLong > MAX_RESPONSE_BYTES) throw CrocheException("invalid_response", "HTTP response exceeds 2MiB")
62
+ if (connection.contentLengthLong > MAX_RESPONSE_BYTES) throw CrocheError("invalid_response", "HTTP response exceeds 2MiB")
56
63
  val data = ByteArrayOutputStream()
57
64
  read(connection, status, cancellation) { buffer, count ->
58
- if (data.size() + count > MAX_RESPONSE_BYTES) throw CrocheException("invalid_response", "HTTP response exceeds 2MiB")
65
+ if (data.size() + count > MAX_RESPONSE_BYTES) throw CrocheError("invalid_response", "HTTP response exceeds 2MiB")
59
66
  data.write(buffer, 0, count); true
60
67
  }
61
68
  val result = obj("status" to num(status), "headers" to fields)
@@ -71,7 +78,7 @@ class RuntimeHttpURLConnection : RuntimeHTTP {
71
78
  override fun chunk(bytes: ByteArray) = sink.chunk(bytes)
72
79
  }, cancellation)
73
80
  internal fun stream(request: PalHttpRequest, sink: ResponseSink, cancellation: RuntimeCancellation) {
74
- request(request.url, request.method, request.headers.map { it.name to it.value }, request.body.toByteArray(Charsets.UTF_8),
81
+ request(request.url, request.method, request.headers.map { it.name to it.value }, request.body?.toByteArray(Charsets.UTF_8) ?: byteArrayOf(),
75
82
  request.timeoutMs.coerceAtMost(Int.MAX_VALUE.toULong()).toInt(), cancellation) { connection, status ->
76
83
  val fields = connection.headerFields.mapNotNull { (key, values) -> key?.let { PalHeader(it, values.joinToString(", ")) } }
77
84
  sink.head(status, fields)
@@ -82,9 +89,9 @@ class RuntimeHttpURLConnection : RuntimeHTTP {
82
89
  private fun <T> request(url: String, method: String, headers: List<Pair<String, String>>, body: ByteArray, timeoutMs: Int,
83
90
  cancellation: RuntimeCancellation, respond: (HttpURLConnection, Int) -> T): T {
84
91
  cancellation.check()
85
- if (CookieHandler.getDefault() != null) throw CrocheException("network_error", "Default transport requires no process CookieHandler")
92
+ if (CookieHandler.getDefault() != null) throw CrocheError("network_error", "Default transport requires no process CookieHandler")
86
93
  val connection = URI(url).toURL().openConnection() as HttpURLConnection
87
- if (CookieHandler.getDefault() != null) { connection.disconnect(); throw CrocheException("network_error", "Process CookieHandler changed during request creation") }
94
+ if (CookieHandler.getDefault() != null) { connection.disconnect(); throw CrocheError("network_error", "Process CookieHandler changed during request creation") }
88
95
  val listener = cancellation.observe { connection.disconnect() }
89
96
  try {
90
97
  connection.instanceFollowRedirects = false
@@ -126,18 +133,17 @@ internal class EffectExecutor : AutoCloseable {
126
133
  fun run(timeoutMs: Long?, cancellation: RuntimeCancellation, block: (RuntimeCancellation) -> JsonElement): JsonElement {
127
134
  cancellation.check()
128
135
  val local = RuntimeCancellation()
129
- val future = try { pool.submit(Callable { local.check(); block(local).also { local.check() } }) }
130
- catch (_: RejectedExecutionException) { throw CrocheException("effect_failed", "Host effect workers are occupied") }
136
+ val future = pool.submit(Callable { local.check(); block(local).also { local.check() } })
131
137
  val listener = cancellation.observe { local.cancel(); future.cancel(true) }
132
138
  try { return if (timeoutMs == null) future.get() else future.get(timeoutMs.coerceAtLeast(1), TimeUnit.MILLISECONDS) }
133
- catch (_: TimeoutException) { local.cancel(); future.cancel(true); throw CrocheException("timeout", "The effect deadline expired") }
134
- catch (_: CancellationException) { throw CrocheException("cancelled", "The operation was cancelled") }
139
+ catch (_: TimeoutException) { local.cancel(); future.cancel(true); throw CrocheError("timeout", "The effect deadline expired") }
140
+ catch (_: CancellationException) { throw CrocheError("cancelled", "The operation was cancelled") }
135
141
  catch (_: InterruptedException) {
136
142
  local.cancel(); future.cancel(true)
137
143
  // Clear interruption so the following required durable write is not aborted.
138
- Thread.interrupted(); throw CrocheException("cancelled", "The operation was cancelled")
144
+ Thread.interrupted(); throw CrocheError("cancelled", "The operation was cancelled")
139
145
  }
140
- catch (error: ExecutionException) { throw (error.cause as? Exception ?: CrocheException("effect_failed", "The host effect failed")) }
146
+ catch (error: ExecutionException) { throw (error.cause ?: error) }
141
147
  finally { cancellation.remove(listener) }
142
148
  }
143
149
  override fun close() { pool.shutdownNow() }
@@ -163,7 +169,7 @@ internal class ToolExecutor : AutoCloseable {
163
169
  try { local.check(); block(local).also { local.check() } }
164
170
  finally { synchronized(lock) { runner = null }; Thread.interrupted() }
165
171
  })
166
- } catch (_: RejectedExecutionException) { throw CrocheException("host_unresponsive", "The application's command workers are closed") }
172
+ } catch (_: RejectedExecutionException) { throw CrocheError("host_unresponsive", "The application's command workers are closed") }
167
173
  val listener = cancellation.observe { local.cancel(); synchronized(lock) { runner?.interrupt() } }
168
174
  try {
169
175
  while (true) {
@@ -172,8 +178,8 @@ internal class ToolExecutor : AutoCloseable {
172
178
  }
173
179
  }
174
180
  catch (error: ExecutionException) {
175
- if (local.isCancelled) throw CrocheException("cancelled", "The operation was cancelled")
176
- throw handlerError(error.cause)
181
+ if (local.isCancelled) throw CrocheError("cancelled", "The operation was cancelled")
182
+ throw handlerError(error.cause ?: error)
177
183
  }
178
184
  finally { cancellation.remove(listener) }
179
185
  }
@@ -187,9 +193,8 @@ internal class ToolNotDispatched : RuntimeException("No handler ran for this too
187
193
  /** An error from a tool handler. "Nothing ran" is the host's to say, never a handler's: a
188
194
  * handler that throws `tool_not_dispatched` or `host_unresponsive` (perhaps passing on another
189
195
  * Runtime's error) may already have had its effect, so the call fails as `tool_failed`. */
190
- internal fun handlerError(error: Throwable?): Exception = when {
191
- error is ToolNotDispatched -> CrocheException("tool_not_dispatched", "No handler ran for this tool")
192
- error is CrocheException && error.code in setOf("tool_not_dispatched", "host_unresponsive") -> CrocheException("tool_failed", error.message)
193
- error is Exception -> error
194
- else -> CrocheException("effect_failed", "The host effect failed")
196
+ internal fun handlerError(error: Throwable): Throwable = when {
197
+ error is ToolNotDispatched -> CrocheError("tool_not_dispatched", "No handler ran for this tool")
198
+ error is CrocheError && error.code in setOf("tool_not_dispatched", "host_unresponsive") -> CrocheError("tool_failed", error.message)
199
+ else -> error
195
200
  }
@@ -0,0 +1,51 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.Gson
4
+ import com.google.gson.JsonParser
5
+ import dev.croche.ffi.CancelToken
6
+ import dev.croche.ffi.CorePalException
7
+ import dev.croche.ffi.PalImageReply
8
+ import kotlin.math.max
9
+ import kotlin.math.min
10
+ import kotlin.math.roundToInt
11
+ import kotlin.math.sqrt
12
+
13
+ /** Fits encoded files to the supplied limits. Admission and output verification remain Core's. */
14
+ internal class EncodedImageCodec(private val pixels: DecodedImageCodec) {
15
+ val support = ImageSupport(listOf("image/png", "image/jpeg", "image/gif", "image/webp"), listOf("image/png", "image/jpeg"), 50_000_000)
16
+ fun operation(operation: String, bytes: ByteArray, options: String, cancel: CancelToken): PalImageReply = when (operation) {
17
+ "info" -> {
18
+ val image = pixels.decode(bytes, ImageDecodeOptions(0u, true), cancel)
19
+ try {
20
+ val info = ImageInfo(NativeImagePal.mime(bytes) ?: unsupported(), image.width.toInt(), image.height.toInt(), image.hasAlpha)
21
+ PalImageReply(Gson().toJson(info), byteArrayOf())
22
+ } finally { pixels.release(image.handle) }
23
+ }
24
+ "resize" -> PalImageReply("{}", resize(bytes, Gson().fromJson(JsonParser.parseString(options), ImageResizeLimits::class.java), cancel))
25
+ else -> unsupported()
26
+ }
27
+ private fun resize(bytes: ByteArray, limits: ImageResizeLimits, cancel: CancelToken): ByteArray {
28
+ val image = pixels.decode(bytes, ImageDecodeOptions(0u, true), cancel)
29
+ try {
30
+ val scale = limits.maxSide?.let { min(1.0, it.toDouble() / max(image.width.toDouble(), image.height.toDouble())) } ?: 1.0
31
+ var width = max(1, (image.width.toDouble() * scale).roundToInt())
32
+ var height = max(1, (image.height.toDouble() * scale).roundToInt())
33
+ for (attempt in 0 until 8) {
34
+ NativeImagePal.check(cancel)
35
+ val candidates = mutableListOf<ByteArray>()
36
+ if ("image/png" in limits.outputMediaTypes)
37
+ candidates += pixels.render(ImageRenderRequest(image.handle, width.toUInt(), height.toUInt(), ImageFormat.PNG, null), cancel)
38
+ if ("image/jpeg" in limits.outputMediaTypes && image.hasAlpha == false)
39
+ candidates += pixels.render(ImageRenderRequest(image.handle, width.toUInt(), height.toUInt(), ImageFormat.JPEG, 0.7), cancel)
40
+ val best = candidates.minByOrNull { it.size } ?: unsupported()
41
+ if (best.size.toLong() <= limits.maxBytes) return best
42
+ if (width == 1 && height == 1) break
43
+ val shrink = (sqrt(limits.maxBytes.toDouble() / best.size) * 0.9).coerceIn(0.1, 0.8)
44
+ width = if (attempt == 6) 1 else max(1, (width * shrink).toInt())
45
+ height = if (attempt == 6) 1 else max(1, (height * shrink).toInt())
46
+ }
47
+ unsupported()
48
+ } finally { pixels.release(image.handle) }
49
+ }
50
+ private fun unsupported(): Nothing = throw CorePalException.Failure("image_unsupported", "The image operation is not supported.")
51
+ }