@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
@@ -3,19 +3,19 @@ import Foundation
3
3
  import UIKit
4
4
  #endif
5
5
 
6
- public struct ToolContext: Sendable {
7
- public let data: JSON
8
- public let cancellation: RuntimeCancellation
9
- public var callId: String { data["callId"].string ?? "" }
10
- public var messageId: String { data["messageId"].string ?? "" }
6
+ struct LegacyToolContext: Sendable {
7
+ let data: JSON
8
+ let cancellation: RuntimeCancellation
9
+ var callId: String { data["callId"].string ?? "" }
10
+ var messageId: String { data["messageId"].string ?? "" }
11
11
  /// The opaque user id Croche issued; "" until Cloud has issued it.
12
- public var userId: String { data["userId"].string ?? "" }
12
+ var userId: String { data["userId"].string ?? "" }
13
13
  /// Present when the Runtime config has an agentId.
14
- public var agentId: String? { data["agentId"].string }
15
- public var user: String? { data["user"].string }
16
- public var crocheUserId: String? { data["crocheUserId"].string }
17
- public var causedBy: [String] { data["causedBy"].array?.compactMap(\.string) ?? [] }
18
- public var origin: String { data["origin"].string ?? "" }
14
+ var agentId: String? { data["agentId"].string }
15
+ var user: String? { data["user"].string }
16
+ var crocheUserId: String? { data["crocheUserId"].string }
17
+ var causedBy: [String] { data["causedBy"].array?.compactMap(\.string) ?? [] }
18
+ var origin: String { data["origin"].string ?? "" }
19
19
  /// Where a `withResult` handler leaves its images for this call.
20
20
  let images: ImageSink?
21
21
  init(data: JSON, cancellation: RuntimeCancellation, images: ImageSink? = nil) {
@@ -24,14 +24,14 @@ public struct ToolContext: Sendable {
24
24
  }
25
25
  /// An app command's handler. An async handler must not block its thread: a blocked thread can
26
26
  /// stall the Runtime's own requests. Await instead, or wrap blocking work in `blockingTool`.
27
- public typealias ToolHandler = @Sendable (_ invocation: JSON, _ context: ToolContext) async throws -> JSON
27
+ typealias ToolHandler = @Sendable (_ invocation: JSON, _ context: LegacyToolContext) async throws -> JSON
28
28
 
29
29
  /// A handler for work that blocks its thread (synchronous I/O, a lock, a sleep). It runs on a
30
30
  /// thread of its own, never on Swift's cooperative pool, on every OS. The call keeps its slot
31
31
  /// until `body` returns, however long after a cancel; observe `context.cancellation` to stop.
32
32
  ///
33
33
  /// tools: ["save": blockingTool { invocation, context in try database.write(invocation) }]
34
- public func blockingTool(_ body: @escaping @Sendable (_ invocation: JSON, _ context: ToolContext) throws -> JSON) -> ToolHandler {
34
+ func blockingTool(_ body: @escaping @Sendable (_ invocation: JSON, _ context: LegacyToolContext) throws -> JSON) -> ToolHandler {
35
35
  { invocation, context in
36
36
  try await withCheckedThrowingContinuation { continuation in
37
37
  let thread = Thread { continuation.resume(with: Result { try body(invocation, context) }) }
@@ -46,390 +46,26 @@ public func blockingTool(_ body: @escaping @Sendable (_ invocation: JSON, _ cont
46
46
  /// `summary`, `keywords` and `agents` (only those agents see the document); `agents` given here
47
47
  /// overrides the frontmatter's. An agent's own path globs are config: `"wiki": {"include": [...],
48
48
  /// "exclude": [...]}`.
49
- public struct WikiDocument: Sendable, Equatable {
50
- public let path: String
51
- public let markdown: String
52
- public let agents: [String]?
53
- public init(path: String, markdown: String, agents: [String]? = nil) {
49
+ struct WikiDocument: Sendable, Equatable {
50
+ let path: String
51
+ let markdown: String
52
+ let agents: [String]?
53
+ init(path: String, markdown: String, agents: [String]? = nil) {
54
54
  self.path = path; self.markdown = markdown; self.agents = agents
55
55
  }
56
56
  }
57
57
 
58
- /// The Croche Runtime for Swift. The Rust Core (crates/croche-ffi) is the Runtime: it holds
59
- /// the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
60
- /// Swift types; `SwiftHost` performs what only the platform can (the PAL). Pass only
61
- /// serializable Runtime configuration in config.
62
- public actor CrocheRuntime {
63
- nonisolated let core: CoreRuntime
64
- let host: SwiftHost
65
- nonisolated let memoryCache = RuntimeMemoryCache()
66
- private var closed = false
67
- var subscriptionHub: StreamHub?
68
- public nonisolated let logId: String
69
- #if canImport(UIKit) && os(iOS)
70
- private var foreground: (any NSObjectProtocol)?
71
- #endif
72
-
73
- private var onDelivery: (@Sendable (JSON) -> Void)?
74
- private init(core: CoreRuntime, host: SwiftHost, logId: String) { self.core = core; self.host = host; self.logId = logId }
75
- private func bind(_ hub: StreamHub) { subscriptionHub = hub }
76
- /// INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
77
- /// module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
78
- /// delivery turn (`ran: true`), whoever called it (the timer, a background run, the foreground,
79
- /// the app), once the turn is in `inspect()`'s history. Interim: the public subscription for
80
- /// agent-initiated messages (F25 on #264: `onBackgroundMessage` with replay on open) replaces it.
81
- @_spi(CrocheBridge)
82
- public func observeDeliveries(_ observer: (@Sendable (JSON) -> Void)?) { onDelivery = observer }
83
- /// `secrets` keeps the Runtime credential apart from `storage`: KeychainSecretStore on
84
- /// Apple platforms. `attestor` proves the genuine app to Cloud when the project requires
85
- /// it: AppAttestAttestor on a device; nil on a simulator or a host that cannot attest.
86
- /// `http` replaces the default URLSession transport with one that answers whole requests.
87
- /// `wiki` is the documents, set at open; this agent's path filter is the config's
88
- /// `"wiki": {"include": [...], "exclude": [...]}`.
89
- /// `onEvent` hears one `turn.started` per turn; a send carried into a running turn at a later
90
- /// model call is `{type:"turn.joined", turnId, inputIds}` (the ids newly carried).
91
- /// `onUsage` receives every paid call's cost (`{type:"usage", operationId, purpose, causedBy, instance, model,
92
- /// costUsd, costStatus, tokens?}`; `tokens` holds the reported counts, e.g. `prompt`, `cached`),
93
- /// `instance` is the named/generated instance key, or null for the main agent.
94
- /// `purpose` is "model" or "summary"; `causedBy` holds the inputs served (empty for upkeep).
95
- /// `model` is the gateway-reported answering model (`modelSource: "response"`), or the
96
- /// request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
97
- /// present only when different. Reported cost is unchanged by a model substitution.
98
- /// at least once, from the start: open itself reports a call the process
99
- /// died during. It runs on a Runtime thread; do not call the Runtime from it.
100
- /// `scheduler` registers the agent's scheduled notes with the OS for when the app is not
101
- /// running: `AppRefreshScheduler` (BGTaskScheduler) on iOS; nil elsewhere, where a timer
102
- /// delivers them while the Runtime is open and the next open delivers what fell due meanwhile.
103
- /// On iOS the Runtime also calls `deliverDue()` each time the app enters the foreground. A
104
- /// scheduler whose identifier another open Runtime holds refuses this one
105
- /// (`scheduler_conflict`).
106
- /// `projectDirectory` is required on Linux, which has no app-private default.
107
- /// On Apple platforms it must be nil: the record stays in Application Support.
108
- public static func create(config: JSON, storage: any RuntimeStorage, secrets: any RuntimeSecretStore,
109
- attestor: (any RuntimeAttestor)? = nil,
110
- tools: [String: ToolHandler] = [:],
111
- http: RuntimeHTTP? = nil,
112
- onEvent: (@Sendable (JSON) -> Void)? = nil,
113
- onDebugEvent: (@Sendable (JSON) -> Void)? = nil,
114
- onUsage: (@Sendable (JSON) -> Void)? = nil,
115
- backgroundSync: Bool = true,
116
- maintenanceInterval: TimeInterval = 60,
117
- wiki: [WikiDocument]? = nil,
118
- scheduler: (any RuntimeScheduler)? = nil,
119
- projectDirectory: URL? = nil) async throws -> CrocheRuntime {
120
- let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
121
- let interval = try clampedMaintenanceInterval(maintenanceInterval)
122
- warnIfReleaseBuildCarriesDebugKey(config)
123
- var bound = config
124
- bound["attestationPlatform"] = attestor.map { .string($0.platform) } ?? .null
125
- let host = SwiftHost(storage: storage, secrets: secrets, attestor: attestor, http: http, tools: tools,
126
- background: backgroundSync, scheduler: scheduler, projectRecords: records)
127
- // The app chose the store, so the Runtime binds its identity to it (a custom storage key).
128
- let options = RuntimeOpenOptions(storageKey: "croche.swift", streaming: config["streaming"].bool ?? true,
129
- backgroundSync: backgroundSync,
130
- maintenanceIntervalMs: interval * 1000)
131
- let configText = String(decoding: try bound.encoded(), as: UTF8.self)
132
- let listener = onEvent.map { EventHook($0) }
133
- let usage = onUsage.map { EventHook($0) }
134
- try host.attachScheduler()
135
- // From here the host's stop (close, or a failed open) detaches the scheduler, once.
136
- let core: CoreRuntime
137
- do { core = try await offload { try CoreRuntime.open(pal: host, config: configText, options: options, onEvent: listener, onUsage: usage) } }
138
- catch { host.stop(); host.session.close(); throw error }
139
- if let onDebugEvent { try? core.setDebugObserver(observer: EventHook(onDebugEvent), full: false) }
140
- let hub: StreamHub
141
- do { hub = try await offload { try StreamHub(port: FFIStreamPort(core: core)) } }
142
- catch { _ = try? await offload { core.close(); return true }; host.stop(); host.session.close(); throw error }
143
- let runtime = CrocheRuntime(core: core, host: host, logId: hub.logId)
144
- await runtime.bind(hub)
145
- try await runtime.refreshMemory()
146
- host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
147
- host.attach(core)
148
- #if canImport(UIKit) && os(iOS)
149
- await runtime.observeForeground()
150
- #endif
151
- if let wiki {
152
- do { try await runtime.wiki.set(wiki) } catch { try? await runtime.close(); throw error }
153
- }
154
- return runtime
155
- }
156
- /// Adopts the Core returned by CoreProject; it never opens a second Runtime.
157
- static func adopt(core: CoreRuntime, host: SwiftHost) async throws -> CrocheRuntime {
158
- let hub: StreamHub
159
- do { hub = try await offload { try StreamHub(port: FFIStreamPort(core: core)) } }
160
- catch { _ = try? await offload { core.close(); return true }; host.stop(); host.session.close(); throw error }
161
- let runtime = CrocheRuntime(core: core, host: host, logId: hub.logId)
162
- await runtime.bind(hub)
163
- try await runtime.refreshMemory()
164
- host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
165
- host.attach(core)
166
- #if canImport(UIKit) && os(iOS)
167
- await runtime.observeForeground()
168
- #endif
169
- return runtime
170
- }
171
-
172
- func refreshMemory() async throws { memoryCache.set(try inspect()["memory"]) }
173
-
174
- /// The founder's condition for debug keys: never silent in a shipped build.
175
- static func warnIfReleaseBuildCarriesDebugKey(_ config: JSON) {
176
- #if !DEBUG
177
- if config["debugKey"].string != nil {
178
- FileHandle.standardError.write(Data("[Croche] A debug key (debugKey) is set in a RELEASE build. It admits any install of this project without App Attest and must not ship.\n".utf8))
179
- }
180
- #endif
181
- }
182
- public static func identity(config: JSON) throws -> JSON {
183
- do { return publicStorageIdentity(try JSON(ffiIdentity(String(decoding: try config.encoded(), as: UTF8.self)))) }
184
- catch { throw CrocheError(error) }
185
- }
186
- /// The Runtime's calls block their thread while the host performs effects: run them on a
187
- /// thread of their own, never on the cooperative pool or the main thread.
188
- /// Croche's own tests: runs first on each offload thread, so a test can delay it the way the
189
- /// OS may (#346). Nil in every app.
190
- nonisolated(unsafe) static var offloadStarting: (@Sendable () -> Void)?
191
- static func offload<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
192
- try await withCheckedThrowingContinuation { continuation in
193
- Thread.detachNewThread {
194
- offloadStarting?()
195
- do { continuation.resume(returning: try body()) }
196
- catch { continuation.resume(throwing: CrocheError(error)) }
197
- }
198
- }
199
- }
200
- fileprivate static func offloaded<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
201
- try await offload(body)
202
- }
203
- fileprivate func run(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
204
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
205
- let core = self.core
206
- return try JSON(try await Self.offload { try body(core) })
207
- }
208
- /// Runs one turn. Cancelling the calling Task cancels this turn only (from any thread, never
209
- /// missed): it ends `cancelled`, keeping what was said and charging an unanswered call.
210
- /// `responseFormat`: structured output, OpenAI's shape (`{"type":"json_schema",...}` or
211
- /// `{"type":"json_object"}`); the result's `output` is the reply as JSON the Core checked.
212
- ///
213
- /// Sends are admitted in the order the calls reach the Runtime (one task's sends in program
214
- /// order): that order is their place among held sends and in a turn they share.
215
- /// `imageResolution`: for every image that does not name its own (default standard).
216
- public func send(_ input: JSON, responseFormat: JSON? = nil, imageResolution: ImageResolution? = nil) async throws -> JSON {
217
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
218
- // Admitted here, on the actor, before the hop to a thread of its own.
219
- return try await beginSend(input, responseFormat: responseFormat, imageResolution: imageResolution).result()
220
- }
221
- /// Admits a send at once on the calling thread, without waiting for its turn: for a host
222
- /// that must fix the order of sends before hopping threads (the React Native bridge).
223
- nonisolated func beginSend(_ input: JSON, responseFormat: JSON? = nil, imageResolution: ImageResolution? = nil) throws -> PendingTurn {
224
- // Standard images are re-encoded here, before admission, so sends keep their order.
225
- let input = Images.prepareInput(input, fallback: imageResolution)
226
- let text = String(decoding: try input.encoded(), as: UTF8.self)
227
- let format = try responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
228
- let token = CancelToken()
229
- do { return PendingTurn(try core.beginSend(input: text, cancel: token, responseFormat: format), token) }
230
- catch { throw CrocheError(error) }
231
- }
232
- public func sync() async throws -> JSON { try await run { try $0.sync(); return "null" } }
233
- /// One round of background upkeep: deliver the outbox of call reports, then sync balances,
234
- /// policy and the model key. The Core does work only when some is due and backs off after
235
- /// a failure. It runs by itself after each turn and on a timer (backgroundSync); call it
236
- /// when the app returns to the foreground. It never delays a turn: a send takes over
237
- /// while it waits on Cloud. Never throws; the result says what happened.
238
- @discardableResult
239
- public func maintain(force: Bool = false) async -> JSON {
240
- (try? await run { $0.maintain(force: force) }) ?? .object(["ran": .bool(false)])
241
- }
242
- /// Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
243
- /// is (no turn, no cost) or one is already being delivered, else `{ran, ids, delivered, turn}`.
244
- /// Never before a note's time. The iOS Runtime calls it at every foreground; elsewhere, call
245
- /// it when the app returns.
246
- ///
247
- /// Cancelling the calling Task cancels this delivery only: waiting behind another turn, it
248
- /// leaves without running; running, its turn stops. Either way its notes stay pending.
249
- /// Cancelled after the delivery ended, nothing happens: never another turn (`cancel()` stops
250
- /// whatever turn runs).
251
- ///
252
- /// Afterwards the pending set is handed to the OS scheduler again (a refusal is reported as
253
- /// `schedule.degraded`): the OS spends a request when it runs it, and a delivery cut short
254
- /// leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
255
- /// ends. A failed delivery that answers `retryAt` waits until then.
256
- @discardableResult
257
- public func deliverDue() async throws -> JSON {
258
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
259
- host.attempted()
260
- let core = self.core
261
- let token = CancelToken()
262
- let result: JSON
263
- do {
264
- result = try await withTaskCancellationHandler {
265
- try JSON(try await Self.offload { try core.deliverDue(cancel: token) })
266
- } onCancel: { token.cancel() }
267
- } catch { await resync(); throw error }
268
- if result["inFlight"].bool == true { return result }
269
- if let retry = retryAt(result["retryAt"]) { host.retryAfter(retry) }
270
- await resync()
271
- if result["ran"].bool == true { onDelivery?(result) }
272
- return result
273
- }
274
- /// Hands the pending set to the OS scheduler again, through the Core, which reports a refusal
275
- /// as `schedule.degraded`.
276
- private func resync() async {
277
- guard !closed else { return }
278
- let core = self.core
279
- _ = try? await Self.offload { try core.reschedule(); return true }
280
- }
281
- #if canImport(UIKit) && os(iOS)
282
- private func observeForeground() {
283
- foreground = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification,
284
- object: nil, queue: nil) { [weak self] _ in
285
- Task { _ = try? await self?.deliverDue() }
286
- }
287
- }
288
- #endif
289
- /// The agent's pending scheduled notes: `{pending: [{id, at, note}], due}`.
290
- public func schedules() async throws -> JSON { try await run { try $0.schedules() } }
291
- public func flush() async throws -> JSON { try await run { try $0.flush(); return "null" } }
292
- /// Forgets this user's conversation and memory and starts over (money and identity stay).
293
- /// The clear takes its place on the actor, as `send` does: behind a running turn, ahead of
294
- /// every send that reaches the Runtime after it. Only the wait for it is on a thread of its own.
295
- public func clearHistory() async throws {
296
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
297
- if let subscriptionHub { try await subscriptionHub.clearHistory(); return }
298
- try await Self.finish(beginClearHistory())
299
- }
300
- /// Admits a clear at once on the calling thread, for a host that must fix its order against
301
- /// sends before hopping threads (the React Native bridge); `finish` then waits for it.
302
- nonisolated func beginClearHistory() -> PendingClear { core.beginClearHistory() }
303
- /// Waits for an admitted clear on a thread of its own.
304
- static func finish(_ pending: PendingClear) async throws {
305
- _ = try await offload { try pending.finish(); return true }
306
- }
307
- /// Asks Cloud to raise (or, `absolute`, set) this user's allowance within the project's
308
- /// ceilings. Pass `id` (e.g. the purchase id) to make a retry safe: Cloud applies it once.
309
- /// Called while another operation runs, it answers `{deferred: true}` at once instead (see
310
- /// `WriteResult`).
311
- public func adjustBudget(_ amount: Double, absolute: Bool = false, id: String? = nil) async throws -> JSON {
312
- try await run { try $0.adjustBudget(amount: amount, absolute: absolute, id: id) }
313
- }
314
- /// Internal until `memory history` (B3): turns `from...to` from the turn archive, as
315
- /// `{"records":[...]}`; `archive_unavailable` when the storage keeps none.
316
- func archiveRead(from: UInt64, to: UInt64) async throws -> JSON {
317
- try await run { try $0.archiveRead(from: from, to: to) }
318
- }
319
- /// Internal: deletes archived turns, every one without a range.
320
- func archiveClear(from: UInt64? = nil, to: UInt64? = nil) async throws {
321
- _ = try await run { try $0.archiveClear(from: from, to: to); return "null" }
322
- }
323
- public func inspect() throws -> JSON {
324
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
325
- do { return try JSON(try core.inspect()) } catch { throw CrocheError(error) }
326
- }
327
- /// Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
328
- /// The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
329
- /// its place in the queue, so turns sent before it still offer the old list. A removed or
330
- /// changed command answers `withdrawn` once the swap applies. A handler given here also
331
- /// serves turns already queued under the same name.
332
- public func setTools(_ tools: JSON, handlers: [String: ToolHandler]) throws {
333
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
334
- let text = String(decoding: try tools.encoded(), as: UTF8.self)
335
- // New names first: the Core cannot call them before it accepts the list. Replacements
336
- // only after it accepts; a refusal removes what it staged, so every handler is as it was.
337
- let stamp = host.stageTools(handlers)
338
- do { try core.setToolDeclarations(tools: text) } catch { host.unstageTools(handlers.keys, stamp: stamp); throw CrocheError(error) }
339
- host.acceptTools(handlers)
340
- }
341
- /// The tool list the model is offered (metadata only).
342
- public func tools() throws -> JSON { try inspect()["tools"] }
343
- /// Stops the running turn only: messages sent while it ran still go, together, as the next
344
- /// turn. Cancelling a send's Task drops just that send while it is held; once its turn has
345
- /// started, the turn stops, for every send it carries.
346
- public func cancel() { core.cancelTurn() }
347
- /// Drops the messages held behind the running turn (each send ends `cancelled`); returns how many.
348
- /// Resolves once the held record no longer lists them.
349
- @discardableResult public func clearQueued() async throws -> Int {
350
- guard !closed else { return 0 }
351
- let core = self.core
352
- return Int(try await Self.offload { try core.clearQueued() })
353
- }
354
- /// Long-term memory: `snapshot()` for a read-only view, the other methods to manage it.
355
- public nonisolated var memory: CrocheMemory { CrocheMemory(runtime: self) }
356
- /// The app's knowledge documents, held by the Rust Core in memory (never stored: load them
357
- /// on each open). The model searches and reads them with the built-in `wiki` command;
358
- /// `list`, `read` and `search` here are that same view.
359
- public nonisolated var wiki: CrocheWiki { CrocheWiki(runtime: self) }
360
- /// Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
361
- /// call upkeep has in flight is finished and settled first.
362
- /// The Core projection fence does not await buffered AsyncStream/UI consumers.
363
- /// An app callback that waits for work on the closer's thread deadlocks under any
364
- /// wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself.
365
- public func close() async throws {
366
- if closed { return }
367
- closed = true
368
- memoryCache.close()
369
- subscriptionHub?.close()
370
- host.stop()
371
- #if canImport(UIKit) && os(iOS)
372
- if let foreground { NotificationCenter.default.removeObserver(foreground) }
373
- foreground = nil
374
- #endif
375
- let core = self.core
376
- _ = try await Self.offload { core.close(); return true }
377
- // After the Core: a paid call upkeep has in flight is finished first.
378
- host.session.close()
379
- }
380
- }
381
-
382
- /// `runtime.memory`: this person's long-term memory, as the TS SDK's `runtime.memory`.
383
- public struct CrocheMemory: Sendable {
384
- fileprivate let runtime: CrocheRuntime
385
- /// The memory part of `inspect()`.
386
- public func callAsFunction() -> JSON { runtime.memoryCache.value }
387
- public func snapshot() async throws -> JSON { try await runtime.refreshMemory(); return callAsFunction() }
388
- private func refreshed(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
389
- let result = try await runtime.run(body)
390
- if result["deferred"].bool != true { try? await runtime.refreshMemory() }
391
- return result
392
- }
393
- /// AI-written facts with ids, turn/time stamps, refs and replacement links.
394
- public func list() async throws -> JSON { try await refreshed { try $0.memoryList() } }
395
- /// `{deleted}`, or `{deferred: true}` (see `WriteResult`).
396
- @discardableResult
397
- public func delete(_ id: String) async throws -> JSON { try await refreshed { try $0.memoryDelete(id: id) } }
398
- /// Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
399
- /// `{deferred: true}` (see `WriteResult`).
400
- @discardableResult
401
- public func clear() async throws -> JSON { try await refreshed { try $0.memoryClear() } }
402
- /// Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied, it
403
- /// carries the setting now in force.
404
- @discardableResult
405
- public func enabled(_ on: Bool) async throws -> WriteResult<Bool> {
406
- WriteResult(try await refreshed { try $0.memorySetEnabled(enabled: on) }) { _ in on }
407
- }
408
- /// Current and replaced AI-written facts: `{enabled, items}`, not the summary.
409
- public func export() async throws -> JSON { try await refreshed { try $0.memoryExport() } }
410
- /// Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's).
411
- public func onChanged(_ listener: (@Sendable (MemoryChangedEvent) -> Void)?) throws {
412
- guard !runtime.memoryCache.closed else { throw CrocheError("closed", "The agent is closed.") }
413
- do {
414
- runtime.core.setMemoryObserver(observer: listener.map { callback in EventHook { event in
415
- Task { try? await runtime.refreshMemory() }
416
- callback(event)
417
- } })
418
- }
419
- }
420
- }
421
-
422
58
  extension WikiDocument {
423
59
  /// The `.md` files under `directory` as wiki documents, paths relative to it with `/`
424
60
  /// (`menu/stew.md`), in name order. Subfolders are read; symbolic links and other files are
425
61
  /// skipped, as the other SDKs' loaders do.
426
- public static func fromDirectory(_ directory: URL) throws -> [WikiDocument] {
62
+ static func fromDirectory(_ directory: URL) throws -> [WikiDocument] {
427
63
  let files = FileManager.default
428
64
  var out: [WikiDocument] = []
429
65
  func walk(_ dir: URL, _ prefix: String) throws {
430
66
  let names: [String]
431
67
  do { names = try files.contentsOfDirectory(atPath: dir.path).sorted() }
432
- catch { throw CrocheError("invalid_wiki", "\(dir.path): \(error.localizedDescription)") }
68
+ catch { throw LegacyCrocheError("invalid_wiki", "\(dir.path): \(error.localizedDescription)") }
433
69
  for name in names {
434
70
  let url = dir.appendingPathComponent(name)
435
71
  let path = prefix.isEmpty ? name : prefix + "/" + name
@@ -438,7 +74,6 @@ extension WikiDocument {
438
74
  if type == .typeDirectory {
439
75
  try walk(url, path)
440
76
  } else if type == .typeRegular && name.hasSuffix(".md") {
441
- if out.count >= 2000 { throw CrocheError("invalid_wiki", "The wiki holds at most 2000 documents") }
442
77
  out.append(WikiDocument(path: path, markdown: String(decoding: try Data(contentsOf: url), as: UTF8.self)))
443
78
  }
444
79
  }
@@ -448,81 +83,20 @@ extension WikiDocument {
448
83
  }
449
84
  /// The documents in a folder shipped with the app (added to the target as a folder
450
85
  /// reference, so its subfolders survive): `WikiDocument.fromBundle()` reads `wiki/`.
451
- public static func fromBundle(_ bundle: Bundle = .main, folder: String = "wiki") throws -> [WikiDocument] {
86
+ static func fromBundle(_ bundle: Bundle = .main, folder: String = "wiki") throws -> [WikiDocument] {
452
87
  guard let url = bundle.url(forResource: folder, withExtension: nil) else {
453
- throw CrocheError("invalid_wiki", "No folder \(folder) in the bundle: add it to the target as a folder reference.")
88
+ throw LegacyCrocheError("invalid_wiki", "No folder \(folder) in the bundle: add it to the target as a folder reference.")
454
89
  }
455
90
  return try fromDirectory(url)
456
91
  }
457
92
  }
458
93
 
459
- /// `runtime.wiki`: the app's documents, as the TS SDK's `runtime.wiki`.
460
- public struct CrocheWiki: Sendable {
461
- fileprivate let runtime: CrocheRuntime
462
- private static func json(_ docs: [WikiDocument]) throws -> String {
463
- let value = JSON.array(docs.map { doc in
464
- var o: [String: JSON] = ["path": .string(doc.path), "markdown": .string(doc.markdown)]
465
- if let agents = doc.agents { o["agents"] = .array(agents.map { .string($0) }) }
466
- return .object(o)
467
- })
468
- return String(decoding: try value.encoded(), as: UTF8.self)
469
- }
470
- /// Replaces every document and answers what it installed: `{documents, bytes, digest}`.
471
- /// On an error nothing changes.
472
- @discardableResult
473
- public func set(_ docs: [WikiDocument]) async throws -> JSON {
474
- let text = try Self.json(docs)
475
- return try await runtime.run { try $0.wikiSet(docs: text) }
476
- }
477
- /// `set`, without the digest.
478
- public func load(_ docs: [WikiDocument]) async throws { try await set(docs) }
479
- /// This user's own documents (saved recipes, lesson notes): stored with their state (at most
480
- /// 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable when
481
- /// this returns. `clearHistory` keeps them. To share one with another character, put it to that character's Runtime too.
482
- /// Answers `{documents, bytes}`, or `{deferred: true}` (see `WriteResult`).
483
- @discardableResult
484
- public func putUser(_ docs: [WikiDocument]) async throws -> JSON {
485
- let text = try Self.json(docs)
486
- return try await runtime.run { try $0.wikiPutUser(docs: text) }
487
- }
488
- /// Removes one of this user's own documents; whether it existed.
489
- @discardableResult
490
- public func removeUser(_ path: String) async throws -> WriteResult<Bool> {
491
- WriteResult(try await runtime.run { try $0.wikiRemoveUser(path: path) }) { $0["removed"].bool ?? false }
492
- }
493
- /// Removes every one of this user's own documents; how many.
494
- @discardableResult
495
- public func clearUser() async throws -> WriteResult<Int> {
496
- WriteResult(try await runtime.run { try $0.wikiClearUser() }) { Int($0["cleared"].number ?? 0) }
497
- }
498
- /// Adds documents or replaces those with the same path, atomically.
499
- public func put(_ docs: [WikiDocument]) async throws {
500
- let text = try Self.json(docs)
501
- _ = try await runtime.run { try $0.wikiPut(docs: text); return "null" }
502
- }
503
- /// Whether the document existed.
504
- @discardableResult
505
- public func remove(_ path: String) async throws -> Bool {
506
- try await runtime.run { try $0.wikiRemove(path: path) ? "true" : "false" }.bool ?? false
507
- }
508
- /// `[{path, title, summary?, characters, parts}]` under `folder` (every document when nil).
509
- public func list(folder: String? = nil) async throws -> JSON { try await runtime.run { try $0.wikiList(folder: folder) } }
510
- /// One part (1-based) of a document, `{path, title, part, parts, text}`; `.null` when none.
511
- public func read(_ path: String, part: Int = 1) async throws -> JSON {
512
- try await runtime.run { try $0.wikiRead(path: path, part: UInt32(clamping: max(0, part))) }
513
- }
514
- /// The best matches, best first: at most `limit` (and 5).
515
- public func search(_ query: String, limit: Int = 5) async throws -> JSON {
516
- try await runtime.run { try $0.wikiSearch(query: query, limit: UInt32(clamping: min(max(0, limit), 5))) }
517
- }
518
- }
519
-
520
94
  /// What a write (memory, this user's own documents, the allowance) answers: `.applied`, with what
521
95
  /// it did, or `.deferred`: it was called while another operation ran, was accepted, and applies in
522
96
  /// call order when that operation ends. A message sent after the write sees it; one sent before
523
97
  /// does not. It is held in this process until then: closing first drops it, and a write that
524
98
  /// cannot apply then is reported as a `write.failed` debug event.
525
- public enum WriteResult<Value: Sendable>: Sendable {
99
+ enum WriteResult<Value: Sendable>: Sendable {
526
100
  case applied(Value)
527
101
  case deferred
528
102
 
@@ -534,18 +108,7 @@ extension WriteResult: Equatable where Value: Equatable {}
534
108
 
535
109
  /// A send `beginSend` admitted. Its result, once: `result()` blocks a thread of its own, and
536
110
  /// cancelling the awaiting Task cancels this send only.
537
- final class PendingTurn: Sendable {
538
- private let pending: PendingSend
539
- private let token: CancelToken
540
- fileprivate init(_ pending: PendingSend, _ token: CancelToken) { self.pending = pending; self.token = token }
541
- func result() async throws -> JSON {
542
- let pending = self.pending
543
- return try await withTaskCancellationHandler {
544
- try JSON(try await CrocheRuntime.offloaded { try pending.wait() })
545
- } onCancel: { [token] in token.cancel() }
546
- }
547
- func cancel() { token.cancel() }
548
- }
111
+
549
112
 
550
113
  final class RuntimeMemoryCache: @unchecked Sendable {
551
114
  private let lock = NSLock()
@@ -0,0 +1,42 @@
1
+ import Foundation
2
+
3
+ /// Shared app-transport adapter for S1 and the native bridge test host.
4
+ enum RuntimeHTTPAdapter {
5
+ /// An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
6
+ /// a response, and its stream deltas as server-sent events.
7
+ static func adapt(_ transport: RuntimeHTTP, _ request: PalHttpRequest, _ sink: HttpSink,
8
+ _ signal: RuntimeCancellation) async throws {
9
+ var headers: [String: JSON] = [:]
10
+ for header in request.headers { headers[header.name] = .string(header.value) }
11
+ let effect = JSON.object(["url": .string(request.url), "method": .string(request.method), "headers": .object(headers),
12
+ "body": request.body.map { (try? JSON($0)) ?? .string($0) } ?? .null,
13
+ "timeoutMs": .number(Double(request.timeoutMs))])
14
+ let streaming = StreamStart()
15
+ let reply = try await transport(effect, signal) { data in
16
+ if streaming.begin() {
17
+ sink.head(status: 200, headers: [PalHeader(name: "content-type", value: "text/event-stream")])
18
+ }
19
+ let frame = data.split(separator: "\n", omittingEmptySubsequences: false).map { "data: \($0)\n" }.joined() + "\n"
20
+ _ = sink.chunk(bytes: Data(frame.utf8))
21
+ }
22
+ let status = UInt16(reply["status"].number ?? 0)
23
+ var fields = (reply["headers"].object ?? [:]).compactMap { key, value in value.string.map { PalHeader(name: key, value: $0) } }
24
+ if reply["streamed"] == .bool(true) {
25
+ if streaming.begin() { sink.head(status: status, headers: [PalHeader(name: "content-type", value: "text/event-stream")]) }
26
+ return
27
+ }
28
+ fields.removeAll { $0.name.lowercased() == "content-type" }
29
+ fields.append(PalHeader(name: "content-type", value: "application/json"))
30
+ sink.head(status: status, headers: fields)
31
+ let body = reply["body"] != .null ? try reply["body"].encoded() : Data((reply["raw"].string ?? "").utf8)
32
+ if !body.isEmpty { _ = sink.chunk(bytes: body) }
33
+ }
34
+
35
+ }
36
+
37
+ private final class StreamStart: @unchecked Sendable {
38
+ private let lock = NSLock()
39
+ private var started = false
40
+ /// True once: the first caller starts the stream.
41
+ func begin() -> Bool { lock.withLock { if started { return false }; started = true; return true } }
42
+ }