@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
@@ -1,496 +0,0 @@
1
- import Foundation
2
-
3
- // Proposed SDK-internal seam only. Core owns projection, ordered capture, delta fences,
4
- // and storage. select/history never allocate a second canonical observation.
5
- struct StreamSelection: Sendable { var initialMessages: Int?; var after: Cursor?; var deltaMs: Int? = nil }
6
- struct CoreProjection: Sendable {
7
- /// Joins Core's synchronous listener, not buffered AsyncStream/UI consumers. A synchronous
8
- /// close from that listener itself fences without waiting for its own stack.
9
- /// An app callback that waits for work on the closer's thread deadlocks under any
10
- /// wait-for-callback fence.
11
- let close: @Sendable () -> Void
12
- let history: @Sendable (Int?, Int) async throws -> Void
13
- }
14
- struct UnitEnd: Sendable, Codable { let seq: Int; let inputs: [String]; let pending: [String] }
15
- struct InputObservation: Sendable, Codable { let id: String; let seq: Int; let status: LegacyInputStatus; let carried: Bool }
16
- enum RequestObservation: Sendable, Codable { case input(InputObservation), messageEnd(LegacyMessageEnd), state(LegacyStateEvent), unitEnd(UnitEnd) }
17
- struct CapturedRequestState: Sendable {
18
- let head: Int; let floor: Int; let status: LegacyInputStatus; let idle: Bool
19
- let carried: Bool; let unitEnd: UnitEnd?
20
- }
21
- struct RetainedRequestEnds: Sendable { let messages: [LegacyMessageEnd]; let gap: Bool }
22
- protocol CoreStreamPort: Sendable {
23
- var logId: String { get }
24
- func observe(_ event: @escaping @Sendable (RequestObservation) -> Void,
25
- end: @escaping @Sendable (LegacyStreamError?) -> Void) throws -> @Sendable () -> Void
26
- func select(_ selection: StreamSelection, event: @escaping @Sendable (LegacyRuntimeEvent) -> Void) -> CoreProjection
27
- func send(_ input: JSON, options: SendOptions) async throws -> LegacyReceipt
28
- /// A typed send; a port with an image PAL captures its byte images at the reserved entry.
29
- func send(_ input: SendInput, options: SendOptions) async throws -> LegacyReceipt
30
- func readOutcome(id: String, fromSeq: Int, captured: @escaping @Sendable (CapturedRequestState) -> Void) async throws -> RetainedRequestEnds
31
- func cancel(_ id: String) async throws
32
- func clearHistory() async throws
33
- }
34
- extension CoreStreamPort {
35
- func send(_ input: SendInput, options: SendOptions) async throws -> LegacyReceipt {
36
- guard input.imageCaptures().isEmpty else { throw LegacyCrocheError("image_unsupported", "The image could not be prepared.") }
37
- return try await send(try input.coreJSON(options: options), options: options)
38
- }
39
- }
40
- enum RequestCompletion: Sendable { case consumingUnit, idle }
41
-
42
- // One predicate for both modes, ready for S1's reviewed unit.end evidence.
43
- // OPEN(§18.24): Atlas must confirm unit.end and capture/retry evidence; no Rust ABI inferred.
44
- private func requestComplete(_ wait: RequestCompletion, status: LegacyInputStatus?, idle: Bool,
45
- carried: Bool, unit: UnitEnd?, id: String?) -> Bool {
46
- guard let id else { return false }
47
- switch wait {
48
- case .idle: return status?.terminal == true && idle
49
- case .consumingUnit: return unit?.inputs.contains(id) == true || (status?.terminal == true && !carried)
50
- }
51
- }
52
- private final class WaitCancellation: @unchecked Sendable {
53
- private let lock = NSLock()
54
- private var cancelled = false
55
- func cancel() { lock.withLock { cancelled = true } }
56
- var value: Bool { lock.withLock { cancelled } }
57
- }
58
- private final class RequestWaiter {
59
- var id: String?; let wait: RequestCompletion; let cancellation: WaitCancellation
60
- let continuation: CheckedContinuation<LegacyRequestResult, Error>
61
- var receipt: LegacyReceipt?; var status: LegacyInputStatus?; var carried = false
62
- var messages: [String: LegacyMessageEnd] = [:]
63
- // Per-call SDK observation bounds; losing observation never cancels Core.
64
- var beforeReceipt: [(RequestObservation, Int)] = []
65
- var beforeReceiptBytes = 0
66
- func dropBeforeReceipt() { beforeReceipt.removeAll(); beforeReceiptBytes = 0 }
67
- func retain(_ observation: RequestObservation, head: Int) {
68
- guard !lost, !cancellation.value else { dropBeforeReceipt(); return }
69
- guard let bytes = try? JSONEncoder().encode(observation).count,
70
- beforeReceipt.count < 256, beforeReceiptBytes + bytes <= 1_048_576 else {
71
- lost = true; dropBeforeReceipt(); return
72
- }
73
- beforeReceipt.append((observation, head)); beforeReceiptBytes += bytes
74
- }
75
- var captured = false
76
- var reading = true; var complete = false; var cutoff: Int?; var gap = false
77
- var lost = false
78
- init(id: String?, wait: RequestCompletion, cancellation: WaitCancellation, continuation: CheckedContinuation<LegacyRequestResult, Error>) {
79
- self.id = id; self.wait = wait; self.cancellation = cancellation; self.continuation = continuation
80
- }
81
- func add(_ message: LegacyMessageEnd) {
82
- guard let id, message.causedBy.contains(id), cutoff.map({ message.seq <= $0 }) ?? true else { return }
83
- messages["\(message.id):\(message.seq)"] = message
84
- }
85
- }
86
-
87
- // Every mutable member is under lock. Core callbacks update waiters synchronously;
88
- // the app only receives owned values through its independent queue.
89
- final class StreamHub: @unchecked Sendable {
90
- private let lock = NSLock()
91
- private let selectionLock = NSRecursiveLock()
92
- private let port: any CoreStreamPort
93
- private var observation: (@Sendable () -> Void)?
94
- private var projection: CoreProjection?
95
- private var branch: AppStreamBranch?
96
- private var waiters: [UUID: RequestWaiter] = [:]
97
- private var ended = false
98
- private var observedHead = 0
99
- private var currentState = LegacyStateEvent(status: .idle, queued: 0, typing: false)
100
- var state: LegacyStateEvent { lock.withLock { currentState } }
101
- var logId: String { port.logId }
102
- init(port: any CoreStreamPort) throws {
103
- self.port = port
104
- observation = try port.observe({ [weak self] in self?.receive($0) }, end: { [weak self] in self?.end($0) })
105
- }
106
- func events(initialMessages: Int = 50) -> AsyncStream<LegacyRuntimeEvent> {
107
- return events(StreamSelection(initialMessages: initialMessages, after: nil))
108
- }
109
- func events(after: Cursor) -> AsyncStream<LegacyRuntimeEvent> { events(StreamSelection(initialMessages: nil, after: after)) }
110
- private func events(_ selection: StreamSelection) -> AsyncStream<LegacyRuntimeEvent> { attach(selection).stream }
111
- func subscribe(_ options: LegacySubscribeOptions) -> LegacyCrocheAgent.Subscription {
112
- let selection = StreamSelection(initialMessages: options.initialMessages ?? (options.after == nil ? 50 : nil), after: options.after,
113
- deltaMs: options.deltaMs)
114
- return LegacyCrocheAgent.Subscription(branch: attach(selection), handler: options.onEvent)
115
- }
116
- private func attach(_ selection: StreamSelection) -> AppStreamBranch {
117
- selectionLock.lock(); defer { selectionLock.unlock() }
118
- // Both the actor façade and synchronous subscribe use this selection fence.
119
- let app = AppStreamBranch()
120
- let old: (AppStreamBranch?, CoreProjection?, Bool) = lock.withLock {
121
- let old = (branch, projection, ended)
122
- branch = app; projection = nil
123
- return old
124
- }
125
- old.1?.close(); old.0?.finish(.replaced)
126
- if selection.initialMessages != nil && selection.after != nil {
127
- app.finish(.streamError(LegacyStreamError(code: "invalid_configuration", message: "Use initialMessages or after, not both", poisoned: false)))
128
- return app
129
- }
130
- if let count = selection.initialMessages, !(0...256).contains(count) {
131
- app.finish(.streamError(LegacyStreamError(code: "invalid_configuration", message: "initialMessages must be in 0...256", poisoned: false)))
132
- return app
133
- }
134
- if old.2 { app.finish(.streamError(LegacyStreamError(code: "closed", message: "Runtime is closed", poisoned: false))); return app }
135
- let closeProjection = port.select(selection) { [weak app] in app?.push($0) }
136
- app.onEnd(closeProjection.close)
137
- app.setHistory(closeProjection.history)
138
- lock.withLock { projection = closeProjection }
139
- return app
140
- }
141
- static func errorStream(_ code: String, _ message: String) -> AsyncStream<LegacyRuntimeEvent> {
142
- AsyncStream { continuation in
143
- continuation.yield(.streamError(LegacyStreamError(code: code, message: message, poisoned: false)))
144
- continuation.finish()
145
- }
146
- }
147
- func send(_ input: SendInput, options: SendOptions) async throws -> LegacyReceipt {
148
- if Task.isCancelled { throw LegacyCrocheError("aborted", "Send cancelled before acceptance") }
149
- guard !lock.withLock({ ended }) else { throw LegacyCrocheError("closed", "Runtime is closed") }
150
- return try await port.send(input, options: options)
151
- }
152
- func history(before: Int?, limit: Int) async throws {
153
- guard (1...256).contains(limit) else { throw LegacyCrocheError("invalid_configuration", "history limit must be in 1...256") }
154
- let selected = lock.withLock { branch?.isActive == true && !ended ? projection : nil }
155
- guard let selected else { throw LegacyCrocheError("invalid_configuration", "No stream is attached") }
156
- try await selected.history(before, limit)
157
- }
158
- func cancel(_ id: String) async throws { try await port.cancel(id) }
159
- func clearHistory() async throws { try await port.clearHistory() }
160
- func request(_ input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = nil) async throws -> LegacyRequestResult {
161
- if Task.isCancelled { throw LegacyCrocheError("aborted", "Request cancelled before sending") }
162
- // Keel/rook: keep terminal + idle until the coordinated TS/Swift/Kotlin consuming-unit change.
163
- // Both nil and the approved public .idle use S2's terminal-plus-idle default.
164
- let completion: RequestCompletion = .idle
165
- let key = UUID(), cancellation = WaitCancellation()
166
- return try await withTaskCancellationHandler {
167
- try await withCheckedThrowingContinuation { continuation in
168
- let admitted = lock.withLock {
169
- if ended { continuation.resume(throwing: LegacyCrocheError("closed", "Runtime is closed")); return false }
170
- if cancellation.value { continuation.resume(throwing: LegacyCrocheError("aborted", "Request cancelled before sending")); return false }
171
- waiters[key] = RequestWaiter(id: nil, wait: completion, cancellation: cancellation, continuation: continuation)
172
- return true
173
- }
174
- guard admitted else { return }
175
- // Do not cancel the acceptance task when the caller stops waiting.
176
- Task { await self.accept(input, options: options, key: key) }
177
- }
178
- } onCancel: {
179
- cancellation.cancel()
180
- self.abort(key)
181
- }
182
- }
183
- private func accept(_ input: SendInput, options: SendOptions, key: UUID) async {
184
- var receipt: LegacyReceipt?
185
- do {
186
- let accepted = try await port.send(input, options: options)
187
- receipt = accepted
188
- let read = lock.withLock {
189
- guard let waiter = waiters[key] else { return false }
190
- waiter.id = accepted.requestId
191
- waiter.receipt = accepted
192
- let early = waiter.beforeReceipt
193
- waiter.dropBeforeReceipt()
194
- for (observation, head) in early { apply(observation, key: key, head: head) }
195
- // A same-id terminal retry emits no new input event. Seed its disposition
196
- // before idle can overtake capture; never regress a status already observed.
197
- if waiter.status == nil || (waiter.status?.terminal != true && accepted.status.terminal) {
198
- waiter.status = accepted.status
199
- }
200
- if waiter.lost { fail(key, code: "observation_lost"); return false }
201
- if waiter.cancellation.value { fail(key, code: "aborted"); return false }
202
- if accepted.seq == nil {
203
- waiters.removeValue(forKey: key)
204
- waiter.continuation.resume(returning: LegacyRequestResult(id: accepted.requestId, status: accepted.status, messages: [], gap: false, legacy: true))
205
- return false
206
- }
207
- return true
208
- }
209
- guard read, let seq = accepted.seq else { return }
210
- let retained = try await port.readOutcome(id: accepted.requestId, fromSeq: seq) { [weak self] captured in
211
- self?.capture(captured, key: key, receipt: accepted)
212
- }
213
- lock.withLock {
214
- guard let waiter = waiters[key] else { return }
215
- guard waiter.captured else { fail(key, code: "observation_lost"); return }
216
- for message in retained.messages { waiter.add(message) }
217
- waiter.gap = waiter.gap || retained.gap
218
- waiter.reading = false
219
- finish(key)
220
- }
221
- } catch {
222
- lock.withLock {
223
- guard let waiter = waiters.removeValue(forKey: key) else { return }
224
- waiter.continuation.resume(throwing: receipt.map { LegacyCrocheError("observation_lost", "Outcome observation failed", receipt: $0) } ?? error)
225
- }
226
- }
227
- }
228
- private func capture(_ captured: CapturedRequestState, key: UUID, receipt: LegacyReceipt) {
229
- lock.withLock {
230
- guard let waiter = waiters[key] else { return }
231
- waiter.captured = true
232
- if waiter.status?.terminal != true { waiter.status = captured.status }
233
- waiter.carried = waiter.carried || captured.carried
234
- waiter.gap = waiter.gap || receipt.seq! < captured.floor
235
- // A newly attached hub can finish a terminal retry at idle before it has seen
236
- // any sequence for that receipt. Its zero/older live cutoff must not discard
237
- // the scoped retained reply. An actual live completion cut stays unchanged.
238
- if waiter.complete, let cutoff = waiter.cutoff, cutoff < receipt.seq! {
239
- waiter.cutoff = captured.head
240
- }
241
- if !waiter.complete && requestComplete(waiter.wait, status: waiter.status, idle: captured.idle, carried: waiter.carried, unit: captured.unitEnd, id: waiter.id) {
242
- waiter.complete = true; waiter.cutoff = captured.head
243
- }
244
- }
245
- }
246
- private func receive(_ observation: RequestObservation) {
247
- lock.withLock {
248
- switch observation {
249
- case .input(let input): observedHead = max(observedHead, input.seq)
250
- case .messageEnd(let message): observedHead = max(observedHead, message.seq)
251
- case .state(let state): currentState = state
252
- case .unitEnd(let unit): observedHead = max(observedHead, unit.seq)
253
- }
254
- for key in Array(waiters.keys) {
255
- guard let waiter = waiters[key], !waiter.complete else { continue }
256
- if waiter.id == nil {
257
- waiter.retain(observation, head: observedHead)
258
- continue
259
- }
260
- apply(observation, key: key, head: observedHead)
261
- }
262
- }
263
- }
264
- // Caller holds lock. Replay uses the head at observation time, not a later head.
265
- private func apply(_ observation: RequestObservation, key: UUID, head: Int) {
266
- guard let waiter = waiters[key], !waiter.complete else { return }
267
- var idle = false, unit: UnitEnd?
268
- switch observation {
269
- case .input(let input) where input.id == waiter.id:
270
- if waiter.status?.terminal != true { waiter.status = input.status }
271
- waiter.carried = waiter.carried || input.carried
272
- case .messageEnd(let message): waiter.add(message)
273
- case .state(let state): idle = state.status == .idle
274
- case .unitEnd(let value): unit = value
275
- default: break
276
- }
277
- if requestComplete(waiter.wait, status: waiter.status, idle: idle, carried: waiter.carried, unit: unit, id: waiter.id) {
278
- waiter.complete = true; waiter.cutoff = unit?.seq ?? head
279
- }
280
- finish(key)
281
- }
282
- private func finish(_ key: UUID) {
283
- guard let waiter = waiters[key], !waiter.reading, waiter.complete, let receipt = waiter.receipt, let status = waiter.status else { return }
284
- waiters.removeValue(forKey: key)
285
- waiter.continuation.resume(returning: LegacyRequestResult(id: receipt.requestId, status: status, messages: waiter.messages.values.sorted { $0.seq < $1.seq }, gap: waiter.gap, legacy: false))
286
- }
287
- // Caller must hold lock.
288
- private func fail(_ key: UUID, code: String) {
289
- guard let waiter = waiters.removeValue(forKey: key) else { return }
290
- waiter.continuation.resume(throwing: LegacyCrocheError(code, "The wait ended; accepted input continues", receipt: waiter.receipt))
291
- }
292
- private func abort(_ key: UUID) { lock.withLock {
293
- waiters[key]?.dropBeforeReceipt()
294
- if waiters[key]?.receipt != nil { fail(key, code: "aborted") }
295
- } }
296
- func close() {
297
- end(LegacyStreamError(code: "closed", message: "Runtime is closed", poisoned: false), drain: false)
298
- let detach = lock.withLock { let old = observation; observation = nil; return old }
299
- detach?()
300
- }
301
- deinit { observation?(); projection?.close() }
302
- private func end(_ error: LegacyStreamError?, drain: Bool = true) {
303
- let old: (AppStreamBranch?, CoreProjection?) = lock.withLock {
304
- guard !ended else { return (nil, nil) }
305
- ended = true
306
- for key in Array(waiters.keys) {
307
- waiters[key]?.lost = true
308
- waiters[key]?.dropBeforeReceipt()
309
- if waiters[key]?.receipt != nil { fail(key, code: "observation_lost") }
310
- }
311
- return (branch, projection)
312
- }
313
- old.1?.close()
314
- old.0?.finish(error.map(LegacyRuntimeEvent.streamError), drain: drain && error != nil)
315
- }
316
- }
317
-
318
- // AsyncStream's unfolding form lets this SDK count queued UTF-8 bytes and events.
319
- // Retain the delivered event's budget until next() is called again: the for-await
320
- // body has then finished (Keel ruling 6071234795).
321
- private final class AppStreamBranch: @unchecked Sendable {
322
- private let lock = NSLock()
323
- private var queue: [(LegacyRuntimeEvent, Int)] = []
324
- private var bytes = 0
325
- private var inFlightBytes: Int?
326
- private var active = true
327
- private var terminal: LegacyRuntimeEvent?
328
- private var consumer: CheckedContinuation<LegacyRuntimeEvent?, Never>?
329
- private var closeProjection: (@Sendable () -> Void)?
330
- private var historyPage: (@Sendable (Int?, Int) async throws -> Void)?
331
- private var immediateEnd: (@Sendable (LegacyRuntimeEvent?) -> Void)?
332
- private var immediateReason: LegacyRuntimeEvent?
333
- private var endedImmediately = false
334
- func setHistory(_ history: @escaping @Sendable (Int?, Int) async throws -> Void) { lock.withLock { historyPage = history } }
335
- func history(_ options: LegacyHistoryOptions) async throws {
336
- guard (1...256).contains(options.limit) else { throw LegacyCrocheError("invalid_configuration", "history limit must be in 1...256") }
337
- let page = lock.withLock { active ? historyPage : nil }
338
- guard let page else { throw LegacyCrocheError("invalid_configuration", "No stream is attached") }
339
- try await page(options.before, options.limit)
340
- }
341
- func observeImmediateEnd(_ observer: @escaping @Sendable (LegacyRuntimeEvent?) -> Void) {
342
- let prior: (Bool, LegacyRuntimeEvent?) = lock.withLock { immediateEnd = observer; return (endedImmediately, immediateReason) }
343
- if prior.0 { observer(prior.1) }
344
- }
345
- var isActive: Bool { lock.withLock { active } }
346
- var stream: AsyncStream<LegacyRuntimeEvent> {
347
- AsyncStream(unfolding: { await self.next() }, onCancel: { self.finish(nil) })
348
- }
349
- func onEnd(_ close: @escaping @Sendable () -> Void) {
350
- let alreadyEnded = lock.withLock { closeProjection = close; return !active }
351
- if alreadyEnded { close() }
352
- }
353
- func push(_ event: LegacyRuntimeEvent) {
354
- if case .replaced = event { finish(event); return }
355
- if case .streamError = event {
356
- finish(event, drain: true); return
357
- }
358
- let count: Int
359
- do { count = try event.serializedBytes() }
360
- catch { finish(.streamError(LegacyStreamError(code: "handler_failed", message: "Event cannot be encoded", poisoned: false))); return }
361
- let overflow = lock.withLock {
362
- guard active else { return false }
363
- if queue.count + (inFlightBytes == nil ? 0 : 1) + 1 > 256 || bytes + count > 1_048_576 { return true }
364
- if let consumer { self.consumer = nil; inFlightBytes = count; bytes += count; consumer.resume(returning: event); return false }
365
- queue.append((event, count)); bytes += count
366
- return false
367
- }
368
- if overflow { finish(.streamError(LegacyStreamError(code: "subscriber_overflow", message: "App event buffer exceeded", poisoned: false))) }
369
- }
370
- func finish(_ event: LegacyRuntimeEvent?, drain: Bool = false) {
371
- let result: ((@Sendable () -> Void)?, (@Sendable (LegacyRuntimeEvent?) -> Void)?) = lock.withLock {
372
- guard active else { return (nil, nil) }
373
- active = false
374
- // Keel ruling 6071234795: Core errors drain; SDK-side ends drop queued values.
375
- if drain {} else { queue.removeAll(); bytes = 0; inFlightBytes = nil }
376
- terminal = event
377
- if let consumer { self.consumer = nil; terminal = nil; consumer.resume(returning: event) }
378
- if !drain { endedImmediately = true; immediateReason = event }
379
- return (closeProjection, drain ? nil : immediateEnd)
380
- }
381
- result.0?()
382
- result.1?(event)
383
- }
384
- private func next() async -> LegacyRuntimeEvent? {
385
- await withCheckedContinuation { continuation in
386
- lock.withLock {
387
- if let inFlightBytes { bytes -= inFlightBytes; self.inFlightBytes = nil }
388
- if !queue.isEmpty { let item = queue.removeFirst(); inFlightBytes = item.1; continuation.resume(returning: item.0) }
389
- else if !active { let last = terminal; terminal = nil; continuation.resume(returning: last) }
390
- else { consumer = continuation }
391
- }
392
- }
393
- }
394
- }
395
-
396
- extension LegacyRuntimeEvent {
397
- // Match the flat wire shape; Swift's synthesized enum encoding adds wrappers.
398
- func serializedBytes() throws -> Int {
399
- let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
400
- return try encoder.encode(wireJSON()).count
401
- }
402
- func wireJSON() throws -> JSON {
403
- let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.withoutEscapingSlashes]
404
- func fields<T: Encodable>(_ value: T, _ type: String) throws -> JSON {
405
- var json = try JSON(data: encoder.encode(value)); json["type"] = .string(type); return json
406
- }
407
- let json: JSON
408
- switch self {
409
- case .input(let v): json = try fields(v, "input")
410
- case .messageStart(let v): json = try fields(v, "message.start")
411
- case .messageDelta(let v): json = try fields(v, "message.delta")
412
- case .messageEnd(let v): json = try fields(v, "message.end")
413
- case .cleared(let v): json = try fields(v, "cleared")
414
- case .app(let v): json = try fields(v, "app")
415
- case .turn(let v): json = try fields(v, "turn")
416
- case .state(let v): json = try fields(v, "state")
417
- case .error(let v): json = try fields(v, "error")
418
- case .gap(let v): json = try fields(v, "gap")
419
- case .snapshot(let v): json = try fields(v, "snapshot")
420
- case .streamError(let v): json = try fields(v, "error")
421
- case .page(let v):
422
- json = .object(["type": .string("page"), "messages": .array(try v.messages.map { try $0.wireJSON() }), "reachedFloor": .bool(v.reachedFloor), "logId": .string(v.logId), "clearedSeq": .number(Double(v.clearedSeq))])
423
- case .replaced: json = .object(["type": .string("replaced")])
424
- case .unknown(let type, let fields):
425
- var object = fields.object ?? [:]; object["type"] = .string(type); json = .object(object)
426
- }
427
- return json
428
- }
429
- }
430
-
431
-
432
- extension LegacyCrocheAgent {
433
- /// Nested (APP-API, founder 09:21Z): a top-level `Subscription` collides with Combine's.
434
- /// One serialized application callback branch; requests have an independent observation.
435
- public final class Subscription: @unchecked Sendable {
436
- private let lock = NSLock()
437
- private let branch: AppStreamBranch
438
- private let handler: @Sendable (LegacyRuntimeEvent) async -> Void
439
- private var outcome: LegacyAppStreamEnd?
440
- private var waits: [CheckedContinuation<LegacyAppStreamEnd, Never>] = []
441
- private var silenced = false
442
- private var consumer: Task<Void, Never>?
443
- fileprivate init(branch: AppStreamBranch, handler: @escaping @Sendable (LegacyRuntimeEvent) async -> Void) {
444
- self.branch = branch; self.handler = handler
445
- branch.observeImmediateEnd { [weak self] event in self?.finish(event, notify: true) }
446
- consumer = Task { [weak self] in
447
- for await event in branch.stream {
448
- guard let self else { return }
449
- if self.lock.withLock({ self.outcome != nil }) { return }
450
- if Self.reason(event) != nil { self.finish(event, notify: false) }
451
- await handler(event)
452
- }
453
- self?.finish(nil, notify: false)
454
- }
455
- }
456
- public var ended: LegacyAppStreamEnd {
457
- get async {
458
- await withCheckedContinuation { continuation in
459
- lock.withLock {
460
- if let outcome { continuation.resume(returning: outcome) }
461
- else { waits.append(continuation) }
462
- }
463
- }
464
- }
465
- }
466
- public func close() {
467
- lock.withLock { silenced = true }
468
- finish(nil, notify: false)
469
- branch.finish(nil)
470
- consumer?.cancel()
471
- }
472
- public func history(_ options: LegacyHistoryOptions) async throws { try await branch.history(options) }
473
- private static func reason(_ event: LegacyRuntimeEvent?) -> String? {
474
- switch event {
475
- case .streamError(let error): return error.code
476
- case .replaced: return "replaced"
477
- default: return nil
478
- }
479
- }
480
- private func finish(_ event: LegacyRuntimeEvent?, notify: Bool) {
481
- let accepted = lock.withLock {
482
- guard outcome == nil else { return false }
483
- let result = LegacyAppStreamEnd(code: Self.reason(event) ?? "closed")
484
- outcome = result
485
- for continuation in waits { continuation.resume(returning: result) }
486
- waits.removeAll(); return true
487
- }
488
- if accepted && notify, let event {
489
- Task { [weak self] in
490
- guard let self, !self.lock.withLock({ self.silenced }) else { return }
491
- await self.handler(event)
492
- }
493
- }
494
- }
495
- }
496
- }
@@ -1,44 +0,0 @@
1
- import Foundation
2
-
3
- #if CROCHE_SUBSCRIPTION_HOST
4
- /// Host-only stand-in for the agent class: the namespace `Subscription` nests in.
5
- enum LegacyCrocheAgent {}
6
- // Test-only façade, same public type and forwarding methods as the FFI build.
7
- // Fake Core is supplied by tests, never a production create implementation.
8
- actor AgentEngine {
9
- let subscriptionHub: StreamHub?
10
- public nonisolated let logId: String
11
- init(port: any CoreStreamPort) throws { subscriptionHub = try StreamHub(port: port); logId = port.logId }
12
- public func clearHistory() async throws { try await subscriptionHub?.clearHistory() }
13
- public func close() async throws { subscriptionHub?.close() }
14
- }
15
- #endif
16
-
17
- extension AgentEngine {
18
- public func events(initialMessages: Int = 50) -> AsyncStream<LegacyRuntimeEvent> {
19
- subscriptionHub?.events(initialMessages: initialMessages) ?? StreamHub.errorStream("invalid_configuration", "Subscription Core port is not bound")
20
- }
21
- public func events(after: Cursor) -> AsyncStream<LegacyRuntimeEvent> {
22
- subscriptionHub?.events(after: after) ?? StreamHub.errorStream("invalid_configuration", "Subscription Core port is not bound")
23
- }
24
- /// SDK shorthand only; Core generates the id and validates the request.
25
- public func send(_ text: String, options: SendOptions = SendOptions()) async throws -> LegacyReceipt {
26
- try await send(SendInput(input: [.text(text, kind: .user)]), options: options)
27
- }
28
- public func send(_ input: SendInput, options: SendOptions = SendOptions()) async throws -> LegacyReceipt {
29
- guard let hub = subscriptionHub else { throw LegacyCrocheError("invalid_configuration", "Subscription Core port is not bound") }
30
- return try await hub.send(input, options: options)
31
- }
32
- public func request(_ input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = nil) async throws -> LegacyRequestResult {
33
- guard let hub = subscriptionHub else { throw LegacyCrocheError("invalid_configuration", "Subscription Core port is not bound") }
34
- return try await hub.request(input, options: options, wait: wait)
35
- }
36
- public func cancel(_ id: String) async throws {
37
- guard let hub = subscriptionHub else { throw LegacyCrocheError("invalid_configuration", "Subscription Core port is not bound") }
38
- try await hub.cancel(id)
39
- }
40
- public func history(before: Int? = nil, limit: Int) async throws {
41
- guard let hub = subscriptionHub else { throw LegacyCrocheError("invalid_configuration", "Subscription Core port is not bound") }
42
- try await hub.history(before: before, limit: limit)
43
- }
44
- }