@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,313 @@
1
+ import Foundation
2
+
3
+ /// One background-delivery outcome, passed to the ``BackgroundOptions`` sink.
4
+ public struct BackgroundEvent: Sendable, Equatable {
5
+ /// `delivered`, `deadline`, `cancelled`, `skipped`, or a type this SDK does not know yet.
6
+ public let type: String
7
+ /// When Core recorded the event, as an ISO 8601 UTC timestamp. `nil` if Core sent none.
8
+ public let at: String?
9
+ /// `skipped`: `storage_unavailable`, or `os_registration_failed` (the OS refused the background
10
+ /// task: on iOS, BGTaskScheduler rejected `ai.croche.background` or it was registered after launch).
11
+ public let reason: String?
12
+ /// The whole event, so an app can log or forward what it does not read.
13
+ public let fields: JSON
14
+ init(_ value: JSON) {
15
+ type = value["type"].string ?? ""; at = value["at"].string; reason = value["reason"].string; fields = value
16
+ }
17
+ }
18
+
19
+ /// When users of a project next have background work due, from ``Croche/wakeTimes(_:before:after:limit:)``.
20
+ public struct WakeTimes: Sendable, Equatable {
21
+ /// One user's next due time.
22
+ public struct Wake: Sendable, Equatable {
23
+ /// nil for a Croche opened with no user (Core sends `user: null`).
24
+ public let user: String?
25
+ /// Epoch ms.
26
+ public let at: Double
27
+ }
28
+ /// Due users within the query's bounds.
29
+ public let wakes: [Wake]
30
+ /// Epoch ms.
31
+ public let next: Double?
32
+ }
33
+
34
+ /// The result of ``Croche/deliverDue()``.
35
+ public struct DueDelivery: Sendable, Equatable {
36
+ /// An agent instance whose due work did not finish in this call; it stays due.
37
+ public struct Deferred: Sendable, Equatable {
38
+ /// nil for a Croche opened with no user (Core sends `user: null`).
39
+ public let user: String?
40
+ /// The agent id.
41
+ public let agent: String
42
+ /// The instance, or `nil` for the default instance.
43
+ public let instance: String?
44
+ /// `deadline` or `cancelled` today; open for codes Core adds.
45
+ public let code: String, message: String
46
+ }
47
+ /// Whether a due instance's delivery ran. `false`, with nothing delivered, when another delivery on this Croche
48
+ /// already owns the work or nothing was due.
49
+ public let ran: Bool
50
+ /// How many pending usage reports this call delivered.
51
+ public let delivered: Int
52
+ /// Work that was due but not finished, for example because the deadline passed.
53
+ public let deferred: [Deferred]
54
+ }
55
+
56
+ // APP-API `debugger.attach({url, token})`.
57
+ /// Connection details for ``Croche/Debugger/attach(_:)``.
58
+ public struct DebugAttachOptions: Sendable, Equatable {
59
+ /// The debugger's control origin.
60
+ public var url: String
61
+ /// The control origin's ingest credential. Keep it out of logs, URLs and committed files.
62
+ public var token: String
63
+ /// Creates attach options from the control origin and its credential.
64
+ public init(url: String, token: String) { self.url = url; self.token = token }
65
+ var json: JSON { .object(["url": .string(url), "token": .string(token)]) }
66
+ }
67
+
68
+ /// A successful ``Croche/Debugger/attach(_:)``.
69
+ public struct AttachedDebugger: Sendable, Equatable {
70
+ /// The same value as the CLI/broker wire's `attachmentId`, so app logs match CLI logs.
71
+ public let debuggerId: String
72
+ /// `agents.list`, `status`, `history`, `send`, `cancel`, `tools`; open for more.
73
+ public let capabilities: [String]
74
+ }
75
+
76
+ /// The shared-resource factory for one user's session.
77
+ public final class Croche: Sendable {
78
+ let handle: S1HandleOwner<CoreCroche>
79
+ var core: CoreCroche { get throws { try handle.value() } }
80
+ init(core: CoreCroche) { self.handle = S1HandleOwner(core) }
81
+ /// Load a shared attachment when the user opens its preview.
82
+ public func attachment(_ id: String) async throws -> AttachmentData { let core = try self.core; return try decode(AttachmentData.self, await blocking { try core.attachment(id: id) }) }
83
+ /// Let the user remove a shared attachment they no longer want to keep.
84
+ public func deleteAttachment(_ id: String) async throws { let core = try self.core; try await blocking { try core.deleteAttachment(id: id) } }
85
+ /// Populate a picker of attachments shared by this user’s agents, newest first, one page at a time.
86
+ public func listAttachments(_ options: ListOptions? = nil) async throws -> Page<Attachment> {
87
+ let core = try self.core, options = options?.optionsJson
88
+ return try page(try await blocking { try core.listAttachments(optionsJson: options) }, "attachment list") { try decode(Attachment.self, text($0)) }
89
+ }
90
+
91
+
92
+ /// Open the app’s user session before letting that user talk to an agent or run a tool.
93
+ ///
94
+ /// Opening twice for the same (projectKey, user) is the SAME Core Croche, ref-counted in Core.
95
+ public static func open(_ options: OpenOptions) async throws -> Croche { try await opening(options, nil) }
96
+
97
+ // RECOVERY OPEN (R1).
98
+ /// Give a user a way to erase local data even when the app can no longer open their session.
99
+ ///
100
+ /// Use it when `open(options)` fails because the project record is corrupt or
101
+ /// too new (`corrupt_store`, `store_too_new`) or a store refuses writes (`store_full`,
102
+ /// `store_refused`). Only `deleteData()` with an empty scope and `close()` work on the handle;
103
+ /// Core rejects every other member, and any recovery mode it does not know, with `invalid_request`.
104
+ public static func open(_ options: OpenOptions, recovery: RecoveryOptions) async throws -> Croche {
105
+ try await opening(options, recovery)
106
+ }
107
+
108
+ private static func opening(_ options: OpenOptions, _ recovery: RecoveryOptions?) async throws -> Croche {
109
+ let selected = try adaptersFor(options.adapters)
110
+ let open = text(options.json), recoveryJson = recovery.map { text($0.json) }
111
+ let registrations = try (options.tools ?? []).map { try $0.core() }
112
+ #if CROCHE_TEST_HOOKS
113
+ if let serve = FixtureCloud.serve { return try await fixtureOpen(open, registrations, selected, recoveryJson, serve) }
114
+ #endif
115
+ let host = try platformHost(image: selected.image), storage = PlatformStorageAdapter(host, state: selected.state)
116
+ return Croche(core: try await owner({ try CoreCroche.open(openJson: open, registrations: registrations, storage: storage, host: host,
117
+ bindingFactsJson: BindingFacts.json(), recoveryJson: recoveryJson) },
118
+ discard: { try? $0.shutdown() }))
119
+ }
120
+
121
+ /// Honor a user’s request to erase one workspace or all their local Croche data.
122
+ ///
123
+ /// Deletes this user's LOCAL data on the opened Croche. No scope (or an empty one): the declared
124
+ /// stores, registered instances and tool runtime; `agent`: that agent's main and named instances;
125
+ /// `agent` + `instance`: one instance. Core validates every scope. Other users, the install
126
+ /// record, undeclared legacy main stores and Cloud records remain. The Croche stays open; agents
127
+ /// in scope close, and a later `agent()` starts fresh stores. Core owns store locks and partial
128
+ /// progress: retry a failure with the same scope.
129
+ public func deleteData(_ scope: DataScope? = nil) async throws {
130
+ let core = try self.core, scope = scope.map { text($0.json) }
131
+ try await blocking { try core.deleteData(scopeJson: scope) }
132
+ }
133
+
134
+ /// Let the app keep up with due work when its UI is no longer in the foreground.
135
+ ///
136
+ /// Call once at launch (iOS: before didFinishLaunching returns). OS identifier `ai.croche.background`.
137
+ public static func registerBackground(_ options: BackgroundOptions = BackgroundOptions()) throws {
138
+ let selected = try adaptersFor(options.adapters)
139
+ let host = try platformHost(image: selected.image), json = text(options.json)
140
+ do {
141
+ // With the app's store, Core also gets the platform store (its background markers);
142
+ // the default registration hands only the one store (Core: never a second wrapper).
143
+ try coreRegisterBackground(optionsJson: json, sink: options.sink.map(BackgroundSink.init),
144
+ storage: PlatformStorageAdapter(host, state: selected.state),
145
+ platformStorage: selected.state.map { _ in PlatformStorageAdapter(host) }, host: host,
146
+ bindingFactsJson: BindingFacts.json())
147
+ } catch { throw CrocheError(error) }
148
+ }
149
+
150
+ /// Let a server schedule just the users whose background work is due.
151
+ ///
152
+ /// When `deliverDue` is next needed (servers, serverless cron). Opens no project.
153
+ public static func wakeTimes(_ options: OpenOptions, before: Double? = nil, after: Double? = nil, limit: Int? = nil) async throws -> WakeTimes {
154
+ var query: [String: JSON] = [:]
155
+ if let before { query["before"] = .number(before) }
156
+ if let after { query["after"] = .number(after) }
157
+ if let limit { query["limit"] = .number(Double(limit)) }
158
+ let selected = try adaptersFor(options.adapters)
159
+ let open = text(options.json), queryText = query.isEmpty ? nil : text(.object(query))
160
+ let host = try platformHost(image: selected.image), storage = PlatformStorageAdapter(host, state: selected.state)
161
+ let value = try reply(try await blocking { try coreWakeTimes(openJson: open, queryJson: queryText, storage: storage, host: host) })
162
+ return try decodeWakeTimes(value)
163
+ }
164
+
165
+ /// Let a host deliver scheduled work when its timer or alarm fires.
166
+ ///
167
+ /// Delivery and config sync only. Cancel the Task to stop it.
168
+ public func deliverDue() async throws -> DueDelivery {
169
+ let core = try self.core
170
+ return try decodeDueDelivery(try reply(try await cancellable { try core.deliverDue(optionsJson: nil, cancel: $0) }))
171
+ }
172
+
173
+ /// Give each chat, case, or workspace its own conversation while reusing the app’s agent definition.
174
+ ///
175
+ /// The same instance with the same or no config returns a handle to it; a different config
176
+ /// is Core's `invalid_configuration`.
177
+ public func agent(_ id: String, _ options: AgentOptions? = nil) async throws -> CrocheAgent {
178
+ let core = try self.core, scope = options.map { text($0.json) }
179
+ let agent = CrocheAgent(core: try await owner({ try core.agent(id: id, scopeJson: scope) }, discard: { try? $0.shutdown() }))
180
+ try handle.adopt(agent.handle)
181
+ return agent
182
+ }
183
+
184
+ /// The project's documents for this Croche.
185
+ public var wiki: Wiki { Wiki(handle: handle) }
186
+ /// Attach the local Croche debugger to this Croche.
187
+ public var debugger: Debugger { Debugger(handle: handle) }
188
+
189
+ /// Release the user’s session when they sign out or the app switches accounts.
190
+ ///
191
+ /// Returns once new work has stopped; the bounded final delivery continues.
192
+ public func close() async throws {
193
+ let handle = self.handle
194
+ try await blocking { try handle.shutdown { try $0.shutdown() } }
195
+ }
196
+
197
+ /// The project's original documents, in memory for this Croche; put/remove last until close().
198
+ public struct Wiki: Sendable {
199
+ let handle: S1HandleOwner<CoreCroche>
200
+ var core: CoreCroche { get throws { try handle.value() } }
201
+ /// Make an updated help article available to agents in the current app session.
202
+ public func put(_ doc: WikiDoc) async throws {
203
+ let core = try self.core, doc = text(doc.json)
204
+ try await blocking { try core.wikiPut(docJson: doc) }
205
+ }
206
+ /// Stop agents from using a help article the app has withdrawn.
207
+ public func remove(_ path: String) async throws {
208
+ let core = try self.core
209
+ try await blocking { try core.wikiRemove(path: path) }
210
+ }
211
+ /// Show which help articles the app has made available to its agents.
212
+ public func list(_ options: ListOptions? = nil) async throws -> Page<WikiDoc> {
213
+ let core = try self.core, options = options?.optionsJson
214
+ return try page(try await blocking { try core.wikiList(optionsJson: options) }, "wiki list", WikiDoc.init)
215
+ }
216
+ }
217
+
218
+ /// The local debugger: loopback (iproxy), or LAN with the development key.
219
+ public struct Debugger: Sendable {
220
+ let handle: S1HandleOwner<CoreCroche>
221
+ var core: CoreCroche { get throws { try handle.value() } }
222
+ /// Inspect a running session when a development build behaves unexpectedly.
223
+ public func attach(_ options: DebugAttachOptions) async throws -> AttachedDebugger {
224
+ let core = try self.core, options = text(options.json)
225
+ let value = try reply(try await blocking { try core.debugAttach(optionsJson: options) })
226
+ guard let id = value["debuggerId"].string, let capabilities = value["capabilities"].array else { throw malformed("attached debugger") }
227
+ return AttachedDebugger(debuggerId: id, capabilities: capabilities.compactMap(\.string))
228
+ }
229
+ /// End diagnostic access after the developer is done or the user withdraws permission.
230
+ ///
231
+ /// The last Croche alias close detaches the runtime.
232
+ public func detach() async throws {
233
+ let core = try self.core
234
+ try await blocking { try core.debugDetach() }
235
+ }
236
+ }
237
+ }
238
+
239
+ /// Core's `user` on a wake or deferral: a string, or null (absent) for a Croche with no user.
240
+ /// Any other type is malformed.
241
+ private func optionalUser(_ value: JSON, _ what: String) throws -> String? {
242
+ switch value["user"] {
243
+ case .null: return nil
244
+ case .string(let user): return user
245
+ default: throw malformed(what)
246
+ }
247
+ }
248
+
249
+ /// `wakeTimes`' reply. Unknown fields are ignored.
250
+ func decodeWakeTimes(_ value: JSON) throws -> WakeTimes {
251
+ let wakes = try (value["wakes"].array ?? []).map { wake -> WakeTimes.Wake in
252
+ let user = try optionalUser(wake, "wake")
253
+ guard let at = wake["at"].number else { throw malformed("wake") }
254
+ return WakeTimes.Wake(user: user, at: at)
255
+ }
256
+ return WakeTimes(wakes: wakes, next: value["next"].number)
257
+ }
258
+
259
+ /// `deliverDue`'s reply. Unknown fields are ignored.
260
+ func decodeDueDelivery(_ value: JSON) throws -> DueDelivery {
261
+ guard let ran = value["ran"].bool, let delivered = value["delivered"].number else { throw malformed("delivery") }
262
+ let deferred = try (value["deferred"].array ?? []).map { item -> DueDelivery.Deferred in
263
+ let user = try optionalUser(item, "deferral")
264
+ guard let agent = item["agent"].string, let code = item["code"].string,
265
+ let message = item["message"].string else { throw malformed("deferral") }
266
+ return DueDelivery.Deferred(user: user, agent: agent, instance: item["instance"].string, code: code, message: message)
267
+ }
268
+ return DueDelivery(ran: ran, delivered: Int(delivered), deferred: deferred)
269
+ }
270
+
271
+ func malformed(_ what: String) -> CrocheError {
272
+ CrocheError(code: "internal", message: "Core's \(what) is malformed.", category: .internal)
273
+ }
274
+
275
+ /// Test-only: the OS launch handler table a host gate gives the platform PAL (macOS has none).
276
+ enum PlatformBackgroundTesting {
277
+ nonisolated(unsafe) static var launches: (any BackgroundLaunches)?
278
+ }
279
+
280
+ /// The platform PAL (#820 seam): its storage is the default when the app gives none.
281
+ func platformHost(image: (any ImageAdapter)? = nil) throws -> PlatformPal {
282
+ let directory = try NativeProjectFiles.directory(projectDirectory: nil)
283
+ return PlatformPal(directory: directory, secrets: PlatformPal.testingSecrets(directory),
284
+ backgroundLaunches: PlatformBackgroundTesting.launches ?? PlatformPal.osBackgroundLaunches(), imageAdapter: image)
285
+ }
286
+
287
+ /// Background events, at least once, at the next registration in a live runtime. The same
288
+ /// delivery protocol as `subscribe` (#830 70a5ca8e): the app's sink runs only after `tryEnter`
289
+ /// succeeds, on the main actor, and every entered delivery is completed. The sink cannot throw, so
290
+ /// its outcome is always `returned`. An event that is not JSON is an untyped exception Core
291
+ /// classifies (no SDK-invented code).
292
+ final class BackgroundSink: CoreEventSink, @unchecked Sendable {
293
+ private let sink: @Sendable (BackgroundEvent) -> Void
294
+ init(_ sink: @escaping @Sendable (BackgroundEvent) -> Void) { self.sink = sink }
295
+
296
+ func deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) throws {
297
+ try deliver(eventJson, delivery)
298
+ }
299
+
300
+ /// The seam tests drive with a fake gate. Returns the main-actor task.
301
+ @discardableResult
302
+ func deliver(_ eventJson: String, _ delivery: any DeliveryGate) throws -> Task<Void, Never> {
303
+ guard let value = try? JSON(eventJson), value.object != nil else {
304
+ throw MalformedEvent(reason: "a background event must be a JSON object")
305
+ }
306
+ let event = BackgroundEvent(value), sink = self.sink
307
+ return Task { @MainActor in
308
+ guard delivery.tryEnter() else { return }
309
+ sink(event)
310
+ delivery.complete(outcomeJson: EventSinkAdapter.returned)
311
+ }
312
+ }
313
+ }
@@ -0,0 +1,146 @@
1
+ import Foundation
2
+
3
+ /// Native spelling of the same question union as the TS App API. Core validates every value.
4
+ public enum DecisionQuestion: Sendable {
5
+ /// One option of a `choice` question.
6
+ public struct Choice: Sendable {
7
+ /// The option id: 1-64 characters of `A-Z a-z 0-9 _ . : -`, distinct within the question.
8
+ public let id: String
9
+ /// What the option means, 1-4000 characters.
10
+ public let description: String?
11
+ /// Creates an option.
12
+ public init(id: String, description: String? = nil) { self.id = id; self.description = description }
13
+ }
14
+ /// A yes/no question. The optional descriptions explain what `true` and `false` mean.
15
+ case noul(id: String, instructions: String, trueDescription: String? = nil, falseDescription: String? = nil)
16
+ /// Pick one of 2-255 options, in order.
17
+ case choice(id: String, instructions: String, criteria: [Choice])
18
+ /// Rate on 2-10 levels, lowest first.
19
+ case score(id: String, instructions: String, criteria: [String])
20
+
21
+ var json: JSON {
22
+ let id: String, instructions: String, type: String
23
+ var criteria: JSON?
24
+ switch self {
25
+ case let .noul(key, text, yes, no):
26
+ id = key; instructions = text; type = "noul"
27
+ var values: [String: JSON] = [:]
28
+ if let yes { values["true"] = .string(yes) }; if let no { values["false"] = .string(no) }
29
+ if !values.isEmpty { criteria = .object(values) }
30
+ case let .choice(key, text, choices):
31
+ id = key; instructions = text; type = "choice"
32
+ criteria = .array(choices.map { choice in
33
+ var value: [String: JSON] = ["id": .string(choice.id)]
34
+ if let description = choice.description { value["description"] = .string(description) }
35
+ return .object(value)
36
+ })
37
+ case let .score(key, text, levels):
38
+ id = key; instructions = text; type = "score"; criteria = .array(levels.map(JSON.string))
39
+ }
40
+ var value: [String: JSON] = ["id": .string(id), "type": .string(type), "instructions": .string(instructions)]
41
+ if let criteria { value["criteria"] = criteria }
42
+ return .object(value)
43
+ }
44
+ }
45
+
46
+ /// A question in ``DecideInput``: the id of one configured on the decision agent, or a question given inline.
47
+ ///
48
+ /// Inline questions are checked against the model only at `decide`.
49
+ public enum DecisionQuestionRef: Sendable {
50
+ /// A question configured under the agent's `questions`.
51
+ case named(String)
52
+ /// A question supplied with this call.
53
+ case inline(DecisionQuestion)
54
+ var json: JSON { switch self { case .named(let id): return .string(id); case .inline(let question): return question.json } }
55
+ }
56
+ /// The input to ``CrocheAgent/decide(_:)``.
57
+ public struct DecideInput: Sendable {
58
+ /// A correlation id for ``CrocheAgent/cancel(_:)``, not a replay key: reusing it after the decision settles buys a
59
+ /// new decision, and reusing it while one is in flight is refused with `idempotency_conflict`.
60
+ public let id: String?
61
+ /// The app data to evaluate.
62
+ public let state: JSON
63
+ /// The questions to answer. `nil` asks the agent's configured questions; an agent with none configured needs them here.
64
+ public let questions: [DecisionQuestionRef]?
65
+ /// Creates a decision input.
66
+ public init(id: String? = nil, state: JSON, questions: [DecisionQuestionRef]? = nil) {
67
+ self.id = id; self.state = state; self.questions = questions
68
+ }
69
+ var json: JSON {
70
+ var value: [String: JSON] = ["state": state]
71
+ if let id { value["id"] = .string(id) }
72
+ if let questions { value["questions"] = .array(questions.map(\.json)) }
73
+ return .object(value)
74
+ }
75
+ }
76
+ /// A confidence the provider reported for one answer.
77
+ ///
78
+ /// Core keeps it only when it matches its own calculation from the answer's probabilities, within 0.01.
79
+ public struct DecisionConfidence: Decodable, Sendable {
80
+ /// The confidence, from 0 to 1.
81
+ public let value: Double
82
+ /// Open provider method, passed through without inference.
83
+ public let method: String
84
+ }
85
+ /// The answer to one question in a ``DecisionResult``.
86
+ public enum DecisionAnswer: Decodable, Sendable {
87
+ /// A yes/no answer. `value` is `probability >= 0.5`; `probability` is the probability of `true`.
88
+ case noul(value: Bool, probability: Double?, confidence: DecisionConfidence?)
89
+ /// The chosen option id, with a probability per option id when the provider gave them.
90
+ case choice(value: String, probabilities: [String: Double]?, confidence: DecisionConfidence?)
91
+ /// The expected level, a zero-based index weighted by `probabilities` (one per level, lowest first).
92
+ case score(value: Double, probabilities: [Double]?, confidence: DecisionConfidence?)
93
+ /// The provider declined to answer, with its reason when it gave one.
94
+ case refusal(reason: String?)
95
+ /// An answer type this SDK does not know, with its original type and fields.
96
+ case unknown(originalType: String, fields: JSON)
97
+
98
+ /// Decodes an answer by its `type`. An unrecognized type becomes ``unknown(originalType:fields:)``.
99
+ public init(from decoder: Decoder) throws {
100
+ let value = try JSON(from: decoder)
101
+ func read<T: Decodable>(_ type: T.Type, _ key: String) throws -> T {
102
+ try JSONDecoder().decode(type, from: value[key].encoded())
103
+ }
104
+ func optional<T: Decodable>(_ type: T.Type, _ key: String) throws -> T? {
105
+ value[key] == .null ? nil : try read(type, key)
106
+ }
107
+ let type = try read(String.self, "type")
108
+ switch type {
109
+ case "noul": self = .noul(value: try read(Bool.self, "value"), probability: try optional(Double.self, "probability"), confidence: try optional(DecisionConfidence.self, "confidence"))
110
+ case "choice": self = .choice(value: try read(String.self, "value"), probabilities: try optional([String: Double].self, "probabilities"), confidence: try optional(DecisionConfidence.self, "confidence"))
111
+ case "score": self = .score(value: try read(Double.self, "value"), probabilities: try optional([Double].self, "probabilities"), confidence: try optional(DecisionConfidence.self, "confidence"))
112
+ case "refusal": self = .refusal(reason: try optional(String.self, "reason"))
113
+ case "unknown": self = .unknown(originalType: try read(String.self, "originalType"), fields: value["fields"])
114
+ default: self = .unknown(originalType: type, fields: value)
115
+ }
116
+ }
117
+ }
118
+ /// The result of ``CrocheAgent/decide(_:)``.
119
+ public struct DecisionResult: Decodable, Sendable {
120
+ /// The decision's correlation id: the input's `id`, or the one Core assigned.
121
+ public let id: String
122
+ /// The model that answered.
123
+ public let model: String
124
+ /// One answer per question id.
125
+ public let answers: [String: DecisionAnswer]
126
+ /// Reported serving-provider label, when known. Diagnostic only.
127
+ public let provider: String?
128
+ /// The provider's token usage, as reported.
129
+ public let usage: JSON
130
+ /// Cost in credits, when reported.
131
+ public let cost: Double?
132
+ /// Open status; unknown costs stay nil, never the estimate.
133
+ public let costStatus: String
134
+ }
135
+ public extension CrocheAgent {
136
+ /// Classify app data for a workflow, such as routing a support ticket without starting a chat.
137
+ ///
138
+ /// Task cancellation fires the existing Core token; Core owns handoff and settlement.
139
+ func decide(_ input: DecideInput) async throws -> DecisionResult {
140
+ let core = try self.core, input = text(input.json)
141
+ let result = try await cancellable {
142
+ try core.decide(inputJson: input, optionsJson: nil, cancel: $0)
143
+ }
144
+ return try decode(DecisionResult.self, result)
145
+ }
146
+ }
@@ -0,0 +1,37 @@
1
+ import Foundation
2
+
3
+ // The reader types are GENERATED from Core's Rust contract (GeneratedAppStream.swift), as in TS
4
+ // (APP-API: AgentEvent, MessageEnd and InputDisposition).
5
+ /// One subscription event. A type this SDK does not know arrives as `.unknown(type:fields:)` with
6
+ /// every field kept.
7
+ public typealias AgentEvent = AppStreamContract.AgentEvent
8
+ /// The end of one agent reply, with its final text and status.
9
+ public typealias MessageEnd = AppStreamContract.MessageEnd
10
+ /// A file kept with a conversation: an image the user sent, or one a tool produced.
11
+ public typealias Attachment = AppStreamContract.Attachment
12
+ /// What happened to one input: its status and, when it failed, the error.
13
+ public typealias InputDisposition = AppStreamContract.InputDisposition
14
+ /// `send`'s answer: Core has ACCEPTED the input. `error` is set when the input already failed.
15
+ public typealias SendReceipt = AppStreamContract.SendReceipt
16
+ /// `request`'s answer: the input is final. `gap` is true when Core says so, nil when absent.
17
+ public typealias RequestResult = AppStreamContract.RequestResult
18
+ /// `{code, category, message}` on a failed receipt, result, input or message.
19
+ public typealias EventError = AppStreamContract.EventError
20
+
21
+ /// Options for ``CrocheAgent/subscribe(_:)``. Give `initialMessages` or `after`, not both.
22
+ public struct SubscribeOptions: Sendable {
23
+ /// How many of the latest messages to deliver before the `snapshot`: 0-256, default 50.
24
+ public var initialMessages: Int?
25
+ /// Resume after a cursor from an earlier subscription. Missed events arrive first, as events or as a `gap`.
26
+ /// A cursor from another log, or past its end, gets one `error` event with `cursor_reset` and the subscription ends.
27
+ public var after: Cursor?
28
+ /// Update the transcript and controls together as the agent makes progress.
29
+ ///
30
+ /// A throw reaches Core as the delivery's `threw` fact; Core decides what follows.
31
+ public var onEvent: @Sendable (AgentEvent) async throws -> Void
32
+ /// Creates subscribe options. Core validates them when you subscribe.
33
+ public init(initialMessages: Int? = nil, after: Cursor? = nil,
34
+ onEvent: @escaping @Sendable (AgentEvent) async throws -> Void) {
35
+ self.initialMessages = initialMessages; self.after = after; self.onEvent = onEvent
36
+ }
37
+ }
@@ -0,0 +1,58 @@
1
+ import Foundation
2
+
3
+ /// Export ownership only. A borrowed strong reference protects an already-entered FFI call.
4
+ /// Views retain this holder, never a generated pointer. ARC drops the export after shutdown.
5
+ protocol S1OwnedHandle: AnyObject, Sendable { func release() }
6
+ final class S1HandleOwner<T: AnyObject & Sendable>: S1OwnedHandle, @unchecked Sendable {
7
+ private let condition = NSCondition()
8
+ private var raw: T?
9
+ private var closing = false
10
+ private var children: [any S1OwnedHandle] = []
11
+ init(_ raw: T) { self.raw = raw }
12
+ func value() throws -> T {
13
+ condition.lock(); defer { condition.unlock() }
14
+ guard !closing, let raw else { throw Self.closed() }
15
+ return raw
16
+ }
17
+ var ended: Bool {
18
+ condition.lock(); defer { condition.unlock() }; return raw == nil || closing
19
+ }
20
+ func adopt(_ child: any S1OwnedHandle) throws {
21
+ condition.lock()
22
+ guard raw != nil, !closing else {
23
+ condition.unlock(); child.release(); throw Self.closed()
24
+ }
25
+ children.append(child); condition.unlock()
26
+ }
27
+ func shutdown(_ stop: (T) throws -> Void) throws {
28
+ condition.lock()
29
+ while closing { condition.wait() }
30
+ guard let value = raw else { condition.unlock(); return }
31
+ closing = true; condition.unlock()
32
+ do { try stop(value) }
33
+ catch {
34
+ condition.lock(); closing = false; condition.broadcast(); condition.unlock()
35
+ throw error // Failed shutdown keeps the owner available for retry.
36
+ }
37
+ condition.lock()
38
+ raw = nil
39
+ let nested = children; children = []
40
+ closing = false; condition.broadcast(); condition.unlock()
41
+ withExtendedLifetime(value) {}
42
+ // Parent shutdown already fenced its children. Never shut down another shared alias.
43
+ nested.forEach { $0.release() }
44
+ }
45
+ func release() {
46
+ condition.lock()
47
+ // A pending explicit shutdown owns its eventual release.
48
+ guard !closing else { condition.unlock(); return }
49
+ let previous = raw, nested = children
50
+ raw = nil; children = []; condition.unlock()
51
+ nested.forEach { $0.release() }
52
+ // Generated deinit can call native code: never run it under the holder lock.
53
+ withExtendedLifetime(previous) {}
54
+ }
55
+ private static func closed() -> CrocheError {
56
+ CrocheError(code: "closed", message: "This handle is closed.", category: .closed)
57
+ }
58
+ }