@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,558 @@
1
+ import Foundation
2
+ #if canImport(UIKit) && os(iOS)
3
+ import UIKit
4
+ #endif
5
+
6
+ public struct ToolContext: Sendable {
7
+ public let data: JSON
8
+ public let cancellation: RuntimeCancellation
9
+ public var callId: String { data["callId"].string ?? "" }
10
+ public var messageId: String { data["messageId"].string ?? "" }
11
+ /// The opaque user id Croche issued; "" until Cloud has issued it.
12
+ public var userId: String { data["userId"].string ?? "" }
13
+ /// Present when the Runtime config has an agentId.
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 ?? "" }
19
+ /// Where a `withResult` handler leaves its images for this call.
20
+ let images: ImageSink?
21
+ init(data: JSON, cancellation: RuntimeCancellation, images: ImageSink? = nil) {
22
+ self.data = data; self.cancellation = cancellation; self.images = images
23
+ }
24
+ }
25
+ /// An app command's handler. An async handler must not block its thread: a blocked thread can
26
+ /// stall the Runtime's own requests. Await instead, or wrap blocking work in `blockingTool`.
27
+ public typealias ToolHandler = @Sendable (_ invocation: JSON, _ context: ToolContext) async throws -> JSON
28
+
29
+ /// A handler for work that blocks its thread (synchronous I/O, a lock, a sleep). It runs on a
30
+ /// thread of its own, never on Swift's cooperative pool, on every OS. The call keeps its slot
31
+ /// until `body` returns, however long after a cancel; observe `context.cancellation` to stop.
32
+ ///
33
+ /// tools: ["save": blockingTool { invocation, context in try database.write(invocation) }]
34
+ public func blockingTool(_ body: @escaping @Sendable (_ invocation: JSON, _ context: ToolContext) throws -> JSON) -> ToolHandler {
35
+ { invocation, context in
36
+ try await withCheckedThrowingContinuation { continuation in
37
+ let thread = Thread { continuation.resume(with: Result { try body(invocation, context) }) }
38
+ thread.name = "dev.croche.tool"
39
+ thread.start()
40
+ }
41
+ }
42
+ }
43
+
44
+ /// One wiki document: a path such as `menu/stew.md` and its markdown (at most 64 KB; 2,000
45
+ /// documents and 8 MB in all). The title is the first `#` heading; optional frontmatter may set
46
+ /// `summary`, `keywords` and `agents` (only those agents see the document); `agents` given here
47
+ /// overrides the frontmatter's. An agent's own path globs are config: `"wiki": {"include": [...],
48
+ /// "exclude": [...]}`.
49
+ public struct WikiDocument: Sendable, Equatable {
50
+ public let path: String
51
+ public let markdown: String
52
+ public let agents: [String]?
53
+ public init(path: String, markdown: String, agents: [String]? = nil) {
54
+ self.path = path; self.markdown = markdown; self.agents = agents
55
+ }
56
+ }
57
+
58
+ /// The Croche Runtime for Swift. The Rust Core (crates/croche-ffi) is the Runtime: it holds
59
+ /// the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
60
+ /// Swift types; `SwiftHost` performs what only the platform can (the PAL). Pass only
61
+ /// serializable Runtime configuration in config.
62
+ public actor CrocheRuntime {
63
+ nonisolated let core: CoreRuntime
64
+ let host: SwiftHost
65
+ nonisolated let memoryCache = RuntimeMemoryCache()
66
+ private var closed = false
67
+ var subscriptionHub: StreamHub?
68
+ public nonisolated let logId: String
69
+ #if canImport(UIKit) && os(iOS)
70
+ private var foreground: (any NSObjectProtocol)?
71
+ #endif
72
+
73
+ private var onDelivery: (@Sendable (JSON) -> Void)?
74
+ private init(core: CoreRuntime, host: SwiftHost, logId: String) { self.core = core; self.host = host; self.logId = logId }
75
+ private func bind(_ hub: StreamHub) { subscriptionHub = hub }
76
+ /// INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
77
+ /// module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
78
+ /// delivery turn (`ran: true`), whoever called it (the timer, a background run, the foreground,
79
+ /// the app), once the turn is in `inspect()`'s history. Interim: the public subscription for
80
+ /// agent-initiated messages (F25 on #264: `onBackgroundMessage` with replay on open) replaces it.
81
+ @_spi(CrocheBridge)
82
+ public func observeDeliveries(_ observer: (@Sendable (JSON) -> Void)?) { onDelivery = observer }
83
+ /// `secrets` keeps the Runtime credential apart from `storage`: KeychainSecretStore on
84
+ /// Apple platforms. `attestor` proves the genuine app to Cloud when the project requires
85
+ /// it: AppAttestAttestor on a device; nil on a simulator or a host that cannot attest.
86
+ /// `http` replaces the default URLSession transport with one that answers whole requests.
87
+ /// `wiki` is the documents, set at open; this agent's path filter is the config's
88
+ /// `"wiki": {"include": [...], "exclude": [...]}`.
89
+ /// `onEvent` hears one `turn.started` per turn; a send carried into a running turn at a later
90
+ /// model call is `{type:"turn.joined", turnId, inputIds}` (the ids newly carried).
91
+ /// `onUsage` receives every paid call's cost (`{type:"usage", operationId, purpose, causedBy, instance, model,
92
+ /// costUsd, costStatus, tokens?}`; `tokens` holds the reported counts, e.g. `prompt`, `cached`),
93
+ /// `instance` is the named/generated instance key, or null for the main agent.
94
+ /// `purpose` is "model" or "summary"; `causedBy` holds the inputs served (empty for upkeep).
95
+ /// `model` is the gateway-reported answering model (`modelSource: "response"`), or the
96
+ /// request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
97
+ /// present only when different. Reported cost is unchanged by a model substitution.
98
+ /// at least once, from the start: open itself reports a call the process
99
+ /// died during. It runs on a Runtime thread; do not call the Runtime from it.
100
+ /// `scheduler` registers the agent's scheduled notes with the OS for when the app is not
101
+ /// running: `AppRefreshScheduler` (BGTaskScheduler) on iOS; nil elsewhere, where a timer
102
+ /// delivers them while the Runtime is open and the next open delivers what fell due meanwhile.
103
+ /// On iOS the Runtime also calls `deliverDue()` each time the app enters the foreground. A
104
+ /// scheduler whose identifier another open Runtime holds refuses this one
105
+ /// (`scheduler_conflict`).
106
+ /// `projectDirectory` is required on Linux, which has no app-private default.
107
+ /// On Apple platforms it must be nil: the record stays in Application Support.
108
+ public static func create(config: JSON, storage: any RuntimeStorage, secrets: any RuntimeSecretStore,
109
+ attestor: (any RuntimeAttestor)? = nil,
110
+ tools: [String: ToolHandler] = [:],
111
+ http: RuntimeHTTP? = nil,
112
+ onEvent: (@Sendable (JSON) -> Void)? = nil,
113
+ onDebugEvent: (@Sendable (JSON) -> Void)? = nil,
114
+ onUsage: (@Sendable (JSON) -> Void)? = nil,
115
+ backgroundSync: Bool = true,
116
+ maintenanceInterval: TimeInterval = 60,
117
+ wiki: [WikiDocument]? = nil,
118
+ scheduler: (any RuntimeScheduler)? = nil,
119
+ projectDirectory: URL? = nil) async throws -> CrocheRuntime {
120
+ let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
121
+ let interval = try clampedMaintenanceInterval(maintenanceInterval)
122
+ warnIfReleaseBuildCarriesDebugKey(config)
123
+ var bound = config
124
+ bound["attestationPlatform"] = attestor.map { .string($0.platform) } ?? .null
125
+ let host = SwiftHost(storage: storage, secrets: secrets, attestor: attestor, http: http, tools: tools,
126
+ background: backgroundSync, scheduler: scheduler, projectRecords: records)
127
+ // The app chose the store, so the Runtime binds its identity to it (a custom storage key).
128
+ let options = RuntimeOpenOptions(storageKey: "croche.swift", streaming: config["streaming"].bool ?? true,
129
+ backgroundSync: backgroundSync,
130
+ maintenanceIntervalMs: interval * 1000)
131
+ let configText = String(decoding: try bound.encoded(), as: UTF8.self)
132
+ let listener = onEvent.map { EventHook($0) }
133
+ let usage = onUsage.map { EventHook($0) }
134
+ try host.attachScheduler()
135
+ // From here the host's stop (close, or a failed open) detaches the scheduler, once.
136
+ let core: CoreRuntime
137
+ do { core = try await offload { try CoreRuntime.open(pal: host, config: configText, options: options, onEvent: listener, onUsage: usage) } }
138
+ catch { host.stop(); host.session.close(); throw error }
139
+ if let onDebugEvent { try? core.setDebugObserver(observer: EventHook(onDebugEvent), full: false) }
140
+ let hub: StreamHub
141
+ do { hub = try await offload { try StreamHub(port: FFIStreamPort(core: core)) } }
142
+ catch { _ = try? await offload { core.close(); return true }; host.stop(); host.session.close(); throw error }
143
+ let runtime = CrocheRuntime(core: core, host: host, logId: hub.logId)
144
+ await runtime.bind(hub)
145
+ try await runtime.refreshMemory()
146
+ host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
147
+ host.attach(core)
148
+ #if canImport(UIKit) && os(iOS)
149
+ await runtime.observeForeground()
150
+ #endif
151
+ if let wiki {
152
+ do { try await runtime.wiki.set(wiki) } catch { try? await runtime.close(); throw error }
153
+ }
154
+ return runtime
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
+
174
+ /// The founder's condition for debug keys: never silent in a shipped build.
175
+ static func warnIfReleaseBuildCarriesDebugKey(_ config: JSON) {
176
+ #if !DEBUG
177
+ if config["debugKey"].string != nil {
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))
179
+ }
180
+ #endif
181
+ }
182
+ public static func identity(config: JSON) throws -> JSON {
183
+ do { return publicStorageIdentity(try JSON(ffiIdentity(String(decoding: try config.encoded(), as: UTF8.self)))) }
184
+ catch { throw CrocheError(error) }
185
+ }
186
+ /// The Runtime's calls block their thread while the host performs effects: run them on a
187
+ /// thread of their own, never on the cooperative pool or the main thread.
188
+ /// Croche's own tests: runs first on each offload thread, so a test can delay it the way the
189
+ /// OS may (#346). Nil in every app.
190
+ nonisolated(unsafe) static var offloadStarting: (@Sendable () -> Void)?
191
+ static func offload<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
192
+ try await withCheckedThrowingContinuation { continuation in
193
+ Thread.detachNewThread {
194
+ offloadStarting?()
195
+ do { continuation.resume(returning: try body()) }
196
+ catch { continuation.resume(throwing: CrocheError(error)) }
197
+ }
198
+ }
199
+ }
200
+ fileprivate static func offloaded<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
201
+ try await offload(body)
202
+ }
203
+ fileprivate func run(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
204
+ guard !closed else { throw CrocheError("closed", "Runtime is closed") }
205
+ let core = self.core
206
+ return try JSON(try await Self.offload { try body(core) })
207
+ }
208
+ /// Runs one turn. Cancelling the calling Task cancels this turn only (from any thread, never
209
+ /// missed): it ends `cancelled`, keeping what was said and charging an unanswered call.
210
+ /// `responseFormat`: structured output, OpenAI's shape (`{"type":"json_schema",...}` or
211
+ /// `{"type":"json_object"}`); the result's `output` is the reply as JSON the Core checked.
212
+ ///
213
+ /// Sends are admitted in the order the calls reach the Runtime (one task's sends in program
214
+ /// order): that order is their place among held sends and in a turn they share.
215
+ /// `imageResolution`: for every image that does not name its own (default standard).
216
+ public func send(_ input: JSON, responseFormat: JSON? = nil, imageResolution: ImageResolution? = nil) async throws -> JSON {
217
+ guard !closed else { throw CrocheError("closed", "Runtime is closed") }
218
+ // Admitted here, on the actor, before the hop to a thread of its own.
219
+ return try await beginSend(input, responseFormat: responseFormat, imageResolution: imageResolution).result()
220
+ }
221
+ /// Admits a send at once on the calling thread, without waiting for its turn: for a host
222
+ /// that must fix the order of sends before hopping threads (the React Native bridge).
223
+ nonisolated func beginSend(_ input: JSON, responseFormat: JSON? = nil, imageResolution: ImageResolution? = nil) throws -> PendingTurn {
224
+ // Standard images are re-encoded here, before admission, so sends keep their order.
225
+ let input = Images.prepareInput(input, fallback: imageResolution)
226
+ let text = String(decoding: try input.encoded(), as: UTF8.self)
227
+ let format = try responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
228
+ let token = CancelToken()
229
+ do { return PendingTurn(try core.beginSend(input: text, cancel: token, responseFormat: format), token) }
230
+ catch { throw CrocheError(error) }
231
+ }
232
+ public func sync() async throws -> JSON { try await run { try $0.sync(); return "null" } }
233
+ /// One round of background upkeep: deliver the outbox of call reports, then sync balances,
234
+ /// policy and the model key. The Core does work only when some is due and backs off after
235
+ /// a failure. It runs by itself after each turn and on a timer (backgroundSync); call it
236
+ /// when the app returns to the foreground. It never delays a turn: a send takes over
237
+ /// while it waits on Cloud. Never throws; the result says what happened.
238
+ @discardableResult
239
+ public func maintain(force: Bool = false) async -> JSON {
240
+ (try? await run { $0.maintain(force: force) }) ?? .object(["ran": .bool(false)])
241
+ }
242
+ /// Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
243
+ /// is (no turn, no cost) or one is already being delivered, else `{ran, ids, delivered, turn}`.
244
+ /// Never before a note's time. The iOS Runtime calls it at every foreground; elsewhere, call
245
+ /// it when the app returns.
246
+ ///
247
+ /// Cancelling the calling Task cancels this delivery only: waiting behind another turn, it
248
+ /// leaves without running; running, its turn stops. Either way its notes stay pending.
249
+ /// Cancelled after the delivery ended, nothing happens: never another turn (`cancel()` stops
250
+ /// whatever turn runs).
251
+ ///
252
+ /// Afterwards the pending set is handed to the OS scheduler again (a refusal is reported as
253
+ /// `schedule.degraded`): the OS spends a request when it runs it, and a delivery cut short
254
+ /// leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
255
+ /// ends. A failed delivery that answers `retryAt` waits until then.
256
+ @discardableResult
257
+ public func deliverDue() async throws -> JSON {
258
+ guard !closed else { throw CrocheError("closed", "Runtime is closed") }
259
+ host.attempted()
260
+ let core = self.core
261
+ let token = CancelToken()
262
+ let result: JSON
263
+ do {
264
+ result = try await withTaskCancellationHandler {
265
+ try JSON(try await Self.offload { try core.deliverDue(cancel: token) })
266
+ } onCancel: { token.cancel() }
267
+ } catch { await resync(); throw error }
268
+ if result["inFlight"].bool == true { return result }
269
+ if let retry = retryAt(result["retryAt"]) { host.retryAfter(retry) }
270
+ await resync()
271
+ if result["ran"].bool == true { onDelivery?(result) }
272
+ return result
273
+ }
274
+ /// Hands the pending set to the OS scheduler again, through the Core, which reports a refusal
275
+ /// as `schedule.degraded`.
276
+ private func resync() async {
277
+ guard !closed else { return }
278
+ let core = self.core
279
+ _ = try? await Self.offload { try core.reschedule(); return true }
280
+ }
281
+ #if canImport(UIKit) && os(iOS)
282
+ private func observeForeground() {
283
+ foreground = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification,
284
+ object: nil, queue: nil) { [weak self] _ in
285
+ Task { _ = try? await self?.deliverDue() }
286
+ }
287
+ }
288
+ #endif
289
+ /// The agent's pending scheduled notes: `{pending: [{id, at, note}], due}`.
290
+ public func schedules() async throws -> JSON { try await run { try $0.schedules() } }
291
+ public func flush() async throws -> JSON { try await run { try $0.flush(); return "null" } }
292
+ /// Forgets this user's conversation and memory and starts over (money and identity stay).
293
+ /// The clear takes its place on the actor, as `send` does: behind a running turn, ahead of
294
+ /// every send that reaches the Runtime after it. Only the wait for it is on a thread of its own.
295
+ public func clearHistory() async throws {
296
+ guard !closed else { throw CrocheError("closed", "Runtime is closed") }
297
+ if let subscriptionHub { try await subscriptionHub.clearHistory(); return }
298
+ try await Self.finish(beginClearHistory())
299
+ }
300
+ /// Admits a clear at once on the calling thread, for a host that must fix its order against
301
+ /// sends before hopping threads (the React Native bridge); `finish` then waits for it.
302
+ nonisolated func beginClearHistory() -> PendingClear { core.beginClearHistory() }
303
+ /// Waits for an admitted clear on a thread of its own.
304
+ static func finish(_ pending: PendingClear) async throws {
305
+ _ = try await offload { try pending.finish(); return true }
306
+ }
307
+ /// Asks Cloud to raise (or, `absolute`, set) this user's allowance within the project's
308
+ /// ceilings. Pass `id` (e.g. the purchase id) to make a retry safe: Cloud applies it once.
309
+ /// Called while another operation runs, it answers `{deferred: true}` at once instead (see
310
+ /// `WriteResult`).
311
+ public func adjustBudget(_ amount: Double, absolute: Bool = false, id: String? = nil) async throws -> JSON {
312
+ try await run { try $0.adjustBudget(amount: amount, absolute: absolute, id: id) }
313
+ }
314
+ /// Internal until `memory history` (B3): turns `from...to` from the turn archive, as
315
+ /// `{"records":[...]}`; `archive_unavailable` when the storage keeps none.
316
+ func archiveRead(from: UInt64, to: UInt64) async throws -> JSON {
317
+ try await run { try $0.archiveRead(from: from, to: to) }
318
+ }
319
+ /// Internal: deletes archived turns, every one without a range.
320
+ func archiveClear(from: UInt64? = nil, to: UInt64? = nil) async throws {
321
+ _ = try await run { try $0.archiveClear(from: from, to: to); return "null" }
322
+ }
323
+ public func inspect() throws -> JSON {
324
+ guard !closed else { throw CrocheError("closed", "Runtime is closed") }
325
+ do { return try JSON(try core.inspect()) } catch { throw CrocheError(error) }
326
+ }
327
+ /// Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
328
+ /// The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
329
+ /// its place in the queue, so turns sent before it still offer the old list. A removed or
330
+ /// changed command answers `withdrawn` once the swap applies. A handler given here also
331
+ /// serves turns already queued under the same name.
332
+ public func setTools(_ tools: JSON, handlers: [String: ToolHandler]) throws {
333
+ guard !closed else { throw CrocheError("closed", "Runtime is closed") }
334
+ let text = String(decoding: try tools.encoded(), as: UTF8.self)
335
+ // New names first: the Core cannot call them before it accepts the list. Replacements
336
+ // only after it accepts; a refusal removes what it staged, so every handler is as it was.
337
+ let stamp = host.stageTools(handlers)
338
+ do { try core.setToolDeclarations(tools: text) } catch { host.unstageTools(handlers.keys, stamp: stamp); throw CrocheError(error) }
339
+ host.acceptTools(handlers)
340
+ }
341
+ /// The tool list the model is offered (metadata only).
342
+ public func tools() throws -> JSON { try inspect()["tools"] }
343
+ /// Stops the running turn only: messages sent while it ran still go, together, as the next
344
+ /// turn. Cancelling a send's Task drops just that send while it is held; once its turn has
345
+ /// started, the turn stops, for every send it carries.
346
+ public func cancel() { core.cancelTurn() }
347
+ /// Drops the messages held behind the running turn (each send ends `cancelled`); returns how many.
348
+ /// Resolves once the held record no longer lists them.
349
+ @discardableResult public func clearQueued() async throws -> Int {
350
+ guard !closed else { return 0 }
351
+ let core = self.core
352
+ return Int(try await Self.offload { try core.clearQueued() })
353
+ }
354
+ /// Long-term memory: `snapshot()` for a read-only view, the other methods to manage it.
355
+ public nonisolated var memory: CrocheMemory { CrocheMemory(runtime: self) }
356
+ /// The app's knowledge documents, held by the Rust Core in memory (never stored: load them
357
+ /// on each open). The model searches and reads them with the built-in `wiki` command;
358
+ /// `list`, `read` and `search` here are that same view.
359
+ public nonisolated var wiki: CrocheWiki { CrocheWiki(runtime: self) }
360
+ /// Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
361
+ /// call upkeep has in flight is finished and settled first.
362
+ /// The Core projection fence does not await buffered AsyncStream/UI consumers.
363
+ /// An app callback that waits for work on the closer's thread deadlocks under any
364
+ /// wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself.
365
+ public func close() async throws {
366
+ if closed { return }
367
+ closed = true
368
+ memoryCache.close()
369
+ subscriptionHub?.close()
370
+ host.stop()
371
+ #if canImport(UIKit) && os(iOS)
372
+ if let foreground { NotificationCenter.default.removeObserver(foreground) }
373
+ foreground = nil
374
+ #endif
375
+ let core = self.core
376
+ _ = try await Self.offload { core.close(); return true }
377
+ // After the Core: a paid call upkeep has in flight is finished first.
378
+ host.session.close()
379
+ }
380
+ }
381
+
382
+ /// `runtime.memory`: this person's long-term memory, as the TS SDK's `runtime.memory`.
383
+ public struct CrocheMemory: Sendable {
384
+ fileprivate let runtime: CrocheRuntime
385
+ /// The memory part of `inspect()`.
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
+ }
393
+ /// AI-written facts with ids, turn/time stamps, refs and replacement links.
394
+ public func list() async throws -> JSON { try await refreshed { try $0.memoryList() } }
395
+ /// `{deleted}`, or `{deferred: true}` (see `WriteResult`).
396
+ @discardableResult
397
+ public func delete(_ id: String) async throws -> JSON { try await refreshed { try $0.memoryDelete(id: id) } }
398
+ /// Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
399
+ /// `{deferred: true}` (see `WriteResult`).
400
+ @discardableResult
401
+ public func clear() async throws -> JSON { try await refreshed { try $0.memoryClear() } }
402
+ /// Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied, it
403
+ /// carries the setting now in force.
404
+ @discardableResult
405
+ public func enabled(_ on: Bool) async throws -> WriteResult<Bool> {
406
+ WriteResult(try await refreshed { try $0.memorySetEnabled(enabled: on) }) { _ in on }
407
+ }
408
+ /// Current and replaced AI-written facts: `{enabled, items}`, not the summary.
409
+ public func export() async throws -> JSON { try await refreshed { try $0.memoryExport() } }
410
+ /// Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's).
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
+ }
419
+ }
420
+ }
421
+
422
+ extension WikiDocument {
423
+ /// The `.md` files under `directory` as wiki documents, paths relative to it with `/`
424
+ /// (`menu/stew.md`), in name order. Subfolders are read; symbolic links and other files are
425
+ /// skipped, as the other SDKs' loaders do.
426
+ public static func fromDirectory(_ directory: URL) throws -> [WikiDocument] {
427
+ let files = FileManager.default
428
+ var out: [WikiDocument] = []
429
+ func walk(_ dir: URL, _ prefix: String) throws {
430
+ let names: [String]
431
+ do { names = try files.contentsOfDirectory(atPath: dir.path).sorted() }
432
+ catch { throw CrocheError("invalid_wiki", "\(dir.path): \(error.localizedDescription)") }
433
+ for name in names {
434
+ let url = dir.appendingPathComponent(name)
435
+ let path = prefix.isEmpty ? name : prefix + "/" + name
436
+ // attributesOfItem does not follow a link, so a link is neither a folder nor a file.
437
+ let type = (try? files.attributesOfItem(atPath: url.path))?[.type] as? FileAttributeType
438
+ if type == .typeDirectory {
439
+ try walk(url, path)
440
+ } else if type == .typeRegular && name.hasSuffix(".md") {
441
+ if out.count >= 2000 { throw CrocheError("invalid_wiki", "The wiki holds at most 2000 documents") }
442
+ out.append(WikiDocument(path: path, markdown: String(decoding: try Data(contentsOf: url), as: UTF8.self)))
443
+ }
444
+ }
445
+ }
446
+ try walk(directory, "")
447
+ return out
448
+ }
449
+ /// The documents in a folder shipped with the app (added to the target as a folder
450
+ /// reference, so its subfolders survive): `WikiDocument.fromBundle()` reads `wiki/`.
451
+ public static func fromBundle(_ bundle: Bundle = .main, folder: String = "wiki") throws -> [WikiDocument] {
452
+ guard let url = bundle.url(forResource: folder, withExtension: nil) else {
453
+ throw CrocheError("invalid_wiki", "No folder \(folder) in the bundle: add it to the target as a folder reference.")
454
+ }
455
+ return try fromDirectory(url)
456
+ }
457
+ }
458
+
459
+ /// `runtime.wiki`: the app's documents, as the TS SDK's `runtime.wiki`.
460
+ public struct CrocheWiki: Sendable {
461
+ fileprivate let runtime: CrocheRuntime
462
+ private static func json(_ docs: [WikiDocument]) throws -> String {
463
+ let value = JSON.array(docs.map { doc in
464
+ var o: [String: JSON] = ["path": .string(doc.path), "markdown": .string(doc.markdown)]
465
+ if let agents = doc.agents { o["agents"] = .array(agents.map { .string($0) }) }
466
+ return .object(o)
467
+ })
468
+ return String(decoding: try value.encoded(), as: UTF8.self)
469
+ }
470
+ /// Replaces every document and answers what it installed: `{documents, bytes, digest}`.
471
+ /// On an error nothing changes.
472
+ @discardableResult
473
+ public func set(_ docs: [WikiDocument]) async throws -> JSON {
474
+ let text = try Self.json(docs)
475
+ return try await runtime.run { try $0.wikiSet(docs: text) }
476
+ }
477
+ /// `set`, without the digest.
478
+ public func load(_ docs: [WikiDocument]) async throws { try await set(docs) }
479
+ /// This user's own documents (saved recipes, lesson notes): stored with their state (at most
480
+ /// 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable when
481
+ /// this returns. `clearHistory` keeps them. To share one with another character, put it to that character's Runtime too.
482
+ /// Answers `{documents, bytes}`, or `{deferred: true}` (see `WriteResult`).
483
+ @discardableResult
484
+ public func putUser(_ docs: [WikiDocument]) async throws -> JSON {
485
+ let text = try Self.json(docs)
486
+ return try await runtime.run { try $0.wikiPutUser(docs: text) }
487
+ }
488
+ /// Removes one of this user's own documents; whether it existed.
489
+ @discardableResult
490
+ public func removeUser(_ path: String) async throws -> WriteResult<Bool> {
491
+ WriteResult(try await runtime.run { try $0.wikiRemoveUser(path: path) }) { $0["removed"].bool ?? false }
492
+ }
493
+ /// Removes every one of this user's own documents; how many.
494
+ @discardableResult
495
+ public func clearUser() async throws -> WriteResult<Int> {
496
+ WriteResult(try await runtime.run { try $0.wikiClearUser() }) { Int($0["cleared"].number ?? 0) }
497
+ }
498
+ /// Adds documents or replaces those with the same path, atomically.
499
+ public func put(_ docs: [WikiDocument]) async throws {
500
+ let text = try Self.json(docs)
501
+ _ = try await runtime.run { try $0.wikiPut(docs: text); return "null" }
502
+ }
503
+ /// Whether the document existed.
504
+ @discardableResult
505
+ public func remove(_ path: String) async throws -> Bool {
506
+ try await runtime.run { try $0.wikiRemove(path: path) ? "true" : "false" }.bool ?? false
507
+ }
508
+ /// `[{path, title, summary?, characters, parts}]` under `folder` (every document when nil).
509
+ public func list(folder: String? = nil) async throws -> JSON { try await runtime.run { try $0.wikiList(folder: folder) } }
510
+ /// One part (1-based) of a document, `{path, title, part, parts, text}`; `.null` when none.
511
+ public func read(_ path: String, part: Int = 1) async throws -> JSON {
512
+ try await runtime.run { try $0.wikiRead(path: path, part: UInt32(clamping: max(0, part))) }
513
+ }
514
+ /// The best matches, best first: at most `limit` (and 5).
515
+ public func search(_ query: String, limit: Int = 5) async throws -> JSON {
516
+ try await runtime.run { try $0.wikiSearch(query: query, limit: UInt32(clamping: min(max(0, limit), 5))) }
517
+ }
518
+ }
519
+
520
+ /// What a write (memory, this user's own documents, the allowance) answers: `.applied`, with what
521
+ /// it did, or `.deferred`: it was called while another operation ran, was accepted, and applies in
522
+ /// call order when that operation ends. A message sent after the write sees it; one sent before
523
+ /// does not. It is held in this process until then: closing first drops it, and a write that
524
+ /// cannot apply then is reported as a `write.failed` debug event.
525
+ public enum WriteResult<Value: Sendable>: Sendable {
526
+ case applied(Value)
527
+ case deferred
528
+
529
+ init(_ answer: JSON, _ applied: (JSON) -> Value) {
530
+ self = answer["deferred"].bool == true ? .deferred : .applied(applied(answer))
531
+ }
532
+ }
533
+ extension WriteResult: Equatable where Value: Equatable {}
534
+
535
+ /// A send `beginSend` admitted. Its result, once: `result()` blocks a thread of its own, and
536
+ /// cancelling the awaiting Task cancels this send only.
537
+ final class PendingTurn: Sendable {
538
+ private let pending: PendingSend
539
+ private let token: CancelToken
540
+ fileprivate init(_ pending: PendingSend, _ token: CancelToken) { self.pending = pending; self.token = token }
541
+ func result() async throws -> JSON {
542
+ let pending = self.pending
543
+ return try await withTaskCancellationHandler {
544
+ try JSON(try await CrocheRuntime.offloaded { try pending.wait() })
545
+ } onCancel: { [token] in token.cancel() }
546
+ }
547
+ func cancel() { token.cancel() }
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
+ }