@h1r-ai/croche-react-native 0.5.0 → 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 (31) hide show
  1. package/README.md +12 -1
  2. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +6 -5
  3. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
  4. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
  5. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +8 -1
  6. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +1 -1
  7. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
  8. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
  9. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +13 -3
  10. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +14 -3
  11. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
  12. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
  13. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
  14. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
  15. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +27 -11
  16. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  17. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  18. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  19. package/ios/CrocheRuntimeBridge.swift +26 -4
  20. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +4 -1
  21. package/ios/vendor/CrocheRuntimeSDK/Host.swift +2 -1
  22. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
  23. package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
  24. package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
  25. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +57 -10
  26. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +103 -9
  27. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +22 -0
  28. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  29. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  30. package/package.json +3 -3
  31. package/src/project.ts +9 -1
@@ -0,0 +1,271 @@
1
+ import Foundation
2
+
3
+ /// Code overrides and instance admission go unchanged to Core.
4
+ public struct AgentOptions: Sendable {
5
+ public var instance: String?
6
+ public var fresh: Bool?
7
+ public var config: JSON?
8
+ public init(instance: String? = nil, fresh: Bool? = nil, config: JSON? = nil) {
9
+ self.instance = instance; self.fresh = fresh; self.config = config
10
+ }
11
+ var json: JSON {
12
+ var value: [String: JSON] = [:]
13
+ if let instance { value["instance"] = .string(instance) }
14
+ if let fresh { value["fresh"] = .bool(fresh) }
15
+ if let config { value["config"] = config }
16
+ return .object(value)
17
+ }
18
+ }
19
+
20
+ public typealias ProjectToolContext = ToolContext
21
+ public typealias ProjectUsageEvent = JSON
22
+ public typealias RuntimeDebugEvent = JSON
23
+ public typealias MemoryChangedEvent = JSON
24
+
25
+ /// The project-returned agent uses the existing Runtime's port, subscriptions and memory.
26
+ public final class CrocheAgent: Sendable {
27
+ private let core: CoreRuntime
28
+ private let runtime: CrocheRuntime
29
+ private let lifetime = ProjectAgentLifetime()
30
+ private let hub: StreamHub
31
+ public let id: String
32
+ public let instance: String?
33
+ public let created: Bool
34
+ public let logId: String
35
+ init(core: CoreRuntime, runtime: CrocheRuntime, hub: StreamHub) {
36
+ self.hub = hub
37
+ self.core = core; self.runtime = runtime
38
+ id = core.agentId(); instance = core.instance(); created = core.created(); logId = runtime.logId
39
+ }
40
+ public var name: String? { core.name() }
41
+ public var mode: String? { core.mode() }
42
+ public var visibleTools: [String]? { core.visibleTools() }
43
+ public var closed: Bool { lifetime.closed }
44
+ public var memory: CrocheMemory { runtime.memory }
45
+ private func check() throws { if closed { throw CrocheError("closed", "The agent is closed.") } }
46
+ public func setTools(_ visible: [String]?) async throws {
47
+ try check(); let core = self.core
48
+ _ = try await CrocheRuntime.offload { try core.setTools(visible: visible); return true }
49
+ }
50
+ public func setMode(_ mode: String?) async throws {
51
+ try check(); let core = self.core
52
+ _ = try await CrocheRuntime.offload { try core.setMode(mode: mode); return true }
53
+ }
54
+ public func sync() async throws { try check(); _ = try await runtime.sync() }
55
+ public func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> Receipt {
56
+ try check(); return try await runtime.send(input, options: options)
57
+ }
58
+ public func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
59
+ try check()
60
+ let result = try await runtime.request(input, options: SendOptions(responseFormat: options.responseFormat), wait: options.wait)
61
+ try? await runtime.refreshMemory()
62
+ return result
63
+ }
64
+ public func subscribe(_ options: SubscribeOptions) -> AgentSubscription { hub.subscribe(options) }
65
+ public func history(_ options: HistoryOptions) async throws {
66
+ try check(); try await runtime.history(before: options.before, limit: options.limit)
67
+ }
68
+ public func cancel(_ id: String? = nil) async throws {
69
+ try check()
70
+ if let id { try await runtime.cancel(id) }
71
+ else {
72
+ let core = self.core
73
+ _ = try await CrocheRuntime.offload { core.cancelTurn(); return true }
74
+ }
75
+ }
76
+ public func clearHistory() async throws { try check(); try await runtime.clearHistory(); try? await runtime.refreshMemory() }
77
+ public func close() async throws {
78
+ let task = lifetime.close { try await self.runtime.close() }
79
+ try await task.value
80
+ }
81
+ }
82
+
83
+ private final class ProjectAgentLifetime: @unchecked Sendable {
84
+ private let lock = NSLock()
85
+ private var closing: Task<Void, Error>?
86
+ var closed: Bool { lock.withLock { closing != nil } }
87
+ func close(_ body: @escaping @Sendable () async throws -> Void) -> Task<Void, Error> {
88
+ lock.withLock {
89
+ if let closing { return closing }
90
+ let task = Task { try await body() }; closing = task; return task
91
+ }
92
+ }
93
+ }
94
+
95
+ // Internal host construction, shared by platform-owned storage and host tests.
96
+ struct NativeProjectOptions: Sendable {
97
+ var host: JSON
98
+ var config: JSON
99
+ var user: String?
100
+ var language: String?
101
+ var handlers: [String: ToolHandler] = [:]
102
+ var streaming = true
103
+ var backgroundSync = true
104
+ var maintenanceIntervalMs = 60_000.0
105
+ var storage: @Sendable (String) -> any RuntimeStorage
106
+ var secretStorage: @Sendable (String) -> any RuntimeSecretStore
107
+ var attestor: (any RuntimeAttestor)?
108
+ var fetch: RuntimeHTTP?
109
+ var timeZone: TimeZone?
110
+ var records: @Sendable () -> ProjectRecordFiles
111
+ var onUsage: (@Sendable (JSON) -> Void)?
112
+ var onDebugEvent: (@Sendable (JSON) -> Void)?
113
+ }
114
+
115
+ final class NativeProjectPals: HostPalFactory, @unchecked Sendable {
116
+ private let lock = NSLock()
117
+ private var hosts: [String: SwiftHost] = [:]
118
+ private var all: [SwiftHost] = []
119
+ let options: NativeProjectOptions
120
+ init(_ options: NativeProjectOptions) { self.options = options }
121
+ func pal(agent: String) -> any HostPal {
122
+ let options = self.options
123
+ let slot = NativeProjectSlot.storageLabel(agent)
124
+ let handlers = options.handlers.mapValues { handler -> ToolHandler in
125
+ { invocation, context in
126
+ var data = context.data.object ?? [:]
127
+ let issued = data.removeValue(forKey: "userId")?.string
128
+ data["user"] = options.user.map(JSON.string) ?? .null
129
+ data["crocheUserId"] = issued.flatMap { $0.isEmpty ? nil : $0 }.map(JSON.string) ?? .null
130
+ do { return try await handler(invocation, ToolContext(data: .object(data), cancellation: context.cancellation, images: context.images)) }
131
+ catch { throw CrocheError("effect_failed", "The tool handler failed.") }
132
+ }
133
+ }
134
+ // A fresh host for every request: record and default-agent PALs are separate.
135
+ let host = SwiftHost(storage: options.storage(slot), secrets: options.secretStorage(slot),
136
+ attestor: options.attestor, http: options.fetch, tools: handlers,
137
+ background: options.backgroundSync, projectRecords: options.records())
138
+ host.timeZone = options.timeZone
139
+ lock.withLock { if !NativeProjectSlot.isMaintenance(agent) { hosts[agent] = host }; all.append(host) }
140
+ return host
141
+ }
142
+ func host(_ slot: String) throws -> SwiftHost {
143
+ try lock.withLock {
144
+ guard let host = hosts[slot] else { throw CrocheError("core_error", "Core opened an agent without requesting its host.") }
145
+ return host
146
+ }
147
+ }
148
+ func stop() {
149
+ let stopped = lock.withLock { () -> [SwiftHost] in
150
+ defer { all.removeAll(); hosts.removeAll() }; return all
151
+ }
152
+ for host in stopped { host.stop(); host.session.close() }
153
+ }
154
+ }
155
+
156
+ /// Core owns configuration selection, agent census, instances, locks and project identity.
157
+ public final class Croche: Sendable {
158
+ private let core: CoreProject
159
+ private let pals: NativeProjectPals
160
+ private let session: NativeProjectSession
161
+ private init(core: CoreProject, pals: NativeProjectPals) {
162
+ self.core = core; self.pals = pals; session = NativeProjectSession(core: core, pals: pals)
163
+ }
164
+ public var user: String? { core.user() }
165
+ public var installationId: String? { core.installationId() }
166
+ public var crocheUserId: String? { core.crocheUserId() }
167
+ public var agentIds: [String] { core.agentIds() }
168
+ var applied: JSON { (try? JSON(core.applied())) ?? .null }
169
+ public static func open(_ options: OpenOptions) async throws -> Croche {
170
+ let native = try await CrocheRuntime.offload { try options.native() }
171
+ return try await open(native)
172
+ }
173
+ public static func deleteStore(_ options: OpenOptions, agent: String? = nil) async throws {
174
+ let native = try await CrocheRuntime.offload { try options.native() }
175
+ try await deleteStore(native, agent: agent)
176
+ }
177
+ static func open(_ options: NativeProjectOptions) async throws -> Croche {
178
+ CrocheRuntime.warnIfReleaseBuildCarriesDebugKey(options.host)
179
+ let pals = NativeProjectPals(options)
180
+ let context = ProjectObserverContext(user: options.user)
181
+ var host = options.host
182
+ if let attestor = options.attestor { host["attestationPlatform"] = .string(attestor.platform) }
183
+ let wire = ProjectOpenOptions(host: try projectText(host), user: options.user,
184
+ config: try projectText(options.config), handlers: Array(options.handlers.keys), language: options.language,
185
+ streaming: options.streaming, backgroundSync: options.backgroundSync,
186
+ maintenanceIntervalMs: options.maintenanceIntervalMs)
187
+ do {
188
+ let core = try await CrocheRuntime.offload {
189
+ try CoreProject.open(pals: pals, options: wire, onUsage: options.onUsage.map { listener in EventHook { listener(context.usage($0)) } },
190
+ onDebug: options.onDebugEvent.map(EventHook.init))
191
+ }
192
+ context.attach(core)
193
+ return Croche(core: core, pals: pals)
194
+ } catch { pals.stop(); throw error }
195
+ }
196
+ static func deleteStore(_ options: NativeProjectOptions, agent: String? = nil) async throws {
197
+ let pals = NativeProjectPals(options); defer { pals.stop() }
198
+ let host = try projectText(options.host), config = try projectText(options.config)
199
+ _ = try await CrocheRuntime.offload {
200
+ try ffiProjectDelete(pals: pals, host: host, user: options.user, config: config, agent: agent); return true
201
+ }
202
+ }
203
+ public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
204
+ try await session.agent(id, options)
205
+ }
206
+ public func close() async throws { try await session.close() }
207
+ }
208
+
209
+ private actor NativeProjectSession {
210
+ private let core: CoreProject
211
+ private let pals: NativeProjectPals
212
+ private var agents: [String: CrocheAgent] = [:]
213
+ private var closing: Task<Void, Error>?
214
+ private var admission: Task<Void, Never>?
215
+ init(core: CoreProject, pals: NativeProjectPals) { self.core = core; self.pals = pals }
216
+ public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
217
+ guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
218
+ let previous = admission
219
+ let task = Task { await previous?.value; return try await self.openAgent(id, options: options) }
220
+ admission = Task { _ = try? await task.value }
221
+ return try await task.value
222
+ }
223
+ private func openAgent(_ id: String?, options: AgentOptions) async throws -> CrocheAgent {
224
+ guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
225
+ let core = self.core, text = try projectText(options.json)
226
+ // Cached calls still go to Core, which checks overrides and admission.
227
+ let handle = try await CrocheRuntime.offload { try core.agentWithOptions(id: id, options: text) }
228
+ guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
229
+ let slot = try handle.instance().map { try projectText(.array([.string(handle.agentId()), .string($0)])) } ?? handle.agentId()
230
+ if let existing = agents[slot], !existing.closed { return existing }
231
+ let runtime = try await CrocheRuntime.adopt(core: handle, host: pals.host(slot))
232
+ let agent = CrocheAgent(core: handle, runtime: runtime, hub: await runtime.subscriptionHub!)
233
+ if closing != nil { try await agent.close(); throw CrocheError("closed", "The project is closed.") }
234
+ agents[slot] = agent
235
+ return agent
236
+ }
237
+ public func close() async throws {
238
+ if let closing { return try await closing.value }
239
+ let core = self.core, pals = self.pals
240
+ let task = Task {
241
+ _ = try await CrocheRuntime.offload { core.close(); return true }
242
+ for agent in self.agents.values { try await agent.close() }
243
+ pals.stop()
244
+ }
245
+ closing = task
246
+ try await task.value
247
+ }
248
+ }
249
+ private func projectText(_ value: JSON) throws -> String {
250
+ let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
251
+ do { return String(decoding: try encoder.encode(value), as: UTF8.self) }
252
+ catch { throw CrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
253
+ }
254
+ private func ffiProjectDelete(pals: any HostPalFactory, host: String, user: String?, config: String, agent: String?) throws {
255
+ try deleteStore(pals: pals, host: host, user: user, config: config, agent: agent)
256
+ }
257
+
258
+ private final class ProjectObserverContext: @unchecked Sendable {
259
+ private let lock = NSLock()
260
+ private weak var core: CoreProject?
261
+ private let user: String?
262
+ init(user: String?) { self.user = user }
263
+ func attach(_ core: CoreProject) { lock.withLock { self.core = core } }
264
+ func usage(_ event: JSON) -> JSON {
265
+ let core = lock.withLock { self.core }
266
+ var value = event
267
+ value["user"] = (core?.user() ?? user).map(JSON.string) ?? .null
268
+ value["crocheUserId"] = core?.crocheUserId().map(JSON.string) ?? .null
269
+ return value
270
+ }
271
+ }
@@ -12,6 +12,10 @@ public struct ToolContext: Sendable {
12
12
  public var userId: String { data["userId"].string ?? "" }
13
13
  /// Present when the Runtime config has an agentId.
14
14
  public var agentId: String? { data["agentId"].string }
15
+ public var user: String? { data["user"].string }
16
+ public var crocheUserId: String? { data["crocheUserId"].string }
17
+ public var causedBy: [String] { data["causedBy"].array?.compactMap(\.string) ?? [] }
18
+ public var origin: String { data["origin"].string ?? "" }
15
19
  /// Where a `withResult` handler leaves its images for this call.
16
20
  let images: ImageSink?
17
21
  init(data: JSON, cancellation: RuntimeCancellation, images: ImageSink? = nil) {
@@ -56,8 +60,9 @@ public struct WikiDocument: Sendable, Equatable {
56
60
  /// Swift types; `SwiftHost` performs what only the platform can (the PAL). Pass only
57
61
  /// serializable Runtime configuration in config.
58
62
  public actor CrocheRuntime {
59
- private let core: CoreRuntime
63
+ nonisolated let core: CoreRuntime
60
64
  let host: SwiftHost
65
+ nonisolated let memoryCache = RuntimeMemoryCache()
61
66
  private var closed = false
62
67
  var subscriptionHub: StreamHub?
63
68
  public nonisolated let logId: String
@@ -137,6 +142,7 @@ public actor CrocheRuntime {
137
142
  catch { _ = try? await offload { core.close(); return true }; host.stop(); host.session.close(); throw error }
138
143
  let runtime = CrocheRuntime(core: core, host: host, logId: hub.logId)
139
144
  await runtime.bind(hub)
145
+ try await runtime.refreshMemory()
140
146
  host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
141
147
  host.attach(core)
142
148
  #if canImport(UIKit) && os(iOS)
@@ -147,8 +153,26 @@ public actor CrocheRuntime {
147
153
  }
148
154
  return runtime
149
155
  }
156
+ /// Adopts the Core returned by CoreProject; it never opens a second Runtime.
157
+ static func adopt(core: CoreRuntime, host: SwiftHost) async throws -> CrocheRuntime {
158
+ let hub: StreamHub
159
+ do { hub = try await offload { try StreamHub(port: FFIStreamPort(core: core)) } }
160
+ catch { _ = try? await offload { core.close(); return true }; host.stop(); host.session.close(); throw error }
161
+ let runtime = CrocheRuntime(core: core, host: host, logId: hub.logId)
162
+ await runtime.bind(hub)
163
+ try await runtime.refreshMemory()
164
+ host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
165
+ host.attach(core)
166
+ #if canImport(UIKit) && os(iOS)
167
+ await runtime.observeForeground()
168
+ #endif
169
+ return runtime
170
+ }
171
+
172
+ func refreshMemory() async throws { memoryCache.set(try inspect()["memory"]) }
173
+
150
174
  /// The founder's condition for debug keys: never silent in a shipped build.
151
- private static func warnIfReleaseBuildCarriesDebugKey(_ config: JSON) {
175
+ static func warnIfReleaseBuildCarriesDebugKey(_ config: JSON) {
152
176
  #if !DEBUG
153
177
  if config["debugKey"].string != nil {
154
178
  FileHandle.standardError.write(Data("[Croche] A debug key (debugKey) is set in a RELEASE build. It admits any install of this project without App Attest and must not ship.\n".utf8))
@@ -341,6 +365,7 @@ public actor CrocheRuntime {
341
365
  public func close() async throws {
342
366
  if closed { return }
343
367
  closed = true
368
+ memoryCache.close()
344
369
  subscriptionHub?.close()
345
370
  host.stop()
346
371
  #if canImport(UIKit) && os(iOS)
@@ -358,27 +383,39 @@ public actor CrocheRuntime {
358
383
  public struct CrocheMemory: Sendable {
359
384
  fileprivate let runtime: CrocheRuntime
360
385
  /// The memory part of `inspect()`.
361
- public func snapshot() async throws -> JSON { try await runtime.inspect()["memory"] }
386
+ public func callAsFunction() -> JSON { runtime.memoryCache.value }
387
+ public func snapshot() async throws -> JSON { try await runtime.refreshMemory(); return callAsFunction() }
388
+ private func refreshed(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
389
+ let result = try await runtime.run(body)
390
+ if result["deferred"].bool != true { try? await runtime.refreshMemory() }
391
+ return result
392
+ }
362
393
  /// AI-written facts with ids, turn/time stamps, refs and replacement links.
363
- public func list() async throws -> JSON { try await runtime.run { try $0.memoryList() } }
394
+ public func list() async throws -> JSON { try await refreshed { try $0.memoryList() } }
364
395
  /// `{deleted}`, or `{deferred: true}` (see `WriteResult`).
365
396
  @discardableResult
366
- public func delete(_ id: String) async throws -> JSON { try await runtime.run { try $0.memoryDelete(id: id) } }
397
+ public func delete(_ id: String) async throws -> JSON { try await refreshed { try $0.memoryDelete(id: id) } }
367
398
  /// Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
368
399
  /// `{deferred: true}` (see `WriteResult`).
369
400
  @discardableResult
370
- public func clear() async throws -> JSON { try await runtime.run { try $0.memoryClear() } }
401
+ public func clear() async throws -> JSON { try await refreshed { try $0.memoryClear() } }
371
402
  /// Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied, it
372
403
  /// carries the setting now in force.
373
404
  @discardableResult
374
405
  public func enabled(_ on: Bool) async throws -> WriteResult<Bool> {
375
- WriteResult(try await runtime.run { try $0.memorySetEnabled(enabled: on) }) { _ in on }
406
+ WriteResult(try await refreshed { try $0.memorySetEnabled(enabled: on) }) { _ in on }
376
407
  }
377
408
  /// Current and replaced AI-written facts: `{enabled, items}`, not the summary.
378
- public func export() async throws -> JSON { try await runtime.run { try $0.memoryExport() } }
409
+ public func export() async throws -> JSON { try await refreshed { try $0.memoryExport() } }
379
410
  /// Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's).
380
- public func onChanged(_ listener: (@Sendable (JSON) -> Void)?) async throws {
381
- _ = try await runtime.run { $0.setMemoryObserver(observer: listener.map { EventHook($0) }); return "null" }
411
+ public func onChanged(_ listener: (@Sendable (MemoryChangedEvent) -> Void)?) throws {
412
+ guard !runtime.memoryCache.closed else { throw CrocheError("closed", "The agent is closed.") }
413
+ do {
414
+ runtime.core.setMemoryObserver(observer: listener.map { callback in EventHook { event in
415
+ Task { try? await runtime.refreshMemory() }
416
+ callback(event)
417
+ } })
418
+ }
382
419
  }
383
420
  }
384
421
 
@@ -509,3 +546,13 @@ final class PendingTurn: Sendable {
509
546
  }
510
547
  func cancel() { token.cancel() }
511
548
  }
549
+
550
+ final class RuntimeMemoryCache: @unchecked Sendable {
551
+ private let lock = NSLock()
552
+ private var ended = false
553
+ var closed: Bool { lock.withLock { ended } }
554
+ func close() { lock.withLock { ended = true } }
555
+ private var snapshot: JSON = .object(["enabled": .bool(true), "text": .string(""), "updatedAt": .null, "compactedTurns": .number(0), "items": .array([])])
556
+ var value: JSON { lock.withLock { snapshot } }
557
+ func set(_ value: JSON) { lock.withLock { snapshot = value } }
558
+ }
@@ -67,6 +67,7 @@ private final class RequestWaiter {
67
67
  // the app only receives owned values through its independent queue.
68
68
  final class StreamHub: @unchecked Sendable {
69
69
  private let lock = NSLock()
70
+ private let selectionLock = NSRecursiveLock()
70
71
  private let port: any CoreStreamPort
71
72
  private var observation: (@Sendable () -> Void)?
72
73
  private var projection: CoreProjection?
@@ -85,8 +86,14 @@ final class StreamHub: @unchecked Sendable {
85
86
  return events(StreamSelection(initialMessages: initialMessages, after: nil))
86
87
  }
87
88
  func events(after: Cursor) -> AsyncStream<RuntimeEvent> { events(StreamSelection(initialMessages: nil, after: after)) }
88
- private func events(_ selection: StreamSelection) -> AsyncStream<RuntimeEvent> {
89
- // Subscription calls are serialized by the owning CrocheRuntime actor.
89
+ private func events(_ selection: StreamSelection) -> AsyncStream<RuntimeEvent> { attach(selection).stream }
90
+ func subscribe(_ options: SubscribeOptions) -> AgentSubscription {
91
+ let selection = StreamSelection(initialMessages: options.initialMessages ?? (options.after == nil ? 50 : nil), after: options.after)
92
+ return AgentSubscription(branch: attach(selection), handler: options.onEvent)
93
+ }
94
+ private func attach(_ selection: StreamSelection) -> AppStreamBranch {
95
+ selectionLock.lock(); defer { selectionLock.unlock() }
96
+ // Both the actor façade and synchronous subscribe use this selection fence.
90
97
  let app = AppStreamBranch()
91
98
  let old: (AppStreamBranch?, CoreProjection?, Bool) = lock.withLock {
92
99
  let old = (branch, projection, ended)
@@ -94,15 +101,20 @@ final class StreamHub: @unchecked Sendable {
94
101
  return old
95
102
  }
96
103
  old.1?.close(); old.0?.finish(.replaced)
104
+ if selection.initialMessages != nil && selection.after != nil {
105
+ app.finish(.streamError(StreamError(code: "invalid_configuration", message: "Use initialMessages or after, not both", poisoned: false)))
106
+ return app
107
+ }
97
108
  if let count = selection.initialMessages, !(0...256).contains(count) {
98
109
  app.finish(.streamError(StreamError(code: "invalid_configuration", message: "initialMessages must be in 0...256", poisoned: false)))
99
- return app.stream
110
+ return app
100
111
  }
101
- if old.2 { app.finish(.streamError(StreamError(code: "closed", message: "Runtime is closed", poisoned: false))); return app.stream }
112
+ if old.2 { app.finish(.streamError(StreamError(code: "closed", message: "Runtime is closed", poisoned: false))); return app }
102
113
  let closeProjection = port.select(selection) { [weak app] in app?.push($0) }
103
114
  app.onEnd(closeProjection.close)
115
+ app.setHistory(closeProjection.history)
104
116
  lock.withLock { projection = closeProjection }
105
- return app.stream
117
+ return app
106
118
  }
107
119
  static func errorStream(_ code: String, _ message: String) -> AsyncStream<RuntimeEvent> {
108
120
  AsyncStream { continuation in
@@ -111,6 +123,7 @@ final class StreamHub: @unchecked Sendable {
111
123
  }
112
124
  }
113
125
  func send(_ input: SendInput, options: SendOptions) async throws -> Receipt {
126
+ if Task.isCancelled { throw CrocheError("aborted", "Send cancelled before acceptance") }
114
127
  guard !lock.withLock({ ended }) else { throw CrocheError("closed", "Runtime is closed") }
115
128
  return try await port.send(try input.coreJSON(options: options), options: options)
116
129
  }
@@ -275,6 +288,21 @@ private final class AppStreamBranch: @unchecked Sendable {
275
288
  private var terminal: RuntimeEvent?
276
289
  private var consumer: CheckedContinuation<RuntimeEvent?, Never>?
277
290
  private var closeProjection: (@Sendable () -> Void)?
291
+ private var historyPage: (@Sendable (Int?, Int) async throws -> Void)?
292
+ private var immediateEnd: (@Sendable (RuntimeEvent?) -> Void)?
293
+ private var immediateReason: RuntimeEvent?
294
+ private var endedImmediately = false
295
+ func setHistory(_ history: @escaping @Sendable (Int?, Int) async throws -> Void) { lock.withLock { historyPage = history } }
296
+ func history(_ options: HistoryOptions) async throws {
297
+ guard (1...256).contains(options.limit) else { throw CrocheError("invalid_configuration", "history limit must be in 1...256") }
298
+ let page = lock.withLock { active ? historyPage : nil }
299
+ guard let page else { throw CrocheError("invalid_configuration", "No stream is attached") }
300
+ try await page(options.before, options.limit)
301
+ }
302
+ func observeImmediateEnd(_ observer: @escaping @Sendable (RuntimeEvent?) -> Void) {
303
+ let prior: (Bool, RuntimeEvent?) = lock.withLock { immediateEnd = observer; return (endedImmediately, immediateReason) }
304
+ if prior.0 { observer(prior.1) }
305
+ }
278
306
  var isActive: Bool { lock.withLock { active } }
279
307
  var stream: AsyncStream<RuntimeEvent> {
280
308
  AsyncStream(unfolding: { await self.next() }, onCancel: { self.finish(nil) })
@@ -301,16 +329,18 @@ private final class AppStreamBranch: @unchecked Sendable {
301
329
  if overflow { finish(.streamError(StreamError(code: "subscriber_overflow", message: "App event buffer exceeded", poisoned: false))) }
302
330
  }
303
331
  func finish(_ event: RuntimeEvent?, drain: Bool = false) {
304
- let close = lock.withLock {
305
- guard active else { return nil as (@Sendable () -> Void)? }
332
+ let result: ((@Sendable () -> Void)?, (@Sendable (RuntimeEvent?) -> Void)?) = lock.withLock {
333
+ guard active else { return (nil, nil) }
306
334
  active = false
307
335
  // Keel ruling 6071234795: Core errors drain; SDK-side ends drop queued values.
308
336
  if drain {} else { queue.removeAll(); bytes = 0; inFlightBytes = nil }
309
337
  terminal = event
310
338
  if let consumer { self.consumer = nil; terminal = nil; consumer.resume(returning: event) }
311
- return closeProjection
339
+ if !drain { endedImmediately = true; immediateReason = event }
340
+ return (closeProjection, drain ? nil : immediateEnd)
312
341
  }
313
- close?()
342
+ result.0?()
343
+ result.1?(event)
314
344
  }
315
345
  private func next() async -> RuntimeEvent? {
316
346
  await withCheckedContinuation { continuation in
@@ -357,3 +387,67 @@ extension RuntimeEvent {
357
387
  return json
358
388
  }
359
389
  }
390
+
391
+
392
+ /// One serialized application callback branch; requests have an independent observation.
393
+ public final class AgentSubscription: @unchecked Sendable {
394
+ private let lock = NSLock()
395
+ private let branch: AppStreamBranch
396
+ private let handler: @Sendable (RuntimeEvent) async -> Void
397
+ private var outcome: AppStreamEnd?
398
+ private var waits: [CheckedContinuation<AppStreamEnd, Never>] = []
399
+ private var silenced = false
400
+ private var consumer: Task<Void, Never>?
401
+ fileprivate init(branch: AppStreamBranch, handler: @escaping @Sendable (RuntimeEvent) async -> Void) {
402
+ self.branch = branch; self.handler = handler
403
+ branch.observeImmediateEnd { [weak self] event in self?.finish(event, notify: true) }
404
+ consumer = Task { [weak self] in
405
+ for await event in branch.stream {
406
+ guard let self else { return }
407
+ if self.lock.withLock({ self.outcome != nil }) { return }
408
+ if Self.reason(event) != nil { self.finish(event, notify: false) }
409
+ await handler(event)
410
+ }
411
+ self?.finish(nil, notify: false)
412
+ }
413
+ }
414
+ public var ended: AppStreamEnd {
415
+ get async {
416
+ await withCheckedContinuation { continuation in
417
+ lock.withLock {
418
+ if let outcome { continuation.resume(returning: outcome) }
419
+ else { waits.append(continuation) }
420
+ }
421
+ }
422
+ }
423
+ }
424
+ public func close() {
425
+ lock.withLock { silenced = true }
426
+ finish(nil, notify: false)
427
+ branch.finish(nil)
428
+ consumer?.cancel()
429
+ }
430
+ public func history(_ options: HistoryOptions) async throws { try await branch.history(options) }
431
+ private static func reason(_ event: RuntimeEvent?) -> String? {
432
+ switch event {
433
+ case .streamError(let error): return error.code
434
+ case .replaced: return "replaced"
435
+ default: return nil
436
+ }
437
+ }
438
+ private func finish(_ event: RuntimeEvent?, notify: Bool) {
439
+ let accepted = lock.withLock {
440
+ guard outcome == nil else { return false }
441
+ let result = AppStreamEnd(code: Self.reason(event) ?? "closed")
442
+ outcome = result
443
+ for continuation in waits { continuation.resume(returning: result) }
444
+ waits.removeAll(); return true
445
+ }
446
+ if accepted && notify, let event {
447
+ Task { [weak self] in
448
+ guard let self, !self.lock.withLock({ self.silenced }) else { return }
449
+ await self.handler(event)
450
+ }
451
+ }
452
+ }
453
+ }
@@ -321,3 +321,25 @@ func clampedMaintenanceInterval(_ seconds: TimeInterval) throws -> TimeInterval
321
321
  guard seconds.isFinite else { throw CrocheError("invalid_configuration", "maintenanceInterval must be finite") }
322
322
  return max(1, seconds)
323
323
  }
324
+
325
+ public struct RequestOptions: Sendable {
326
+ public var responseFormat: JSON?
327
+ public var wait: RequestWait?
328
+ public init(responseFormat: JSON? = nil, wait: RequestWait? = nil) { self.responseFormat = responseFormat; self.wait = wait }
329
+ }
330
+ public struct SubscribeOptions: Sendable {
331
+ public var initialMessages: Int?
332
+ public var after: Cursor?
333
+ public var onEvent: @Sendable (RuntimeEvent) async -> Void
334
+ public init(initialMessages: Int? = nil, after: Cursor? = nil, onEvent: @escaping @Sendable (RuntimeEvent) async -> Void) {
335
+ self.initialMessages = initialMessages; self.after = after; self.onEvent = onEvent
336
+ }
337
+ }
338
+ public struct HistoryOptions: Sendable {
339
+ public var before: Int?
340
+ public var limit: Int
341
+ public init(before: Int? = nil, limit: Int) { self.before = before; self.limit = limit }
342
+ }
343
+ public struct AppStreamEnd: Sendable, Equatable {
344
+ public let code: String
345
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@h1r-ai/croche-react-native",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -20,11 +20,11 @@
20
20
  "THIRD-PARTY-NOTICES"
21
21
  ],
22
22
  "peerDependencies": {
23
- "@h1r-ai/croche": "0.5.0",
23
+ "@h1r-ai/croche": "0.5.1",
24
24
  "react-native": ">=0.76"
25
25
  },
26
26
  "devDependencies": {
27
- "@h1r-ai/croche": "0.5.0"
27
+ "@h1r-ai/croche": "0.5.1"
28
28
  },
29
29
  "codegenConfig": {
30
30
  "name": "CrocheRuntimeSpec",
package/src/project.ts CHANGED
@@ -77,13 +77,17 @@ function pick(options: Options, keys: readonly string[]) {
77
77
  const source = options as unknown as Record<string, unknown>;
78
78
  return Object.fromEntries(keys.filter(key => source[key] !== undefined).map(key => [key, source[key]]));
79
79
  }
80
+ /** The user's language when the app gives none: the device locale, as BCP-47 (founder 10-12). */
81
+ function deviceLanguage(): string | undefined {
82
+ try { return Intl.DateTimeFormat().resolvedOptions().locale || undefined; } catch { return undefined; }
83
+ }
80
84
  function wire(options: Options) {
81
85
  return {
82
86
  host: pick(options, hostFields),
83
87
  ...(options.user === undefined ? {} : { user: options.user }),
84
88
  config: options.config,
85
89
  handlers: Object.keys(options.handlers ?? {}),
86
- ...(options.language === undefined ? {} : { language: options.language }),
90
+ ...((language => language === undefined ? {} : { language })(options.language ?? deviceLanguage())),
87
91
  runtime: pick(options, runtimeFields),
88
92
  ...pick(options, ['timeZone', 'attestation', 'android', 'backgroundDelivery']),
89
93
  };
@@ -314,6 +318,10 @@ export class Croche {
314
318
  if (['storageKey', 'identity', 'storage', 'serverKey'].some(key => Object.hasOwn(options, key))) {
315
319
  throw new CrocheError('invalid_configuration', 'storage, serverKey, storageKey and identity are not options on React Native.');
316
320
  }
321
+ // #587: refused rather than dropped until project agents have a per-agent task identifier (#581 Q9).
322
+ if (options.backgroundDelivery !== undefined && options.backgroundDelivery !== false) {
323
+ throw new CrocheError('invalid_configuration', 'backgroundDelivery is not available for project agents yet.');
324
+ }
317
325
  const handlers = { ...options.handlers };
318
326
  if (Object.values(handlers).some(handler => typeof handler !== 'function')) {
319
327
  throw new CrocheError('invalid_configuration', 'Every handler must be a function.');