@h1r-ai/croche-react-native 0.5.4 → 0.6.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 (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -3,19 +3,19 @@ import Foundation
3
3
  import UIKit
4
4
  #endif
5
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 ?? "" }
6
+ struct LegacyToolContext: Sendable {
7
+ let data: JSON
8
+ let cancellation: RuntimeCancellation
9
+ var callId: String { data["callId"].string ?? "" }
10
+ var messageId: String { data["messageId"].string ?? "" }
11
11
  /// The opaque user id Croche issued; "" until Cloud has issued it.
12
- public var userId: String { data["userId"].string ?? "" }
12
+ var userId: String { data["userId"].string ?? "" }
13
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 ?? "" }
14
+ var agentId: String? { data["agentId"].string }
15
+ var user: String? { data["user"].string }
16
+ var crocheUserId: String? { data["crocheUserId"].string }
17
+ var causedBy: [String] { data["causedBy"].array?.compactMap(\.string) ?? [] }
18
+ var origin: String { data["origin"].string ?? "" }
19
19
  /// Where a `withResult` handler leaves its images for this call.
20
20
  let images: ImageSink?
21
21
  init(data: JSON, cancellation: RuntimeCancellation, images: ImageSink? = nil) {
@@ -24,14 +24,14 @@ public struct ToolContext: Sendable {
24
24
  }
25
25
  /// An app command's handler. An async handler must not block its thread: a blocked thread can
26
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
27
+ typealias ToolHandler = @Sendable (_ invocation: JSON, _ context: LegacyToolContext) async throws -> JSON
28
28
 
29
29
  /// A handler for work that blocks its thread (synchronous I/O, a lock, a sleep). It runs on a
30
30
  /// thread of its own, never on Swift's cooperative pool, on every OS. The call keeps its slot
31
31
  /// until `body` returns, however long after a cancel; observe `context.cancellation` to stop.
32
32
  ///
33
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 {
34
+ func blockingTool(_ body: @escaping @Sendable (_ invocation: JSON, _ context: LegacyToolContext) throws -> JSON) -> ToolHandler {
35
35
  { invocation, context in
36
36
  try await withCheckedThrowingContinuation { continuation in
37
37
  let thread = Thread { continuation.resume(with: Result { try body(invocation, context) }) }
@@ -46,11 +46,11 @@ public func blockingTool(_ body: @escaping @Sendable (_ invocation: JSON, _ cont
46
46
  /// `summary`, `keywords` and `agents` (only those agents see the document); `agents` given here
47
47
  /// overrides the frontmatter's. An agent's own path globs are config: `"wiki": {"include": [...],
48
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) {
49
+ struct WikiDocument: Sendable, Equatable {
50
+ let path: String
51
+ let markdown: String
52
+ let agents: [String]?
53
+ init(path: String, markdown: String, agents: [String]? = nil) {
54
54
  self.path = path; self.markdown = markdown; self.agents = agents
55
55
  }
56
56
  }
@@ -59,13 +59,13 @@ public struct WikiDocument: Sendable, Equatable {
59
59
  /// the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
60
60
  /// Swift types; `SwiftHost` performs what only the platform can (the PAL). Pass only
61
61
  /// serializable Runtime configuration in config.
62
- public actor CrocheRuntime {
62
+ actor AgentEngine {
63
63
  nonisolated let core: CoreRuntime
64
64
  let host: SwiftHost
65
65
  nonisolated let memoryCache = RuntimeMemoryCache()
66
66
  private var closed = false
67
67
  var subscriptionHub: StreamHub?
68
- public nonisolated let logId: String
68
+ nonisolated let logId: String
69
69
  #if canImport(UIKit) && os(iOS)
70
70
  private var foreground: (any NSObjectProtocol)?
71
71
  #endif
@@ -76,10 +76,9 @@ public actor CrocheRuntime {
76
76
  /// INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
77
77
  /// module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
78
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
79
+ /// the app), once the turn is in `inspect()`'s history. Interim: the subscription for
80
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 }
81
+ func observeDeliveries(_ observer: (@Sendable (JSON) -> Void)?) { onDelivery = observer }
83
82
  /// `secrets` keeps the Runtime credential apart from `storage`: KeychainSecretStore on
84
83
  /// Apple platforms. `attestor` proves the genuine app to Cloud when the project requires
85
84
  /// it: AppAttestAttestor on a device; nil on a simulator or a host that cannot attest.
@@ -95,6 +94,8 @@ public actor CrocheRuntime {
95
94
  /// `model` is the gateway-reported answering model (`modelSource: "response"`), or the
96
95
  /// request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
97
96
  /// present only when different. Reported cost is unchanged by a model substitution.
97
+ /// `routedFor: "images"` and `routedFrom` mark a call whose images the app's (else the
98
+ /// project's) model does not accept, sent to an image-capable project model instead.
98
99
  /// at least once, from the start: open itself reports a call the process
99
100
  /// died during. It runs on a Runtime thread; do not call the Runtime from it.
100
101
  /// `scheduler` registers the agent's scheduled notes with the OS for when the app is not
@@ -105,7 +106,7 @@ public actor CrocheRuntime {
105
106
  /// (`scheduler_conflict`).
106
107
  /// `projectDirectory` is required on Linux, which has no app-private default.
107
108
  /// 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
+ static func create(config: JSON, storage: any RuntimeStorage, secrets: any RuntimeSecretStore,
109
110
  attestor: (any RuntimeAttestor)? = nil,
110
111
  tools: [String: ToolHandler] = [:],
111
112
  http: RuntimeHTTP? = nil,
@@ -116,7 +117,7 @@ public actor CrocheRuntime {
116
117
  maintenanceInterval: TimeInterval = 60,
117
118
  wiki: [WikiDocument]? = nil,
118
119
  scheduler: (any RuntimeScheduler)? = nil,
119
- projectDirectory: URL? = nil) async throws -> CrocheRuntime {
120
+ projectDirectory: URL? = nil) async throws -> AgentEngine {
120
121
  let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
121
122
  let interval = try clampedMaintenanceInterval(maintenanceInterval)
122
123
  warnIfReleaseBuildCarriesDebugKey(config)
@@ -134,13 +135,13 @@ public actor CrocheRuntime {
134
135
  try host.attachScheduler()
135
136
  // From here the host's stop (close, or a failed open) detaches the scheduler, once.
136
137
  let core: CoreRuntime
137
- do { core = try await offload { try CoreRuntime.open(pal: host, config: configText, options: options, onEvent: listener, onUsage: usage) } }
138
+ do { core = try await Offload.run { try CoreRuntime.open(pal: host, config: configText, options: options, onEvent: listener, onUsage: usage) } }
138
139
  catch { host.stop(); host.session.close(); throw error }
139
140
  if let onDebugEvent { try? core.setDebugObserver(observer: EventHook(onDebugEvent), full: false) }
140
141
  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)
142
+ do { hub = try await Offload.run { try StreamHub(port: FFIStreamPort(core: core, images: host.images)) } }
143
+ catch { _ = try? await Offload.run { core.close(); return true }; host.stop(); host.session.close(); throw error }
144
+ let runtime = AgentEngine(core: core, host: host, logId: hub.logId)
144
145
  await runtime.bind(hub)
145
146
  try await runtime.refreshMemory()
146
147
  host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
@@ -154,11 +155,11 @@ public actor CrocheRuntime {
154
155
  return runtime
155
156
  }
156
157
  /// Adopts the Core returned by CoreProject; it never opens a second Runtime.
157
- static func adopt(core: CoreRuntime, host: SwiftHost) async throws -> CrocheRuntime {
158
+ static func adopt(core: CoreRuntime, host: SwiftHost) async throws -> AgentEngine {
158
159
  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)
160
+ do { hub = try await Offload.run { try StreamHub(port: FFIStreamPort(core: core, images: host.images)) } }
161
+ catch { _ = try? await Offload.run { core.close(); return true }; host.stop(); host.session.close(); throw error }
162
+ let runtime = AgentEngine(core: core, host: host, logId: hub.logId)
162
163
  await runtime.bind(hub)
163
164
  try await runtime.refreshMemory()
164
165
  host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
@@ -179,31 +180,10 @@ public actor CrocheRuntime {
179
180
  }
180
181
  #endif
181
182
  }
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
183
  fileprivate func run(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
204
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
184
+ guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
205
185
  let core = self.core
206
- return try JSON(try await Self.offload { try body(core) })
186
+ return try JSON(try await Offload.run { try body(core) })
207
187
  }
208
188
  /// Runs one turn. Cancelling the calling Task cancels this turn only (from any thread, never
209
189
  /// missed): it ends `cancelled`, keeping what was said and charging an unanswered call.
@@ -213,8 +193,8 @@ public actor CrocheRuntime {
213
193
  /// Sends are admitted in the order the calls reach the Runtime (one task's sends in program
214
194
  /// order): that order is their place among held sends and in a turn they share.
215
195
  /// `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") }
196
+ func send(_ input: JSON, responseFormat: JSON? = nil, imageResolution: ImageResolution? = nil) async throws -> JSON {
197
+ guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
218
198
  // Admitted here, on the actor, before the hop to a thread of its own.
219
199
  return try await beginSend(input, responseFormat: responseFormat, imageResolution: imageResolution).result()
220
200
  }
@@ -227,16 +207,17 @@ public actor CrocheRuntime {
227
207
  let format = try responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
228
208
  let token = CancelToken()
229
209
  do { return PendingTurn(try core.beginSend(input: text, cancel: token, responseFormat: format), token) }
230
- catch { throw CrocheError(error) }
210
+ catch { throw LegacyCrocheError(error) }
231
211
  }
232
- public func sync() async throws -> JSON { try await run { try $0.sync(); return "null" } }
212
+ func sync() async throws -> JSON { try await run { try $0.sync(); return "null" } }
233
213
  /// One round of background upkeep: deliver the outbox of call reports, then sync balances,
234
214
  /// 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
215
+ /// a failure. Timer upkeep follows backgroundSync; call it when the app returns to the foreground.
216
+ /// Separately, Core delivers pending reports when the agent goes idle and after open,
217
+ /// even with backgroundSync off. That delivery never folds or syncs. It never delays a turn: a send takes over
237
218
  /// while it waits on Cloud. Never throws; the result says what happened.
238
219
  @discardableResult
239
- public func maintain(force: Bool = false) async -> JSON {
220
+ func maintain(force: Bool = false) async -> JSON {
240
221
  (try? await run { $0.maintain(force: force) }) ?? .object(["ran": .bool(false)])
241
222
  }
242
223
  /// Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
@@ -254,15 +235,15 @@ public actor CrocheRuntime {
254
235
  /// leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
255
236
  /// ends. A failed delivery that answers `retryAt` waits until then.
256
237
  @discardableResult
257
- public func deliverDue() async throws -> JSON {
258
- guard !closed else { throw CrocheError("closed", "Runtime is closed") }
238
+ func deliverDue() async throws -> JSON {
239
+ guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
259
240
  host.attempted()
260
241
  let core = self.core
261
242
  let token = CancelToken()
262
243
  let result: JSON
263
244
  do {
264
245
  result = try await withTaskCancellationHandler {
265
- try JSON(try await Self.offload { try core.deliverDue(cancel: token) })
246
+ try JSON(try await Offload.run { try core.deliverDue(cancel: token) })
266
247
  } onCancel: { token.cancel() }
267
248
  } catch { await resync(); throw error }
268
249
  if result["inFlight"].bool == true { return result }
@@ -276,7 +257,7 @@ public actor CrocheRuntime {
276
257
  private func resync() async {
277
258
  guard !closed else { return }
278
259
  let core = self.core
279
- _ = try? await Self.offload { try core.reschedule(); return true }
260
+ _ = try? await Offload.run { try core.reschedule(); return true }
280
261
  }
281
262
  #if canImport(UIKit) && os(iOS)
282
263
  private func observeForeground() {
@@ -287,13 +268,13 @@ public actor CrocheRuntime {
287
268
  }
288
269
  #endif
289
270
  /// 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" } }
271
+ func schedules() async throws -> JSON { try await run { try $0.schedules() } }
272
+ func flush() async throws -> JSON { try await run { try $0.flush(); return "null" } }
292
273
  /// Forgets this user's conversation and memory and starts over (money and identity stay).
293
274
  /// The clear takes its place on the actor, as `send` does: behind a running turn, ahead of
294
275
  /// 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") }
276
+ func clearHistory() async throws {
277
+ guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
297
278
  if let subscriptionHub { try await subscriptionHub.clearHistory(); return }
298
279
  try await Self.finish(beginClearHistory())
299
280
  }
@@ -302,14 +283,7 @@ public actor CrocheRuntime {
302
283
  nonisolated func beginClearHistory() -> PendingClear { core.beginClearHistory() }
303
284
  /// Waits for an admitted clear on a thread of its own.
304
285
  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) }
286
+ _ = try await Offload.run { try pending.finish(); return true }
313
287
  }
314
288
  /// Internal until `memory history` (B3): turns `from...to` from the turn archive, as
315
289
  /// `{"records":[...]}`; `archive_unavailable` when the storage keeps none.
@@ -320,49 +294,49 @@ public actor CrocheRuntime {
320
294
  func archiveClear(from: UInt64? = nil, to: UInt64? = nil) async throws {
321
295
  _ = try await run { try $0.archiveClear(from: from, to: to); return "null" }
322
296
  }
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) }
297
+ func inspect() throws -> JSON {
298
+ guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
299
+ do { return try JSON(try core.inspect()) } catch { throw LegacyCrocheError(error) }
326
300
  }
327
301
  /// Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
328
302
  /// The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
329
303
  /// its place in the queue, so turns sent before it still offer the old list. A removed or
330
304
  /// changed command answers `withdrawn` once the swap applies. A handler given here also
331
305
  /// 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") }
306
+ func setTools(_ tools: JSON, handlers: [String: ToolHandler]) throws {
307
+ guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
334
308
  let text = String(decoding: try tools.encoded(), as: UTF8.self)
335
309
  // New names first: the Core cannot call them before it accepts the list. Replacements
336
310
  // only after it accepts; a refusal removes what it staged, so every handler is as it was.
337
311
  let stamp = host.stageTools(handlers)
338
- do { try core.setToolDeclarations(tools: text) } catch { host.unstageTools(handlers.keys, stamp: stamp); throw CrocheError(error) }
312
+ do { try core.setToolDeclarations(tools: text) } catch { host.unstageTools(handlers.keys, stamp: stamp); throw LegacyCrocheError(error) }
339
313
  host.acceptTools(handlers)
340
314
  }
341
315
  /// The tool list the model is offered (metadata only).
342
- public func tools() throws -> JSON { try inspect()["tools"] }
316
+ func tools() throws -> JSON { try inspect()["tools"] }
343
317
  /// Stops the running turn only: messages sent while it ran still go, together, as the next
344
318
  /// turn. Cancelling a send's Task drops just that send while it is held; once its turn has
345
319
  /// started, the turn stops, for every send it carries.
346
- public func cancel() { core.cancelTurn() }
320
+ func cancel() { core.cancelTurn() }
347
321
  /// Drops the messages held behind the running turn (each send ends `cancelled`); returns how many.
348
322
  /// Resolves once the held record no longer lists them.
349
- @discardableResult public func clearQueued() async throws -> Int {
323
+ @discardableResult func clearQueued() async throws -> Int {
350
324
  guard !closed else { return 0 }
351
325
  let core = self.core
352
- return Int(try await Self.offload { try core.clearQueued() })
326
+ return Int(try await Offload.run { try core.clearQueued() })
353
327
  }
354
328
  /// Long-term memory: `snapshot()` for a read-only view, the other methods to manage it.
355
- public nonisolated var memory: CrocheMemory { CrocheMemory(runtime: self) }
329
+ nonisolated var memory: CrocheMemory { CrocheMemory(runtime: self) }
356
330
  /// The app's knowledge documents, held by the Rust Core in memory (never stored: load them
357
331
  /// on each open). The model searches and reads them with the built-in `wiki` command;
358
332
  /// `list`, `read` and `search` here are that same view.
359
- public nonisolated var wiki: CrocheWiki { CrocheWiki(runtime: self) }
333
+ nonisolated var wiki: CrocheWiki { CrocheWiki(runtime: self) }
360
334
  /// Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
361
335
  /// call upkeep has in flight is finished and settled first.
362
336
  /// The Core projection fence does not await buffered AsyncStream/UI consumers.
363
337
  /// An app callback that waits for work on the closer's thread deadlocks under any
364
338
  /// wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself.
365
- public func close() async throws {
339
+ func close() async throws {
366
340
  if closed { return }
367
341
  closed = true
368
342
  memoryCache.close()
@@ -373,43 +347,43 @@ public actor CrocheRuntime {
373
347
  foreground = nil
374
348
  #endif
375
349
  let core = self.core
376
- _ = try await Self.offload { core.close(); return true }
350
+ _ = try await Offload.run { core.close(); return true }
377
351
  // After the Core: a paid call upkeep has in flight is finished first.
378
352
  host.session.close()
379
353
  }
380
354
  }
381
355
 
382
356
  /// `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
357
+ struct CrocheMemory: Sendable {
358
+ fileprivate let runtime: AgentEngine
385
359
  /// 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() }
360
+ func callAsFunction() -> JSON { runtime.memoryCache.value }
361
+ func snapshot() async throws -> JSON { try await runtime.refreshMemory(); return callAsFunction() }
388
362
  private func refreshed(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
389
363
  let result = try await runtime.run(body)
390
364
  if result["deferred"].bool != true { try? await runtime.refreshMemory() }
391
365
  return result
392
366
  }
393
367
  /// 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() } }
368
+ func list() async throws -> JSON { try await refreshed { try $0.memoryList() } }
395
369
  /// `{deleted}`, or `{deferred: true}` (see `WriteResult`).
396
370
  @discardableResult
397
- public func delete(_ id: String) async throws -> JSON { try await refreshed { try $0.memoryDelete(id: id) } }
371
+ func delete(_ id: String) async throws -> JSON { try await refreshed { try $0.memoryDelete(id: id) } }
398
372
  /// Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
399
373
  /// `{deferred: true}` (see `WriteResult`).
400
374
  @discardableResult
401
- public func clear() async throws -> JSON { try await refreshed { try $0.memoryClear() } }
375
+ func clear() async throws -> JSON { try await refreshed { try $0.memoryClear() } }
402
376
  /// Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied, it
403
377
  /// carries the setting now in force.
404
378
  @discardableResult
405
- public func enabled(_ on: Bool) async throws -> WriteResult<Bool> {
379
+ func enabled(_ on: Bool) async throws -> WriteResult<Bool> {
406
380
  WriteResult(try await refreshed { try $0.memorySetEnabled(enabled: on) }) { _ in on }
407
381
  }
408
382
  /// Current and replaced AI-written facts: `{enabled, items}`, not the summary.
409
- public func export() async throws -> JSON { try await refreshed { try $0.memoryExport() } }
383
+ func export() async throws -> JSON { try await refreshed { try $0.memoryExport() } }
410
384
  /// 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.") }
385
+ func onChanged(_ listener: (@Sendable (MemoryChangedEvent) -> Void)?) throws {
386
+ guard !runtime.memoryCache.closed else { throw LegacyCrocheError("closed", "The agent is closed.") }
413
387
  do {
414
388
  runtime.core.setMemoryObserver(observer: listener.map { callback in EventHook { event in
415
389
  Task { try? await runtime.refreshMemory() }
@@ -423,13 +397,13 @@ extension WikiDocument {
423
397
  /// The `.md` files under `directory` as wiki documents, paths relative to it with `/`
424
398
  /// (`menu/stew.md`), in name order. Subfolders are read; symbolic links and other files are
425
399
  /// skipped, as the other SDKs' loaders do.
426
- public static func fromDirectory(_ directory: URL) throws -> [WikiDocument] {
400
+ static func fromDirectory(_ directory: URL) throws -> [WikiDocument] {
427
401
  let files = FileManager.default
428
402
  var out: [WikiDocument] = []
429
403
  func walk(_ dir: URL, _ prefix: String) throws {
430
404
  let names: [String]
431
405
  do { names = try files.contentsOfDirectory(atPath: dir.path).sorted() }
432
- catch { throw CrocheError("invalid_wiki", "\(dir.path): \(error.localizedDescription)") }
406
+ catch { throw LegacyCrocheError("invalid_wiki", "\(dir.path): \(error.localizedDescription)") }
433
407
  for name in names {
434
408
  let url = dir.appendingPathComponent(name)
435
409
  let path = prefix.isEmpty ? name : prefix + "/" + name
@@ -438,7 +412,7 @@ extension WikiDocument {
438
412
  if type == .typeDirectory {
439
413
  try walk(url, path)
440
414
  } else if type == .typeRegular && name.hasSuffix(".md") {
441
- if out.count >= 2000 { throw CrocheError("invalid_wiki", "The wiki holds at most 2000 documents") }
415
+ if out.count >= 2000 { throw LegacyCrocheError("invalid_wiki", "The wiki holds at most 2000 documents") }
442
416
  out.append(WikiDocument(path: path, markdown: String(decoding: try Data(contentsOf: url), as: UTF8.self)))
443
417
  }
444
418
  }
@@ -448,17 +422,17 @@ extension WikiDocument {
448
422
  }
449
423
  /// The documents in a folder shipped with the app (added to the target as a folder
450
424
  /// reference, so its subfolders survive): `WikiDocument.fromBundle()` reads `wiki/`.
451
- public static func fromBundle(_ bundle: Bundle = .main, folder: String = "wiki") throws -> [WikiDocument] {
425
+ static func fromBundle(_ bundle: Bundle = .main, folder: String = "wiki") throws -> [WikiDocument] {
452
426
  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.")
427
+ throw LegacyCrocheError("invalid_wiki", "No folder \(folder) in the bundle: add it to the target as a folder reference.")
454
428
  }
455
429
  return try fromDirectory(url)
456
430
  }
457
431
  }
458
432
 
459
433
  /// `runtime.wiki`: the app's documents, as the TS SDK's `runtime.wiki`.
460
- public struct CrocheWiki: Sendable {
461
- fileprivate let runtime: CrocheRuntime
434
+ struct CrocheWiki: Sendable {
435
+ fileprivate let runtime: AgentEngine
462
436
  private static func json(_ docs: [WikiDocument]) throws -> String {
463
437
  let value = JSON.array(docs.map { doc in
464
438
  var o: [String: JSON] = ["path": .string(doc.path), "markdown": .string(doc.markdown)]
@@ -470,49 +444,49 @@ public struct CrocheWiki: Sendable {
470
444
  /// Replaces every document and answers what it installed: `{documents, bytes, digest}`.
471
445
  /// On an error nothing changes.
472
446
  @discardableResult
473
- public func set(_ docs: [WikiDocument]) async throws -> JSON {
447
+ func set(_ docs: [WikiDocument]) async throws -> JSON {
474
448
  let text = try Self.json(docs)
475
449
  return try await runtime.run { try $0.wikiSet(docs: text) }
476
450
  }
477
451
  /// `set`, without the digest.
478
- public func load(_ docs: [WikiDocument]) async throws { try await set(docs) }
452
+ func load(_ docs: [WikiDocument]) async throws { try await set(docs) }
479
453
  /// This user's own documents (saved recipes, lesson notes): stored with their state (at most
480
454
  /// 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable when
481
455
  /// this returns. `clearHistory` keeps them. To share one with another character, put it to that character's Runtime too.
482
456
  /// Answers `{documents, bytes}`, or `{deferred: true}` (see `WriteResult`).
483
457
  @discardableResult
484
- public func putUser(_ docs: [WikiDocument]) async throws -> JSON {
458
+ func putUser(_ docs: [WikiDocument]) async throws -> JSON {
485
459
  let text = try Self.json(docs)
486
460
  return try await runtime.run { try $0.wikiPutUser(docs: text) }
487
461
  }
488
462
  /// Removes one of this user's own documents; whether it existed.
489
463
  @discardableResult
490
- public func removeUser(_ path: String) async throws -> WriteResult<Bool> {
464
+ func removeUser(_ path: String) async throws -> WriteResult<Bool> {
491
465
  WriteResult(try await runtime.run { try $0.wikiRemoveUser(path: path) }) { $0["removed"].bool ?? false }
492
466
  }
493
467
  /// Removes every one of this user's own documents; how many.
494
468
  @discardableResult
495
- public func clearUser() async throws -> WriteResult<Int> {
469
+ func clearUser() async throws -> WriteResult<Int> {
496
470
  WriteResult(try await runtime.run { try $0.wikiClearUser() }) { Int($0["cleared"].number ?? 0) }
497
471
  }
498
472
  /// Adds documents or replaces those with the same path, atomically.
499
- public func put(_ docs: [WikiDocument]) async throws {
473
+ func put(_ docs: [WikiDocument]) async throws {
500
474
  let text = try Self.json(docs)
501
475
  _ = try await runtime.run { try $0.wikiPut(docs: text); return "null" }
502
476
  }
503
477
  /// Whether the document existed.
504
478
  @discardableResult
505
- public func remove(_ path: String) async throws -> Bool {
479
+ func remove(_ path: String) async throws -> Bool {
506
480
  try await runtime.run { try $0.wikiRemove(path: path) ? "true" : "false" }.bool ?? false
507
481
  }
508
482
  /// `[{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) } }
483
+ func list(folder: String? = nil) async throws -> JSON { try await runtime.run { try $0.wikiList(folder: folder) } }
510
484
  /// 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 {
485
+ func read(_ path: String, part: Int = 1) async throws -> JSON {
512
486
  try await runtime.run { try $0.wikiRead(path: path, part: UInt32(clamping: max(0, part))) }
513
487
  }
514
488
  /// The best matches, best first: at most `limit` (and 5).
515
- public func search(_ query: String, limit: Int = 5) async throws -> JSON {
489
+ func search(_ query: String, limit: Int = 5) async throws -> JSON {
516
490
  try await runtime.run { try $0.wikiSearch(query: query, limit: UInt32(clamping: min(max(0, limit), 5))) }
517
491
  }
518
492
  }
@@ -522,7 +496,7 @@ public struct CrocheWiki: Sendable {
522
496
  /// call order when that operation ends. A message sent after the write sees it; one sent before
523
497
  /// does not. It is held in this process until then: closing first drops it, and a write that
524
498
  /// cannot apply then is reported as a `write.failed` debug event.
525
- public enum WriteResult<Value: Sendable>: Sendable {
499
+ enum WriteResult<Value: Sendable>: Sendable {
526
500
  case applied(Value)
527
501
  case deferred
528
502
 
@@ -541,7 +515,7 @@ final class PendingTurn: Sendable {
541
515
  func result() async throws -> JSON {
542
516
  let pending = self.pending
543
517
  return try await withTaskCancellationHandler {
544
- try JSON(try await CrocheRuntime.offloaded { try pending.wait() })
518
+ try JSON(try await Offload.run { try pending.wait() })
545
519
  } onCancel: { [token] in token.cancel() }
546
520
  }
547
521
  func cancel() { token.cancel() }