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

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