@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
@@ -2,7 +2,31 @@ package dev.croche
2
2
 
3
3
  import com.google.gson.*
4
4
 
5
- class CrocheException(val code: String, override val message: String, val receipt: Receipt? = null) : RuntimeException("$code: $message")
5
+ /** Closed set of error categories used to decide how the app should respond. */
6
+ typealias ErrorCategory = AppStreamContract.ErrorCategory
7
+
8
+ /**
9
+ * Error translated from Core or raised by the host wrapper.
10
+ *
11
+ * @property code Machine-readable error code.
12
+ * @property message Human-readable failure message.
13
+ * @property category Group used to decide how the app should handle the error.
14
+ * @property path Location supplied for a field-specific error, when available.
15
+ * @property retryAfter Suggested retry delay in seconds, when supplied.
16
+ */
17
+ class CrocheError internal constructor(val code: String, override val message: String,
18
+ val category: ErrorCategory, val path: String? = null, val retryAfter: ULong? = null) : Exception(message) {
19
+ // Only the retained legacy implementation calls this constructor; S1 uses the full envelope.
20
+ internal constructor(code: String, message: String) : this(code, message, ErrorCategory.INTERNAL, null)
21
+ }
22
+
23
+ /** Known agent error codes; other Core and host codes reach [CrocheError.code] verbatim. */
24
+ object CrocheErrorCode {
25
+ /** The id is open with another configuration or parent, or already holds a child's data. */
26
+ const val AGENT_CONFLICT = "agent_conflict"
27
+ /** Core refused the runtime configuration. */
28
+ const val INVALID_CONFIGURATION = "invalid_configuration"
29
+ }
6
30
 
7
31
  internal fun obj(vararg fields: Pair<String, JsonElement>): JsonObject = JsonObject().apply { fields.forEach { add(it.first, it.second) } }
8
32
  internal fun str(value: String): JsonElement = JsonPrimitive(value)
@@ -1,120 +1,138 @@
1
1
  package dev.croche
2
2
 
3
3
  import com.google.gson.*
4
- import dev.croche.ffi.CoreProject
5
- import dev.croche.ffi.ProjectOpenOptions
6
- import kotlinx.coroutines.Dispatchers
7
- import kotlinx.coroutines.withContext
8
- import kotlinx.coroutines.sync.Mutex
9
- import kotlinx.coroutines.sync.withLock
10
- import java.io.File
4
+ import dev.croche.ffi.*
5
+ import dev.croche.s7.*
11
6
 
12
- /** Project census, config selection, overrides, instances and durable ownership belong to Core. */
13
- class Croche private constructor(private val binding: ProjectBinding) {
14
- private val agents = mutableMapOf<CrocheRuntime, CrocheAgent>()
15
- private val admission = Mutex()
16
- val user: String? get() = binding.user
17
- val installationId: String? get() = binding.installationId
18
- val crocheUserId: String? get() = binding.crocheUserId
19
- val agentIds: List<String> get() = binding.agentIds
20
- suspend fun agent(id: String? = null, options: AgentOptions = AgentOptions()): CrocheAgent {
21
- val encoded = JsonObject().apply {
22
- options.instance?.let { addProperty("instance", it) }
23
- options.fresh?.let { addProperty("fresh", it) }
24
- options.config?.let { add("config", it.deepCopy()) }
25
- }.toString()
26
- return admission.withLock {
27
- projectIO {
28
- agents.entries.removeIf { it.key.isClosed }
29
- val (core, runtime) = binding.agent(id, encoded)
30
- agents.getOrPut(runtime) { CrocheAgent.adopt(core, runtime) }
31
- }
7
+ /** One Core owner; no wrapper agent registry, resolved config or admission decisions. */
8
+ class Croche internal constructor(core: CoreCrocheInterface, private val pals: NativePlatformPals,
9
+ private val lifecycle: LifecycleBinding = GeneratedLifecycleBinding) {
10
+ private val core = NativeHandleOwner.wrap(CoreCrocheInterface::class.java, core)
11
+ /** Let an app button run a tool outside chat, such as generating an image for a form. */
12
+ suspend fun runTool(name: String, args: JsonObject, id: String): RunToolResult = dev.croche.runTool(core, name, args, id)
13
+ /** Load a shared attachment when the user opens its preview. */
14
+ suspend fun attachment(id: String): AttachmentData = publicCall { PublicResults.attachmentData(core.attachment(id)) }
15
+ /** Let the user remove a shared attachment they no longer want to keep. */
16
+ suspend fun deleteAttachment(id: String) { publicCall { core.deleteAttachment(id) } }
17
+ /** Populate a picker of attachments shared by this user’s agents, newest first, one page at a time. */
18
+ suspend fun listAttachments(options: ListOptions? = null): Page<AppStreamContract.Attachment> =
19
+ publicCall { PublicResults.attachments(core.listAttachments(options?.json())) }
20
+ /** Give each chat, case, or workspace its own conversation while reusing the app’s agent definition. */
21
+ suspend fun agent(id: String, options: AgentOptions? = null): CrocheAgent = publicCall {
22
+ CrocheAgent(core.agent(id, options?.json()?.toString()), pals.eventDispatcher)
23
+ }
24
+ /** Let a host deliver scheduled work when its timer or alarm fires. */
25
+ suspend fun deliverDue(): DueDelivery = publicCall { cancel -> PublicResults.delivery(core.deliverDue(null, cancel)) }
26
+ /** Let the app show how Croche Cloud verified this installation, or explain a withheld key. Read-only; never calls Cloud. */
27
+ suspend fun verification(): Verification = publicCall { PublicResults.verification(core.verification()) }
28
+ /** Access the current user's daily allowance controls. */
29
+ val allowance = Allowance()
30
+ /** Manage the local daily spend limit for this user. */
31
+ inner class Allowance internal constructor() {
32
+ /**
33
+ * Set this user's allowance: the most credits the runtime lets this user spend per UTC day. Absolute, it
34
+ * replaces the earlier value; null returns the user to Studio's default. The runtime counts and enforces it
35
+ * from its own storage; Croche Cloud keeps no per-user ledger (founder 2026-11-21; same call as TS/RN/Swift).
36
+ */
37
+ suspend fun set(limit: Double?) { publicCall { core.allowanceSet(limit?.let { JsonPrimitive(it) }?.toString() ?: "null") } }
38
+ }
39
+ /** Access the project's wiki documents available to this user. */
40
+ val wiki = Wiki()
41
+ /** Manage the app help documents made available to agents. */
42
+ inner class Wiki internal constructor() {
43
+ /** Make an updated help article available to agents in the current app session. */
44
+ suspend fun put(doc: WikiDoc) { publicCall { core.wikiPut(doc.json().toString()) } }
45
+ /** Stop agents from using a help article the app has withdrawn. */
46
+ suspend fun remove(path: String) { publicCall { core.wikiRemove(path) } }
47
+ /** Show which help articles the app has made available to its agents. */
48
+ suspend fun list(options: ListOptions? = null): Page<WikiDoc> = publicCall { PublicResults.wiki(core.wikiList(options?.json())) }
49
+ }
50
+ /** Access debugger controls for this session. */
51
+ val debugger = Debugger()
52
+ /** Attach or detach access to the runtime debugger for this session. */
53
+ inner class Debugger internal constructor() {
54
+ /** Inspect a running session when a development build behaves unexpectedly. */
55
+ suspend fun attach(options: DebugAttachOptions): AttachedDebugger = publicCall {
56
+ PublicResults.debug(core.debugAttach(options.json().toString()))
32
57
  }
58
+ /** End diagnostic access after the developer is done or the user withdraws permission. */
59
+ suspend fun detach() { publicCall { core.debugDetach() } }
33
60
  }
34
- suspend fun close() = admission.withLock {
35
- projectIO { try { binding.close() } finally { agents.clear() } }
61
+ /**
62
+ * Honor a user’s request to erase one workspace or all their local Croche data.
63
+ *
64
+ * Local data only. Omitted/empty scope deletes declared stores, registered instances and tool runtime.
65
+ * Agent selects its main and named instances; agent + instance selects one. Core validates all scopes.
66
+ * Other users, the install record and undeclared legacy main stores remain. Recovery accepts only empty scope.
67
+ * The handle stays open. Core owns closure of in-scope agents, locks and retryable partial progress.
68
+ */
69
+ suspend fun deleteData(scope: DeleteDataOptions? = null) {
70
+ publicCall { lifecycle.deleteData(core, scope?.json()?.toString()) }
36
71
  }
72
+ /** Release the user’s session when they sign out or the app switches accounts. */
73
+ suspend fun close() { publicCall { core.shutdown() } }
74
+
75
+ /** Open sessions and inspect or run background delivery through the host. */
37
76
  companion object {
38
- suspend fun open(options: OpenOptions): Croche {
39
- val owned = options.owned()
40
- var created: Croche? = null
41
- return try { projectIO {
42
- val platform = projectPlatform(owned)
43
- val pals = factory(owned, platform)
44
- val pending = mutableListOf<JsonObject>()
45
- val lock = Any()
46
- var binding: ProjectBinding? = null
47
- fun usage(event: JsonElement) = synchronized(lock) {
48
- val value = event.asJsonObject.deepCopy()
49
- val project = binding
50
- if (project == null) pending.add(value)
51
- else notifyUsage(owned, project, value)
77
+ /** Open the app’s user session before letting that user talk to an agent or run a tool. */
78
+ suspend fun open(options: OpenOptions): Croche = opening(options, null)
79
+ /**
80
+ * Give a user a way to erase local data even when the app can no longer open their session.
81
+ *
82
+ * Only deleteData and close work on a recovery handle. Core rejects malformed recovery modes.
83
+ */
84
+ suspend fun open(options: OpenOptions, recovery: RecoveryOptions): Croche = opening(options, recovery)
85
+ private suspend fun opening(options: OpenOptions, recovery: RecoveryOptions?): Croche {
86
+ val selected = adaptersFor(options.adapters)
87
+ return openBound(options, recovery, nativePlatform(options.platform, selected), GeneratedLifecycleBinding)
88
+ }
89
+
90
+ /** Immutable binding seam for transport tests; production always uses the generated native binding. */
91
+ internal suspend fun openBound(options: OpenOptions, recovery: RecoveryOptions?, pals: NativePlatformPals,
92
+ lifecycle: LifecycleBinding): Croche {
93
+ val selected = adaptersFor(options.adapters)
94
+ val json = options.json(); val tools = options.tools?.toList()
95
+ return publicCall(discard = { abandoned: Croche -> abandoned.core.shutdown() }) {
96
+ withToolRegistrations(tools) { registrations ->
97
+ val bound = pals.copy(host = selected.image?.let { ImageAdapterHost(pals.host, it) } ?: pals.host)
98
+ val encoded = CoreOptionsEncoding.encode(json, registrations, bound.storage, selected.state?.let { bound.storage })
99
+ val owner = lifecycle.open(encoded.optionsJson, encoded.registrations, attached(encoded.storage),
100
+ attached(bound.host), BindingFacts.json(), recovery?.json()?.toString())
101
+ Croche(owner, bound, lifecycle)
52
102
  }
53
- try {
54
- val core = CoreProject.open(pals,
55
- ProjectOpenOptions(owned.hostJson(platform.attestor).toString(), owned.user,
56
- owned.config.toString(), owned.handlers.keys.toList(), owned.language,
57
- owned.streaming ?: true, owned.backgroundSync ?: true,
58
- (owned.maintenanceIntervalMs ?: 60_000).toDouble()),
59
- owned.onUsage?.let { EventHook(::usage) },
60
- owned.onDebugEvent?.let { callback -> EventHook { event -> try { callback(event.asJsonObject) } catch (_: Throwable) {} } })
61
- val bound = ProjectBinding(core, pals)
62
- synchronized(lock) { binding = bound; pending.forEach { notifyUsage(owned, bound, it) }; pending.clear() }
63
- Croche(bound).also { created = it; ProjectOpenSeam.opened?.invoke(it) }
64
- } catch (error: Exception) { pals.release(); throw crocheError(error) }
65
- } } catch (cancelled: kotlinx.coroutines.CancellationException) {
66
- // IO's cancellable return must not strand a project the caller never received.
67
- withContext(kotlinx.coroutines.NonCancellable) { created?.close() }
68
- throw cancelled
69
103
  }
70
104
  }
71
- suspend fun deleteStore(options: OpenOptions, agent: String? = null) {
72
- val owned = options.copy(config = options.config.deepCopy(), handlers = emptyMap(),
73
- backgroundSync = false, attestation = Attestation.OFF)
74
- projectIO {
75
- val platform = projectPlatform(owned)
76
- val pals = factory(owned, platform)
77
- try { dev.croche.ffi.deleteStore(pals, owned.hostJson(null).toString(), owned.user, owned.config.toString(), agent) }
78
- finally { pals.release() }
105
+ /** Let a server schedule just the users whose background work is due. */
106
+ suspend fun wakeTimes(options: OpenOptions, query: WakeQuery? = null): WakeTimes {
107
+ val selected = adaptersFor(options.adapters)
108
+ val original = nativePlatform(options.platform, selected)
109
+ val pals = original.copy(host = selected.image?.let { ImageAdapterHost(original.host, it) } ?: original.host)
110
+ val json = options.json(); val tools = options.tools?.toList()
111
+ return publicCall {
112
+ withToolRegistrations(tools) { registrations ->
113
+ val encoded = CoreOptionsEncoding.encode(json, registrations, pals.storage, selected.state?.let { pals.storage })
114
+ PublicResults.wakes(coreWakeTimes(encoded.optionsJson, query?.json()?.toString(), attached(encoded.storage), attached(pals.host)))
115
+ }
79
116
  }
80
117
  }
81
- private fun notifyUsage(options: OpenOptions, binding: ProjectBinding, event: JsonObject) {
82
- try {
83
- ProjectUsageSeam.beforeObserver?.invoke()
84
- event.add("user", options.user?.let(::JsonPrimitive) ?: JsonNull.INSTANCE)
85
- event.add("crocheUserId", binding.usageUserId?.let(::JsonPrimitive) ?: JsonNull.INSTANCE)
86
- options.onUsage?.invoke(event)
87
- } catch (_: Throwable) { /* observers cannot break Core */ }
88
- }
89
- private fun factory(options: OpenOptions, platform: ProjectPlatform): ProjectPals {
90
- val host = options.hostJson(platform.attestor)
91
- val zone = projectTimeZone(options.timeZone)
92
- return ProjectPals { slot ->
93
- val identity = projectPalRoute(slot).identity(host, options.user)
94
- val key = CrocheRuntime.identity(identity).asJsonObject["storageKey"].asString
95
- val safe = key.replace(Regex("[^A-Za-z0-9._-]"), "_")
96
- KotlinHost(FileRuntimeStorage(File(platform.directory, "$safe.json")), platform.secretStorage(safe),
97
- platform.attestor, options.http ?: RuntimeHttpURLConnection(), options.handlers.mapValues { (_, handler) ->
98
- ToolHandler { invocation, context ->
99
- try { handler.execute(invocation, context) }
100
- catch (error: Throwable) {
101
- if (error is CrocheException && error.code == "invalid_tool_result") throw error
102
- throw CrocheException("effect_failed", "The application tool failed")
103
- }
104
- }
105
- },
106
- options.backgroundSync ?: true, projectDirectory = options.projectDirectory,
107
- user = options.user, timeZone = zone)
118
+ /**
119
+ * Let the app keep up with due work when its UI is no longer in the foreground.
120
+ *
121
+ * Android supplies its Context at startup; no SDK enrollment list or wake policy.
122
+ */
123
+ fun registerBackground(context: Any, options: BackgroundOptions? = null) {
124
+ val selected = adaptersFor(options?.adapters)
125
+ val pals = nativePlatform(context, selected)
126
+ val host = selected.image?.let { ImageAdapterHost(pals.host, it) } ?: pals.host
127
+ val listener = options?.sink?.let { backgroundSink(pals.eventDispatcher, it) }
128
+ val encoded = JsonObject().apply {
129
+ listener?.let { add("sink", JsonNull.INSTANCE) }
130
+ selected.state?.let { add("storage", JsonNull.INSTANCE) }
108
131
  }
132
+ publicSync { coreRegisterBackground(encoded.toString(), attached(listener), attached(pals.storage), attached(pals.platformStorage), attached(host), BindingFacts.json()) }
133
+ }
134
+ internal fun truncate(text: String, max: Int): String = publicSync {
135
+ dev.croche.ffi.truncate(text, max.toDouble())
109
136
  }
110
137
  }
111
138
  }
112
-
113
- internal suspend fun <T> projectIO(body: () -> T): T = withContext(Dispatchers.IO) {
114
- try { body() } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } catch (error: Exception) { throw crocheError(error) }
115
- }
116
-
117
- /** Host-only race gate at IO's cancellable return; never set by an app. */
118
- internal object ProjectOpenSeam { @Volatile var opened: ((Croche) -> Unit)? = null }
119
-
120
- internal object ProjectUsageSeam { @Volatile var beforeObserver: (() -> Unit)? = null }
@@ -1,116 +1,102 @@
1
1
  package dev.croche
2
2
 
3
3
  import com.google.gson.*
4
- import dev.croche.ffi.CoreRuntime
5
- import kotlinx.coroutines.*
6
- import java.util.concurrent.atomic.AtomicBoolean
4
+ import dev.croche.ffi.*
5
+ import dev.croche.s7.*
6
+ import kotlinx.coroutines.CoroutineDispatcher
7
7
 
8
- /** One project agent; the existing Runtime owns its production PAL and subscription kernel. */
9
- class CrocheAgent private constructor(private val core: CoreRuntime, private val runtime: CrocheRuntime) {
10
- private val lifecycle = kotlinx.coroutines.sync.Mutex()
11
- private val retired = AtomicBoolean()
12
- private val callbacks = CoroutineScope(SupervisorJob() + Dispatchers.Default)
13
- val id: String = core.agentId()
14
- val instance: String? = core.instance()
15
- val created: Boolean = core.created()
16
- val logId: String = core.logId()
17
- @Volatile private var lastName = core.name()
18
- @Volatile private var lastMode = core.mode()
19
- @Volatile private var lastVisible = core.visibleTools()
20
- val closed: Boolean get() = retired.get() || runtime.isClosed
21
- val name: String? get() = if (closed) lastName else native { core.name() }.also { lastName = it }
22
- val mode: String? get() = if (closed) lastMode else native { core.mode() }.also { lastMode = it }
23
- val visibleTools: List<String>? get() = if (closed) lastVisible?.toList() else native { core.visibleTools() }.also { lastVisible = it }
24
- private fun requireOpen() { if (closed) throw CrocheException("closed", "The agent is closed") }
25
- private fun <T> native(body: () -> T): T {
26
- requireOpen()
27
- return try { body() } catch (error: Exception) { throw crocheError(error) }
8
+ /** All identity, accepted work and scope live in Core. Every operation calls that same handle. */
9
+ class CrocheAgent internal constructor(core: CoreAgentInterface, private val dispatcher: CoroutineDispatcher) {
10
+ internal val core = NativeHandleOwner.wrap(CoreAgentInterface::class.java, core)
11
+ /** Load an attachment when someone opens it from this conversation. */
12
+ suspend fun attachment(id: String): AttachmentData = publicCall { PublicResults.attachmentData(core.attachment(id)) }
13
+ /** Let a user remove a file they no longer want kept with this conversation. */
14
+ suspend fun deleteAttachment(id: String) { publicCall { core.deleteAttachment(id) } }
15
+ /** Show the files a user can revisit from this conversation. */
16
+ suspend fun listAttachments(options: ListOptions? = null): Page<AppStreamContract.Attachment> =
17
+ publicCall { PublicResults.attachments(core.listAttachments(options?.json())) }
18
+ /** Bring a file from another conversation into this one before sharing it here. */
19
+ suspend fun copyAttachment(source: AttachmentSource): AppStreamContract.Attachment = publicCall { PublicResults.attachment(core.copyAttachment(source.json().toString())) }
20
+ /** Let the app drop its hold on a file when the user removes it from a draft. */
21
+ suspend fun releaseAttachment(id: String) { publicCall { core.releaseAttachment(id) } }
22
+ /** Let an app associate a reply with the configured agent that produced it. */
23
+ val id: String get() = publicSync { core.id() }
24
+ /** Let an app distinguish two conversations that use the same agent definition. */
25
+ val instance: String? get() = publicSync { core.instance() }
26
+ /** Accept input from chat without making the UI wait for the reply. */
27
+ suspend fun send(text: String, options: SendOptions? = null): SendReceipt = sendJson(JsonPrimitive(text).toString(), emptyList(), options)
28
+ /** Accept input from chat without making the UI wait for the reply. */
29
+ suspend fun send(input: SendInput, options: SendOptions? = null): SendReceipt =
30
+ sendJson(input.encoded().toString(), input.imageCaptures().map { CoreAttachmentInput(it.first.toUInt(), it.second) }, options)
31
+ private suspend fun sendJson(input: String, images: List<CoreAttachmentInput>, options: SendOptions?): SendReceipt = publicCall { token ->
32
+ AppStreamContract.decodeSendReceipt(JsonParser.parseString(core.send(input, images, sendOptions(options), token)).asJsonObject)
28
33
  }
29
- suspend fun setTools(visible: List<String>?) {
30
- val owned = visible?.toList()
31
- projectIO { native { core.setTools(owned) }; lastVisible = core.visibleTools() }
34
+ /** Wait for an outcome when an app workflow needs to decide what happens next. */
35
+ suspend fun request(text: String, options: RequestOptions? = null): RequestResult = requestJson(JsonPrimitive(text).toString(), emptyList(), options)
36
+ /** Wait for an outcome when an app workflow needs to decide what happens next. */
37
+ suspend fun request(input: SendInput, options: RequestOptions? = null): RequestResult =
38
+ requestJson(input.encoded().toString(), input.imageCaptures().map { CoreAttachmentInput(it.first.toUInt(), it.second) }, options)
39
+ private suspend fun requestJson(input: String, images: List<CoreAttachmentInput>, options: RequestOptions?): RequestResult = publicCall { token ->
40
+ AppStreamContract.decodeRequestResult(JsonParser.parseString(core.request(input, images, options?.json()?.toString(), token)).asJsonObject)
32
41
  }
33
- suspend fun setMode(mode: String?) { projectIO { native { core.setMode(mode) }; lastMode = core.mode() } }
34
- suspend fun sync() { projectIO { native { core.sync() } } }
35
- suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt {
36
- requireOpen(); return runtime.send(input, options)
42
+ /**
43
+ * Classify app data for a workflow, such as routing a support ticket without starting a chat.
44
+ *
45
+ * Coroutine cancellation fires Core's token; Core owns the paid call.
46
+ */
47
+ suspend fun decide(input: DecideInput): DecisionResult = publicCall { token ->
48
+ DecisionResult.read(core.decide(input.json().toString(), null, token))
37
49
  }
38
- suspend fun request(input: SendInput, options: RequestOptions = RequestOptions()): RequestResult {
39
- requireOpen()
40
- return runtime.request(input, SendOptions(options.responseFormat), options.wait).also { memory.refreshQuietly() }
41
- }
42
- fun subscribe(options: SubscribeOptions): AgentSubscription {
43
- // Opening synchronously preserves replacement order and an immediate history call's generation.
44
- val collection = runtime.openSubscription(options.initialMessages ?: if (options.after == null) 50 else null, options.after)
45
- return AgentSubscription(collection, options.onEvent, callbacks)
46
- }
47
- suspend fun history(options: HistoryOptions) { requireOpen(); runtime.history(options.before, options.limit) }
48
- suspend fun clearHistory() { requireOpen(); runtime.clearHistory(); memory.refreshQuietly() }
49
- suspend fun cancel(id: String? = null) {
50
- requireOpen()
51
- if (id != null) runtime.cancel(id) else projectIO { native { core.cancelTurn() } }
52
- }
53
- suspend fun close() {
54
- lifecycle.lock()
55
- try {
56
- if (!retired.compareAndSet(false, true)) return
57
- projectIO { runtime.close() }
58
- } finally { lifecycle.unlock() }
50
+ /** Keep a chat screen in step with the agent as messages and tool activity arrive. */
51
+ fun subscribe(options: SubscribeOptions): AgentSubscription = publicSync {
52
+ AgentSubscription(core.subscribe(options.json().toString(), attached(appEventSink(dispatcher, options.onEvent))))
59
53
  }
54
+ /** Let the user stop a reply or withdraw input they no longer want processed. */
55
+ suspend fun cancel(id: String? = null) { publicCall { core.cancel(id) } }
56
+ /** Let a user clear the conversation they see while keeping the agent available. */
57
+ /** Clears the whole conversation. */
58
+ suspend fun clearHistory() { publicCall { core.clearHistory(null) } }
59
+ /** Limit an agent to the actions appropriate for the user’s current workflow. */
60
+ suspend fun setTools(scope: ToolSelection) { publicCall { core.setTools(scope.json().toString()) } }
61
+ /** Restore the usual actions after the user leaves a restricted workflow. */
62
+ suspend fun resetTools() { publicCall { core.resetTools() } }
63
+ /** Give an agent help material relevant to the screen or workspace the user is in. */
64
+ suspend fun setWiki(scope: WikiSelection) { publicCall { core.setWiki(scope.json().toString()) } }
65
+ /** Restore the usual help material after the user leaves a specialized workspace. */
66
+ suspend fun resetWiki() { publicCall { core.resetWiki() } }
67
+ /** Release an agent when the app leaves its conversation and no longer needs the handle. */
68
+ suspend fun close() { publicCall { core.shutdown() } }
69
+ /** Access controls for this conversation's memory. */
60
70
  val memory = Memory()
61
- inner class Memory {
62
- @Volatile private var snapshot = runtime.memory().asJsonObject.deepCopy()
63
- operator fun invoke(): JsonObject = snapshot.deepCopy()
64
- private suspend fun <T> operation(body: () -> T): T {
65
- requireOpen()
66
- return projectIO { body() }.also { result ->
67
- val deferred = result === WriteResult.Deferred ||
68
- (result is JsonObject && result.at("deferred").let { it.isJsonPrimitive && it.asBoolean })
69
- if (!deferred) refreshQuietly()
70
- }
71
- }
72
- internal suspend fun refreshQuietly() {
73
- if (closed) return
74
- try { snapshot = projectIO { runtime.memory().asJsonObject.deepCopy() } } catch (_: CrocheException) {}
75
- }
76
- suspend fun list(): JsonArray = operation { runtime.memory.list() }
77
- suspend fun delete(id: String): JsonObject = operation { runtime.memory.delete(id) }
78
- suspend fun clear(): JsonObject = operation { runtime.memory.clear() }
79
- suspend fun enabled(on: Boolean): WriteResult<Boolean> = operation { runtime.memory.enabled(on) }
80
- suspend fun export(): JsonObject = operation { runtime.memory.export() }
81
- fun onChanged(listener: ((MemoryChangedEvent) -> Unit)?) {
82
- requireOpen()
83
- try { runtime.memory.onChanged(listener?.let { callback -> { value -> try { callback(value.asJsonObject) } catch (_: Throwable) {} } }) }
84
- catch (error: Exception) { throw crocheError(error) }
85
- }
71
+ /** Read or change stored memory for this conversation. */
72
+ inner class Memory internal constructor() {
73
+ /** Show the user what the agent remembers so they can review it. */
74
+ suspend fun list(options: ListOptions? = null): Page<MemoryItem> = publicCall { PublicResults.memories(core.memoryList(options?.json())) }
75
+ /** Let the user remove one remembered fact without clearing the rest. */
76
+ suspend fun delete(id: String) { publicCall { core.memoryDelete(id) } }
77
+ /** Let the user start over with a clean memory while keeping their conversation. */
78
+ suspend fun clear() { publicCall { core.memoryClear() } }
79
+ /** Let the user choose whether the agent uses memory in this conversation. */
80
+ suspend fun enabled(on: Boolean) { publicCall { core.memoryEnabled(on) } }
81
+ }
82
+ private fun sendOptions(options: SendOptions?): String? = options?.let {
83
+ JsonObject().apply { it.responseFormat?.let { add("responseFormat", it.deepCopy()) } }.toString()
86
84
  }
87
- internal companion object { fun adopt(core: CoreRuntime, runtime: CrocheRuntime) = CrocheAgent(core, runtime) }
88
85
  }
86
+ /** `send`'s answer: Core has ACCEPTED the input. `error` is set when the input already failed. */
87
+ typealias SendReceipt = AppStreamContract.SendReceipt
88
+ /** `request`'s answer: the input is final. `gap` is true when Core says so, null when absent. */
89
+ typealias RequestResult = AppStreamContract.RequestResult
90
+ /** `{code, category, message}` on a failed receipt, result, input or message. */
91
+ typealias EventError = AppStreamContract.EventError
89
92
 
90
- /** A generation-pinned subscription; closing it leaves canonical request observation alive. */
91
- class AgentSubscription internal constructor(
92
- private val collection: StreamHub.Collection,
93
- private val onEvent: suspend (RuntimeEvent) -> Unit,
94
- scope: CoroutineScope,
95
- ) {
96
- private val completion = CompletableDeferred<AppStreamEnd>()
97
- val ended: Deferred<AppStreamEnd> get() = completion
98
- init {
99
- scope.launch {
100
- var code = "closed"
101
- try {
102
- collection.deliver { event ->
103
- if (event is RuntimeEvent.StreamError) code = event.code
104
- if (event === RuntimeEvent.Replaced) code = "replaced"
105
- onEvent(event)
106
- }
107
- } catch (failure: Throwable) {
108
- code = "handler_failed"
109
- collection.close()
110
- try { onEvent(RuntimeEvent.StreamError(code, "Event handler failed", false)) } catch (_: Throwable) {}
111
- } finally { completion.complete(AppStreamEnd(code)) }
112
- }
113
- }
114
- fun close() = collection.close()
115
- suspend fun history(options: HistoryOptions) = collection.history(options.before, options.limit)
93
+ /** Live agent subscription used to receive updates and request older transcript pages. */
94
+ class AgentSubscription internal constructor(core: CoreSubscriptionInterface) {
95
+ private val core = NativeHandleOwner.wrap(CoreSubscriptionInterface::class.java, core)
96
+ /** Load older messages into the same chat view when the user scrolls back. */
97
+ suspend fun history(options: HistoryOptions) { publicCall { core.history(options.json().toString()) } }
98
+ /** Stop routing updates to a chat view that has been dismissed. */
99
+ fun close() = publicSync { core.shutdown() }
100
+ /** Whether Core has ended this subscription. */
101
+ val ended: Boolean get() = publicSync { core.ended() }
116
102
  }