@h1r-ai/croche-react-native 0.0.0-stage → 0.5.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.
- package/LICENSE +32 -0
- package/README.md +475 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/android/build.gradle +47 -0
- package/android/src/main/AndroidManifest.xml +8 -0
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +836 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +28 -0
- package/ios/CrocheRuntimeBridge.swift +986 -0
- package/ios/RNCrocheRuntime.mm +221 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
- package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +40 -4
- package/scripts/vendor-native.sh +56 -0
- package/src/NativeCrocheRuntime.ts +162 -0
- package/src/index.ts +660 -0
- package/src/project-types.ts +35 -0
- package/src/project.ts +426 -0
- package/src/protocol.ts +28 -0
- package/src/types.ts +9 -0
|
@@ -0,0 +1,359 @@
|
|
|
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? }
|
|
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 { 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) }
|
|
17
|
+
struct CapturedRequestState: Sendable {
|
|
18
|
+
let head: Int; let floor: Int; let status: InputStatus; let idle: Bool
|
|
19
|
+
let carried: Bool; let unitEnd: UnitEnd?
|
|
20
|
+
}
|
|
21
|
+
struct RetainedRequestEnds: Sendable { let messages: [MessageEnd]; let gap: Bool }
|
|
22
|
+
protocol CoreStreamPort: Sendable {
|
|
23
|
+
var logId: String { get }
|
|
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
|
|
28
|
+
func readOutcome(id: String, fromSeq: Int, captured: @escaping @Sendable (CapturedRequestState) -> Void) async throws -> RetainedRequestEnds
|
|
29
|
+
func cancel(_ id: String) async throws
|
|
30
|
+
func clearHistory() async throws
|
|
31
|
+
}
|
|
32
|
+
enum RequestCompletion: Sendable { case consumingUnit, idle }
|
|
33
|
+
|
|
34
|
+
// One predicate for both modes, ready for S1's reviewed unit.end evidence.
|
|
35
|
+
// 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 {
|
|
38
|
+
switch wait {
|
|
39
|
+
case .idle: return status?.terminal == true && idle
|
|
40
|
+
case .consumingUnit: return unit?.inputs.contains(id) == true || (status?.terminal == true && !carried)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
private final class WaitCancellation: @unchecked Sendable {
|
|
44
|
+
private let lock = NSLock()
|
|
45
|
+
private var cancelled = false
|
|
46
|
+
func cancel() { lock.withLock { cancelled = true } }
|
|
47
|
+
var value: Bool { lock.withLock { cancelled } }
|
|
48
|
+
}
|
|
49
|
+
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] = [:]
|
|
54
|
+
var captured = false
|
|
55
|
+
var reading = true; var complete = false; var cutoff: Int?; var gap = false
|
|
56
|
+
var lost = false
|
|
57
|
+
init(id: String, wait: RequestCompletion, cancellation: WaitCancellation, continuation: CheckedContinuation<RequestResult, Error>) {
|
|
58
|
+
self.id = id; self.wait = wait; self.cancellation = cancellation; self.continuation = continuation
|
|
59
|
+
}
|
|
60
|
+
func add(_ message: MessageEnd) {
|
|
61
|
+
guard message.causedBy.contains(id), cutoff.map({ message.seq <= $0 }) ?? true else { return }
|
|
62
|
+
messages["\(message.id):\(message.seq)"] = message
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Every mutable member is under lock. Core callbacks update waiters synchronously;
|
|
67
|
+
// the app only receives owned values through its independent queue.
|
|
68
|
+
final class StreamHub: @unchecked Sendable {
|
|
69
|
+
private let lock = NSLock()
|
|
70
|
+
private let port: any CoreStreamPort
|
|
71
|
+
private var observation: (@Sendable () -> Void)?
|
|
72
|
+
private var projection: CoreProjection?
|
|
73
|
+
private var branch: AppStreamBranch?
|
|
74
|
+
private var waiters: [UUID: RequestWaiter] = [:]
|
|
75
|
+
private var ended = false
|
|
76
|
+
private var observedHead = 0
|
|
77
|
+
private var currentState = StateEvent(status: .idle, queued: 0, typing: false)
|
|
78
|
+
var state: StateEvent { lock.withLock { currentState } }
|
|
79
|
+
var logId: String { port.logId }
|
|
80
|
+
init(port: any CoreStreamPort) throws {
|
|
81
|
+
self.port = port
|
|
82
|
+
observation = try port.observe({ [weak self] in self?.receive($0) }, end: { [weak self] in self?.end($0) })
|
|
83
|
+
}
|
|
84
|
+
func events(initialMessages: Int = 50) -> AsyncStream<RuntimeEvent> {
|
|
85
|
+
return events(StreamSelection(initialMessages: initialMessages, after: nil))
|
|
86
|
+
}
|
|
87
|
+
func events(after: Cursor) -> AsyncStream<RuntimeEvent> { events(StreamSelection(initialMessages: nil, after: after)) }
|
|
88
|
+
private func events(_ selection: StreamSelection) -> AsyncStream<RuntimeEvent> {
|
|
89
|
+
// Subscription calls are serialized by the owning CrocheRuntime actor.
|
|
90
|
+
let app = AppStreamBranch()
|
|
91
|
+
let old: (AppStreamBranch?, CoreProjection?, Bool) = lock.withLock {
|
|
92
|
+
let old = (branch, projection, ended)
|
|
93
|
+
branch = app; projection = nil
|
|
94
|
+
return old
|
|
95
|
+
}
|
|
96
|
+
old.1?.close(); old.0?.finish(.replaced)
|
|
97
|
+
if let count = selection.initialMessages, !(0...256).contains(count) {
|
|
98
|
+
app.finish(.streamError(StreamError(code: "invalid_configuration", message: "initialMessages must be in 0...256", poisoned: false)))
|
|
99
|
+
return app.stream
|
|
100
|
+
}
|
|
101
|
+
if old.2 { app.finish(.streamError(StreamError(code: "closed", message: "Runtime is closed", poisoned: false))); return app.stream }
|
|
102
|
+
let closeProjection = port.select(selection) { [weak app] in app?.push($0) }
|
|
103
|
+
app.onEnd(closeProjection.close)
|
|
104
|
+
lock.withLock { projection = closeProjection }
|
|
105
|
+
return app.stream
|
|
106
|
+
}
|
|
107
|
+
static func errorStream(_ code: String, _ message: String) -> AsyncStream<RuntimeEvent> {
|
|
108
|
+
AsyncStream { continuation in
|
|
109
|
+
continuation.yield(.streamError(StreamError(code: code, message: message, poisoned: false)))
|
|
110
|
+
continuation.finish()
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
func send(_ input: SendInput, options: SendOptions) async throws -> Receipt {
|
|
114
|
+
guard !lock.withLock({ ended }) else { throw CrocheError("closed", "Runtime is closed") }
|
|
115
|
+
return try await port.send(try input.coreJSON(options: options), options: options)
|
|
116
|
+
}
|
|
117
|
+
func history(before: Int?, limit: Int) async throws {
|
|
118
|
+
guard (1...256).contains(limit) else { throw CrocheError("invalid_configuration", "history limit must be in 1...256") }
|
|
119
|
+
let selected = lock.withLock { branch?.isActive == true && !ended ? projection : nil }
|
|
120
|
+
guard let selected else { throw CrocheError("invalid_configuration", "No stream is attached") }
|
|
121
|
+
try await selected.history(before, limit)
|
|
122
|
+
}
|
|
123
|
+
func cancel(_ id: String) async throws { try await port.cancel(id) }
|
|
124
|
+
func clearHistory() async throws { try await port.clearHistory() }
|
|
125
|
+
func request(_ input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = nil) async throws -> RequestResult {
|
|
126
|
+
if Task.isCancelled { throw CrocheError("aborted", "Request cancelled before sending") }
|
|
127
|
+
// Keel/rook: keep terminal + idle until the coordinated TS/Swift/Kotlin consuming-unit change.
|
|
128
|
+
// Both nil and the approved public .idle use S2's terminal-plus-idle default.
|
|
129
|
+
let completion: RequestCompletion = .idle
|
|
130
|
+
let key = UUID(), cancellation = WaitCancellation()
|
|
131
|
+
return try await withTaskCancellationHandler {
|
|
132
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
133
|
+
let admitted = lock.withLock {
|
|
134
|
+
if ended { continuation.resume(throwing: CrocheError("closed", "Runtime is closed")); return false }
|
|
135
|
+
if cancellation.value { continuation.resume(throwing: CrocheError("aborted", "Request cancelled before sending")); return false }
|
|
136
|
+
waiters[key] = RequestWaiter(id: input.id, wait: completion, cancellation: cancellation, continuation: continuation)
|
|
137
|
+
return true
|
|
138
|
+
}
|
|
139
|
+
guard admitted else { return }
|
|
140
|
+
// Do not cancel the acceptance task when the caller stops waiting.
|
|
141
|
+
Task { await self.accept(input, options: options, key: key) }
|
|
142
|
+
}
|
|
143
|
+
} onCancel: {
|
|
144
|
+
cancellation.cancel()
|
|
145
|
+
self.abort(key)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
private func accept(_ input: SendInput, options: SendOptions, key: UUID) async {
|
|
149
|
+
var receipt: Receipt?
|
|
150
|
+
do {
|
|
151
|
+
let accepted = try await port.send(try input.coreJSON(options: options), options: options)
|
|
152
|
+
receipt = accepted
|
|
153
|
+
let read = lock.withLock {
|
|
154
|
+
guard let waiter = waiters[key] else { return false }
|
|
155
|
+
waiter.receipt = accepted
|
|
156
|
+
// A same-id terminal retry emits no new input event. Seed its disposition
|
|
157
|
+
// before idle can overtake capture; never regress a status already observed.
|
|
158
|
+
if waiter.status == nil || (waiter.status?.terminal != true && accepted.status.terminal) {
|
|
159
|
+
waiter.status = accepted.status
|
|
160
|
+
}
|
|
161
|
+
if waiter.lost { fail(key, code: "observation_lost"); return false }
|
|
162
|
+
if waiter.cancellation.value { fail(key, code: "aborted"); return false }
|
|
163
|
+
if accepted.seq == nil {
|
|
164
|
+
waiters.removeValue(forKey: key)
|
|
165
|
+
waiter.continuation.resume(returning: RequestResult(id: accepted.id, status: accepted.status, messages: [], gap: false, legacy: true))
|
|
166
|
+
return false
|
|
167
|
+
}
|
|
168
|
+
return true
|
|
169
|
+
}
|
|
170
|
+
guard read, let seq = accepted.seq else { return }
|
|
171
|
+
let retained = try await port.readOutcome(id: accepted.id, fromSeq: seq) { [weak self] captured in
|
|
172
|
+
self?.capture(captured, key: key, receipt: accepted)
|
|
173
|
+
}
|
|
174
|
+
lock.withLock {
|
|
175
|
+
guard let waiter = waiters[key] else { return }
|
|
176
|
+
guard waiter.captured else { fail(key, code: "observation_lost"); return }
|
|
177
|
+
for message in retained.messages { waiter.add(message) }
|
|
178
|
+
waiter.gap = waiter.gap || retained.gap
|
|
179
|
+
waiter.reading = false
|
|
180
|
+
finish(key)
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
lock.withLock {
|
|
184
|
+
guard let waiter = waiters.removeValue(forKey: key) else { return }
|
|
185
|
+
waiter.continuation.resume(throwing: receipt.map { CrocheError("observation_lost", "Outcome observation failed", receipt: $0) } ?? error)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
private func capture(_ captured: CapturedRequestState, key: UUID, receipt: Receipt) {
|
|
190
|
+
lock.withLock {
|
|
191
|
+
guard let waiter = waiters[key] else { return }
|
|
192
|
+
waiter.captured = true
|
|
193
|
+
if waiter.status?.terminal != true { waiter.status = captured.status }
|
|
194
|
+
waiter.carried = waiter.carried || captured.carried
|
|
195
|
+
waiter.gap = waiter.gap || receipt.seq! < captured.floor
|
|
196
|
+
// A newly attached hub can finish a terminal retry at idle before it has seen
|
|
197
|
+
// any sequence for that receipt. Its zero/older live cutoff must not discard
|
|
198
|
+
// the scoped retained reply. An actual live completion cut stays unchanged.
|
|
199
|
+
if waiter.complete, let cutoff = waiter.cutoff, cutoff < receipt.seq! {
|
|
200
|
+
waiter.cutoff = captured.head
|
|
201
|
+
}
|
|
202
|
+
if !waiter.complete && requestComplete(waiter.wait, status: waiter.status, idle: captured.idle, carried: waiter.carried, unit: captured.unitEnd, id: waiter.id) {
|
|
203
|
+
waiter.complete = true; waiter.cutoff = captured.head
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
private func receive(_ observation: RequestObservation) {
|
|
208
|
+
lock.withLock {
|
|
209
|
+
switch observation {
|
|
210
|
+
case .input(let input): observedHead = max(observedHead, input.seq)
|
|
211
|
+
case .messageEnd(let message): observedHead = max(observedHead, message.seq)
|
|
212
|
+
case .state(let state): currentState = state
|
|
213
|
+
case .unitEnd(let unit): observedHead = max(observedHead, unit.seq)
|
|
214
|
+
}
|
|
215
|
+
for key in Array(waiters.keys) {
|
|
216
|
+
guard let waiter = waiters[key], !waiter.complete else { continue }
|
|
217
|
+
var idle = false, unit: UnitEnd?
|
|
218
|
+
switch observation {
|
|
219
|
+
case .input(let input) where input.id == waiter.id:
|
|
220
|
+
if waiter.status?.terminal != true { waiter.status = input.status }
|
|
221
|
+
waiter.carried = waiter.carried || input.carried
|
|
222
|
+
case .messageEnd(let message): waiter.add(message)
|
|
223
|
+
case .state(let state): idle = state.status == .idle
|
|
224
|
+
case .unitEnd(let value): unit = value
|
|
225
|
+
default: break
|
|
226
|
+
}
|
|
227
|
+
if requestComplete(waiter.wait, status: waiter.status, idle: idle, carried: waiter.carried, unit: unit, id: waiter.id) {
|
|
228
|
+
waiter.complete = true; waiter.cutoff = unit?.seq ?? observedHead
|
|
229
|
+
}
|
|
230
|
+
finish(key)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
private func finish(_ key: UUID) {
|
|
235
|
+
guard let waiter = waiters[key], !waiter.reading, waiter.complete, let receipt = waiter.receipt, let status = waiter.status else { return }
|
|
236
|
+
waiters.removeValue(forKey: key)
|
|
237
|
+
waiter.continuation.resume(returning: RequestResult(id: receipt.id, status: status, messages: waiter.messages.values.sorted { $0.seq < $1.seq }, gap: waiter.gap, legacy: false))
|
|
238
|
+
}
|
|
239
|
+
// Caller must hold lock.
|
|
240
|
+
private func fail(_ key: UUID, code: String) {
|
|
241
|
+
guard let waiter = waiters.removeValue(forKey: key) else { return }
|
|
242
|
+
waiter.continuation.resume(throwing: CrocheError(code, "The wait ended; accepted input continues", receipt: waiter.receipt))
|
|
243
|
+
}
|
|
244
|
+
private func abort(_ key: UUID) { lock.withLock { if waiters[key]?.receipt != nil { fail(key, code: "aborted") } } }
|
|
245
|
+
func close() {
|
|
246
|
+
end(StreamError(code: "closed", message: "Runtime is closed", poisoned: false), drain: false)
|
|
247
|
+
let detach = lock.withLock { let old = observation; observation = nil; return old }
|
|
248
|
+
detach?()
|
|
249
|
+
}
|
|
250
|
+
deinit { observation?(); projection?.close() }
|
|
251
|
+
private func end(_ error: StreamError?, drain: Bool = true) {
|
|
252
|
+
let old: (AppStreamBranch?, CoreProjection?) = lock.withLock {
|
|
253
|
+
guard !ended else { return (nil, nil) }
|
|
254
|
+
ended = true
|
|
255
|
+
for key in Array(waiters.keys) {
|
|
256
|
+
waiters[key]?.lost = true
|
|
257
|
+
if waiters[key]?.receipt != nil { fail(key, code: "observation_lost") }
|
|
258
|
+
}
|
|
259
|
+
return (branch, projection)
|
|
260
|
+
}
|
|
261
|
+
old.1?.close()
|
|
262
|
+
old.0?.finish(error.map(RuntimeEvent.streamError), drain: drain && error != nil)
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// AsyncStream's unfolding form lets this SDK count queued UTF-8 bytes and events.
|
|
267
|
+
// Retain the delivered event's budget until next() is called again: the for-await
|
|
268
|
+
// body has then finished (Keel ruling 6071234795).
|
|
269
|
+
private final class AppStreamBranch: @unchecked Sendable {
|
|
270
|
+
private let lock = NSLock()
|
|
271
|
+
private var queue: [(RuntimeEvent, Int)] = []
|
|
272
|
+
private var bytes = 0
|
|
273
|
+
private var inFlightBytes: Int?
|
|
274
|
+
private var active = true
|
|
275
|
+
private var terminal: RuntimeEvent?
|
|
276
|
+
private var consumer: CheckedContinuation<RuntimeEvent?, Never>?
|
|
277
|
+
private var closeProjection: (@Sendable () -> Void)?
|
|
278
|
+
var isActive: Bool { lock.withLock { active } }
|
|
279
|
+
var stream: AsyncStream<RuntimeEvent> {
|
|
280
|
+
AsyncStream(unfolding: { await self.next() }, onCancel: { self.finish(nil) })
|
|
281
|
+
}
|
|
282
|
+
func onEnd(_ close: @escaping @Sendable () -> Void) {
|
|
283
|
+
let alreadyEnded = lock.withLock { closeProjection = close; return !active }
|
|
284
|
+
if alreadyEnded { close() }
|
|
285
|
+
}
|
|
286
|
+
func push(_ event: RuntimeEvent) {
|
|
287
|
+
if case .replaced = event { finish(event); return }
|
|
288
|
+
if case .streamError = event {
|
|
289
|
+
finish(event, drain: true); return
|
|
290
|
+
}
|
|
291
|
+
let count: Int
|
|
292
|
+
do { count = try event.serializedBytes() }
|
|
293
|
+
catch { finish(.streamError(StreamError(code: "handler_failed", message: "Event cannot be encoded", poisoned: false))); return }
|
|
294
|
+
let overflow = lock.withLock {
|
|
295
|
+
guard active else { return false }
|
|
296
|
+
if queue.count + (inFlightBytes == nil ? 0 : 1) + 1 > 256 || bytes + count > 1_048_576 { return true }
|
|
297
|
+
if let consumer { self.consumer = nil; inFlightBytes = count; bytes += count; consumer.resume(returning: event); return false }
|
|
298
|
+
queue.append((event, count)); bytes += count
|
|
299
|
+
return false
|
|
300
|
+
}
|
|
301
|
+
if overflow { finish(.streamError(StreamError(code: "subscriber_overflow", message: "App event buffer exceeded", poisoned: false))) }
|
|
302
|
+
}
|
|
303
|
+
func finish(_ event: RuntimeEvent?, drain: Bool = false) {
|
|
304
|
+
let close = lock.withLock {
|
|
305
|
+
guard active else { return nil as (@Sendable () -> Void)? }
|
|
306
|
+
active = false
|
|
307
|
+
// Keel ruling 6071234795: Core errors drain; SDK-side ends drop queued values.
|
|
308
|
+
if drain {} else { queue.removeAll(); bytes = 0; inFlightBytes = nil }
|
|
309
|
+
terminal = event
|
|
310
|
+
if let consumer { self.consumer = nil; terminal = nil; consumer.resume(returning: event) }
|
|
311
|
+
return closeProjection
|
|
312
|
+
}
|
|
313
|
+
close?()
|
|
314
|
+
}
|
|
315
|
+
private func next() async -> RuntimeEvent? {
|
|
316
|
+
await withCheckedContinuation { continuation in
|
|
317
|
+
lock.withLock {
|
|
318
|
+
if let inFlightBytes { bytes -= inFlightBytes; self.inFlightBytes = nil }
|
|
319
|
+
if !queue.isEmpty { let item = queue.removeFirst(); inFlightBytes = item.1; continuation.resume(returning: item.0) }
|
|
320
|
+
else if !active { let last = terminal; terminal = nil; continuation.resume(returning: last) }
|
|
321
|
+
else { consumer = continuation }
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
extension RuntimeEvent {
|
|
328
|
+
// Match the flat wire shape; Swift's synthesized enum encoding adds wrappers.
|
|
329
|
+
func serializedBytes() throws -> Int {
|
|
330
|
+
let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
|
|
331
|
+
return try encoder.encode(wireJSON()).count
|
|
332
|
+
}
|
|
333
|
+
func wireJSON() throws -> JSON {
|
|
334
|
+
let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.withoutEscapingSlashes]
|
|
335
|
+
func fields<T: Encodable>(_ value: T, _ type: String) throws -> JSON {
|
|
336
|
+
var json = try JSON(data: encoder.encode(value)); json["type"] = .string(type); return json
|
|
337
|
+
}
|
|
338
|
+
let json: JSON
|
|
339
|
+
switch self {
|
|
340
|
+
case .input(let v): json = try fields(v, "input")
|
|
341
|
+
case .messageStart(let v): json = try fields(v, "message.start")
|
|
342
|
+
case .messageDelta(let v): json = try fields(v, "message.delta")
|
|
343
|
+
case .messageEnd(let v): json = try fields(v, "message.end")
|
|
344
|
+
case .cleared(let v): json = try fields(v, "cleared")
|
|
345
|
+
case .app(let v): json = try fields(v, "app")
|
|
346
|
+
case .turn(let v): json = try fields(v, "turn")
|
|
347
|
+
case .state(let v): json = try fields(v, "state")
|
|
348
|
+
case .error(let v): json = try fields(v, "error")
|
|
349
|
+
case .gap(let v): json = try fields(v, "gap")
|
|
350
|
+
case .snapshot(let v): json = try fields(v, "snapshot")
|
|
351
|
+
case .streamError(let v): json = try fields(v, "error")
|
|
352
|
+
case .page(let v):
|
|
353
|
+
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))])
|
|
354
|
+
case .replaced: json = .object(["type": .string("replaced")])
|
|
355
|
+
case .unknown(let type): json = .object(["type": .string(type)])
|
|
356
|
+
}
|
|
357
|
+
return json
|
|
358
|
+
}
|
|
359
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
#if CROCHE_SUBSCRIPTION_HOST
|
|
4
|
+
// Test-only façade, same public type and forwarding methods as the FFI build.
|
|
5
|
+
// Fake Core is supplied by tests, never a production create implementation.
|
|
6
|
+
public actor CrocheRuntime {
|
|
7
|
+
let subscriptionHub: StreamHub?
|
|
8
|
+
public nonisolated let logId: String
|
|
9
|
+
init(port: any CoreStreamPort) throws { subscriptionHub = try StreamHub(port: port); logId = port.logId }
|
|
10
|
+
public func clearHistory() async throws { try await subscriptionHub?.clearHistory() }
|
|
11
|
+
public func close() async throws { subscriptionHub?.close() }
|
|
12
|
+
}
|
|
13
|
+
#endif
|
|
14
|
+
|
|
15
|
+
extension CrocheRuntime {
|
|
16
|
+
public func events(initialMessages: Int = 50) -> AsyncStream<RuntimeEvent> {
|
|
17
|
+
subscriptionHub?.events(initialMessages: initialMessages) ?? StreamHub.errorStream("invalid_configuration", "Subscription Core port is not bound")
|
|
18
|
+
}
|
|
19
|
+
public func events(after: Cursor) -> AsyncStream<RuntimeEvent> {
|
|
20
|
+
subscriptionHub?.events(after: after) ?? StreamHub.errorStream("invalid_configuration", "Subscription Core port is not bound")
|
|
21
|
+
}
|
|
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
|
+
return try await hub.send(input, options: options)
|
|
25
|
+
}
|
|
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") }
|
|
28
|
+
return try await hub.request(input, options: options, wait: wait)
|
|
29
|
+
}
|
|
30
|
+
public func cancel(_ id: String) async throws {
|
|
31
|
+
guard let hub = subscriptionHub else { throw CrocheError("invalid_configuration", "Subscription Core port is not bound") }
|
|
32
|
+
try await hub.cancel(id)
|
|
33
|
+
}
|
|
34
|
+
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") }
|
|
36
|
+
try await hub.history(before: before, limit: limit)
|
|
37
|
+
}
|
|
38
|
+
}
|