@h1r-ai/croche-react-native 0.5.4 → 0.6.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 (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -2,7 +2,7 @@ import Foundation
2
2
 
3
3
  // Proposed SDK-internal seam only. Core owns projection, ordered capture, delta fences,
4
4
  // and storage. select/history never allocate a second canonical observation.
5
- struct StreamSelection: Sendable { var initialMessages: Int?; var after: Cursor? }
5
+ struct StreamSelection: Sendable { var initialMessages: Int?; var after: Cursor?; var deltaMs: Int? = nil }
6
6
  struct CoreProjection: Sendable {
7
7
  /// Joins Core's synchronous listener, not buffered AsyncStream/UI consumers. A synchronous
8
8
  /// close from that listener itself fences without waiting for its own stack.
@@ -11,30 +11,39 @@ struct CoreProjection: Sendable {
11
11
  let close: @Sendable () -> Void
12
12
  let history: @Sendable (Int?, Int) async throws -> Void
13
13
  }
14
- struct UnitEnd: Sendable { let seq: Int; let inputs: [String]; let pending: [String] }
15
- struct InputObservation: Sendable { let id: String; let seq: Int; let status: InputStatus; let carried: Bool }
16
- enum RequestObservation: Sendable { case input(InputObservation), messageEnd(MessageEnd), state(StateEvent), unitEnd(UnitEnd) }
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
17
  struct CapturedRequestState: Sendable {
18
- let head: Int; let floor: Int; let status: InputStatus; let idle: Bool
18
+ let head: Int; let floor: Int; let status: LegacyInputStatus; let idle: Bool
19
19
  let carried: Bool; let unitEnd: UnitEnd?
20
20
  }
21
- struct RetainedRequestEnds: Sendable { let messages: [MessageEnd]; let gap: Bool }
21
+ struct RetainedRequestEnds: Sendable { let messages: [LegacyMessageEnd]; let gap: Bool }
22
22
  protocol CoreStreamPort: Sendable {
23
23
  var logId: String { get }
24
24
  func observe(_ event: @escaping @Sendable (RequestObservation) -> Void,
25
- end: @escaping @Sendable (StreamError?) -> Void) throws -> @Sendable () -> Void
26
- func select(_ selection: StreamSelection, event: @escaping @Sendable (RuntimeEvent) -> Void) -> CoreProjection
27
- func send(_ input: JSON, options: SendOptions) async throws -> Receipt
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
28
30
  func readOutcome(id: String, fromSeq: Int, captured: @escaping @Sendable (CapturedRequestState) -> Void) async throws -> RetainedRequestEnds
29
31
  func cancel(_ id: String) async throws
30
32
  func clearHistory() async throws
31
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
+ }
32
40
  enum RequestCompletion: Sendable { case consumingUnit, idle }
33
41
 
34
42
  // One predicate for both modes, ready for S1's reviewed unit.end evidence.
35
43
  // OPEN(§18.24): Atlas must confirm unit.end and capture/retry evidence; no Rust ABI inferred.
36
- private func requestComplete(_ wait: RequestCompletion, status: InputStatus?, idle: Bool,
37
- carried: Bool, unit: UnitEnd?, id: String) -> Bool {
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 }
38
47
  switch wait {
39
48
  case .idle: return status?.terminal == true && idle
40
49
  case .consumingUnit: return unit?.inputs.contains(id) == true || (status?.terminal == true && !carried)
@@ -47,18 +56,30 @@ private final class WaitCancellation: @unchecked Sendable {
47
56
  var value: Bool { lock.withLock { cancelled } }
48
57
  }
49
58
  private final class RequestWaiter {
50
- let id: String; let wait: RequestCompletion; let cancellation: WaitCancellation
51
- let continuation: CheckedContinuation<RequestResult, Error>
52
- var receipt: Receipt?; var status: InputStatus?; var carried = false
53
- var messages: [String: MessageEnd] = [:]
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
+ }
54
75
  var captured = false
55
76
  var reading = true; var complete = false; var cutoff: Int?; var gap = false
56
77
  var lost = false
57
- init(id: String, wait: RequestCompletion, cancellation: WaitCancellation, continuation: CheckedContinuation<RequestResult, Error>) {
78
+ init(id: String?, wait: RequestCompletion, cancellation: WaitCancellation, continuation: CheckedContinuation<LegacyRequestResult, Error>) {
58
79
  self.id = id; self.wait = wait; self.cancellation = cancellation; self.continuation = continuation
59
80
  }
60
- func add(_ message: MessageEnd) {
61
- guard message.causedBy.contains(id), cutoff.map({ message.seq <= $0 }) ?? true else { return }
81
+ func add(_ message: LegacyMessageEnd) {
82
+ guard let id, message.causedBy.contains(id), cutoff.map({ message.seq <= $0 }) ?? true else { return }
62
83
  messages["\(message.id):\(message.seq)"] = message
63
84
  }
64
85
  }
@@ -75,21 +96,22 @@ final class StreamHub: @unchecked Sendable {
75
96
  private var waiters: [UUID: RequestWaiter] = [:]
76
97
  private var ended = false
77
98
  private var observedHead = 0
78
- private var currentState = StateEvent(status: .idle, queued: 0, typing: false)
79
- var state: StateEvent { lock.withLock { currentState } }
99
+ private var currentState = LegacyStateEvent(status: .idle, queued: 0, typing: false)
100
+ var state: LegacyStateEvent { lock.withLock { currentState } }
80
101
  var logId: String { port.logId }
81
102
  init(port: any CoreStreamPort) throws {
82
103
  self.port = port
83
104
  observation = try port.observe({ [weak self] in self?.receive($0) }, end: { [weak self] in self?.end($0) })
84
105
  }
85
- func events(initialMessages: Int = 50) -> AsyncStream<RuntimeEvent> {
106
+ func events(initialMessages: Int = 50) -> AsyncStream<LegacyRuntimeEvent> {
86
107
  return events(StreamSelection(initialMessages: initialMessages, after: nil))
87
108
  }
88
- func events(after: Cursor) -> AsyncStream<RuntimeEvent> { events(StreamSelection(initialMessages: nil, after: after)) }
89
- private func events(_ selection: StreamSelection) -> AsyncStream<RuntimeEvent> { attach(selection).stream }
90
- func subscribe(_ options: SubscribeOptions) -> AgentSubscription {
91
- let selection = StreamSelection(initialMessages: options.initialMessages ?? (options.after == nil ? 50 : nil), after: options.after)
92
- return AgentSubscription(branch: attach(selection), handler: options.onEvent)
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)
93
115
  }
94
116
  private func attach(_ selection: StreamSelection) -> AppStreamBranch {
95
117
  selectionLock.lock(); defer { selectionLock.unlock() }
@@ -102,41 +124,41 @@ final class StreamHub: @unchecked Sendable {
102
124
  }
103
125
  old.1?.close(); old.0?.finish(.replaced)
104
126
  if selection.initialMessages != nil && selection.after != nil {
105
- app.finish(.streamError(StreamError(code: "invalid_configuration", message: "Use initialMessages or after, not both", poisoned: false)))
127
+ app.finish(.streamError(LegacyStreamError(code: "invalid_configuration", message: "Use initialMessages or after, not both", poisoned: false)))
106
128
  return app
107
129
  }
108
130
  if let count = selection.initialMessages, !(0...256).contains(count) {
109
- app.finish(.streamError(StreamError(code: "invalid_configuration", message: "initialMessages must be in 0...256", poisoned: false)))
131
+ app.finish(.streamError(LegacyStreamError(code: "invalid_configuration", message: "initialMessages must be in 0...256", poisoned: false)))
110
132
  return app
111
133
  }
112
- if old.2 { app.finish(.streamError(StreamError(code: "closed", message: "Runtime is closed", poisoned: false))); return app }
134
+ if old.2 { app.finish(.streamError(LegacyStreamError(code: "closed", message: "Runtime is closed", poisoned: false))); return app }
113
135
  let closeProjection = port.select(selection) { [weak app] in app?.push($0) }
114
136
  app.onEnd(closeProjection.close)
115
137
  app.setHistory(closeProjection.history)
116
138
  lock.withLock { projection = closeProjection }
117
139
  return app
118
140
  }
119
- static func errorStream(_ code: String, _ message: String) -> AsyncStream<RuntimeEvent> {
141
+ static func errorStream(_ code: String, _ message: String) -> AsyncStream<LegacyRuntimeEvent> {
120
142
  AsyncStream { continuation in
121
- continuation.yield(.streamError(StreamError(code: code, message: message, poisoned: false)))
143
+ continuation.yield(.streamError(LegacyStreamError(code: code, message: message, poisoned: false)))
122
144
  continuation.finish()
123
145
  }
124
146
  }
125
- func send(_ input: SendInput, options: SendOptions) async throws -> Receipt {
126
- if Task.isCancelled { throw CrocheError("aborted", "Send cancelled before acceptance") }
127
- guard !lock.withLock({ ended }) else { throw CrocheError("closed", "Runtime is closed") }
128
- return try await port.send(try input.coreJSON(options: options), options: options)
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)
129
151
  }
130
152
  func history(before: Int?, limit: Int) async throws {
131
- guard (1...256).contains(limit) else { throw CrocheError("invalid_configuration", "history limit must be in 1...256") }
153
+ guard (1...256).contains(limit) else { throw LegacyCrocheError("invalid_configuration", "history limit must be in 1...256") }
132
154
  let selected = lock.withLock { branch?.isActive == true && !ended ? projection : nil }
133
- guard let selected else { throw CrocheError("invalid_configuration", "No stream is attached") }
155
+ guard let selected else { throw LegacyCrocheError("invalid_configuration", "No stream is attached") }
134
156
  try await selected.history(before, limit)
135
157
  }
136
158
  func cancel(_ id: String) async throws { try await port.cancel(id) }
137
159
  func clearHistory() async throws { try await port.clearHistory() }
138
- func request(_ input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = nil) async throws -> RequestResult {
139
- if Task.isCancelled { throw CrocheError("aborted", "Request cancelled before sending") }
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") }
140
162
  // Keel/rook: keep terminal + idle until the coordinated TS/Swift/Kotlin consuming-unit change.
141
163
  // Both nil and the approved public .idle use S2's terminal-plus-idle default.
142
164
  let completion: RequestCompletion = .idle
@@ -144,9 +166,9 @@ final class StreamHub: @unchecked Sendable {
144
166
  return try await withTaskCancellationHandler {
145
167
  try await withCheckedThrowingContinuation { continuation in
146
168
  let admitted = lock.withLock {
147
- if ended { continuation.resume(throwing: CrocheError("closed", "Runtime is closed")); return false }
148
- if cancellation.value { continuation.resume(throwing: CrocheError("aborted", "Request cancelled before sending")); return false }
149
- waiters[key] = RequestWaiter(id: input.id, wait: completion, cancellation: cancellation, continuation: continuation)
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)
150
172
  return true
151
173
  }
152
174
  guard admitted else { return }
@@ -159,13 +181,17 @@ final class StreamHub: @unchecked Sendable {
159
181
  }
160
182
  }
161
183
  private func accept(_ input: SendInput, options: SendOptions, key: UUID) async {
162
- var receipt: Receipt?
184
+ var receipt: LegacyReceipt?
163
185
  do {
164
- let accepted = try await port.send(try input.coreJSON(options: options), options: options)
186
+ let accepted = try await port.send(input, options: options)
165
187
  receipt = accepted
166
188
  let read = lock.withLock {
167
189
  guard let waiter = waiters[key] else { return false }
190
+ waiter.id = accepted.requestId
168
191
  waiter.receipt = accepted
192
+ let early = waiter.beforeReceipt
193
+ waiter.dropBeforeReceipt()
194
+ for (observation, head) in early { apply(observation, key: key, head: head) }
169
195
  // A same-id terminal retry emits no new input event. Seed its disposition
170
196
  // before idle can overtake capture; never regress a status already observed.
171
197
  if waiter.status == nil || (waiter.status?.terminal != true && accepted.status.terminal) {
@@ -175,13 +201,13 @@ final class StreamHub: @unchecked Sendable {
175
201
  if waiter.cancellation.value { fail(key, code: "aborted"); return false }
176
202
  if accepted.seq == nil {
177
203
  waiters.removeValue(forKey: key)
178
- waiter.continuation.resume(returning: RequestResult(id: accepted.id, status: accepted.status, messages: [], gap: false, legacy: true))
204
+ waiter.continuation.resume(returning: LegacyRequestResult(id: accepted.requestId, status: accepted.status, messages: [], gap: false, legacy: true))
179
205
  return false
180
206
  }
181
207
  return true
182
208
  }
183
209
  guard read, let seq = accepted.seq else { return }
184
- let retained = try await port.readOutcome(id: accepted.id, fromSeq: seq) { [weak self] captured in
210
+ let retained = try await port.readOutcome(id: accepted.requestId, fromSeq: seq) { [weak self] captured in
185
211
  self?.capture(captured, key: key, receipt: accepted)
186
212
  }
187
213
  lock.withLock {
@@ -195,11 +221,11 @@ final class StreamHub: @unchecked Sendable {
195
221
  } catch {
196
222
  lock.withLock {
197
223
  guard let waiter = waiters.removeValue(forKey: key) else { return }
198
- waiter.continuation.resume(throwing: receipt.map { CrocheError("observation_lost", "Outcome observation failed", receipt: $0) } ?? error)
224
+ waiter.continuation.resume(throwing: receipt.map { LegacyCrocheError("observation_lost", "Outcome observation failed", receipt: $0) } ?? error)
199
225
  }
200
226
  }
201
227
  }
202
- private func capture(_ captured: CapturedRequestState, key: UUID, receipt: Receipt) {
228
+ private func capture(_ captured: CapturedRequestState, key: UUID, receipt: LegacyReceipt) {
203
229
  lock.withLock {
204
230
  guard let waiter = waiters[key] else { return }
205
231
  waiter.captured = true
@@ -227,52 +253,65 @@ final class StreamHub: @unchecked Sendable {
227
253
  }
228
254
  for key in Array(waiters.keys) {
229
255
  guard let waiter = waiters[key], !waiter.complete else { continue }
230
- var idle = false, unit: UnitEnd?
231
- switch observation {
232
- case .input(let input) where input.id == waiter.id:
233
- if waiter.status?.terminal != true { waiter.status = input.status }
234
- waiter.carried = waiter.carried || input.carried
235
- case .messageEnd(let message): waiter.add(message)
236
- case .state(let state): idle = state.status == .idle
237
- case .unitEnd(let value): unit = value
238
- default: break
239
- }
240
- if requestComplete(waiter.wait, status: waiter.status, idle: idle, carried: waiter.carried, unit: unit, id: waiter.id) {
241
- waiter.complete = true; waiter.cutoff = unit?.seq ?? observedHead
256
+ if waiter.id == nil {
257
+ waiter.retain(observation, head: observedHead)
258
+ continue
242
259
  }
243
- finish(key)
260
+ apply(observation, key: key, head: observedHead)
244
261
  }
245
262
  }
246
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
+ }
247
282
  private func finish(_ key: UUID) {
248
283
  guard let waiter = waiters[key], !waiter.reading, waiter.complete, let receipt = waiter.receipt, let status = waiter.status else { return }
249
284
  waiters.removeValue(forKey: key)
250
- waiter.continuation.resume(returning: RequestResult(id: receipt.id, status: status, messages: waiter.messages.values.sorted { $0.seq < $1.seq }, gap: waiter.gap, legacy: false))
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))
251
286
  }
252
287
  // Caller must hold lock.
253
288
  private func fail(_ key: UUID, code: String) {
254
289
  guard let waiter = waiters.removeValue(forKey: key) else { return }
255
- waiter.continuation.resume(throwing: CrocheError(code, "The wait ended; accepted input continues", receipt: waiter.receipt))
290
+ waiter.continuation.resume(throwing: LegacyCrocheError(code, "The wait ended; accepted input continues", receipt: waiter.receipt))
256
291
  }
257
- private func abort(_ key: UUID) { lock.withLock { if waiters[key]?.receipt != nil { fail(key, code: "aborted") } } }
292
+ private func abort(_ key: UUID) { lock.withLock {
293
+ waiters[key]?.dropBeforeReceipt()
294
+ if waiters[key]?.receipt != nil { fail(key, code: "aborted") }
295
+ } }
258
296
  func close() {
259
- end(StreamError(code: "closed", message: "Runtime is closed", poisoned: false), drain: false)
297
+ end(LegacyStreamError(code: "closed", message: "Runtime is closed", poisoned: false), drain: false)
260
298
  let detach = lock.withLock { let old = observation; observation = nil; return old }
261
299
  detach?()
262
300
  }
263
301
  deinit { observation?(); projection?.close() }
264
- private func end(_ error: StreamError?, drain: Bool = true) {
302
+ private func end(_ error: LegacyStreamError?, drain: Bool = true) {
265
303
  let old: (AppStreamBranch?, CoreProjection?) = lock.withLock {
266
304
  guard !ended else { return (nil, nil) }
267
305
  ended = true
268
306
  for key in Array(waiters.keys) {
269
307
  waiters[key]?.lost = true
308
+ waiters[key]?.dropBeforeReceipt()
270
309
  if waiters[key]?.receipt != nil { fail(key, code: "observation_lost") }
271
310
  }
272
311
  return (branch, projection)
273
312
  }
274
313
  old.1?.close()
275
- old.0?.finish(error.map(RuntimeEvent.streamError), drain: drain && error != nil)
314
+ old.0?.finish(error.map(LegacyRuntimeEvent.streamError), drain: drain && error != nil)
276
315
  }
277
316
  }
278
317
 
@@ -281,44 +320,44 @@ final class StreamHub: @unchecked Sendable {
281
320
  // body has then finished (Keel ruling 6071234795).
282
321
  private final class AppStreamBranch: @unchecked Sendable {
283
322
  private let lock = NSLock()
284
- private var queue: [(RuntimeEvent, Int)] = []
323
+ private var queue: [(LegacyRuntimeEvent, Int)] = []
285
324
  private var bytes = 0
286
325
  private var inFlightBytes: Int?
287
326
  private var active = true
288
- private var terminal: RuntimeEvent?
289
- private var consumer: CheckedContinuation<RuntimeEvent?, Never>?
327
+ private var terminal: LegacyRuntimeEvent?
328
+ private var consumer: CheckedContinuation<LegacyRuntimeEvent?, Never>?
290
329
  private var closeProjection: (@Sendable () -> Void)?
291
330
  private var historyPage: (@Sendable (Int?, Int) async throws -> Void)?
292
- private var immediateEnd: (@Sendable (RuntimeEvent?) -> Void)?
293
- private var immediateReason: RuntimeEvent?
331
+ private var immediateEnd: (@Sendable (LegacyRuntimeEvent?) -> Void)?
332
+ private var immediateReason: LegacyRuntimeEvent?
294
333
  private var endedImmediately = false
295
334
  func setHistory(_ history: @escaping @Sendable (Int?, Int) async throws -> Void) { lock.withLock { historyPage = history } }
296
- func history(_ options: HistoryOptions) async throws {
297
- guard (1...256).contains(options.limit) else { throw CrocheError("invalid_configuration", "history limit must be in 1...256") }
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") }
298
337
  let page = lock.withLock { active ? historyPage : nil }
299
- guard let page else { throw CrocheError("invalid_configuration", "No stream is attached") }
338
+ guard let page else { throw LegacyCrocheError("invalid_configuration", "No stream is attached") }
300
339
  try await page(options.before, options.limit)
301
340
  }
302
- func observeImmediateEnd(_ observer: @escaping @Sendable (RuntimeEvent?) -> Void) {
303
- let prior: (Bool, RuntimeEvent?) = lock.withLock { immediateEnd = observer; return (endedImmediately, immediateReason) }
341
+ func observeImmediateEnd(_ observer: @escaping @Sendable (LegacyRuntimeEvent?) -> Void) {
342
+ let prior: (Bool, LegacyRuntimeEvent?) = lock.withLock { immediateEnd = observer; return (endedImmediately, immediateReason) }
304
343
  if prior.0 { observer(prior.1) }
305
344
  }
306
345
  var isActive: Bool { lock.withLock { active } }
307
- var stream: AsyncStream<RuntimeEvent> {
346
+ var stream: AsyncStream<LegacyRuntimeEvent> {
308
347
  AsyncStream(unfolding: { await self.next() }, onCancel: { self.finish(nil) })
309
348
  }
310
349
  func onEnd(_ close: @escaping @Sendable () -> Void) {
311
350
  let alreadyEnded = lock.withLock { closeProjection = close; return !active }
312
351
  if alreadyEnded { close() }
313
352
  }
314
- func push(_ event: RuntimeEvent) {
353
+ func push(_ event: LegacyRuntimeEvent) {
315
354
  if case .replaced = event { finish(event); return }
316
355
  if case .streamError = event {
317
356
  finish(event, drain: true); return
318
357
  }
319
358
  let count: Int
320
359
  do { count = try event.serializedBytes() }
321
- catch { finish(.streamError(StreamError(code: "handler_failed", message: "Event cannot be encoded", poisoned: false))); return }
360
+ catch { finish(.streamError(LegacyStreamError(code: "handler_failed", message: "Event cannot be encoded", poisoned: false))); return }
322
361
  let overflow = lock.withLock {
323
362
  guard active else { return false }
324
363
  if queue.count + (inFlightBytes == nil ? 0 : 1) + 1 > 256 || bytes + count > 1_048_576 { return true }
@@ -326,10 +365,10 @@ private final class AppStreamBranch: @unchecked Sendable {
326
365
  queue.append((event, count)); bytes += count
327
366
  return false
328
367
  }
329
- if overflow { finish(.streamError(StreamError(code: "subscriber_overflow", message: "App event buffer exceeded", poisoned: false))) }
368
+ if overflow { finish(.streamError(LegacyStreamError(code: "subscriber_overflow", message: "App event buffer exceeded", poisoned: false))) }
330
369
  }
331
- func finish(_ event: RuntimeEvent?, drain: Bool = false) {
332
- let result: ((@Sendable () -> Void)?, (@Sendable (RuntimeEvent?) -> Void)?) = lock.withLock {
370
+ func finish(_ event: LegacyRuntimeEvent?, drain: Bool = false) {
371
+ let result: ((@Sendable () -> Void)?, (@Sendable (LegacyRuntimeEvent?) -> Void)?) = lock.withLock {
333
372
  guard active else { return (nil, nil) }
334
373
  active = false
335
374
  // Keel ruling 6071234795: Core errors drain; SDK-side ends drop queued values.
@@ -342,7 +381,7 @@ private final class AppStreamBranch: @unchecked Sendable {
342
381
  result.0?()
343
382
  result.1?(event)
344
383
  }
345
- private func next() async -> RuntimeEvent? {
384
+ private func next() async -> LegacyRuntimeEvent? {
346
385
  await withCheckedContinuation { continuation in
347
386
  lock.withLock {
348
387
  if let inFlightBytes { bytes -= inFlightBytes; self.inFlightBytes = nil }
@@ -354,7 +393,7 @@ private final class AppStreamBranch: @unchecked Sendable {
354
393
  }
355
394
  }
356
395
 
357
- extension RuntimeEvent {
396
+ extension LegacyRuntimeEvent {
358
397
  // Match the flat wire shape; Swift's synthesized enum encoding adds wrappers.
359
398
  func serializedBytes() throws -> Int {
360
399
  let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
@@ -382,71 +421,75 @@ extension RuntimeEvent {
382
421
  case .page(let v):
383
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))])
384
423
  case .replaced: json = .object(["type": .string("replaced")])
385
- case .unknown(let type): json = .object(["type": .string(type)])
424
+ case .unknown(let type, let fields):
425
+ var object = fields.object ?? [:]; object["type"] = .string(type); json = .object(object)
386
426
  }
387
427
  return json
388
428
  }
389
429
  }
390
430
 
391
431
 
392
- /// One serialized application callback branch; requests have an independent observation.
393
- public final class AgentSubscription: @unchecked Sendable {
394
- private let lock = NSLock()
395
- private let branch: AppStreamBranch
396
- private let handler: @Sendable (RuntimeEvent) async -> Void
397
- private var outcome: AppStreamEnd?
398
- private var waits: [CheckedContinuation<AppStreamEnd, Never>] = []
399
- private var silenced = false
400
- private var consumer: Task<Void, Never>?
401
- fileprivate init(branch: AppStreamBranch, handler: @escaping @Sendable (RuntimeEvent) async -> Void) {
402
- self.branch = branch; self.handler = handler
403
- branch.observeImmediateEnd { [weak self] event in self?.finish(event, notify: true) }
404
- consumer = Task { [weak self] in
405
- for await event in branch.stream {
406
- guard let self else { return }
407
- if self.lock.withLock({ self.outcome != nil }) { return }
408
- if Self.reason(event) != nil { self.finish(event, notify: false) }
409
- await handler(event)
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)
410
454
  }
411
- self?.finish(nil, notify: false)
412
455
  }
413
- }
414
- public var ended: AppStreamEnd {
415
- get async {
416
- await withCheckedContinuation { continuation in
417
- lock.withLock {
418
- if let outcome { continuation.resume(returning: outcome) }
419
- else { waits.append(continuation) }
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
+ }
420
463
  }
421
464
  }
422
465
  }
423
- }
424
- public func close() {
425
- lock.withLock { silenced = true }
426
- finish(nil, notify: false)
427
- branch.finish(nil)
428
- consumer?.cancel()
429
- }
430
- public func history(_ options: HistoryOptions) async throws { try await branch.history(options) }
431
- private static func reason(_ event: RuntimeEvent?) -> String? {
432
- switch event {
433
- case .streamError(let error): return error.code
434
- case .replaced: return "replaced"
435
- default: return nil
466
+ public func close() {
467
+ lock.withLock { silenced = true }
468
+ finish(nil, notify: false)
469
+ branch.finish(nil)
470
+ consumer?.cancel()
436
471
  }
437
- }
438
- private func finish(_ event: RuntimeEvent?, notify: Bool) {
439
- let accepted = lock.withLock {
440
- guard outcome == nil else { return false }
441
- let result = AppStreamEnd(code: Self.reason(event) ?? "closed")
442
- outcome = result
443
- for continuation in waits { continuation.resume(returning: result) }
444
- waits.removeAll(); return true
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
+ }
445
479
  }
446
- if accepted && notify, let event {
447
- Task { [weak self] in
448
- guard let self, !self.lock.withLock({ self.silenced }) else { return }
449
- await self.handler(event)
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
+ }
450
493
  }
451
494
  }
452
495
  }
@@ -1,9 +1,11 @@
1
1
  import Foundation
2
2
 
3
3
  #if CROCHE_SUBSCRIPTION_HOST
4
+ /// Host-only stand-in for the agent class: the namespace `Subscription` nests in.
5
+ enum LegacyCrocheAgent {}
4
6
  // Test-only façade, same public type and forwarding methods as the FFI build.
5
7
  // Fake Core is supplied by tests, never a production create implementation.
6
- public actor CrocheRuntime {
8
+ actor AgentEngine {
7
9
  let subscriptionHub: StreamHub?
8
10
  public nonisolated let logId: String
9
11
  init(port: any CoreStreamPort) throws { subscriptionHub = try StreamHub(port: port); logId = port.logId }
@@ -12,27 +14,31 @@ public actor CrocheRuntime {
12
14
  }
13
15
  #endif
14
16
 
15
- extension CrocheRuntime {
16
- public func events(initialMessages: Int = 50) -> AsyncStream<RuntimeEvent> {
17
+ extension AgentEngine {
18
+ public func events(initialMessages: Int = 50) -> AsyncStream<LegacyRuntimeEvent> {
17
19
  subscriptionHub?.events(initialMessages: initialMessages) ?? StreamHub.errorStream("invalid_configuration", "Subscription Core port is not bound")
18
20
  }
19
- public func events(after: Cursor) -> AsyncStream<RuntimeEvent> {
21
+ public func events(after: Cursor) -> AsyncStream<LegacyRuntimeEvent> {
20
22
  subscriptionHub?.events(after: after) ?? StreamHub.errorStream("invalid_configuration", "Subscription Core port is not bound")
21
23
  }
22
- public func send(_ input: SendInput, options: SendOptions = SendOptions()) async throws -> Receipt {
23
- guard let hub = subscriptionHub else { throw CrocheError("invalid_configuration", "Subscription Core port is not bound") }
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") }
24
30
  return try await hub.send(input, options: options)
25
31
  }
26
- public func request(_ input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = nil) async throws -> RequestResult {
27
- guard let hub = subscriptionHub else { throw CrocheError("invalid_configuration", "Subscription Core port is not bound") }
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") }
28
34
  return try await hub.request(input, options: options, wait: wait)
29
35
  }
30
36
  public func cancel(_ id: String) async throws {
31
- guard let hub = subscriptionHub else { throw CrocheError("invalid_configuration", "Subscription Core port is not bound") }
37
+ guard let hub = subscriptionHub else { throw LegacyCrocheError("invalid_configuration", "Subscription Core port is not bound") }
32
38
  try await hub.cancel(id)
33
39
  }
34
40
  public func history(before: Int? = nil, limit: Int) async throws {
35
- guard let hub = subscriptionHub else { throw CrocheError("invalid_configuration", "Subscription Core port is not bound") }
41
+ guard let hub = subscriptionHub else { throw LegacyCrocheError("invalid_configuration", "Subscription Core port is not bound") }
36
42
  try await hub.history(before: before, limit: limit)
37
43
  }
38
44
  }