@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.
Files changed (66) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +475 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/android/build.gradle +47 -0
  5. package/android/src/main/AndroidManifest.xml +8 -0
  6. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +836 -0
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
  9. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  11. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  12. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  13. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  16. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  17. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  18. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  32. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  33. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  34. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  35. package/croche-react-native.podspec +28 -0
  36. package/ios/CrocheRuntimeBridge.swift +986 -0
  37. package/ios/RNCrocheRuntime.mm +221 -0
  38. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  39. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  40. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  41. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
  42. package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
  43. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  44. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  45. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  48. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
  49. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  50. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
  51. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  52. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  53. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  54. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  55. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  56. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  57. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  58. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  59. package/package.json +40 -4
  60. package/scripts/vendor-native.sh +56 -0
  61. package/src/NativeCrocheRuntime.ts +162 -0
  62. package/src/index.ts +660 -0
  63. package/src/project-types.ts +35 -0
  64. package/src/project.ts +426 -0
  65. package/src/protocol.ts +28 -0
  66. package/src/types.ts +9 -0
@@ -0,0 +1,561 @@
1
+ import Foundation
2
+ #if canImport(FoundationNetworking)
3
+ import FoundationNetworking
4
+ #endif
5
+
6
+ // The Swift PAL: what only the platform can do. The Rust Runtime (crates/croche-ffi) decides
7
+ // everything else, including SSE framing, response bounds, timeouts' meaning, persistence
8
+ // order, upkeep and cancellation rules. Its calls into this host block a background thread.
9
+
10
+ extension CrocheError {
11
+ init(_ error: Error) {
12
+ if let e = error as? CrocheError { self = e }
13
+ else if case let .Failure(code, message)? = error as? FfiError { self.init(code, message) }
14
+ else { self.init("host_error", "The host operation failed") }
15
+ }
16
+ var ffi: FfiError { .Failure(code: code, message: message) }
17
+ }
18
+
19
+ /// The binding's `identity`, named so `CrocheRuntime.identity` does not shadow it. Unqualified:
20
+ /// the React Native pod compiles the SDK and its bindings into one module.
21
+ func ffiIdentity(_ config: String) throws -> String { try identity(config: config) }
22
+
23
+ /// Runs `body` on the Swift concurrency pool and blocks this (Rust-owned, background) thread
24
+ /// until it finishes, `cancel` fires or `milliseconds` pass.
25
+ func blockOn<T: Sendable>(milliseconds: Double?, cancel: CancelToken?,
26
+ _ body: @escaping @Sendable (RuntimeCancellation) async throws -> T) throws -> T {
27
+ let cancellation = RuntimeCancellation()
28
+ cancel?.onCancel(callback: CancelHook(cancellation))
29
+ let box = ResultBox<T>()
30
+ let done = DispatchSemaphore(value: 0)
31
+ Task {
32
+ do { box.set(.success(try await bounded(milliseconds: milliseconds, cancellation: cancellation, body: body))) }
33
+ catch { box.set(.failure(error)) }
34
+ done.signal()
35
+ }
36
+ done.wait()
37
+ do { return try box.get() } catch { throw CrocheError(error).ffi }
38
+ }
39
+
40
+ /// An app command (H1): runs `body` until it returns, however long after a cancel. The cancel
41
+ /// (the turn's, or the command's deadline: the Runtime is its only clock) reaches the handler
42
+ /// through its `RuntimeCancellation`, as before H1. The Task itself is not cancelled: a handler
43
+ /// polling with `try? await Task.sleep` would then spin on the cooperative pool. The Runtime has
44
+ /// already stopped waiting, so only this abandoned worker waits, and the command's slot stays
45
+ /// held until the handler is done.
46
+ func blockUntilSettled<T: Sendable>(cancel: CancelToken,
47
+ _ body: @escaping @Sendable (RuntimeCancellation) async throws -> T) throws -> T {
48
+ let cancellation = RuntimeCancellation()
49
+ let box = ResultBox<T>()
50
+ let done = DispatchSemaphore(value: 0)
51
+ let run: @Sendable () async -> Void = {
52
+ do { try cancellation.check(); box.set(.success(try await body(cancellation))) }
53
+ catch { box.set(.failure(error)) }
54
+ done.signal()
55
+ }
56
+ // Handlers run on `ToolThreads` where the OS has task executors, apart from the cooperative
57
+ // pool, and on that pool before. Neither path makes blocking safe: async handlers must not
58
+ // block, and blocking work goes through `blockingTool`, a thread of its own on every OS.
59
+ // Keep this branch (Keel, #342). `ToolExecution.forceFallback` lets the tests run the
60
+ // earlier-OS path, and `AtlasH1ReviewTests` and `BlockingToolTests` cover both paths.
61
+ if !ToolExecution.forceFallback, #available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *) {
62
+ Task(executorPreference: ToolThreads.shared) { await run() }
63
+ } else {
64
+ Task { await run() }
65
+ }
66
+ cancel.onCancel(callback: CancelHook(cancellation))
67
+ done.wait()
68
+ if cancellation.isCancelled { throw CrocheError("cancelled", "The operation was cancelled").ffi }
69
+ do { return try box.get() } catch { throw handlerError(error).ffi }
70
+ }
71
+
72
+ /// For tests: run handlers as an OS without `TaskExecutor` does (on Swift's cooperative pool).
73
+ enum ToolExecution { nonisolated(unsafe) static var forceFallback = false }
74
+
75
+ /// Thrown by an SDK bridge's own handler (React Native, compiled into this module) when it has
76
+ /// no handler of its own to run, before anything ran. Internal: app code cannot claim it.
77
+ struct ToolNotDispatched: Error {}
78
+
79
+ /// An error from a tool handler. "Nothing ran" is the host's to say, never a handler's: a
80
+ /// handler that throws `tool_not_dispatched` or `host_unresponsive` (perhaps passing on another
81
+ /// Runtime's error) may already have had its effect, so the call fails as `tool_failed`.
82
+ func handlerError(_ error: Error) -> CrocheError {
83
+ if error is ToolNotDispatched { return CrocheError("tool_not_dispatched", "No handler ran for this tool") }
84
+ let e = CrocheError(error)
85
+ return ["tool_not_dispatched", "host_unresponsive"].contains(e.code) ? CrocheError("tool_failed", e.message) : e
86
+ }
87
+
88
+ /// Where app command handlers run (H1), where the OS has task executors: GCD threads, apart from
89
+ /// Swift's cooperative pool, which also runs the Runtime's own requests. This does not make a
90
+ /// blocking async handler safe (measured on Linux, #342); blocking work uses `blockingTool`.
91
+ @available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
92
+ final class ToolThreads: TaskExecutor, @unchecked Sendable {
93
+ static let shared = ToolThreads()
94
+ private let queue = DispatchQueue(label: "dev.croche.tools", attributes: .concurrent)
95
+ func enqueue(_ job: consuming ExecutorJob) {
96
+ let job = UnownedJob(job), executor = asUnownedTaskExecutor()
97
+ queue.async { job.runSynchronously(on: executor) }
98
+ }
99
+ }
100
+
101
+ final class CancelHook: CancelCallback, @unchecked Sendable {
102
+ private let cancellation: RuntimeCancellation
103
+ init(_ cancellation: RuntimeCancellation) { self.cancellation = cancellation }
104
+ func cancelled() { cancellation.cancel() }
105
+ }
106
+ final class EventHook: EventListener, @unchecked Sendable {
107
+ private let callback: @Sendable (JSON) -> Void
108
+ init(_ callback: @escaping @Sendable (JSON) -> Void) { self.callback = callback }
109
+ func onEvent(event: String) { if let value = try? JSON(event) { callback(value) } }
110
+ }
111
+ private final class ResultBox<T>: @unchecked Sendable {
112
+ private let lock = NSLock()
113
+ private var value: Result<T, Error>?
114
+ func set(_ result: Result<T, Error>) { lock.withLock { value = result } }
115
+ func get() throws -> T { try lock.withLock { value! }.get() }
116
+ }
117
+
118
+ /// An ISO time as epoch ms.
119
+ private func epochMs(_ text: String) -> Double? {
120
+ let parse = ISO8601DateFormatter()
121
+ parse.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
122
+ if let date = parse.date(from: text) { return date.timeIntervalSince1970 * 1000 }
123
+ parse.formatOptions = [.withInternetDateTime]
124
+ return parse.date(from: text).map { $0.timeIntervalSince1970 * 1000 }
125
+ }
126
+ /// The `at`s (epoch ms) of a schedule set `[{id, at}]`.
127
+ func times(_ entries: JSON) -> [Double] { (entries.array ?? []).compactMap { $0["at"].string.flatMap(epochMs) } }
128
+ /// A delivery's `retryAt` (epoch ms, or an ISO time), or nil.
129
+ func retryAt(_ value: JSON) -> Double? { value.number ?? value.string.flatMap(epochMs) }
130
+
131
+ /// The Swift PAL handed to the Rust Runtime.
132
+ final class SwiftHost: HostPal, @unchecked Sendable {
133
+ private let storage: any RuntimeStorage
134
+ private let projectRecords: ProjectRecordFiles
135
+ // Internal test trace, configured before Core starts; records only delegated store calls.
136
+ var beforeStoreAccess: (@Sendable (String) -> Void)?
137
+ private let secretStore: any RuntimeSecretStore
138
+ private let attestor: (any RuntimeAttestor)?
139
+ private let http: RuntimeHTTP?
140
+ /// The default transport's session, closed with the Runtime.
141
+ let session = RuntimeSession()
142
+ // Accepted tools are never removed: a tool change waits its turn in the Core's queue, and turns queued before it
143
+ // still run the old list. The Core alone decides which commands a turn may call.
144
+ private var handlers: [String: ToolHandler]
145
+ private var staged: [String: Int] = [:], stamp = 0 // names whose only handler is from a call in flight
146
+ private let identity: String
147
+ private let background: Bool
148
+ private let lock = NSLock()
149
+ private weak var core: CoreRuntime?
150
+ private var wakeTarget: Double?
151
+ private var timer: Task<Void, Never>?
152
+ private var stopped = false
153
+ /// This Runtime's attachment to `osScheduler` (attached right after the host is built),
154
+ /// released once: a second stop, or a stale close after the scheduler was attached again for
155
+ /// another Runtime, must not free an identifier someone else holds. Guarded by `lock`.
156
+ private var osAttached = false
157
+ private let osScheduler: (any RuntimeScheduler)?
158
+ private var wallClock: @Sendable () -> Double = { Date().timeIntervalSince1970 * 1000 }
159
+ /// The wall clock (epoch ms) the Runtime and its timers read. Tests move it.
160
+ var clock: @Sendable () -> Double {
161
+ get { lock.withLock { wallClock } }
162
+ set { lock.withLock { wallClock = newValue } }
163
+ }
164
+ private var deliverDue: (@Sendable () async -> Void)?
165
+ /// Runs `deliverDue()` on the Runtime when the earliest note's time comes.
166
+ var deliver: (@Sendable () async -> Void)? {
167
+ get { lock.withLock { deliverDue } }
168
+ set { lock.withLock { deliverDue = newValue } }
169
+ }
170
+ private var dueAt: Double?
171
+ private var fired: Double?
172
+ private var dueTimer: Task<Void, Never>?
173
+
174
+ init(storage: any RuntimeStorage, secrets: any RuntimeSecretStore, attestor: (any RuntimeAttestor)?,
175
+ http: RuntimeHTTP?, tools: [String: ToolHandler], background: Bool,
176
+ scheduler: (any RuntimeScheduler)? = nil, projectRecords: ProjectRecordFiles = ProjectRecordFiles()) {
177
+ self.storage = storage; self.projectRecords = projectRecords; secretStore = secrets; self.attestor = attestor; self.http = http
178
+ handlers = tools; self.background = background; osScheduler = scheduler
179
+ identity = "\(ObjectIdentifier(storage as AnyObject).hashValue)"
180
+ }
181
+
182
+ private func host<T>(_ body: () throws -> T) throws -> T {
183
+ do { return try body() } catch { throw CrocheError(error).ffi }
184
+ }
185
+
186
+ // MARK: HTTP
187
+ func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws {
188
+ let transport = http, session = session
189
+ _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
190
+ if let transport { try await Self.adapt(transport, request, sink, signal) }
191
+ else { try await session.stream(request, into: sink, cancellation: signal) }
192
+ return true
193
+ }
194
+ }
195
+
196
+ /// An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
197
+ /// a response, and its stream deltas as server-sent events.
198
+ private static func adapt(_ transport: RuntimeHTTP, _ request: PalHttpRequest, _ sink: HttpSink,
199
+ _ signal: RuntimeCancellation) async throws {
200
+ var headers: [String: JSON] = [:]
201
+ for header in request.headers { headers[header.name] = .string(header.value) }
202
+ let effect = JSON.object(["url": .string(request.url), "method": .string(request.method), "headers": .object(headers),
203
+ "body": (try? JSON(request.body)) ?? .string(request.body),
204
+ "timeoutMs": .number(Double(request.timeoutMs))])
205
+ let streaming = StreamStart()
206
+ let reply = try await transport(effect, signal) { data in
207
+ if streaming.begin() {
208
+ sink.head(status: 200, headers: [PalHeader(name: "content-type", value: "text/event-stream")])
209
+ }
210
+ let frame = data.split(separator: "\n", omittingEmptySubsequences: false).map { "data: \($0)\n" }.joined() + "\n"
211
+ _ = sink.chunk(bytes: Data(frame.utf8))
212
+ }
213
+ let status = UInt16(reply["status"].number ?? 0)
214
+ var fields = (reply["headers"].object ?? [:]).compactMap { key, value in value.string.map { PalHeader(name: key, value: $0) } }
215
+ if reply["streamed"] == .bool(true) {
216
+ if streaming.begin() { sink.head(status: status, headers: [PalHeader(name: "content-type", value: "text/event-stream")]) }
217
+ return
218
+ }
219
+ fields.removeAll { $0.name.lowercased() == "content-type" }
220
+ fields.append(PalHeader(name: "content-type", value: "application/json"))
221
+ sink.head(status: status, headers: fields)
222
+ let body = reply["body"] != .null ? try reply["body"].encoded() : Data((reply["raw"].string ?? "").utf8)
223
+ if !body.isEmpty { _ = sink.chunk(bytes: body) }
224
+ }
225
+
226
+ // MARK: Storage
227
+ /// The Core names its snapshot by the key it locks, and other records `<key>.<entry>` (F19's
228
+ /// held sends: `<key>.held`). Each goes to its own place: an entry never replaces the snapshot.
229
+ private var snapshotKey: String? { get { lock.withLock { lockedKey } } set { lock.withLock { lockedKey = newValue } } }
230
+ private var lockedKey: String?
231
+ private func entry(_ key: String) throws -> String? {
232
+ guard let main = snapshotKey, key != main else { return nil }
233
+ guard key.hasPrefix(main + "."), key.count > main.count + 1 else { throw CrocheError("storage_error", "Unknown storage key") }
234
+ return String(key.dropFirst(main.count + 1))
235
+ }
236
+ func read(key: String) throws -> String? {
237
+ try host {
238
+ if ProjectRecordFiles.owns(key) { return try projectRecords.read(key) }
239
+ beforeStoreAccess?(key)
240
+ let state: JSON
241
+ if let name = try entry(key) {
242
+ // A storage without entries never stored one.
243
+ guard let keyed = storage as? any KeyedRuntimeStorage else { return nil }
244
+ state = try keyed.load(entry: name)
245
+ } else { state = try storage.load() }
246
+ return state == .null ? nil : String(decoding: try state.encoded(), as: UTF8.self)
247
+ }
248
+ }
249
+ func write(key: String, value: String) throws {
250
+ try host {
251
+ if ProjectRecordFiles.owns(key) { return try projectRecords.write(key, value) }
252
+ beforeStoreAccess?(key)
253
+ guard let name = try entry(key) else { return try storage.save(try JSON(value)) }
254
+ guard let keyed = storage as? any KeyedRuntimeStorage else {
255
+ throw CrocheError("storage_error", "This RuntimeStorage keeps only its snapshot")
256
+ }
257
+ try keyed.save(entry: name, try JSON(value))
258
+ }
259
+ }
260
+ func readSecret(key: String) throws -> String? {
261
+ try host { String(decoding: try secretStore.load().encoded(), as: UTF8.self) }
262
+ }
263
+ func writeSecret(key: String, value: String) throws { try host { try secretStore.save(try JSON(value)) } }
264
+ func remove(key: String) throws {
265
+ try host {
266
+ guard !ProjectRecordFiles.owns(key) else { throw CrocheError("storage_error", "The project record is kept when agent data is removed") }
267
+ beforeStoreAccess?(key)
268
+ if let name = try entry(key) {
269
+ guard let keyed = storage as? any KeyedRuntimeStorage else { return }
270
+ try keyed.remove(entry: name)
271
+ } else { try storage.remove() }
272
+ }
273
+ }
274
+ func removeSecret(key: String) throws { try host { try secretStore.remove() } }
275
+ func lock(key: String) throws {
276
+ try host {
277
+ if ProjectRecordFiles.owns(key) { return try projectRecords.acquire(key) }
278
+ guard !projectRecords.held else { throw CrocheError("storage_error", "Release the project record lock before taking a store lock") }
279
+ beforeStoreAccess?(key)
280
+ try storage.acquire(); snapshotKey = key
281
+ }
282
+ }
283
+ func unlock(key: String) {
284
+ if ProjectRecordFiles.owns(key) { projectRecords.release(key); return }
285
+ beforeStoreAccess?(key)
286
+ stop(); storage.release(); snapshotKey = nil
287
+ }
288
+ func storeIdentity() -> String { identity }
289
+
290
+ // MARK: The turn archive (F20.6)
291
+ /// The storage's archive, or the typed "no archive": the Runtime then keeps none, and every
292
+ /// turn, clearHistory and memory work as before.
293
+ private func archive() throws -> any ArchiveRuntimeStorage {
294
+ guard let archive = storage as? any ArchiveRuntimeStorage else {
295
+ throw CrocheError("archive_unavailable", "This host keeps no turn archive.")
296
+ }
297
+ return archive
298
+ }
299
+ func archiveAppendLine(entry: String, line: String) throws { try host { try archive().appendLine(entry: entry, line) } }
300
+ func archiveReadLines(entry: String) throws -> [String] { try host { try archive().readLines(entry: entry) } }
301
+ func archiveReplaceLines(entry: String, lines: [String]) throws { try host { try archive().replaceLines(entry: entry, lines) } }
302
+ func archiveRemove(entry: String) throws { try host { try archive().remove(entry: entry) } }
303
+ func archiveEntries(prefix: String) throws -> [ArchiveEntry] {
304
+ try host { try archive().entries(prefix: prefix).sorted { $0.key < $1.key }.map { ArchiveEntry(entry: $0.key, bytes: UInt64($0.value)) } }
305
+ }
306
+ /// Where the message log goes (S1, rev 4 §17.13): in lines when the storage appends them, in
307
+ /// entries when it keeps entries, else inside the snapshot. Never refused.
308
+ func storageCapability() -> StorageCapability {
309
+ if storage is any ArchiveRuntimeStorage { return .lines }
310
+ if storage is any KeyedRuntimeStorage { return .keyed }
311
+ return .snapshot
312
+ }
313
+
314
+ /// Stages the handlers for names with none yet, or with one only staged by a call still in
315
+ /// flight (a later call wins). Returns the stamp that `unstageTools` needs.
316
+ func stageTools(_ tools: [String: ToolHandler]) -> Int {
317
+ lock.withLock {
318
+ stamp += 1
319
+ for (name, handler) in tools where handlers[name] == nil || staged[name] != nil {
320
+ handlers[name] = handler; staged[name] = stamp
321
+ }
322
+ return stamp
323
+ }
324
+ }
325
+ /// A refused call: removes what it staged, unless a later call has staged the name since.
326
+ func unstageTools(_ names: Dictionary<String, ToolHandler>.Keys, stamp: Int) {
327
+ lock.withLock { for name in names where staged[name] == stamp { handlers[name] = nil; staged[name] = nil } }
328
+ }
329
+ /// An accepted call: its handlers serve every name it passed.
330
+ func acceptTools(_ tools: [String: ToolHandler]) {
331
+ lock.withLock { for (name, handler) in tools { handlers[name] = handler; staged[name] = nil } }
332
+ }
333
+
334
+ // MARK: Tools and attestation
335
+ func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput {
336
+ let call = try host { try JSON(invocation) }
337
+ guard let name = call["tool"].string, let handler = lock.withLock({ handlers[name] }) else {
338
+ // Nothing ran, and the Runtime may tell the model so (driver.rs NOT_DISPATCHED).
339
+ throw FfiError.Failure(code: "tool_not_dispatched", message: "The host tool is not available")
340
+ }
341
+ var invocation = JSON.object(["tool": call["tool"], "key": call["key"], "args": call["args"]])
342
+ if call["command"] != .null { invocation["command"] = call["command"] }
343
+ let context = call["context"], request = invocation, sink = ImageSink()
344
+ // No deadline here: the Runtime times the call and cancels it (H4). This returns when
345
+ // the handler does, so a stuck one keeps its slot (H1).
346
+ let value = try blockUntilSettled(cancel: cancel) { signal in
347
+ try await handler(request, ToolContext(data: context, cancellation: signal, images: sink))
348
+ }
349
+ // A plain handler's JSON is the value as it was; a `withResult` one's images ride beside
350
+ // it, one sink per call (never shared between concurrent calls).
351
+ return ToolOutput(value: String(decoding: try host { try value.encoded() }, as: UTF8.self),
352
+ images: try sink.take().map(Images.record))
353
+ }
354
+ func attest(request: String, timeoutMs: UInt64) throws -> String {
355
+ guard let attestor else { throw FfiError.Failure(code: "attestation_unsupported", message: "This host has no attestor") }
356
+ let effect = try host { try JSON(request) }
357
+ guard let clientData = effect["clientData"].string, let hash = base64URLDecode(effect["clientDataHash"].string ?? "") else {
358
+ throw FfiError.Failure(code: "invalid_abi", message: "Malformed attest effect")
359
+ }
360
+ let proof = try blockOn(milliseconds: Double(timeoutMs), cancel: nil) { _ -> JSON in
361
+ let proof = try await attestor.attest(clientData: clientData, clientDataHash: hash)
362
+ return .object(["platform": .string(attestor.platform), "token": .string(proof.token),
363
+ "keyId": proof.keyId.map { .string($0) } ?? .null])
364
+ }
365
+ return String(decoding: try host { try proof.encoded() }, as: UTF8.self)
366
+ }
367
+
368
+ // MARK: Clock, entropy, timer
369
+ func nowMs() -> Double { clock() }
370
+ func utcOffsetMinutes(atMs: Double) -> Int64 {
371
+ Int64(TimeZone.current.secondsFromGMT(for: Date(timeIntervalSince1970: atMs / 1000)) / 60)
372
+ }
373
+ func random() -> String { UUID().uuidString }
374
+ func wake(atMs: Double?) {
375
+ lock.withLock { wakeTarget = atMs }
376
+ arm()
377
+ }
378
+ /// The agent's whole pending schedule set (JSON `[{id, at}]`), after each durable change and at
379
+ /// open: a timer while running, and the OS's deferred work (`scheduler`) for after. A refused
380
+ /// registration fails this acknowledgement, which the Core reports as `schedule.degraded`
381
+ /// with its code.
382
+ func schedule(entries: String) throws { try host { try applySchedule(target(times(try JSON(entries)))) } }
383
+ private var retryFloor: Double?
384
+ /// A failed delivery answered `retryAt`: a note already due waits until then.
385
+ func retryAfter(_ at: Double) { lock.withLock { retryFloor = at } }
386
+ /// When to wake for these notes: the earliest `at`, except that a note already due waits for
387
+ /// a later `retryAt` (a delivery failed).
388
+ func target(_ times: [Double]) -> Double? {
389
+ let now = clock()
390
+ let floor = lock.withLock { retryFloor }.flatMap { $0 > now ? $0 : nil }
391
+ return times.map { at in floor.map { at <= now ? $0 : at } ?? at }.min()
392
+ }
393
+ /// Arms the timer for `at` (nil: nothing pending) and registers it with the OS.
394
+ func applySchedule(_ at: Double?) throws {
395
+ lock.withLock { dueAt = at }
396
+ armDelivery()
397
+ guard let os = osScheduler else { return }
398
+ do {
399
+ if let at { try os.schedule(earliest: Date(timeIntervalSince1970: at / 1000)) } else { os.cancel() }
400
+ } catch let error as CrocheError { throw error }
401
+ catch { throw CrocheError("schedule_failed", "The OS scheduler refused the request") }
402
+ }
403
+ /// A delivery is starting: it covers every note due now, so the timer never retries one.
404
+ func attempted() { let now = clock(); lock.withLock { fired = max(fired ?? -.infinity, now) } }
405
+ /// The Runtime is open: a wake it asked for while opening can now fire.
406
+ func attach(_ core: CoreRuntime) { lock.withLock { self.core = core }; arm(); armDelivery() }
407
+ /// The Runtime is opening: attach it to the OS scheduler (which may refuse with
408
+ /// `scheduler_conflict`); `stop` releases that attachment once.
409
+ func attachScheduler() throws {
410
+ guard let os = osScheduler else { return }
411
+ try os.attach()
412
+ lock.withLock { osAttached = true }
413
+ }
414
+ func stop() {
415
+ let release = lock.withLock {
416
+ stopped = true; timer?.cancel(); timer = nil; dueTimer?.cancel(); dueTimer = nil
417
+ defer { osAttached = false }
418
+ return osAttached
419
+ }
420
+ if release { osScheduler?.detach() }
421
+ }
422
+ /// One timer at the earliest note, never firing a delivery before its time (a timer that ends
423
+ /// early re-arms), and at most once per time: a delivery that was cut short leaves its notes
424
+ /// for the next open, foreground or OS run rather than retrying at once.
425
+ private func armDelivery() {
426
+ let now = clock()
427
+ lock.withLock {
428
+ dueTimer?.cancel(); dueTimer = nil
429
+ guard !stopped, core != nil, let target = dueAt, !(fired.map { target <= $0 } ?? false) else { return }
430
+ let delay = max(0, target - now)
431
+ dueTimer = Task.detached { [weak self] in
432
+ try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000))
433
+ guard !Task.isCancelled, let self else { return }
434
+ await self.due(target)
435
+ }
436
+ }
437
+ }
438
+ private func due(_ target: Double) async {
439
+ if clock() < target { armDelivery(); return }
440
+ let run: (@Sendable () async -> Void)? = lock.withLock {
441
+ if stopped { return nil }
442
+ fired = target
443
+ return deliverDue
444
+ }
445
+ await run?()
446
+ }
447
+ private func arm() {
448
+ lock.withLock {
449
+ timer?.cancel(); timer = nil
450
+ guard background, !stopped, let target = wakeTarget, let core else { return }
451
+ timer = Task.detached { [weak core] in
452
+ let delay = max(0, target - Date().timeIntervalSince1970 * 1000)
453
+ try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000))
454
+ guard !Task.isCancelled, let core else { return }
455
+ Thread.detachNewThread { core.tick() }
456
+ }
457
+ }
458
+ }
459
+ }
460
+
461
+ private final class StreamStart: @unchecked Sendable {
462
+ private let lock = NSLock()
463
+ private var started = false
464
+ /// True once: the first caller starts the stream.
465
+ func begin() -> Bool { lock.withLock { if started { return false }; started = true; return true } }
466
+ }
467
+
468
+ /// The default transport's connections: one ephemeral URLSession per Runtime, so consecutive
469
+ /// calls (a first launch's challenge, register and sync; a turn's gateway calls) reuse a
470
+ /// connection instead of paying DNS, TCP and TLS again. As before: no cookies, cache, stored
471
+ /// credentials or redirects, and each request keeps its own timeout. Closing the Runtime
472
+ /// invalidates it; a request after that is refused.
473
+ final class RuntimeSession: @unchecked Sendable {
474
+ private let lock = NSLock()
475
+ private var session: URLSession?
476
+ private let router = HTTPStreamDelegate()
477
+ init() {
478
+ let config = URLSessionConfiguration.ephemeral
479
+ config.httpCookieStorage = nil; config.httpShouldSetCookies = false; config.urlCache = nil
480
+ config.urlCredentialStorage = nil
481
+ session = URLSession(configuration: config, delegate: router, delegateQueue: nil)
482
+ }
483
+ deinit { session?.invalidateAndCancel() }
484
+ var isClosed: Bool { lock.withLock { session == nil } }
485
+ /// Cancels what is in flight and refuses every later request.
486
+ func close() {
487
+ let closing = lock.withLock { () -> URLSession? in defer { session = nil }; return session }
488
+ closing?.invalidateAndCancel()
489
+ }
490
+ /// A task on this session whose parts arrive on the returned stream. Never on a closed one.
491
+ private func start(_ request: URLRequest) throws -> (URLSessionDataTask, AsyncThrowingStream<HTTPPart, Error>) {
492
+ let (parts, continuation) = AsyncThrowingStream<HTTPPart, Error>.makeStream()
493
+ return try lock.withLock {
494
+ guard let session else { throw CrocheError("network_error", "The Runtime is closed") }
495
+ let task = session.dataTask(with: request)
496
+ router.register(task, continuation)
497
+ return (task, parts)
498
+ }
499
+ }
500
+ /// The response goes to the Runtime as it arrives. The Runtime frames and bounds it.
501
+ func stream(_ request: PalHttpRequest, into sink: any HttpSinkProtocol, cancellation: RuntimeCancellation) async throws {
502
+ try cancellation.check()
503
+ guard let url = URL(string: request.url) else { throw CrocheError("network_error", "Invalid HTTP effect URL") }
504
+ var urlRequest = URLRequest(url: url)
505
+ urlRequest.httpMethod = request.method
506
+ if !["GET", "HEAD"].contains(request.method) { urlRequest.httpBody = Data(request.body.utf8) }
507
+ urlRequest.timeoutInterval = Double(request.timeoutMs) / 1000
508
+ urlRequest.httpShouldHandleCookies = false
509
+ for header in request.headers { urlRequest.setValue(header.value, forHTTPHeaderField: header.name) }
510
+ let (task, parts) = try start(urlRequest)
511
+ let listener = cancellation.observe { task.cancel() }
512
+ // Only this request ends here: a finished task ignores the cancel, an unfinished one
513
+ // (cancelled, or refused by the sink) gives up its connection, never another's.
514
+ defer { cancellation.remove(listener); task.cancel() }
515
+ task.resume()
516
+ for try await part in parts {
517
+ switch part {
518
+ case .head(let status, let fields, _):
519
+ sink.head(status: UInt16(clamping: status),
520
+ headers: fields.compactMap { key, value in value.string.map { PalHeader(name: key, value: $0) } })
521
+ case .body(let data):
522
+ // The Runtime wants no more (a bound was exceeded): stop reading.
523
+ if !sink.chunk(bytes: data) { return }
524
+ }
525
+ }
526
+ try cancellation.check()
527
+ }
528
+ }
529
+
530
+ /// The session's delegate: hands each task's callbacks to that task's stream.
531
+ private final class HTTPStreamDelegate: NSObject, URLSessionDataDelegate, @unchecked Sendable {
532
+ private let lock = NSLock()
533
+ private var sinks: [Int: AsyncThrowingStream<HTTPPart, Error>.Continuation] = [:]
534
+ func register(_ task: URLSessionTask, _ sink: AsyncThrowingStream<HTTPPart, Error>.Continuation) {
535
+ lock.withLock { sinks[task.taskIdentifier] = sink }
536
+ }
537
+ private func sink(_ task: URLSessionTask) -> AsyncThrowingStream<HTTPPart, Error>.Continuation? {
538
+ lock.withLock { sinks[task.taskIdentifier] }
539
+ }
540
+ func urlSession(_ session: URLSession, task: URLSessionTask,
541
+ willPerformHTTPRedirection response: HTTPURLResponse,
542
+ newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
543
+ completionHandler(nil)
544
+ }
545
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
546
+ didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
547
+ guard let sink = sink(dataTask) else { completionHandler(.cancel); return }
548
+ guard let http = response as? HTTPURLResponse else {
549
+ sink.finish(throwing: CrocheError("network_error", "No HTTP response")); completionHandler(.cancel); return
550
+ }
551
+ var headers: [String: JSON] = [:]
552
+ for (key, value) in http.allHeaderFields { headers[String(describing: key)] = .string(String(describing: value)) }
553
+ sink.yield(.head(status: http.statusCode, headers: headers, expectedLength: response.expectedContentLength))
554
+ completionHandler(.allow)
555
+ }
556
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) { sink(dataTask)?.yield(.body(chunk)) }
557
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
558
+ let sink = lock.withLock { sinks.removeValue(forKey: task.taskIdentifier) }
559
+ if error != nil { sink?.finish(throwing: CrocheError("network_error", "HTTP transport failed")) } else { sink?.finish() }
560
+ }
561
+ }