@h1r-ai/croche-react-native 0.0.0-stage → 0.5.1

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 (77) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +486 -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 +837 -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/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
  11. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  12. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  16. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +32 -0
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  18. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +415 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +379 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +227 -0
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  40. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  41. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  42. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  43. package/croche-react-native.podspec +28 -0
  44. package/ios/CrocheRuntimeBridge.swift +1008 -0
  45. package/ios/RNCrocheRuntime.mm +221 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  48. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  49. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +215 -0
  50. package/ios/vendor/CrocheRuntimeSDK/Host.swift +562 -0
  51. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  52. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  53. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
  54. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  55. package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
  56. package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
  57. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +558 -0
  58. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  59. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +453 -0
  60. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  61. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +345 -0
  62. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  63. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  64. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  65. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  66. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  67. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  68. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  69. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  70. package/package.json +40 -4
  71. package/scripts/vendor-native.sh +56 -0
  72. package/src/NativeCrocheRuntime.ts +162 -0
  73. package/src/index.ts +660 -0
  74. package/src/project-types.ts +35 -0
  75. package/src/project.ts +434 -0
  76. package/src/protocol.ts +28 -0
  77. package/src/types.ts +9 -0
@@ -0,0 +1,1008 @@
1
+ import Foundation
2
+ import CryptoKit
3
+
4
+ // The React Native bridge over the iOS SDK (sdk/swift). It holds one CrocheRuntime per JS
5
+ // handle and carries calls, events and tool round-trips; every decision stays in the Rust
6
+ // Core. The protocol is packages/react-native/src/protocol.ts, and tests/mock-native.ts is
7
+ // its executable reference. Project agents expose the raw FFI stream to the TS hub.
8
+
9
+ @objc(CrocheRuntimeBridge)
10
+ public final class CrocheRuntimeBridge: NSObject, @unchecked Sendable {
11
+ /// Set by the ObjC++ module: sends one `CrocheRuntimeEvent` {handle, type, json}.
12
+ #if CROCHE_BRIDGE
13
+ /// The Swift package's bridge test only (sdk/swift/scripts/bridge-source.sh defines
14
+ /// CROCHE_BRIDGE; the podspec never does, so no app build has this): the Fixture's transport, a
15
+ /// scratch directory for stores and project records, in-memory secrets, and the attestor a device
16
+ /// would have (macOS cannot attest).
17
+ nonisolated(unsafe) static var testing: (http: RuntimeHTTP, directory: URL, secrets: @Sendable (String) -> any RuntimeSecretStore, attestor: (any RuntimeAttestor)?)?
18
+ #endif
19
+ @objc public var emit: (@Sendable (String, String, String) -> Void)?
20
+
21
+ /// Raw Core strings: the ObjC++ module only adds the routing envelope.
22
+ @objc public var emitStream: (@Sendable (String, String, String) -> Void)?
23
+ private final class Lane: @unchecked Sendable {
24
+ let calls = DispatchQueue(label: "dev.croche.rn.core", qos: .userInitiated)
25
+ let events = DispatchQueue(label: "dev.croche.rn.events")
26
+ }
27
+ private var lanes: [String: Lane] = [:]
28
+ private var streamCores: [String: CoreRuntime] = [:]
29
+ private var projects: [String: ProjectEntry] = [:]
30
+ private var agentProjects: [String: String] = [:]
31
+ private var agentIds: [String: String] = [:]
32
+ private var closedAgents: Set<String> = []
33
+ private var receiptCalls: [String: CancelToken] = [:]
34
+ private let lock = NSLock()
35
+ private var runtimes: [String: CrocheRuntime] = [:]
36
+ /// Each send call's task, by handle and call id (a retry of an input is its own call).
37
+ private var tasks: [String: Task<JSON, Error>] = [:]
38
+ /// Calls cancelled before their send registered: they start cancelled (Atlas, #278).
39
+ private var early: Set<String> = []
40
+ private var projectWaiters: [String: ProjectToolReply] = [:]
41
+ private var waiters: [String: CheckedContinuation<JSON, Error>] = [:]
42
+
43
+ private func send(_ handle: String, _ type: String, _ value: JSON) {
44
+ if lock.withLock({ streamCores[handle] != nil || closedAgents.contains(handle) }) {
45
+ lane(handle).events.async {
46
+ guard let data = try? value.encoded() else { return }
47
+ self.emit?(handle, type, String(decoding: data, as: UTF8.self))
48
+ }
49
+ } else {
50
+ // Preserve legacy Runtime emission semantics.
51
+ guard let data = try? value.encoded() else { return }
52
+ emit?(handle, type, String(decoding: data, as: UTF8.self))
53
+ }
54
+ }
55
+ private func runtime(_ handle: String) throws -> CrocheRuntime {
56
+ guard let runtime = lock.withLock({ runtimes[handle] }) else { throw CrocheError("closed", "Runtime is closed") }
57
+ return runtime
58
+ }
59
+
60
+ private func lane(_ handle: String) -> Lane {
61
+ lock.withLock {
62
+ if let lane = lanes[handle] { return lane }
63
+ let lane = Lane()
64
+ // Late callbacks hold their original queue; failed calls on closed handles do not
65
+ // repopulate the registry after close removed it.
66
+ if !closedAgents.contains(handle) { lanes[handle] = lane }
67
+ return lane
68
+ }
69
+ }
70
+ private func streamCore(_ handle: String) throws -> CoreRuntime {
71
+ guard let core = lock.withLock({ streamCores[handle] }) else { throw CrocheError("closed", "Runtime is closed") }
72
+ return core
73
+ }
74
+ private final class RawListener: EventListener, @unchecked Sendable {
75
+ let callback: @Sendable (String) -> Void
76
+ init(_ callback: @escaping @Sendable (String) -> Void) { self.callback = callback }
77
+ func onEvent(event: String) { callback(event) }
78
+ }
79
+ private func raw(_ handle: String, _ kind: String, _ json: String, readId: String? = nil, on events: DispatchQueue) {
80
+ // Reserve the callback's place before constructing its wrapper. Core JSON is verbatim.
81
+ events.async {
82
+ let body: String
83
+ if let readId {
84
+ let quoted = String(decoding: try! JSON.string(readId).encoded(), as: UTF8.self)
85
+ body = "{\"readId\":\(quoted),\"state\":\(json)}"
86
+ } else { body = json }
87
+ self.emitStream?(handle, kind, body)
88
+ }
89
+ }
90
+ // One Core call queue and one callback queue per handle. Promise completions fence behind
91
+ // every callback the blocking call enqueued; no JSON from Core is decoded or re-encoded.
92
+ private func coreCall<T: Sendable>(_ handle: String,
93
+ resolve: @escaping @Sendable (T) -> Void,
94
+ reject: @escaping @Sendable (String, String) -> Void,
95
+ _ body: @escaping @Sendable (CoreRuntime) throws -> T) {
96
+ do {
97
+ let core = try streamCore(handle), lane = lane(handle)
98
+ lane.calls.async {
99
+ do { let result = try body(core); lane.events.async { resolve(result) } }
100
+ catch { let error = CrocheError(error); lane.events.async { reject(error.code, error.message) } }
101
+ }
102
+ } catch { let error = CrocheError(error); DispatchQueue.global(qos: .userInitiated).async { reject(error.code, error.message) } }
103
+ }
104
+ // Stops bypass ordinary calls: a held send/history/sync must never hold their thread up.
105
+ private func stoppingCall(_ handle: String, resolve: @escaping @Sendable () -> Void,
106
+ reject: @escaping @Sendable (String, String) -> Void,
107
+ _ body: @escaping @Sendable (CoreRuntime) -> Void) {
108
+ do {
109
+ let core = try streamCore(handle), lane = lane(handle)
110
+ Thread.detachNewThread {
111
+ body(core)
112
+ lane.events.async { resolve() }
113
+ }
114
+ } catch { let error = CrocheError(error); DispatchQueue.global(qos: .userInitiated).async { reject(error.code, error.message) } }
115
+ }
116
+ private static let maxSafeInteger: UInt64 = 9_007_199_254_740_991
117
+ private static func number(_ value: Double) throws -> UInt64 {
118
+ guard let number = UInt64(exactly: value), number <= maxSafeInteger else {
119
+ throw CrocheError("invalid_input", "Expected a nonnegative safe integer")
120
+ }
121
+ return number
122
+ }
123
+ @objc public func observe(_ handle: String, resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
124
+ let events = lane(handle).events
125
+ coreCall(handle, resolve: { (_: Bool) in resolve() }, reject: reject) { [self] core in
126
+ try core.observe(onEvent: RawListener { [weak self] in self?.raw(handle, "observe", $0, on: events) },
127
+ onEnd: RawListener { [weak self] in
128
+ self?.lock.withLock { _ = self?.closedAgents.insert(handle) }
129
+ self?.raw(handle, "observeEnd", $0, on: events)
130
+ })
131
+ return true
132
+ }
133
+ }
134
+ @objc public func unobserve(_ handle: String) {
135
+ guard let core = try? streamCore(handle) else { return }
136
+ lane(handle).calls.async { core.unobserve() }
137
+ }
138
+ // select invokes the first callbacks before it returns its id. Reserve their positions
139
+ // in the shared event queue at invocation time, then fill in the id without reordering.
140
+ private final class ProjectionId: @unchecked Sendable {
141
+ let condition = NSCondition(); var settled = false; var value: UInt64?
142
+ func finish(_ value: UInt64?) { condition.lock(); self.value = value; settled = true; condition.broadcast(); condition.unlock() }
143
+ func get() -> UInt64? {
144
+ condition.lock(); defer { condition.unlock() }
145
+ while !settled { condition.wait() }
146
+ return value
147
+ }
148
+ }
149
+ @objc public func select(_ handle: String, selectionJson: String, resolve: @escaping @Sendable (NSNumber) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
150
+ let id = ProjectionId(), events = lane(handle).events
151
+ coreCall(handle, resolve: resolve, reject: reject) { [self] core in
152
+ do {
153
+ let projection = try core.select(selection: selectionJson, onEvent: RawListener { [weak self] json in
154
+ events.async {
155
+ guard let projection = id.get() else { return } // No accepted projection on failure.
156
+ self?.emitStream?(handle, "projection", "{\"projection\":\(projection),\"event\":\(json)}")
157
+ }
158
+ })
159
+ guard projection <= Self.maxSafeInteger else {
160
+ core.closeProjection(id: projection)
161
+ throw CrocheError("invalid_input", "Projection id exceeds the JavaScript safe integer range")
162
+ }
163
+ id.finish(projection)
164
+ return NSNumber(value: projection)
165
+ } catch { id.finish(nil); throw error }
166
+ }
167
+ }
168
+ @objc public func closeProjection(_ handle: String, projection: Double) {
169
+ guard let core = try? streamCore(handle), let id = try? Self.number(projection) else { return }
170
+ lane(handle).calls.async { core.closeProjection(id: id) }
171
+ }
172
+ @objc public func history(_ handle: String, projection: Double, before: Double, limit: Double,
173
+ resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
174
+ coreCall(handle, resolve: { (_: Bool) in resolve() }, reject: reject) { core in
175
+ let id = try Self.number(projection), seq = before == -1 ? nil : try Self.number(before)
176
+ guard let count = UInt32(exactly: limit) else { throw CrocheError("invalid_input", "Expected an integer history limit") }
177
+ try core.history(id: id, before: seq, limit: count)
178
+ return true
179
+ }
180
+ }
181
+ @objc public func readOutcome(_ handle: String, id: String, fromSeq: Double, readId: String,
182
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
183
+ let events = lane(handle).events
184
+ coreCall(handle, resolve: resolve, reject: reject) { [self] core in
185
+ try core.readOutcome(id: id, fromSeq: Self.number(fromSeq), captured: RawListener { [weak self] in self?.raw(handle, "captured", $0, readId: readId, on: events) })
186
+ }
187
+ }
188
+ @objc public func sendReceipt(_ handle: String, inputJson: String, responseFormatJson: String, callId: String,
189
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
190
+ let key = Self.sendKey(handle, callId), token = CancelToken()
191
+ lock.withLock {
192
+ if early.remove(key) != nil { token.cancel() }
193
+ receiptCalls[key] = token
194
+ }
195
+ coreCall(handle, resolve: { value in self.lock.withLock { _ = self.receiptCalls.removeValue(forKey: key) }; resolve(value) },
196
+ reject: { code, message in self.lock.withLock { _ = self.receiptCalls.removeValue(forKey: key) }; reject(code, message) }) { core in
197
+ var text = inputJson
198
+ // Every input, single or stacked, as the SDK's own send prepares it (#414): a single
199
+ // input's photo was sent at full size when only stacks were prepared here. Anything
200
+ // prepareInput cannot read passes through unchanged, for the Core to judge.
201
+ if let input = try? JSON(inputJson) {
202
+ text = String(decoding: try Images.prepareInput(input, fallback: nil).encoded(), as: UTF8.self)
203
+ }
204
+ let format = responseFormatJson.trimmingCharacters(in: .whitespacesAndNewlines) == "null" ? nil : responseFormatJson
205
+ return try core.send(input: text, cancel: token, responseFormat: format)
206
+ }
207
+ }
208
+ @objc public func cancelInput(_ handle: String, id: String,
209
+ resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
210
+ coreCall(handle, resolve: { (_: Bool) in resolve() }, reject: reject) { core in try core.cancel(id: id); return true }
211
+ }
212
+
213
+ @objc public func cancelTurn(_ handle: String, resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
214
+ stoppingCall(handle, resolve: resolve, reject: reject) { core in core.cancelTurn() }
215
+ }
216
+
217
+ private final class ProjectToolReply: @unchecked Sendable {
218
+ private let lock = NSLock()
219
+ private var result: Result<JSON, Error>?
220
+ private var waiter: CheckedContinuation<JSON, Error>?
221
+ func value() async throws -> JSON {
222
+ try await withCheckedThrowingContinuation { continuation in
223
+ let ready = lock.withLock { () -> Result<JSON, Error>? in
224
+ if let result { return result }
225
+ waiter = continuation; return nil
226
+ }
227
+ if let ready { continuation.resume(with: ready) }
228
+ }
229
+ }
230
+ func finish(_ result: Result<JSON, Error>) {
231
+ let waiter = lock.withLock { () -> CheckedContinuation<JSON, Error>? in
232
+ guard self.result == nil else { return nil }
233
+ self.result = result; defer { self.waiter = nil }; return self.waiter
234
+ }
235
+ waiter?.resume(with: result)
236
+ }
237
+ }
238
+ private final class ToolReplies: @unchecked Sendable {
239
+ private let lock = NSLock()
240
+ private var replies: [String: ProjectToolReply] = [:]
241
+ func get(_ id: String) -> ProjectToolReply? { lock.withLock { replies[id] } }
242
+ func put(_ id: String, _ reply: ProjectToolReply) { lock.withLock { replies[id] = reply } }
243
+ func remove(_ id: String) { lock.withLock { _ = replies.removeValue(forKey: id) } }
244
+ }
245
+ private final class ToolCancel: CancelCallback, @unchecked Sendable {
246
+ let callback: @Sendable () -> Void
247
+ init(_ callback: @escaping @Sendable () -> Void) { self.callback = callback }
248
+ func cancelled() { callback() }
249
+ }
250
+ // The Core calls this PAL synchronously. Only the result wait enters SwiftHost's async
251
+ // handler: tool/toolCancel reserve their place on the same emitter as Core stream events.
252
+ private final class ProjectPal: HostPal, @unchecked Sendable {
253
+ let host: SwiftHost
254
+ let replies: ToolReplies
255
+ let begin: @Sendable (JSON, CancelToken) throws -> (String, String, ProjectToolReply)
256
+ let end: @Sendable (String, ProjectToolReply) -> Void
257
+ init(_ host: SwiftHost, _ replies: ToolReplies,
258
+ begin: @escaping @Sendable (JSON, CancelToken) throws -> (String, String, ProjectToolReply),
259
+ end: @escaping @Sendable (String, ProjectToolReply) -> Void) {
260
+ self.host = host; self.replies = replies; self.begin = begin; self.end = end
261
+ }
262
+ func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput {
263
+ let (id, key, reply) = try begin(JSON(invocation), cancel)
264
+ replies.put(id, reply)
265
+ defer { replies.remove(id); end(key, reply) }
266
+ return try host.tool(invocation: invocation, cancel: cancel)
267
+ }
268
+ func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws { try host.http(request: request, sink: sink, cancel: cancel) }
269
+ func read(key: String) throws -> String? { return try host.read(key: key) }
270
+ func write(key: String, value: String) throws { try host.write(key: key, value: value) }
271
+ func readSecret(key: String) throws -> String? { return try host.readSecret(key: key) }
272
+ func writeSecret(key: String, value: String) throws { try host.writeSecret(key: key, value: value) }
273
+ func remove(key: String) throws { try host.remove(key: key) }
274
+ func removeSecret(key: String) throws { try host.removeSecret(key: key) }
275
+ func lock(key: String) throws { try host.lock(key: key) }
276
+ func unlock(key: String) { host.unlock(key: key) }
277
+ func storeIdentity() -> String { return host.storeIdentity() }
278
+ func attest(request: String, timeoutMs: UInt64) throws -> String { return try host.attest(request: request, timeoutMs: timeoutMs) }
279
+ func nowMs() -> Double { return host.nowMs() }
280
+ func utcOffsetMinutes(atMs: Double) -> Int64 { return host.utcOffsetMinutes(atMs: atMs) }
281
+ func random() -> String { return host.random() }
282
+ func wake(atMs: Double?) { host.wake(atMs: atMs) }
283
+ func schedule(entries: String) throws { try host.schedule(entries: entries) }
284
+ func archiveAppendLine(entry: String, line: String) throws { try host.archiveAppendLine(entry: entry, line: line) }
285
+ func archiveReadLines(entry: String) throws -> [String] { return try host.archiveReadLines(entry: entry) }
286
+ func archiveReplaceLines(entry: String, lines: [String]) throws { try host.archiveReplaceLines(entry: entry, lines: lines) }
287
+ func archiveRemove(entry: String) throws { try host.archiveRemove(entry: entry) }
288
+ func archiveEntries(prefix: String) throws -> [ArchiveEntry] { return try host.archiveEntries(prefix: prefix) }
289
+ func storageCapability() -> StorageCapability { return host.storageCapability() }
290
+ }
291
+ private func beginProjectTool(_ handle: String, events: DispatchQueue, call: JSON, cancel: CancelToken) throws -> (String, String, ProjectToolReply) {
292
+ let context = call["context"], id = context["callId"].string ?? "", key = "\(handle):\(id)"
293
+ let reply = ProjectToolReply()
294
+ lock.withLock { projectWaiters[key] = reply }
295
+ var invocation = call.object ?? [:]; invocation.removeValue(forKey: "context")
296
+ let body = JSON.object(["callId": .string(key), "invocation": .object(invocation), "context": context])
297
+ events.async { self.emitStream?(handle, "tool", try! Self.text(body)) }
298
+ cancel.onCancel(callback: ToolCancel { [weak self] in
299
+ events.async { self?.emitStream?(handle, "toolCancel", try! Self.text(.object(["callId": .string(key)]))) }
300
+ })
301
+ return (id, key, reply)
302
+ }
303
+ private func endProjectTool(_ key: String, reply: ProjectToolReply) {
304
+ lock.withLock { if projectWaiters[key] === reply { projectWaiters.removeValue(forKey: key) } }
305
+ }
306
+
307
+ private final class ProjectEntry: @unchecked Sendable {
308
+ let core: CoreProject
309
+ let pals: ProjectPals
310
+ init(_ core: CoreProject, _ pals: ProjectPals) { self.core = core; self.pals = pals }
311
+ }
312
+ // The pod compiles SwiftHost and the SDK into this module: no public SDK API is widened.
313
+ private final class ProjectPals: HostPalFactory, @unchecked Sendable {
314
+ private let lock = NSLock()
315
+ private var hosts: [String: SwiftHost] = [:]
316
+ private var pals: [String: ProjectPal] = [:]
317
+ private var handles: [String: (String, DispatchQueue)] = [:]
318
+ private var maintenanceHosts: [SwiftHost] = []
319
+ let directory: URL
320
+ let namespace: String
321
+ let names: [String]
322
+ let background: Bool
323
+ let timeZone: TimeZone?
324
+ let attestor: (any RuntimeAttestor)?
325
+ weak var bridge: CrocheRuntimeBridge?
326
+ init(_ bridge: CrocheRuntimeBridge, options: JSON) throws {
327
+ self.bridge = bridge
328
+ if let name = options["timeZone"].string {
329
+ guard let zone = TimeZone(identifier: name) else {
330
+ throw CrocheError("invalid_configuration", "Unknown timeZone: " + name)
331
+ }
332
+ timeZone = zone
333
+ } else { timeZone = nil }
334
+ directory = try CrocheRuntimeBridge.directory()
335
+ var identityConfig = options["host"]
336
+ identityConfig["user"] = options["user"]
337
+ namespace = try CrocheRuntime.identity(config: identityConfig)["storageKey"].string ?? "croche.runtime"
338
+ names = options["handlers"].array?.compactMap(\.string) ?? []
339
+ let runtime = options["runtime"].object == nil ? options : options["runtime"]
340
+ background = runtime["backgroundSync"] != .bool(false)
341
+ let off = options["attestation"].string == "off"
342
+ #if CROCHE_BRIDGE
343
+ if let test = CrocheRuntimeBridge.testing { attestor = off ? nil : test.attestor; return }
344
+ #endif
345
+ #if targetEnvironment(simulator)
346
+ attestor = nil
347
+ #else
348
+ attestor = off ? nil : AppAttestAttestor()
349
+ #endif
350
+ }
351
+ func route(_ agent: String, to handle: String, events: DispatchQueue) { lock.withLock { handles[agent] = (handle, events) } }
352
+ func pal(agent: String) -> HostPal { port(agent) }
353
+ private func port(_ agent: String) -> ProjectPal {
354
+ lock.withLock {
355
+ let maintenance = NativeProjectSlot.isMaintenance(agent)
356
+ if !maintenance, let pal = pals[agent] { return pal }
357
+ // Fixed-size agent namespace, including ids with multibyte characters.
358
+ let suffix = SHA256.hash(data: Data(NativeProjectSlot.storageLabel(agent).utf8)).map { String(format: "%02x", $0) }.joined()
359
+ let key = namespace + ".agent." + suffix
360
+ let replies = ToolReplies()
361
+ var tools: [String: ToolHandler] = [:]
362
+ for name in names {
363
+ tools[name] = withResult { _, context in
364
+ guard let reply = replies.get(context.callId) else { throw ToolNotDispatched() }
365
+ return try CrocheRuntimeBridge.toolResult(try await reply.value())
366
+ }
367
+ }
368
+ #if CROCHE_BRIDGE
369
+ let test = CrocheRuntimeBridge.testing
370
+ let host = SwiftHost(storage: FileRuntimeStorage(url: directory.appendingPathComponent(key + ".json")),
371
+ secrets: test?.secrets(key) ?? KeychainSecretStore(account: key), attestor: attestor,
372
+ http: test?.http, tools: tools, background: background,
373
+ projectRecords: test.map { t in ProjectRecordFiles(directory: { t.directory }) } ?? ProjectRecordFiles())
374
+ #else
375
+ let host = SwiftHost(storage: FileRuntimeStorage(url: directory.appendingPathComponent(key + ".json")),
376
+ secrets: KeychainSecretStore(account: key), attestor: attestor,
377
+ http: nil, tools: tools, background: background)
378
+ #endif
379
+ host.timeZone = timeZone
380
+ let pal = ProjectPal(host, replies, begin: { [weak self] call, cancel in
381
+ guard let self, let bridge = self.bridge,
382
+ let name = call["tool"].string, self.names.contains(name),
383
+ let (handle, events) = self.lock.withLock({ self.handles[agent] }) else {
384
+ throw FfiError.Failure(code: "tool_not_dispatched", message: "The host tool is not available")
385
+ }
386
+ return try bridge.beginProjectTool(handle, events: events, call: call, cancel: cancel)
387
+ }, end: { [weak bridge = self.bridge] key, reply in bridge?.endProjectTool(key, reply: reply) })
388
+ if maintenance { maintenanceHosts.append(host) }
389
+ else { hosts[agent] = host; pals[agent] = pal }
390
+ return pal
391
+ }
392
+ }
393
+ func attach(_ core: CoreRuntime) {
394
+ let host = port(CrocheRuntimeBridge.slot(core)).host
395
+ host.deliver = { [weak core] in
396
+ guard let core else { return }
397
+ _ = try? await CrocheRuntime.offload { try core.deliverDue() }
398
+ }
399
+ host.attach(core)
400
+ }
401
+ func stop(_ agent: String? = nil) {
402
+ let stopped = lock.withLock { () -> [SwiftHost] in
403
+ if let agent { handles.removeValue(forKey: agent); pals.removeValue(forKey: agent); return hosts.removeValue(forKey: agent).map { [$0] } ?? [] }
404
+ let all = Array(hosts.values) + maintenanceHosts; maintenanceHosts.removeAll(); hosts.removeAll(); pals.removeAll(); handles.removeAll(); return all
405
+ }
406
+ for host in stopped { host.stop(); host.session.close() }
407
+ }
408
+ }
409
+ #if CROCHE_BRIDGE
410
+ static func projectPalsForTesting(_ options: JSON) throws -> (any HostPalFactory, @Sendable () -> Void) {
411
+ let pals = try ProjectPals(CrocheRuntimeBridge(), options: options)
412
+ return (pals, { pals.stop() })
413
+ }
414
+ static func projectOffsetForTesting(_ options: JSON, atMs: Double) throws -> Int64 {
415
+ let pals = try ProjectPals(CrocheRuntimeBridge(), options: options)
416
+ defer { pals.stop() }
417
+ return pals.pal(agent: "default").utcOffsetMinutes(atMs: atMs)
418
+ }
419
+ #endif
420
+ private static func text(_ value: JSON) throws -> String { String(decoding: try value.encoded(), as: UTF8.self) }
421
+ private static func optional(_ value: String?) -> JSON { value.map(JSON.string) ?? .null }
422
+ private static func strings(_ value: [String]?) -> JSON { value.map { .array($0.map(JSON.string)) } ?? .null }
423
+ private func project(_ project: String) throws -> ProjectEntry {
424
+ guard let entry = lock.withLock({ projects[project] }) else { throw CrocheError("closed", "Project is closed") }
425
+ return entry
426
+ }
427
+ private static func info(_ core: CoreProject) throws -> String {
428
+ try text(.object(["user": optional(core.user()), "installationId": optional(core.installationId()),
429
+ "crocheUserId": optional(core.crocheUserId()), "agentIds": strings(core.agentIds()),
430
+ "applied": try JSON(core.applied())]))
431
+ }
432
+ private func projectCall<T: Sendable>(_ project: String, resolve: @escaping @Sendable (T) -> Void,
433
+ reject: @escaping @Sendable (String, String) -> Void,
434
+ _ body: @escaping @Sendable () throws -> T) {
435
+ let lane = lane(project)
436
+ lane.calls.async {
437
+ do { let result = try body(); lane.events.async { resolve(result) } }
438
+ catch { let error = CrocheError(error); lane.events.async { reject(error.code, error.message) } }
439
+ }
440
+ }
441
+ /// `Croche.deleteStore` (R8), as TypeScript: `{host, user?, config, agent?}`. The stores are the
442
+ /// ones `projectOpen` with the same host and user would use; Core locks them all first and
443
+ /// rejects `store_busy` with nothing deleted when one is open.
444
+ @objc public func projectDeleteStore(_ optionsJson: String, resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
445
+ DispatchQueue.global(qos: .userInitiated).async { [self] in
446
+ do {
447
+ var options = try JSON(optionsJson)
448
+ options["attestation"] = .string("off") // no agent registers or attests
449
+ options["runtime"] = .object(["backgroundSync": .bool(false)])
450
+ let pals = try ProjectPals(self, options: options)
451
+ defer { pals.stop() }
452
+ try deleteStore(pals: pals, host: try Self.text(options["host"]), user: options["user"].string,
453
+ config: try Self.text(options["config"]), agent: options["agent"].string)
454
+ resolve()
455
+ } catch { let error = CrocheError(error); reject(error.code, error.message) }
456
+ }
457
+ }
458
+ @objc public func projectOpen(_ project: String, optionsJson: String, resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
459
+ lock.withLock { _ = closedAgents.remove(project) }
460
+ let events = lane(project).events
461
+ projectCall(project, resolve: resolve, reject: reject) { [self] in
462
+ guard self.lock.withLock({ self.projects[project] == nil }) else { throw CrocheError("invalid_configuration", "Project handle is already open") }
463
+ let options = try JSON(optionsJson)
464
+ let pals = try ProjectPals(self, options: options)
465
+ do {
466
+ let runtime = options["runtime"].object == nil ? options : options["runtime"]
467
+ // Name the platform only when this host has an attestor, as Runtime.swift does: otherwise no
468
+ // agent asks to attest and every install registers unverified (sdk-internal #24).
469
+ var host = options["host"]
470
+ if let attestor = pals.attestor { host["attestationPlatform"] = .string(attestor.platform) }
471
+ let config = ProjectOpenOptions(host: try Self.text(host), user: options["user"].string,
472
+ config: try Self.text(options["config"]), handlers: pals.names, language: options["language"].string,
473
+ streaming: runtime["streaming"] != .bool(false), backgroundSync: pals.background,
474
+ maintenanceIntervalMs: runtime["maintenanceIntervalMs"].number ?? 60_000)
475
+ // Debug entries only when JS passed onDebugEvent (`debug: true`); what they show is the
476
+ // Core's `debugVisibility`; public builds offer only `runtime`.
477
+ let onDebug: RawListener? = options["debug"] == .bool(true)
478
+ ? RawListener { [weak self] in self?.raw(project, "debug", $0, on: events) } : nil
479
+ let core = try CoreProject.open(pals: pals, options: config, onUsage: RawListener { [weak self] in self?.raw(project, "usage", $0, on: events) }, onDebug: onDebug)
480
+ do {
481
+ let result = try Self.info(core)
482
+ self.lock.withLock { self.projects[project] = ProjectEntry(core, pals) }
483
+ return result
484
+ } catch { core.close(); throw error }
485
+ } catch {
486
+ pals.stop()
487
+ self.lock.withLock { self.closedAgents.insert(project); self.lanes.removeValue(forKey: project) }
488
+ throw error
489
+ }
490
+ }
491
+ }
492
+ // FFI getters only: no storage, network or blocking operation on the JS thread.
493
+ @objc public func projectInfo(_ project: String) throws -> String {
494
+ do { return try Self.info(self.project(project).core) }
495
+ catch {
496
+ let error = CrocheError(error)
497
+ throw NSError(domain: "dev.croche", code: 0,
498
+ userInfo: ["code": error.code, NSLocalizedDescriptionKey: error.message])
499
+ }
500
+ }
501
+ @objc public func agentState(_ handle: String) -> String {
502
+ guard let core = lock.withLock({ streamCores[handle] }) else {
503
+ return "{\"id\":\"\",\"name\":null,\"mode\":null,\"visibleTools\":null,\"closed\":true}"
504
+ }
505
+ // This object contains only strings, nulls and a boolean; its encoding cannot fail.
506
+ return try! Self.text(.object(["id": .string(core.agentId()), "name": Self.optional(core.name()),
507
+ "mode": Self.optional(core.mode()), "visibleTools": Self.strings(core.visibleTools()),
508
+ "closed": .bool(lock.withLock { closedAgents.contains(handle) })]))
509
+ }
510
+ /// The Core's name for an agent's PAL and store (`agent_slot`): its id, or `[id, instance]`.
511
+ static func slot(_ core: CoreRuntime) -> String {
512
+ guard let instance = core.instance() else { return core.agentId() }
513
+ return (try? text(.array([.string(core.agentId()), .string(instance)]))) ?? core.agentId()
514
+ }
515
+ /// `optionsJson`: `{instance?, fresh?, config?}` (#406), passed to Core as is.
516
+ @objc public func projectAgent(_ project: String, handle: String, id: String, optionsJson: String,
517
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
518
+ projectCall(project, resolve: resolve, reject: reject) {
519
+ let entry = try self.project(project)
520
+ let core = try entry.core.agentWithOptions(id: id.isEmpty ? nil : id, options: optionsJson)
521
+ let agent = Self.slot(core)
522
+ let result = try Self.text(.object(["id": .string(core.agentId()), "name": Self.optional(core.name()),
523
+ "mode": Self.optional(core.mode()), "visibleTools": Self.strings(core.visibleTools()), "logId": .string(try core.logId()),
524
+ "instance": Self.optional(core.instance()), "created": .bool(core.created())]))
525
+ self.lock.withLock { self.streamCores[handle] = core; self.agentProjects[handle] = project; self.agentIds[handle] = agent; self.closedAgents.remove(handle) }
526
+ entry.pals.route(agent, to: handle, events: self.lane(handle).events)
527
+ entry.pals.attach(core)
528
+ return result
529
+ }
530
+ }
531
+ @objc public func projectClose(_ project: String, resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
532
+ projectCall(project, resolve: { (_: Bool) in resolve() }, reject: reject) {
533
+ guard let entry = self.lock.withLock({ self.projects.removeValue(forKey: project) }) else { return true }
534
+ entry.core.close()
535
+ self.lock.withLock {
536
+ let handles = self.agentProjects.filter { $0.value == project }.map(\.key)
537
+ for handle in handles {
538
+ self.closedAgents.insert(handle)
539
+ self.streamCores.removeValue(forKey: handle); self.agentProjects.removeValue(forKey: handle)
540
+ self.agentIds.removeValue(forKey: handle); self.lanes.removeValue(forKey: handle)
541
+ self.early = self.early.filter { !$0.hasPrefix(handle + "\u{0}") }
542
+ }
543
+ self.closedAgents.insert(project)
544
+ self.lanes.removeValue(forKey: project)
545
+ }
546
+ entry.pals.stop()
547
+ return true
548
+ }
549
+ }
550
+ @objc public func agentControl(_ handle: String, op: String, argsJson: String, resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
551
+ coreCall(handle, resolve: resolve, reject: reject) { core in
552
+ let args = try JSON(argsJson)
553
+ switch op {
554
+ case "setTools":
555
+ let visible: [String]?
556
+ if args["visible"] == .null { visible = nil }
557
+ else {
558
+ guard let list = args["visible"].array, list.allSatisfy({ $0.string != nil }) else {
559
+ throw CrocheError("invalid_input", "visible must be a list of tool names or null")
560
+ }
561
+ visible = list.compactMap(\.string)
562
+ }
563
+ try core.setTools(visible: visible); return "null"
564
+ case "setMode": try core.setMode(mode: args["mode"].string); return "null"
565
+ case "sync": try core.sync(); return "null"
566
+ default: throw CrocheError("invalid_input", "Unknown agent control operation")
567
+ }
568
+ }
569
+ }
570
+
571
+ /// App-private directory for Runtime state; Keychain holds the credential.
572
+ private static func directory() throws -> URL {
573
+ #if CROCHE_BRIDGE
574
+ if let scratch = testing?.directory {
575
+ try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)
576
+ return scratch
577
+ }
578
+ #endif
579
+ let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
580
+ let url = base.appendingPathComponent("croche", isDirectory: true)
581
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
582
+ var values = URLResourceValues(); values.isExcludedFromBackup = true
583
+ var excluded = url; try? excluded.setResourceValues(values)
584
+ return url
585
+ }
586
+
587
+ @objc public func open(_ handle: String, configJson: String, optionsJson: String,
588
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
589
+ Task {
590
+ do {
591
+ var config = try JSON(configJson); let options = try JSON(optionsJson)
592
+ let tools = config["tools"].array ?? []
593
+ let handlers = self.toolHandlers(handle, tools: tools)
594
+ var key = options["storageKey"].string ?? ""
595
+ if key.isEmpty { key = try CrocheRuntime.identity(config: config)["storageKey"].string ?? "croche.runtime" }
596
+ let safe = key.replacingOccurrences(of: "[^A-Za-z0-9._-]", with: "_", options: .regularExpression)
597
+ let directory = try Self.directory()
598
+ var attestor: (any RuntimeAttestor)? = nil
599
+ if options["attestation"].string != "off" {
600
+ #if targetEnvironment(simulator)
601
+ attestor = nil // simulators cannot attest; a project with attestation off still works
602
+ #else
603
+ attestor = AppAttestAttestor()
604
+ #endif
605
+ }
606
+ config["tools"] = .array(tools)
607
+ // Typed apart: a ternary yielding an optional @Sendable closure fails to type-check (Swift 6.4).
608
+ var onUsage: (@Sendable (JSON) -> Void)? = nil
609
+ if options["usage"] == .bool(true) { onUsage = { [weak self] event in self?.send(handle, "usage", event) } }
610
+ let runtime = try await CrocheRuntime.create(
611
+ config: config,
612
+ storage: FileRuntimeStorage(url: directory.appendingPathComponent("\(safe).json")),
613
+ secrets: KeychainSecretStore(account: key),
614
+ attestor: attestor, tools: handlers,
615
+ onEvent: { [weak self] event in self?.send(handle, "event", event) },
616
+ onUsage: onUsage,
617
+ backgroundSync: options["backgroundSync"] != .bool(false),
618
+ maintenanceInterval: (options["maintenanceIntervalMs"].number ?? 60_000) / 1000,
619
+ scheduler: Self.scheduler(options["backgroundDelivery"]))
620
+ // Whoever delivered (the timer, the foreground, a background run), JavaScript hears
621
+ // of it and refreshes its cached history (rook, #323 E). The SDK's internal hook
622
+ // (this pod compiles the SDK sources into its module): interim, until the public
623
+ // subscription (F25 on #264) replaces it.
624
+ await runtime.observeDeliveries { [weak self] result in self?.send(handle, "delivered", result) }
625
+ self.lock.withLock { self.runtimes[handle] = runtime }
626
+ if let identifier = options["backgroundDelivery"]["iosTaskIdentifier"].string { BackgroundRuntimes.shared.opened(runtime, for: identifier) }
627
+ let inspection = try await runtime.inspect()
628
+ resolve(String(decoding: try inspection.encoded(), as: UTF8.self))
629
+ } catch let error as CrocheError { reject(error.code, error.message) }
630
+ catch { reject("native_error", "The native Runtime failed to open") }
631
+ }
632
+ }
633
+
634
+ private func callTool(_ handle: String, invocation: JSON, context: ToolContext) async throws -> JSON {
635
+ let callId = "\(handle):\(context.callId)"
636
+ let listener = context.cancellation.observe { [weak self] in
637
+ self?.send(handle, "toolCancel", .object(["callId": .string(callId)]))
638
+ }
639
+ defer { context.cancellation.remove(listener) }
640
+ return try await withCheckedThrowingContinuation { continuation in
641
+ lock.withLock { waiters[callId] = continuation }
642
+ send(handle, "tool", .object(["callId": .string(callId), "invocation": invocation, "context": context.data]))
643
+ }
644
+ }
645
+
646
+ /// A JavaScript tool's answer as a ToolResult. Images that are not a list fail the call
647
+ /// loudly (invalid_tool_result: that call alone), never silently dropped.
648
+ static func toolResult(_ answer: JSON) throws -> ToolResult {
649
+ let images: [JSON]
650
+ switch answer["images"] {
651
+ case .null: images = []
652
+ case .array(let list): images = list
653
+ default: throw CrocheError("invalid_tool_result", "A tool result's images are a list. Its effects may have completed.")
654
+ }
655
+ return ToolResult(value: answer["value"], images: images,
656
+ imageResolution: answer["imageResolution"].string.flatMap(ImageResolution.init(rawValue:)))
657
+ }
658
+
659
+ @objc public func resolveTool(_ callId: String, ok: Bool, resultJson: String) {
660
+ let reply = lock.withLock { projectWaiters[callId] }
661
+ let waiter = reply == nil ? lock.withLock({ waiters.removeValue(forKey: callId) }) : nil
662
+ guard reply != nil || waiter != nil else { return }
663
+ let result: Result<JSON, Error>
664
+ if ok, let value = try? JSON(resultJson) { result = .success(value) }
665
+ else if !ok, (try? JSON(resultJson))?["code"] == .string("tool_not_dispatched") { result = .failure(ToolNotDispatched()) }
666
+ else if !ok, (try? JSON(resultJson))?["code"] == .string("invalid_tool_result") {
667
+ result = .failure(CrocheError("invalid_tool_result", "The JavaScript tool returned an unreadable result. Its effects may have completed."))
668
+ } else { result = .failure(CrocheError("effect_failed", "The JavaScript tool failed")) }
669
+ if let reply { reply.finish(result) } else { waiter?.resume(with: result) }
670
+ }
671
+
672
+ @objc public func send(_ handle: String, inputJson: String, responseFormatJson: String, callId: String,
673
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
674
+ do {
675
+ let runtime = try runtime(handle); let input = try JSON(inputJson)
676
+ let format = try JSON(responseFormatJson); let responseFormat: JSON? = format == .null ? nil : format
677
+ // Sends made while a turn runs are held by the Runtime and run together next: several
678
+ // may be in flight per handle, each cancellable by its call.
679
+ let key = Self.sendKey(handle, callId)
680
+ // A cancellation remembered before registration is consumed BEFORE the send is
681
+ // admitted: a later cancel could not undo its dispatch (Atlas, #278). Registration
682
+ // happens under the same lock, so a cancelSend either finds the task or is remembered
683
+ // for this check; never neither.
684
+ let task: Task<JSON, Error>? = try lock.withLock {
685
+ if early.remove(key) != nil { return nil }
686
+ // Admitted here, on the module's serial queue, in the order JS made the calls; the
687
+ // wait then hops. A Task per send admitted them in whatever order the tasks ran
688
+ // (#264 F19.4, the RN run of 2026-10-06).
689
+ let pending = try runtime.beginSend(input, responseFormat: responseFormat)
690
+ let task = Task { try await pending.result() }
691
+ tasks[key] = task
692
+ return task
693
+ }
694
+ guard let task else { return reject("cancelled", "The operation was cancelled.") }
695
+ Task {
696
+ // Only this call's entry: call ids are unique, so no other call's task is removed.
697
+ defer { self.lock.withLock { if self.tasks[key] == task { _ = self.tasks.removeValue(forKey: key) } } }
698
+ do { resolve(String(decoding: try await task.value.encoded(), as: UTF8.self)) }
699
+ catch let error as CrocheError { reject(error.code, error.message) }
700
+ catch { reject("native_error", "The native Runtime failed") }
701
+ }
702
+ } catch let error as CrocheError { reject(error.code, error.message) }
703
+ catch { reject("invalid_input", "Input must be JSON") }
704
+ }
705
+
706
+ private static func sendKey(_ handle: String, _ callId: String) -> String { handle + "\u{0}" + callId }
707
+
708
+ /// Stops the running turn only; held sends still run, together, as the next turn.
709
+ @objc public func cancel(_ handle: String) {
710
+ guard let runtime = lock.withLock({ runtimes[handle] }) else { return }
711
+ Task { await runtime.cancel() }
712
+ }
713
+
714
+ @objc public func cancelSend(_ handle: String, callId: String) {
715
+ let key = Self.sendKey(handle, callId)
716
+ // Not registered yet: remembered under the same lock the send registers under.
717
+ let cancellation: (Task<JSON, Error>?, CancelToken?) = lock.withLock {
718
+ if let token = receiptCalls[key] { return (nil, token) }
719
+ if let task = tasks[key] { return (task, nil) }
720
+ early.insert(key); return (nil, nil)
721
+ }
722
+ cancellation.0?.cancel(); cancellation.1?.cancel()
723
+ }
724
+
725
+ @objc public func clearQueued(_ handle: String, resolve: @escaping @Sendable (NSNumber) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
726
+ Task {
727
+ do { resolve(NSNumber(value: try await self.runtime(handle).clearQueued())) }
728
+ catch let error as CrocheError { reject(error.code, error.message) }
729
+ catch { reject("native_error", "The native Runtime failed") }
730
+ }
731
+ }
732
+
733
+ @objc public func inspect(_ handle: String, resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
734
+ if lock.withLock({ streamCores[handle] != nil || closedAgents.contains(handle) }) {
735
+ coreCall(handle, resolve: resolve, reject: reject) { core in try core.inspect() }
736
+ return
737
+ }
738
+ Task {
739
+ do { resolve(String(decoding: try await self.runtime(handle).inspect().encoded(), as: UTF8.self)) }
740
+ catch let error as CrocheError { reject(error.code, error.message) }
741
+ catch { reject("native_error", "The native Runtime failed") }
742
+ }
743
+ }
744
+
745
+ /// The OS's deferred work for the agent's notes, when JavaScript asked for it.
746
+ private static func scheduler(_ delivery: JSON) -> (any RuntimeScheduler)? {
747
+ #if canImport(BackgroundTasks) && os(iOS)
748
+ if let identifier = delivery["iosTaskIdentifier"].string { return AppRefreshScheduler(identifier: identifier) }
749
+ #endif
750
+ return nil
751
+ }
752
+
753
+ /// Call from `application(_:didFinishLaunchingWithOptions:)`, before it returns, with the
754
+ /// identifier listed in Info.plist `BGTaskSchedulerPermittedIdentifiers` and passed as
755
+ /// `backgroundDelivery.iosTaskIdentifier` (default "dev.croche.schedule"). A run delivers
756
+ /// through the Runtime JavaScript opens with it; when none opens in time (JavaScript did not
757
+ /// start, or opened none), the run ends and the next foreground delivers.
758
+ @objc public static func registerBackgroundDelivery(_ identifier: String) {
759
+ #if canImport(BackgroundTasks) && os(iOS)
760
+ AppRefreshScheduler(identifier: identifier).registerHandler {
761
+ try await BackgroundRuntimes.shared.runtime(for: identifier, within: 20)
762
+ }
763
+ #endif
764
+ }
765
+
766
+ @objc public func deliverDue(_ handle: String,
767
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
768
+ Task {
769
+ do { resolve(String(decoding: try await self.runtime(handle).deliverDue().encoded(), as: UTF8.self)) }
770
+ catch let error as CrocheError { reject(error.code, error.message) }
771
+ catch { reject("native_error", "The native Runtime failed") }
772
+ }
773
+ }
774
+
775
+ @objc public func schedules(_ handle: String,
776
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
777
+ Task {
778
+ do { resolve(String(decoding: try await self.runtime(handle).schedules().encoded(), as: UTF8.self)) }
779
+ catch let error as CrocheError { reject(error.code, error.message) }
780
+ catch { reject("native_error", "The native Runtime failed") }
781
+ }
782
+ }
783
+
784
+ @objc public func maintain(_ handle: String, force: Bool,
785
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
786
+ Task {
787
+ do { resolve(String(decoding: try await self.runtime(handle).maintain(force: force).encoded(), as: UTF8.self)) }
788
+ catch let error as CrocheError { reject(error.code, error.message) }
789
+ catch { reject("native_error", "The native Runtime failed") }
790
+ }
791
+ }
792
+
793
+ @objc public func adjustBudget(_ handle: String, amount: Double, absolute: Bool, id: String,
794
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
795
+ Task {
796
+ do {
797
+ let result = try await self.runtime(handle).adjustBudget(amount, absolute: absolute, id: id.isEmpty ? nil : id)
798
+ resolve(String(decoding: try result.encoded(), as: UTF8.self))
799
+ }
800
+ catch let error as CrocheError { reject(error.code, error.message) }
801
+ catch { reject("native_error", "The native Runtime failed") }
802
+ }
803
+ }
804
+
805
+ /// One `runtime.wiki` operation; see NativeCrocheRuntime.ts `wiki` for the ops and shapes.
806
+ @objc public func wiki(_ handle: String, op: String, argsJson: String,
807
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
808
+ Task {
809
+ do {
810
+ let args = try JSON(argsJson)
811
+ func docs() throws -> [WikiDocument] {
812
+ guard let list = args["docs"].array else { throw CrocheError("invalid_wiki", "Wiki documents are [{path, markdown, agents?}].") }
813
+ return try list.map { d in
814
+ guard let path = d["path"].string, let markdown = d["markdown"].string else {
815
+ throw CrocheError("invalid_wiki", "Wiki documents are [{path, markdown, agents?}].")
816
+ }
817
+ return WikiDocument(path: path, markdown: markdown, agents: d["agents"].array?.compactMap(\.string))
818
+ }
819
+ }
820
+ func plain(_ list: [WikiDocument]) -> JSON {
821
+ .array(list.map { .object(["path": .string($0.path), "markdown": .string($0.markdown)]) })
822
+ }
823
+ let path = args["path"].string ?? ""
824
+ let out: JSON
825
+ switch op {
826
+ case "bundled": out = plain(try WikiDocument.fromBundle(folder: args["folder"].string ?? "wiki"))
827
+ case "set": out = try await self.runtime(handle).wiki.set(try docs())
828
+ case "put": try await self.runtime(handle).wiki.put(try docs()); out = .null
829
+ case "remove": out = .bool(try await self.runtime(handle).wiki.remove(path))
830
+ case "list": out = try await self.runtime(handle).wiki.list(folder: args["folder"].string)
831
+ case "read": out = try await self.runtime(handle).wiki.read(path, part: Int(args["part"].number ?? 1))
832
+ case "search": out = try await self.runtime(handle).wiki.search(args["query"].string ?? "", limit: Int(args["limit"].number ?? 5))
833
+ case "putUser": out = try await self.runtime(handle).wiki.putUser(try docs())
834
+ case "removeUser": out = answer(try await self.runtime(handle).wiki.removeUser(path)) { .bool($0) }
835
+ case "clearUser": out = answer(try await self.runtime(handle).wiki.clearUser()) { .number(Double($0)) }
836
+ default: throw CrocheError("invalid_wiki", "Unknown wiki operation \(op)")
837
+ }
838
+ resolve(String(decoding: try out.encoded(), as: UTF8.self))
839
+ }
840
+ catch let error as CrocheError { reject(error.code, error.message) }
841
+ catch { reject("native_error", "The native Runtime failed") }
842
+ }
843
+ }
844
+
845
+ /// One `runtime.memory` operation; see NativeCrocheRuntime.ts `memory` for the ops and shapes.
846
+ @objc public func memory(_ handle: String, op: String, argsJson: String,
847
+ resolve: @escaping @Sendable (String) -> Void, reject: @escaping @Sendable (String, String) -> Void) {
848
+ if lock.withLock({ streamCores[handle] != nil || closedAgents.contains(handle) }) {
849
+ // Memory bypasses the serial call queue so a busy Core can answer deferred.
850
+ Task {
851
+ do {
852
+ let core = try self.streamCore(handle), args = try JSON(argsJson)
853
+ let out: String
854
+ switch op {
855
+ case "list": out = try core.memoryList()
856
+ case "set": throw CrocheError("invalid_memory", "memory.set was removed: only the AI writes memories.")
857
+ case "delete": out = try core.memoryDelete(id: args["id"].string ?? "")
858
+ case "clear": out = try core.memoryClear()
859
+ case "enabled": out = try core.memorySetEnabled(enabled: args["on"] == .bool(true))
860
+ case "export": out = try core.memoryExport()
861
+ case "observe":
862
+ core.setMemoryObserver(observer: args["on"] == .bool(true) ? RawListener { [weak self] event in
863
+ guard let self else { return }
864
+ self.raw(handle, "memoryChanged", event, on: self.lane(handle).events)
865
+ } : nil)
866
+ out = "null"
867
+ default: throw CrocheError("invalid_memory", "Unknown memory operation \(op)")
868
+ }
869
+ self.lane(handle).events.async { resolve(out) }
870
+ } catch { let error = CrocheError(error); reject(error.code, error.message) }
871
+ }
872
+ return
873
+ }
874
+ Task {
875
+ do {
876
+ let args = try JSON(argsJson)
877
+ let memory = try self.runtime(handle).memory
878
+ let out: JSON
879
+ switch op {
880
+ case "list": out = try await memory.list()
881
+ case "set":
882
+ throw CrocheError("invalid_memory", "memory.set was removed: only the AI writes memories.")
883
+ case "delete": out = try await memory.delete(args["id"].string ?? "")
884
+ case "clear": out = try await memory.clear()
885
+ case "enabled": out = answer(try await memory.enabled(args["on"] == .bool(true))) { _ in .null }
886
+ case "export": out = try await memory.export()
887
+ case "observe":
888
+ var listener: (@Sendable (JSON) -> Void)? = nil
889
+ if args["on"] == .bool(true) { listener = { [weak self] event in self?.send(handle, "memoryChanged", event) } }
890
+ try await memory.onChanged(listener)
891
+ out = .null
892
+ default: throw CrocheError("invalid_memory", "Unknown memory operation \(op)")
893
+ }
894
+ resolve(String(decoding: try out.encoded(), as: UTF8.self))
895
+ }
896
+ catch let error as CrocheError { reject(error.code, error.message) }
897
+ catch { reject("native_error", "The native Runtime failed") }
898
+ }
899
+ }
900
+
901
+ /// Every tool runs in JavaScript: one forwarder per name, the JS side holds the handlers.
902
+ private func toolHandlers(_ handle: String, tools: [JSON]) -> [String: ToolHandler] {
903
+ var handlers: [String: ToolHandler] = [:]
904
+ for tool in tools {
905
+ guard let name = tool["name"].string else { continue }
906
+ // JavaScript answers `{value, images?, imageResolution?}`; the images go beside the
907
+ // value through the SDK's withResult, which prepares them (H3).
908
+ handlers[name] = withResult { [weak self] invocation, context in
909
+ guard let self else { throw CrocheError("closed", "Runtime is closed") }
910
+ return try Self.toolResult(try await self.callTool(handle, invocation: invocation, context: context))
911
+ }
912
+ }
913
+ return handlers
914
+ }
915
+
916
+ @objc public func setTools(_ handle: String, toolsJson: String, resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
917
+ Task {
918
+ do {
919
+ let tools = try JSON(toolsJson)
920
+ try await self.runtime(handle).setTools(tools, handlers: self.toolHandlers(handle, tools: tools.array ?? []))
921
+ resolve()
922
+ }
923
+ catch let error as CrocheError { reject(error.code, error.message) }
924
+ catch { reject("native_error", "The native Runtime failed") }
925
+ }
926
+ }
927
+
928
+ @objc public func clearHistory(_ handle: String, resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
929
+ if lock.withLock({ streamCores[handle] != nil }) {
930
+ coreCall(handle, resolve: { (_: Bool) in resolve() }, reject: reject) { core in try core.clearHistory(); return true }
931
+ return
932
+ }
933
+ // Admitted here, on the module's serial queue, in the order JS made the calls, as a send
934
+ // is; only the wait hops (#346).
935
+ let pending: PendingClear
936
+ do { pending = try runtime(handle).beginClearHistory() }
937
+ catch let error as CrocheError { return reject(error.code, error.message) }
938
+ catch { return reject("native_error", "The native Runtime failed") }
939
+ Task {
940
+ do { try await CrocheRuntime.finish(pending); resolve() }
941
+ catch let error as CrocheError { reject(error.code, error.message) }
942
+ catch { reject("native_error", "The native Runtime failed") }
943
+ }
944
+ }
945
+
946
+ @objc public func close(_ handle: String, resolve: @escaping @Sendable () -> Void, reject: @escaping @Sendable (String, String) -> Void) {
947
+ if lock.withLock({ streamCores[handle] != nil }) {
948
+ stoppingCall(handle, resolve: resolve, reject: reject) { core in
949
+ core.close()
950
+ let entry = self.lock.withLock { () -> ProjectEntry? in
951
+ let project = self.agentProjects[handle], agent = self.agentIds[handle]
952
+ for (other, parent) in self.agentProjects where parent == project && self.agentIds[other] == agent {
953
+ self.closedAgents.insert(other)
954
+ }
955
+ self.streamCores.removeValue(forKey: handle)
956
+ self.agentProjects.removeValue(forKey: handle)
957
+ self.agentIds.removeValue(forKey: handle)
958
+ self.lanes.removeValue(forKey: handle)
959
+ self.early = self.early.filter { !$0.hasPrefix(handle + "\u{0}") }
960
+ return project.flatMap { self.projects[$0] }
961
+ }
962
+ entry?.pals.stop(Self.slot(core))
963
+ }
964
+ return
965
+ }
966
+ guard let runtime = lock.withLock({ () -> CrocheRuntime? in
967
+ early = early.filter { !$0.hasPrefix(handle + "\u{0}") }
968
+ lanes.removeValue(forKey: handle)
969
+ return runtimes.removeValue(forKey: handle)
970
+ }) else { resolve(); return }
971
+ BackgroundRuntimes.shared.closed(runtime)
972
+ Task {
973
+ do { try await runtime.close(); resolve() }
974
+ catch let error as CrocheError { reject(error.code, error.message) }
975
+ catch { reject("native_error", "The native Runtime failed to close") }
976
+ }
977
+ }
978
+ }
979
+
980
+ /// A write's answer as the JS side reads it: what it did, or `{deferred: true}`.
981
+ private func answer<T>(_ result: WriteResult<T>, _ applied: (T) -> JSON) -> JSON {
982
+ switch result {
983
+ case .applied(let value): return applied(value)
984
+ case .deferred: return .object(["deferred": .bool(true)])
985
+ }
986
+ }
987
+
988
+ /// The Runtimes JavaScript opened with background delivery, by task identifier: what an iOS
989
+ /// background run delivers through. A run that starts before JavaScript has opened one waits.
990
+ /// One Runtime per identifier: a second open with an identifier in use is refused when it opens
991
+ /// (`scheduler_conflict`, from `AppRefreshScheduler.attach`), so `opened` never replaces one.
992
+ final class BackgroundRuntimes: @unchecked Sendable {
993
+ static let shared = BackgroundRuntimes()
994
+ private let lock = NSLock()
995
+ private var runtimes: [String: CrocheRuntime] = [:]
996
+
997
+ func opened(_ runtime: CrocheRuntime, for identifier: String) { lock.withLock { runtimes[identifier] = runtime } }
998
+ func closed(_ runtime: CrocheRuntime) { lock.withLock { runtimes = runtimes.filter { $0.value !== runtime } } }
999
+
1000
+ func runtime(for identifier: String, within seconds: Double) async throws -> CrocheRuntime {
1001
+ let deadline = Date().addingTimeInterval(seconds)
1002
+ while Date() < deadline {
1003
+ if let runtime = lock.withLock({ runtimes[identifier] }) { return runtime }
1004
+ try await Task.sleep(nanoseconds: 100_000_000)
1005
+ }
1006
+ throw CrocheError("closed", "No Runtime was opened for background delivery")
1007
+ }
1008
+ }