@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,410 @@
1
+ import Foundation
2
+ #if canImport(CryptoKit)
3
+ import CryptoKit
4
+ #endif
5
+ #if canImport(ImageIO)
6
+ import ImageIO
7
+ #endif
8
+ #if canImport(UIKit)
9
+ import UIKit
10
+ #elseif canImport(AppKit)
11
+ import AppKit
12
+ #endif
13
+
14
+ /// Private native image PAL (Rev 4a), the Swift twin of the TypeScript `ImagePal`. Core owns
15
+ /// admission, sizing plans, budgets, deadlines and every URL; this only holds owned captures and
16
+ /// decodes/encodes to the plan Core gives. Names, codes and messages match TypeScript.
17
+ final class NativeImagePal: @unchecked Sendable {
18
+ // No size, byte or pixel limits of its own (Leo 18:40Z): Core owns admission and passes each
19
+ // bound it applies (read and plan maxBytes, render sizes). Only decoder facts refuse here.
20
+
21
+ private let lock = NSLock()
22
+ private var captures: [String: Data] = [:]
23
+ #if canImport(ImageIO)
24
+ /// Decoded pixels by handle: private to this process, never sent across the bridge.
25
+ private var decoded: [String: CGImage] = [:]
26
+ #endif
27
+ private var closed = false
28
+
29
+ /// A platform decoder is present (ImageIO). No I/O.
30
+ var codecAvailable: Bool {
31
+ #if canImport(ImageIO)
32
+ return true
33
+ #else
34
+ return false
35
+ #endif
36
+ }
37
+
38
+ /// Snapshot encoded bytes at the reserved entry boundary; returns the capture token.
39
+ func capture(_ bytes: Data) throws -> String {
40
+ let owned = Data(bytes) // Value copy: later caller mutation cannot reach it.
41
+ let token = UUID().uuidString
42
+ try lock.withLock {
43
+ if closed { throw LegacyCrocheError("closed", "The Runtime is closed.") }
44
+ captures[token] = owned
45
+ }
46
+ return token
47
+ }
48
+
49
+ /// Raw bytes only (#830 b4ace3eb): Core sniffs the MIME type and hashes.
50
+ func read(_ request: PalImageReadRequest, _ cancel: CancelToken) throws -> Data {
51
+ try Self.check(cancel)
52
+ let token: String
53
+ switch request.source {
54
+ case .capture(let value): token = value
55
+ case .local(let uri): return try Self.readLocal(uri, maxBytes: Int(request.maxBytes), cancel)
56
+ }
57
+ // A capture is taken once; a second read finds nothing.
58
+ let bytes = lock.withLock { captures.removeValue(forKey: token) }
59
+ guard let bytes, UInt64(bytes.count) <= request.maxBytes else { throw Self.failure("image_fetch_failed") }
60
+ try Self.check(cancel)
61
+ return bytes
62
+ }
63
+
64
+ func prepare(_ source: PalImageBytes, _ plan: PalImagePreparePlan, _ cancel: CancelToken) throws -> PalImageBytes {
65
+ try Self.check(cancel)
66
+ if let side = plan.maxSide, side < 1 { throw Self.failure("image_unsupported") }
67
+ guard codecAvailable else { throw Self.failure("image_unsupported") }
68
+ do {
69
+ return try Self.prepareVerified(source, maxSide: plan.maxSide.map(Int.init), maxBytes: Int(plan.maxBytes), cancel)
70
+ } catch {
71
+ try Self.check(cancel)
72
+ throw Self.failure("image_unsupported")
73
+ }
74
+ }
75
+
76
+ /// Idempotent.
77
+ func release(_ token: String) { lock.withLock { _ = captures.removeValue(forKey: token) } }
78
+
79
+ func close() {
80
+ lock.withLock {
81
+ closed = true; captures.removeAll()
82
+ #if canImport(ImageIO)
83
+ decoded.removeAll()
84
+ #endif
85
+ }
86
+ }
87
+
88
+ // MARK: Local URI (S3: iOS reads file:// only; ph:// is out for 0.6)
89
+
90
+ /// A `file://` URL into an owned buffer: bounded by `maxBytes`, read in pieces with a cancel
91
+ /// check between them. Anything else, a missing file, a directory or an oversize file is
92
+ /// `image_fetch_failed`.
93
+ static func readLocal(_ uri: String, maxBytes: Int, _ cancel: CancelToken) throws -> Data {
94
+ guard let url = URL(string: uri), url.isFileURL, !url.path.isEmpty,
95
+ let handle = try? FileHandle(forReadingFrom: url) else { throw failure("image_fetch_failed") }
96
+ defer { try? handle.close() }
97
+ var isDirectory: ObjCBool = false
98
+ guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), !isDirectory.boolValue else { throw failure("image_fetch_failed") }
99
+ var bytes = Data()
100
+ while true {
101
+ try check(cancel)
102
+ // One byte past the bound proves the file is too large without reading all of it.
103
+ let piece = (try? handle.read(upToCount: min(256 * 1024, maxBytes + 1 - bytes.count))) ?? nil
104
+ guard let piece, !piece.isEmpty else { break }
105
+ bytes.append(piece)
106
+ if bytes.count > maxBytes { throw failure("image_fetch_failed") }
107
+ }
108
+ guard !bytes.isEmpty else { throw failure("image_fetch_failed") }
109
+ try check(cancel)
110
+ return bytes
111
+ }
112
+
113
+ // MARK: Codec primitives (S3): Core chooses frame, orientation, sizes and formats
114
+
115
+ /// Decodes `bytes` (no MIME selects a decoder) into private RGBA8 pixels. `hasAlpha` is true
116
+ /// only when a pixel is not opaque, never because the format could carry alpha.
117
+ func decode(_ bytes: Data, _ options: ImageDecodeOptions, _ cancel: CancelToken) throws -> DecodedImage {
118
+ try Self.check(cancel)
119
+ #if canImport(ImageIO)
120
+ let image = try Self.decodePixels(bytes, frame: Int(options.frame), orient: options.applyOrientation, cancel)
121
+ let hasAlpha = try Self.anyTransparent(image, cancel)
122
+ let handle = UUID().uuidString
123
+ try lock.withLock {
124
+ if closed { throw LegacyCrocheError("closed", "The Runtime is closed.") }
125
+ decoded[handle] = image
126
+ }
127
+ // A cancel that lands after the store still wins; the handle is not leaked.
128
+ if cancel.isCancelled() { releaseDecoded(handle); throw Self.cancelled }
129
+ return DecodedImage(handle: handle, width: UInt32(image.width), height: UInt32(image.height), hasAlpha: hasAlpha)
130
+ #else
131
+ throw LegacyCrocheError("invalid_input", "The image could not be decoded.")
132
+ #endif
133
+ }
134
+
135
+ /// Encodes a decoded handle at exactly `width`×`height`. `quality` (0...1) applies to JPEG.
136
+ func render(_ request: ImageRenderRequest, _ cancel: CancelToken) throws -> Data {
137
+ try Self.check(cancel)
138
+ #if canImport(ImageIO)
139
+ guard let image = lock.withLock({ decoded[request.handle] }),
140
+ request.width >= 1, request.height >= 1 else {
141
+ throw Self.failure("image_unsupported")
142
+ }
143
+ if let quality = request.quality, !(0...1).contains(quality) { throw Self.failure("image_unsupported") }
144
+ let jpeg = request.format == .jpeg
145
+ let scaled = try Self.draw(image, width: Int(request.width), height: Int(request.height), opaque: jpeg)
146
+ try Self.check(cancel)
147
+ guard let out = Self.encode(scaled, jpeg ? "public.jpeg" : "public.png", jpeg ? request.quality : nil) else {
148
+ throw Self.failure("image_unsupported")
149
+ }
150
+ try Self.check(cancel)
151
+ return out
152
+ #else
153
+ throw Self.failure("image_unsupported")
154
+ #endif
155
+ }
156
+
157
+ /// Live decoded handles (tests prove nothing leaks).
158
+ var decodedCount: Int {
159
+ #if canImport(ImageIO)
160
+ lock.withLock { decoded.count }
161
+ #else
162
+ 0
163
+ #endif
164
+ }
165
+
166
+ /// Synchronous and idempotent, including after a cancel.
167
+ func releaseDecoded(_ handle: String) {
168
+ #if canImport(ImageIO)
169
+ lock.withLock { _ = decoded.removeValue(forKey: handle) }
170
+ #endif
171
+ }
172
+
173
+ #if canImport(ImageIO)
174
+
175
+ private static func decodePixels(_ bytes: Data, frame: Int, orient: Bool, _ cancel: CancelToken) throws -> CGImage {
176
+ let undecodable = LegacyCrocheError("invalid_input", "The image could not be decoded.")
177
+ // A truncated JPEG/PNG would be drawn with filler; refuse it as TypeScript does.
178
+ if let mime = mime(bytes), !complete(bytes, mime) { throw undecodable }
179
+ guard let source = CGImageSourceCreateWithData(bytes as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),
180
+ frame >= 0, frame < CGImageSourceGetCount(source),
181
+ CGImageSourceGetStatusAtIndex(source, frame) == .statusComplete,
182
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, frame, nil) as? [CFString: Any],
183
+ let w = properties[kCGImagePropertyPixelWidth] as? Int, let h = properties[kCGImagePropertyPixelHeight] as? Int,
184
+ w > 0, h > 0, !w.multipliedReportingOverflow(by: h).overflow else { throw undecodable }
185
+ try check(cancel)
186
+ guard let raw = CGImageSourceCreateImageAtIndex(source, frame, [kCGImageSourceShouldCacheImmediately: true] as CFDictionary) else { throw undecodable }
187
+ try check(cancel)
188
+ let orientation = orient ? ((properties[kCGImagePropertyOrientation] as? NSNumber)?.intValue ?? 1) : 1
189
+ return try upright(raw, orientation: (1...8).contains(orientation) ? orientation : 1)
190
+ }
191
+
192
+ /// Draws into an owned sRGB RGBA8 buffer, applying EXIF orientation 1-8.
193
+ private static func upright(_ image: CGImage, orientation: Int) throws -> CGImage {
194
+ let w = image.width, h = image.height, swapped = (5...8).contains(orientation)
195
+ let outW = swapped ? h : w, outH = swapped ? w : h
196
+ guard let context = CGContext(data: nil, width: outW, height: outH, bitsPerComponent: 8, bytesPerRow: outW * 4,
197
+ space: CGColorSpace(name: CGColorSpace.sRGB)!,
198
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { throw platformFault }
199
+ let W = CGFloat(outW), H = CGFloat(outH)
200
+ // EXIF orientation as a transform in Core Graphics' bottom-left coordinates.
201
+ let t: CGAffineTransform
202
+ switch orientation {
203
+ case 2: t = CGAffineTransform(a: -1, b: 0, c: 0, d: 1, tx: W, ty: 0)
204
+ case 3: t = CGAffineTransform(a: -1, b: 0, c: 0, d: -1, tx: W, ty: H)
205
+ case 4: t = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: H)
206
+ case 5: t = CGAffineTransform(a: 0, b: -1, c: -1, d: 0, tx: W, ty: H)
207
+ case 6: t = CGAffineTransform(a: 0, b: -1, c: 1, d: 0, tx: 0, ty: H)
208
+ case 7: t = CGAffineTransform(a: 0, b: 1, c: 1, d: 0, tx: 0, ty: 0)
209
+ case 8: t = CGAffineTransform(a: 0, b: 1, c: -1, d: 0, tx: W, ty: 0)
210
+ default: t = .identity
211
+ }
212
+ context.concatenate(t)
213
+ context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))
214
+ guard let out = context.makeImage() else { throw platformFault }
215
+ return out
216
+ }
217
+
218
+ /// True when any pixel's alpha is below 255: a scan of the actual RGBA8 pixels.
219
+ private static func anyTransparent(_ image: CGImage, _ cancel: CancelToken) throws -> Bool {
220
+ guard let data = image.dataProvider?.data, let base = CFDataGetBytePtr(data) else { throw platformFault }
221
+ let row = image.bytesPerRow, w = image.width
222
+ for y in 0..<image.height {
223
+ if y % 256 == 0 { try check(cancel) }
224
+ let line = base + y * row
225
+ for x in 0..<w where line[x * 4 + 3] != 255 { return true }
226
+ }
227
+ return false
228
+ }
229
+
230
+ private static func draw(_ image: CGImage, width: Int, height: Int, opaque: Bool) throws -> CGImage {
231
+ let info = opaque ? CGImageAlphaInfo.noneSkipLast.rawValue : CGImageAlphaInfo.premultipliedLast.rawValue
232
+ guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
233
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info) else { throw failure("image_unsupported") }
234
+ context.interpolationQuality = .high
235
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
236
+ guard let out = context.makeImage() else { throw failure("image_unsupported") }
237
+ return out
238
+ }
239
+
240
+ private static func encode(_ image: CGImage, _ type: String, _ quality: Double?) -> Data? {
241
+ let out = NSMutableData()
242
+ guard let destination = CGImageDestinationCreateWithData(out, type as CFString, 1, nil) else { return nil }
243
+ CGImageDestinationAddImage(destination, image, quality.map { [kCGImageDestinationLossyCompressionQuality: $0] as CFDictionary })
244
+ return CGImageDestinationFinalize(destination) ? out as Data : nil
245
+ }
246
+ #endif
247
+
248
+ // MARK: Preparation (same steps as TypeScript `prepareImageBytes`)
249
+
250
+ private static func prepareVerified(_ asset: PalImageBytes, maxSide: Int?, maxBytes: Int, _ cancel: CancelToken) throws -> PalImageBytes {
251
+ let bytes = asset.bytes
252
+ guard let mime = mime(bytes), complete(bytes, mime) else { throw failure("image_unsupported") }
253
+ let digest = sha256(bytes)
254
+ guard asset.sha256 == digest else { throw failure("image_unsupported") }
255
+ try check(cancel)
256
+ #if canImport(ImageIO)
257
+ guard let opened = OpenedImage(bytes) else { throw failure("image_unsupported") }
258
+ let sourceWidth = opened.width, sourceHeight = opened.height
259
+ let scale = maxSide.map { min(1, Double($0) / Double(max(sourceWidth, sourceHeight))) } ?? 1
260
+ var width = max(1, Int((Double(sourceWidth) * scale).rounded()))
261
+ var height = max(1, Int((Double(sourceHeight) * scale).rounded()))
262
+ for attempt in 0..<8 {
263
+ try check(cancel)
264
+ let rendered = try opened.render(width: width, height: height)
265
+ try check(cancel)
266
+ var candidates: [PalImageBytes] = []
267
+ if rendered.png.count <= maxBytes { candidates.append(PalImageBytes(bytes: rendered.png, mime: "image/png", sha256: sha256(rendered.png))) }
268
+ if let jpeg = rendered.jpeg, jpeg.count <= maxBytes { candidates.append(PalImageBytes(bytes: jpeg, mime: "image/jpeg", sha256: sha256(jpeg))) }
269
+ if width == sourceWidth && height == sourceHeight && mime != "image/gif" && !opened.reoriented {
270
+ candidates.append(PalImageBytes(bytes: bytes, mime: mime, sha256: digest))
271
+ }
272
+ if let best = candidates.min(by: { $0.bytes.count < $1.bytes.count }), best.bytes.count <= maxBytes { return best }
273
+ if width == 1 && height == 1 { break }
274
+ // As TypeScript: an oversized source candidate also guides the shrink.
275
+ let bestLength = Double(min(rendered.png.count, rendered.jpeg?.count ?? .max, candidates.map(\.bytes.count).min() ?? .max))
276
+ let shrink = max(0.1, min(0.8, (Double(maxBytes) / bestLength).squareRoot() * 0.9))
277
+ width = attempt == 6 ? 1 : max(1, Int(Double(width) * shrink))
278
+ height = attempt == 6 ? 1 : max(1, Int(Double(height) * shrink))
279
+ }
280
+ #endif
281
+ throw failure("image_unsupported")
282
+ }
283
+
284
+ #if canImport(ImageIO)
285
+ /// One decoded source. Dimensions come from the header (upright, after EXIF orientation).
286
+ private final class OpenedImage {
287
+ let source: CGImageSource
288
+ let width: Int, height: Int
289
+ /// EXIF turns the stored pixels, so the unchanged source is not upright as encoded.
290
+ let reoriented: Bool
291
+
292
+ init?(_ bytes: Data) {
293
+ guard let source = CGImageSourceCreateWithData(bytes as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),
294
+ CGImageSourceGetCount(source) >= 1,
295
+ CGImageSourceGetStatusAtIndex(source, 0) == .statusComplete,
296
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
297
+ let w = properties[kCGImagePropertyPixelWidth] as? Int,
298
+ let h = properties[kCGImagePropertyPixelHeight] as? Int,
299
+ w > 0, h > 0,
300
+ !w.multipliedReportingOverflow(by: h).overflow else { return nil }
301
+ let orientation = (properties[kCGImagePropertyOrientation] as? NSNumber)?.intValue ?? 1
302
+ let swapped = (5...8).contains(orientation)
303
+ self.source = source
304
+ width = swapped ? h : w; height = swapped ? w : h
305
+ reoriented = orientation != 1
306
+ }
307
+
308
+ /// Upright, exactly `width`×`height`: PNG, and JPEG unless a pixel can be transparent.
309
+ func render(width: Int, height: Int) throws -> (png: Data, jpeg: Data?) {
310
+ // The thumbnail path decodes at reduced size when it can (no full 12 MP bitmap for a
311
+ // 512 px target) and applies the EXIF orientation.
312
+ let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true,
313
+ kCGImageSourceCreateThumbnailWithTransform: true,
314
+ kCGImageSourceThumbnailMaxPixelSize: max(width, height)]
315
+ guard let thumb = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { throw NativeImagePal.failure("image_unsupported") }
316
+ let opaque = [.none, .noneSkipFirst, .noneSkipLast].contains(thumb.alphaInfo)
317
+ let image = try (thumb.width == width && thumb.height == height) ? thumb : Self.scaled(thumb, width, height, opaque)
318
+ guard let png = Self.encode(image, "public.png", nil) else { throw NativeImagePal.failure("image_unsupported") }
319
+ return (png, opaque ? Self.encode(image, "public.jpeg", Images.jpegQuality) : nil)
320
+ }
321
+
322
+ private static func scaled(_ image: CGImage, _ width: Int, _ height: Int, _ opaque: Bool) throws -> CGImage {
323
+ let info = opaque ? CGImageAlphaInfo.noneSkipLast.rawValue : CGImageAlphaInfo.premultipliedLast.rawValue
324
+ guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
325
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info) else { throw NativeImagePal.failure("image_unsupported") }
326
+ context.interpolationQuality = .high
327
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
328
+ guard let out = context.makeImage() else { throw NativeImagePal.failure("image_unsupported") }
329
+ return out
330
+ }
331
+
332
+ private static func encode(_ image: CGImage, _ type: String, _ quality: Double?) -> Data? {
333
+ let out = NSMutableData()
334
+ guard let destination = CGImageDestinationCreateWithData(out, type as CFString, 1, nil) else { return nil }
335
+ CGImageDestinationAddImage(destination, image, quality.map { [kCGImageDestinationLossyCompressionQuality: $0] as CFDictionary })
336
+ return CGImageDestinationFinalize(destination) ? out as Data : nil
337
+ }
338
+ }
339
+ #endif
340
+
341
+ // MARK: Helpers
342
+
343
+ static func failure(_ code: String) -> LegacyCrocheError {
344
+ LegacyCrocheError(code, code == "image_fetch_failed" ? "The image could not be read." : "The image could not be prepared.")
345
+ }
346
+
347
+ static var cancelled: LegacyCrocheError { LegacyCrocheError("cancelled", "Image preparation was cancelled.") }
348
+ /// CoreGraphics or memory failed while handling bytes that did decode: not a fact about the
349
+ /// app's image (never invalid_input): `internal`, sent literally (Keel 19:10Z, 21:00Z).
350
+ static var platformFault: LegacyCrocheError { LegacyCrocheError("internal", "CoreGraphics could not hold the decoded pixels.") }
351
+ /// Core's token is authoritative; its own terminal code wins over this one.
352
+ static func check(_ cancel: CancelToken) throws {
353
+ if cancel.isCancelled() { throw cancelled }
354
+ }
355
+
356
+ static func mime(_ bytes: Data) -> String? {
357
+ let b = [UInt8](bytes.prefix(12))
358
+ func at(_ values: [UInt8]) -> Bool { b.count >= values.count && Array(b[0..<values.count]) == values }
359
+ if at([137, 80, 78, 71, 13, 10, 26, 10]) { return "image/png" }
360
+ if at([255, 216, 255]) { return "image/jpeg" }
361
+ if at([71, 73, 70, 56]), b.count >= 6, b[4] == 55 || b[4] == 57, b[5] == 97 { return "image/gif" }
362
+ if b.count >= 12, at([82, 73, 70, 70]), b[8] == 87, b[9] == 69, b[10] == 66, b[11] == 80 { return "image/webp" }
363
+ return nil
364
+ }
365
+
366
+ /// ImageIO draws a truncated JPEG or PNG with filler; the TypeScript codecs refuse it. A JPEG
367
+ /// must carry its end-of-image marker near the end (trailing camera data is allowed), a PNG
368
+ /// its IEND chunk.
369
+ static func complete(_ bytes: Data, _ mime: String) -> Bool {
370
+ let tail = [UInt8](bytes.suffix(64 * 1024))
371
+ func contains(_ marker: [UInt8]) -> Bool {
372
+ guard tail.count >= marker.count else { return false }
373
+ for i in stride(from: tail.count - marker.count, through: 0, by: -1) where tail[i] == marker[0] && Array(tail[i..<i + marker.count]) == marker { return true }
374
+ return false
375
+ }
376
+ switch mime {
377
+ case "image/jpeg": return contains([0xFF, 0xD9])
378
+ case "image/png": return contains([0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82])
379
+ default: return true
380
+ }
381
+ }
382
+
383
+ static func sha256(_ bytes: Data) -> Data {
384
+ #if canImport(CryptoKit)
385
+ return Data(SHA256.hash(data: bytes))
386
+ #else
387
+ let hex = PortableSHA256.hex([UInt8](bytes))
388
+ var out = Data(capacity: 32), index = hex.startIndex
389
+ while index < hex.endIndex {
390
+ let next = hex.index(index, offsetBy: 2)
391
+ out.append(UInt8(hex[index..<next], radix: 16)!); index = next
392
+ }
393
+ return out
394
+ #endif
395
+ }
396
+ }
397
+
398
+ #if canImport(ImageIO) && (canImport(UIKit) || canImport(AppKit))
399
+ extension NativeImagePal {
400
+ /// A platform image as PNG bytes, encoded once at capture time (no EXIF: drawn upright).
401
+ static func encodedPNG(_ cgImage: CGImage?) throws -> Data {
402
+ guard let cgImage else { throw failure("image_unsupported") }
403
+ let out = NSMutableData()
404
+ guard let destination = CGImageDestinationCreateWithData(out, "public.png" as CFString, 1, nil) else { throw failure("image_unsupported") }
405
+ CGImageDestinationAddImage(destination, cgImage, nil)
406
+ guard CGImageDestinationFinalize(destination) else { throw failure("image_fetch_failed") }
407
+ return out as Data
408
+ }
409
+ }
410
+ #endif
@@ -12,15 +12,16 @@ import CoreGraphics
12
12
 
13
13
 
14
14
  /// A tool's result with images beside its value (H3): the same image kinds and limits as a
15
- /// message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4); a violation fails that call
16
- /// with `invalid_tool_result`, and the turn goes on. Return it from a handler made with
17
- /// `withResult`.
18
- public struct ToolResult: Sendable {
19
- public var value: JSON
20
- public var images: [JSON]
15
+ /// message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4). A malformed list fails that
16
+ /// call with `invalid_tool_result`, and the turn goes on; a size limit broken (more than 4
17
+ /// images, an `alt` over 500 characters) ends the turn with `input_too_large`. Return it from a
18
+ /// handler made with `withResult`.
19
+ struct LegacyToolResult: Sendable {
20
+ var value: JSON
21
+ var images: [JSON]
21
22
  /// For every image that does not name its own `"resolution"`.
22
- public var imageResolution: ImageResolution?
23
- public init(value: JSON = .null, images: [JSON] = [], imageResolution: ImageResolution? = nil) {
23
+ var imageResolution: ImageResolution?
24
+ init(value: JSON = .null, images: [JSON] = [], imageResolution: ImageResolution? = nil) {
24
25
  self.value = value; self.images = images; self.imageResolution = imageResolution
25
26
  }
26
27
  }
@@ -29,7 +30,7 @@ public struct ToolResult: Sendable {
29
30
  /// `tools: ["room": withResult { invocation, context in ToolResult(value: ..., images: [...]) }]`.
30
31
  /// The images go to the Runtime beside the value; a plain `ToolHandler`'s JSON is never looked
31
32
  /// inside.
32
- public func withResult(_ handler: @escaping @Sendable (_ invocation: JSON, _ context: ToolContext) async throws -> ToolResult) -> ToolHandler {
33
+ func withResult(_ handler: @escaping @Sendable (_ invocation: JSON, _ context: LegacyToolContext) async throws -> LegacyToolResult) -> ToolHandler {
33
34
  { invocation, context in
34
35
  let result = try await handler(invocation, context)
35
36
  // The handler ran: what it returned (plain values, nothing that can throw) is read once,
@@ -0,0 +1,88 @@
1
+ import Foundation
2
+
3
+ /// Prepared physical I/O only; Core retains exact instance custody and owns scope selection.
4
+ struct InstancePayloadPlan {
5
+ let eraseTemps: () throws -> Void
6
+ let durable: () throws -> Void
7
+ let eraseValues: () throws -> Void
8
+ }
9
+
10
+ func planInstancePayloads(_ root: URL, area: String, prefix: String,
11
+ sync: @escaping (URL) throws -> Void) throws -> InstancePayloadPlan {
12
+ guard PlatformStorage.valid(prefix), prefix.count > 1, prefix.hasSuffix("/") else {
13
+ throw LegacyCrocheError("storage_error", "Invalid purge prefix.")
14
+ }
15
+ let base = root.appendingPathComponent(area, isDirectory: true).standardizedFileURL
16
+ let manager = FileManager.default
17
+ var temps: [URL] = [], values: [URL] = [], directories: Set<URL> = []
18
+ func invalid() -> LegacyCrocheError { LegacyCrocheError("storage_error", "Invalid payload path.") }
19
+ func decode(_ hex: String) throws -> String {
20
+ let digits = Array(hex.utf8)
21
+ guard !digits.isEmpty, digits.count % 2 == 0 else { throw invalid() }
22
+ var bytes: [UInt8] = []
23
+ for i in stride(from: 0, to: digits.count, by: 2) {
24
+ guard let byte = UInt8(String(decoding: digits[i..<i+2], as: UTF8.self), radix: 16) else { throw invalid() }
25
+ bytes.append(byte)
26
+ }
27
+ guard let key = String(bytes: bytes, encoding: .utf8), PlatformStorage.valid(key) else { throw invalid() }
28
+ return key
29
+ }
30
+ let exists: Bool
31
+ do {
32
+ // Check the backend-managed ancestor before following it into either area.
33
+ let rootAttributes = try manager.attributesOfItem(atPath: root.path)
34
+ guard rootAttributes[.type] as? FileAttributeType == .typeDirectory else { throw invalid() }
35
+ let attributes = try manager.attributesOfItem(atPath: base.path)
36
+ guard attributes[.type] as? FileAttributeType == .typeDirectory else { throw invalid() }
37
+ exists = true
38
+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile {
39
+ exists = false
40
+ }
41
+ if exists {
42
+ let canonicalBase = base.resolvingSymlinksInPath()
43
+ var enumerationError: Error?
44
+ guard let entries = manager.enumerator(at: canonicalBase, includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey], errorHandler: { _, error in enumerationError = error; return false }) else { throw invalid() }
45
+ for case let file as URL in entries {
46
+ let kind = try file.resourceValues(forKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey])
47
+ let components = file.standardizedFileURL.pathComponents
48
+ guard components.starts(with: canonicalBase.pathComponents) else { throw invalid() }
49
+ let parts = Array(components.dropFirst(canonicalBase.pathComponents.count))
50
+ if kind.isDirectory == true, kind.isSymbolicLink != true {
51
+ guard parts.count == 1 else { throw invalid() }
52
+ let head = try decode(parts[0])
53
+ // Include retained empty head dirs so retry durably acknowledges a prior temp unlink.
54
+ if prefix.hasPrefix(head) || head.hasPrefix(prefix) { directories.insert(file) }
55
+ continue
56
+ }
57
+ guard parts.count == 2, let dot = parts[1].firstIndex(of: ".") else { throw invalid() }
58
+ let tail = parts[1], suffix = String(tail[dot...])
59
+ guard parts[0].count <= 200, dot == tail.startIndex || parts[0].count == 200 else { throw invalid() }
60
+ let key = try decode(parts[0] + tail[..<dot])
61
+ guard key.hasPrefix(prefix) else { continue }
62
+ guard kind.isRegularFile == true, kind.isSymbolicLink != true else { throw invalid() }
63
+ if suffix == ".value" { values.append(file) }
64
+ else if suffix.hasPrefix(".value.tmp-"), UUID(uuidString: String(suffix.dropFirst(".value.tmp-".count))) != nil { temps.append(file) }
65
+ else { throw invalid() }
66
+ directories.insert(file.deletingLastPathComponent())
67
+ }
68
+ if let enumerationError { throw enumerationError }
69
+ }
70
+ func erase(_ files: [URL]) throws {
71
+ for file in files {
72
+ do { try manager.removeItem(at: file) }
73
+ catch let error as CocoaError where error.code == .fileNoSuchFile { /* idempotent retry */ }
74
+ }
75
+ }
76
+ return InstancePayloadPlan(eraseTemps: { try erase(temps) }, durable: { for directory in directories { try sync(directory) } }, eraseValues: { try erase(values) })
77
+ }
78
+
79
+ /// Erases every payload file of one instance, not log-floor pruning.
80
+ func eraseInstancePayloads(values: InstancePayloadPlan?, secrets: InstancePayloadPlan?,
81
+ deleteSecret: () throws -> Void = {}, deleteState: () throws -> Void = {}) throws {
82
+ try values?.eraseTemps(); try secrets?.eraseTemps()
83
+ try values?.durable(); try secrets?.durable()
84
+ try deleteSecret()
85
+ try secrets?.eraseValues(); try secrets?.durable()
86
+ try deleteState()
87
+ try values?.eraseValues(); try values?.durable()
88
+ }
@@ -1,8 +1,20 @@
1
1
  import Foundation
2
2
 
3
3
  /// A value-semantic JSON tree. Core state and machine stay opaque to the host.
4
- public enum JSON: Codable, Sendable, Equatable {
5
- case null, bool(Bool), number(Double), string(String), array([JSON]), object([String: JSON])
4
+ public enum JSON: Codable, Sendable, Hashable {
5
+ /// JSON `null`.
6
+ case null
7
+ /// A JSON `true` or `false`.
8
+ case bool(Bool)
9
+ /// A JSON number. Every number is held as a `Double`, so integers above 2^53 lose precision.
10
+ case number(Double)
11
+ /// A JSON string.
12
+ case string(String)
13
+ /// A JSON array, in order.
14
+ case array([JSON])
15
+ /// A JSON object. Key order is not preserved.
16
+ case object([String: JSON])
17
+ /// Decodes any JSON value. It tries `null`, then `Bool`, `Double`, `String` and an array, and otherwise decodes an object.
6
18
  public init(from decoder: Decoder) throws {
7
19
  let c = try decoder.singleValueContainer()
8
20
  if c.decodeNil() { self = .null }
@@ -12,6 +24,7 @@ public enum JSON: Codable, Sendable, Equatable {
12
24
  else if let v = try? c.decode([JSON].self) { self = .array(v) }
13
25
  else { self = .object(try c.decode([String: JSON].self)) }
14
26
  }
27
+ /// Encodes the value as the matching JSON value.
15
28
  public func encode(to encoder: Encoder) throws {
16
29
  var c = encoder.singleValueContainer()
17
30
  switch self {
@@ -23,25 +36,37 @@ public enum JSON: Codable, Sendable, Equatable {
23
36
  case .object(let v): try c.encode(v)
24
37
  }
25
38
  }
39
+ /// Parses UTF-8 JSON bytes with `JSONDecoder`. Throws if the bytes are not valid JSON.
26
40
  public init(data: Data) throws { self = try JSONDecoder().decode(JSON.self, from: data) }
41
+ /// Parses JSON text. Throws if the text is not valid JSON.
27
42
  public init(_ text: String) throws { try self.init(data: Data(text.utf8)) }
43
+ /// Serializes the value to JSON bytes with a default `JSONEncoder`. Object key order is not fixed.
28
44
  public func encoded() throws -> Data { try JSONEncoder().encode(self) }
45
+ /// Reads or writes an object member.
46
+ ///
47
+ /// Reading returns `.null` when the key is missing or the value is not an object. Writing to a value that
48
+ /// is not an object replaces it with a one-member object.
29
49
  public subscript(_ key: String) -> JSON {
30
50
  get { if case .object(let v) = self { return v[key] ?? .null }; return .null }
31
51
  set { var v = object ?? [:]; v[key] = newValue; self = .object(v) }
32
52
  }
53
+ /// The members when the value is an object, otherwise `nil`.
33
54
  public var object: [String: JSON]? { if case .object(let v) = self { return v }; return nil }
55
+ /// The elements when the value is an array, otherwise `nil`.
34
56
  public var array: [JSON]? { if case .array(let v) = self { return v }; return nil }
57
+ /// The text when the value is a string, otherwise `nil`.
35
58
  public var string: String? { if case .string(let v) = self { return v }; return nil }
59
+ /// The number when the value is a number, otherwise `nil`.
36
60
  public var number: Double? { if case .number(let v) = self { return v }; return nil }
61
+ /// The flag when the value is a Boolean, otherwise `nil`.
37
62
  public var bool: Bool? { if case .bool(let v) = self { return v }; return nil }
38
63
  }
39
64
 
40
- public struct CrocheError: Error, Sendable, CustomStringConvertible {
65
+ struct LegacyCrocheError: Error, Sendable, CustomStringConvertible {
41
66
  public let code: String
42
67
  public let message: String
43
- public let receipt: Receipt?
44
- public init(_ code: String, _ message: String, receipt: Receipt? = nil) { self.code = code; self.message = message; self.receipt = receipt }
68
+ public let receipt: LegacyReceipt?
69
+ public init(_ code: String, _ message: String, receipt: LegacyReceipt? = nil) { self.code = code; self.message = message; self.receipt = receipt }
45
70
  public var description: String { "\(code): \(message)" }
46
71
  }
47
72
 
@@ -52,12 +77,3 @@ func publicStorageIdentity(_ value: JSON) -> JSON {
52
77
  fields.removeValue(forKey: "defaultStorageKey")
53
78
  return .object(fields)
54
79
  }
55
-
56
- // OPEN(Project→Agent): wire this at Croche.open once the reviewed Swift open surface lands.
57
- // The SDK neither chooses a default nor validates the retention budget; Core owns both.
58
- func coreOpenConfig(_ config: JSON, retentionBytes: Int?) -> JSON {
59
- guard let retentionBytes else { return config }
60
- var bound = config
61
- bound["retentionBytes"] = .number(Double(retentionBytes))
62
- return bound
63
- }
@@ -0,0 +1,24 @@
1
+ import Foundation
2
+
3
+ /// Core's calls block their thread while the host performs effects: run them on a thread of
4
+ /// their own, never on the cooperative pool or the main thread.
5
+ enum Offload {
6
+ /// Croche's own tests: runs first on each offload thread, so a test can delay it the way the
7
+ /// OS may (#346). Nil in every app.
8
+ nonisolated(unsafe) static var starting: (@Sendable () -> Void)?
9
+ static func run<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
10
+ try await withCheckedThrowingContinuation { continuation in
11
+ Thread.detachNewThread {
12
+ starting?()
13
+ do { continuation.resume(returning: try body()) }
14
+ catch { continuation.resume(throwing: LegacyCrocheError(error)) }
15
+ }
16
+ }
17
+ }
18
+ }
19
+
20
+ /// Core's storage identity for a config: the key a store is bound to. Internal; apps never read it.
21
+ func storageIdentity(config: JSON) throws -> JSON {
22
+ do { return publicStorageIdentity(try JSON(ffiIdentity(String(decoding: try config.encoded(), as: UTF8.self)))) }
23
+ catch { throw LegacyCrocheError(error) }
24
+ }