@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,59 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import java.time.Instant
5
+
6
+ // Pure legacy-event reader retained for its existing stream kernel and reader witnesses.
7
+ internal fun publicSequence(value: ULong): Long {
8
+ if (value > Long.MAX_VALUE.toULong()) throw CrocheError("invalid_input", "Core sequence exceeds Long.MAX_VALUE")
9
+ return value.toLong()
10
+ }
11
+ internal fun coreSequence(value: Long): ULong {
12
+ if (value < 0) throw CrocheError("invalid_input", "Sequence must not be negative")
13
+ return value.toULong()
14
+ }
15
+ private fun JsonElement.sequence(): Long {
16
+ val value = asString.toULongOrNull() ?: throw CrocheError("invalid_input", "Core sequence is not an unsigned integer")
17
+ return publicSequence(value)
18
+ }
19
+ private fun JsonObject.number(name: String) = get(name).sequence()
20
+ private fun JsonObject.optionalLong(name: String) = get(name)?.takeUnless { it.isJsonNull }?.sequence()
21
+ private fun JsonObject.flag(name: String) = get(name)?.takeUnless { it.isJsonNull }?.asBoolean ?: false
22
+ private fun JsonObject.list(name: String): List<JsonElement> = get(name)?.takeIf { it.isJsonArray }?.asJsonArray?.toList() ?: emptyList()
23
+ private fun JsonObject.strings(name: String) = list(name).map { it.asString }
24
+ private fun JsonObject.error() = get("error")?.takeIf { it.isJsonObject }?.asJsonObject?.let { RuntimeError(it.at("code").text(), it.at("message").text()) }
25
+
26
+ /** Decode the Core's tagged JSON; omission stays omission, unknown reader values keep their exact strings. */
27
+ internal fun nativeEvent(value: JsonObject): RuntimeEvent {
28
+ fun at() = Instant.parse(value.at("at").text())
29
+ fun state(v: JsonObject) = RuntimeEvent.State(AgentStatus(v.at("status").text()), v.number("queued").toInt(), v.flag("typing"),
30
+ v.get("activity")?.takeUnless { it.isJsonNull }?.let { AgentActivity(it.text()) },
31
+ v.get("tools")?.takeIf { it.isJsonArray }?.asJsonArray?.map { it.asString })
32
+ return when (val type = value.at("type").text()) {
33
+ "input" -> RuntimeEvent.Input(value.number("seq"), value.number("firstSeq"), value.at("id").text(), InputKind(value.at("kind").text()),
34
+ value.get("text")?.takeUnless { it.isJsonNull }?.asString, value.list("images").map { image -> image.asJsonObject.let {
35
+ ImageSummary(it.get("alt")?.asString, it.get("mime")?.asString, it.optionalLong("bytes"))
36
+ } }, InputStatus(value.at("status").text()), value.error(), at())
37
+ "message.start" -> RuntimeEvent.MessageStart(value.number("seq"), value.number("firstSeq"), value.at("id").text(), at())
38
+ "message.delta" -> RuntimeEvent.MessageDelta(value.at("id").text(), value.at("text").text())
39
+ "message.end" -> RuntimeEvent.MessageEnd(value.number("seq"), value.number("firstSeq"), value.at("id").text(), MessageStatus(value.at("status").text()),
40
+ value.at("text").text(), value.strings("markers"), value.get("output")?.takeUnless { it.isJsonNull }?.deepCopy(),
41
+ value.strings("inReplyTo"), value.strings("causedBy"), value.error(), at())
42
+ "state" -> state(value)
43
+ "snapshot" -> RuntimeEvent.Snapshot(value.at("logId").text(), state(value.getAsJsonObject("state")), value.get("streaming")?.takeIf { it.isJsonObject }?.asJsonObject?.let {
44
+ Streaming(it.at("messageId").text(), it.number("firstSeq"), it.at("text").text())
45
+ })
46
+ "page" -> RuntimeEvent.Page(value.list("messages").map { nativeEvent(it.asJsonObject) }, value.flag("reachedFloor"), value.at("logId").text(), value.number("clearedSeq"))
47
+ "gap" -> RuntimeEvent.Gap(value.number("afterSeq"), value.number("throughSeq"), GapReason(value.at("reason").text()))
48
+ "cleared" -> RuntimeEvent.Cleared(value.number("seq"), value.at("id").text(), at())
49
+ "turn" -> RuntimeEvent.Turn(value.number("seq"), value.at("id").text(), value.strings("causedBy"), value.strings("inputs"), value.at("purpose").text(),
50
+ value.get("usage")?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet()?.associate { it.key to it.value.asLong } ?: emptyMap(),
51
+ value.get("costUsd")?.asDouble ?: 0.0, CostStatus(value.at("costStatus").text()), value.at("model").text(), value.optionalLong("imagesOmitted")?.toInt(), at())
52
+ "app" -> value.getAsJsonObject("source").let { RuntimeEvent.App(value.number("seq"), value.at("id").text(), value.at("name").text(), value.get("data").deepCopy(),
53
+ ToolSource(it.at("command").text(), it.at("callId").text()), at()) }
54
+ "error" -> if (value.has("seq")) RuntimeEvent.Error(value.number("seq"), value.at("id").text(), value.at("code").text(), value.at("message").text(), value.strings("inputs"), at())
55
+ else RuntimeEvent.StreamError(value.at("code").text(), value.at("message").text(), value.flag("poisoned"))
56
+ "replaced" -> RuntimeEvent.Replaced
57
+ else -> RuntimeEvent.Unknown(type, value.deepCopy())
58
+ }
59
+ }
@@ -0,0 +1,118 @@
1
+ package dev.croche
2
+
3
+ import dev.croche.ffi.*
4
+ import java.lang.ref.WeakReference
5
+ import java.lang.reflect.InvocationTargetException
6
+ import java.lang.reflect.Method
7
+ import java.lang.reflect.Proxy
8
+
9
+ /** Pointer ownership only. UniFFI's call counter keeps already-entered foreign calls alive during destroy. */
10
+ internal object NativeHandleOwner {
11
+ private class Key(value: Any) : WeakReference<Any>(value) {
12
+ private val hash = System.identityHashCode(value)
13
+ override fun hashCode() = hash
14
+ override fun equals(other: Any?): Boolean {
15
+ if (this === other) return true
16
+ val value = get() ?: return false
17
+ return other is Key && value === other.get()
18
+ }
19
+ }
20
+ private val scopes = mutableMapOf<Key, WeakReference<Scope>>()
21
+ private fun scope(raw: Any): Scope = synchronized(scopes) {
22
+ scopes.entries.removeAll { it.key.get() == null || it.value.get() == null }
23
+ val key = Key(raw)
24
+ scopes[key]?.get() ?: Scope(raw).also { scopes[key] = WeakReference(it) }
25
+ }
26
+ fun <T : Any> wrap(type: Class<T>, raw: T): T {
27
+ val owner = scope(raw)
28
+ return type.cast(Proxy.newProxyInstance(type.classLoader, arrayOf(type)) { proxy, method, args ->
29
+ when (method.name) {
30
+ "equals" -> proxy === args?.firstOrNull()
31
+ "hashCode" -> System.identityHashCode(proxy)
32
+ "toString" -> "Core owner"
33
+ "shutdown" -> owner.shutdown(method)
34
+ else -> owner.invoke(method, args ?: emptyArray())
35
+ }
36
+ })
37
+ }
38
+ private fun closed() = CrocheError("closed", "This handle is closed.", ErrorCategory.CLOSED)
39
+ private class Scope(private var raw: Any?) {
40
+ private val lock = Object()
41
+ private val children = mutableSetOf<Scope>()
42
+ private val snapshot = mutableMapOf<String, Any?>()
43
+ private var closing = false
44
+ private var disposed = when (val value = raw) {
45
+ is CoreAgent -> value.uniffiIsDestroyed
46
+ is CoreCroche -> value.uniffiIsDestroyed
47
+ is CoreSubscription -> value.uniffiIsDestroyed
48
+ else -> false
49
+ }
50
+ init { if (disposed) raw = null }
51
+ private fun capture(value: Any) {
52
+ if (value !is CoreAgentInterface) return
53
+ for (key in listOf("id", "instance")) try {
54
+ snapshot[key] = CoreAgentInterface::class.java.getMethod(key).invoke(value)
55
+ } catch (_: Exception) { /* recovery */ }
56
+ }
57
+ fun invoke(method: Method, args: Array<out Any?>): Any? {
58
+ val value = synchronized(lock) {
59
+ if (disposed || closing) {
60
+ if (method.name == "ended") return true
61
+ if (snapshot.containsKey(method.name)) return snapshot[method.name]
62
+ throw closed()
63
+ }
64
+ raw ?: throw closed()
65
+ }
66
+ return try {
67
+ val result = method.invoke(value, *args)
68
+ if (result is CoreAgent || result is CoreSubscription) {
69
+ val child = scope(result)
70
+ synchronized(lock) { if (disposed) child.release() else children.add(child) }
71
+ }
72
+ result
73
+ } catch (error: InvocationTargetException) {
74
+ val cause = error.targetException
75
+ if (cause is IllegalStateException && synchronized(lock) { disposed || closing }) throw closed()
76
+ throw cause
77
+ }
78
+ }
79
+ fun shutdown(method: Method) {
80
+ val value = synchronized(lock) {
81
+ while (closing) lock.wait()
82
+ if (disposed) return
83
+ val value = raw ?: return
84
+ capture(value); closing = true; value
85
+ }
86
+ var succeeded = false
87
+ try { method.invoke(value); succeeded = true }
88
+ catch (error: InvocationTargetException) { throw error.targetException }
89
+ finally {
90
+ val disposal = synchronized(lock) {
91
+ closing = false
92
+ val disposal = if (succeeded) take() else null
93
+ lock.notifyAll(); disposal
94
+ }
95
+ disposal?.let { destroy(it) }
96
+ }
97
+ }
98
+ private fun take(): Pair<Any, List<Scope>>? {
99
+ if (disposed) return null
100
+ val value = raw ?: return null
101
+ capture(value); disposed = true; raw = null
102
+ val nested = children.toList(); children.clear()
103
+ return value to nested
104
+ }
105
+ private fun destroy(disposal: Pair<Any, List<Scope>>) {
106
+ disposal.second.forEach { it.release() }
107
+ (disposal.first as? Disposable)?.destroy()
108
+ }
109
+ fun release() {
110
+ val disposal = synchronized(lock) {
111
+ // An already-running shutdown owns its final drop; never free it early.
112
+ if (closing) return
113
+ take()
114
+ }
115
+ disposal?.let { destroy(it) }
116
+ }
117
+ }
118
+ }
@@ -1,28 +1,29 @@
1
1
  package dev.croche
2
2
 
3
- import com.google.gson.*
4
- import java.io.File
5
- import java.io.FileOutputStream
6
- import java.nio.file.Files
7
- import java.nio.file.StandardCopyOption.*
8
- import java.nio.file.attribute.PosixFilePermissions
3
+ import com.google.gson.JsonObject
9
4
 
10
5
  // Platform Abstraction Layer. The Rust Core decides; these perform what only the platform
11
6
  // can: keep a credential in hardware-backed storage, and vouch for the app binary.
12
- // See docs/MOBILE-SDK-AND-PAL.md. Android implementations live in the android module.
7
+ // See docs/hld/surface-and-hosts.md. Android implementations live in the android module.
13
8
 
14
9
  /** Where the Runtime credential lives, apart from the general state file. load returns an
15
10
  * object (empty when nothing is stored); save replaces the whole object atomically. */
16
- interface RuntimeSecretStore {
11
+ internal interface RuntimeSecretStore {
17
12
  fun load(): JsonObject
18
13
  fun save(secrets: JsonObject)
19
14
  /** Delete the credential item for real; an absent item is already removed. */
20
15
  fun remove()
21
16
  }
22
17
 
23
- /** The platform's attestation of this app binary, bound to the client data hash. */
18
+ /**
19
+ * The platform's attestation of this app binary, bound to the client data hash.
20
+ *
21
+ * @property keyId Attestation key identifier, when supplied by the platform.
22
+ * @property token Proof token returned by the platform.
23
+ */
24
24
  data class RuntimeAttestation(val token: String, val keyId: String? = null)
25
25
 
26
+ /** Host provider of a device or app attestation for runtime registration. */
26
27
  interface RuntimeAttestor {
27
28
  /** "android-play-integrity" or "ios-app-attest"; declared to the Core in config. */
28
29
  val platform: String
@@ -31,71 +32,6 @@ interface RuntimeAttestor {
31
32
  fun attest(clientData: String, clientDataHash: String, cancellation: RuntimeCancellation): RuntimeAttestation
32
33
  }
33
34
 
34
- /**
35
- * The OS's deferred work for the agent's scheduled notes while the app is not running (founder
36
- * 17:14Z): WorkManager on Android (`dev.croche.android.WorkManagerScheduler`). The Runtime calls
37
- * it with the earliest pending note after every change, at every open, and after every
38
- * `deliverDue()`. The work it registers runs `deliverDue()`: inexact, never before that time. No
39
- * exact alarms, notifications or permissions.
40
- */
41
- interface RuntimeScheduler {
42
- /** Replaces any earlier request with one at or after `earliestAtMs` (epoch ms). Idempotent:
43
- * one request at a time, by a unique name. Throw `CrocheException("not_configured", ...)` when
44
- * the app is not set up for it: the Runtime reports `schedule.degraded` with that code and
45
- * still delivers while running and at the next open. */
46
- fun schedule(earliestAtMs: Long)
47
- /** Nothing is pending: withdraw the request. */
48
- fun cancel()
49
- /** A Runtime is opening with this scheduler. Throw `CrocheException("scheduler_conflict",
50
- * ...)` to refuse it when its request name is already another open Runtime's: that name's
51
- * runs could deliver through only one of them, including when the same scheduler object is
52
- * given to a second Runtime. */
53
- fun attach() {}
54
- /** That Runtime closed (or failed to open): the name is free again. The Runtime calls this at
55
- * most once per successful `attach`, however often it is closed. */
56
- fun detach() {}
57
- }
58
-
59
- /** A private file beside the state file. For hosts without a secret store (JVM servers,
60
- * tests). On Android, use KeystoreSecretStore from the android module. */
61
- class FileRuntimeSecretStore(private val file: File) : RuntimeSecretStore {
62
- @Synchronized override fun load(): JsonObject {
63
- if (!file.exists()) return JsonObject()
64
- val saved = try { JsonParser.parseString(file.readText(Charsets.UTF_8)) }
65
- catch (_: Exception) { throw CrocheException("corrupt_store", "Runtime credentials are unreadable; remove them to register again") }
66
- if (!saved.isJsonObject) throw CrocheException("corrupt_store", "Runtime credentials must be an object")
67
- return saved.asJsonObject
68
- }
69
- @Synchronized override fun remove() { Files.deleteIfExists(file.toPath()) }
70
- @Synchronized override fun save(secrets: JsonObject) {
71
- file.absoluteFile.parentFile.mkdirs()
72
- val temporary = File.createTempFile("croche-secrets-", ".tmp", file.absoluteFile.parentFile)
73
- try {
74
- try { Files.setPosixFilePermissions(temporary.toPath(), PosixFilePermissions.fromString("rw-------")) }
75
- catch (_: UnsupportedOperationException) {}
76
- FileOutputStream(temporary).use { output -> output.write(secrets.toString().toByteArray(Charsets.UTF_8)); output.fd.sync() }
77
- Files.move(temporary.toPath(), file.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
78
- } finally { temporary.delete() }
79
- }
80
- }
81
-
82
- /** One open Runtime per OS identity (a WorkManager name): the rule the OS schedulers share, kept
83
- * in one place so the tests' schedulers run the same code as `WorkManagerScheduler` (Atlas, #323
84
- * P1-2 and the NO at dc38bf0). `claim` is refused while the identity is held by anyone, the
85
- * claiming object included: `create` claims once per Runtime, so one object given to two
86
- * Runtimes is refused the second time. `release` frees it only for its holder. */
87
- internal class SchedulerClaims(private val what: String) {
88
- private val holders = HashMap<String, Any>()
89
- @Synchronized fun claim(identity: String, by: Any) {
90
- if (holders[identity] != null) {
91
- throw CrocheException("scheduler_conflict", "Another open Runtime uses the $what \"$identity\"; give each Runtime its own, or close it first")
92
- }
93
- holders[identity] = by
94
- }
95
- @Synchronized fun release(identity: String, by: Any) { if (holders[identity] === by) holders.remove(identity) }
96
- @Synchronized fun held(identity: String) = holders[identity] != null
97
- }
98
-
99
35
  /** Marks the React Native bridge's internal hooks: not part of the SDK's public API, not frozen,
100
36
  * and replaced without notice. Interim until the public subscription for agent-initiated
101
37
  * messages (F25 on #264) lands. */
@@ -1,46 +1,303 @@
1
1
  package dev.croche
2
2
 
3
- import com.google.gson.JsonObject
4
- import java.io.File
3
+ import com.google.gson.*
5
4
 
5
+ /** App and host configuration for opening a Croche session. */
6
6
  data class OpenOptions(
7
- val cloudUrl: String? = null,
7
+ /** Public project key identifying the Croche project. */
8
8
  val projectKey: String,
9
- /** App config temperature: number 0..2; absent uses a tuned default; JsonNull = omit.
10
- * Structured calls always omit it; remote configs require schema 4 / 0.5.3+. */
11
- val config: JsonObject,
9
+ /** Bundled project and agent configuration supplied to Core. */
10
+ val bundledConfig: JsonElement,
11
+ /** Optional user ID for the session. Core validates it for the selected access path. */
12
12
  val user: String? = null,
13
- val handlers: Map<String, ToolHandler> = emptyMap(),
13
+ /** Optional language preference supplied to Core. */
14
14
  val language: String? = null,
15
- val timeZone: String? = null,
16
- val streaming: Boolean? = null,
17
- val backgroundSync: Boolean? = null,
18
- val maintenanceIntervalMs: Long? = null,
19
- val debugKey: String? = null,
20
- val requestTimeoutMs: Long? = null,
21
- val maxPendingEvents: Int? = null,
22
- val syncIntervalMs: Long? = null,
23
- val maintenanceBackoffMs: Long? = null,
15
+ /** Tool definitions registered by the app. */
16
+ val tools: List<ToolRegistration>? = null,
17
+ /** Wiki documents supplied with this session. */
18
+ val wiki: List<WikiDoc>? = null,
19
+ /** Host adapters to supply for this session. */
20
+ val adapters: List<Adapter>? = null,
21
+ /** Android Context; opaque to the common wrapper, never serialized as an object. */
22
+ val platform: Any? = null,
23
+ /** Optional credential for a trusted server host. */
24
+ val serverKey: String? = null,
25
+ /** Optional development key, used while developing the app. */
26
+ val developmentKey: String? = null,
27
+ /** Optional per-instance archive budgets. */
28
+ val archive: ArchiveOptions? = null,
29
+ /**
30
+ * The byte budget of each instance's live stream log, the screen record used for replay.
31
+ * Every storage size has a default and an app setting (founder 2026-11-19): null = omitted,
32
+ * and Core uses its default of 4 MiB. Core validates the value (2 MiB to 1 GiB); this SDK
33
+ * passes it through unchanged.
34
+ */
24
35
  val retentionBytes: Long? = null,
25
- val onUsage: ((ProjectUsageEvent) -> Unit)? = null,
26
- val onDebugEvent: ((RuntimeDebugEvent) -> Unit)? = null,
27
- val debugVisibility: DebugVisibility? = null,
28
- val attestation: Attestation? = null,
29
- val android: AndroidOptions? = null,
30
- val projectDirectory: File? = null,
31
- val http: RuntimeHTTP? = null,
32
- )
33
- enum class DebugVisibility { RUNTIME }
34
- enum class Attestation { PLATFORM, OFF }
35
- data class AndroidOptions(val cloudProjectNumber: Long? = null)
36
- typealias ProjectUsageEvent = JsonObject
37
- typealias RuntimeDebugEvent = JsonObject
38
- typealias MemoryChangedEvent = JsonObject
39
- typealias ProjectToolContext = ToolContext
40
-
41
- data class AgentOptions(val instance: String? = null, val fresh: Boolean? = null, val config: JsonObject? = null)
42
- data class RequestOptions(val responseFormat: JsonObject? = null, val wait: RequestWait? = null)
36
+ /** Total named-instance budget for this user, also used as the per-instance budget for finished turns waiting to seal. */
37
+ val instanceMaxBytes: Long? = null,
38
+ /**
39
+ * The app wiki's limits (founder 2026-11-19, B27): the largest document in markdown bytes
40
+ * (default 64 KiB; a larger one is refused, so split it) and the wiki's total (default
41
+ * 8 MiB). null = omitted; Core validates and applies the defaults.
42
+ */
43
+ val wikiDocumentMaxBytes: Long? = null,
44
+ /** Total byte budget for the app wiki. Null uses the Core default of 8 MiB. */
45
+ val wikiMaxBytes: Long? = null,
46
+ /** App-wide input and scheduling guards for every agent (B27). Code-owned: a bundle cannot set them. */
47
+ val limits: LimitsOptions? = null,
48
+ ) {
49
+ /** Return the type label without printing configuration or credentials. */
50
+ override fun toString(): String = "OpenOptions"
51
+
52
+ internal fun json() = JsonObject().apply {
53
+ addProperty("projectKey", projectKey); add("bundledConfig", bundledConfig.deepCopy())
54
+ user?.let { addProperty("user", it) }; language?.let { addProperty("language", it) }
55
+ serverKey?.let { addProperty("serverKey", it) }; developmentKey?.let { addProperty("developmentKey", it) }
56
+ archive?.let { add("archive", it.json()) }
57
+ retentionBytes?.let { addProperty("retentionBytes", it) }
58
+ instanceMaxBytes?.let { addProperty("instanceMaxBytes", it) }
59
+ wikiDocumentMaxBytes?.let { addProperty("wikiDocumentMaxBytes", it) }
60
+ wikiMaxBytes?.let { addProperty("wikiMaxBytes", it) }
61
+ limits?.let { add("limits", it.json()) }
62
+ adapters?.let { add("adapters", it.markers()) }
63
+ wiki?.let { docs -> add("wiki", JsonArray().apply { docs.forEach { add(it.json()) } }) }
64
+ platform?.let { add("platform", JsonNull.INSTANCE) }
65
+ }
66
+ }
67
+
68
+ /** `OpenOptions.limits`: each null field is omitted and Core applies its default. */
69
+ data class LimitsOptions(
70
+ /** Total user and app-event text of one send, 1,000..200,000 UTF-16 units (default 32,000). */
71
+ val userTextChars: Long? = null,
72
+ /** Total app-state text of one send, 1,000..200,000 (default 32,000). */
73
+ val appStateChars: Long? = null,
74
+ /** One tool result's value as compact JSON, 1,000..1,000,000 (default 200,000). */
75
+ val toolResultChars: Long? = null,
76
+ /** Images per message or tool result, 1..16 (default 4). Image byte limits stay fixed. */
77
+ val turnImages: Long? = null,
78
+ /** Schedule notes pending at once, 1..20 (default 20). */
79
+ val pendingSchedules: Long? = null,
80
+ ) {
81
+ internal fun json() = JsonObject().apply {
82
+ userTextChars?.let { addProperty("userTextChars", it) }
83
+ appStateChars?.let { addProperty("appStateChars", it) }
84
+ toolResultChars?.let { addProperty("toolResultChars", it) }
85
+ turnImages?.let { addProperty("turnImages", it) }
86
+ pendingSchedules?.let { addProperty("pendingSchedules", it) }
87
+ }
88
+ }
89
+
90
+ /**
91
+ * A patch is sent on every open; Core decides identity, conflicts and the effective config.
92
+ *
93
+ * @property config Optional instance-specific patch passed to Core on open.
94
+ * @property id Name of the conversation within the agent.
95
+ */
96
+ data class Instance(val id: String, val config: JsonElement? = null) {
97
+ internal fun json() = JsonObject().apply { addProperty("id", id); config?.let { add("config", it.deepCopy()) } }
98
+ }
99
+ /**
100
+ * Options for opening a conversation from an agent definition.
101
+ *
102
+ * @property instance Named conversation and its optional configuration patch.
103
+ * @property tools Tool scope for this agent handle.
104
+ * @property wiki Wiki scope for this agent handle.
105
+ */
106
+ data class AgentOptions(val instance: Instance? = null, val tools: ToolSelection? = null, val wiki: WikiSelection? = null) {
107
+ internal fun json() = JsonObject().apply {
108
+ instance?.let { add("instance", it.json()) }; tools?.let { add("tools", it.json()) }; wiki?.let { add("wiki", it.json()) }
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Scoped configuration for one tool available to an agent.
114
+ *
115
+ * @property bind Optional bindings supplied for this scoped tool.
116
+ * @property commands Optional selection of command keys the agent can use.
117
+ * @property guide Optional guidance for using this tool in the current scope.
118
+ * @property tool Name of the registered tool.
119
+ */
120
+ data class ToolEntry(val tool: String, val bind: JsonObject? = null, val commands: List<String>? = null, val guide: String? = null) {
121
+ internal fun json() = JsonObject().apply {
122
+ addProperty("tool", tool); bind?.let { add("bind", it.deepCopy()) }
123
+ commands?.let { names -> add("commands", JsonArray().apply { names.forEach(::add) }) }
124
+ guide?.let { addProperty("guide", it) }
125
+ }
126
+ }
127
+ /** Controls which registered tools an agent can use. */
128
+ sealed interface ToolSelection {
129
+ /** Select all available tools. */
130
+ data object All : ToolSelection
131
+ /**
132
+ * Select the listed tools and their scoped settings.
133
+ *
134
+ * @property entries Tool entries included in the selection.
135
+ */
136
+ data class Only(val entries: List<ToolEntry>) : ToolSelection
137
+ /** Encode the tool scope for Core as an all selector or a list of entries. */
138
+ fun json(): JsonElement = when (this) {
139
+ All -> JsonPrimitive("all")
140
+ is Only -> JsonArray().apply { entries.forEach { add(it.json()) } }
141
+ }
142
+ }
143
+ /**
144
+ * Scoped wiki document and optional guidance for the agent.
145
+ *
146
+ * @property doc Path of the wiki document to include.
147
+ * @property guide Optional guidance for the agent on using this document.
148
+ */
149
+ data class WikiEntry(val doc: String, val guide: String? = null) {
150
+ internal fun json() = JsonObject().apply { addProperty("doc", doc); guide?.let { addProperty("guide", it) } }
151
+ }
152
+ /** Controls which wiki documents are available to an agent. */
153
+ sealed interface WikiSelection {
154
+ /** Select all available wiki documents. */
155
+ data object All : WikiSelection
156
+ /**
157
+ * Select the listed documents and any guidance supplied for them.
158
+ *
159
+ * @property entries Document entries included in the selection.
160
+ */
161
+ data class Only(val entries: List<WikiEntry>) : WikiSelection
162
+ /** Encode the wiki scope for Core as an all selector or a list of entries. */
163
+ fun json(): JsonElement = when (this) {
164
+ All -> JsonPrimitive("all")
165
+ is Only -> JsonArray().apply { entries.forEach { add(it.json()) } }
166
+ }
167
+ }
168
+ /** A wiki document supplied inline or addressed by a file. */
169
+ sealed interface WikiDoc {
170
+ /** Path used to identify the document in the wiki. */
171
+ val path: String
172
+ /** Description supplied with the document. */
173
+ val description: String
174
+ /**
175
+ * A wiki document supplied as Markdown text.
176
+ *
177
+ * @property description Description supplied for this document.
178
+ * @property markdown Markdown content supplied by the app.
179
+ * @property path Path used to identify the document in the wiki.
180
+ */
181
+ data class Markdown(override val path: String, override val description: String, val markdown: String) : WikiDoc
182
+ /**
183
+ * A wiki document whose content comes from a file.
184
+ *
185
+ * @property description Description supplied for this document.
186
+ * @property file File location passed to Core to load the document.
187
+ * @property path Path used to identify the document in the wiki.
188
+ */
189
+ data class File(override val path: String, override val description: String, val file: String) : WikiDoc
190
+ /** Encode the document as a Markdown or file descriptor for Core. */
191
+ fun json() = JsonObject().apply {
192
+ addProperty("path", path); addProperty("description", description)
193
+ when (val doc = this@WikiDoc) {
194
+ is Markdown -> addProperty("markdown", doc.markdown)
195
+ is File -> addProperty("file", doc.file)
196
+ }
197
+ }
198
+ }
199
+ /**
200
+ * Separate second argument to Croche.open; Core validates the recover string.
201
+ *
202
+ * @property recover Recovery mode passed to Core for opening a handle that supports deletion and close.
203
+ */
204
+ data class RecoveryOptions(val recover: String) {
205
+ internal fun json() = JsonObject().apply { addProperty("recover", recover) }
206
+ }
207
+ /**
208
+ * Limits deletion to one agent or one conversation. With neither field, the deletion is user-wide.
209
+ *
210
+ * @property agent Agent whose local data is selected for deletion.
211
+ * @property instance Named conversation within the selected agent.
212
+ */
213
+ data class DeleteDataOptions(val agent: String? = null, val instance: String? = null) {
214
+ internal fun json() = JsonObject().apply { agent?.let { addProperty("agent", it) }; instance?.let { addProperty("instance", it) } }
215
+ }
216
+ /**
217
+ * Response options for a request that waits for a terminal result.
218
+ *
219
+ * @property responseFormat Optional format supplied to Core for structured output.
220
+ * @property wait Extra completion condition. Null returns when the request is terminal.
221
+ */
222
+ data class RequestOptions(val responseFormat: JsonObject? = null, val wait: RequestWait? = null) {
223
+ internal fun json() = JsonObject().apply {
224
+ responseFormat?.let { add("responseFormat", it.deepCopy()) }; wait?.let { addProperty("wait", it.name.lowercase()) }
225
+ }
226
+ }
227
+ /**
228
+ * @property onEvent Called with each event for this subscription. Update the transcript and controls from it together.
229
+ *
230
+ * @property after Resume after this cursor in its stream log.
231
+ * @property initialMessages Number of recent messages to replay on attach. Null uses Core's default.
232
+ */
43
233
  data class SubscribeOptions(val initialMessages: Int? = null, val after: Cursor? = null,
44
- val onEvent: suspend (RuntimeEvent) -> Unit)
45
- data class HistoryOptions(val before: Long? = null, val limit: Int)
46
- data class AppStreamEnd(val code: String)
234
+ val onEvent: suspend (AppStreamContract.AgentEvent) -> Unit) {
235
+ internal fun json() = JsonObject().apply {
236
+ initialMessages?.let { addProperty("initialMessages", it) }
237
+ after?.let { add("after", JsonObject().apply { addProperty("logId", it.logId); addProperty("seq", it.seq) }) }
238
+ }
239
+ }
240
+ /**
241
+ * Selects a page of retained transcript events to send to a subscription.
242
+ *
243
+ * @property before Exclusive sequence bound for older events. Null requests the latest page.
244
+ * @property limit Requested page size.
245
+ */
246
+ data class HistoryOptions(val before: Long? = null, val limit: Int) {
247
+ internal fun json() = JsonObject().apply { before?.let { addProperty("before", it) }; addProperty("limit", limit) }
248
+ }
249
+ /**
250
+ * Optional time bounds and limit for looking up scheduled wakes.
251
+ *
252
+ * @property after Inclusive lower bound in epoch milliseconds. Pass the previous result's next value to continue.
253
+ * @property before Upper time bound in epoch milliseconds.
254
+ * @property limit Requested maximum number of wakes.
255
+ */
256
+ data class WakeQuery(val before: Long? = null, val after: Long? = null, val limit: Int? = null) {
257
+ internal fun json() = JsonObject().apply {
258
+ before?.let { addProperty("before", it) }; after?.let { addProperty("after", it) }; limit?.let { addProperty("limit", it) }
259
+ }
260
+ }
261
+ /**
262
+ * Core's background notification, forwarded unchanged. A skipped event's known reasons are
263
+ * `storage_unavailable` and `os_registration_failed`; future reasons remain readable strings.
264
+ * OS registration failure has only type/reason/at and never contains host failure details.
265
+ *
266
+ * @property at Event timestamp, when supplied.
267
+ * @property fields Complete notification object received from Core.
268
+ * @property reason Background deferral or skip reason, when supplied.
269
+ * @property type Notification type sent to the background sink.
270
+ */
271
+ data class BackgroundEvent(val type: String, val at: String?, val reason: String?, val fields: JsonObject)
272
+
273
+ /**
274
+ * @property sink Let the app react when scheduled work was delivered or could not run.
275
+ * @property storage Use the same store as the app uses when opening Croche.
276
+ *
277
+ * @property adapters Host adapters for the background run. Use the same storage as the foreground session.
278
+ */
279
+ data class BackgroundOptions(val sink: ((BackgroundEvent) -> Unit)? = null, val adapters: List<Adapter>? = null)
280
+
281
+ /**
282
+ * Connection details for attaching a debugger.
283
+ *
284
+ * @property token Debugger access token.
285
+ * @property url Endpoint for the debugger connection.
286
+ */
287
+ data class DebugAttachOptions(val url: String, val token: String) {
288
+ internal fun json() = JsonObject().apply { addProperty("url", url); addProperty("token", token) }
289
+ }
290
+
291
+
292
+ /**
293
+ * App-wide host policy; each instance has its own byte budget. Core validates.
294
+ *
295
+ * @property maxBytes History byte budget for each agent instance. Null uses the Core default of 8 MiB.
296
+ * @property notesMaxBytes Shared archive byte budget for retired summary pieces and saved memory facts per instance. Null uses the Core default of 4 MiB.
297
+ */
298
+ data class ArchiveOptions(val maxBytes: Long? = null, val notesMaxBytes: Long? = null) {
299
+ internal fun json() = JsonObject().apply {
300
+ maxBytes?.let { addProperty("maxBytes", it) }
301
+ notesMaxBytes?.let { addProperty("notesMaxBytes", it) }
302
+ }
303
+ }