@h1r-ai/croche-react-native 0.6.0 → 0.7.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 (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -1,31 +1,27 @@
1
1
  import Foundation
2
2
 
3
- /// ARCHITECTURE §2a: the ONE storage interface, the same methods on every SDK. Omitted in
4
- /// `OpenOptions` = the platform default (Application Support files, Keychain secrets). A custom
5
- /// store (servers: KV, Redis, S3) implements exactly this. Keys and layout are Core's.
6
- public protocol StoragePal: Sendable {
7
- /// nil = absent.
8
- func read(_ key: String) async throws -> String?
9
- /// ATOMIC REPLACE, durable on return.
10
- func write(_ key: String, _ value: String) async throws
11
- /// A real delete; absent = ok.
12
- func remove(_ key: String) async throws
13
- /// Keys starting with `prefix`, any order.
14
- func list(_ prefix: String) async throws -> [String]
15
- /// Exclusive across processes; never waits. Another owner holding it is the FACT
16
- /// `.held`, not an error; Core maps it. A throw is a failure (Core's `storage_error`).
17
- func lock(_ name: String) async throws -> LockOutcome
18
- func unlock(_ name: String) async throws
19
- var secrets: any SecretsPal { get }
3
+ /// Atomic app state. The condition and all writes share one transaction.
4
+ public protocol StateStore: Adapter {
5
+ /// Read saved state so a user can continue where they left off.
6
+ func get(_ key: String) async throws -> StateValue?
7
+ /// Load just the relevant records so a long conversation still opens promptly.
8
+ func list(_ prefix: String, _ options: StateListOptions?) async throws -> StatePage
9
+ /// Keep a saved reply and its related progress consistent if the app stops mid-write.
10
+ func commit(_ ops: [StateOp], _ condition: StateCondition) async throws -> StateCommitResult
11
+ }
12
+ public extension StateStore {
13
+ /// Always `"state"`.
14
+ var kind: String { "state" }
20
15
  }
21
16
 
22
- /// What `lock` found (ARCHITECTURE §2a).
23
- public enum LockOutcome: Sendable, Equatable { case acquired, held }
24
-
25
- public protocol SecretsPal: Sendable {
26
- func read(_ key: String) async throws -> String?
27
- func write(_ key: String, _ value: String) async throws
28
- func remove(_ key: String) async throws
17
+ /// A stored value with its version.
18
+ public struct StateValue: Sendable, Equatable {
19
+ /// The stored text.
20
+ public let value: String
21
+ /// The store's opaque version of this key. Core passes it back unchanged in a ``StateCondition``.
22
+ public let version: String
23
+ /// Creates a stored value.
24
+ public init(value: String, version: String) { self.value = value; self.version = version }
29
25
  }
30
26
 
31
27
  /// A storage failure reports facts only (ARCHITECTURE §2/§2a, Leo 12:39Z): its text, for
@@ -37,12 +33,27 @@ func storageFailure(_ error: Error) -> CoreStorageFailure {
37
33
  return .Failure(detail: "\(error)")
38
34
  }
39
35
 
40
- /// The app's `StoragePal` as Core's callback. Core calls it on a Core thread (never the
41
- /// cooperative pool: see `blocking`), so waiting for the app's async method is safe there.
42
- /// Whatever the app throws reaches Core as text only; contention is `lock`'s `.held`.
43
- final class CoreStorageAdapter: CoreStoragePal, @unchecked Sendable {
44
- let storage: any StoragePal
45
- init(_ storage: any StoragePal) { self.storage = storage }
36
+ private extension Result where Failure == Error {
37
+ init(_ body: () async throws -> Success) async {
38
+ do { self = .success(try await body()) } catch { self = .failure(error) }
39
+ }
40
+ }
41
+
42
+ /// The platform default store as Core's storage argument (Keel 16:08Z): the argument always
43
+ /// carries a PAL, the app's or this one; Core has no storage default of its own. The options JSON
44
+ /// carries selected adapter-kind markers, so Core can tell the default from an app store.
45
+ final class PlatformStorageAdapter: CoreStoragePal, @unchecked Sendable {
46
+ let pal: PlatformPal
47
+ let state: (any StateStore)?
48
+
49
+ init(_ pal: PlatformPal, state: (any StateStore)? = nil) {
50
+ self.pal = pal
51
+ self.state = state
52
+ }
53
+
54
+ private func call<T>(_ body: () throws -> T) throws -> T {
55
+ do { return try body() } catch { throw storageFailure(error) }
56
+ }
46
57
 
47
58
  private func wait<T: Sendable>(_ body: @escaping @Sendable () async throws -> T) throws -> T {
48
59
  let done = DispatchSemaphore(value: 0)
@@ -52,44 +63,103 @@ final class CoreStorageAdapter: CoreStoragePal, @unchecked Sendable {
52
63
  do { return try result.get() } catch { throw storageFailure(error) }
53
64
  }
54
65
 
55
- func read(key: String) throws -> String? { let s = storage; return try wait { try await s.read(key) } }
56
- func write(key: String, value: String) throws { let s = storage; try wait { try await s.write(key, value) } }
57
- func remove(key: String) throws { let s = storage; try wait { try await s.remove(key) } }
58
- func list(prefix: String) throws -> [String] { let s = storage; return try wait { try await s.list(prefix) } }
59
- func lock(name: String) throws -> PalLockOutcome {
60
- let s = storage
61
- switch try wait({ try await s.lock(name) }) { case .acquired: return .acquired; case .held: return .held }
66
+ func commitState(ops: [CoreStateOp], condition: CoreStateCondition) throws -> CoreStateCommit {
67
+ let batch = ops.map { $0.app() }, guardValue = condition.app()
68
+ return try call {
69
+ guard let state else { return try pal.commitState(ops: batch, condition: guardValue).core() }
70
+ try validateStateBatch(batch, guardValue)
71
+ return try wait { try await state.commit(batch, guardValue) }.core()
72
+ }
62
73
  }
63
- func unlock(name: String) throws { let s = storage; try wait { try await s.unlock(name) } }
64
- func readSecret(key: String) throws -> String? { let s = storage.secrets; return try wait { try await s.read(key) } }
65
- func writeSecret(key: String, value: String) throws { let s = storage.secrets; try wait { try await s.write(key, value) } }
66
- func removeSecret(key: String) throws { let s = storage.secrets; try wait { try await s.remove(key) } }
67
- }
68
74
 
69
- private extension Result where Failure == Error {
70
- init(_ body: () async throws -> Success) async {
71
- do { self = .success(try await body()) } catch { self = .failure(error) }
75
+ func listState(prefix: String, options: CoreStateListOptions) throws -> CoreStatePage {
76
+ let range = options.app()
77
+ return try call {
78
+ guard let state else { return try pal.listState(prefix: prefix, options: range).core() }
79
+ _ = try StateRange(prefix: prefix, options: StateListOptions(start: range.start, reverse: range.reverse, limit: range.limit))
80
+ return try wait { try await state.list(prefix, range) }.core()
81
+ }
72
82
  }
73
- }
74
83
 
75
- /// The platform default store as Core's storage argument (Keel 16:08Z): the argument always
76
- /// carries a PAL, the app's or this one; Core has no storage default of its own. The options JSON
77
- /// still omits `storage` here, so Core can tell the default from an app store.
78
- final class PlatformStorageAdapter: CoreStoragePal, @unchecked Sendable {
79
- let pal: PlatformPal
80
- init(_ pal: PlatformPal) { self.pal = pal }
84
+ func readVersioned(key: String) throws -> CoreVersionedValue {
85
+ try call {
86
+ guard let state else { return try pal.readVersioned(key: key) }
87
+ try validateStateKey(key)
88
+ let row = try wait { try await state.get(key) }
89
+ return try VersionedValue(value: row?.value, version: row?.version).core()
90
+ }
91
+ }
81
92
 
82
- private func call<T>(_ body: () throws -> T) throws -> T {
83
- do { return try body() } catch { throw storageFailure(error) }
93
+ func writeIf(key: String, value: String?, expect: String?) throws -> CoreWriteOutcome {
94
+ try call {
95
+ guard state != nil else { return try pal.writeIf(key: key, value: value, expect: expect) }
96
+ let op: CoreStateOp = value.map { .put(key: key, value: $0) } ?? .delete(key: key)
97
+ switch try commitState(ops: [op], condition: CoreStateCondition(key: key, version: expect)) {
98
+ case .committed(let version): return .written(version: version)
99
+ case .conflict: return .conflict(version: nil)
100
+ }
101
+ }
84
102
  }
85
103
 
86
- func read(key: String) throws -> String? { try call { try pal.read(key: key) } }
87
- func write(key: String, value: String) throws { try call { try pal.write(key: key, value: value) } }
88
- func remove(key: String) throws { try call { try pal.remove(key: key) } }
89
- func list(prefix: String) throws -> [String] { try call { try pal.list(prefix: prefix) } }
104
+ func read(key: String) throws -> String? {
105
+ guard state != nil else { return try call { try pal.read(key: key) } }
106
+ return try readVersioned(key: key).value
107
+ }
108
+
109
+ private func modify(_ key: String, _ value: String?) throws {
110
+ let version = try readVersioned(key: key).version
111
+ guard case .written = try writeIf(key: key, value: value, expect: version) else {
112
+ throw CoreStorageFailure.Failure(detail: "StateStore key changed before commit.")
113
+ }
114
+ }
115
+
116
+ func write(key: String, value: String) throws {
117
+ if state == nil { try call { try pal.write(key: key, value: value) } }
118
+ else { try modify(key, value) }
119
+ }
120
+ func remove(key: String) throws {
121
+ if state == nil { try call { try pal.remove(key: key) } }
122
+ else { try modify(key, nil) }
123
+ }
124
+
125
+ func list(prefix: String) throws -> [String] {
126
+ guard state != nil else { return try call { try pal.list(prefix: prefix) } }
127
+ var keys: [String] = [], cursor: String?
128
+ var seen = Set<String>()
129
+ repeat {
130
+ let page = try listState(prefix: prefix, options: CoreStateListOptions(start: nil, reverse: false, limit: nil, cursor: cursor))
131
+ for row in page.entries {
132
+ guard row.key.hasPrefix(prefix), keys.last.map({ $0 < row.key }) ?? true else {
133
+ throw CoreStorageFailure.Failure(detail: "StateStore returned invalid list order or scope.")
134
+ }
135
+ keys.append(row.key)
136
+ }
137
+ cursor = page.nextCursor
138
+ if let cursor, !seen.insert(cursor).inserted {
139
+ throw CoreStorageFailure.Failure(detail: "StateStore cursor did not advance.")
140
+ }
141
+ } while cursor != nil
142
+ return keys
143
+ }
144
+
145
+ func purgeInstance(prefix: String, secretKey: String?) throws {
146
+ try call {
147
+ try pal.purgeStorage(prefix: prefix, localState: state == nil, localSecret: true, deleteState: {
148
+ if state != nil {
149
+ for key in try list(prefix: prefix) { try modify(key, nil) }
150
+ }
151
+ })
152
+ }
153
+ }
90
154
  func lock(name: String) throws -> PalLockOutcome { try call { try pal.lock(key: name) } }
91
155
  func unlock(name: String) throws { pal.unlock(key: name) }
92
- func readSecret(key: String) throws -> String? { try call { try pal.readSecret(key: key) } }
93
- func writeSecret(key: String, value: String) throws { try call { try pal.writeSecret(key: key, value: value) } }
94
- func removeSecret(key: String) throws { try call { try pal.removeSecret(key: key) } }
156
+ func readSecret(key: String) throws -> String? {
157
+ return try call { try pal.readSecret(key: key) }
158
+ }
159
+ func writeSecret(key: String, value: String) throws {
160
+ try call { try pal.writeSecret(key: key, value: value) }
161
+ }
162
+ func removeSecret(key: String) throws {
163
+ try call { try pal.removeSecret(key: key) }
164
+ }
95
165
  }
@@ -45,21 +45,21 @@ final class FixtureHost: HostPal, @unchecked Sendable {
45
45
  let serve = self.serve
46
46
  try effect {
47
47
  _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
48
- try await SwiftHost.adapt(serve, request, sink, signal); return true
48
+ try await RuntimeHTTPAdapter.adapt(serve, request, sink, signal); return true
49
49
  }
50
50
  }
51
51
  }
52
52
  /// A fixed public answer: no DNS query leaves the process.
53
53
  func resolve(host: String, cancel: CancelToken) throws -> [String] { ["93.184.216.34"] }
54
54
 
55
+ func blobOperation(operation: String, key: String, cursor: String?, bytes: Data?) throws -> PalBlobReply {
56
+ try base.blobOperation(operation: operation, key: key, cursor: cursor, bytes: bytes)
57
+ }
55
58
  func streamPlatform() -> HostStreamPlatform { base.streamPlatform() }
56
- func imageCodecAvailable() -> Bool { base.imageCodecAvailable() }
59
+ func imageSupport() -> String? { base.imageSupport() }
60
+ func imageOperation(operation: String, bytes: Data, optionsJson: String, cancel: CancelToken) throws -> PalImageReply { try base.imageOperation(operation: operation, bytes: bytes, optionsJson: optionsJson, cancel: cancel) }
57
61
  func readImage(request: PalImageReadRequest, cancel: CancelToken) throws -> Data { try base.readImage(request: request, cancel: cancel) }
58
- func prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) throws -> PalImageBytes { try base.prepareImage(source: source, plan: plan, cancel: cancel) }
59
62
  func releaseImage(capture: String) { base.releaseImage(capture: capture) }
60
- func decodeImage(bytes: Data, options: PalImageDecodeOptions, cancel: CancelToken) throws -> PalDecodedImage { try base.decodeImage(bytes: bytes, options: options, cancel: cancel) }
61
- func renderImage(request: PalImageRenderRequest, cancel: CancelToken) throws -> Data { try base.renderImage(request: request, cancel: cancel) }
62
- func releaseDecodedImage(handle: String) { base.releaseDecodedImage(handle: handle) }
63
63
  func platformFacts() -> PalPlatformFacts { base.platformFacts() }
64
64
  func readAsset(path: String) throws -> Data? { try base.readAsset(path: path) }
65
65
  func list(prefix: String) throws -> [String] { try base.list(prefix: prefix) }
@@ -68,6 +68,7 @@ final class FixtureHost: HostPal, @unchecked Sendable {
68
68
  func readSecret(key: String) throws -> String? { try base.readSecret(key: key) }
69
69
  func writeSecret(key: String, value: String) throws { try base.writeSecret(key: key, value: value) }
70
70
  func remove(key: String) throws { try base.remove(key: key) }
71
+ func purgeInstance(prefix: String) throws { try base.purgeInstance(prefix: prefix) }
71
72
  func removeSecret(key: String) throws { try base.removeSecret(key: key) }
72
73
  func lock(key: String) throws -> PalLockOutcome { try base.lock(key: key) }
73
74
  func unlock(key: String) throws { try base.unlock(key: key) }
@@ -80,20 +81,14 @@ final class FixtureHost: HostPal, @unchecked Sendable {
80
81
  func wake(atMs: Double?) { base.wake(atMs: atMs) }
81
82
  func schedule(entries: String) throws { try base.schedule(entries: entries) }
82
83
  func registerBackground(identifier: String, wake: CoreBackgroundWake) throws { try base.registerBackground(identifier: identifier, wake: wake) }
83
- func archiveAppendLine(entry: String, line: String) throws { try base.archiveAppendLine(entry: entry, line: line) }
84
- func archiveReadLines(entry: String) throws -> [String] { try base.archiveReadLines(entry: entry) }
85
- func archiveReplaceLines(entry: String, lines: [String]) throws { try base.archiveReplaceLines(entry: entry, lines: lines) }
86
- func archiveRemove(entry: String) throws { try base.archiveRemove(entry: entry) }
87
- func archiveEntries(prefix: String) throws -> [ArchiveEntry] { try base.archiveEntries(prefix: prefix) }
88
- func storageCapability() -> StorageCapability { base.storageCapability() }
89
84
  }
90
85
 
91
86
  extension Croche {
92
87
  /// `open` through the private test entry, when a test has set `FixtureCloud.serve`.
93
- static func fixtureOpen(_ open: String, _ registrations: [CoreToolRegistration], _ storage: (any StoragePal)?,
88
+ static func fixtureOpen(_ open: String, _ registrations: [CoreToolRegistration], _ selected: SelectedAdapters,
94
89
  _ recoveryJson: String?, _ serve: @escaping RuntimeHTTP) async throws -> Croche {
95
- let base = try platformHost(), host = FixtureHost(base: base, serve: serve)
96
- let store = storageArgument(storage, base)
90
+ let base = try platformHost(image: selected.image), host = FixtureHost(base: base, serve: serve)
91
+ let store = PlatformStorageAdapter(base, state: selected.state)
97
92
  return Croche(core: try await owner({ try CoreCroche.openForTests(openJson: open, registrations: registrations,
98
93
  storage: store, host: host, bindingFactsJson: BindingFacts.json(),
99
94
  intervalsJson: fixtureSettings, recoveryJson: recoveryJson) },
@@ -2,61 +2,112 @@ import Foundation
2
2
 
3
3
  /// What the model asked for. Bound arguments are already merged in by Core.
4
4
  public struct ToolCall: Sendable {
5
+ /// The manifest command key the model called.
5
6
  public let key: String
7
+ /// The call's arguments, bound values included.
6
8
  public let args: [String: JSON]
7
9
  }
8
10
 
11
+ /// The source owner and id for an explicit app-held attachment copy.
12
+ public struct AttachmentSource: Sendable {
13
+ /// The agent that holds the attachment.
14
+ public let agent: String
15
+ /// The attachment id.
16
+ public let id: String
17
+ /// The instance that holds it, or `nil` for the default instance.
18
+ public let instance: String?
19
+ /// Creates an attachment source.
20
+ public init(agent: String, id: String, instance: String? = nil) { self.agent = agent; self.id = id; self.instance = instance }
21
+ var json: JSON { var value: [String: JSON] = ["agent": .string(agent), "id": .string(id)]; if let instance { value["instance"] = .string(instance) }; return .object(value) }
22
+ }
23
+ /// An original attachment read through Core's scoped capability. `data` is base64.
24
+ public struct AttachmentData: Sendable, Decodable, Equatable {
25
+ /// The original's media type, such as `image/png`.
26
+ public let mediaType: String
27
+ /// The original bytes, base64-encoded.
28
+ public let data: String
29
+ }
9
30
  /// Who the call works for. Cancellation is the Task's: it fires on cancel, agent close and teardown.
10
31
  public struct ToolContext: Sendable {
32
+ /// The call id, matching the agent's tool event.
11
33
  public let callId: String
34
+ let attachments: any CoreAttachmentReader
35
+ /// Let an app tool read the file the user shared for that action.
36
+ ///
37
+ /// Reads from the calling instance only; a missing attachment fails with `unknown_id`.
38
+ public func attachment(_ id: String) async throws -> AttachmentData {
39
+ try decode(AttachmentData.self, await blocking { try attachments.attachment(id: id) })
40
+ }
41
+ /// The agent that made the call.
12
42
  public let agentId: String
13
43
  /// nil = the default instance.
14
44
  public let instance: String?
45
+ /// The Croche's user, or `nil` when it was opened without one.
15
46
  public let user: String?
16
47
  /// The input ids this call works for (avoid buying twice).
17
48
  public let causedBy: [String]
18
49
  }
19
50
 
51
+ /// One part of a tool's ``ToolResult/content(_:)`` result.
52
+ ///
53
+ /// For images, `attach: true` keeps the original on the final message; omit it for model-only input. Any other
54
+ /// explicit value is refused with `invalid_tool_result`.
20
55
  public enum ToolContent: Sendable, Equatable {
56
+ /// Text for the model.
21
57
  case text(String)
22
58
  /// Base64 bytes.
23
- case image(mediaType: String, data: String)
24
- /// A `file://` URL, read by the native PAL.
25
- case imageFile(mediaType: String, uri: String)
59
+ case image(mediaType: String, data: String, alt: String? = nil, attach: Bool? = nil)
60
+ /// A `file://` URL, read by the native host.
61
+ case imageFile(mediaType: String, uri: String, alt: String? = nil, attach: Bool? = nil)
26
62
  }
27
63
 
28
64
  /// A tool's tagged result. Returning nil is the empty result.
29
65
  public enum ToolResult: Sendable, Equatable {
66
+ /// Text and images for the model.
30
67
  case content([ToolContent])
68
+ /// A JSON value for the model.
31
69
  case json(JSON)
32
70
  }
33
71
 
34
72
  /// Its message reaches the model verbatim. Core chooses every code.
35
73
  public struct ToolError: Error, Sendable {
74
+ /// The text the model sees.
36
75
  public let message: String
76
+ /// Creates a tool error with the text the model sees.
37
77
  public init(_ message: String) { self.message = message }
38
78
  }
39
79
 
80
+ /// Let the app apply its own permissions and use its own data for an action the agent requests.
40
81
  public typealias ToolExecute = @Sendable (ToolCall, ToolContext) async throws -> ToolResult?
41
82
 
42
83
  /// A manifest (JSON, the same on every SDK) plus its execute. Core validates the manifest
43
84
  /// here: an invalid one throws `invalid_tool` with Core's path.
44
85
  public final class ToolDefinition: Sendable {
45
- let core: CoreToolDefinition
46
- public var name: String { core.name() }
47
- init(core: CoreToolDefinition) { self.core = core }
48
- init(manifest: JSON, execute: @escaping ToolExecute) throws {
49
- let text = text(manifest)
50
- do { core = try CoreToolDefinition(manifestJson: text, execute: ToolExecuteAdapter(execute)) }
86
+ private let make: @Sendable () throws -> CoreToolDefinition
87
+ /// The registered tool name, from the manifest.
88
+ public let name: String
89
+ init(make: @escaping @Sendable () throws -> CoreToolDefinition) throws {
90
+ self.make = make
91
+ // A validation export lasts only for this call; reusable public tools hold immutable inputs.
92
+ name = try make().name()
93
+ }
94
+ convenience init(manifest: JSON, execute: @escaping ToolExecute) throws {
95
+ let encoded = text(manifest)
96
+ do { try self.init(make: { try CoreToolDefinition(manifestJson: encoded, execute: ToolExecuteAdapter(execute)) }) }
51
97
  catch { throw CrocheError(error) }
52
98
  }
99
+ func core() throws -> CoreToolDefinition { try make() }
53
100
  }
54
101
 
102
+ /// Let the agent use app-owned features such as looking up an order.
55
103
  public func defineTool(_ manifest: JSON, _ execute: @escaping ToolExecute) throws -> ToolDefinition {
56
104
  try ToolDefinition(manifest: manifest, execute: execute)
57
105
  }
58
106
 
59
- /// The same, for a handler that returns a plain Swift value (Leo 17:23Z): String, a number,
107
+ // Leo 17:23Z.
108
+ /// Let the agent use app-owned features such as looking up an order.
109
+ ///
110
+ /// The same, for a handler that returns a plain Swift value: String, a number,
60
111
  /// Bool, nil, a Dictionary or Array of those, or any `Encodable`. It is serialized to JSON
61
112
  /// mechanically (no policy); a `ToolResult` passes through and nil is "nothing to report", as
62
113
  /// for `ToolExecute`. A value that has no JSON form (a non-finite number, a non-string key, a
@@ -121,7 +172,10 @@ enum PlainToolValue {
121
172
 
122
173
  /// `Croche.open` registration: a tool, or a tool with a bind for every agent. No commands or guide here.
123
174
  public enum ToolRegistration: Sendable {
175
+ /// The tool as defined, with no bind.
124
176
  case tool(ToolDefinition)
177
+ /// The tool with argument values bound for every agent.
178
+ ///
125
179
  /// `[:]` is an explicit empty bind and reaches Core as `{}`, distinct from `.tool`.
126
180
  case bound(ToolDefinition, bind: [String: JSON])
127
181
 
@@ -136,15 +190,18 @@ public enum ToolRegistration: Sendable {
136
190
 
137
191
  func core() throws -> CoreToolRegistration {
138
192
  switch self {
139
- case .tool(let tool): CoreToolRegistration(tool: tool.core, optionsJson: nil)
140
- case .bound(let tool, _): CoreToolRegistration(tool: tool.core, optionsJson: text(json))
193
+ case .tool(let tool): CoreToolRegistration(tool: try tool.core(), optionsJson: nil)
194
+ case .bound(let tool, _): CoreToolRegistration(tool: try tool.core(), optionsJson: text(json))
141
195
  }
142
196
  }
143
197
  }
144
198
 
145
199
  /// Core-owned tools. Registered name `webSearch`.
146
200
  public enum CrocheTools {
147
- public static var webSearch: ToolDefinition { ToolDefinition(core: coreWebSearch()) }
201
+ /// Croche's paid web search tool.
202
+ public static var webSearch: ToolDefinition { try! ToolDefinition(make: { coreWebSearch() }) }
203
+ /// Croche's built-in image tool.
204
+ public static var image: ToolDefinition { try! ToolDefinition(make: { coreImage() }) }
148
205
  }
149
206
 
150
207
  /// Core's execute callback, on a Core worker thread. Reports one tagged fact; Core applies policy
@@ -154,10 +211,10 @@ final class ToolExecuteAdapter: CoreToolExecute, @unchecked Sendable {
154
211
  private let execute: ToolExecute
155
212
  init(_ execute: @escaping ToolExecute) { self.execute = execute }
156
213
 
157
- func execute(callJson: String, contextJson: String, cancel: CancelToken) throws -> String {
214
+ func execute(callJson: String, contextJson: String, cancel: CancelToken, attachments: any CoreAttachmentReader) throws -> String {
158
215
  let call = try JSON(callJson), context = try JSON(contextJson)
159
216
  let toolCall = ToolCall(key: call["key"].string ?? "", args: call["args"].object ?? [:])
160
- let toolContext = ToolContext(callId: context["callId"].string ?? "", agentId: context["agentId"].string ?? "", instance: context["instance"].string,
217
+ let toolContext = ToolContext(callId: context["callId"].string ?? "", attachments: attachments, agentId: context["agentId"].string ?? "", instance: context["instance"].string,
161
218
  user: context["user"].string, causedBy: context["causedBy"].array?.compactMap(\.string) ?? [])
162
219
  let execute = self.execute
163
220
  let box = ResultBox<ToolResult?>()
@@ -202,8 +259,20 @@ extension ToolContent {
202
259
  var json: JSON {
203
260
  switch self {
204
261
  case .text(let text): .object(["type": .string("text"), "text": .string(text)])
205
- case .image(let mediaType, let data): .object(["type": .string("image"), "mediaType": .string(mediaType), "data": .string(data)])
206
- case .imageFile(let mediaType, let uri): .object(["type": .string("image"), "mediaType": .string(mediaType), "uri": .string(uri)])
262
+ case .image(let mediaType, let data, let alt, let attach):
263
+ Self.imageJSON(mediaType, "data", data, alt, attach)
264
+ case .imageFile(let mediaType, let uri, let alt, let attach):
265
+ Self.imageJSON(mediaType, "uri", uri, alt, attach)
207
266
  }
208
267
  }
209
268
  }
269
+
270
+ extension ToolContent {
271
+ private static func imageJSON(_ mediaType: String, _ key: String, _ source: String,
272
+ _ alt: String?, _ attach: Bool?) -> JSON {
273
+ var image: [String: JSON] = ["type": .string("image"), "mediaType": .string(mediaType), key: .string(source)]
274
+ image["alt"] = alt.map(JSON.string)
275
+ image["attach"] = attach.map(JSON.bool)
276
+ return .object(image)
277
+ }
278
+ }
@@ -0,0 +1,27 @@
1
+ import Foundation
2
+
3
+ // Founder 2026-11-22 02:31:47Z.
4
+ /// How Croche Cloud verified this installation (``Croche/verification()``).
5
+ /// Verification is not access: a withheld key leaves it unchanged. The strings match TS/RN and Kotlin,
6
+ /// and the set is open (`String`, like `RunToolResult.costStatus`).
7
+ public struct Verification: Sendable, Equatable, Decodable {
8
+ /// `attested`, `server`, `development`, `unverified`, or `unknown` (not registered yet, or Cloud did not say).
9
+ public let status: String
10
+ /// The device-side code of the last attestor attempt without a usable proof, or nil.
11
+ /// Nil does not mean Cloud accepted a proof; read `status` for that.
12
+ public let lastAttestation: String?
13
+
14
+ /// Creates a verification value.
15
+ public init(status: String, lastAttestation: String?) {
16
+ self.status = status; self.lastAttestation = lastAttestation
17
+ }
18
+ }
19
+
20
+ extension Croche {
21
+ /// Let the app show how Croche Cloud verified this installation, or explain a withheld key.
22
+ /// Read-only, from stored registration state; it never calls Cloud.
23
+ public func verification() async throws -> Verification {
24
+ let core = try self.core
25
+ return try decode(Verification.self, await blocking { try core.verification() })
26
+ }
27
+ }