@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,110 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The adapter is the implementation of one capability.
|
|
4
|
+
public protocol Adapter: Sendable {
|
|
5
|
+
/// The capability this adapter implements: `"image"` or `"state"`. `open` refuses any other kind, a second
|
|
6
|
+
/// adapter of the same kind, and an adapter that does not conform to its kind's protocol.
|
|
7
|
+
var kind: String { get }
|
|
8
|
+
}
|
|
9
|
+
/// Decodes and re-encodes images for Core. Without one, images that need preparation are refused as unsupported.
|
|
10
|
+
///
|
|
11
|
+
/// Core keeps the policy: it checks the declared media types and the pixel ceiling, reads the header itself, and checks
|
|
12
|
+
/// `info` against it before calling `resize`.
|
|
13
|
+
public protocol ImageAdapter: Adapter {
|
|
14
|
+
/// What this adapter can read and write. Core re-validates it before each preparation.
|
|
15
|
+
var support: ImageSupport { get }
|
|
16
|
+
/// Find out whether a photo fits before preparing it for the selected model.
|
|
17
|
+
func info(_ bytes: Data) async throws -> ImageInfo
|
|
18
|
+
/// Fit a large photo within the model’s limits while keeping the user’s original.
|
|
19
|
+
func resize(_ bytes: Data, limits: ImageResizeLimits) async throws -> Data
|
|
20
|
+
}
|
|
21
|
+
public extension ImageAdapter {
|
|
22
|
+
/// Always `"image"`.
|
|
23
|
+
var kind: String { "image" }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// The formats an ``ImageAdapter`` handles.
|
|
27
|
+
///
|
|
28
|
+
/// Both lists must be non-empty, distinct, `image/` media types without whitespace; otherwise Core treats the adapter as
|
|
29
|
+
/// unsupported.
|
|
30
|
+
public struct ImageSupport: Sendable, Equatable {
|
|
31
|
+
/// Media types the adapter can decode. A source in any other type is refused as unsupported.
|
|
32
|
+
public var inputMediaTypes: [String]
|
|
33
|
+
/// Media types the adapter can encode. Core asks only for `image/png` and `image/jpeg` from this list, and for JPEG only when the image has no alpha.
|
|
34
|
+
public var outputMediaTypes: [String]
|
|
35
|
+
/// Largest width × height the adapter accepts. Core caps it at 50,000,000 pixels, which is also the default; `0` is invalid.
|
|
36
|
+
public var maxInputPixels: Int?
|
|
37
|
+
/// Declares the adapter's formats and optional pixel limit.
|
|
38
|
+
public init(inputMediaTypes: [String], outputMediaTypes: [String], maxInputPixels: Int? = nil) {
|
|
39
|
+
self.inputMediaTypes = inputMediaTypes; self.outputMediaTypes = outputMediaTypes; self.maxInputPixels = maxInputPixels
|
|
40
|
+
}
|
|
41
|
+
var json: JSON {
|
|
42
|
+
var value: [String: JSON] = ["inputMediaTypes": .array(inputMediaTypes.map(JSON.string)), "outputMediaTypes": .array(outputMediaTypes.map(JSON.string))]
|
|
43
|
+
if let maxInputPixels { value["maxInputPixels"] = .number(Double(maxInputPixels)) }
|
|
44
|
+
return .object(value)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/// Dimensions of the upright, EXIF-applied first frame.
|
|
48
|
+
///
|
|
49
|
+
/// Core rejects the result unless `mediaType` matches the source and the size matches the header, in either orientation.
|
|
50
|
+
public struct ImageInfo: Sendable, Equatable {
|
|
51
|
+
/// Media type of the encoded input.
|
|
52
|
+
public var mediaType: String
|
|
53
|
+
/// Upright width in pixels.
|
|
54
|
+
public var width: Int
|
|
55
|
+
/// Upright height in pixels.
|
|
56
|
+
public var height: Int
|
|
57
|
+
/// Whether the frame has an alpha channel. Core asks for JPEG output only when this is `false`.
|
|
58
|
+
public var hasAlpha: Bool?
|
|
59
|
+
/// Describes one decoded image.
|
|
60
|
+
public init(mediaType: String, width: Int, height: Int, hasAlpha: Bool? = nil) {
|
|
61
|
+
self.mediaType = mediaType; self.width = width; self.height = height; self.hasAlpha = hasAlpha
|
|
62
|
+
}
|
|
63
|
+
var json: JSON {
|
|
64
|
+
var value: [String: JSON] = ["mediaType": .string(mediaType), "width": .number(Double(width)), "height": .number(Double(height))]
|
|
65
|
+
if let hasAlpha { value["hasAlpha"] = .bool(hasAlpha) }
|
|
66
|
+
return .object(value)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/// The target Core gives ``ImageAdapter/resize(_:limits:)``.
|
|
70
|
+
public struct ImageResizeLimits: Sendable, Equatable {
|
|
71
|
+
/// Longest side in pixels, or `nil` for no side limit.
|
|
72
|
+
public var maxSide: Int?
|
|
73
|
+
/// Largest encoded size in bytes.
|
|
74
|
+
public var maxBytes: Int
|
|
75
|
+
/// Allowed output media types (PNG listed before JPEG). Core refuses a result that is larger than `maxBytes` or
|
|
76
|
+
/// in another type.
|
|
77
|
+
public var outputMediaTypes: [String]
|
|
78
|
+
/// Creates resize limits. Core builds these; apps normally only read them.
|
|
79
|
+
public init(maxSide: Int? = nil, maxBytes: Int, outputMediaTypes: [String]) {
|
|
80
|
+
self.maxSide = maxSide; self.maxBytes = maxBytes; self.outputMediaTypes = outputMediaTypes
|
|
81
|
+
}
|
|
82
|
+
init(_ value: JSON) throws {
|
|
83
|
+
guard let bytes = value["maxBytes"].number, let formats = value["outputMediaTypes"].array,
|
|
84
|
+
bytes.isFinite, bytes.rounded() == bytes, bytes >= 0, bytes < Double(Int.max),
|
|
85
|
+
formats.allSatisfy({ $0.string != nil }) else { throw malformed("image resize limits") }
|
|
86
|
+
let side = value["maxSide"].number
|
|
87
|
+
if let side, !side.isFinite || side.rounded() != side || side < 0 || side >= Double(Int.max) { throw malformed("image resize limits") }
|
|
88
|
+
self.init(maxSide: side.map(Int.init), maxBytes: Int(bytes), outputMediaTypes: formats.compactMap(\.string))
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
struct SelectedAdapters {
|
|
93
|
+
var state: (any StateStore)?
|
|
94
|
+
var image: (any ImageAdapter)?
|
|
95
|
+
}
|
|
96
|
+
func adaptersFor(_ adapters: [any Adapter]?) throws -> SelectedAdapters {
|
|
97
|
+
var selected = SelectedAdapters(), seen = Set<String>()
|
|
98
|
+
for adapter in adapters ?? [] {
|
|
99
|
+
guard ["image", "state"].contains(adapter.kind) else {
|
|
100
|
+
throw CrocheError(code: "invalid_configuration", message: "Unknown adapter kind.", category: .setup)
|
|
101
|
+
}
|
|
102
|
+
guard seen.insert(adapter.kind).inserted else {
|
|
103
|
+
throw CrocheError(code: "invalid_configuration", message: "Duplicate adapter kind: \(adapter.kind).", category: .setup)
|
|
104
|
+
}
|
|
105
|
+
if adapter.kind == "image", let image = adapter as? any ImageAdapter { selected.image = image }
|
|
106
|
+
else if adapter.kind == "state", let state = adapter as? any StateStore { selected.state = state }
|
|
107
|
+
else { throw CrocheError(code: "invalid_configuration", message: "Adapter does not implement its declared kind.", category: .setup) }
|
|
108
|
+
}
|
|
109
|
+
return selected
|
|
110
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// One fact the agent remembers, as listed by ``CrocheAgent/Memory/list(_:)``.
|
|
4
|
+
public struct MemoryItem: Sendable, Equatable {
|
|
5
|
+
/// Core's id for the item; pass it to ``CrocheAgent/Memory/delete(_:)``.
|
|
6
|
+
public let id: String
|
|
7
|
+
/// The remembered text.
|
|
8
|
+
public let text: String
|
|
9
|
+
/// The whole item, including fields this SDK does not read.
|
|
10
|
+
public let fields: JSON
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/// One instance, self-contained.
|
|
14
|
+
public final class CrocheAgent: Sendable {
|
|
15
|
+
let handle: S1HandleOwner<CoreAgent>
|
|
16
|
+
var core: CoreAgent { get throws { try handle.value() } }
|
|
17
|
+
/// The agent id this handle was opened for.
|
|
18
|
+
public let id: String
|
|
19
|
+
/// nil = the default instance.
|
|
20
|
+
public let instance: String?
|
|
21
|
+
init(core: CoreAgent) { self.handle = S1HandleOwner(core); id = core.id(); instance = core.instance() }
|
|
22
|
+
|
|
23
|
+
/// Load an attachment when someone opens it from this conversation.
|
|
24
|
+
public func attachment(_ id: String) async throws -> AttachmentData { let core = try self.core; return try decode(AttachmentData.self, await blocking { try core.attachment(id: id) }) }
|
|
25
|
+
/// Let a user remove a file they no longer want kept with this conversation.
|
|
26
|
+
public func deleteAttachment(_ id: String) async throws { let core = try self.core; try await blocking { try core.deleteAttachment(id: id) } }
|
|
27
|
+
/// Show the files a user can revisit from this conversation.
|
|
28
|
+
public func listAttachments(_ options: ListOptions? = nil) async throws -> Page<Attachment> {
|
|
29
|
+
let core = try self.core, options = options?.optionsJson
|
|
30
|
+
return try page(try await blocking { try core.listAttachments(optionsJson: options) }, "attachment list") { try decode(Attachment.self, text($0)) }
|
|
31
|
+
}
|
|
32
|
+
/// Bring a file from another conversation into this one before sharing it here.
|
|
33
|
+
public func copyAttachment(_ source: AttachmentSource) async throws -> Attachment { let core = try self.core, json = text(source.json); return try decode(Attachment.self, await blocking { try core.copyAttachment(sourceJson: json) }) }
|
|
34
|
+
/// Let the app drop its hold on a file when the user removes it from a draft.
|
|
35
|
+
public func releaseAttachment(_ id: String) async throws { let core = try self.core; try await blocking { try core.releaseAttachment(id: id) } }
|
|
36
|
+
|
|
37
|
+
/// Accept input from chat without making the UI wait for the reply.
|
|
38
|
+
///
|
|
39
|
+
/// Returns when Core has ACCEPTED the input. Cancelling the Task before acceptance = never
|
|
40
|
+
/// queued; after it = `aborted` (the input continues).
|
|
41
|
+
public func send(_ text: String, _ options: SendOptions = SendOptions()) async throws -> SendReceipt {
|
|
42
|
+
try await send(SendInput(input: [.text(text)]), options)
|
|
43
|
+
}
|
|
44
|
+
/// Accept input from chat without making the UI wait for the reply.
|
|
45
|
+
public func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> SendReceipt {
|
|
46
|
+
let core = try self.core, (input, images, options) = try Self.wire(input, options.responseFormat, wait: nil)
|
|
47
|
+
return try Self.receipt(try await cancellable { try core.send(inputJson: input, images: images, optionsJson: options, cancel: $0) })
|
|
48
|
+
}
|
|
49
|
+
/// Core's reply decodes straight into the generated contract type, `error` included.
|
|
50
|
+
static func receipt(_ value: String) throws -> SendReceipt { try decode(SendReceipt.self, value) }
|
|
51
|
+
|
|
52
|
+
/// Wait for an outcome when an app workflow needs to decide what happens next.
|
|
53
|
+
///
|
|
54
|
+
/// Returns when the input is final; with `wait: .idle`, when the agent is idle too.
|
|
55
|
+
public func request(_ text: String, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
|
|
56
|
+
try await request(SendInput(input: [.text(text)]), options)
|
|
57
|
+
}
|
|
58
|
+
/// Wait for an outcome when an app workflow needs to decide what happens next.
|
|
59
|
+
public func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
|
|
60
|
+
let core = try self.core, (input, images, options) = try Self.wire(input, options.responseFormat, wait: options.wait)
|
|
61
|
+
return try Self.requestResult(try await cancellable { try core.request(inputJson: input, images: images, optionsJson: options, cancel: $0) })
|
|
62
|
+
}
|
|
63
|
+
static func requestResult(_ value: String) throws -> RequestResult { try decode(RequestResult.self, value) }
|
|
64
|
+
|
|
65
|
+
/// Byte images ride beside the JSON as owned bytes indexed into `input` (the element is
|
|
66
|
+
/// `{type: image, alt?}`; Core joins the position); never base64. Core sniffs and validates them.
|
|
67
|
+
static func wire(_ input: SendInput, _ responseFormat: JSON?, wait: RequestWait?) throws -> (String, [CoreAttachmentInput], String?) {
|
|
68
|
+
let images = input.imageCaptures().map { CoreAttachmentInput(element: UInt32($0.element), bytes: $0.bytes) }
|
|
69
|
+
var options: [String: JSON] = [:]
|
|
70
|
+
if let responseFormat { options["responseFormat"] = responseFormat }
|
|
71
|
+
if wait == .idle { options["wait"] = .string("idle") }
|
|
72
|
+
return (text(try input.wireJSON()), images, options.isEmpty ? nil : text(.object(options)))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/// Keep a chat screen in step with the agent as messages and tool activity arrive.
|
|
76
|
+
///
|
|
77
|
+
/// `onEvent` runs serially on the main thread; a delivery counts as handled once it returns.
|
|
78
|
+
/// Core's refusal is thrown unchanged, as in every SDK.
|
|
79
|
+
public func subscribe(_ options: SubscribeOptions) throws -> Subscription {
|
|
80
|
+
var selection: [String: JSON] = [:]
|
|
81
|
+
if let initialMessages = options.initialMessages { selection["initialMessages"] = .number(Double(initialMessages)) }
|
|
82
|
+
if let after = options.after { selection["after"] = .object(["logId": .string(after.logId), "seq": .number(Double(after.seq))]) }
|
|
83
|
+
let selectionJson = text(.object(selection))
|
|
84
|
+
do {
|
|
85
|
+
let subscription = Subscription(core: try core.subscribe(selectionJson: selectionJson, eventSink: EventSinkAdapter(options.onEvent)))
|
|
86
|
+
try handle.adopt(subscription.handle)
|
|
87
|
+
return subscription
|
|
88
|
+
}
|
|
89
|
+
catch { throw CrocheError(error) }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/// Let the user stop a reply or withdraw input they no longer want processed.
|
|
93
|
+
///
|
|
94
|
+
/// The one cross-handle cancel; returns once Core has durably recorded it.
|
|
95
|
+
public func cancel(_ id: String? = nil) async throws {
|
|
96
|
+
let core = try self.core
|
|
97
|
+
try await blocking { try core.cancel(inputId: id) }
|
|
98
|
+
}
|
|
99
|
+
/// Let a user clear the conversation they see while keeping the agent available.
|
|
100
|
+
///
|
|
101
|
+
/// Clears the whole conversation. The app empties its list on the `cleared` event.
|
|
102
|
+
public func clearHistory() async throws {
|
|
103
|
+
let core = try self.core
|
|
104
|
+
try await blocking { try core.clearHistory(optionsJson: nil) }
|
|
105
|
+
}
|
|
106
|
+
/// The agent's memory for this instance: list, delete, clear and turn it on or off.
|
|
107
|
+
public var memory: Memory { Memory(handle: handle) }
|
|
108
|
+
|
|
109
|
+
/// Limit an agent to the actions appropriate for the user’s current workflow.
|
|
110
|
+
///
|
|
111
|
+
/// As if `agent()` had opened with this list, from the NEXT turn; may widen past it.
|
|
112
|
+
public func setTools(_ scope: ToolScope) async throws {
|
|
113
|
+
let core = try self.core, scope = text(scope.json(\.json))
|
|
114
|
+
try await blocking { try core.setTools(scopeJson: scope) }
|
|
115
|
+
}
|
|
116
|
+
/// Restore the usual actions after the user leaves a restricted workflow.
|
|
117
|
+
///
|
|
118
|
+
/// Back to `agent()`'s open scope.
|
|
119
|
+
public func resetTools() async throws {
|
|
120
|
+
let core = try self.core
|
|
121
|
+
try await blocking { try core.resetTools() }
|
|
122
|
+
}
|
|
123
|
+
/// Give an agent help material relevant to the screen or workspace the user is in.
|
|
124
|
+
public func setWiki(_ scope: WikiScope) async throws {
|
|
125
|
+
let core = try self.core, scope = text(scope.json(\.json))
|
|
126
|
+
try await blocking { try core.setWiki(scopeJson: scope) }
|
|
127
|
+
}
|
|
128
|
+
/// Restore the usual help material after the user leaves a specialized workspace.
|
|
129
|
+
public func resetWiki() async throws {
|
|
130
|
+
let core = try self.core
|
|
131
|
+
try await blocking { try core.resetWiki() }
|
|
132
|
+
}
|
|
133
|
+
/// Release an agent when the app leaves its conversation and no longer needs the handle.
|
|
134
|
+
public func close() async throws {
|
|
135
|
+
let handle = self.handle
|
|
136
|
+
try await blocking { try handle.shutdown { try $0.shutdown() } }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/// Memory operations for one agent instance. It shares the agent's handle, so it stops working once the agent is closed.
|
|
140
|
+
public struct Memory: Sendable {
|
|
141
|
+
let handle: S1HandleOwner<CoreAgent>
|
|
142
|
+
var core: CoreAgent { get throws { try handle.value() } }
|
|
143
|
+
/// Show the user what the agent remembers so they can review it.
|
|
144
|
+
public func list(_ options: ListOptions? = nil) async throws -> Page<MemoryItem> {
|
|
145
|
+
let core = try self.core, options = options?.optionsJson
|
|
146
|
+
return try page(try await blocking { try core.memoryList(optionsJson: options) }, "memory list") { item in
|
|
147
|
+
guard let id = item["id"].string, let text = item["text"].string else { throw malformed("memory item") }
|
|
148
|
+
return MemoryItem(id: id, text: text, fields: item)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/// Let the user remove one remembered fact without clearing the rest.
|
|
152
|
+
public func delete(_ id: String) async throws {
|
|
153
|
+
let core = try self.core
|
|
154
|
+
try await blocking { try core.memoryDelete(id: id) }
|
|
155
|
+
}
|
|
156
|
+
/// Let the user start over with a clean memory while keeping their conversation.
|
|
157
|
+
public func clear() async throws {
|
|
158
|
+
let core = try self.core
|
|
159
|
+
try await blocking { try core.memoryClear() }
|
|
160
|
+
}
|
|
161
|
+
/// Let the user choose whether the agent uses memory in this conversation.
|
|
162
|
+
public func enabled(_ on: Bool) async throws {
|
|
163
|
+
let core = try self.core
|
|
164
|
+
try await blocking { try core.memoryEnabled(on: on) }
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/// Nested: a top-level `Subscription` collides with Combine's.
|
|
169
|
+
public final class Subscription: Sendable {
|
|
170
|
+
let handle: S1HandleOwner<CoreSubscription>
|
|
171
|
+
var core: CoreSubscription { get throws { try handle.value() } }
|
|
172
|
+
init(core: CoreSubscription) { self.handle = S1HandleOwner(core) }
|
|
173
|
+
/// Load older messages into the same chat view when the user scrolls back.
|
|
174
|
+
///
|
|
175
|
+
/// Older pages, as `page` events on the same `onEvent`.
|
|
176
|
+
public func history(before: Int? = nil, limit: Int) async throws {
|
|
177
|
+
let core = try self.core
|
|
178
|
+
var options: [String: JSON] = ["limit": .number(Double(limit))]
|
|
179
|
+
if let before { options["before"] = .number(Double(before)) }
|
|
180
|
+
let text = text(.object(options))
|
|
181
|
+
try await blocking { try core.history(optionsJson: text) }
|
|
182
|
+
}
|
|
183
|
+
/// Stop routing updates to a chat view that has been dismissed.
|
|
184
|
+
public func close() { try? handle.shutdown { $0.shutdown() } }
|
|
185
|
+
/// `true` once the subscription delivers no more events: after ``close()``, after an `error` or `replaced`
|
|
186
|
+
/// event, or once its agent handle is released.
|
|
187
|
+
public var ended: Bool { (try? handle.value().ended()) ?? true }
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
func decode<T: Decodable>(_ type: T.Type, _ text: String) throws -> T {
|
|
192
|
+
do { return try JSONDecoder().decode(type, from: Data(text.utf8)) }
|
|
193
|
+
catch { throw CrocheError(code: "internal", message: "Core's reply is malformed.", category: .internal) }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/// Core's event delivery. Decodes with the GENERATED reader, posts to the main thread; on THAT
|
|
197
|
+
/// stack, `tryEnter` immediately before the app's handler (false = no entry), then reports how it
|
|
198
|
+
/// finished: `returned`, or `threw` with the thrown value's facts (TS events.ts). Core assigns the
|
|
199
|
+
/// codes (`handler_failed`). No SDK queue, no wait at close: queue and close policy are Core's.
|
|
200
|
+
final class EventSinkAdapter: CoreEventSink, @unchecked Sendable {
|
|
201
|
+
private let onEvent: @Sendable (AgentEvent) async throws -> Void
|
|
202
|
+
init(_ onEvent: @escaping @Sendable (AgentEvent) async throws -> Void) { self.onEvent = onEvent }
|
|
203
|
+
|
|
204
|
+
static let returned = #"{"outcome":"returned"}"#
|
|
205
|
+
/// `{outcome:"threw", error:{name, message, code?}}`: facts only, as TS `thrownFacts`.
|
|
206
|
+
static func threw(_ error: Error) -> String {
|
|
207
|
+
var facts: [String: JSON] = ["name": .string(String(reflecting: type(of: error)))]
|
|
208
|
+
if let error = error as? CrocheError {
|
|
209
|
+
facts["message"] = .string(error.message); facts["code"] = .string(error.code)
|
|
210
|
+
} else {
|
|
211
|
+
facts["message"] = .string("\(error)")
|
|
212
|
+
}
|
|
213
|
+
return (strictText(.object(["outcome": .string("threw"), "error": .object(facts)]))) ?? #"{"outcome":"threw"}"#
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
func deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) throws {
|
|
217
|
+
try deliver(eventJson, delivery)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/// The seam tests drive with a fake gate (Keel 14:40Z); Core's side of the fence is proven in
|
|
221
|
+
/// Rust/WASM with `for_tests`. Returns the main-actor task.
|
|
222
|
+
@discardableResult
|
|
223
|
+
func deliver(_ eventJson: String, _ delivery: any DeliveryGate) throws -> Task<Void, Never> {
|
|
224
|
+
let event: AgentEvent
|
|
225
|
+
do { event = try JSONDecoder().decode(AgentEvent.self, from: Data(eventJson.utf8)) }
|
|
226
|
+
catch { throw MalformedEvent(reason: "\(error)") }
|
|
227
|
+
let onEvent = self.onEvent
|
|
228
|
+
return Task { @MainActor in
|
|
229
|
+
guard delivery.tryEnter() else { return }
|
|
230
|
+
do { try await onEvent(event); delivery.complete(outcomeJson: Self.returned) }
|
|
231
|
+
catch { delivery.complete(outcomeJson: Self.threw(error)) }
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/// A Core event the generated reader cannot read. The sink has NO error codes (Atlas's PAL error
|
|
237
|
+
/// contract): this untyped transport exception reaches Core, which classifies it (`internal`).
|
|
238
|
+
struct MalformedEvent: Error, CustomStringConvertible {
|
|
239
|
+
let reason: String
|
|
240
|
+
var description: String { "Core's event is not an AgentEvent: \(reason)" }
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/// Core's per-delivery fence: entry is checked on the handler's own stack, then the outcome reported.
|
|
244
|
+
protocol DeliveryGate: Sendable {
|
|
245
|
+
func tryEnter() -> Bool
|
|
246
|
+
func complete(outcomeJson: String)
|
|
247
|
+
}
|
|
248
|
+
extension CoreDelivery: DeliveryGate {}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
extension Croche {
|
|
4
|
+
/// The per-user daily spending limit for this Croche's user.
|
|
5
|
+
public var allowance: Allowance { Allowance(handle: handle) }
|
|
6
|
+
|
|
7
|
+
/// This Croche's user's allowance. All validation and admission logic is Core's.
|
|
8
|
+
public struct Allowance: Sendable {
|
|
9
|
+
let handle: S1HandleOwner<CoreCroche>
|
|
10
|
+
var core: CoreCroche { get throws { try handle.value() } }
|
|
11
|
+
// Founder 2026-11-21; the same call as TS/RN `croche.allowance.set` and Kotlin `allowance.set`.
|
|
12
|
+
/// Set this user's allowance: the most credits the runtime lets this user spend per UTC day.
|
|
13
|
+
/// Absolute, it replaces the earlier value; `nil` returns the user to Studio's default. The runtime
|
|
14
|
+
/// counts and enforces it from its own storage; Croche Cloud keeps no per-user ledger.
|
|
15
|
+
public func set(_ limit: Double?) async throws {
|
|
16
|
+
let core = try self.core, input = text(limit.map(JSON.number) ?? .null)
|
|
17
|
+
try await blocking { try core.allowanceSet(limitJson: input) }
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The binding facts Core reports to Cloud with each Runtime (docs/RUNTIME-CLOUD-PROTOCOL.md):
|
|
4
|
+
/// `{sdk, sdk_version, platform}`, passed beside the open JSON, never an OpenOptions member. They
|
|
5
|
+
/// are diagnostic and carry no logic; Core adds its own runtime_version.
|
|
6
|
+
enum BindingFacts {
|
|
7
|
+
/// This package's version. scripts/release-version.mjs sets it with every other SDK version,
|
|
8
|
+
/// and its --check refuses a value that differs from sdk/swift/VERSION.
|
|
9
|
+
static let sdkVersion = "0.7.0"
|
|
10
|
+
static var platform: String {
|
|
11
|
+
#if os(iOS)
|
|
12
|
+
return "ios"
|
|
13
|
+
#elseif os(macOS)
|
|
14
|
+
return "macos"
|
|
15
|
+
#elseif os(Linux)
|
|
16
|
+
return "linux"
|
|
17
|
+
#elseif os(Windows)
|
|
18
|
+
return "windows"
|
|
19
|
+
#elseif os(visionOS)
|
|
20
|
+
return "visionos"
|
|
21
|
+
#elseif os(tvOS)
|
|
22
|
+
return "tvos"
|
|
23
|
+
#elseif os(watchOS)
|
|
24
|
+
return "watchos"
|
|
25
|
+
#else
|
|
26
|
+
return "unknown" // never "server": an unlisted OS is reported as unknown, not guessed
|
|
27
|
+
#endif
|
|
28
|
+
}
|
|
29
|
+
/// `sdk` is "swift", or "react-native" from the RN iOS bridge, which builds these sources.
|
|
30
|
+
static func json(sdk: String = "swift") -> String {
|
|
31
|
+
text(.object(["sdk": .string(sdk), "sdk_version": .string(sdkVersion), "platform": .string(platform)]))
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// The 0.6 App API (docs/APP-API.md) over Core's S1 handle ABI: the module's public names. The
|
|
4
|
+
// legacy engine's facade stays internal (Legacy*) until its last caller, the RN iOS bridge, moves
|
|
5
|
+
// to S1 (Keel 21:58Z). Every value the app gives is passed to Core unchanged as JSON; this layer
|
|
6
|
+
// decides nothing.
|
|
7
|
+
|
|
8
|
+
// The ONE closed set (APP-API), generated from Core's contract; the SDK never derives it.
|
|
9
|
+
/// What the app does about an error. Core attaches a category to every code, and a code outside Core's table
|
|
10
|
+
/// has category `.internal`.
|
|
11
|
+
public typealias ErrorCategory = AppStreamContract.ErrorCategory
|
|
12
|
+
|
|
13
|
+
/// The error every Croche call throws. Core assigns the code and category; the SDK passes them through unchanged.
|
|
14
|
+
///
|
|
15
|
+
/// Errors raised inside the binding itself have code `internal` and category `.internal`.
|
|
16
|
+
public struct CrocheError: Error, Sendable, CustomStringConvertible {
|
|
17
|
+
/// Core's error code, such as `invalid_input` or `rate_limited`.
|
|
18
|
+
public let code: String
|
|
19
|
+
/// Core's human-readable description. Do not parse it: match on `code`.
|
|
20
|
+
public let message: String
|
|
21
|
+
/// The closed category Core attached to the code. An unknown category from Core becomes `.internal`.
|
|
22
|
+
public let category: ErrorCategory
|
|
23
|
+
/// Where in the app's value Core found the fault (a manifest, scope or bind), when it says.
|
|
24
|
+
public let path: String?
|
|
25
|
+
/// Integer seconds to wait before trying again. Present only on the hourly app-paid `rate_limited` refusal.
|
|
26
|
+
public let retryAfter: UInt64?
|
|
27
|
+
init(code: String, message: String, category: ErrorCategory, path: String? = nil, retryAfter: UInt64? = nil) {
|
|
28
|
+
self.code = code; self.message = message; self.category = category; self.path = path; self.retryAfter = retryAfter
|
|
29
|
+
}
|
|
30
|
+
/// Core's carrier, passed through. A category outside the closed set is a Core bug: `internal`.
|
|
31
|
+
init(_ error: CoreApiError) {
|
|
32
|
+
switch error {
|
|
33
|
+
// Core's `detail` is the public message (UniFFI reserves `message`).
|
|
34
|
+
case let .Failure(code, detail, category, path, retryAfter):
|
|
35
|
+
self.init(code: code, message: detail, category: ErrorCategory(rawValue: category) ?? .internal, path: path, retryAfter: retryAfter)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/// Anything else a call threw (the binding's own errors) is code `internal`, literally, category internal (Keel #9).
|
|
39
|
+
init(_ error: Error) {
|
|
40
|
+
if let e = error as? CrocheError { self = e }
|
|
41
|
+
else if let e = error as? CoreApiError { self.init(e) }
|
|
42
|
+
else { self.init(code: "internal", message: "\(error)", category: .internal) }
|
|
43
|
+
}
|
|
44
|
+
/// `code: message`.
|
|
45
|
+
public var description: String { "\(code): \(message)" }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// Core's calls block their thread while the host performs effects: run them on a thread of
|
|
49
|
+
/// their own, never on the cooperative pool or the main thread.
|
|
50
|
+
func blocking<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
|
|
51
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
52
|
+
Thread.detachNewThread {
|
|
53
|
+
Offload.starting?()
|
|
54
|
+
do { continuation.resume(returning: try body()) }
|
|
55
|
+
catch { continuation.resume(throwing: CrocheError(error)) }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// As `blocking`, with a Core token the awaiting Task's cancellation fires (APP-API: cancelling
|
|
61
|
+
/// the Task is Swift's signal). A fresh token even when nothing cancels: Core requires one.
|
|
62
|
+
/// Where the app's async code runs when Core calls it (a tool's execute, a custom StateStore), where
|
|
63
|
+
/// the OS has task executors: GCD threads apart from Swift's cooperative pool, so app code that
|
|
64
|
+
/// blocks its thread never starves the SDK's own work or another call (#342).
|
|
65
|
+
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
|
66
|
+
final class ToolThreads: TaskExecutor, @unchecked Sendable {
|
|
67
|
+
static let shared = ToolThreads()
|
|
68
|
+
private let queue = DispatchQueue(label: "dev.croche.tools", attributes: .concurrent)
|
|
69
|
+
func enqueue(_ job: consuming ExecutorJob) {
|
|
70
|
+
let job = UnownedJob(job), executor = asUnownedTaskExecutor()
|
|
71
|
+
queue.async { job.runSynchronously(on: executor) }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/// Starts the app's async code for a Core callback on `ToolThreads` (the cooperative pool on an
|
|
76
|
+
/// OS without task executors).
|
|
77
|
+
@discardableResult
|
|
78
|
+
func appTask(_ body: @escaping @Sendable () async -> Void) -> Task<Void, Never> {
|
|
79
|
+
if #available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *) {
|
|
80
|
+
return Task(executorPreference: ToolThreads.shared) { await body() }
|
|
81
|
+
}
|
|
82
|
+
return Task { await body() }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/// A Core call that hands back an OWNER (an open Croche, an agent). Cancelling the caller's Task
|
|
86
|
+
/// resumes the caller at once with `cancelled`; Core has no token for these calls, so the call
|
|
87
|
+
/// finishes on its own thread, and an owner that arrives after the cancellation is shut down
|
|
88
|
+
/// there (`discard`), never leaked holding its store or instance lock (Keel ruling #4).
|
|
89
|
+
func owner<T: Sendable>(_ body: @escaping @Sendable () throws -> T, discard: @escaping @Sendable (T) -> Void) async throws -> T {
|
|
90
|
+
let pending = Pending<T>()
|
|
91
|
+
return try await withTaskCancellationHandler {
|
|
92
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
93
|
+
guard pending.wait(continuation) else { return }
|
|
94
|
+
Thread.detachNewThread {
|
|
95
|
+
Offload.starting?()
|
|
96
|
+
let result = Result { try body() }.mapError { CrocheError($0) as Error }
|
|
97
|
+
if !pending.finish(result), case .success(let value) = result { discard(value) }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
} onCancel: { pending.cancel() }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// One caller's wait: whichever of the result and the cancellation comes first resumes it.
|
|
104
|
+
private final class Pending<T: Sendable>: @unchecked Sendable {
|
|
105
|
+
private let lock = NSLock()
|
|
106
|
+
private var continuation: CheckedContinuation<T, Error>?
|
|
107
|
+
private var cancelled = false, done = false
|
|
108
|
+
private static var cancellation: CrocheError {
|
|
109
|
+
CrocheError(code: "cancelled", message: "The caller's Task was cancelled.", category: .closed)
|
|
110
|
+
}
|
|
111
|
+
/// false = already cancelled (resumed here); start nothing.
|
|
112
|
+
func wait(_ continuation: CheckedContinuation<T, Error>) -> Bool {
|
|
113
|
+
let cancelled = lock.withLock { () -> Bool in
|
|
114
|
+
if self.cancelled { done = true; return true }
|
|
115
|
+
self.continuation = continuation; return false
|
|
116
|
+
}
|
|
117
|
+
if cancelled { continuation.resume(throwing: Self.cancellation) }
|
|
118
|
+
return !cancelled
|
|
119
|
+
}
|
|
120
|
+
func cancel() {
|
|
121
|
+
let waiting = lock.withLock { () -> CheckedContinuation<T, Error>? in
|
|
122
|
+
cancelled = true
|
|
123
|
+
guard !done, let continuation else { return nil }
|
|
124
|
+
done = true; return continuation
|
|
125
|
+
}
|
|
126
|
+
waiting?.resume(throwing: Self.cancellation)
|
|
127
|
+
}
|
|
128
|
+
/// false = the caller already left: the result is unclaimed.
|
|
129
|
+
func finish(_ result: Result<T, Error>) -> Bool {
|
|
130
|
+
let waiting = lock.withLock { () -> CheckedContinuation<T, Error>? in
|
|
131
|
+
guard !done, let continuation else { return nil }
|
|
132
|
+
done = true; return continuation
|
|
133
|
+
}
|
|
134
|
+
waiting?.resume(with: result)
|
|
135
|
+
return waiting != nil
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
func cancellable<T: Sendable>(_ body: @escaping @Sendable (CancelToken) throws -> T) async throws -> T {
|
|
140
|
+
let token = CancelToken()
|
|
141
|
+
return try await withTaskCancellationHandler {
|
|
142
|
+
try await blocking { try body(token) }
|
|
143
|
+
} onCancel: { token.cancel() }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// The app's value as the text Core reads. A Swift `JSON` cannot hold `undefined`. A non-finite
|
|
147
|
+
/// number has no JSON form: it is written as its bare token (`NaN`, `Infinity`, `-Infinity`), so
|
|
148
|
+
/// the text is not JSON and Core refuses it with its own code and category (Leo 18:40Z). Never
|
|
149
|
+
/// dropped, and no code or category is chosen here.
|
|
150
|
+
func text(_ value: JSON) -> String {
|
|
151
|
+
let mark = "croche-nonfinite-\(UUID().uuidString)"
|
|
152
|
+
let encoder = JSONEncoder()
|
|
153
|
+
encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: mark + "+", negativeInfinity: mark + "-", nan: mark + "n")
|
|
154
|
+
// JSON's cases are strings, numbers, bools, null, arrays and objects: encoding cannot otherwise fail.
|
|
155
|
+
let encoded = String(decoding: (try? encoder.encode(value)) ?? Data("null".utf8), as: UTF8.self)
|
|
156
|
+
guard encoded.contains(mark) else { return encoded }
|
|
157
|
+
return encoded.replacingOccurrences(of: "\"\(mark)+\"", with: "Infinity")
|
|
158
|
+
.replacingOccurrences(of: "\"\(mark)-\"", with: "-Infinity")
|
|
159
|
+
.replacingOccurrences(of: "\"\(mark)n\"", with: "NaN")
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/// A completion fact's JSON text, or nil when it has none (the caller sends its fallback fact).
|
|
163
|
+
func strictText(_ value: JSON) -> String? {
|
|
164
|
+
(try? value.encoded()).map { String(decoding: $0, as: UTF8.self) }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// A Core reply. Unreadable = a Core bug, reported as such.
|
|
168
|
+
func reply(_ text: String) throws -> JSON {
|
|
169
|
+
do { return try JSON(text) } catch { throw CrocheError(code: "internal", message: "Core's reply is not JSON.", category: .internal) }
|
|
170
|
+
}
|