@h1r-ai/croche-react-native 0.6.0 → 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 (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -0,0 +1,124 @@
1
+ import Foundation
2
+ #if canImport(Darwin)
3
+ import Darwin
4
+ #elseif canImport(Glibc)
5
+ import Glibc
6
+ #endif
7
+
8
+ /// Private transport for Core's blob keys. Object files contain the original bytes.
9
+ final class BlobFiles: Sendable {
10
+ struct Entry { let key: String; let size: UInt64 }
11
+ struct Page { let entries: [Entry]; let nextCursor: String? }
12
+
13
+ private let root: URL
14
+
15
+ init(directory: URL) { root = directory.appendingPathComponent("blobs", isDirectory: true) }
16
+
17
+ private static func valid(_ segment: Substring) -> Bool {
18
+ segment.utf8.first.map { (48...57).contains($0) || (97...122).contains($0) || $0 == 126 } == true
19
+ && segment.utf8.allSatisfy { (48...57).contains($0) || (97...122).contains($0) || [45, 46, 95, 126].contains($0) }
20
+ }
21
+
22
+ private func directory(_ key: String, create: Bool) throws -> URL? {
23
+ let segments = key.isEmpty ? [] : key.split(separator: "/", omittingEmptySubsequences: false)
24
+ guard key.utf8.count <= 1024, segments.allSatisfy(Self.valid) else { throw CocoaError(.fileWriteInvalidFileName) }
25
+ var path = root
26
+ for segment in [""] + segments.map(String.init) {
27
+ if !segment.isEmpty { path.appendPathComponent(segment, isDirectory: true) }
28
+ if create {
29
+ do {
30
+ try FileManager.default.createDirectory(at: path, withIntermediateDirectories: false)
31
+ try sync(path.deletingLastPathComponent())
32
+ } catch let error as CocoaError where error.code == .fileWriteFileExists {}
33
+ }
34
+ do {
35
+ let facts = try path.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
36
+ guard facts.isDirectory == true, facts.isSymbolicLink != true else { throw CocoaError(.fileReadCorruptFile) }
37
+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile && !create { return nil }
38
+ }
39
+ return path
40
+ }
41
+
42
+ func put(_ key: String, _ bytes: Data) throws {
43
+ guard !key.isEmpty, let dir = try directory(key, create: true) else { throw CocoaError(.fileWriteInvalidFileName) }
44
+ let temporary = dir.appendingPathComponent(".tmp-" + UUID().uuidString)
45
+ try bytes.write(to: temporary, options: .withoutOverwriting)
46
+ defer { try? FileManager.default.removeItem(at: temporary) }
47
+ try sync(temporary)
48
+ guard rename(temporary.path, dir.appendingPathComponent("object").path) == 0 else { throw CocoaError(.fileWriteUnknown) }
49
+ try sync(dir)
50
+ }
51
+
52
+ func get(_ key: String) throws -> Data? {
53
+ guard !key.isEmpty, let dir = try directory(key, create: false) else { return nil }
54
+ let file = dir.appendingPathComponent("object")
55
+ do {
56
+ let facts = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
57
+ guard facts.isRegularFile == true, facts.isSymbolicLink != true else { throw CocoaError(.fileReadCorruptFile) }
58
+ return try Data(contentsOf: file)
59
+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile { return nil }
60
+ }
61
+
62
+ func delete(_ key: String) throws {
63
+ guard !key.isEmpty, let dir = try directory(key, create: false) else { return }
64
+ if unlink(dir.appendingPathComponent("object").path) == 0 { try sync(dir) }
65
+ else if errno != ENOENT { throw CocoaError(.fileWriteUnknown) }
66
+ }
67
+
68
+ func list(_ prefix: String, cursor: String?) throws -> Page {
69
+ let keys: Set<URLResourceKey> = [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]
70
+ var entries: [Entry] = []
71
+ func walk(_ dir: URL, key: String) throws {
72
+ for child in try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: Array(keys)) {
73
+ let name = child.lastPathComponent
74
+ let facts = try child.resourceValues(forKeys: keys)
75
+ if facts.isSymbolicLink == true { continue }
76
+ if name == "object", facts.isRegularFile == true, key.hasPrefix(prefix), cursor.map({ key > $0 }) ?? true {
77
+ guard let size = facts.fileSize, size >= 0 else { throw CocoaError(.fileReadCorruptFile) }
78
+ entries.append(Entry(key: key, size: UInt64(size)))
79
+ } else if facts.isDirectory == true, Self.valid(name[...]) {
80
+ let next = key.isEmpty ? name : key + "/" + name
81
+ if next.hasPrefix(prefix) || prefix.hasPrefix(next + "/") { try walk(child, key: next) }
82
+ }
83
+ }
84
+ }
85
+ let parent = prefix.lastIndex(of: "/").map { String(prefix[..<$0]) } ?? ""
86
+ if let dir = try directory(parent, create: false) { try walk(dir, key: parent) }
87
+ entries.sort { $0.key < $1.key }
88
+ let page = Array(entries.prefix(1_000))
89
+ return Page(entries: page, nextCursor: entries.count > page.count ? page.last?.key : nil)
90
+ }
91
+
92
+ /// Core has drained the exact owner scope before invoking this.
93
+ func purgeStaging(_ prefix: String) throws {
94
+ guard prefix.count > 1, prefix.hasSuffix("/") else { throw CocoaError(.fileWriteInvalidFileName) }
95
+ guard let dir = try directory(String(prefix.dropLast()), create: false) else { return }
96
+ try removeStagedFiles(dir)
97
+ }
98
+
99
+ private func removeStagedFiles(_ dir: URL) throws {
100
+ // The exact owner lease covers the no-follow check and subsequent unlink.
101
+ for name in try FileManager.default.contentsOfDirectory(atPath: dir.path) {
102
+ let child = dir.appendingPathComponent(name)
103
+ var info = stat()
104
+ guard lstat(child.path, &info) == 0 else {
105
+ if errno == ENOENT { continue }
106
+ throw CocoaError(.fileReadUnknown)
107
+ }
108
+ let type = info.st_mode & mode_t(S_IFMT)
109
+ if type == mode_t(S_IFREG), name.hasPrefix(".tmp-") {
110
+ guard unlink(child.path) == 0 || errno == ENOENT else { throw CocoaError(.fileWriteUnknown) }
111
+ } else if type == mode_t(S_IFDIR), Self.valid(name[...]) {
112
+ try removeStagedFiles(child)
113
+ }
114
+ }
115
+ try sync(dir)
116
+ }
117
+
118
+ private func sync(_ path: URL) throws {
119
+ let fd = open(path.path, O_RDONLY)
120
+ guard fd >= 0 else { throw CocoaError(.fileWriteUnknown) }
121
+ defer { close(fd) }
122
+ guard fsync(fd) == 0 else { throw CocoaError(.fileWriteUnknown) }
123
+ }
124
+ }
@@ -1,23 +1,19 @@
1
1
  import Foundation
2
2
 
3
- /// Schema-6 context settings. Core owns defaults and validation.
3
+ /// Schema-7 context settings. Core owns defaults and validation.
4
4
  struct ContextConfig: Sendable {
5
5
  /// Target average input tokens per model call, 1...16_777_216.
6
6
  var turnTokens: Int?
7
7
  /// 0...0.5, default 0.25; controls memory inclusion; zero disables it. Ignored when memory is disabled.
8
8
  var memoryShare: Double?
9
- /// Hard input-token cap per model call, independent of the model's own window, 1...16_777_216.
10
- var maxTokens: Int?
11
- init(turnTokens: Int? = nil, memoryShare: Double? = nil, maxTokens: Int? = nil) {
9
+ init(turnTokens: Int? = nil, memoryShare: Double? = nil) {
12
10
  self.turnTokens = turnTokens
13
11
  self.memoryShare = memoryShare
14
- self.maxTokens = maxTokens
15
12
  }
16
13
  var json: JSON {
17
14
  var value: JSON = .object([:])
18
15
  if let turnTokens { value["turnTokens"] = .number(Double(turnTokens)) }
19
16
  if let memoryShare { value["memoryShare"] = .number(memoryShare) }
20
- if let maxTokens { value["maxTokens"] = .number(Double(maxTokens)) }
21
17
  return value
22
18
  }
23
19
  }
@@ -0,0 +1,85 @@
1
+ import Foundation
2
+
3
+ // Platform-private pixel handles; the Core ABI carries encoded files only.
4
+ struct DecodedImage { let handle: String; let width: UInt32; let height: UInt32; let hasAlpha: Bool? }
5
+ struct ImageDecodeOptions { let frame: UInt32; let applyOrientation: Bool }
6
+ enum ImageFormat { case png, jpeg }
7
+ struct ImageRenderRequest {
8
+ let handle: String; let width: UInt32; let height: UInt32
9
+ let format: ImageFormat; let quality: Double?
10
+ }
11
+
12
+ extension NativeImagePal {
13
+ var support: ImageSupport? {
14
+ guard codecAvailable else { return nil }
15
+ return ImageSupport(inputMediaTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"],
16
+ outputMediaTypes: ["image/png", "image/jpeg"], maxInputPixels: 50_000_000)
17
+ }
18
+
19
+ // Both metadata and resizing decode the upright first frame, including EXIF orientation.
20
+ func operation(_ operation: String, _ bytes: Data, _ options: String, _ cancel: CancelToken) throws -> PalImageReply {
21
+ guard operation == "info" || operation == "resize" else { throw imageOperationUnsupported() }
22
+ let image = try decode(bytes, ImageDecodeOptions(frame: 0, applyOrientation: true), cancel)
23
+ defer { releaseDecoded(image.handle) }
24
+ if operation == "info" {
25
+ guard let mediaType = Self.mime(bytes) else { throw imageOperationUnsupported() }
26
+ let info = ImageInfo(mediaType: mediaType, width: Int(image.width), height: Int(image.height), hasAlpha: image.hasAlpha)
27
+ return PalImageReply(metadataJson: text(info.json), bytes: Data())
28
+ }
29
+ let limits = try ImageResizeLimits(JSON(options))
30
+ let scale = limits.maxSide.map { min(1, Double($0) / Double(max(image.width, image.height))) } ?? 1
31
+ var width = max(1, Int((Double(image.width) * scale).rounded()))
32
+ var height = max(1, Int((Double(image.height) * scale).rounded()))
33
+ for attempt in 0..<8 {
34
+ try Self.check(cancel)
35
+ var candidates: [Data] = []
36
+ if limits.outputMediaTypes.contains("image/png") {
37
+ candidates.append(try render(ImageRenderRequest(handle: image.handle, width: UInt32(width), height: UInt32(height), format: .png, quality: nil), cancel))
38
+ }
39
+ if limits.outputMediaTypes.contains("image/jpeg"), image.hasAlpha == false {
40
+ candidates.append(try render(ImageRenderRequest(handle: image.handle, width: UInt32(width), height: UInt32(height), format: .jpeg, quality: 0.7), cancel))
41
+ }
42
+ guard let best = candidates.min(by: { $0.count < $1.count }) else { throw imageOperationUnsupported() }
43
+ if best.count <= limits.maxBytes { return PalImageReply(metadataJson: "{}", bytes: best) }
44
+ if width == 1 && height == 1 { break }
45
+ let shrink = min(0.8, max(0.1, sqrt(Double(limits.maxBytes) / Double(best.count)) * 0.9))
46
+ width = attempt == 6 ? 1 : max(1, Int(Double(width) * shrink))
47
+ height = attempt == 6 ? 1 : max(1, Int(Double(height) * shrink))
48
+ }
49
+ throw imageOperationUnsupported()
50
+ }
51
+ }
52
+
53
+ private func imageOperationUnsupported() -> CorePalError {
54
+ .Failure(code: "image_unsupported", detail: "The image operation is not supported.")
55
+ }
56
+
57
+ // Core's synchronous effect waits for the app's async adapter. Task cancellation is AbortSignal.
58
+ func runImageAdapterOperation(_ image: any ImageAdapter, _ operation: String, _ bytes: Data,
59
+ _ options: String, _ cancel: CancelToken) throws -> PalImageReply {
60
+ try NativeImagePal.check(cancel)
61
+ let done = DispatchSemaphore(value: 0), box = ResultBox<PalImageReply>()
62
+ let task = appTask {
63
+ do {
64
+ try NativeImagePal.check(cancel)
65
+ try Task.checkCancellation()
66
+ let reply: PalImageReply
67
+ switch operation {
68
+ case "info": reply = PalImageReply(metadataJson: text(try await image.info(bytes).json), bytes: Data())
69
+ case "resize": reply = PalImageReply(metadataJson: "{}", bytes: try await image.resize(bytes, limits: ImageResizeLimits(JSON(options))))
70
+ default: throw imageOperationUnsupported()
71
+ }
72
+ box.set(.success(reply))
73
+ } catch { box.set(.failure(error)) }
74
+ done.signal()
75
+ }
76
+ cancel.onCancel(callback: ImageTaskCancel(task))
77
+ if cancel.isCancelled() { task.cancel() }
78
+ done.wait()
79
+ return try box.get()
80
+ }
81
+ private final class ImageTaskCancel: CancelCallback, @unchecked Sendable {
82
+ let task: Task<Void, Never>
83
+ init(_ task: Task<Void, Never>) { self.task = task }
84
+ func cancelled() { task.cancel() }
85
+ }
@@ -1,179 +1,6 @@
1
1
  import Foundation
2
2
 
3
- // The only stream adapter to UniFFI. Core owns projection, ordering and capture.
4
- // Keep the receipt method spelling in this one file/call site for the reviewed rename.
5
- final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
6
- private let core: CoreRuntime
7
- private let images: NativeImagePal?
8
- let logId: String
9
- init(core: CoreRuntime, images: NativeImagePal? = nil) throws {
10
- self.core = core; self.images = images
11
- logId = try Self.blocking { try core.logId() }
12
- }
13
- private final class Box<T>: @unchecked Sendable { var result: Result<T, Error>? }
14
- // select/observe are synchronous seams. Main-thread callers wait on a dedicated thread;
15
- // callbacks already on a Core thread stay there, preserving FFI's reentrancy rule.
16
- private static func blocking<T>(record: Bool = true, _ body: @escaping @Sendable () throws -> T) throws -> T {
17
- let measured: @Sendable () throws -> T = {
18
- if record { Offload.starting?() }
19
- return try body()
20
- }
21
- if !Thread.isMainThread { return try measured() }
22
- let done = DispatchSemaphore(value: 0), box = Box<T>()
23
- Thread.detachNewThread { box.result = Result { try measured() }; done.signal() }
24
- done.wait()
25
- return try box.result!.get()
26
- }
27
- private static func offload<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
28
- try await Offload.run(body)
29
- }
30
- private final class Listener: EventListener, @unchecked Sendable {
31
- let callback: @Sendable (String) -> Void
32
- init(_ callback: @escaping @Sendable (String) -> Void) { self.callback = callback }
33
- func onEvent(event: String) { callback(event) }
34
- }
35
- private static func failure(_ error: Error) -> LegacyStreamError {
36
- let error = LegacyCrocheError(error)
37
- return LegacyStreamError(code: error.code, message: error.message, poisoned: false)
38
- }
39
- func observe(_ event: @escaping @Sendable (RequestObservation) -> Void,
40
- end: @escaping @Sendable (LegacyStreamError?) -> Void) throws -> @Sendable () -> Void {
41
- do {
42
- try Self.blocking { [core] in
43
- try core.observe(onEvent: Listener { text in
44
- do {
45
- let decoded = try CoreEvent.decode(text)
46
- switch decoded {
47
- case .input(let v): event(.input(InputObservation(id: v.id, seq: v.seq, status: v.status, carried: v.status == .seen)))
48
- case .messageEnd(let v): event(.messageEnd(v))
49
- case .state(let v): event(.state(v))
50
- default: break
51
- }
52
- } catch { end(Self.failure(error)) }
53
- }, onEnd: Listener { text in
54
- do { end(try CoreEvent.decodeFailure(text)) }
55
- catch { end(Self.failure(error)) }
56
- })
57
- }
58
- } catch { throw LegacyCrocheError(error) }
59
- return { [core] in _ = try? Self.blocking { core.unobserve() } }
60
- }
61
- /// Core's selection JSON. A nil field is omitted (Core's default), never filled in here.
62
- static func selectionText(_ selection: StreamSelection) throws -> String {
63
- struct Selection: Encodable { let initialMessages: Int?; let after: Cursor?; let deltaMs: Int? }
64
- let value = Selection(initialMessages: selection.initialMessages, after: selection.after, deltaMs: selection.deltaMs)
65
- return String(decoding: try JSONEncoder().encode(value), as: UTF8.self)
66
- }
67
- func select(_ selection: StreamSelection, event: @escaping @Sendable (LegacyRuntimeEvent) -> Void) -> CoreProjection {
68
- do {
69
- if let after = selection.after { _ = try Self.coreSequence(after.seq) }
70
- let text = try Self.selectionText(selection)
71
- let id = try Self.blocking { [core] in
72
- try core.select(selection: text, onEvent: Listener { text in
73
- do { event(try CoreEvent.decode(text)) }
74
- catch { event(.streamError(Self.failure(error))) }
75
- })
76
- }
77
- return CoreProjection(close: { [core] in _ = try? Self.blocking { core.closeProjection(id: id) } }, history: { before, limit in
78
- guard let count = UInt32(exactly: limit) else { throw LegacyCrocheError("invalid_configuration", "Invalid history range") }
79
- let seq = try before.map(Self.coreSequence)
80
- try await Self.offload { try self.historyNow(id: id, before: seq, limit: count) }
81
- })
82
- } catch {
83
- event(.streamError(Self.failure(error)))
84
- return CoreProjection(close: {}, history: { _, _ in throw LegacyCrocheError("invalid_configuration", "No stream is attached") })
85
- }
86
- }
87
- // Also used at the synchronous callback boundary to retain FFI's reentrancy rule.
88
- func historyNow(id: UInt64, before: UInt64?, limit: UInt32) throws {
89
- try Self.blocking { [core] in try core.history(id: id, before: before, limit: limit) }
90
- }
91
- func send(_ input: JSON, options: SendOptions) async throws -> LegacyReceipt {
92
- let token = CancelToken()
93
- return try await withTaskCancellationHandler {
94
- try await send(input, options: options, cancel: token)
95
- } onCancel: { token.cancel() }
96
- }
97
- func send(_ input: JSON, options: SendOptions, cancel: CancelToken?) async throws -> LegacyReceipt {
98
- let text = String(decoding: try input.encoded(), as: UTF8.self)
99
- let format = try options.responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
100
- let value = try await Self.offload { [core] in try core.send(input: text, cancel: cancel, responseFormat: format) }
101
- struct WireReceipt: Decodable { let requestId: String; let status: LegacyInputStatus; let seq: Int? }
102
- let receipt = try CoreEvent.decodeValue(WireReceipt.self, value)
103
- return LegacyReceipt(requestId: receipt.requestId, status: receipt.status, seq: receipt.seq)
104
- }
105
- /// Byte images go through Core's reserved entry: reserve, capture, submit, all before the
106
- /// first await, so the send keeps its place; only the receipt wait is offloaded. Until submit
107
- /// returns, this owns the captures; afterwards Core releases them on every exit.
108
- func send(_ input: SendInput, options: SendOptions) async throws -> LegacyReceipt {
109
- let captured = input.imageCaptures()
110
- guard !captured.isEmpty else { return try await send(try input.coreJSON(options: options), options: options) }
111
- guard let images else { throw LegacyCrocheError("image_unsupported", "The image could not be prepared.") }
112
- let text = String(decoding: try input.coreJSON(options: options).encoded(), as: UTF8.self)
113
- let format = try options.responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
114
- let token = CancelToken()
115
- let pending = try Self.blocking { [core] () throws -> PendingSend in
116
- let entry = try core.reserveSend()
117
- var tokens: [String] = []
118
- do {
119
- var captures: [PalCapturedImageSource] = []
120
- for (element, bytes) in captured {
121
- let capture = try images.capture(bytes)
122
- tokens.append(capture)
123
- captures.append(PalCapturedImageSource(element: UInt32(element), kind: "encoded-v1", token: capture))
124
- }
125
- return try entry.submit(input: text, captures: captures, cancel: token, responseFormat: format)
126
- } catch {
127
- for capture in tokens { images.release(capture) }
128
- throw error
129
- }
130
- }
131
- let value = try await withTaskCancellationHandler {
132
- try await Self.offload { try pending.wait() }
133
- } onCancel: { token.cancel() }
134
- struct WireReceipt: Decodable { let requestId: String; let status: LegacyInputStatus; let seq: Int? }
135
- let receipt = try CoreEvent.decodeValue(WireReceipt.self, value)
136
- return LegacyReceipt(requestId: receipt.requestId, status: receipt.status, seq: receipt.seq)
137
- }
138
- func readOutcome(id: String, fromSeq: Int, captured: @escaping @Sendable (CapturedRequestState) -> Void) async throws -> RetainedRequestEnds {
139
- let seq = try Self.coreSequence(fromSeq)
140
- // Capture parsing failures must fail the read, never silently strand a waiter.
141
- let captureError = CaptureError()
142
- let text = try await Self.offload { [core] in
143
- try core.readOutcome(id: id, fromSeq: seq, captured: Listener { value in
144
- do {
145
- struct Capture: Decodable { let head: Int; let floor: Int; let status: LegacyInputStatus; let idle: Bool; let consumedBy: String? }
146
- let at = try CoreEvent.decodeValue(Capture.self, value)
147
- captured(CapturedRequestState(head: at.head, floor: at.floor, status: at.status, idle: at.idle, carried: at.consumedBy != nil, unitEnd: nil))
148
- } catch { captureError.set(error) }
149
- })
150
- }
151
- if let error = captureError.get() { throw error }
152
- struct Outcome: Decodable { let messages: [LegacyMessageEnd]; let gap: Bool? }
153
- let outcome = try CoreEvent.decodeValue(Outcome.self, text)
154
- return RetainedRequestEnds(messages: outcome.messages, gap: outcome.gap ?? false)
155
- }
156
- private final class CaptureError: @unchecked Sendable {
157
- private let lock = NSLock(); private var error: Error?
158
- func set(_ value: Error) { lock.withLock { error = value } }
159
- func get() -> Error? { lock.withLock { error } }
160
- }
161
- static func coreSequence(_ value: Int) throws -> UInt64 {
162
- guard let result = UInt64(exactly: value) else { throw LegacyCrocheError("invalid_input", "Sequence is outside the Core range") }
163
- return result
164
- }
165
- func cancel(_ id: String) async throws {
166
- try await Self.offload { [core] in try core.cancel(id: id) }
167
- }
168
- func clearHistory() async throws {
169
- // Preserve the existing admission fence: only waiting crosses the offload hop.
170
- let pending = try Self.blocking(record: false) { [core] in core.beginClearHistory() }
171
- try await Self.offload { try pending.finish() }
172
- }
173
- }
174
-
175
- // Decode numbers from the original JSON bytes, never through the legacy Double JSON tree.
176
- // Extra Core keys stay internal; unknown event types remain forward-compatible.
3
+ // Pure legacy-event reader retained for existing stream-kernel/reader witnesses.
177
4
  enum CoreEvent {
178
5
  static func publicSequence(_ value: UInt64) throws -> Int {
179
6
  guard let result = Int(exactly: value) else { throw LegacyCrocheError("invalid_input", "Core sequence is outside the public range") }