@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.
- package/LICENSE +1 -1
- package/README.md +32 -4
- package/THIRD-PARTY-NOTICES +899 -6
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
- package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +1 -0
- package/dist/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +148 -25
- package/dist/react-native/src/core-wire.d.ts +20 -3
- package/dist/rn-shared-build.json +8 -8
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +53 -5
- package/dist/runtime/src/agent.js +69 -7
- package/dist/runtime/src/app-api.d.ts +307 -19
- package/dist/runtime/src/cancel.d.ts +2 -2
- package/dist/runtime/src/cancel.js +7 -4
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +48 -35
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -0
- package/dist/runtime/src/croche.d.ts +64 -9
- package/dist/runtime/src/croche.js +78 -17
- package/dist/runtime/src/errors.d.ts +7 -0
- package/dist/runtime/src/errors.js +15 -1
- package/dist/runtime/src/generated/app-stream.d.ts +155 -1
- package/dist/runtime/src/generated/app-stream.js +7 -4
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -21
- package/dist/runtime/src/index.native.js +2 -8
- package/dist/runtime/src/native-adapter.d.ts +1 -1
- package/dist/runtime/src/native-adapter.js +10 -4
- package/dist/runtime/src/pal/host.d.ts +3 -3
- package/dist/runtime/src/pal/host.js +34 -9
- package/dist/runtime/src/pal/platform.d.ts +11 -6
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -0
- package/dist/runtime/src/tools.d.ts +20 -4
- package/dist/runtime/src/tools.js +31 -7
- package/ios/CoreAgentTransport.swift +2 -2
- package/ios/CoreNativePal.swift +26 -21
- package/ios/CorePlatformTransport.swift +4 -4
- package/ios/CoreWireDispatch.swift +38 -8
- package/ios/CoreWireSupport.swift +179 -4
- package/ios/CrocheRuntimeBridge.swift +1 -1
- package/ios/ProjectPal.swift +15 -12
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
- package/package.json +3 -3
- package/scripts/README.md +1 -1
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +4 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
- package/dist/runtime/src/pal/codec.d.ts +0 -15
- package/dist/runtime/src/pal/codec.js +0 -52
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
|
@@ -108,11 +108,7 @@ final class CancelHook: CancelCallback, @unchecked Sendable {
|
|
|
108
108
|
init(_ cancellation: RuntimeCancellation) { self.cancellation = cancellation }
|
|
109
109
|
func cancelled() { cancellation.cancel() }
|
|
110
110
|
}
|
|
111
|
-
|
|
112
|
-
private let callback: @Sendable (JSON) -> Void
|
|
113
|
-
init(_ callback: @escaping @Sendable (JSON) -> Void) { self.callback = callback }
|
|
114
|
-
func onEvent(event: String) { if let value = try? JSON(event) { callback(value) } }
|
|
115
|
-
}
|
|
111
|
+
|
|
116
112
|
final class ResultBox<T>: @unchecked Sendable {
|
|
117
113
|
private let lock = NSLock()
|
|
118
114
|
private var value: Result<T, Error>?
|
|
@@ -133,400 +129,6 @@ func times(_ entries: JSON) -> [Double] { (entries.array ?? []).compactMap { $0[
|
|
|
133
129
|
/// A delivery's `retryAt` (epoch ms, or an ISO time), or nil.
|
|
134
130
|
func retryAt(_ value: JSON) -> Double? { value.number ?? value.string.flatMap(epochMs) }
|
|
135
131
|
|
|
136
|
-
/// The Swift PAL handed to the Rust Runtime.
|
|
137
|
-
final class SwiftHost: HostPal, @unchecked Sendable {
|
|
138
|
-
// This legacy host has no process-wide OS registrar. Never report success
|
|
139
|
-
// through its per-Runtime scheduler; Core owns replacement and retry policy.
|
|
140
|
-
func registerBackground(identifier: String, wake: CoreBackgroundWake) throws {
|
|
141
|
-
throw CorePalError.Failure(code: "capability_unsupported", detail: "This host has no OS background registrar.")
|
|
142
|
-
}
|
|
143
|
-
/// Where this host runs (a fact Core reads); a React Native host sets `.reactNative`.
|
|
144
|
-
var streamPlatformFact = HostStreamPlatform.other
|
|
145
|
-
private let storage: any RuntimeStorage
|
|
146
|
-
private let projectRecords: ProjectRecordFiles
|
|
147
|
-
// Internal test trace, configured before Core starts; records only delegated store calls.
|
|
148
|
-
var beforeStoreAccess: (@Sendable (String) -> Void)?
|
|
149
|
-
private let secretStore: any RuntimeSecretStore
|
|
150
|
-
private let attestor: (any RuntimeAttestor)?
|
|
151
|
-
private let http: RuntimeHTTP?
|
|
152
|
-
/// The default transport's session, closed with the Runtime.
|
|
153
|
-
let session = RuntimeSession()
|
|
154
|
-
// Accepted tools are never removed: a tool change waits its turn in the Core's queue, and turns queued before it
|
|
155
|
-
// still run the old list. The Core alone decides which commands a turn may call.
|
|
156
|
-
private var handlers: [String: ToolHandler]
|
|
157
|
-
private var staged: [String: Int] = [:], stamp = 0 // names whose only handler is from a call in flight
|
|
158
|
-
private let identity: String
|
|
159
|
-
private let background: Bool
|
|
160
|
-
private let lock = NSLock()
|
|
161
|
-
private weak var core: CoreRuntime?
|
|
162
|
-
private var wakeTarget: Double?
|
|
163
|
-
private var timer: Task<Void, Never>?
|
|
164
|
-
private var stopped = false
|
|
165
|
-
/// This Runtime's attachment to `osScheduler` (attached right after the host is built),
|
|
166
|
-
/// released once: a second stop, or a stale close after the scheduler was attached again for
|
|
167
|
-
/// another Runtime, must not free an identifier someone else holds. Guarded by `lock`.
|
|
168
|
-
private var osAttached = false
|
|
169
|
-
private let osScheduler: (any RuntimeScheduler)?
|
|
170
|
-
var timeZone: TimeZone?
|
|
171
|
-
private var wallClock: @Sendable () -> Double = { Date().timeIntervalSince1970 * 1000 }
|
|
172
|
-
/// The wall clock (epoch ms) the Runtime and its timers read. Tests move it.
|
|
173
|
-
var clock: @Sendable () -> Double {
|
|
174
|
-
get { lock.withLock { wallClock } }
|
|
175
|
-
set { lock.withLock { wallClock = newValue } }
|
|
176
|
-
}
|
|
177
|
-
private var deliverDue: (@Sendable () async -> Void)?
|
|
178
|
-
/// Runs `deliverDue()` on the Runtime when the earliest note's time comes.
|
|
179
|
-
var deliver: (@Sendable () async -> Void)? {
|
|
180
|
-
get { lock.withLock { deliverDue } }
|
|
181
|
-
set { lock.withLock { deliverDue = newValue } }
|
|
182
|
-
}
|
|
183
|
-
private var dueAt: Double?
|
|
184
|
-
private var fired: Double?
|
|
185
|
-
private var dueTimer: Task<Void, Never>?
|
|
186
|
-
|
|
187
|
-
init(storage: any RuntimeStorage, secrets: any RuntimeSecretStore, attestor: (any RuntimeAttestor)?,
|
|
188
|
-
http: RuntimeHTTP?, tools: [String: ToolHandler], background: Bool,
|
|
189
|
-
scheduler: (any RuntimeScheduler)? = nil, projectRecords: ProjectRecordFiles = ProjectRecordFiles()) {
|
|
190
|
-
self.storage = storage; self.projectRecords = projectRecords; secretStore = secrets; self.attestor = attestor; self.http = http
|
|
191
|
-
handlers = tools; self.background = background; osScheduler = scheduler
|
|
192
|
-
identity = "\(ObjectIdentifier(storage as AnyObject).hashValue)"
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
private func host<T>(_ body: () throws -> T) throws -> T {
|
|
196
|
-
do { return try body() } catch { throw LegacyCrocheError(error).ffi }
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// MARK: Images (private Rev 4a PAL). Core owns plans, limits and every URL; ImageIO decodes.
|
|
200
|
-
let images = NativeImagePal()
|
|
201
|
-
func imageCodecAvailable() -> Bool { images.codecAvailable }
|
|
202
|
-
func readImage(request: PalImageReadRequest, cancel: CancelToken) throws -> Data {
|
|
203
|
-
try effect { try images.read(request, cancel) }
|
|
204
|
-
}
|
|
205
|
-
func prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) throws -> PalImageBytes {
|
|
206
|
-
try effect { try images.prepare(source, plan, cancel) }
|
|
207
|
-
}
|
|
208
|
-
func releaseImage(capture: String) { images.release(capture) }
|
|
209
|
-
func decodeImage(bytes: Data, options: PalImageDecodeOptions, cancel: CancelToken) throws -> PalDecodedImage {
|
|
210
|
-
try effect { try images.decode(bytes, options, cancel) }
|
|
211
|
-
}
|
|
212
|
-
func renderImage(request: PalImageRenderRequest, cancel: CancelToken) throws -> Data {
|
|
213
|
-
try effect { try images.render(request, cancel) }
|
|
214
|
-
}
|
|
215
|
-
func releaseDecodedImage(handle: String) { images.releaseDecoded(handle) }
|
|
216
|
-
/// A fact about the host, never a batching choice. A React Native host reports .reactNative.
|
|
217
|
-
func streamPlatform() -> HostStreamPlatform { streamPlatformFact }
|
|
218
|
-
|
|
219
|
-
// MARK: HTTP
|
|
220
|
-
func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws {
|
|
221
|
-
try effect {
|
|
222
|
-
guard request.responseMode == "standard" else {
|
|
223
|
-
throw LegacyCrocheError("capability_unsupported", "Native image inputs are not supported yet")
|
|
224
|
-
}
|
|
225
|
-
if try PlatformHTTP.direct(request, sink: sink, cancel: cancel) { return }
|
|
226
|
-
let transport = http, session = session
|
|
227
|
-
_ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
|
|
228
|
-
if let transport { try await Self.adapt(transport, request, sink, signal) }
|
|
229
|
-
else { try await session.stream(request, into: sink, cancellation: signal) }
|
|
230
|
-
return true
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/// An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
|
|
236
|
-
/// a response, and its stream deltas as server-sent events.
|
|
237
|
-
static func adapt(_ transport: RuntimeHTTP, _ request: PalHttpRequest, _ sink: HttpSink,
|
|
238
|
-
_ signal: RuntimeCancellation) async throws {
|
|
239
|
-
var headers: [String: JSON] = [:]
|
|
240
|
-
for header in request.headers { headers[header.name] = .string(header.value) }
|
|
241
|
-
let effect = JSON.object(["url": .string(request.url), "method": .string(request.method), "headers": .object(headers),
|
|
242
|
-
"body": request.body.map { (try? JSON($0)) ?? .string($0) } ?? .null,
|
|
243
|
-
"timeoutMs": .number(Double(request.timeoutMs))])
|
|
244
|
-
let streaming = StreamStart()
|
|
245
|
-
let reply = try await transport(effect, signal) { data in
|
|
246
|
-
if streaming.begin() {
|
|
247
|
-
sink.head(status: 200, headers: [PalHeader(name: "content-type", value: "text/event-stream")])
|
|
248
|
-
}
|
|
249
|
-
let frame = data.split(separator: "\n", omittingEmptySubsequences: false).map { "data: \($0)\n" }.joined() + "\n"
|
|
250
|
-
_ = sink.chunk(bytes: Data(frame.utf8))
|
|
251
|
-
}
|
|
252
|
-
let status = UInt16(reply["status"].number ?? 0)
|
|
253
|
-
var fields = (reply["headers"].object ?? [:]).compactMap { key, value in value.string.map { PalHeader(name: key, value: $0) } }
|
|
254
|
-
if reply["streamed"] == .bool(true) {
|
|
255
|
-
if streaming.begin() { sink.head(status: status, headers: [PalHeader(name: "content-type", value: "text/event-stream")]) }
|
|
256
|
-
return
|
|
257
|
-
}
|
|
258
|
-
fields.removeAll { $0.name.lowercased() == "content-type" }
|
|
259
|
-
fields.append(PalHeader(name: "content-type", value: "application/json"))
|
|
260
|
-
sink.head(status: status, headers: fields)
|
|
261
|
-
let body = reply["body"] != .null ? try reply["body"].encoded() : Data((reply["raw"].string ?? "").utf8)
|
|
262
|
-
if !body.isEmpty { _ = sink.chunk(bytes: body) }
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// MARK: #820 calls: the same assets, resolver and facts as `PlatformPal`. This per-agent
|
|
266
|
-
// store has no keyed listing; the keyed `PlatformPal` replaces it at Core's cutover.
|
|
267
|
-
func readAsset(path: String) throws -> Data? { try effect { try PlatformAssets.read(path, bundle: .main) } }
|
|
268
|
-
func resolve(host name: String, cancel: CancelToken) throws -> [String] { try effect { try PlatformResolver.resolve(name) } }
|
|
269
|
-
func platformFacts() -> PalPlatformFacts { PalPlatformFacts(targetKind: AppBuildFacts.targetKind, debuggable: AppBuildFacts.debuggable, locale: nil, attestationPlatform: nil, browserFetch: nil) }
|
|
270
|
-
func list(prefix: String) throws -> [String] {
|
|
271
|
-
throw FfiError.Failure(code: "storage_error", message: "This per-agent store keeps no keyed listing.")
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// MARK: Storage
|
|
275
|
-
/// The Core names its snapshot by the key it locks, and other records `<key>.<entry>` (F19's
|
|
276
|
-
/// held sends: `<key>.held`). Each goes to its own place: an entry never replaces the snapshot.
|
|
277
|
-
private var snapshotKey: String? { get { lock.withLock { lockedKey } } set { lock.withLock { lockedKey = newValue } } }
|
|
278
|
-
private var lockedKey: String?
|
|
279
|
-
private func entry(_ key: String) throws -> String? {
|
|
280
|
-
guard let main = snapshotKey, key != main else { return nil }
|
|
281
|
-
guard key.hasPrefix(main + "."), key.count > main.count + 1 else { throw LegacyCrocheError("storage_error", "Unknown storage key") }
|
|
282
|
-
return String(key.dropFirst(main.count + 1))
|
|
283
|
-
}
|
|
284
|
-
func read(key: String) throws -> String? {
|
|
285
|
-
try host {
|
|
286
|
-
if ProjectRecordFiles.owns(key) { return try projectRecords.read(key) }
|
|
287
|
-
beforeStoreAccess?(key)
|
|
288
|
-
let state: JSON
|
|
289
|
-
if let name = try entry(key) {
|
|
290
|
-
// A storage without entries never stored one.
|
|
291
|
-
guard let keyed = storage as? any KeyedRuntimeStorage else { return nil }
|
|
292
|
-
state = try keyed.load(entry: name)
|
|
293
|
-
} else { state = try storage.load() }
|
|
294
|
-
return state == .null ? nil : String(decoding: try state.encoded(), as: UTF8.self)
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
func write(key: String, value: String) throws {
|
|
298
|
-
try host {
|
|
299
|
-
if ProjectRecordFiles.owns(key) { return try projectRecords.write(key, value) }
|
|
300
|
-
beforeStoreAccess?(key)
|
|
301
|
-
guard let name = try entry(key) else { return try storage.save(try JSON(value)) }
|
|
302
|
-
guard let keyed = storage as? any KeyedRuntimeStorage else {
|
|
303
|
-
throw LegacyCrocheError("storage_error", "This RuntimeStorage keeps only its snapshot")
|
|
304
|
-
}
|
|
305
|
-
try keyed.save(entry: name, try JSON(value))
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
func readSecret(key: String) throws -> String? {
|
|
309
|
-
try host { String(decoding: try secretStore.load().encoded(), as: UTF8.self) }
|
|
310
|
-
}
|
|
311
|
-
func writeSecret(key: String, value: String) throws { try host { try secretStore.save(try JSON(value)) } }
|
|
312
|
-
func remove(key: String) throws {
|
|
313
|
-
try host {
|
|
314
|
-
guard !ProjectRecordFiles.owns(key) else { throw LegacyCrocheError("storage_error", "The project record is kept when agent data is removed") }
|
|
315
|
-
beforeStoreAccess?(key)
|
|
316
|
-
if let name = try entry(key) {
|
|
317
|
-
guard let keyed = storage as? any KeyedRuntimeStorage else { return }
|
|
318
|
-
try keyed.remove(entry: name)
|
|
319
|
-
} else { try storage.remove() }
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
func removeSecret(key: String) throws { try host { try secretStore.remove() } }
|
|
323
|
-
/// Contention is the fact `.held` (ARCHITECTURE §2a): the legacy storages' own `store_busy`
|
|
324
|
-
/// becomes that fact here, and every other throw stays a failure.
|
|
325
|
-
@discardableResult func lock(key: String) throws -> PalLockOutcome {
|
|
326
|
-
do {
|
|
327
|
-
try host {
|
|
328
|
-
if ProjectRecordFiles.owns(key) { return try projectRecords.acquire(key) }
|
|
329
|
-
guard !projectRecords.held else { throw LegacyCrocheError("storage_error", "Release the project record lock before taking a store lock") }
|
|
330
|
-
beforeStoreAccess?(key)
|
|
331
|
-
try storage.acquire(); snapshotKey = key
|
|
332
|
-
}
|
|
333
|
-
return .acquired
|
|
334
|
-
} catch FfiError.Failure("store_busy", _) { return .held }
|
|
335
|
-
}
|
|
336
|
-
func unlock(key: String) {
|
|
337
|
-
if ProjectRecordFiles.owns(key) { projectRecords.release(key); return }
|
|
338
|
-
beforeStoreAccess?(key)
|
|
339
|
-
stop(); storage.release(); snapshotKey = nil
|
|
340
|
-
}
|
|
341
|
-
func storeIdentity() -> String { identity }
|
|
342
|
-
|
|
343
|
-
// MARK: The turn archive (F20.6)
|
|
344
|
-
/// The storage's archive, or the typed "no archive": the Runtime then keeps none, and every
|
|
345
|
-
/// turn, clearHistory and memory work as before.
|
|
346
|
-
private func archive() throws -> any ArchiveRuntimeStorage {
|
|
347
|
-
guard let archive = storage as? any ArchiveRuntimeStorage else {
|
|
348
|
-
throw LegacyCrocheError("archive_unavailable", "This host keeps no turn archive.")
|
|
349
|
-
}
|
|
350
|
-
return archive
|
|
351
|
-
}
|
|
352
|
-
func archiveAppendLine(entry: String, line: String) throws { try host { try archive().appendLine(entry: entry, line) } }
|
|
353
|
-
func archiveReadLines(entry: String) throws -> [String] { try host { try archive().readLines(entry: entry) } }
|
|
354
|
-
func archiveReplaceLines(entry: String, lines: [String]) throws { try host { try archive().replaceLines(entry: entry, lines) } }
|
|
355
|
-
func archiveRemove(entry: String) throws { try host { try archive().remove(entry: entry) } }
|
|
356
|
-
func archiveEntries(prefix: String) throws -> [ArchiveEntry] {
|
|
357
|
-
try host { try archive().entries(prefix: prefix).sorted { $0.key < $1.key }.map { ArchiveEntry(entry: $0.key, bytes: UInt64($0.value)) } }
|
|
358
|
-
}
|
|
359
|
-
/// Where the message log goes (S1, rev 4 §17.13): in lines when the storage appends them, in
|
|
360
|
-
/// entries when it keeps entries, else inside the snapshot. Never refused.
|
|
361
|
-
func storageCapability() -> StorageCapability {
|
|
362
|
-
if storage is any ArchiveRuntimeStorage { return .lines }
|
|
363
|
-
if storage is any KeyedRuntimeStorage { return .keyed }
|
|
364
|
-
return .snapshot
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
/// Stages the handlers for names with none yet, or with one only staged by a call still in
|
|
368
|
-
/// flight (a later call wins). Returns the stamp that `unstageTools` needs.
|
|
369
|
-
func stageTools(_ tools: [String: ToolHandler]) -> Int {
|
|
370
|
-
lock.withLock {
|
|
371
|
-
stamp += 1
|
|
372
|
-
for (name, handler) in tools where handlers[name] == nil || staged[name] != nil {
|
|
373
|
-
handlers[name] = handler; staged[name] = stamp
|
|
374
|
-
}
|
|
375
|
-
return stamp
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
/// A refused call: removes what it staged, unless a later call has staged the name since.
|
|
379
|
-
func unstageTools(_ names: Dictionary<String, ToolHandler>.Keys, stamp: Int) {
|
|
380
|
-
lock.withLock { for name in names where staged[name] == stamp { handlers[name] = nil; staged[name] = nil } }
|
|
381
|
-
}
|
|
382
|
-
/// An accepted call: its handlers serve every name it passed.
|
|
383
|
-
func acceptTools(_ tools: [String: ToolHandler]) {
|
|
384
|
-
lock.withLock { for (name, handler) in tools { handlers[name] = handler; staged[name] = nil } }
|
|
385
|
-
}
|
|
386
|
-
/// A project instance's latest successful patched open: its table replaces the old one for future
|
|
387
|
-
/// invocations, as in TypeScript. A call already running keeps the handler it started with.
|
|
388
|
-
func replaceTools(_ tools: [String: ToolHandler]) {
|
|
389
|
-
lock.withLock { handlers = tools; staged.removeAll() }
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
// MARK: Tools and attestation
|
|
393
|
-
func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput {
|
|
394
|
-
let call = try host { try JSON(invocation) }
|
|
395
|
-
guard let name = call["tool"].string, let handler = lock.withLock({ handlers[name] }) else {
|
|
396
|
-
// Nothing ran, and the Runtime may tell the model so (driver.rs NOT_DISPATCHED).
|
|
397
|
-
throw FfiError.Failure(code: "tool_not_dispatched", message: "The host tool is not available")
|
|
398
|
-
}
|
|
399
|
-
var invocation = JSON.object(["tool": call["tool"], "key": call["key"], "args": call["args"]])
|
|
400
|
-
if call["command"] != .null { invocation["command"] = call["command"] }
|
|
401
|
-
let context = call["context"], request = invocation, sink = ImageSink()
|
|
402
|
-
// No deadline here: the Runtime times the call and cancels it (H4). This returns when
|
|
403
|
-
// the handler does, so a stuck one keeps its slot (H1).
|
|
404
|
-
let value = try blockUntilSettled(cancel: cancel) { signal in
|
|
405
|
-
try await handler(request, LegacyToolContext(data: context, cancellation: signal, images: sink))
|
|
406
|
-
}
|
|
407
|
-
// A plain handler's JSON is the value as it was; a `withResult` one's images ride beside
|
|
408
|
-
// it, one sink per call (never shared between concurrent calls).
|
|
409
|
-
return ToolOutput(value: String(decoding: try host { try value.encoded() }, as: UTF8.self),
|
|
410
|
-
images: try sink.take().map(Images.record))
|
|
411
|
-
}
|
|
412
|
-
func attest(request: String, timeoutMs: UInt64) throws -> String {
|
|
413
|
-
try effect {
|
|
414
|
-
guard let attestor else { throw LegacyCrocheError("attestation_unsupported", "This host has no attestor") }
|
|
415
|
-
let call = try JSON(request)
|
|
416
|
-
// A malformed call is Core's bug, not an attestation fact: unlisted, so Core reports internal.
|
|
417
|
-
guard let clientData = call["clientData"].string, let hash = base64URLDecode(call["clientDataHash"].string ?? "") else {
|
|
418
|
-
throw LegacyCrocheError("invalid_abi", "Malformed attest effect")
|
|
419
|
-
}
|
|
420
|
-
let proof = try blockOn(milliseconds: Double(timeoutMs), cancel: nil) { _ -> JSON in
|
|
421
|
-
let proof = try await attestor.attest(clientData: clientData, clientDataHash: hash)
|
|
422
|
-
return .object(["platform": .string(attestor.platform), "token": .string(proof.token),
|
|
423
|
-
"keyId": proof.keyId.map { .string($0) } ?? .null])
|
|
424
|
-
}
|
|
425
|
-
return String(decoding: try proof.encoded(), as: UTF8.self)
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
// MARK: Clock, entropy, timer
|
|
430
|
-
func nowMs() -> Double { clock() }
|
|
431
|
-
func utcOffsetMinutes(atMs: Double) -> Int64 {
|
|
432
|
-
Int64((timeZone ?? TimeZone.current).secondsFromGMT(for: Date(timeIntervalSince1970: atMs / 1000)) / 60)
|
|
433
|
-
}
|
|
434
|
-
func random() -> String { UUID().uuidString }
|
|
435
|
-
func wake(atMs: Double?) {
|
|
436
|
-
lock.withLock { wakeTarget = atMs }
|
|
437
|
-
arm()
|
|
438
|
-
}
|
|
439
|
-
/// The agent's whole pending schedule set (JSON `[{id, at}]`), after each durable change and at
|
|
440
|
-
/// open: a timer while running, and the OS's deferred work (`scheduler`) for after. A refused
|
|
441
|
-
/// registration fails this acknowledgement, which the Core reports as `schedule.degraded`
|
|
442
|
-
/// with its code.
|
|
443
|
-
func schedule(entries: String) throws { try effect { try applySchedule(target(times(try JSON(entries)))) } }
|
|
444
|
-
private var retryFloor: Double?
|
|
445
|
-
/// A failed delivery answered `retryAt`: a note already due waits until then.
|
|
446
|
-
func retryAfter(_ at: Double) { lock.withLock { retryFloor = at } }
|
|
447
|
-
/// When to wake for these notes: the earliest `at`, except that a note already due waits for
|
|
448
|
-
/// a later `retryAt` (a delivery failed).
|
|
449
|
-
func target(_ times: [Double]) -> Double? {
|
|
450
|
-
let now = clock()
|
|
451
|
-
let floor = lock.withLock { retryFloor }.flatMap { $0 > now ? $0 : nil }
|
|
452
|
-
return times.map { at in floor.map { at <= now ? $0 : at } ?? at }.min()
|
|
453
|
-
}
|
|
454
|
-
/// Arms the timer for `at` (nil: nothing pending) and registers it with the OS.
|
|
455
|
-
func applySchedule(_ at: Double?) throws {
|
|
456
|
-
lock.withLock { dueAt = at }
|
|
457
|
-
armDelivery()
|
|
458
|
-
guard let os = osScheduler else { return }
|
|
459
|
-
do {
|
|
460
|
-
if let at { try os.schedule(earliest: Date(timeIntervalSince1970: at / 1000)) } else { os.cancel() }
|
|
461
|
-
} catch let error as LegacyCrocheError { throw error }
|
|
462
|
-
catch { throw LegacyCrocheError("schedule_failed", "The OS scheduler refused the request") }
|
|
463
|
-
}
|
|
464
|
-
/// A delivery is starting: it covers every note due now, so the timer never retries one.
|
|
465
|
-
func attempted() { let now = clock(); lock.withLock { fired = max(fired ?? -.infinity, now) } }
|
|
466
|
-
/// The Runtime is open: a wake it asked for while opening can now fire.
|
|
467
|
-
func attach(_ core: CoreRuntime) { lock.withLock { self.core = core }; arm(); armDelivery() }
|
|
468
|
-
/// The Runtime is opening: attach it to the OS scheduler (which may refuse with
|
|
469
|
-
/// `scheduler_conflict`); `stop` releases that attachment once.
|
|
470
|
-
func attachScheduler() throws {
|
|
471
|
-
guard let os = osScheduler else { return }
|
|
472
|
-
try os.attach()
|
|
473
|
-
lock.withLock { osAttached = true }
|
|
474
|
-
}
|
|
475
|
-
func stop() {
|
|
476
|
-
let release = lock.withLock {
|
|
477
|
-
stopped = true; timer?.cancel(); timer = nil; dueTimer?.cancel(); dueTimer = nil
|
|
478
|
-
defer { osAttached = false }
|
|
479
|
-
return osAttached
|
|
480
|
-
}
|
|
481
|
-
if release { osScheduler?.detach() }
|
|
482
|
-
images.close()
|
|
483
|
-
}
|
|
484
|
-
/// One timer at the earliest note, never firing a delivery before its time (a timer that ends
|
|
485
|
-
/// early re-arms), and at most once per time: a delivery that was cut short leaves its notes
|
|
486
|
-
/// for the next open, foreground or OS run rather than retrying at once.
|
|
487
|
-
private func armDelivery() {
|
|
488
|
-
let now = clock()
|
|
489
|
-
lock.withLock {
|
|
490
|
-
dueTimer?.cancel(); dueTimer = nil
|
|
491
|
-
guard !stopped, core != nil, let target = dueAt, !(fired.map { target <= $0 } ?? false) else { return }
|
|
492
|
-
let delay = max(0, target - now)
|
|
493
|
-
dueTimer = Task.detached { [weak self] in
|
|
494
|
-
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000))
|
|
495
|
-
guard !Task.isCancelled, let self else { return }
|
|
496
|
-
await self.due(target)
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
private func due(_ target: Double) async {
|
|
501
|
-
if clock() < target { armDelivery(); return }
|
|
502
|
-
let run: (@Sendable () async -> Void)? = lock.withLock {
|
|
503
|
-
if stopped { return nil }
|
|
504
|
-
fired = target
|
|
505
|
-
return deliverDue
|
|
506
|
-
}
|
|
507
|
-
await run?()
|
|
508
|
-
}
|
|
509
|
-
private func arm() {
|
|
510
|
-
lock.withLock {
|
|
511
|
-
timer?.cancel(); timer = nil
|
|
512
|
-
guard background, !stopped, let target = wakeTarget, let core else { return }
|
|
513
|
-
timer = Task.detached { [weak core] in
|
|
514
|
-
let delay = max(0, target - Date().timeIntervalSince1970 * 1000)
|
|
515
|
-
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000))
|
|
516
|
-
guard !Task.isCancelled, let core else { return }
|
|
517
|
-
Thread.detachNewThread { core.tick() }
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
private final class StreamStart: @unchecked Sendable {
|
|
524
|
-
private let lock = NSLock()
|
|
525
|
-
private var started = false
|
|
526
|
-
/// True once: the first caller starts the stream.
|
|
527
|
-
func begin() -> Bool { lock.withLock { if started { return false }; started = true; return true } }
|
|
528
|
-
}
|
|
529
|
-
|
|
530
132
|
/// The default transport's connections: one ephemeral URLSession per Runtime, so consecutive
|
|
531
133
|
/// calls (a first launch's challenge, register and sync; a turn's gateway calls) reuse a
|
|
532
134
|
/// connection instead of paying DNS, TCP and TLS again. As before: no cookies, cache, stored
|
|
@@ -114,7 +114,7 @@ final class NativeImagePal: @unchecked Sendable {
|
|
|
114
114
|
|
|
115
115
|
/// Decodes `bytes` (no MIME selects a decoder) into private RGBA8 pixels. `hasAlpha` is true
|
|
116
116
|
/// only when a pixel is not opaque, never because the format could carry alpha.
|
|
117
|
-
func decode(_ bytes: Data, _ options:
|
|
117
|
+
func decode(_ bytes: Data, _ options: ImageDecodeOptions, _ cancel: CancelToken) throws -> DecodedImage {
|
|
118
118
|
try Self.check(cancel)
|
|
119
119
|
#if canImport(ImageIO)
|
|
120
120
|
let image = try Self.decodePixels(bytes, frame: Int(options.frame), orient: options.applyOrientation, cancel)
|
|
@@ -126,14 +126,14 @@ final class NativeImagePal: @unchecked Sendable {
|
|
|
126
126
|
}
|
|
127
127
|
// A cancel that lands after the store still wins; the handle is not leaked.
|
|
128
128
|
if cancel.isCancelled() { releaseDecoded(handle); throw Self.cancelled }
|
|
129
|
-
return
|
|
129
|
+
return DecodedImage(handle: handle, width: UInt32(image.width), height: UInt32(image.height), hasAlpha: hasAlpha)
|
|
130
130
|
#else
|
|
131
131
|
throw LegacyCrocheError("invalid_input", "The image could not be decoded.")
|
|
132
132
|
#endif
|
|
133
133
|
}
|
|
134
134
|
|
|
135
135
|
/// Encodes a decoded handle at exactly `width`×`height`. `quality` (0...1) applies to JPEG.
|
|
136
|
-
func render(_ request:
|
|
136
|
+
func render(_ request: ImageRenderRequest, _ cancel: CancelToken) throws -> Data {
|
|
137
137
|
try Self.check(cancel)
|
|
138
138
|
#if canImport(ImageIO)
|
|
139
139
|
guard let image = lock.withLock({ decoded[request.handle] }),
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Prepared physical I/O only; Core retains exact instance custody and owns scope selection.
|
|
4
|
+
struct InstancePayloadPlan {
|
|
5
|
+
let eraseTemps: () throws -> Void
|
|
6
|
+
let durable: () throws -> Void
|
|
7
|
+
let eraseValues: () throws -> Void
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
func planInstancePayloads(_ root: URL, area: String, prefix: String,
|
|
11
|
+
sync: @escaping (URL) throws -> Void) throws -> InstancePayloadPlan {
|
|
12
|
+
guard PlatformStorage.valid(prefix), prefix.count > 1, prefix.hasSuffix("/") else {
|
|
13
|
+
throw LegacyCrocheError("storage_error", "Invalid purge prefix.")
|
|
14
|
+
}
|
|
15
|
+
let base = root.appendingPathComponent(area, isDirectory: true).standardizedFileURL
|
|
16
|
+
let manager = FileManager.default
|
|
17
|
+
var temps: [URL] = [], values: [URL] = [], directories: Set<URL> = []
|
|
18
|
+
func invalid() -> LegacyCrocheError { LegacyCrocheError("storage_error", "Invalid payload path.") }
|
|
19
|
+
func decode(_ hex: String) throws -> String {
|
|
20
|
+
let digits = Array(hex.utf8)
|
|
21
|
+
guard !digits.isEmpty, digits.count % 2 == 0 else { throw invalid() }
|
|
22
|
+
var bytes: [UInt8] = []
|
|
23
|
+
for i in stride(from: 0, to: digits.count, by: 2) {
|
|
24
|
+
guard let byte = UInt8(String(decoding: digits[i..<i+2], as: UTF8.self), radix: 16) else { throw invalid() }
|
|
25
|
+
bytes.append(byte)
|
|
26
|
+
}
|
|
27
|
+
guard let key = String(bytes: bytes, encoding: .utf8), PlatformStorage.valid(key) else { throw invalid() }
|
|
28
|
+
return key
|
|
29
|
+
}
|
|
30
|
+
let exists: Bool
|
|
31
|
+
do {
|
|
32
|
+
// Check the backend-managed ancestor before following it into either area.
|
|
33
|
+
let rootAttributes = try manager.attributesOfItem(atPath: root.path)
|
|
34
|
+
guard rootAttributes[.type] as? FileAttributeType == .typeDirectory else { throw invalid() }
|
|
35
|
+
let attributes = try manager.attributesOfItem(atPath: base.path)
|
|
36
|
+
guard attributes[.type] as? FileAttributeType == .typeDirectory else { throw invalid() }
|
|
37
|
+
exists = true
|
|
38
|
+
} catch let error as CocoaError where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile {
|
|
39
|
+
exists = false
|
|
40
|
+
}
|
|
41
|
+
if exists {
|
|
42
|
+
let canonicalBase = base.resolvingSymlinksInPath()
|
|
43
|
+
var enumerationError: Error?
|
|
44
|
+
guard let entries = manager.enumerator(at: canonicalBase, includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey], errorHandler: { _, error in enumerationError = error; return false }) else { throw invalid() }
|
|
45
|
+
for case let file as URL in entries {
|
|
46
|
+
let kind = try file.resourceValues(forKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey])
|
|
47
|
+
let components = file.standardizedFileURL.pathComponents
|
|
48
|
+
guard components.starts(with: canonicalBase.pathComponents) else { throw invalid() }
|
|
49
|
+
let parts = Array(components.dropFirst(canonicalBase.pathComponents.count))
|
|
50
|
+
if kind.isDirectory == true, kind.isSymbolicLink != true {
|
|
51
|
+
guard parts.count == 1 else { throw invalid() }
|
|
52
|
+
let head = try decode(parts[0])
|
|
53
|
+
// Include retained empty head dirs so retry durably acknowledges a prior temp unlink.
|
|
54
|
+
if prefix.hasPrefix(head) || head.hasPrefix(prefix) { directories.insert(file) }
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
guard parts.count == 2, let dot = parts[1].firstIndex(of: ".") else { throw invalid() }
|
|
58
|
+
let tail = parts[1], suffix = String(tail[dot...])
|
|
59
|
+
guard parts[0].count <= 200, dot == tail.startIndex || parts[0].count == 200 else { throw invalid() }
|
|
60
|
+
let key = try decode(parts[0] + tail[..<dot])
|
|
61
|
+
guard key.hasPrefix(prefix) else { continue }
|
|
62
|
+
guard kind.isRegularFile == true, kind.isSymbolicLink != true else { throw invalid() }
|
|
63
|
+
if suffix == ".value" { values.append(file) }
|
|
64
|
+
else if suffix.hasPrefix(".value.tmp-"), UUID(uuidString: String(suffix.dropFirst(".value.tmp-".count))) != nil { temps.append(file) }
|
|
65
|
+
else { throw invalid() }
|
|
66
|
+
directories.insert(file.deletingLastPathComponent())
|
|
67
|
+
}
|
|
68
|
+
if let enumerationError { throw enumerationError }
|
|
69
|
+
}
|
|
70
|
+
func erase(_ files: [URL]) throws {
|
|
71
|
+
for file in files {
|
|
72
|
+
do { try manager.removeItem(at: file) }
|
|
73
|
+
catch let error as CocoaError where error.code == .fileNoSuchFile { /* idempotent retry */ }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return InstancePayloadPlan(eraseTemps: { try erase(temps) }, durable: { for directory in directories { try sync(directory) } }, eraseValues: { try erase(values) })
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// Erases every payload file of one instance, not log-floor pruning.
|
|
80
|
+
func eraseInstancePayloads(values: InstancePayloadPlan?, secrets: InstancePayloadPlan?,
|
|
81
|
+
deleteSecret: () throws -> Void = {}, deleteState: () throws -> Void = {}) throws {
|
|
82
|
+
try values?.eraseTemps(); try secrets?.eraseTemps()
|
|
83
|
+
try values?.durable(); try secrets?.durable()
|
|
84
|
+
try deleteSecret()
|
|
85
|
+
try secrets?.eraseValues(); try secrets?.durable()
|
|
86
|
+
try deleteState()
|
|
87
|
+
try values?.eraseValues(); try values?.durable()
|
|
88
|
+
}
|
|
@@ -2,7 +2,19 @@ import Foundation
|
|
|
2
2
|
|
|
3
3
|
/// A value-semantic JSON tree. Core state and machine stay opaque to the host.
|
|
4
4
|
public enum JSON: Codable, Sendable, Hashable {
|
|
5
|
-
|
|
5
|
+
/// JSON `null`.
|
|
6
|
+
case null
|
|
7
|
+
/// A JSON `true` or `false`.
|
|
8
|
+
case bool(Bool)
|
|
9
|
+
/// A JSON number. Every number is held as a `Double`, so integers above 2^53 lose precision.
|
|
10
|
+
case number(Double)
|
|
11
|
+
/// A JSON string.
|
|
12
|
+
case string(String)
|
|
13
|
+
/// A JSON array, in order.
|
|
14
|
+
case array([JSON])
|
|
15
|
+
/// A JSON object. Key order is not preserved.
|
|
16
|
+
case object([String: JSON])
|
|
17
|
+
/// Decodes any JSON value. It tries `null`, then `Bool`, `Double`, `String` and an array, and otherwise decodes an object.
|
|
6
18
|
public init(from decoder: Decoder) throws {
|
|
7
19
|
let c = try decoder.singleValueContainer()
|
|
8
20
|
if c.decodeNil() { self = .null }
|
|
@@ -12,6 +24,7 @@ public enum JSON: Codable, Sendable, Hashable {
|
|
|
12
24
|
else if let v = try? c.decode([JSON].self) { self = .array(v) }
|
|
13
25
|
else { self = .object(try c.decode([String: JSON].self)) }
|
|
14
26
|
}
|
|
27
|
+
/// Encodes the value as the matching JSON value.
|
|
15
28
|
public func encode(to encoder: Encoder) throws {
|
|
16
29
|
var c = encoder.singleValueContainer()
|
|
17
30
|
switch self {
|
|
@@ -23,17 +36,29 @@ public enum JSON: Codable, Sendable, Hashable {
|
|
|
23
36
|
case .object(let v): try c.encode(v)
|
|
24
37
|
}
|
|
25
38
|
}
|
|
39
|
+
/// Parses UTF-8 JSON bytes with `JSONDecoder`. Throws if the bytes are not valid JSON.
|
|
26
40
|
public init(data: Data) throws { self = try JSONDecoder().decode(JSON.self, from: data) }
|
|
41
|
+
/// Parses JSON text. Throws if the text is not valid JSON.
|
|
27
42
|
public init(_ text: String) throws { try self.init(data: Data(text.utf8)) }
|
|
43
|
+
/// Serializes the value to JSON bytes with a default `JSONEncoder`. Object key order is not fixed.
|
|
28
44
|
public func encoded() throws -> Data { try JSONEncoder().encode(self) }
|
|
45
|
+
/// Reads or writes an object member.
|
|
46
|
+
///
|
|
47
|
+
/// Reading returns `.null` when the key is missing or the value is not an object. Writing to a value that
|
|
48
|
+
/// is not an object replaces it with a one-member object.
|
|
29
49
|
public subscript(_ key: String) -> JSON {
|
|
30
50
|
get { if case .object(let v) = self { return v[key] ?? .null }; return .null }
|
|
31
51
|
set { var v = object ?? [:]; v[key] = newValue; self = .object(v) }
|
|
32
52
|
}
|
|
53
|
+
/// The members when the value is an object, otherwise `nil`.
|
|
33
54
|
public var object: [String: JSON]? { if case .object(let v) = self { return v }; return nil }
|
|
55
|
+
/// The elements when the value is an array, otherwise `nil`.
|
|
34
56
|
public var array: [JSON]? { if case .array(let v) = self { return v }; return nil }
|
|
57
|
+
/// The text when the value is a string, otherwise `nil`.
|
|
35
58
|
public var string: String? { if case .string(let v) = self { return v }; return nil }
|
|
59
|
+
/// The number when the value is a number, otherwise `nil`.
|
|
36
60
|
public var number: Double? { if case .number(let v) = self { return v }; return nil }
|
|
61
|
+
/// The flag when the value is a Boolean, otherwise `nil`.
|
|
37
62
|
public var bool: Bool? { if case .bool(let v) = self { return v }; return nil }
|
|
38
63
|
}
|
|
39
64
|
|
|
@@ -52,12 +77,3 @@ func publicStorageIdentity(_ value: JSON) -> JSON {
|
|
|
52
77
|
fields.removeValue(forKey: "defaultStorageKey")
|
|
53
78
|
return .object(fields)
|
|
54
79
|
}
|
|
55
|
-
|
|
56
|
-
// OPEN(Project→Agent): wire this at Croche.open once the reviewed Swift open surface lands.
|
|
57
|
-
// The SDK neither chooses a default nor validates the retention budget; Core owns both.
|
|
58
|
-
func coreOpenConfig(_ config: JSON, retentionBytes: Int?) -> JSON {
|
|
59
|
-
guard let retentionBytes else { return config }
|
|
60
|
-
var bound = config
|
|
61
|
-
bound["retentionBytes"] = .number(Double(retentionBytes))
|
|
62
|
-
return bound
|
|
63
|
-
}
|