@h1r-ai/croche-react-native 0.5.5 → 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 +90 -451
- package/THIRD-PARTY-NOTICES +906 -14
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
- 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 +44 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
- package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
- 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/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
- 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 +294 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- 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/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -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/package.json +1 -0
- package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
- package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
- package/dist/react-native/src/core-native.d.ts +6 -0
- package/dist/react-native/src/core-native.js +316 -0
- package/dist/react-native/src/core-wire.d.ts +55 -0
- package/dist/react-native/src/core-wire.js +1 -0
- package/dist/react-native/src/native-module.d.ts +8 -0
- package/dist/react-native/src/native-module.js +53 -0
- package/dist/rn-shared-build.json +16 -0
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +91 -0
- package/dist/runtime/src/agent.js +137 -0
- package/dist/runtime/src/app-api.d.ts +572 -0
- package/dist/runtime/src/app-api.js +1 -0
- package/dist/runtime/src/cancel.d.ts +9 -0
- package/dist/runtime/src/cancel.js +27 -0
- 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 +247 -0
- package/dist/runtime/src/core/port.js +1 -0
- 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/core/wasm.d.ts +1 -0
- package/dist/runtime/src/core/wasm.js +2 -0
- package/dist/runtime/src/croche.d.ts +97 -0
- package/dist/runtime/src/croche.js +172 -0
- package/dist/runtime/src/errors.d.ts +33 -0
- package/dist/runtime/src/errors.js +63 -0
- package/dist/runtime/src/events.d.ts +5 -0
- package/dist/runtime/src/events.js +31 -0
- package/dist/runtime/src/generated/app-stream.d.ts +328 -0
- package/dist/runtime/src/generated/app-stream.js +127 -0
- 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 -0
- package/dist/runtime/src/index.native.js +2 -0
- package/dist/runtime/src/json.d.ts +13 -0
- package/dist/runtime/src/json.js +120 -0
- package/dist/runtime/src/native-adapter.d.ts +3 -0
- package/dist/runtime/src/native-adapter.js +30 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +60 -0
- package/dist/runtime/src/pal/platform.d.ts +21 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- 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/rn-entry.d.ts +1 -0
- package/dist/runtime/src/rn-entry.js +4 -0
- package/dist/runtime/src/run-tool.d.ts +33 -0
- package/dist/runtime/src/run-tool.js +7 -0
- package/dist/runtime/src/tools.d.ts +35 -0
- package/dist/runtime/src/tools.js +94 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +98 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +122 -0
- package/ios/CoreWireSupport.swift +286 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +49 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
- 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 +23 -269
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
- 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 +899 -608
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +18 -8
- package/scripts/README.md +11 -0
- package/scripts/build-shared.mjs +46 -0
- package/scripts/build.mjs +11 -0
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +8 -6
- package/src/NativeCrocheRuntime.ts +12 -159
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
- 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 -110
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- 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/StreamHub.kt +0 -227
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
- package/src/index.ts +0 -664
- package/src/project-types.ts +0 -35
- package/src/project.ts +0 -434
- package/src/protocol.ts +0 -28
- package/src/types.ts +0 -9
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(Darwin)
|
|
3
|
+
import Darwin
|
|
4
|
+
#elseif canImport(Glibc)
|
|
5
|
+
import Glibc
|
|
6
|
+
#endif
|
|
7
|
+
|
|
8
|
+
/// Default StateStore, lifetime locks, and the separate file secret transport.
|
|
9
|
+
/// Core owns the keys and the instance scopes used for deletion.
|
|
10
|
+
final class PlatformStorage: @unchecked Sendable {
|
|
11
|
+
private let root: URL
|
|
12
|
+
private let state: PlatformStateStore
|
|
13
|
+
private let guarded = NSLock()
|
|
14
|
+
/// Tests stop a child after real fsync, before publication; unset in ordinary use.
|
|
15
|
+
var beforeReplace: (() -> Void)?
|
|
16
|
+
var beforeStateCommit: (() throws -> Void)? {
|
|
17
|
+
get { state.beforeCommit }
|
|
18
|
+
set { state.beforeCommit = newValue }
|
|
19
|
+
}
|
|
20
|
+
/// Held lock files by lock name. flock is per open file: another handle (or process) on the
|
|
21
|
+
/// same directory contends even inside this process.
|
|
22
|
+
private var held: [String: Int32] = [:]
|
|
23
|
+
|
|
24
|
+
init(directory: URL) {
|
|
25
|
+
let root = directory.appendingPathComponent("kv-v1", isDirectory: true)
|
|
26
|
+
self.root = root
|
|
27
|
+
state = PlatformStateStore(path: root.appendingPathComponent("state.db"))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// Core's portable key grammar; anything else is a Core bug and never reaches the disk.
|
|
31
|
+
static func valid(_ key: String) -> Bool {
|
|
32
|
+
(1...200).contains(key.utf8.count) && key.utf8.allSatisfy { b in
|
|
33
|
+
(b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122) || b == 46 || b == 95 || b == 47 || b == 45
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
private static func hex<S: Sequence>(_ bytes: S) -> String where S.Element == UInt8 {
|
|
37
|
+
bytes.map { String(format: "%02x", $0) }.joined()
|
|
38
|
+
}
|
|
39
|
+
private func path(_ area: String, _ key: String, suffix: String) throws -> URL {
|
|
40
|
+
guard Self.valid(key) else { throw LegacyCrocheError("storage_error", "Invalid storage key.") }
|
|
41
|
+
let bytes = Array(key.utf8), split = min(100, bytes.count)
|
|
42
|
+
return root.appendingPathComponent(area, isDirectory: true)
|
|
43
|
+
.appendingPathComponent(Self.hex(bytes[..<split]), isDirectory: true)
|
|
44
|
+
.appendingPathComponent(Self.hex(bytes[split...]) + suffix)
|
|
45
|
+
}
|
|
46
|
+
private static func decode(_ name: String) -> String? {
|
|
47
|
+
guard name.utf8.count % 2 == 0 else { return nil }
|
|
48
|
+
var bytes: [UInt8] = [], digits = Array(name.utf8)
|
|
49
|
+
var index = 0
|
|
50
|
+
while index < digits.count {
|
|
51
|
+
guard let byte = UInt8(String(decoding: digits[index..<index + 2], as: UTF8.self), radix: 16) else { return nil }
|
|
52
|
+
bytes.append(byte); index += 2
|
|
53
|
+
}
|
|
54
|
+
digits.removeAll()
|
|
55
|
+
guard let key = String(bytes: bytes, encoding: .utf8), valid(key) else { return nil }
|
|
56
|
+
return key
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
func readRaw(_ area: String, _ key: String) throws -> String? {
|
|
60
|
+
let file = try path(area, key, suffix: ".value")
|
|
61
|
+
do { return String(decoding: try Data(contentsOf: file), as: UTF8.self) }
|
|
62
|
+
catch let error as CocoaError where error.code == .fileReadNoSuchFile { return nil }
|
|
63
|
+
catch { throw LegacyCrocheError("storage_error", "Storage read failed.") }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Atomic replace, durable on return: temp file, fsync, rename, then the directory's fsync.
|
|
67
|
+
/// A crash leaves the old value or the new one, never a mix.
|
|
68
|
+
func writeRaw(_ area: String, _ key: String, _ value: String) throws {
|
|
69
|
+
let file = try path(area, key, suffix: ".value"), dir = file.deletingLastPathComponent()
|
|
70
|
+
try ensure(dir)
|
|
71
|
+
let temp = dir.appendingPathComponent(file.lastPathComponent + ".tmp-" + UUID().uuidString)
|
|
72
|
+
let fd = open(temp.path, O_WRONLY | O_CREAT | O_EXCL, 0o600)
|
|
73
|
+
guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Storage write failed.") }
|
|
74
|
+
let bytes = Array(value.utf8)
|
|
75
|
+
var written = 0, ok = true
|
|
76
|
+
while written < bytes.count {
|
|
77
|
+
let n = bytes.withUnsafeBufferPointer { posixWrite(fd, $0.baseAddress! + written, bytes.count - written) }
|
|
78
|
+
if n <= 0 { ok = false; break }
|
|
79
|
+
written += n
|
|
80
|
+
}
|
|
81
|
+
ok = ok && fsync(fd) == 0
|
|
82
|
+
close(fd)
|
|
83
|
+
if ok { beforeReplace?() }
|
|
84
|
+
guard ok, rename(temp.path, file.path) == 0 else {
|
|
85
|
+
unlink(temp.path)
|
|
86
|
+
throw LegacyCrocheError("storage_error", "Storage write failed.")
|
|
87
|
+
}
|
|
88
|
+
try sync(dir)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/// Real deletion; absent is not an error.
|
|
92
|
+
func removeRaw(_ area: String, _ key: String) throws {
|
|
93
|
+
let file = try path(area, key, suffix: ".value")
|
|
94
|
+
if unlink(file.path) != 0 && errno != ENOENT { throw LegacyCrocheError("storage_error", "Storage remove failed.") }
|
|
95
|
+
if FileManager.default.fileExists(atPath: file.deletingLastPathComponent().path) { try sync(file.deletingLastPathComponent()) }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// All and only the keys starting with `prefix`, in any order. Temporary files are not keys.
|
|
99
|
+
func listRaw(_ area: String, _ prefix: String) throws -> [String] {
|
|
100
|
+
let base = root.appendingPathComponent(area, isDirectory: true), files = FileManager.default
|
|
101
|
+
guard let heads = try? files.contentsOfDirectory(atPath: base.path) else { return [] }
|
|
102
|
+
var keys: [String] = []
|
|
103
|
+
for head in heads {
|
|
104
|
+
guard let tails = try? files.contentsOfDirectory(atPath: base.appendingPathComponent(head).path) else { continue }
|
|
105
|
+
for tail in tails where tail.hasSuffix(".value") {
|
|
106
|
+
guard let key = Self.decode(head + tail.dropLast(6)) else { throw LegacyCrocheError("storage_error", "Invalid storage filename.") }
|
|
107
|
+
if key.hasPrefix(prefix) { keys.append(key) }
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return keys
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/// Exclusive across handles and processes; contention is the fact `.held`, never an error
|
|
114
|
+
/// and never a wait.
|
|
115
|
+
@discardableResult func lock(_ name: String) throws -> PalLockOutcome {
|
|
116
|
+
let file = try path("locks", name, suffix: ".lock")
|
|
117
|
+
try ensure(file.deletingLastPathComponent())
|
|
118
|
+
return try guarded.withLock {
|
|
119
|
+
guard held[name] == nil else { return .held }
|
|
120
|
+
let fd = open(file.path, O_RDWR | O_CREAT, 0o600)
|
|
121
|
+
guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Storage lock failed.") }
|
|
122
|
+
guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
|
|
123
|
+
let busy = errno == EWOULDBLOCK
|
|
124
|
+
close(fd)
|
|
125
|
+
if busy { return .held }
|
|
126
|
+
throw LegacyCrocheError("storage_error", "Storage lock failed.")
|
|
127
|
+
}
|
|
128
|
+
held[name] = fd
|
|
129
|
+
return .acquired
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
func unlock(_ name: String) {
|
|
133
|
+
guard let fd = guarded.withLock({ held.removeValue(forKey: name) }) else { return }
|
|
134
|
+
flock(fd, LOCK_UN); close(fd)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
func read(_ area: String, _ key: String) throws -> String? {
|
|
138
|
+
_ = try logicalStorageKey(key)
|
|
139
|
+
return area == "state" ? try state.get(key).value : try readRaw(area, key)
|
|
140
|
+
}
|
|
141
|
+
func write(_ area: String, _ key: String, _ value: String) throws {
|
|
142
|
+
_ = try logicalStorageKey(key)
|
|
143
|
+
if area == "state" { try state.write(key, value) } else { try writeRaw(area, key, value) }
|
|
144
|
+
}
|
|
145
|
+
func remove(_ area: String, _ key: String) throws {
|
|
146
|
+
_ = try logicalStorageKey(key)
|
|
147
|
+
if area == "state" { try state.remove(key) } else { try removeRaw(area, key) }
|
|
148
|
+
}
|
|
149
|
+
func list(_ area: String, _ prefix: String) throws -> [String] {
|
|
150
|
+
_ = try logicalStorageKey(prefix)
|
|
151
|
+
guard area == "state" else { return try listRaw(area, prefix) }
|
|
152
|
+
var keys: [String] = []
|
|
153
|
+
var options = StateListOptions()
|
|
154
|
+
repeat {
|
|
155
|
+
let page = try state.list(prefix, options)
|
|
156
|
+
keys.append(contentsOf: page.entries.map(\.key))
|
|
157
|
+
options.cursor = page.nextCursor
|
|
158
|
+
} while options.cursor != nil
|
|
159
|
+
return keys
|
|
160
|
+
}
|
|
161
|
+
func readVersioned(_ key: String) throws -> VersionedValue {
|
|
162
|
+
try state.get(versionedStorageKey(key))
|
|
163
|
+
}
|
|
164
|
+
func writeIf(_ key: String, _ value: String?, _ expect: String?) throws -> WriteOutcome {
|
|
165
|
+
try state.writeIf(versionedStorageKey(key), value, expect)
|
|
166
|
+
}
|
|
167
|
+
func commitState(_ ops: [StateOp], _ condition: StateCondition) throws -> StateCommitResult {
|
|
168
|
+
try state.commit(ops, condition)
|
|
169
|
+
}
|
|
170
|
+
func listState(_ prefix: String, _ options: StateListOptions) throws -> StatePage {
|
|
171
|
+
try state.list(prefix, options)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
func instancePurgePlan(_ area: String, _ prefix: String) throws -> InstancePayloadPlan {
|
|
175
|
+
let filePlan = try planInstancePayloads(root, area: area, prefix: prefix, sync: { try self.sync($0) })
|
|
176
|
+
guard area == "state" else { return filePlan }
|
|
177
|
+
return InstancePayloadPlan(eraseTemps: filePlan.eraseTemps, durable: filePlan.durable, eraseValues: {
|
|
178
|
+
try filePlan.eraseValues()
|
|
179
|
+
try self.state.purge(prefix)
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
private func ensure(_ dir: URL) throws {
|
|
183
|
+
do { try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) }
|
|
184
|
+
catch { throw LegacyCrocheError("storage_error", "Storage directory failed.") }
|
|
185
|
+
}
|
|
186
|
+
private func sync(_ dir: URL) throws {
|
|
187
|
+
let fd = open(dir.path, O_RDONLY)
|
|
188
|
+
guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Storage sync failed.") }
|
|
189
|
+
defer { close(fd) }
|
|
190
|
+
guard fsync(fd) == 0 else { throw LegacyCrocheError("storage_error", "Storage sync failed.") }
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
#if canImport(Darwin)
|
|
195
|
+
private let posixWrite = Darwin.write
|
|
196
|
+
#else
|
|
197
|
+
private let posixWrite = Glibc.write
|
|
198
|
+
#endif
|
|
199
|
+
|
|
200
|
+
/// Where secrets live: apart from state, never through `read` or `list`.
|
|
201
|
+
protocol PlatformSecrets: Sendable {
|
|
202
|
+
func instancePurgePlan(_ prefix: String) throws -> InstancePayloadPlan
|
|
203
|
+
func read(_ key: String) throws -> String?
|
|
204
|
+
func write(_ key: String, _ value: String) throws
|
|
205
|
+
func remove(_ key: String) throws
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/// Files in their own area: hosts without a Keychain, and Croche's own tests.
|
|
209
|
+
struct FileSecrets: PlatformSecrets {
|
|
210
|
+
let storage: PlatformStorage
|
|
211
|
+
func instancePurgePlan(_ prefix: String) throws -> InstancePayloadPlan { try storage.instancePurgePlan("secrets", prefix) }
|
|
212
|
+
func read(_ key: String) throws -> String? { try storage.read("secrets", key) }
|
|
213
|
+
func write(_ key: String, _ value: String) throws { try storage.write("secrets", key, value) }
|
|
214
|
+
func remove(_ key: String) throws { try storage.remove("secrets", key) }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
#if canImport(Security) && !os(Linux)
|
|
218
|
+
import Security
|
|
219
|
+
|
|
220
|
+
/// One Keychain generic-password item per Core secret key, readable after first unlock on
|
|
221
|
+
/// this device only (never in a backup or on another device).
|
|
222
|
+
struct KeychainSecrets: PlatformSecrets {
|
|
223
|
+
var service = "ai.croche.pal"
|
|
224
|
+
// Instance-local seams keep erasure sensitivity tests out of the real Keychain.
|
|
225
|
+
var deleteItem: @Sendable ([String: Any]) -> OSStatus = { SecItemDelete($0 as CFDictionary) }
|
|
226
|
+
var updateItem: @Sendable ([String: Any], [String: Any]) -> OSStatus = { SecItemUpdate($0 as CFDictionary, $1 as CFDictionary) }
|
|
227
|
+
// Attribute-only query seam; tests supply accounts without touching the real Keychain.
|
|
228
|
+
var listAccounts: @Sendable (String) throws -> [String] = { service in
|
|
229
|
+
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
|
|
230
|
+
kSecReturnAttributes as String: true, kSecMatchLimit as String: kSecMatchLimitAll]
|
|
231
|
+
var result: CFTypeRef?
|
|
232
|
+
let status = SecItemCopyMatching(query as CFDictionary, &result)
|
|
233
|
+
if status == errSecItemNotFound { return [] }
|
|
234
|
+
guard status == errSecSuccess, let items = result as? [[String: Any]] else {
|
|
235
|
+
throw LegacyCrocheError("storage_error", "Keychain enumeration failed.")
|
|
236
|
+
}
|
|
237
|
+
return try items.map { item in
|
|
238
|
+
guard let account = item[kSecAttrAccount as String] as? String else {
|
|
239
|
+
throw LegacyCrocheError("storage_error", "Invalid Keychain account.")
|
|
240
|
+
}
|
|
241
|
+
return account
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
func instancePurgePlan(_ prefix: String) throws -> InstancePayloadPlan {
|
|
245
|
+
guard PlatformStorage.valid(prefix), prefix.count > 1, prefix.hasSuffix("/") else {
|
|
246
|
+
throw LegacyCrocheError("storage_error", "Invalid purge prefix.")
|
|
247
|
+
}
|
|
248
|
+
let keys = try listAccounts(service).filter { $0.hasPrefix(prefix) }
|
|
249
|
+
guard keys.allSatisfy(PlatformStorage.valid) else { throw LegacyCrocheError("storage_error", "Invalid Keychain account.") }
|
|
250
|
+
return InstancePayloadPlan(eraseTemps: {}, durable: {}, eraseValues: { for key in keys { try self.remove(key) } })
|
|
251
|
+
}
|
|
252
|
+
private func query(_ key: String) -> [String: Any] {
|
|
253
|
+
[kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key]
|
|
254
|
+
}
|
|
255
|
+
func read(_ key: String) throws -> String? {
|
|
256
|
+
var lookup = query(key)
|
|
257
|
+
lookup[kSecReturnData as String] = true
|
|
258
|
+
lookup[kSecMatchLimit as String] = kSecMatchLimitOne
|
|
259
|
+
var item: CFTypeRef?
|
|
260
|
+
let status = SecItemCopyMatching(lookup as CFDictionary, &item)
|
|
261
|
+
if status == errSecItemNotFound { return nil }
|
|
262
|
+
guard status == errSecSuccess, let data = item as? Data else { throw LegacyCrocheError("storage_error", "Keychain read failed (\(status)).") }
|
|
263
|
+
return String(decoding: data, as: UTF8.self)
|
|
264
|
+
}
|
|
265
|
+
func write(_ key: String, _ value: String) throws {
|
|
266
|
+
let data = Data(value.utf8)
|
|
267
|
+
let update = updateItem(query(key), [kSecValueData as String: data])
|
|
268
|
+
if update == errSecSuccess { return }
|
|
269
|
+
guard update == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(update)).") }
|
|
270
|
+
var add = query(key)
|
|
271
|
+
add[kSecValueData as String] = data
|
|
272
|
+
add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
|
273
|
+
let status = SecItemAdd(add as CFDictionary, nil)
|
|
274
|
+
guard status == errSecSuccess else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(status)).") }
|
|
275
|
+
}
|
|
276
|
+
func remove(_ key: String) throws {
|
|
277
|
+
let status = deleteItem(query(key))
|
|
278
|
+
guard status == errSecSuccess || status == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain delete failed (\(status)).") }
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
#endif
|
|
@@ -1,271 +1,6 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
public var config: JSON?
|
|
8
|
-
public init(instance: String? = nil, fresh: Bool? = nil, config: JSON? = nil) {
|
|
9
|
-
self.instance = instance; self.fresh = fresh; self.config = config
|
|
10
|
-
}
|
|
11
|
-
var json: JSON {
|
|
12
|
-
var value: [String: JSON] = [:]
|
|
13
|
-
if let instance { value["instance"] = .string(instance) }
|
|
14
|
-
if let fresh { value["fresh"] = .bool(fresh) }
|
|
15
|
-
if let config { value["config"] = config }
|
|
16
|
-
return .object(value)
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
public typealias ProjectToolContext = ToolContext
|
|
21
|
-
public typealias ProjectUsageEvent = JSON
|
|
22
|
-
public typealias RuntimeDebugEvent = JSON
|
|
23
|
-
public typealias MemoryChangedEvent = JSON
|
|
24
|
-
|
|
25
|
-
/// The project-returned agent uses the existing Runtime's port, subscriptions and memory.
|
|
26
|
-
public final class CrocheAgent: Sendable {
|
|
27
|
-
private let core: CoreRuntime
|
|
28
|
-
private let runtime: CrocheRuntime
|
|
29
|
-
private let lifetime = ProjectAgentLifetime()
|
|
30
|
-
private let hub: StreamHub
|
|
31
|
-
public let id: String
|
|
32
|
-
public let instance: String?
|
|
33
|
-
public let created: Bool
|
|
34
|
-
public let logId: String
|
|
35
|
-
init(core: CoreRuntime, runtime: CrocheRuntime, hub: StreamHub) {
|
|
36
|
-
self.hub = hub
|
|
37
|
-
self.core = core; self.runtime = runtime
|
|
38
|
-
id = core.agentId(); instance = core.instance(); created = core.created(); logId = runtime.logId
|
|
39
|
-
}
|
|
40
|
-
public var name: String? { core.name() }
|
|
41
|
-
public var mode: String? { core.mode() }
|
|
42
|
-
public var visibleTools: [String]? { core.visibleTools() }
|
|
43
|
-
public var closed: Bool { lifetime.closed }
|
|
44
|
-
public var memory: CrocheMemory { runtime.memory }
|
|
45
|
-
private func check() throws { if closed { throw CrocheError("closed", "The agent is closed.") } }
|
|
46
|
-
public func setTools(_ visible: [String]?) async throws {
|
|
47
|
-
try check(); let core = self.core
|
|
48
|
-
_ = try await CrocheRuntime.offload { try core.setTools(visible: visible); return true }
|
|
49
|
-
}
|
|
50
|
-
public func setMode(_ mode: String?) async throws {
|
|
51
|
-
try check(); let core = self.core
|
|
52
|
-
_ = try await CrocheRuntime.offload { try core.setMode(mode: mode); return true }
|
|
53
|
-
}
|
|
54
|
-
public func sync() async throws { try check(); _ = try await runtime.sync() }
|
|
55
|
-
public func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> Receipt {
|
|
56
|
-
try check(); return try await runtime.send(input, options: options)
|
|
57
|
-
}
|
|
58
|
-
public func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
|
|
59
|
-
try check()
|
|
60
|
-
let result = try await runtime.request(input, options: SendOptions(responseFormat: options.responseFormat), wait: options.wait)
|
|
61
|
-
try? await runtime.refreshMemory()
|
|
62
|
-
return result
|
|
63
|
-
}
|
|
64
|
-
public func subscribe(_ options: SubscribeOptions) -> AgentSubscription { hub.subscribe(options) }
|
|
65
|
-
public func history(_ options: HistoryOptions) async throws {
|
|
66
|
-
try check(); try await runtime.history(before: options.before, limit: options.limit)
|
|
67
|
-
}
|
|
68
|
-
public func cancel(_ id: String? = nil) async throws {
|
|
69
|
-
try check()
|
|
70
|
-
if let id { try await runtime.cancel(id) }
|
|
71
|
-
else {
|
|
72
|
-
let core = self.core
|
|
73
|
-
_ = try await CrocheRuntime.offload { core.cancelTurn(); return true }
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
public func clearHistory() async throws { try check(); try await runtime.clearHistory(); try? await runtime.refreshMemory() }
|
|
77
|
-
public func close() async throws {
|
|
78
|
-
let task = lifetime.close { try await self.runtime.close() }
|
|
79
|
-
try await task.value
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
private final class ProjectAgentLifetime: @unchecked Sendable {
|
|
84
|
-
private let lock = NSLock()
|
|
85
|
-
private var closing: Task<Void, Error>?
|
|
86
|
-
var closed: Bool { lock.withLock { closing != nil } }
|
|
87
|
-
func close(_ body: @escaping @Sendable () async throws -> Void) -> Task<Void, Error> {
|
|
88
|
-
lock.withLock {
|
|
89
|
-
if let closing { return closing }
|
|
90
|
-
let task = Task { try await body() }; closing = task; return task
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// Internal host construction, shared by platform-owned storage and host tests.
|
|
96
|
-
struct NativeProjectOptions: Sendable {
|
|
97
|
-
var host: JSON
|
|
98
|
-
var config: JSON
|
|
99
|
-
var user: String?
|
|
100
|
-
var language: String?
|
|
101
|
-
var handlers: [String: ToolHandler] = [:]
|
|
102
|
-
var streaming = true
|
|
103
|
-
var backgroundSync = true
|
|
104
|
-
var maintenanceIntervalMs = 60_000.0
|
|
105
|
-
var storage: @Sendable (String) -> any RuntimeStorage
|
|
106
|
-
var secretStorage: @Sendable (String) -> any RuntimeSecretStore
|
|
107
|
-
var attestor: (any RuntimeAttestor)?
|
|
108
|
-
var fetch: RuntimeHTTP?
|
|
109
|
-
var timeZone: TimeZone?
|
|
110
|
-
var records: @Sendable () -> ProjectRecordFiles
|
|
111
|
-
var onUsage: (@Sendable (JSON) -> Void)?
|
|
112
|
-
var onDebugEvent: (@Sendable (JSON) -> Void)?
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
final class NativeProjectPals: HostPalFactory, @unchecked Sendable {
|
|
116
|
-
private let lock = NSLock()
|
|
117
|
-
private var hosts: [String: SwiftHost] = [:]
|
|
118
|
-
private var all: [SwiftHost] = []
|
|
119
|
-
let options: NativeProjectOptions
|
|
120
|
-
init(_ options: NativeProjectOptions) { self.options = options }
|
|
121
|
-
func pal(agent: String) -> any HostPal {
|
|
122
|
-
let options = self.options
|
|
123
|
-
let slot = NativeProjectSlot.storageLabel(agent)
|
|
124
|
-
let handlers = options.handlers.mapValues { handler -> ToolHandler in
|
|
125
|
-
{ invocation, context in
|
|
126
|
-
var data = context.data.object ?? [:]
|
|
127
|
-
let issued = data.removeValue(forKey: "userId")?.string
|
|
128
|
-
data["user"] = options.user.map(JSON.string) ?? .null
|
|
129
|
-
data["crocheUserId"] = issued.flatMap { $0.isEmpty ? nil : $0 }.map(JSON.string) ?? .null
|
|
130
|
-
do { return try await handler(invocation, ToolContext(data: .object(data), cancellation: context.cancellation, images: context.images)) }
|
|
131
|
-
catch { throw CrocheError("effect_failed", "The tool handler failed.") }
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
// A fresh host for every request: record and default-agent PALs are separate.
|
|
135
|
-
let host = SwiftHost(storage: options.storage(slot), secrets: options.secretStorage(slot),
|
|
136
|
-
attestor: options.attestor, http: options.fetch, tools: handlers,
|
|
137
|
-
background: options.backgroundSync, projectRecords: options.records())
|
|
138
|
-
host.timeZone = options.timeZone
|
|
139
|
-
lock.withLock { if !NativeProjectSlot.isMaintenance(agent) { hosts[agent] = host }; all.append(host) }
|
|
140
|
-
return host
|
|
141
|
-
}
|
|
142
|
-
func host(_ slot: String) throws -> SwiftHost {
|
|
143
|
-
try lock.withLock {
|
|
144
|
-
guard let host = hosts[slot] else { throw CrocheError("core_error", "Core opened an agent without requesting its host.") }
|
|
145
|
-
return host
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
func stop() {
|
|
149
|
-
let stopped = lock.withLock { () -> [SwiftHost] in
|
|
150
|
-
defer { all.removeAll(); hosts.removeAll() }; return all
|
|
151
|
-
}
|
|
152
|
-
for host in stopped { host.stop(); host.session.close() }
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/// Core owns configuration selection, agent census, instances, locks and project identity.
|
|
157
|
-
public final class Croche: Sendable {
|
|
158
|
-
private let core: CoreProject
|
|
159
|
-
private let pals: NativeProjectPals
|
|
160
|
-
private let session: NativeProjectSession
|
|
161
|
-
private init(core: CoreProject, pals: NativeProjectPals) {
|
|
162
|
-
self.core = core; self.pals = pals; session = NativeProjectSession(core: core, pals: pals)
|
|
163
|
-
}
|
|
164
|
-
public var user: String? { core.user() }
|
|
165
|
-
public var installationId: String? { core.installationId() }
|
|
166
|
-
public var crocheUserId: String? { core.crocheUserId() }
|
|
167
|
-
public var agentIds: [String] { core.agentIds() }
|
|
168
|
-
var applied: JSON { (try? JSON(core.applied())) ?? .null }
|
|
169
|
-
public static func open(_ options: OpenOptions) async throws -> Croche {
|
|
170
|
-
let native = try await CrocheRuntime.offload { try options.native() }
|
|
171
|
-
return try await open(native)
|
|
172
|
-
}
|
|
173
|
-
public static func deleteStore(_ options: OpenOptions, agent: String? = nil) async throws {
|
|
174
|
-
let native = try await CrocheRuntime.offload { try options.native() }
|
|
175
|
-
try await deleteStore(native, agent: agent)
|
|
176
|
-
}
|
|
177
|
-
static func open(_ options: NativeProjectOptions) async throws -> Croche {
|
|
178
|
-
CrocheRuntime.warnIfReleaseBuildCarriesDebugKey(options.host)
|
|
179
|
-
let pals = NativeProjectPals(options)
|
|
180
|
-
let context = ProjectObserverContext(user: options.user)
|
|
181
|
-
var host = options.host
|
|
182
|
-
if let attestor = options.attestor { host["attestationPlatform"] = .string(attestor.platform) }
|
|
183
|
-
let wire = ProjectOpenOptions(host: try projectText(host), user: options.user,
|
|
184
|
-
config: try projectText(options.config), handlers: Array(options.handlers.keys), language: options.language,
|
|
185
|
-
streaming: options.streaming, backgroundSync: options.backgroundSync,
|
|
186
|
-
maintenanceIntervalMs: options.maintenanceIntervalMs)
|
|
187
|
-
do {
|
|
188
|
-
let core = try await CrocheRuntime.offload {
|
|
189
|
-
try CoreProject.open(pals: pals, options: wire, onUsage: options.onUsage.map { listener in EventHook { listener(context.usage($0)) } },
|
|
190
|
-
onDebug: options.onDebugEvent.map(EventHook.init))
|
|
191
|
-
}
|
|
192
|
-
context.attach(core)
|
|
193
|
-
return Croche(core: core, pals: pals)
|
|
194
|
-
} catch { pals.stop(); throw error }
|
|
195
|
-
}
|
|
196
|
-
static func deleteStore(_ options: NativeProjectOptions, agent: String? = nil) async throws {
|
|
197
|
-
let pals = NativeProjectPals(options); defer { pals.stop() }
|
|
198
|
-
let host = try projectText(options.host), config = try projectText(options.config)
|
|
199
|
-
_ = try await CrocheRuntime.offload {
|
|
200
|
-
try ffiProjectDelete(pals: pals, host: host, user: options.user, config: config, agent: agent); return true
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
|
|
204
|
-
try await session.agent(id, options)
|
|
205
|
-
}
|
|
206
|
-
public func close() async throws { try await session.close() }
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
private actor NativeProjectSession {
|
|
210
|
-
private let core: CoreProject
|
|
211
|
-
private let pals: NativeProjectPals
|
|
212
|
-
private var agents: [String: CrocheAgent] = [:]
|
|
213
|
-
private var closing: Task<Void, Error>?
|
|
214
|
-
private var admission: Task<Void, Never>?
|
|
215
|
-
init(core: CoreProject, pals: NativeProjectPals) { self.core = core; self.pals = pals }
|
|
216
|
-
public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
|
|
217
|
-
guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
|
|
218
|
-
let previous = admission
|
|
219
|
-
let task = Task { await previous?.value; return try await self.openAgent(id, options: options) }
|
|
220
|
-
admission = Task { _ = try? await task.value }
|
|
221
|
-
return try await task.value
|
|
222
|
-
}
|
|
223
|
-
private func openAgent(_ id: String?, options: AgentOptions) async throws -> CrocheAgent {
|
|
224
|
-
guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
|
|
225
|
-
let core = self.core, text = try projectText(options.json)
|
|
226
|
-
// Cached calls still go to Core, which checks overrides and admission.
|
|
227
|
-
let handle = try await CrocheRuntime.offload { try core.agentWithOptions(id: id, options: text) }
|
|
228
|
-
guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
|
|
229
|
-
let slot = try handle.instance().map { try projectText(.array([.string(handle.agentId()), .string($0)])) } ?? handle.agentId()
|
|
230
|
-
if let existing = agents[slot], !existing.closed { return existing }
|
|
231
|
-
let runtime = try await CrocheRuntime.adopt(core: handle, host: pals.host(slot))
|
|
232
|
-
let agent = CrocheAgent(core: handle, runtime: runtime, hub: await runtime.subscriptionHub!)
|
|
233
|
-
if closing != nil { try await agent.close(); throw CrocheError("closed", "The project is closed.") }
|
|
234
|
-
agents[slot] = agent
|
|
235
|
-
return agent
|
|
236
|
-
}
|
|
237
|
-
public func close() async throws {
|
|
238
|
-
if let closing { return try await closing.value }
|
|
239
|
-
let core = self.core, pals = self.pals
|
|
240
|
-
let task = Task {
|
|
241
|
-
_ = try await CrocheRuntime.offload { core.close(); return true }
|
|
242
|
-
for agent in self.agents.values { try await agent.close() }
|
|
243
|
-
pals.stop()
|
|
244
|
-
}
|
|
245
|
-
closing = task
|
|
246
|
-
try await task.value
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
private func projectText(_ value: JSON) throws -> String {
|
|
250
|
-
let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
|
|
251
|
-
do { return String(decoding: try encoder.encode(value), as: UTF8.self) }
|
|
252
|
-
catch { throw CrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
|
|
253
|
-
}
|
|
254
|
-
private func ffiProjectDelete(pals: any HostPalFactory, host: String, user: String?, config: String, agent: String?) throws {
|
|
255
|
-
try deleteStore(pals: pals, host: host, user: user, config: config, agent: agent)
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
private final class ProjectObserverContext: @unchecked Sendable {
|
|
259
|
-
private let lock = NSLock()
|
|
260
|
-
private weak var core: CoreProject?
|
|
261
|
-
private let user: String?
|
|
262
|
-
init(user: String?) { self.user = user }
|
|
263
|
-
func attach(_ core: CoreProject) { lock.withLock { self.core = core } }
|
|
264
|
-
func usage(_ event: JSON) -> JSON {
|
|
265
|
-
let core = lock.withLock { self.core }
|
|
266
|
-
var value = event
|
|
267
|
-
value["user"] = (core?.user() ?? user).map(JSON.string) ?? .null
|
|
268
|
-
value["crocheUserId"] = core?.crocheUserId().map(JSON.string) ?? .null
|
|
269
|
-
return value
|
|
270
|
-
}
|
|
271
|
-
}
|
|
3
|
+
// Retained namespaces for the shared fake-port stream and truncate utilities.
|
|
4
|
+
enum LegacyCrocheAgent {}
|
|
5
|
+
enum LegacyCroche {}
|
|
6
|
+
typealias MemoryChangedEvent = JSON
|