@h1r-ai/croche-react-native 0.6.0 → 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 (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -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
+ }
@@ -1,14 +1,17 @@
1
1
  package dev.croche
2
2
 
3
3
  import dev.croche.ffi.CancelToken
4
- import dev.croche.ffi.PalDecodedImage
5
- import dev.croche.ffi.PalImageDecodeOptions
6
- import dev.croche.ffi.PalImageRenderRequest
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?)
7
10
 
8
11
  /** Native codec effects only. All sizing, formats, limits and candidate selection are Core's. */
9
12
  internal interface DecodedImageCodec : AutoCloseable {
10
- fun decode(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken): PalDecodedImage
11
- fun render(request: PalImageRenderRequest, cancel: CancelToken): ByteArray
13
+ fun decode(bytes: ByteArray, options: ImageDecodeOptions, cancel: CancelToken): DecodedImage
14
+ fun render(request: ImageRenderRequest, cancel: CancelToken): ByteArray
12
15
  fun release(handle: String)
13
16
  }
14
17
 
@@ -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()
20
+ /** Throw a cancellation error if cancellation has been requested. */
19
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,6 +52,7 @@ 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)
@@ -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
+ }