@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,194 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(FoundationNetworking)
|
|
3
|
+
import FoundationNetworking
|
|
4
|
+
#endif
|
|
5
|
+
|
|
6
|
+
/// Cooperative tool cancellation. A cancelled invocation is never automatically replayed.
|
|
7
|
+
public final class RuntimeCancellation: @unchecked Sendable {
|
|
8
|
+
private let lock = NSLock()
|
|
9
|
+
private var stopped = false
|
|
10
|
+
private var listeners: [UUID: @Sendable () -> Void] = [:]
|
|
11
|
+
public init() {}
|
|
12
|
+
public var isCancelled: Bool { lock.withLock { stopped } }
|
|
13
|
+
public func check() throws {
|
|
14
|
+
if isCancelled { throw CrocheError("cancelled", "The operation was cancelled") }
|
|
15
|
+
}
|
|
16
|
+
public func cancel() {
|
|
17
|
+
let callbacks = lock.withLock { () -> [@Sendable () -> Void] in
|
|
18
|
+
guard !stopped else { return [] }; stopped = true
|
|
19
|
+
let values = Array(listeners.values); listeners.removeAll(); return values
|
|
20
|
+
}
|
|
21
|
+
for callback in callbacks { callback() }
|
|
22
|
+
}
|
|
23
|
+
@discardableResult func observe(_ callback: @escaping @Sendable () -> Void) -> UUID {
|
|
24
|
+
let id = UUID()
|
|
25
|
+
let already = lock.withLock { if stopped { return true }; listeners[id] = callback; return false }
|
|
26
|
+
if already { callback() }; return id
|
|
27
|
+
}
|
|
28
|
+
func remove(_ id: UUID) { _ = lock.withLock { listeners.removeValue(forKey: id) } }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
private final class EffectRace<T: Sendable>: @unchecked Sendable {
|
|
32
|
+
private let lock = NSLock()
|
|
33
|
+
private var continuation: CheckedContinuation<T, Error>?
|
|
34
|
+
private var done = false
|
|
35
|
+
private var tasks: [Task<Void, Never>] = []
|
|
36
|
+
init(_ continuation: CheckedContinuation<T, Error>) { self.continuation = continuation }
|
|
37
|
+
func add(_ task: Task<Void, Never>) {
|
|
38
|
+
if lock.withLock({ if done { return true }; tasks.append(task); return false }) { task.cancel() }
|
|
39
|
+
}
|
|
40
|
+
func finish(_ result: Result<T, Error>) {
|
|
41
|
+
let pending = lock.withLock { () -> (CheckedContinuation<T, Error>?, [Task<Void, Never>]) in
|
|
42
|
+
guard !done else { return (nil, []) }; done = true
|
|
43
|
+
let c = continuation; continuation = nil; let t = tasks; tasks = []; return (c, t)
|
|
44
|
+
}
|
|
45
|
+
pending.0?.resume(with: result)
|
|
46
|
+
for task in pending.1 { task.cancel() }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
func boundedEffect(milliseconds: Double, cancellation: RuntimeCancellation,
|
|
51
|
+
body: @escaping @Sendable (RuntimeCancellation) async throws -> JSON) async throws -> JSON {
|
|
52
|
+
try await bounded(milliseconds: milliseconds, cancellation: cancellation, body: body)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// A deadline returns even when an application handler ignores cancellation. Its context
|
|
56
|
+
/// is revoked and any late result is discarded; the host cannot promise effect rollback.
|
|
57
|
+
/// `milliseconds` nil: no deadline here, only `cancellation` (a tool: the Runtime is its only
|
|
58
|
+
/// clock and cancels it at the command's deadline).
|
|
59
|
+
func bounded<T: Sendable>(milliseconds: Double?, cancellation: RuntimeCancellation,
|
|
60
|
+
body: @escaping @Sendable (RuntimeCancellation) async throws -> T) async throws -> T {
|
|
61
|
+
let local = RuntimeCancellation()
|
|
62
|
+
return try await withCheckedThrowingContinuation { continuation in
|
|
63
|
+
let race = EffectRace<T>(continuation)
|
|
64
|
+
let listener = cancellation.observe {
|
|
65
|
+
local.cancel(); race.finish(.failure(CrocheError("cancelled", "The operation was cancelled")))
|
|
66
|
+
}
|
|
67
|
+
race.add(Task {
|
|
68
|
+
do { try local.check(); let value = try await body(local); try local.check(); race.finish(.success(value)) }
|
|
69
|
+
catch { race.finish(.failure(error)) }
|
|
70
|
+
cancellation.remove(listener)
|
|
71
|
+
})
|
|
72
|
+
guard let milliseconds else { return }
|
|
73
|
+
race.add(Task {
|
|
74
|
+
do {
|
|
75
|
+
try await Task.sleep(nanoseconds: UInt64(max(1, milliseconds) * 1_000_000))
|
|
76
|
+
race.finish(.failure(CrocheError("timeout", "The effect deadline expired"))); local.cancel()
|
|
77
|
+
cancellation.remove(listener)
|
|
78
|
+
} catch {}
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// `onDelta` receives each server-sent event's data while a streamed response arrives, in
|
|
84
|
+
/// order; the Rust Core assembles them. A transport that cannot stream never calls it.
|
|
85
|
+
public typealias RuntimeHTTP = @Sendable (_ effect: JSON, _ cancellation: RuntimeCancellation,
|
|
86
|
+
_ onDelta: @escaping @Sendable (String) async -> Void) async throws -> JSON
|
|
87
|
+
|
|
88
|
+
private let maxResponseBytes = 2 * 1024 * 1024
|
|
89
|
+
/// A gateway stream wraps each piece of content in its own JSON event.
|
|
90
|
+
private let maxStreamBytes = 3 * maxResponseBytes
|
|
91
|
+
|
|
92
|
+
/// Ephemeral URLSession transport: no cookies/cache, no redirects, 2MiB response bound.
|
|
93
|
+
/// A `text/event-stream` answer is read incrementally and its deltas are handed on.
|
|
94
|
+
public enum RuntimeURLSession {
|
|
95
|
+
public static func send(_ effect: JSON, cancellation: RuntimeCancellation,
|
|
96
|
+
onDelta: @escaping @Sendable (String) async -> Void = { _ in }) async throws -> JSON {
|
|
97
|
+
try cancellation.check()
|
|
98
|
+
guard let address = effect["url"].string, let url = URL(string: address) else {
|
|
99
|
+
throw CrocheError("network_error", "Invalid HTTP effect URL")
|
|
100
|
+
}
|
|
101
|
+
var request = URLRequest(url: url)
|
|
102
|
+
request.httpMethod = effect["method"].string
|
|
103
|
+
if !["GET", "HEAD"].contains(request.httpMethod ?? "") { request.httpBody = try effect["body"].encoded() }
|
|
104
|
+
request.timeoutInterval = (effect["timeoutMs"].number ?? 30_000) / 1000
|
|
105
|
+
request.httpShouldHandleCookies = false
|
|
106
|
+
for (name, value) in effect["headers"].object ?? [:] {
|
|
107
|
+
if let value = value.string { request.setValue(value, forHTTPHeaderField: name) }
|
|
108
|
+
}
|
|
109
|
+
let (chunks, sink) = AsyncThrowingStream<HTTPPart, Error>.makeStream()
|
|
110
|
+
let delegate = HTTPDelegate(sink)
|
|
111
|
+
let config = URLSessionConfiguration.ephemeral
|
|
112
|
+
config.httpCookieStorage = nil; config.httpShouldSetCookies = false; config.urlCache = nil
|
|
113
|
+
let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
|
|
114
|
+
defer { session.invalidateAndCancel() }
|
|
115
|
+
let task = session.dataTask(with: request)
|
|
116
|
+
let listener = cancellation.observe { task.cancel() }
|
|
117
|
+
defer { cancellation.remove(listener) }
|
|
118
|
+
task.resume()
|
|
119
|
+
return try await read(chunks, cancellation: cancellation, onDelta: onDelta)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
static func read(_ chunks: AsyncThrowingStream<HTTPPart, Error>, cancellation: RuntimeCancellation,
|
|
123
|
+
onDelta: @Sendable (String) async -> Void) async throws -> JSON {
|
|
124
|
+
var status = 0
|
|
125
|
+
var headers: [String: JSON] = [:]
|
|
126
|
+
var streaming = false
|
|
127
|
+
var body = Data()
|
|
128
|
+
var parser = EventStreamParser()
|
|
129
|
+
var size = 0
|
|
130
|
+
for try await part in chunks {
|
|
131
|
+
switch part {
|
|
132
|
+
case .head(let code, let fields, let expected):
|
|
133
|
+
status = code; headers = fields
|
|
134
|
+
let type = fields.first { $0.key.lowercased() == "content-type" }?.value.string ?? ""
|
|
135
|
+
// A refusal arrives as ordinary JSON even when a stream was asked for; only an
|
|
136
|
+
// event stream is read incrementally.
|
|
137
|
+
streaming = (200..<300).contains(code) && type.lowercased().hasPrefix("text/event-stream")
|
|
138
|
+
if !streaming && expected > Int64(maxResponseBytes) {
|
|
139
|
+
throw CrocheError("invalid_response", "HTTP response exceeds 2MiB")
|
|
140
|
+
}
|
|
141
|
+
case .body(let data):
|
|
142
|
+
size += data.count
|
|
143
|
+
if !streaming {
|
|
144
|
+
guard size <= maxResponseBytes else { throw CrocheError("invalid_response", "HTTP response exceeds 2MiB") }
|
|
145
|
+
body.append(data); continue
|
|
146
|
+
}
|
|
147
|
+
guard size <= maxStreamBytes else { throw CrocheError("invalid_provider_response", "The gateway stream exceeds its bound") }
|
|
148
|
+
for event in parser.push([UInt8](data)) where !event.data.isEmpty { await onDelta(event.data) }
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
try cancellation.check()
|
|
152
|
+
if streaming {
|
|
153
|
+
for event in parser.end() where !event.data.isEmpty { await onDelta(event.data) }
|
|
154
|
+
// The stream's end completes the call; the Core judges what it assembled.
|
|
155
|
+
return .object(["status": .number(Double(status)), "headers": .object(headers), "streamed": .bool(true)])
|
|
156
|
+
}
|
|
157
|
+
var reply = JSON.object(["status": .number(Double(status)), "headers": .object(headers)])
|
|
158
|
+
if let parsed = try? JSON(data: body) { reply["body"] = parsed }
|
|
159
|
+
else { reply["raw"] = .string(String(decoding: body, as: UTF8.self)) }
|
|
160
|
+
return reply
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
enum HTTPPart: Sendable {
|
|
165
|
+
case head(status: Int, headers: [String: JSON], expectedLength: Int64)
|
|
166
|
+
case body(Data)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private final class HTTPDelegate: NSObject, URLSessionDataDelegate, @unchecked Sendable {
|
|
170
|
+
private let sink: AsyncThrowingStream<HTTPPart, Error>.Continuation
|
|
171
|
+
init(_ sink: AsyncThrowingStream<HTTPPart, Error>.Continuation) { self.sink = sink }
|
|
172
|
+
func urlSession(_ session: URLSession, task: URLSessionTask,
|
|
173
|
+
willPerformHTTPRedirection response: HTTPURLResponse,
|
|
174
|
+
newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
|
|
175
|
+
completionHandler(nil)
|
|
176
|
+
}
|
|
177
|
+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
|
|
178
|
+
didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
|
|
179
|
+
guard let http = response as? HTTPURLResponse else {
|
|
180
|
+
sink.finish(throwing: CrocheError("network_error", "No HTTP response")); completionHandler(.cancel); return
|
|
181
|
+
}
|
|
182
|
+
var headers: [String: JSON] = [:]
|
|
183
|
+
for (key, value) in http.allHeaderFields { headers[String(describing: key)] = .string(String(describing: value)) }
|
|
184
|
+
sink.yield(.head(status: http.statusCode, headers: headers, expectedLength: response.expectedContentLength))
|
|
185
|
+
completionHandler(.allow)
|
|
186
|
+
}
|
|
187
|
+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) {
|
|
188
|
+
sink.yield(.body(chunk))
|
|
189
|
+
}
|
|
190
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
191
|
+
if error != nil { sink.finish(throwing: CrocheError("network_error", "HTTP transport failed")) }
|
|
192
|
+
else { sink.finish() }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// The only stream adapter to UniFFI. Core owns projection, ordering and capture.
|
|
4
|
+
// Keep the receipt method spelling in this one file/call site for the reviewed rename.
|
|
5
|
+
final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
|
|
6
|
+
private let core: CoreRuntime
|
|
7
|
+
let logId: String
|
|
8
|
+
init(core: CoreRuntime) throws {
|
|
9
|
+
self.core = core
|
|
10
|
+
logId = try Self.blocking { try core.logId() }
|
|
11
|
+
}
|
|
12
|
+
private final class Box<T>: @unchecked Sendable { var result: Result<T, Error>? }
|
|
13
|
+
// select/observe are synchronous seams. Main-thread callers wait on a dedicated thread;
|
|
14
|
+
// callbacks already on a Core thread stay there, preserving FFI's reentrancy rule.
|
|
15
|
+
private static func blocking<T>(record: Bool = true, _ body: @escaping @Sendable () throws -> T) throws -> T {
|
|
16
|
+
let measured: @Sendable () throws -> T = {
|
|
17
|
+
if record { CrocheRuntime.offloadStarting?() }
|
|
18
|
+
return try body()
|
|
19
|
+
}
|
|
20
|
+
if !Thread.isMainThread { return try measured() }
|
|
21
|
+
let done = DispatchSemaphore(value: 0), box = Box<T>()
|
|
22
|
+
Thread.detachNewThread { box.result = Result { try measured() }; done.signal() }
|
|
23
|
+
done.wait()
|
|
24
|
+
return try box.result!.get()
|
|
25
|
+
}
|
|
26
|
+
private static func offload<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
|
|
27
|
+
try await CrocheRuntime.offload(body)
|
|
28
|
+
}
|
|
29
|
+
private final class Listener: EventListener, @unchecked Sendable {
|
|
30
|
+
let callback: @Sendable (String) -> Void
|
|
31
|
+
init(_ callback: @escaping @Sendable (String) -> Void) { self.callback = callback }
|
|
32
|
+
func onEvent(event: String) { callback(event) }
|
|
33
|
+
}
|
|
34
|
+
private static func failure(_ error: Error) -> StreamError {
|
|
35
|
+
let error = CrocheError(error)
|
|
36
|
+
return StreamError(code: error.code, message: error.message, poisoned: false)
|
|
37
|
+
}
|
|
38
|
+
func observe(_ event: @escaping @Sendable (RequestObservation) -> Void,
|
|
39
|
+
end: @escaping @Sendable (StreamError?) -> Void) throws -> @Sendable () -> Void {
|
|
40
|
+
do {
|
|
41
|
+
try Self.blocking { [core] in
|
|
42
|
+
try core.observe(onEvent: Listener { text in
|
|
43
|
+
do {
|
|
44
|
+
let decoded = try CoreEvent.decode(text)
|
|
45
|
+
switch decoded {
|
|
46
|
+
case .input(let v): event(.input(InputObservation(id: v.id, seq: v.seq, status: v.status, carried: v.status == .seen)))
|
|
47
|
+
case .messageEnd(let v): event(.messageEnd(v))
|
|
48
|
+
case .state(let v): event(.state(v))
|
|
49
|
+
default: break
|
|
50
|
+
}
|
|
51
|
+
} catch { end(Self.failure(error)) }
|
|
52
|
+
}, onEnd: Listener { text in
|
|
53
|
+
do { end(try CoreEvent.decodeFailure(text)) }
|
|
54
|
+
catch { end(Self.failure(error)) }
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
} catch { throw CrocheError(error) }
|
|
58
|
+
return { [core] in _ = try? Self.blocking { core.unobserve() } }
|
|
59
|
+
}
|
|
60
|
+
func select(_ selection: StreamSelection, event: @escaping @Sendable (RuntimeEvent) -> Void) -> CoreProjection {
|
|
61
|
+
struct Selection: Encodable { let initialMessages: Int?; let after: Cursor? }
|
|
62
|
+
do {
|
|
63
|
+
if let after = selection.after { _ = try Self.coreSequence(after.seq) }
|
|
64
|
+
let text = String(decoding: try JSONEncoder().encode(Selection(initialMessages: selection.initialMessages, after: selection.after)), as: UTF8.self)
|
|
65
|
+
let id = try Self.blocking { [core] in
|
|
66
|
+
try core.select(selection: text, onEvent: Listener { text in
|
|
67
|
+
do { event(try CoreEvent.decode(text)) }
|
|
68
|
+
catch { event(.streamError(Self.failure(error))) }
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
return CoreProjection(close: { [core] in _ = try? Self.blocking { core.closeProjection(id: id) } }, history: { before, limit in
|
|
72
|
+
guard let count = UInt32(exactly: limit) else { throw CrocheError("invalid_configuration", "Invalid history range") }
|
|
73
|
+
let seq = try before.map(Self.coreSequence)
|
|
74
|
+
try await Self.offload { try self.historyNow(id: id, before: seq, limit: count) }
|
|
75
|
+
})
|
|
76
|
+
} catch {
|
|
77
|
+
event(.streamError(Self.failure(error)))
|
|
78
|
+
return CoreProjection(close: {}, history: { _, _ in throw CrocheError("invalid_configuration", "No stream is attached") })
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// Also used at the synchronous callback boundary to retain FFI's reentrancy rule.
|
|
82
|
+
func historyNow(id: UInt64, before: UInt64?, limit: UInt32) throws {
|
|
83
|
+
try Self.blocking { [core] in try core.history(id: id, before: before, limit: limit) }
|
|
84
|
+
}
|
|
85
|
+
func send(_ input: JSON, options: SendOptions) async throws -> Receipt {
|
|
86
|
+
try await send(input, options: options, cancel: nil)
|
|
87
|
+
}
|
|
88
|
+
func send(_ input: JSON, options: SendOptions, cancel: CancelToken?) async throws -> Receipt {
|
|
89
|
+
let text = String(decoding: try input.encoded(), as: UTF8.self)
|
|
90
|
+
let format = try options.responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
|
|
91
|
+
let value = try await Self.offload { [core] in try core.send(input: text, cancel: cancel, responseFormat: format) }
|
|
92
|
+
struct WireReceipt: Decodable { let id: String; let status: InputStatus; let seq: Int? }
|
|
93
|
+
let receipt = try CoreEvent.decodeValue(WireReceipt.self, value)
|
|
94
|
+
return Receipt(id: receipt.id, status: receipt.status, seq: receipt.seq)
|
|
95
|
+
}
|
|
96
|
+
func readOutcome(id: String, fromSeq: Int, captured: @escaping @Sendable (CapturedRequestState) -> Void) async throws -> RetainedRequestEnds {
|
|
97
|
+
let seq = try Self.coreSequence(fromSeq)
|
|
98
|
+
// Capture parsing failures must fail the read, never silently strand a waiter.
|
|
99
|
+
let captureError = CaptureError()
|
|
100
|
+
let text = try await Self.offload { [core] in
|
|
101
|
+
try core.readOutcome(id: id, fromSeq: seq, captured: Listener { value in
|
|
102
|
+
do {
|
|
103
|
+
struct Capture: Decodable { let head: Int; let floor: Int; let status: InputStatus; let idle: Bool; let consumedBy: String? }
|
|
104
|
+
let at = try CoreEvent.decodeValue(Capture.self, value)
|
|
105
|
+
captured(CapturedRequestState(head: at.head, floor: at.floor, status: at.status, idle: at.idle, carried: at.consumedBy != nil, unitEnd: nil))
|
|
106
|
+
} catch { captureError.set(error) }
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
if let error = captureError.get() { throw error }
|
|
110
|
+
struct Outcome: Decodable { let messages: [MessageEnd]; let gap: Bool? }
|
|
111
|
+
let outcome = try CoreEvent.decodeValue(Outcome.self, text)
|
|
112
|
+
return RetainedRequestEnds(messages: outcome.messages, gap: outcome.gap ?? false)
|
|
113
|
+
}
|
|
114
|
+
private final class CaptureError: @unchecked Sendable {
|
|
115
|
+
private let lock = NSLock(); private var error: Error?
|
|
116
|
+
func set(_ value: Error) { lock.withLock { error = value } }
|
|
117
|
+
func get() -> Error? { lock.withLock { error } }
|
|
118
|
+
}
|
|
119
|
+
static func coreSequence(_ value: Int) throws -> UInt64 {
|
|
120
|
+
guard let result = UInt64(exactly: value) else { throw CrocheError("invalid_input", "Sequence is outside the Core range") }
|
|
121
|
+
return result
|
|
122
|
+
}
|
|
123
|
+
func cancel(_ id: String) async throws {
|
|
124
|
+
try await Self.offload { [core] in try core.cancel(id: id) }
|
|
125
|
+
}
|
|
126
|
+
func clearHistory() async throws {
|
|
127
|
+
// Preserve the existing admission fence: only waiting crosses the offload hop.
|
|
128
|
+
let pending = try Self.blocking(record: false) { [core] in core.beginClearHistory() }
|
|
129
|
+
try await Self.offload { try pending.finish() }
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Decode numbers from the original JSON bytes, never through the legacy Double JSON tree.
|
|
134
|
+
// Extra Core keys stay internal; unknown event types remain forward-compatible.
|
|
135
|
+
enum CoreEvent {
|
|
136
|
+
static func publicSequence(_ value: UInt64) throws -> Int {
|
|
137
|
+
guard let result = Int(exactly: value) else { throw CrocheError("invalid_input", "Core sequence is outside the public range") }
|
|
138
|
+
return result
|
|
139
|
+
}
|
|
140
|
+
// Validate only Core envelope fields, never arbitrary app data/output or usage values.
|
|
141
|
+
private struct Sequences: Decodable {
|
|
142
|
+
enum Keys: String, CodingKey { case seq, firstSeq, clearedSeq, head, floor, afterSeq, throughSeq, messages, streaming }
|
|
143
|
+
init(from decoder: Decoder) throws {
|
|
144
|
+
let keys = try decoder.container(keyedBy: Keys.self)
|
|
145
|
+
for key in [Keys.seq, .firstSeq, .clearedSeq, .head, .floor, .afterSeq, .throughSeq] {
|
|
146
|
+
if keys.contains(key), !(try keys.decodeNil(forKey: key)) {
|
|
147
|
+
let value: UInt64
|
|
148
|
+
do { value = try keys.decode(UInt64.self, forKey: key) }
|
|
149
|
+
catch { throw CrocheError("invalid_input", "Invalid Core sequence") }
|
|
150
|
+
_ = try CoreEvent.publicSequence(value)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
_ = try keys.decodeIfPresent([Sequences].self, forKey: .messages)
|
|
154
|
+
_ = try keys.decodeIfPresent(Sequences.self, forKey: .streaming)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
static func decodeValue<T: Decodable>(_ type: T.Type, _ text: String) throws -> T {
|
|
158
|
+
let bytes = Data(text.utf8)
|
|
159
|
+
_ = try decoder().decode(Sequences.self, from: bytes)
|
|
160
|
+
return try decoder().decode(type, from: bytes)
|
|
161
|
+
}
|
|
162
|
+
static func decoder() -> JSONDecoder {
|
|
163
|
+
let decoder = JSONDecoder()
|
|
164
|
+
decoder.dateDecodingStrategy = .custom { value in
|
|
165
|
+
let text = try value.singleValueContainer().decode(String.self)
|
|
166
|
+
let fractional = ISO8601DateFormatter(); fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
167
|
+
guard let date = fractional.date(from: text) ?? ISO8601DateFormatter().date(from: text) else {
|
|
168
|
+
throw CrocheError("invalid_input", "Invalid Core event date")
|
|
169
|
+
}
|
|
170
|
+
return date
|
|
171
|
+
}
|
|
172
|
+
return decoder
|
|
173
|
+
}
|
|
174
|
+
private struct Failure: Decodable { let code: String; let message: String; let poisoned: Bool? }
|
|
175
|
+
static func decodeFailure(_ text: String) throws -> StreamError {
|
|
176
|
+
let value = try decoder().decode(Failure.self, from: Data(text.utf8))
|
|
177
|
+
return StreamError(code: value.code, message: value.message, poisoned: value.poisoned ?? false)
|
|
178
|
+
}
|
|
179
|
+
private struct Event: Decodable {
|
|
180
|
+
let value: RuntimeEvent
|
|
181
|
+
enum Keys: String, CodingKey { case type, seq, images, messages, reachedFloor, logId, clearedSeq }
|
|
182
|
+
init(from decoder: Decoder) throws {
|
|
183
|
+
let keys = try decoder.container(keyedBy: Keys.self)
|
|
184
|
+
let type = try keys.decode(String.self, forKey: .type)
|
|
185
|
+
switch type {
|
|
186
|
+
case "input":
|
|
187
|
+
struct Input: Decodable { let seq: Int; let firstSeq: Int; let id: String; let kind: InputKind; let text: String?; let images: [ImageSummary]?; let status: InputStatus; let error: RuntimeError?; let at: Date }
|
|
188
|
+
let v = try Input(from: decoder)
|
|
189
|
+
value = .input(InputEvent(seq: v.seq, firstSeq: v.firstSeq, id: v.id, kind: v.kind, text: v.text, images: v.images ?? [], status: v.status, error: v.error, at: v.at))
|
|
190
|
+
case "message.start": value = .messageStart(try MessageStart(from: decoder))
|
|
191
|
+
case "message.delta": value = .messageDelta(try MessageDelta(from: decoder))
|
|
192
|
+
case "message.end": value = .messageEnd(try MessageEnd(from: decoder))
|
|
193
|
+
case "state": value = .state(try StateEvent(from: decoder))
|
|
194
|
+
case "snapshot": value = .snapshot(try Snapshot(from: decoder))
|
|
195
|
+
case "gap": value = .gap(try Gap(from: decoder))
|
|
196
|
+
case "app": value = .app(try AppStreamEvent(from: decoder))
|
|
197
|
+
case "turn": value = .turn(try TurnEvent(from: decoder))
|
|
198
|
+
case "cleared": value = .cleared(try Cleared(from: decoder))
|
|
199
|
+
case "error":
|
|
200
|
+
if keys.contains(.seq) { value = .error(try ErrorEvent(from: decoder)) }
|
|
201
|
+
else {
|
|
202
|
+
let e = try Failure(from: decoder)
|
|
203
|
+
value = .streamError(StreamError(code: e.code, message: e.message, poisoned: e.poisoned ?? false))
|
|
204
|
+
}
|
|
205
|
+
case "page": value = .page(Page(messages: try keys.decode([Event].self, forKey: .messages).map(\.value), reachedFloor: try keys.decode(Bool.self, forKey: .reachedFloor), logId: try keys.decode(String.self, forKey: .logId), clearedSeq: try keys.decode(Int.self, forKey: .clearedSeq)))
|
|
206
|
+
case "replaced": value = .replaced
|
|
207
|
+
default: value = .unknown(type: type)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
static func decode(_ text: String) throws -> RuntimeEvent { try decodeValue(Event.self, text).value }
|
|
212
|
+
}
|