@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
@@ -0,0 +1,189 @@
1
+ import Foundation
2
+
3
+ /// One write in a ``StateStore/commit(_:_:)`` batch. A batch never repeats a key.
4
+ public enum StateOp: Sendable, Equatable {
5
+ /// Store `value` under `key`, replacing any earlier value.
6
+ case put(key: String, value: String)
7
+ /// Remove `key`. Deleting an absent key succeeds.
8
+ case delete(key: String)
9
+
10
+ var key: String {
11
+ switch self {
12
+ case .put(let key, _), .delete(let key): return key
13
+ }
14
+ }
15
+ }
16
+
17
+ /// The guard of a commit: the batch applies only if `key` is at `version` now.
18
+ public struct StateCondition: Sendable, Equatable {
19
+ /// The guard key.
20
+ public var key: String
21
+ /// The version the key must have; `nil` means the key must be absent.
22
+ public var version: String?
23
+ /// Creates a commit condition.
24
+ public init(key: String, version: String?) { self.key = key; self.version = version }
25
+ }
26
+
27
+ /// The outcome of a ``StateStore/commit(_:_:)``.
28
+ public enum StateCommitResult: Sendable, Equatable {
29
+ /// The whole batch was applied. `version` is the guard key's resulting version.
30
+ case committed(version: String?)
31
+ /// The guard did not match and nothing was written. Do not retry or merge the batch: Core decides what follows.
32
+ case conflict
33
+ }
34
+
35
+ /// How ``StateStore/list(_:_:)`` pages through a prefix.
36
+ public struct StateListOptions: Sendable, Equatable {
37
+ /// Inclusive lower bound within the prefix. It stays a lower bound when `reverse` is set.
38
+ public var start: String?
39
+ /// List in descending UTF-8 key order instead of ascending.
40
+ public var reverse: Bool
41
+ /// Most entries in one page, up to 128.
42
+ public var limit: UInt32?
43
+ /// The previous page's ``StatePage/nextCursor``, used with the same prefix, start and direction.
44
+ public var cursor: String?
45
+ /// Creates list options.
46
+ public init(start: String? = nil, reverse: Bool = false, limit: UInt32? = nil, cursor: String? = nil) {
47
+ self.start = start
48
+ self.reverse = reverse
49
+ self.limit = limit
50
+ self.cursor = cursor
51
+ }
52
+ }
53
+
54
+ /// One key and value in a ``StatePage``.
55
+ public struct StateEntry: Sendable, Equatable {
56
+ /// The full key.
57
+ public var key: String
58
+ /// The stored text.
59
+ public var value: String
60
+ /// Creates an entry.
61
+ public init(key: String, value: String) { self.key = key; self.value = value }
62
+ }
63
+
64
+ /// One page of ``StateStore/list(_:_:)``.
65
+ public struct StatePage: Sendable, Equatable {
66
+ /// The entries, in the requested order, no more than the limit.
67
+ public var entries: [StateEntry]
68
+ /// Opaque cursor to continue strictly past this page; `nil` when the range is exhausted. A page with a cursor
69
+ /// holds at least one entry; a short page can still have one.
70
+ public var nextCursor: String?
71
+ /// Creates a page.
72
+ public init(entries: [StateEntry], nextCursor: String? = nil) {
73
+ self.entries = entries
74
+ self.nextCursor = nextCursor
75
+ }
76
+ }
77
+
78
+ func validateStateBatch(_ ops: [StateOp], _ condition: StateCondition) throws {
79
+ try validateStateKey(condition.key)
80
+ _ = try storageVersion(condition.version)
81
+ guard !ops.isEmpty else { throw stateBatchError() }
82
+ var keys: Set<String> = []
83
+ for op in ops {
84
+ try validateStateKey(op.key)
85
+ guard keys.insert(op.key).inserted else { throw stateBatchError() }
86
+ }
87
+ }
88
+
89
+ func validateStateKey(_ key: String) throws {
90
+ guard PlatformStorage.valid(key) else { throw stateBatchError() }
91
+ }
92
+
93
+ private func stateBatchError() -> LegacyCrocheError { LegacyCrocheError("invalid_configuration", "Invalid StateStore batch or list range.") }
94
+
95
+ /// State keys are ASCII, so the database's BINARY collation matches UTF-8 order.
96
+ struct StateRange {
97
+ private struct Cursor: Codable {
98
+ let prefix: String
99
+ let start: String?
100
+ let reverse: Bool
101
+ let after: String
102
+ }
103
+
104
+ private let prefix: String
105
+ private let options: StateListOptions
106
+ let lower: String
107
+ let upper: String
108
+ let after: String
109
+ let limit: Int
110
+ var reverse: Bool { options.reverse }
111
+
112
+ // The two key bounds of this page (HLD storage, "Range reads"). A cursor replaces a bound.
113
+ // Written as a third predicate it makes SQLite seek to the range start and filter every
114
+ // earlier page again.
115
+ private var resumed: Bool { options.cursor != nil }
116
+ /// Lower bound: exclusive when an ascending walk resumes after its cursor, else inclusive.
117
+ var from: String { !reverse && resumed ? after : lower }
118
+ var fromExclusive: Bool { !reverse && resumed }
119
+ /// Upper bound, always exclusive: the cursor when a descending walk resumes.
120
+ var to: String { reverse && resumed ? after : upper }
121
+ /// The page statement for a `(key, value)` table; binds `from`, `to`, then the row limit.
122
+ func statement(table: String) -> String {
123
+ "SELECT key, value FROM \(table) WHERE key \(fromExclusive ? ">" : ">=") ? AND key < ? "
124
+ + "ORDER BY key \(reverse ? "DESC" : "ASC") LIMIT ?"
125
+ }
126
+
127
+ init(prefix: String, options: StateListOptions) throws {
128
+ if !prefix.isEmpty { try validateStateKey(prefix) }
129
+ if let start = options.start { try validateStateKey(start) }
130
+ guard options.limit != 0 else { throw stateBatchError() }
131
+ self.prefix = prefix
132
+ self.options = options
133
+ lower = max(prefix, options.start ?? prefix)
134
+ if let last = prefix.utf8.last {
135
+ upper = String(decoding: Array(prefix.utf8.dropLast()) + [last + 1], as: UTF8.self)
136
+ } else {
137
+ upper = "\u{7f}"
138
+ }
139
+ limit = Int(min(options.limit ?? 128, 128))
140
+ if let token = options.cursor {
141
+ let cursor = try JSONDecoder().decode(Cursor.self, from: Data(token.utf8))
142
+ try validateStateKey(cursor.after)
143
+ guard cursor.prefix == prefix, cursor.start == options.start, cursor.reverse == options.reverse,
144
+ cursor.after >= lower, cursor.after < upper else { throw stateBatchError() }
145
+ after = cursor.after
146
+ } else {
147
+ after = options.reverse ? upper : ""
148
+ }
149
+ }
150
+
151
+ func page(_ rows: [StateEntry]) throws -> StatePage {
152
+ let entries = Array(rows.prefix(limit))
153
+ guard rows.count > limit, let last = entries.last else { return StatePage(entries: entries) }
154
+ let cursor = Cursor(prefix: prefix, start: options.start, reverse: reverse, after: last.key)
155
+ return StatePage(entries: entries, nextCursor: String(decoding: try JSONEncoder().encode(cursor), as: UTF8.self))
156
+ }
157
+ }
158
+
159
+ extension CoreStateOp {
160
+ func app() -> StateOp {
161
+ switch self {
162
+ case .put(let key, let value): return .put(key: key, value: value)
163
+ case .delete(let key): return .delete(key: key)
164
+ }
165
+ }
166
+ }
167
+
168
+ extension CoreStateCondition {
169
+ func app() -> StateCondition { StateCondition(key: key, version: version) }
170
+ }
171
+
172
+ extension CoreStateListOptions {
173
+ func app() -> StateListOptions { StateListOptions(start: start, reverse: reverse, limit: limit, cursor: cursor) }
174
+ }
175
+
176
+ extension StateCommitResult {
177
+ func core() throws -> CoreStateCommit {
178
+ switch self {
179
+ case .committed(let version): return .committed(version: try storageVersion(version))
180
+ case .conflict: return .conflict
181
+ }
182
+ }
183
+ }
184
+
185
+ extension StatePage {
186
+ func core() -> CoreStatePage {
187
+ CoreStatePage(entries: entries.map { CoreStateEntry(key: $0.key, value: $0.value) }, nextCursor: nextCursor)
188
+ }
189
+ }
@@ -0,0 +1,68 @@
1
+ import Foundation
2
+
3
+ struct VersionedValue: Sendable, Equatable {
4
+ let value: String?, version: String?
5
+ init(value: String?, version: String?) { self.value = value; self.version = version }
6
+ }
7
+ enum WriteOutcome: Sendable, Equatable { case written(version: String?), conflict(version: String?) }
8
+
9
+ func logicalStorageKey(_ key: String) throws -> String {
10
+ guard key.split(separator: "/", omittingEmptySubsequences: true).last != ".p1" else {
11
+ throw CoreStorageFailure.Failure(detail: "Reserved storage sibling")
12
+ }
13
+ return key
14
+ }
15
+ func versionedStorageKey(_ key: String) throws -> String {
16
+ _ = try logicalStorageKey(key)
17
+ guard PlatformStorage.valid(key), key.utf8.count <= 196, !key.split(separator: "/").contains("secret-index") else {
18
+ throw CoreStorageFailure.Failure(detail: "Invalid versioned storage key")
19
+ }
20
+ return key
21
+ }
22
+ func storageVersion(_ token: String?) throws -> String? {
23
+ if let token {
24
+ guard (1...128).contains(token.utf8.count), token.utf8.allSatisfy({ (0x21...0x7e).contains($0) }) else {
25
+ throw CoreStorageFailure.Failure(detail: "Invalid storage version")
26
+ }
27
+ }
28
+ return token
29
+ }
30
+ extension VersionedValue {
31
+ func core() throws -> CoreVersionedValue {
32
+ let token = try storageVersion(version)
33
+ guard (value == nil) == (token == nil) else { throw CoreStorageFailure.Failure(detail: "Unpaired storage value and version") }
34
+ return CoreVersionedValue(value: value, version: token)
35
+ }
36
+ }
37
+ extension WriteOutcome {
38
+ func core(for requestedValue: String?) throws -> CoreWriteOutcome {
39
+ switch self {
40
+ case let .conflict(version): return .conflict(version: try storageVersion(version))
41
+ case let .written(version):
42
+ let token = try storageVersion(version)
43
+ guard (requestedValue == nil) == (token == nil) else { throw CoreStorageFailure.Failure(detail: "Written version does not match request") }
44
+ guard token != "legacy" else { throw CoreStorageFailure.Failure(detail: "Written must return a new storage version") }
45
+ return .written(version: token)
46
+ }
47
+ }
48
+ }
49
+
50
+ func storageNullableString(_ value: Any?) throws -> String? {
51
+ guard let value else { throw CoreStorageFailure.Failure(detail: "Missing storage field") }
52
+ if value is NSNull { return nil }
53
+ guard let text = value as? String else { throw CoreStorageFailure.Failure(detail: "Invalid storage field") }
54
+ return text
55
+ }
56
+ func decodeStorageValue(_ value: Any) throws -> CoreVersionedValue {
57
+ guard let row = value as? [String: Any] else { throw CoreStorageFailure.Failure(detail: "Invalid versioned reply") }
58
+ return try VersionedValue(value: storageNullableString(row["value"]), version: storageNullableString(row["version"])).core()
59
+ }
60
+ func decodeStorageOutcome(_ value: Any, for request: String?) throws -> CoreWriteOutcome {
61
+ guard let row = value as? [String: Any] else { throw CoreStorageFailure.Failure(detail: "Invalid conditional reply") }
62
+ let version = try storageNullableString(row["version"])
63
+ switch row["type"] as? String {
64
+ case "written": return try WriteOutcome.written(version: version).core(for: request)
65
+ case "conflict": return try WriteOutcome.conflict(version: version).core(for: request)
66
+ default: throw CoreStorageFailure.Failure(detail: "Invalid conditional outcome")
67
+ }
68
+ }
@@ -28,38 +28,12 @@ protocol KeyedRuntimeStorage: RuntimeStorage {
28
28
  func remove(entry: String) throws
29
29
  }
30
30
 
31
- /// A RuntimeStorage that also keeps the turn archive (F20.6): every finished turn in full, as
32
- /// JSON lines in entries named `archive<NNNN>` (100 turns each) beside the snapshot. Opt-in and
33
- /// separate from KeyedRuntimeStorage: a storage without it keeps no archive, typed
34
- /// (`archive_unavailable`), and everything else works. The Runtime keeps the rules (segments,
35
- /// the byte bound, the last record per turn); the storage keeps lines:
36
- /// - `appendLine` writes a newline first when the entry does not end with one, and is durable
37
- /// when it returns;
38
- /// - `readLines` returns complete lines only: a torn last line (a crash mid-append) is not one;
39
- /// - `replaceLines` is atomic: after a crash the entry holds every old line or every new one,
40
- /// never a mix and never none; `[]` deletes the entry;
41
- /// - `remove` deletes for real; an absent entry is not an error;
42
- /// - `entries` lists the entries whose names start with `prefix`, with their sizes in bytes.
43
- protocol ArchiveRuntimeStorage: RuntimeStorage {
44
- func appendLine(entry: String, _ line: String) throws
45
- func readLines(entry: String) throws -> [String]
46
- func replaceLines(entry: String, _ lines: [String]) throws
47
- func remove(entry: String) throws
48
- func entries(prefix: String) throws -> [String: Int]
49
- }
50
-
51
31
  /// Private local file storage with a process-safe advisory lock and atomic replacement.
52
- /// Use an application-private directory; snapshots include runtime credentials. Entries are
53
- /// sidecar files beside the snapshot (`<file>.held`), each replaced atomically. The turn archive
54
- /// is sidecars too (`<file>.archive0001`, JSON lines), under the same lock; a segment is rewritten
55
- /// to `<file>.archive0001.tmp-<nonce>` and renamed over it, and stale temporaries are deleted when
56
- /// the storage is acquired.
57
- final class FileRuntimeStorage: KeyedRuntimeStorage, ArchiveRuntimeStorage, @unchecked Sendable {
32
+ /// Use an application-private directory; snapshots include runtime credentials.
33
+ final class FileRuntimeStorage: KeyedRuntimeStorage, @unchecked Sendable {
58
34
  private let url: URL
59
35
  private let mutex = NSLock()
60
36
  private var descriptor: Int32 = -1
61
- /// Runs after a segment's temporary is complete and before the rename (tests inject a crash).
62
- var beforeCommit: ((URL) throws -> Void)?
63
37
  init(url: URL) { self.url = url }
64
38
  func acquire() throws {
65
39
  mutex.lock(); defer { mutex.unlock() }
@@ -71,7 +45,6 @@ final class FileRuntimeStorage: KeyedRuntimeStorage, ArchiveRuntimeStorage, @unc
71
45
  _ = close(fd); throw LegacyCrocheError("store_busy", "Storage is already owned")
72
46
  }
73
47
  descriptor = fd
74
- removeStaleTemporaries()
75
48
  }
76
49
  func load() throws -> JSON {
77
50
  mutex.lock(); defer { mutex.unlock() }
@@ -104,112 +77,13 @@ final class FileRuntimeStorage: KeyedRuntimeStorage, ArchiveRuntimeStorage, @unc
104
77
  guard !entry.isEmpty, entry.allSatisfy({ $0.isASCII && ($0.isLowercase || $0.isNumber) }) else { throw LegacyCrocheError("storage_error", "Invalid storage entry") }
105
78
  return URL(fileURLWithPath: url.path + "." + entry)
106
79
  }
107
- // MARK: The turn archive (F20.6)
108
- func appendLine(entry: String, _ line: String) throws {
109
- mutex.lock(); defer { mutex.unlock() }
110
- let file = try segment(entry)
111
- guard !line.contains("\n") else { throw LegacyCrocheError("storage_error", "An archive line holds no newline") }
112
- let fd = open(file.path, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR)
113
- guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Could not open the archive") }
114
- defer { _ = close(fd) }
115
- var info = stat()
116
- guard fstat(fd, &info) == 0 else { throw LegacyCrocheError("storage_error", "Could not read the archive") }
117
- var bytes = [UInt8]()
118
- if info.st_size > 0 {
119
- var last: UInt8 = 0
120
- guard pread(fd, &last, 1, off_t(info.st_size - 1)) == 1 else { throw LegacyCrocheError("storage_error", "Could not read the archive") }
121
- if last != 0x0a { bytes.append(0x0a) } // a torn line never swallows this record
122
- }
123
- bytes += Array(line.utf8); bytes.append(0x0a)
124
- try Self.writeAll(fd, bytes)
125
- guard fsync(fd) == 0 else { throw LegacyCrocheError("storage_error", "Could not sync the archive") }
126
- }
127
- func readLines(entry: String) throws -> [String] {
128
- mutex.lock(); defer { mutex.unlock() }
129
- let file = try segment(entry)
130
- guard FileManager.default.fileExists(atPath: file.path) else { return [] }
131
- var lines = String(decoding: try Data(contentsOf: file), as: UTF8.self)
132
- .split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
133
- lines.removeLast() // the piece after the last newline: a torn line, or "" when whole
134
- return lines.filter { !$0.isEmpty }
135
- }
136
- func replaceLines(entry: String, _ lines: [String]) throws {
137
- mutex.lock(); defer { mutex.unlock() }
138
- let file = try segment(entry)
139
- guard !lines.isEmpty else { return try unlinkIfPresent(file) }
140
- guard !lines.contains(where: { $0.contains("\n") }) else { throw LegacyCrocheError("storage_error", "An archive line holds no newline") }
141
- // '.' and '-' are outside the entry rule: a temporary is never an entry, `held` or `lock`.
142
- let nonce = UUID().uuidString.lowercased()
143
- let temporary = URL(fileURLWithPath: file.path + ".tmp-" + nonce)
144
- let fd = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR)
145
- guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Could not write the archive") }
146
- do {
147
- defer { _ = close(fd) }
148
- try Self.writeAll(fd, Array(lines.map { $0 + "\n" }.joined().utf8))
149
- guard fsync(fd) == 0 else { throw LegacyCrocheError("storage_error", "Could not sync the archive") }
150
- } catch { _ = unlink(temporary.path); throw error }
151
- do {
152
- try beforeCommit?(temporary)
153
- guard rename(temporary.path, file.path) == 0 else { throw LegacyCrocheError("storage_error", "Could not replace the archive") }
154
- } catch { _ = unlink(temporary.path); throw error }
155
- }
156
80
  func remove(entry: String) throws {
157
81
  mutex.lock(); defer { mutex.unlock() }
158
82
  try unlinkIfPresent(try sidecar(entry))
159
83
  }
160
- func entries(prefix: String) throws -> [String: Int] {
161
- mutex.lock(); defer { mutex.unlock() }
162
- guard descriptor >= 0 else { throw LegacyCrocheError("storage_error", "Storage is not owned") }
163
- var found: [String: Int] = [:]
164
- for (name, path) in try siblings() {
165
- guard Self.isEntry(name), name.hasPrefix(prefix) else { continue }
166
- if let size = try? FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber { found[name] = size.intValue }
167
- }
168
- return found
169
- }
170
- /// Line entries are segments only: the archive's (`archive` and four digits) and the message
171
- /// log's (`log` and six digits, S1). Never the snapshot's own sidecars (`held`) or its lock
172
- /// file (`lock`).
173
- private func segment(_ entry: String) throws -> URL {
174
- guard Self.isSegment(entry) else { throw LegacyCrocheError("storage_error", "Invalid archive entry") }
175
- return try sidecar(entry)
176
- }
177
- private static func isSegment(_ entry: Substring) -> Bool {
178
- let digits = { (n: Int) in entry.dropFirst(n).allSatisfy { $0.isASCII && $0.isNumber } }
179
- return (entry.count == 11 && entry.hasPrefix("archive") && digits(7))
180
- || (entry.count == 9 && entry.hasPrefix("log") && digits(3))
181
- }
182
- private static func isSegment(_ entry: String) -> Bool { isSegment(Substring(entry)) }
183
- private static func isEntry(_ name: String) -> Bool {
184
- !name.isEmpty && name.allSatisfy { $0.isASCII && ($0.isLowercase || $0.isNumber) }
185
- }
186
- /// The files beside the snapshot: `<file>.<suffix>`, as (suffix, path).
187
- private func siblings() throws -> [(String, String)] {
188
- let directory = url.deletingLastPathComponent().path, base = url.lastPathComponent + "."
189
- guard let names = try? FileManager.default.contentsOfDirectory(atPath: directory) else { return [] }
190
- return names.filter { $0.hasPrefix(base) }.map { (String($0.dropFirst(base.count)), directory + "/" + $0) }
191
- }
192
- /// Segment rewrites a crash interrupted (`archive<NNNN>.tmp-<nonce>`, `log<NNNNNN>.tmp-<nonce>`):
193
- /// deleted by the owner.
194
- private func removeStaleTemporaries() {
195
- for (suffix, path) in (try? siblings()) ?? [] {
196
- let parts = suffix.split(separator: ".", maxSplits: 1).map(String.init)
197
- guard parts.count == 2, Self.isSegment(parts[0]), parts[1].hasPrefix("tmp-") else { continue }
198
- _ = unlink(path)
199
- }
200
- }
201
84
  private func unlinkIfPresent(_ file: URL) throws {
202
- if unlink(file.path) != 0 && errno != ENOENT { throw LegacyCrocheError("storage_error", "Could not delete the archive") }
203
- }
204
- private static func writeAll(_ fd: Int32, _ bytes: [UInt8]) throws {
205
- var offset = 0
206
- while offset < bytes.count {
207
- let written = bytes[offset...].withUnsafeBytes { write(fd, $0.baseAddress, $0.count) }
208
- guard written > 0 else { throw LegacyCrocheError("storage_error", "Could not write the archive") }
209
- offset += written
210
- }
85
+ if unlink(file.path) != 0 && errno != ENOENT { throw LegacyCrocheError("storage_error", "Could not delete the storage entry") }
211
86
  }
212
-
213
87
  func remove() throws {
214
88
  try mutex.withLock {
215
89
  guard descriptor >= 0 else { throw LegacyCrocheError("storage_error", "Storage is not owned") }
@@ -223,123 +97,3 @@ final class FileRuntimeStorage: KeyedRuntimeStorage, ArchiveRuntimeStorage, @unc
223
97
  }
224
98
  deinit { release() }
225
99
  }
226
-
227
- // Project namespace, independent of every app-supplied RuntimeStorage. Core mints and
228
- // validates the record; this host only owns its file, atomic replacement and flock.
229
- final class ProjectRecordFiles: @unchecked Sendable {
230
- private let directory: @Sendable () -> URL?
231
- private let mutex = NSLock()
232
- private var descriptors: [String: Int32] = [:]
233
- // Internal host-test fences; configured before the host is handed to Core.
234
- var afterRead: (@Sendable (String, String?) -> Void)?
235
- var beforeLock: (@Sendable (String) -> Void)?
236
- var afterWrite: (@Sendable (String) -> Void)?
237
- init(directory: @escaping @Sendable () -> URL? = ProjectRecordFiles.defaultDirectory) { self.directory = directory }
238
- static var hasPrivateStorage: Bool {
239
- #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) || os(visionOS)
240
- true
241
- #else
242
- false
243
- #endif
244
- }
245
- // Policy seam lets host tests exercise a platform without a default on Apple too.
246
- static func forOpen(projectDirectory: URL?, hasPrivateStorage: Bool = ProjectRecordFiles.hasPrivateStorage) throws -> ProjectRecordFiles {
247
- if hasPrivateStorage {
248
- guard projectDirectory == nil else {
249
- throw LegacyCrocheError("invalid_configuration", "this platform keeps the project record in the app's private storage")
250
- }
251
- return ProjectRecordFiles()
252
- }
253
- guard let projectDirectory else {
254
- throw LegacyCrocheError("storage_error", "This platform requires projectDirectory for the project record")
255
- }
256
- return ProjectRecordFiles(directory: { projectDirectory })
257
- }
258
- static func defaultDirectory() -> URL? {
259
- #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) || os(visionOS)
260
- return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
261
- #else
262
- return nil
263
- #endif
264
- }
265
- static func owns(_ key: String) -> Bool { key.hasPrefix("croche.project.") }
266
- func file(_ key: String) throws -> URL {
267
- let prefix = "croche.project.v1."
268
- let hash = key.dropFirst(prefix.count)
269
- guard key.hasPrefix(prefix), hash.count == 64, hash.allSatisfy({ $0.isASCII && ($0.isNumber || ("a"..."f").contains(String($0))) }) else {
270
- throw LegacyCrocheError("storage_error", "Unsupported project record key")
271
- }
272
- guard let directory = directory() else {
273
- throw LegacyCrocheError("storage_error", "Project record needs app-private storage or an explicit projectDirectory")
274
- }
275
- return directory.appendingPathComponent("croche.project.v1.\(hash).json")
276
- }
277
- private func io<T>(_ body: () throws -> T) throws -> T {
278
- do { return try body() }
279
- catch let error as LegacyCrocheError { throw error }
280
- catch { throw LegacyCrocheError("storage_error", "Could not access the project record directory") }
281
- }
282
- func acquire(_ key: String) throws {
283
- beforeLock?(key)
284
- try io { try mutex.withLock {
285
- guard descriptors[key] == nil else { throw LegacyCrocheError("store_busy", "Project record is already owned") }
286
- let url = try file(key)
287
- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
288
- let fd = open(url.path + ".lock", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
289
- guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Could not open project record lock") }
290
- guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
291
- _ = close(fd); throw LegacyCrocheError("store_busy", "Project record is already owned")
292
- }
293
- descriptors[key] = fd
294
- } }
295
- }
296
- private func ownedFile(_ key: String) throws -> URL {
297
- guard descriptors[key] != nil else { throw LegacyCrocheError("storage_error", "Project record is not owned") }
298
- return try file(key)
299
- }
300
- func read(_ key: String) throws -> String? {
301
- let value = try io { try mutex.withLock {
302
- let url = try ownedFile(key)
303
- guard FileManager.default.fileExists(atPath: url.path) else { return nil as String? }
304
- return try String(contentsOf: url, encoding: .utf8)
305
- } }
306
- afterRead?(key, value)
307
- return value
308
- }
309
- func write(_ key: String, _ value: String) throws {
310
- try io { try mutex.withLock {
311
- let url = try ownedFile(key)
312
- let temporary = URL(fileURLWithPath: url.path + ".tmp-" + UUID().uuidString)
313
- let fd = open(temporary.path, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR)
314
- guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Could not write project record") }
315
- defer { _ = close(fd); _ = unlink(temporary.path) }
316
- let bytes = Array(value.utf8)
317
- var offset = 0
318
- while offset < bytes.count {
319
- let count = bytes[offset...].withUnsafeBytes {
320
- #if canImport(Glibc)
321
- return Glibc.write(fd, $0.baseAddress, $0.count)
322
- #else
323
- return Darwin.write(fd, $0.baseAddress, $0.count)
324
- #endif
325
- }
326
- if count < 0 && errno == EINTR { continue }
327
- guard count > 0 else { throw LegacyCrocheError("storage_error", "Could not write project record") }
328
- offset += count
329
- }
330
- guard fsync(fd) == 0, rename(temporary.path, url.path) == 0 else {
331
- throw LegacyCrocheError("storage_error", "Could not commit project record")
332
- }
333
- } }
334
- afterWrite?(key)
335
- }
336
- func release(_ key: String) {
337
- mutex.withLock {
338
- if let fd = descriptors.removeValue(forKey: key) { _ = flock(fd, LOCK_UN); _ = close(fd) }
339
- }
340
- }
341
- var held: Bool { mutex.withLock { !descriptors.isEmpty } }
342
- deinit {
343
- for fd in descriptors.values { _ = flock(fd, LOCK_UN); _ = close(fd) }
344
- }
345
- }
@@ -9,7 +9,9 @@ import AppKit
9
9
  enum ImageResolution: String, Sendable, Codable { case standard, high }
10
10
  /** One ordered input element. Core owns all validation, defaults and admission. */
11
11
  public enum SendElement: Sendable, Equatable {
12
+ /// Text, with its input kind. `nil` leaves the kind to Core.
12
13
  case text(String, kind: InputKind? = nil)
14
+ /// An image.
13
15
  case image(ImageInput)
14
16
  func wireJSON() throws -> JSON {
15
17
  switch self {
@@ -21,11 +23,15 @@ public enum SendElement: Sendable, Equatable {
21
23
  }
22
24
  }
23
25
  }
24
- /** One image element, supplied by URI or encoded bytes (APP-API ImageInput: uri or bytes, alt). */
26
+ // APP-API ImageInput: uri or bytes, alt.
27
+ /** One image element, supplied by URI or encoded bytes. */
25
28
  public struct ImageInput: Sendable, Equatable {
29
+ /// The image's URI, when it was given by URI.
26
30
  public let uri: String?
27
31
  private let image: Data?
32
+ /// Alternative text for the image.
28
33
  public let alt: String?
34
+ /// An image read from `uri` by the native host.
29
35
  public init(uri: String, alt: String? = nil) {
30
36
  self.uri = uri; image = nil; self.alt = alt
31
37
  }
@@ -67,8 +73,12 @@ public struct ImageInput: Sendable, Equatable {
67
73
  }
68
74
  /** One request; only an absent id asks Core to generate its identity. */
69
75
  public struct SendInput: Sendable, Equatable {
76
+ /// The input id. Sending the last accepted id again with the same content joins or returns that input; with
77
+ /// other content it fails with `idempotency_conflict`.
70
78
  public let id: String?
79
+ /// The ordered text and image elements.
71
80
  public let input: [SendElement]
81
+ /// Creates a send input.
72
82
  public init(id: String? = nil, input: [SendElement]) { self.id = id; self.input = input }
73
83
  func wireJSON() throws -> JSON {
74
84
  var fields: [String: JSON] = ["input": .array(try input.map { try $0.wireJSON() })]
@@ -84,11 +94,18 @@ public struct SendInput: Sendable, Equatable {
84
94
  }
85
95
  }
86
96
  }
97
+ /// Options for one send.
87
98
  public struct SendOptions: Sendable, Equatable {
99
+ /// A structured-output format for the reply, passed to Core unchanged.
88
100
  public let responseFormat: JSON?
101
+ /// Creates send options.
89
102
  public init(responseFormat: JSON? = nil) { self.responseFormat = responseFormat }
90
103
  }
91
- public enum RequestWait: Sendable { case idle }
104
+ /// What `request` waits for beyond the input's terminal result.
105
+ public enum RequestWait: Sendable {
106
+ /// Also wait until the agent is idle.
107
+ case idle
108
+ }
92
109
  struct LegacyReceipt: Sendable, Equatable { public let requestId: String; public let status: LegacyInputStatus; public let seq: Int? }
93
110
  struct LegacyRequestResult: Sendable, Equatable {
94
111
  public let id: String
@@ -98,9 +115,13 @@ struct LegacyRequestResult: Sendable, Equatable {
98
115
  public let legacy: Bool
99
116
  // RequestResult.pending comes with the coordinated TS/Swift/Kotlin consuming-unit change.
100
117
  }
118
+ /// A position in an instance's stream log, for ``SubscribeOptions/after``.
101
119
  public struct Cursor: Sendable, Codable, Hashable {
120
+ /// The log the position belongs to.
102
121
  public let logId: String
122
+ /// The last sequence number seen.
103
123
  public let seq: Int
124
+ /// Creates a cursor.
104
125
  public init(logId: String, seq: Int) { self.logId = logId; self.seq = seq }
105
126
  }
106
127
  struct LegacyStreamError: Sendable, Codable, Equatable { public let code: String; public let message: String; public let poisoned: Bool }
@@ -161,8 +182,17 @@ enum LegacyRuntimeEvent: Sendable, Equatable {
161
182
  }
162
183
  }
163
184
 
185
+ /// Who an input's text comes from.
164
186
  public enum InputKind: Sendable, Codable, Hashable {
165
- case user, appEvent, appState, unknown(String)
187
+ /// Text the user wrote.
188
+ case user
189
+ /// An app event for the agent (`app_event`).
190
+ case appEvent
191
+ /// App state for the agent (`app_state`).
192
+ case appState
193
+ /// A kind this SDK does not know, kept as sent.
194
+ case unknown(String)
195
+ /// Decodes the wire string.
166
196
  public init(from decoder: Decoder) throws {
167
197
  let value = try decoder.singleValueContainer().decode(String.self)
168
198
  switch value {
@@ -172,6 +202,7 @@ public enum InputKind: Sendable, Codable, Hashable {
172
202
  default: self = .unknown(value)
173
203
  }
174
204
  }
205
+ /// Encodes the wire string.
175
206
  public func encode(to encoder: Encoder) throws {
176
207
  var container = encoder.singleValueContainer()
177
208
  switch self {
@@ -334,20 +365,21 @@ func clampedMaintenanceInterval(_ seconds: TimeInterval) throws -> TimeInterval
334
365
  return max(1, seconds)
335
366
  }
336
367
 
368
+ /// Options for `request`.
337
369
  public struct RequestOptions: Sendable {
370
+ /// A structured-output format for the reply, passed to Core unchanged.
338
371
  public var responseFormat: JSON?
372
+ /// `.idle` also waits until the agent is idle; `nil` returns at the input's terminal result.
339
373
  public var wait: RequestWait?
374
+ /// Creates request options.
340
375
  public init(responseFormat: JSON? = nil, wait: RequestWait? = nil) { self.responseFormat = responseFormat; self.wait = wait }
341
376
  }
342
377
  struct LegacySubscribeOptions: Sendable {
343
378
  public var initialMessages: Int?
344
379
  public var after: Cursor?
345
- /// How Core batches `messageDelta`. Nil = omitted: Core applies its platform default. The SDK
346
- /// sets none and passes a value (0 included) to Core unchanged.
347
- public var deltaMs: Int?
348
380
  public var onEvent: @Sendable (LegacyRuntimeEvent) async -> Void
349
- public init(initialMessages: Int? = nil, after: Cursor? = nil, deltaMs: Int? = nil, onEvent: @escaping @Sendable (LegacyRuntimeEvent) async -> Void) {
350
- self.initialMessages = initialMessages; self.after = after; self.deltaMs = deltaMs; self.onEvent = onEvent
381
+ public init(initialMessages: Int? = nil, after: Cursor? = nil, onEvent: @escaping @Sendable (LegacyRuntimeEvent) async -> Void) {
382
+ self.initialMessages = initialMessages; self.after = after; self.onEvent = onEvent
351
383
  }
352
384
  }
353
385
  struct LegacyHistoryOptions: Sendable {