@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,346 @@
1
+ import Foundation
2
+
3
+ /// One entry = one tool, by its registered name. `bind` REPLACES the registration bind as a
4
+ /// whole; nil keeps it. Core validates every field.
5
+ public struct ToolEntry: Sendable, ExpressibleByStringLiteral {
6
+ /// The registered tool name.
7
+ public var tool: String
8
+ /// Bound argument values for this agent; replaces the registration's `bind` as a whole.
9
+ public var bind: [String: JSON]?
10
+ /// Narrows the tool to these stable command keys from its manifest. `nil` allows all of them.
11
+ public var commands: [String]?
12
+ /// App guidance for this tool on this agent, added after the manifest guide and the agent's `toolGuide`.
13
+ public var guide: String?
14
+ /// Creates a tool entry.
15
+ public init(tool: String, bind: [String: JSON]? = nil, commands: [String]? = nil, guide: String? = nil) {
16
+ self.tool = tool; self.bind = bind; self.commands = commands; self.guide = guide
17
+ }
18
+ /// The tool by name, with nothing narrowed or bound.
19
+ public init(stringLiteral name: String) { self.init(tool: name) }
20
+ var json: JSON {
21
+ guard bind != nil || commands != nil || guide != nil else { return .string(tool) }
22
+ var fields: [String: JSON] = ["tool": .string(tool)]
23
+ if let bind { fields["bind"] = .object(bind) }
24
+ if let commands { fields["commands"] = .array(commands.map(JSON.string)) }
25
+ if let guide { fields["guide"] = .string(guide) }
26
+ return .object(fields)
27
+ }
28
+ }
29
+
30
+ /// One entry = one path or glob, e.g. `"faq/**"`.
31
+ public struct WikiEntry: Sendable, ExpressibleByStringLiteral {
32
+ /// A registered document path or a glob over them.
33
+ public var doc: String
34
+ /// App guidance on when the agent should use these documents.
35
+ public var guide: String?
36
+ /// Creates a wiki entry.
37
+ public init(doc: String, guide: String? = nil) { self.doc = doc; self.guide = guide }
38
+ /// The path or glob, without a guide.
39
+ public init(stringLiteral doc: String) { self.init(doc: doc) }
40
+ var json: JSON {
41
+ guard let guide else { return .string(doc) }
42
+ return .object(["doc": .string(doc), "guide": .string(guide)])
43
+ }
44
+ }
45
+
46
+ /// `.all` = every registered; `[]` = none. In `AgentOptions`, nil also means all.
47
+ public enum Scope<Entry: Sendable>: Sendable, ExpressibleByArrayLiteral {
48
+ /// Every registered entry.
49
+ case all
50
+ /// Exactly these entries; an empty list means none.
51
+ case list([Entry])
52
+ /// A list scope from an array literal.
53
+ public init(arrayLiteral entries: Entry...) { self = .list(entries) }
54
+ }
55
+ /// The tools an agent may use.
56
+ public typealias ToolScope = Scope<ToolEntry>
57
+ /// The wiki documents an agent may read.
58
+ public typealias WikiScope = Scope<WikiEntry>
59
+
60
+ /// `{path, description, markdown}` or `{path, description, file}`. iOS resolves `file` as a
61
+ /// main-bundle resource or a `file://` URL, when Core reads it.
62
+ public enum WikiDoc: Sendable, Equatable {
63
+ /// A document given inline as Markdown text.
64
+ case markdown(path: String, description: String, markdown: String)
65
+ /// A document read from a file when Core needs it. A missing file fails the turn that reads it.
66
+ case file(path: String, description: String, file: String)
67
+ var json: JSON {
68
+ switch self {
69
+ case let .markdown(path, description, markdown):
70
+ .object(["path": .string(path), "description": .string(description), "markdown": .string(markdown)])
71
+ case let .file(path, description, file):
72
+ .object(["path": .string(path), "description": .string(description), "file": .string(file)])
73
+ }
74
+ }
75
+ init(_ value: JSON) throws {
76
+ guard let path = value["path"].string, let description = value["description"].string else {
77
+ throw CrocheError(code: "internal", message: "Core's wiki document has no path or description.", category: .internal)
78
+ }
79
+ if let markdown = value["markdown"].string { self = .markdown(path: path, description: description, markdown: markdown) }
80
+ else if let file = value["file"].string { self = .file(path: path, description: description, file: file) }
81
+ else { throw CrocheError(code: "internal", message: "Core's wiki document has no body.", category: .internal) }
82
+ }
83
+ }
84
+
85
+ /// A named instance of an agent: its own conversation and memory.
86
+ public struct AgentInstance: Sendable {
87
+ /// The instance id, chosen by the app.
88
+ public var id: String
89
+ /// A patch over the agent config. NOT saved: pass it on every open.
90
+ public var config: JSON?
91
+ /// Creates an instance reference.
92
+ public init(id: String, config: JSON? = nil) { self.id = id; self.config = config }
93
+ }
94
+
95
+ /// Options for ``Croche/agent(_:_:)``.
96
+ public struct AgentOptions: Sendable {
97
+ /// nil = the agent's default instance.
98
+ public var instance: AgentInstance?
99
+ /// nil or `.all` = all registered; `[]` = none.
100
+ public var tools: ToolScope?
101
+ /// nil or `.all` = all registered documents; `[]` = none.
102
+ public var wiki: WikiScope?
103
+ /// Creates agent options.
104
+ public init(instance: AgentInstance? = nil, tools: ToolScope? = nil, wiki: WikiScope? = nil) {
105
+ self.instance = instance; self.tools = tools; self.wiki = wiki
106
+ }
107
+ var json: JSON {
108
+ var fields: [String: JSON] = [:]
109
+ if let instance {
110
+ var value: [String: JSON] = ["id": .string(instance.id)]
111
+ if let config = instance.config { value["config"] = config }
112
+ fields["instance"] = .object(value)
113
+ }
114
+ if let tools { fields["tools"] = tools.json(\.json) }
115
+ if let wiki { fields["wiki"] = wiki.json(\.json) }
116
+ return .object(fields)
117
+ }
118
+ }
119
+
120
+ /// Options for ``Croche/open(_:)``. The SDK passes every value to Core unchanged, and Core validates it.
121
+ public struct OpenOptions: Sendable {
122
+ /// Identifies the Croche Cloud project.
123
+ public var projectKey: String
124
+ /// The app's stable id for the signed-in user. `nil` opens without a user.
125
+ public var user: String?
126
+ // ARCHITECTURE §2: the device locale is a PAL fact, never an SDK default.
127
+ /// The user's language. `nil` omits it, and Core chooses from the device locale.
128
+ public var language: String?
129
+ /// The project config the app ships (schema 7), used until Croche Cloud delivers one.
130
+ public var bundledConfig: JSON
131
+ // APP-API gives an empty list its own meaning.
132
+ /// The tools to register. `nil` omits the field and `[]` is sent as an empty list; this SDK passes either to
133
+ /// Core unchanged.
134
+ public var tools: [ToolRegistration]?
135
+ /// nil = omitted; `[]` is sent as `[]`.
136
+ public var wiki: [WikiDoc]?
137
+ // ARCHITECTURE §2a.
138
+ /// App-supplied adapters. A kind left out uses the platform default; `nil` uses the defaults for all kinds.
139
+ public var adapters: [any Adapter]?
140
+ /// A server key, for a trusted backend only. Never ship one in an app.
141
+ public var serverKey: String?
142
+ /// A development key, for development builds only.
143
+ public var developmentKey: String?
144
+ /// Per-instance History and notes budgets.
145
+ public var archive: ArchiveOptions?
146
+ // Every storage size has a default and an app setting (founder 2026-11-19).
147
+ /// The byte budget of each instance's live stream log, the screen record used for replay.
148
+ /// `nil` omits it, and Core uses its default of 4 MiB. Core validates the value (2 MiB to 1 GiB); this SDK
149
+ /// passes it through unchanged.
150
+ public var retentionBytes: Int?
151
+ /// Total budget for the user's named instances, and each instance's budget for finished turns not yet sealed into
152
+ /// History; a send past it fails with `store_full`. Default 32 MiB, at most 1 GiB. nil = omitted.
153
+ public var instanceMaxBytes: Int?
154
+ // Founder 2026-11-19, B27.
155
+ /// The app wiki's limits: the largest document in markdown bytes
156
+ /// (default 64 KiB; a larger one is refused, so split it) and the wiki's total (default
157
+ /// 8 MiB). nil = omitted; Core validates and applies the defaults.
158
+ public var wikiDocumentMaxBytes: Int?
159
+ /// The wiki's total size limit (default 8 MiB). See `wikiDocumentMaxBytes`.
160
+ public var wikiMaxBytes: Int?
161
+ // B27.
162
+ /// App-wide input and scheduling guards for every agent. Only app code sets them: a bundle cannot
163
+ /// set them. nil = omitted; Core validates and applies the defaults.
164
+ public var limits: LimitsOptions?
165
+ /// Creates open options. Each `nil` is omitted, so Core applies its default.
166
+ public init(projectKey: String, bundledConfig: JSON, user: String? = nil, language: String? = nil,
167
+ tools: [ToolRegistration]? = nil, wiki: [WikiDoc]? = nil, adapters: [any Adapter]? = nil,
168
+ serverKey: String? = nil, developmentKey: String? = nil, archive: ArchiveOptions? = nil,
169
+ retentionBytes: Int? = nil, instanceMaxBytes: Int? = nil,
170
+ wikiDocumentMaxBytes: Int? = nil, wikiMaxBytes: Int? = nil, limits: LimitsOptions? = nil) {
171
+ self.projectKey = projectKey; self.bundledConfig = bundledConfig; self.user = user; self.language = language
172
+ self.tools = tools; self.wiki = wiki; self.adapters = adapters; self.serverKey = serverKey; self.developmentKey = developmentKey; self.archive = archive
173
+ self.retentionBytes = retentionBytes
174
+ self.instanceMaxBytes = instanceMaxBytes
175
+ self.wikiDocumentMaxBytes = wikiDocumentMaxBytes; self.wikiMaxBytes = wikiMaxBytes
176
+ self.limits = limits
177
+ }
178
+ /// The WHOLE options as JSON (Atlas's S1 ABI): only the opaque tool and storage references
179
+ /// become null; the tools themselves travel beside it as registrations, in this order.
180
+ var json: JSON {
181
+ var fields: [String: JSON] = ["projectKey": .string(projectKey), "bundledConfig": bundledConfig]
182
+ if let user { fields["user"] = .string(user) }
183
+ if let language { fields["language"] = .string(language) }
184
+ if let tools { fields["tools"] = .array(tools.map(\.json)) }
185
+ if let wiki { fields["wiki"] = .array(wiki.map(\.json)) }
186
+ if let adapters { fields["adapters"] = .array(adapters.map { .object(["kind": .string($0.kind)]) }) }
187
+ if let serverKey { fields["serverKey"] = .string(serverKey) }
188
+ if let developmentKey { fields["developmentKey"] = .string(developmentKey) }
189
+ if let archive { fields["archive"] = archive.json }
190
+ if let retentionBytes { fields["retentionBytes"] = .number(Double(retentionBytes)) }
191
+ if let instanceMaxBytes { fields["instanceMaxBytes"] = .number(Double(instanceMaxBytes)) }
192
+ if let wikiDocumentMaxBytes { fields["wikiDocumentMaxBytes"] = .number(Double(wikiDocumentMaxBytes)) }
193
+ if let wikiMaxBytes { fields["wikiMaxBytes"] = .number(Double(wikiMaxBytes)) }
194
+ if let limits { fields["limits"] = limits.json }
195
+ return .object(fields)
196
+ }
197
+ }
198
+
199
+ /// `OpenOptions.limits`: each nil field is omitted and Core applies its default.
200
+ public struct LimitsOptions: Sendable, Equatable {
201
+ /// Total user and app-event text of one send, 1_000...200_000 UTF-16 units (default 32_000).
202
+ public var userTextChars: Int?
203
+ /// Total app-state text of one send, 1_000...200_000 (default 32_000).
204
+ public var appStateChars: Int?
205
+ /// One tool result's value as compact JSON, 1_000...1_000_000 (default 200_000).
206
+ public var toolResultChars: Int?
207
+ /// Images per message or tool result, 1...16 (default 4). Image byte limits stay fixed.
208
+ public var turnImages: Int?
209
+ /// Schedule notes pending at once, 1...20 (default 20).
210
+ public var pendingSchedules: Int?
211
+ /// Creates limits; each `nil` keeps Core's default.
212
+ public init(userTextChars: Int? = nil, appStateChars: Int? = nil, toolResultChars: Int? = nil,
213
+ turnImages: Int? = nil, pendingSchedules: Int? = nil) {
214
+ self.userTextChars = userTextChars; self.appStateChars = appStateChars
215
+ self.toolResultChars = toolResultChars; self.turnImages = turnImages
216
+ self.pendingSchedules = pendingSchedules
217
+ }
218
+ var json: JSON {
219
+ var value: [String: JSON] = [:]
220
+ if let userTextChars { value["userTextChars"] = .number(Double(userTextChars)) }
221
+ if let appStateChars { value["appStateChars"] = .number(Double(appStateChars)) }
222
+ if let toolResultChars { value["toolResultChars"] = .number(Double(toolResultChars)) }
223
+ if let turnImages { value["turnImages"] = .number(Double(turnImages)) }
224
+ if let pendingSchedules { value["pendingSchedules"] = .number(Double(pendingSchedules)) }
225
+ return .object(value)
226
+ }
227
+ }
228
+
229
+ /// `Croche.registerBackground`. `storage` = the one `open()` uses.
230
+ public struct BackgroundOptions: Sendable {
231
+ /// Let the app react when scheduled work was delivered or could not run.
232
+ public var sink: (@Sendable (BackgroundEvent) -> Void)?
233
+ /// The same adapters as `open`, so background work uses the same stores.
234
+ public var adapters: [any Adapter]?
235
+ /// Creates background options.
236
+ public init(sink: (@Sendable (BackgroundEvent) -> Void)? = nil, adapters: [any Adapter]? = nil) {
237
+ self.sink = sink; self.adapters = adapters
238
+ }
239
+ /// The opaque sink and selected StateStore become null transport markers.
240
+ var json: JSON {
241
+ var fields: [String: JSON] = [:]
242
+ if sink != nil { fields["sink"] = .null }
243
+ if adapters?.contains(where: { $0.kind == "state" }) == true { fields["storage"] = .null }
244
+ return .object(fields)
245
+ }
246
+ }
247
+
248
+ /// `croche.deleteData(_:)` on an opened Croche: `{agent}`, `{agent, instance}` or `{}`. Core rejects
249
+ /// `{instance}` alone. A recovery handle accepts only `{}` or no scope.
250
+ public struct DataScope: Sendable {
251
+ /// The agent whose data to delete: its default and named instances.
252
+ public var agent: String?
253
+ /// One named instance of `agent`. Requires `agent`.
254
+ public var instance: String?
255
+ /// Creates a deletion scope.
256
+ public init(agent: String? = nil, instance: String? = nil) { self.agent = agent; self.instance = instance }
257
+ var json: JSON {
258
+ var fields: [String: JSON] = [:]
259
+ if let agent { fields["agent"] = .string(agent) }
260
+ if let instance { fields["instance"] = .string(instance) }
261
+ return .object(fields)
262
+ }
263
+ }
264
+
265
+ extension Scope {
266
+ func json(_ entry: (Entry) -> JSON) -> JSON {
267
+ switch self {
268
+ case .all: .string("all")
269
+ case .list(let entries): .array(entries.map(entry))
270
+ }
271
+ }
272
+ }
273
+
274
+ /// The second argument of `Croche.open(_:recovery:)`. Swift serializes `{"recover": recover}`;
275
+ /// Core alone validates it (`"delete"` today; anything else is `invalid_request`).
276
+ public struct RecoveryOptions: Sendable, Equatable {
277
+ /// The recovery mode: `"delete"`.
278
+ public let recover: String
279
+ /// Creates recovery options.
280
+ public init(recover: String) { self.recover = recover }
281
+ var json: JSON { .object(["recover": .string(recover)]) }
282
+ }
283
+
284
+
285
+ /// The options of every paged public list: `listAttachments`, `memory.list` and `wiki.list`.
286
+ /// `limit` is a positive integer; a page holds at most 128 items, which is also the
287
+ /// default. `cursor` is the cursor of the previous page of the same list.
288
+ public struct ListOptions: Sendable, Equatable {
289
+ /// Items per page, at most 128 (also the default).
290
+ public var limit: Int?
291
+ /// The previous page's ``Page/cursor``; `nil` starts from the beginning.
292
+ public var cursor: String?
293
+ /// Creates list options.
294
+ public init(limit: Int? = nil, cursor: String? = nil) {
295
+ self.limit = limit
296
+ self.cursor = cursor
297
+ }
298
+ /// The `{limit?, cursor?}` text Core reads. The limit is written as an integer.
299
+ var optionsJson: String {
300
+ var fields: [String] = []
301
+ if let limit { fields.append("\"limit\":\(limit)") }
302
+ if let cursor { fields.append("\"cursor\":" + text(.string(cursor))) }
303
+ return "{" + fields.joined(separator: ",") + "}"
304
+ }
305
+ }
306
+
307
+ /// One page of a public list, in the list's stable order. `cursor` is present only when more
308
+ /// items follow: pass it back to the same list to continue strictly past this page.
309
+ public struct Page<Item: Sendable>: Sendable {
310
+ /// This page's items.
311
+ public var items: [Item]
312
+ /// Pass back as ``ListOptions/cursor`` for the next page; `nil` when no items follow.
313
+ public var cursor: String?
314
+ /// Creates a page.
315
+ public init(items: [Item], cursor: String? = nil) {
316
+ self.items = items
317
+ self.cursor = cursor
318
+ }
319
+ }
320
+
321
+ /// Reads Core's `{items, cursor?}` reply, turning each item with `item`.
322
+ func page<Item: Sendable>(_ replyText: String, _ what: String, _ item: (JSON) throws -> Item) throws -> Page<Item> {
323
+ let value = try reply(replyText)
324
+ guard let items = value["items"].array else { throw malformed(what) }
325
+ return Page(items: try items.map(item), cursor: value["cursor"].string)
326
+ }
327
+
328
+
329
+ /// App-wide host policy; the byte budget applies separately to every instance.
330
+ public struct ArchiveOptions: Sendable {
331
+ /// History budget per instance in bytes: 64 KiB to 1 GiB, default 8 MiB. Older records can be evicted to stay within it.
332
+ public var maxBytes: Double?
333
+ /// Budget for retired summary pieces and saved memory facts per instance: 64 KiB to 1 GiB, default 4 MiB.
334
+ public var notesMaxBytes: Double?
335
+ /// Creates archive options; each `nil` keeps the default.
336
+ public init(maxBytes: Double? = nil, notesMaxBytes: Double? = nil) {
337
+ self.maxBytes = maxBytes
338
+ self.notesMaxBytes = notesMaxBytes
339
+ }
340
+ var json: JSON {
341
+ var fields: [String: JSON] = [:]
342
+ if let maxBytes { fields["maxBytes"] = .number(maxBytes) }
343
+ if let notesMaxBytes { fields["notesMaxBytes"] = .number(notesMaxBytes) }
344
+ return .object(fields)
345
+ }
346
+ }
@@ -0,0 +1,89 @@
1
+ import Foundation
2
+
3
+ /// Core's one result envelope. A plugin's output remains arbitrary JSON.
4
+ public enum RunToolResult: Sendable {
5
+ /// The tool ran and returned a value.
6
+ public struct Ok: Sendable {
7
+ /// The call id passed to `runTool`.
8
+ public let id: String
9
+ /// The tool's output, as the tool returned it.
10
+ public let output: JSON
11
+ /// Files the tool produced.
12
+ public let attachments: [AppStreamContract.Attachment]
13
+ /// Cost in credits; `nil` unless reported.
14
+ public let cost: Double?
15
+ /// `reported`, `unknown`, `none`, or a status this SDK does not know yet.
16
+ public let costStatus: String
17
+ }
18
+ /// The tool ran and failed.
19
+ public struct Failed: Sendable {
20
+ /// The call id passed to `runTool`.
21
+ public let id: String
22
+ /// Core's error code.
23
+ public let code: String
24
+ /// Core's description of the failure.
25
+ public let message: String
26
+ /// The error's category.
27
+ public let category: ErrorCategory
28
+ /// Cost in credits; `nil` unless reported.
29
+ public let cost: Double?
30
+ /// `reported`, `unknown`, `none`, or a status this SDK does not know yet.
31
+ public let costStatus: String
32
+ }
33
+ /// The process stopped while this call was running, so its outcome is unknown. Core does not run the same id again.
34
+ public struct Lost: Sendable {
35
+ /// The call id passed to `runTool`.
36
+ public let id: String
37
+ /// `outcome_unknown`.
38
+ public let code: String
39
+ /// Core's description.
40
+ public let message: String
41
+ /// `.closed`.
42
+ public let category: ErrorCategory
43
+ }
44
+ /// See ``Ok``.
45
+ case ok(Ok)
46
+ /// See ``Failed``.
47
+ case failed(Failed)
48
+ /// See ``Lost``.
49
+ case lost(Lost)
50
+ /// A status this SDK does not know, with every field kept.
51
+ case unknown(status: String, fields: JSON)
52
+
53
+ init(_ value: JSON) throws {
54
+ func string(_ key: String) throws -> String {
55
+ guard let result = value[key].string else { throw malformed("runTool \(key)") }
56
+ return result
57
+ }
58
+ func category() throws -> ErrorCategory {
59
+ guard let result = ErrorCategory(rawValue: try string("category")) else { throw malformed("runTool category") }
60
+ return result
61
+ }
62
+ switch try string("status") {
63
+ case "ok":
64
+ guard value.object?["output"] != nil else { throw malformed("runTool output") }
65
+ let attachments = try JSONDecoder().decode([AppStreamContract.Attachment].self,
66
+ from: Data(text(value["attachments"]).utf8))
67
+ self = .ok(Ok(id: try string("id"), output: value["output"], attachments: attachments,
68
+ cost: value["cost"].number, costStatus: try string("costStatus")))
69
+ case "failed":
70
+ self = .failed(Failed(id: try string("id"), code: try string("code"), message: try string("message"),
71
+ category: try category(), cost: value["cost"].number, costStatus: try string("costStatus")))
72
+ case "lost":
73
+ self = .lost(Lost(id: try string("id"), code: try string("code"), message: try string("message"), category: try category()))
74
+ case let status: self = .unknown(status: status, fields: value)
75
+ }
76
+ }
77
+ }
78
+
79
+ public extension Croche {
80
+ /// Let an app button run a tool outside chat, such as generating an image for a form.
81
+ ///
82
+ /// Cancelling the Task detaches this caller; Core owns the dispatched effect.
83
+ func runTool(_ name: String, args: [String: JSON], id: String) async throws -> RunToolResult {
84
+ let core = try self.core, arguments = text(.object(args)), options = text(.object(["id": .string(id)]))
85
+ return try RunToolResult(reply(try await cancellable {
86
+ try core.runTool(name: name, argsJson: arguments, optionsJson: options, cancel: $0)
87
+ }))
88
+ }
89
+ }
@@ -0,0 +1,165 @@
1
+ import Foundation
2
+
3
+ /// Atomic app state. The condition and all writes share one transaction.
4
+ public protocol StateStore: Adapter {
5
+ /// Read saved state so a user can continue where they left off.
6
+ func get(_ key: String) async throws -> StateValue?
7
+ /// Load just the relevant records so a long conversation still opens promptly.
8
+ func list(_ prefix: String, _ options: StateListOptions?) async throws -> StatePage
9
+ /// Keep a saved reply and its related progress consistent if the app stops mid-write.
10
+ func commit(_ ops: [StateOp], _ condition: StateCondition) async throws -> StateCommitResult
11
+ }
12
+ public extension StateStore {
13
+ /// Always `"state"`.
14
+ var kind: String { "state" }
15
+ }
16
+
17
+ /// A stored value with its version.
18
+ public struct StateValue: Sendable, Equatable {
19
+ /// The stored text.
20
+ public let value: String
21
+ /// The store's opaque version of this key. Core passes it back unchanged in a ``StateCondition``.
22
+ public let version: String
23
+ /// Creates a stored value.
24
+ public init(value: String, version: String) { self.value = value; self.version = version }
25
+ }
26
+
27
+ /// A storage failure reports facts only (ARCHITECTURE §2/§2a, Leo 12:39Z): its text, for
28
+ /// debugging. No code or category crosses, whatever the app threw; Core reports `storage_error`.
29
+ func storageFailure(_ error: Error) -> CoreStorageFailure {
30
+ if let error = error as? CoreStorageFailure { return error }
31
+ if let error = error as? CrocheError { return .Failure(detail: error.message) }
32
+ if case let .Failure(_, message)? = error as? FfiError { return .Failure(detail: message) }
33
+ return .Failure(detail: "\(error)")
34
+ }
35
+
36
+ private extension Result where Failure == Error {
37
+ init(_ body: () async throws -> Success) async {
38
+ do { self = .success(try await body()) } catch { self = .failure(error) }
39
+ }
40
+ }
41
+
42
+ /// The platform default store as Core's storage argument (Keel 16:08Z): the argument always
43
+ /// carries a PAL, the app's or this one; Core has no storage default of its own. The options JSON
44
+ /// carries selected adapter-kind markers, so Core can tell the default from an app store.
45
+ final class PlatformStorageAdapter: CoreStoragePal, @unchecked Sendable {
46
+ let pal: PlatformPal
47
+ let state: (any StateStore)?
48
+
49
+ init(_ pal: PlatformPal, state: (any StateStore)? = nil) {
50
+ self.pal = pal
51
+ self.state = state
52
+ }
53
+
54
+ private func call<T>(_ body: () throws -> T) throws -> T {
55
+ do { return try body() } catch { throw storageFailure(error) }
56
+ }
57
+
58
+ private func wait<T: Sendable>(_ body: @escaping @Sendable () async throws -> T) throws -> T {
59
+ let done = DispatchSemaphore(value: 0)
60
+ nonisolated(unsafe) var result: Result<T, Error>!
61
+ appTask { result = await Result { try await body() }; done.signal() }
62
+ done.wait()
63
+ do { return try result.get() } catch { throw storageFailure(error) }
64
+ }
65
+
66
+ func commitState(ops: [CoreStateOp], condition: CoreStateCondition) throws -> CoreStateCommit {
67
+ let batch = ops.map { $0.app() }, guardValue = condition.app()
68
+ return try call {
69
+ guard let state else { return try pal.commitState(ops: batch, condition: guardValue).core() }
70
+ try validateStateBatch(batch, guardValue)
71
+ return try wait { try await state.commit(batch, guardValue) }.core()
72
+ }
73
+ }
74
+
75
+ func listState(prefix: String, options: CoreStateListOptions) throws -> CoreStatePage {
76
+ let range = options.app()
77
+ return try call {
78
+ guard let state else { return try pal.listState(prefix: prefix, options: range).core() }
79
+ _ = try StateRange(prefix: prefix, options: StateListOptions(start: range.start, reverse: range.reverse, limit: range.limit))
80
+ return try wait { try await state.list(prefix, range) }.core()
81
+ }
82
+ }
83
+
84
+ func readVersioned(key: String) throws -> CoreVersionedValue {
85
+ try call {
86
+ guard let state else { return try pal.readVersioned(key: key) }
87
+ try validateStateKey(key)
88
+ let row = try wait { try await state.get(key) }
89
+ return try VersionedValue(value: row?.value, version: row?.version).core()
90
+ }
91
+ }
92
+
93
+ func writeIf(key: String, value: String?, expect: String?) throws -> CoreWriteOutcome {
94
+ try call {
95
+ guard state != nil else { return try pal.writeIf(key: key, value: value, expect: expect) }
96
+ let op: CoreStateOp = value.map { .put(key: key, value: $0) } ?? .delete(key: key)
97
+ switch try commitState(ops: [op], condition: CoreStateCondition(key: key, version: expect)) {
98
+ case .committed(let version): return .written(version: version)
99
+ case .conflict: return .conflict(version: nil)
100
+ }
101
+ }
102
+ }
103
+
104
+ func read(key: String) throws -> String? {
105
+ guard state != nil else { return try call { try pal.read(key: key) } }
106
+ return try readVersioned(key: key).value
107
+ }
108
+
109
+ private func modify(_ key: String, _ value: String?) throws {
110
+ let version = try readVersioned(key: key).version
111
+ guard case .written = try writeIf(key: key, value: value, expect: version) else {
112
+ throw CoreStorageFailure.Failure(detail: "StateStore key changed before commit.")
113
+ }
114
+ }
115
+
116
+ func write(key: String, value: String) throws {
117
+ if state == nil { try call { try pal.write(key: key, value: value) } }
118
+ else { try modify(key, value) }
119
+ }
120
+ func remove(key: String) throws {
121
+ if state == nil { try call { try pal.remove(key: key) } }
122
+ else { try modify(key, nil) }
123
+ }
124
+
125
+ func list(prefix: String) throws -> [String] {
126
+ guard state != nil else { return try call { try pal.list(prefix: prefix) } }
127
+ var keys: [String] = [], cursor: String?
128
+ var seen = Set<String>()
129
+ repeat {
130
+ let page = try listState(prefix: prefix, options: CoreStateListOptions(start: nil, reverse: false, limit: nil, cursor: cursor))
131
+ for row in page.entries {
132
+ guard row.key.hasPrefix(prefix), keys.last.map({ $0 < row.key }) ?? true else {
133
+ throw CoreStorageFailure.Failure(detail: "StateStore returned invalid list order or scope.")
134
+ }
135
+ keys.append(row.key)
136
+ }
137
+ cursor = page.nextCursor
138
+ if let cursor, !seen.insert(cursor).inserted {
139
+ throw CoreStorageFailure.Failure(detail: "StateStore cursor did not advance.")
140
+ }
141
+ } while cursor != nil
142
+ return keys
143
+ }
144
+
145
+ func purgeInstance(prefix: String, secretKey: String?) throws {
146
+ try call {
147
+ try pal.purgeStorage(prefix: prefix, localState: state == nil, localSecret: true, deleteState: {
148
+ if state != nil {
149
+ for key in try list(prefix: prefix) { try modify(key, nil) }
150
+ }
151
+ })
152
+ }
153
+ }
154
+ func lock(name: String) throws -> PalLockOutcome { try call { try pal.lock(key: name) } }
155
+ func unlock(name: String) throws { pal.unlock(key: name) }
156
+ func readSecret(key: String) throws -> String? {
157
+ return try call { try pal.readSecret(key: key) }
158
+ }
159
+ func writeSecret(key: String, value: String) throws {
160
+ try call { try pal.writeSecret(key: key, value: value) }
161
+ }
162
+ func removeSecret(key: String) throws {
163
+ try call { try pal.removeSecret(key: key) }
164
+ }
165
+ }