@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
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import Foundation
|
|
2
|
-
|
|
3
|
-
public typealias ControlSend = @Sendable (_ input: JSON, _ cancellation: RuntimeCancellation) async throws -> JSON
|
|
4
|
-
public typealias ControlCancel = @Sendable () async -> Bool
|
|
5
|
-
|
|
6
|
-
/// Opt-in attachment of an existing Runtime. This broker token is unrelated to Cloud
|
|
7
|
-
/// developer/project credentials. No Runtime identity or storage is opened here.
|
|
8
|
-
public actor RuntimeControl {
|
|
9
|
-
public nonisolated let runtimeInstanceId: String
|
|
10
|
-
public nonisolated let capabilities = ["status", "history", "send", "cancel", "sync", "budget.get", "budget.set", "tools"]
|
|
11
|
-
private let runtime: CrocheRuntime
|
|
12
|
-
private let url: String
|
|
13
|
-
private let token: String
|
|
14
|
-
private let clientId = UUID().uuidString
|
|
15
|
-
private let http: RuntimeHTTP
|
|
16
|
-
private let sendAdapter: ControlSend?
|
|
17
|
-
private let cancelAdapter: ControlCancel?
|
|
18
|
-
private let onError: (@Sendable (CrocheError) -> Void)?
|
|
19
|
-
private let lifetime = RuntimeCancellation()
|
|
20
|
-
private var loop: Task<Void, Never>?
|
|
21
|
-
private var closed = false
|
|
22
|
-
private var handled = Set<String>()
|
|
23
|
-
private var results: [String: JSON] = [:]
|
|
24
|
-
private var active: [String: RuntimeCancellation] = [:]
|
|
25
|
-
private var tasks: [String: Task<Void, Never>] = [:]
|
|
26
|
-
|
|
27
|
-
private init(runtime: CrocheRuntime, runtimeInstanceId: String, url: String, token: String,
|
|
28
|
-
http: @escaping RuntimeHTTP, send: ControlSend?, cancel: ControlCancel?,
|
|
29
|
-
onError: (@Sendable (CrocheError) -> Void)?) {
|
|
30
|
-
self.runtime = runtime; self.runtimeInstanceId = runtimeInstanceId; self.url = url; self.token = token
|
|
31
|
-
self.http = http; sendAdapter = send; cancelAdapter = cancel; self.onError = onError
|
|
32
|
-
}
|
|
33
|
-
public static func attach(runtime: CrocheRuntime, url: String = "http://127.0.0.1:8791", token: String,
|
|
34
|
-
http: @escaping RuntimeHTTP = { try await RuntimeURLSession.send($0, cancellation: $1, onDelta: $2) },
|
|
35
|
-
send: ControlSend? = nil, cancel: ControlCancel? = nil,
|
|
36
|
-
onError: (@Sendable (CrocheError) -> Void)? = nil) async throws -> RuntimeControl {
|
|
37
|
-
guard let parsed = URLComponents(string: url), parsed.scheme == "http",
|
|
38
|
-
["localhost", "127.0.0.1", "[::1]", "::1"].contains(parsed.host ?? ""),
|
|
39
|
-
parsed.user == nil, parsed.password == nil, parsed.query == nil, parsed.fragment == nil,
|
|
40
|
-
parsed.path.isEmpty || parsed.path == "/",
|
|
41
|
-
token.range(of: "^[A-Za-z0-9._~-]{24,4096}$", options: .regularExpression) != nil else {
|
|
42
|
-
throw CrocheError("invalid_configuration", "Control requires a loopback HTTP origin and explicit local token")
|
|
43
|
-
}
|
|
44
|
-
let status = try await runtime.inspect()["status"]
|
|
45
|
-
let id = status["runtimeInstanceId"].string ?? ""
|
|
46
|
-
guard validControlId(id) else { throw CrocheError("invalid_configuration", "Invalid Runtime identity") }
|
|
47
|
-
let control = RuntimeControl(runtime: runtime, runtimeInstanceId: id,
|
|
48
|
-
url: url.hasSuffix("/") ? String(url.dropLast()) : url, token: token,
|
|
49
|
-
http: http, send: send, cancel: cancel, onError: onError)
|
|
50
|
-
try await control.start(status)
|
|
51
|
-
return control
|
|
52
|
-
}
|
|
53
|
-
private var identity: [String: JSON] { ["client_id": .string(clientId), "runtime_instance_id": .string(runtimeInstanceId)] }
|
|
54
|
-
private func register(_ status: JSON) async throws {
|
|
55
|
-
_ = try await post("register", .object(["client_id": .string(clientId), "runtime": status,
|
|
56
|
-
"capabilities": .array(capabilities.map(JSON.string))]))
|
|
57
|
-
}
|
|
58
|
-
private func start(_ status: JSON) async throws {
|
|
59
|
-
try await register(status)
|
|
60
|
-
loop = Task { [weak self] in
|
|
61
|
-
while !Task.isCancelled {
|
|
62
|
-
guard let keep = await self?.tick(), keep else { break }
|
|
63
|
-
do { try await Task.sleep(nanoseconds: 100_000_000) } catch { break }
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
private func post(_ path: String, _ body: JSON) async throws -> JSON {
|
|
68
|
-
guard try body.encoded().count <= 1024 * 1024 else { throw CrocheError("control_capacity", "Control request exceeds 1MiB") }
|
|
69
|
-
let effect = JSON.object(["url": .string(url + "/v1/control/" + path), "method": .string("POST"),
|
|
70
|
-
"headers": .object(["Authorization": .string("Bearer " + token), "Content-Type": .string("application/json")]),
|
|
71
|
-
"body": body, "timeoutMs": .number(5000)])
|
|
72
|
-
let transport = http
|
|
73
|
-
let response = try await boundedEffect(milliseconds: 5000, cancellation: lifetime) { signal in try await transport(effect, signal) { _ in } }
|
|
74
|
-
let data = response["body"]
|
|
75
|
-
guard data.object != nil, try data.encoded().count <= 1024 * 1024 else { throw CrocheError("invalid_response", "Invalid bounded control response") }
|
|
76
|
-
guard let status = response["status"].number, (200..<300).contains(status) else {
|
|
77
|
-
throw CrocheError(data["error"]["code"].string ?? "control_error", "Local control broker rejected the request")
|
|
78
|
-
}
|
|
79
|
-
return data
|
|
80
|
-
}
|
|
81
|
-
private func tick() async -> Bool {
|
|
82
|
-
if closed { return false }
|
|
83
|
-
do {
|
|
84
|
-
for (id, result) in Array(results.prefix(8)) {
|
|
85
|
-
do { _ = try await post("results", result); results.removeValue(forKey: id) }
|
|
86
|
-
catch let error as CrocheError {
|
|
87
|
-
if ["not_found", "attachment_lost"].contains(error.code) { results.removeValue(forKey: id) }
|
|
88
|
-
throw error
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
if results.count < 32 && tasks.count < 16 {
|
|
92
|
-
let response = try await post("poll", .object(identity))
|
|
93
|
-
guard let commands = response["commands"].array else { throw CrocheError("invalid_response", "Broker command list is invalid") }
|
|
94
|
-
for command in commands.prefix(8) { try accept(command) }
|
|
95
|
-
}
|
|
96
|
-
} catch {
|
|
97
|
-
if !closed {
|
|
98
|
-
let issue = error as? CrocheError ?? CrocheError("control_error", "Local control failed")
|
|
99
|
-
onError?(issue)
|
|
100
|
-
if issue.code == "attachment_lost" {
|
|
101
|
-
do { try await register(runtime.inspect()["status"]) } catch {}
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
return !closed
|
|
106
|
-
}
|
|
107
|
-
private func accept(_ value: JSON) throws {
|
|
108
|
-
let id = value["request_id"].string ?? "", command = value["command"].string ?? ""
|
|
109
|
-
guard validControlId(id), capabilities.contains(command), let payload = value["payload"].object else {
|
|
110
|
-
throw CrocheError("invalid_command", "Invalid control command envelope")
|
|
111
|
-
}
|
|
112
|
-
if handled.contains(id) { return }
|
|
113
|
-
guard handled.count < 1000 else { throw CrocheError("control_capacity", "Reattach after 1000 control requests") }
|
|
114
|
-
handled.insert(id)
|
|
115
|
-
tasks[id] = Task { await self.perform(id, command, .object(payload)) }
|
|
116
|
-
}
|
|
117
|
-
private func perform(_ id: String, _ command: String, _ payload: JSON) async {
|
|
118
|
-
var response = identity; response["request_id"] = .string(id)
|
|
119
|
-
do {
|
|
120
|
-
let result = try await execute(command, payload, id)
|
|
121
|
-
guard try result.encoded().count <= 900_000 else { throw CrocheError("result_too_large", "Request a smaller result page") }
|
|
122
|
-
response["result"] = result
|
|
123
|
-
} catch {
|
|
124
|
-
response["error"] = .object(["code": .string(publicControlCode(error)),
|
|
125
|
-
"message": .string("The Runtime command failed. Inspect it before retrying."),
|
|
126
|
-
"uncertain": .bool(command == "send" || command == "budget.set")])
|
|
127
|
-
}
|
|
128
|
-
if !closed { results[id] = .object(response) }
|
|
129
|
-
tasks.removeValue(forKey: id)
|
|
130
|
-
}
|
|
131
|
-
private func execute(_ command: String, _ payload: JSON, _ id: String) async throws -> JSON {
|
|
132
|
-
guard !closed else { throw CrocheError("control_closed", "Control is closed") }
|
|
133
|
-
let keys = Set(payload.object!.keys)
|
|
134
|
-
if command == "send" {
|
|
135
|
-
guard keys.isSubset(of: ["id", "text"]), validControlId(payload["id"].string ?? ""),
|
|
136
|
-
let text = payload["text"].string, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
|
137
|
-
text.utf16.count <= 32000 else { throw CrocheError("invalid_command", "send needs immutable id and text only") }
|
|
138
|
-
let signal = RuntimeCancellation(); active[id] = signal; defer { active.removeValue(forKey: id) }
|
|
139
|
-
if let sendAdapter { return try await sendAdapter(payload, signal) }
|
|
140
|
-
let task = Task { try await runtime.send(payload) }
|
|
141
|
-
let listener = signal.observe { task.cancel() }; defer { signal.remove(listener) }
|
|
142
|
-
return try await task.value
|
|
143
|
-
}
|
|
144
|
-
if command == "history" {
|
|
145
|
-
guard keys.isSubset(of: ["offset", "limit"]) else { throw CrocheError("invalid_command", "Unsupported history fields") }
|
|
146
|
-
guard (!keys.contains("offset") || payload["offset"].number != nil), (!keys.contains("limit") || payload["limit"].number != nil) else { throw CrocheError("invalid_command", "History page values must be numbers") }
|
|
147
|
-
let offset = payload["offset"].number ?? 0, limit = payload["limit"].number ?? 100
|
|
148
|
-
guard offset.isFinite, offset >= 0, offset <= Double(Int.max / 2), offset.rounded() == offset,
|
|
149
|
-
limit >= 1, limit <= 200, limit.rounded() == limit else { throw CrocheError("invalid_command", "Invalid history page") }
|
|
150
|
-
let history = try await runtime.inspect()["history"].array ?? []
|
|
151
|
-
return .object(["messages": .array(Array(history.dropFirst(Int(offset)).prefix(Int(limit)))),
|
|
152
|
-
"total": .number(Double(history.count)), "offset": .number(offset), "limit": .number(limit)])
|
|
153
|
-
}
|
|
154
|
-
if command == "budget.set" {
|
|
155
|
-
guard keys == ["amount"], let amount = payload["amount"].number, amount.isFinite, amount >= 0 else {
|
|
156
|
-
throw CrocheError("invalid_command", "Budget needs a non-negative finite amount")
|
|
157
|
-
}
|
|
158
|
-
return try await runtime.adjustBudget(amount, absolute: true)
|
|
159
|
-
}
|
|
160
|
-
guard keys.isEmpty else { throw CrocheError("invalid_command", "Unsupported command fields") }
|
|
161
|
-
if command == "cancel" {
|
|
162
|
-
let hadActive = !active.isEmpty; for signal in active.values { signal.cancel() }
|
|
163
|
-
let host = await cancelAdapter?() ?? false
|
|
164
|
-
return .object(["requested": .bool(hadActive || host), "scope": .string(cancelAdapter == nil ? "control_client" : "host"), "rollback": .bool(false)])
|
|
165
|
-
}
|
|
166
|
-
if command == "sync" { _ = try await runtime.sync() }
|
|
167
|
-
let view = try await runtime.inspect()
|
|
168
|
-
switch command {
|
|
169
|
-
case "status":
|
|
170
|
-
var status = view["status"]; status["control"] = .object(["cancellation_scope": .string(cancelAdapter == nil ? "control_client" : "host")]); return status
|
|
171
|
-
case "sync": return view["status"]
|
|
172
|
-
case "tools": return view["tools"]
|
|
173
|
-
case "budget.get": return view["budget"]
|
|
174
|
-
default: throw CrocheError("unsupported_capability", "Unsupported Runtime command")
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
public func close() async {
|
|
178
|
-
if closed { return }; closed = true
|
|
179
|
-
for signal in active.values { signal.cancel() }
|
|
180
|
-
// Transport stays alive for unregister; closing attachment never closes Runtime.
|
|
181
|
-
_ = try? await post("unregister", .object(identity))
|
|
182
|
-
lifetime.cancel(); loop?.cancel(); await loop?.value; loop = nil
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
private func validControlId(_ value: String) -> Bool {
|
|
186
|
-
value.range(of: "^[A-Za-z0-9_.:-]{1,200}$", options: .regularExpression) != nil
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
private func publicControlCode(_ error: Error) -> String {
|
|
190
|
-
let code = (error as? CrocheError)?.code ?? "runtime_error"
|
|
191
|
-
return ["invalid_command", "control_closed", "unsupported_capability", "result_too_large", "busy", "closed", "storage_error", "context_limit", "budget_limit"].contains(code) ? code : "runtime_error"
|
|
192
|
-
}
|
|
@@ -1,453 +0,0 @@
|
|
|
1
|
-
import Foundation
|
|
2
|
-
|
|
3
|
-
// Proposed SDK-internal seam only. Core owns projection, ordered capture, delta fences,
|
|
4
|
-
// and storage. select/history never allocate a second canonical observation.
|
|
5
|
-
struct StreamSelection: Sendable { var initialMessages: Int?; var after: Cursor? }
|
|
6
|
-
struct CoreProjection: Sendable {
|
|
7
|
-
/// Joins Core's synchronous listener, not buffered AsyncStream/UI consumers. A synchronous
|
|
8
|
-
/// close from that listener itself fences without waiting for its own stack.
|
|
9
|
-
/// An app callback that waits for work on the closer's thread deadlocks under any
|
|
10
|
-
/// wait-for-callback fence.
|
|
11
|
-
let close: @Sendable () -> Void
|
|
12
|
-
let history: @Sendable (Int?, Int) async throws -> Void
|
|
13
|
-
}
|
|
14
|
-
struct UnitEnd: Sendable { let seq: Int; let inputs: [String]; let pending: [String] }
|
|
15
|
-
struct InputObservation: Sendable { let id: String; let seq: Int; let status: InputStatus; let carried: Bool }
|
|
16
|
-
enum RequestObservation: Sendable { case input(InputObservation), messageEnd(MessageEnd), state(StateEvent), unitEnd(UnitEnd) }
|
|
17
|
-
struct CapturedRequestState: Sendable {
|
|
18
|
-
let head: Int; let floor: Int; let status: InputStatus; let idle: Bool
|
|
19
|
-
let carried: Bool; let unitEnd: UnitEnd?
|
|
20
|
-
}
|
|
21
|
-
struct RetainedRequestEnds: Sendable { let messages: [MessageEnd]; let gap: Bool }
|
|
22
|
-
protocol CoreStreamPort: Sendable {
|
|
23
|
-
var logId: String { get }
|
|
24
|
-
func observe(_ event: @escaping @Sendable (RequestObservation) -> Void,
|
|
25
|
-
end: @escaping @Sendable (StreamError?) -> Void) throws -> @Sendable () -> Void
|
|
26
|
-
func select(_ selection: StreamSelection, event: @escaping @Sendable (RuntimeEvent) -> Void) -> CoreProjection
|
|
27
|
-
func send(_ input: JSON, options: SendOptions) async throws -> Receipt
|
|
28
|
-
func readOutcome(id: String, fromSeq: Int, captured: @escaping @Sendable (CapturedRequestState) -> Void) async throws -> RetainedRequestEnds
|
|
29
|
-
func cancel(_ id: String) async throws
|
|
30
|
-
func clearHistory() async throws
|
|
31
|
-
}
|
|
32
|
-
enum RequestCompletion: Sendable { case consumingUnit, idle }
|
|
33
|
-
|
|
34
|
-
// One predicate for both modes, ready for S1's reviewed unit.end evidence.
|
|
35
|
-
// OPEN(§18.24): Atlas must confirm unit.end and capture/retry evidence; no Rust ABI inferred.
|
|
36
|
-
private func requestComplete(_ wait: RequestCompletion, status: InputStatus?, idle: Bool,
|
|
37
|
-
carried: Bool, unit: UnitEnd?, id: String) -> Bool {
|
|
38
|
-
switch wait {
|
|
39
|
-
case .idle: return status?.terminal == true && idle
|
|
40
|
-
case .consumingUnit: return unit?.inputs.contains(id) == true || (status?.terminal == true && !carried)
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
private final class WaitCancellation: @unchecked Sendable {
|
|
44
|
-
private let lock = NSLock()
|
|
45
|
-
private var cancelled = false
|
|
46
|
-
func cancel() { lock.withLock { cancelled = true } }
|
|
47
|
-
var value: Bool { lock.withLock { cancelled } }
|
|
48
|
-
}
|
|
49
|
-
private final class RequestWaiter {
|
|
50
|
-
let id: String; let wait: RequestCompletion; let cancellation: WaitCancellation
|
|
51
|
-
let continuation: CheckedContinuation<RequestResult, Error>
|
|
52
|
-
var receipt: Receipt?; var status: InputStatus?; var carried = false
|
|
53
|
-
var messages: [String: MessageEnd] = [:]
|
|
54
|
-
var captured = false
|
|
55
|
-
var reading = true; var complete = false; var cutoff: Int?; var gap = false
|
|
56
|
-
var lost = false
|
|
57
|
-
init(id: String, wait: RequestCompletion, cancellation: WaitCancellation, continuation: CheckedContinuation<RequestResult, Error>) {
|
|
58
|
-
self.id = id; self.wait = wait; self.cancellation = cancellation; self.continuation = continuation
|
|
59
|
-
}
|
|
60
|
-
func add(_ message: MessageEnd) {
|
|
61
|
-
guard message.causedBy.contains(id), cutoff.map({ message.seq <= $0 }) ?? true else { return }
|
|
62
|
-
messages["\(message.id):\(message.seq)"] = message
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Every mutable member is under lock. Core callbacks update waiters synchronously;
|
|
67
|
-
// the app only receives owned values through its independent queue.
|
|
68
|
-
final class StreamHub: @unchecked Sendable {
|
|
69
|
-
private let lock = NSLock()
|
|
70
|
-
private let selectionLock = NSRecursiveLock()
|
|
71
|
-
private let port: any CoreStreamPort
|
|
72
|
-
private var observation: (@Sendable () -> Void)?
|
|
73
|
-
private var projection: CoreProjection?
|
|
74
|
-
private var branch: AppStreamBranch?
|
|
75
|
-
private var waiters: [UUID: RequestWaiter] = [:]
|
|
76
|
-
private var ended = false
|
|
77
|
-
private var observedHead = 0
|
|
78
|
-
private var currentState = StateEvent(status: .idle, queued: 0, typing: false)
|
|
79
|
-
var state: StateEvent { lock.withLock { currentState } }
|
|
80
|
-
var logId: String { port.logId }
|
|
81
|
-
init(port: any CoreStreamPort) throws {
|
|
82
|
-
self.port = port
|
|
83
|
-
observation = try port.observe({ [weak self] in self?.receive($0) }, end: { [weak self] in self?.end($0) })
|
|
84
|
-
}
|
|
85
|
-
func events(initialMessages: Int = 50) -> AsyncStream<RuntimeEvent> {
|
|
86
|
-
return events(StreamSelection(initialMessages: initialMessages, after: nil))
|
|
87
|
-
}
|
|
88
|
-
func events(after: Cursor) -> AsyncStream<RuntimeEvent> { events(StreamSelection(initialMessages: nil, after: after)) }
|
|
89
|
-
private func events(_ selection: StreamSelection) -> AsyncStream<RuntimeEvent> { attach(selection).stream }
|
|
90
|
-
func subscribe(_ options: SubscribeOptions) -> AgentSubscription {
|
|
91
|
-
let selection = StreamSelection(initialMessages: options.initialMessages ?? (options.after == nil ? 50 : nil), after: options.after)
|
|
92
|
-
return AgentSubscription(branch: attach(selection), handler: options.onEvent)
|
|
93
|
-
}
|
|
94
|
-
private func attach(_ selection: StreamSelection) -> AppStreamBranch {
|
|
95
|
-
selectionLock.lock(); defer { selectionLock.unlock() }
|
|
96
|
-
// Both the actor façade and synchronous subscribe use this selection fence.
|
|
97
|
-
let app = AppStreamBranch()
|
|
98
|
-
let old: (AppStreamBranch?, CoreProjection?, Bool) = lock.withLock {
|
|
99
|
-
let old = (branch, projection, ended)
|
|
100
|
-
branch = app; projection = nil
|
|
101
|
-
return old
|
|
102
|
-
}
|
|
103
|
-
old.1?.close(); old.0?.finish(.replaced)
|
|
104
|
-
if selection.initialMessages != nil && selection.after != nil {
|
|
105
|
-
app.finish(.streamError(StreamError(code: "invalid_configuration", message: "Use initialMessages or after, not both", poisoned: false)))
|
|
106
|
-
return app
|
|
107
|
-
}
|
|
108
|
-
if let count = selection.initialMessages, !(0...256).contains(count) {
|
|
109
|
-
app.finish(.streamError(StreamError(code: "invalid_configuration", message: "initialMessages must be in 0...256", poisoned: false)))
|
|
110
|
-
return app
|
|
111
|
-
}
|
|
112
|
-
if old.2 { app.finish(.streamError(StreamError(code: "closed", message: "Runtime is closed", poisoned: false))); return app }
|
|
113
|
-
let closeProjection = port.select(selection) { [weak app] in app?.push($0) }
|
|
114
|
-
app.onEnd(closeProjection.close)
|
|
115
|
-
app.setHistory(closeProjection.history)
|
|
116
|
-
lock.withLock { projection = closeProjection }
|
|
117
|
-
return app
|
|
118
|
-
}
|
|
119
|
-
static func errorStream(_ code: String, _ message: String) -> AsyncStream<RuntimeEvent> {
|
|
120
|
-
AsyncStream { continuation in
|
|
121
|
-
continuation.yield(.streamError(StreamError(code: code, message: message, poisoned: false)))
|
|
122
|
-
continuation.finish()
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
func send(_ input: SendInput, options: SendOptions) async throws -> Receipt {
|
|
126
|
-
if Task.isCancelled { throw CrocheError("aborted", "Send cancelled before acceptance") }
|
|
127
|
-
guard !lock.withLock({ ended }) else { throw CrocheError("closed", "Runtime is closed") }
|
|
128
|
-
return try await port.send(try input.coreJSON(options: options), options: options)
|
|
129
|
-
}
|
|
130
|
-
func history(before: Int?, limit: Int) async throws {
|
|
131
|
-
guard (1...256).contains(limit) else { throw CrocheError("invalid_configuration", "history limit must be in 1...256") }
|
|
132
|
-
let selected = lock.withLock { branch?.isActive == true && !ended ? projection : nil }
|
|
133
|
-
guard let selected else { throw CrocheError("invalid_configuration", "No stream is attached") }
|
|
134
|
-
try await selected.history(before, limit)
|
|
135
|
-
}
|
|
136
|
-
func cancel(_ id: String) async throws { try await port.cancel(id) }
|
|
137
|
-
func clearHistory() async throws { try await port.clearHistory() }
|
|
138
|
-
func request(_ input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = nil) async throws -> RequestResult {
|
|
139
|
-
if Task.isCancelled { throw CrocheError("aborted", "Request cancelled before sending") }
|
|
140
|
-
// Keel/rook: keep terminal + idle until the coordinated TS/Swift/Kotlin consuming-unit change.
|
|
141
|
-
// Both nil and the approved public .idle use S2's terminal-plus-idle default.
|
|
142
|
-
let completion: RequestCompletion = .idle
|
|
143
|
-
let key = UUID(), cancellation = WaitCancellation()
|
|
144
|
-
return try await withTaskCancellationHandler {
|
|
145
|
-
try await withCheckedThrowingContinuation { continuation in
|
|
146
|
-
let admitted = lock.withLock {
|
|
147
|
-
if ended { continuation.resume(throwing: CrocheError("closed", "Runtime is closed")); return false }
|
|
148
|
-
if cancellation.value { continuation.resume(throwing: CrocheError("aborted", "Request cancelled before sending")); return false }
|
|
149
|
-
waiters[key] = RequestWaiter(id: input.id, wait: completion, cancellation: cancellation, continuation: continuation)
|
|
150
|
-
return true
|
|
151
|
-
}
|
|
152
|
-
guard admitted else { return }
|
|
153
|
-
// Do not cancel the acceptance task when the caller stops waiting.
|
|
154
|
-
Task { await self.accept(input, options: options, key: key) }
|
|
155
|
-
}
|
|
156
|
-
} onCancel: {
|
|
157
|
-
cancellation.cancel()
|
|
158
|
-
self.abort(key)
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
private func accept(_ input: SendInput, options: SendOptions, key: UUID) async {
|
|
162
|
-
var receipt: Receipt?
|
|
163
|
-
do {
|
|
164
|
-
let accepted = try await port.send(try input.coreJSON(options: options), options: options)
|
|
165
|
-
receipt = accepted
|
|
166
|
-
let read = lock.withLock {
|
|
167
|
-
guard let waiter = waiters[key] else { return false }
|
|
168
|
-
waiter.receipt = accepted
|
|
169
|
-
// A same-id terminal retry emits no new input event. Seed its disposition
|
|
170
|
-
// before idle can overtake capture; never regress a status already observed.
|
|
171
|
-
if waiter.status == nil || (waiter.status?.terminal != true && accepted.status.terminal) {
|
|
172
|
-
waiter.status = accepted.status
|
|
173
|
-
}
|
|
174
|
-
if waiter.lost { fail(key, code: "observation_lost"); return false }
|
|
175
|
-
if waiter.cancellation.value { fail(key, code: "aborted"); return false }
|
|
176
|
-
if accepted.seq == nil {
|
|
177
|
-
waiters.removeValue(forKey: key)
|
|
178
|
-
waiter.continuation.resume(returning: RequestResult(id: accepted.id, status: accepted.status, messages: [], gap: false, legacy: true))
|
|
179
|
-
return false
|
|
180
|
-
}
|
|
181
|
-
return true
|
|
182
|
-
}
|
|
183
|
-
guard read, let seq = accepted.seq else { return }
|
|
184
|
-
let retained = try await port.readOutcome(id: accepted.id, fromSeq: seq) { [weak self] captured in
|
|
185
|
-
self?.capture(captured, key: key, receipt: accepted)
|
|
186
|
-
}
|
|
187
|
-
lock.withLock {
|
|
188
|
-
guard let waiter = waiters[key] else { return }
|
|
189
|
-
guard waiter.captured else { fail(key, code: "observation_lost"); return }
|
|
190
|
-
for message in retained.messages { waiter.add(message) }
|
|
191
|
-
waiter.gap = waiter.gap || retained.gap
|
|
192
|
-
waiter.reading = false
|
|
193
|
-
finish(key)
|
|
194
|
-
}
|
|
195
|
-
} catch {
|
|
196
|
-
lock.withLock {
|
|
197
|
-
guard let waiter = waiters.removeValue(forKey: key) else { return }
|
|
198
|
-
waiter.continuation.resume(throwing: receipt.map { CrocheError("observation_lost", "Outcome observation failed", receipt: $0) } ?? error)
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
private func capture(_ captured: CapturedRequestState, key: UUID, receipt: Receipt) {
|
|
203
|
-
lock.withLock {
|
|
204
|
-
guard let waiter = waiters[key] else { return }
|
|
205
|
-
waiter.captured = true
|
|
206
|
-
if waiter.status?.terminal != true { waiter.status = captured.status }
|
|
207
|
-
waiter.carried = waiter.carried || captured.carried
|
|
208
|
-
waiter.gap = waiter.gap || receipt.seq! < captured.floor
|
|
209
|
-
// A newly attached hub can finish a terminal retry at idle before it has seen
|
|
210
|
-
// any sequence for that receipt. Its zero/older live cutoff must not discard
|
|
211
|
-
// the scoped retained reply. An actual live completion cut stays unchanged.
|
|
212
|
-
if waiter.complete, let cutoff = waiter.cutoff, cutoff < receipt.seq! {
|
|
213
|
-
waiter.cutoff = captured.head
|
|
214
|
-
}
|
|
215
|
-
if !waiter.complete && requestComplete(waiter.wait, status: waiter.status, idle: captured.idle, carried: waiter.carried, unit: captured.unitEnd, id: waiter.id) {
|
|
216
|
-
waiter.complete = true; waiter.cutoff = captured.head
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
private func receive(_ observation: RequestObservation) {
|
|
221
|
-
lock.withLock {
|
|
222
|
-
switch observation {
|
|
223
|
-
case .input(let input): observedHead = max(observedHead, input.seq)
|
|
224
|
-
case .messageEnd(let message): observedHead = max(observedHead, message.seq)
|
|
225
|
-
case .state(let state): currentState = state
|
|
226
|
-
case .unitEnd(let unit): observedHead = max(observedHead, unit.seq)
|
|
227
|
-
}
|
|
228
|
-
for key in Array(waiters.keys) {
|
|
229
|
-
guard let waiter = waiters[key], !waiter.complete else { continue }
|
|
230
|
-
var idle = false, unit: UnitEnd?
|
|
231
|
-
switch observation {
|
|
232
|
-
case .input(let input) where input.id == waiter.id:
|
|
233
|
-
if waiter.status?.terminal != true { waiter.status = input.status }
|
|
234
|
-
waiter.carried = waiter.carried || input.carried
|
|
235
|
-
case .messageEnd(let message): waiter.add(message)
|
|
236
|
-
case .state(let state): idle = state.status == .idle
|
|
237
|
-
case .unitEnd(let value): unit = value
|
|
238
|
-
default: break
|
|
239
|
-
}
|
|
240
|
-
if requestComplete(waiter.wait, status: waiter.status, idle: idle, carried: waiter.carried, unit: unit, id: waiter.id) {
|
|
241
|
-
waiter.complete = true; waiter.cutoff = unit?.seq ?? observedHead
|
|
242
|
-
}
|
|
243
|
-
finish(key)
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
private func finish(_ key: UUID) {
|
|
248
|
-
guard let waiter = waiters[key], !waiter.reading, waiter.complete, let receipt = waiter.receipt, let status = waiter.status else { return }
|
|
249
|
-
waiters.removeValue(forKey: key)
|
|
250
|
-
waiter.continuation.resume(returning: RequestResult(id: receipt.id, status: status, messages: waiter.messages.values.sorted { $0.seq < $1.seq }, gap: waiter.gap, legacy: false))
|
|
251
|
-
}
|
|
252
|
-
// Caller must hold lock.
|
|
253
|
-
private func fail(_ key: UUID, code: String) {
|
|
254
|
-
guard let waiter = waiters.removeValue(forKey: key) else { return }
|
|
255
|
-
waiter.continuation.resume(throwing: CrocheError(code, "The wait ended; accepted input continues", receipt: waiter.receipt))
|
|
256
|
-
}
|
|
257
|
-
private func abort(_ key: UUID) { lock.withLock { if waiters[key]?.receipt != nil { fail(key, code: "aborted") } } }
|
|
258
|
-
func close() {
|
|
259
|
-
end(StreamError(code: "closed", message: "Runtime is closed", poisoned: false), drain: false)
|
|
260
|
-
let detach = lock.withLock { let old = observation; observation = nil; return old }
|
|
261
|
-
detach?()
|
|
262
|
-
}
|
|
263
|
-
deinit { observation?(); projection?.close() }
|
|
264
|
-
private func end(_ error: StreamError?, drain: Bool = true) {
|
|
265
|
-
let old: (AppStreamBranch?, CoreProjection?) = lock.withLock {
|
|
266
|
-
guard !ended else { return (nil, nil) }
|
|
267
|
-
ended = true
|
|
268
|
-
for key in Array(waiters.keys) {
|
|
269
|
-
waiters[key]?.lost = true
|
|
270
|
-
if waiters[key]?.receipt != nil { fail(key, code: "observation_lost") }
|
|
271
|
-
}
|
|
272
|
-
return (branch, projection)
|
|
273
|
-
}
|
|
274
|
-
old.1?.close()
|
|
275
|
-
old.0?.finish(error.map(RuntimeEvent.streamError), drain: drain && error != nil)
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// AsyncStream's unfolding form lets this SDK count queued UTF-8 bytes and events.
|
|
280
|
-
// Retain the delivered event's budget until next() is called again: the for-await
|
|
281
|
-
// body has then finished (Keel ruling 6071234795).
|
|
282
|
-
private final class AppStreamBranch: @unchecked Sendable {
|
|
283
|
-
private let lock = NSLock()
|
|
284
|
-
private var queue: [(RuntimeEvent, Int)] = []
|
|
285
|
-
private var bytes = 0
|
|
286
|
-
private var inFlightBytes: Int?
|
|
287
|
-
private var active = true
|
|
288
|
-
private var terminal: RuntimeEvent?
|
|
289
|
-
private var consumer: CheckedContinuation<RuntimeEvent?, Never>?
|
|
290
|
-
private var closeProjection: (@Sendable () -> Void)?
|
|
291
|
-
private var historyPage: (@Sendable (Int?, Int) async throws -> Void)?
|
|
292
|
-
private var immediateEnd: (@Sendable (RuntimeEvent?) -> Void)?
|
|
293
|
-
private var immediateReason: RuntimeEvent?
|
|
294
|
-
private var endedImmediately = false
|
|
295
|
-
func setHistory(_ history: @escaping @Sendable (Int?, Int) async throws -> Void) { lock.withLock { historyPage = history } }
|
|
296
|
-
func history(_ options: HistoryOptions) async throws {
|
|
297
|
-
guard (1...256).contains(options.limit) else { throw CrocheError("invalid_configuration", "history limit must be in 1...256") }
|
|
298
|
-
let page = lock.withLock { active ? historyPage : nil }
|
|
299
|
-
guard let page else { throw CrocheError("invalid_configuration", "No stream is attached") }
|
|
300
|
-
try await page(options.before, options.limit)
|
|
301
|
-
}
|
|
302
|
-
func observeImmediateEnd(_ observer: @escaping @Sendable (RuntimeEvent?) -> Void) {
|
|
303
|
-
let prior: (Bool, RuntimeEvent?) = lock.withLock { immediateEnd = observer; return (endedImmediately, immediateReason) }
|
|
304
|
-
if prior.0 { observer(prior.1) }
|
|
305
|
-
}
|
|
306
|
-
var isActive: Bool { lock.withLock { active } }
|
|
307
|
-
var stream: AsyncStream<RuntimeEvent> {
|
|
308
|
-
AsyncStream(unfolding: { await self.next() }, onCancel: { self.finish(nil) })
|
|
309
|
-
}
|
|
310
|
-
func onEnd(_ close: @escaping @Sendable () -> Void) {
|
|
311
|
-
let alreadyEnded = lock.withLock { closeProjection = close; return !active }
|
|
312
|
-
if alreadyEnded { close() }
|
|
313
|
-
}
|
|
314
|
-
func push(_ event: RuntimeEvent) {
|
|
315
|
-
if case .replaced = event { finish(event); return }
|
|
316
|
-
if case .streamError = event {
|
|
317
|
-
finish(event, drain: true); return
|
|
318
|
-
}
|
|
319
|
-
let count: Int
|
|
320
|
-
do { count = try event.serializedBytes() }
|
|
321
|
-
catch { finish(.streamError(StreamError(code: "handler_failed", message: "Event cannot be encoded", poisoned: false))); return }
|
|
322
|
-
let overflow = lock.withLock {
|
|
323
|
-
guard active else { return false }
|
|
324
|
-
if queue.count + (inFlightBytes == nil ? 0 : 1) + 1 > 256 || bytes + count > 1_048_576 { return true }
|
|
325
|
-
if let consumer { self.consumer = nil; inFlightBytes = count; bytes += count; consumer.resume(returning: event); return false }
|
|
326
|
-
queue.append((event, count)); bytes += count
|
|
327
|
-
return false
|
|
328
|
-
}
|
|
329
|
-
if overflow { finish(.streamError(StreamError(code: "subscriber_overflow", message: "App event buffer exceeded", poisoned: false))) }
|
|
330
|
-
}
|
|
331
|
-
func finish(_ event: RuntimeEvent?, drain: Bool = false) {
|
|
332
|
-
let result: ((@Sendable () -> Void)?, (@Sendable (RuntimeEvent?) -> Void)?) = lock.withLock {
|
|
333
|
-
guard active else { return (nil, nil) }
|
|
334
|
-
active = false
|
|
335
|
-
// Keel ruling 6071234795: Core errors drain; SDK-side ends drop queued values.
|
|
336
|
-
if drain {} else { queue.removeAll(); bytes = 0; inFlightBytes = nil }
|
|
337
|
-
terminal = event
|
|
338
|
-
if let consumer { self.consumer = nil; terminal = nil; consumer.resume(returning: event) }
|
|
339
|
-
if !drain { endedImmediately = true; immediateReason = event }
|
|
340
|
-
return (closeProjection, drain ? nil : immediateEnd)
|
|
341
|
-
}
|
|
342
|
-
result.0?()
|
|
343
|
-
result.1?(event)
|
|
344
|
-
}
|
|
345
|
-
private func next() async -> RuntimeEvent? {
|
|
346
|
-
await withCheckedContinuation { continuation in
|
|
347
|
-
lock.withLock {
|
|
348
|
-
if let inFlightBytes { bytes -= inFlightBytes; self.inFlightBytes = nil }
|
|
349
|
-
if !queue.isEmpty { let item = queue.removeFirst(); inFlightBytes = item.1; continuation.resume(returning: item.0) }
|
|
350
|
-
else if !active { let last = terminal; terminal = nil; continuation.resume(returning: last) }
|
|
351
|
-
else { consumer = continuation }
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
extension RuntimeEvent {
|
|
358
|
-
// Match the flat wire shape; Swift's synthesized enum encoding adds wrappers.
|
|
359
|
-
func serializedBytes() throws -> Int {
|
|
360
|
-
let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
|
|
361
|
-
return try encoder.encode(wireJSON()).count
|
|
362
|
-
}
|
|
363
|
-
func wireJSON() throws -> JSON {
|
|
364
|
-
let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.withoutEscapingSlashes]
|
|
365
|
-
func fields<T: Encodable>(_ value: T, _ type: String) throws -> JSON {
|
|
366
|
-
var json = try JSON(data: encoder.encode(value)); json["type"] = .string(type); return json
|
|
367
|
-
}
|
|
368
|
-
let json: JSON
|
|
369
|
-
switch self {
|
|
370
|
-
case .input(let v): json = try fields(v, "input")
|
|
371
|
-
case .messageStart(let v): json = try fields(v, "message.start")
|
|
372
|
-
case .messageDelta(let v): json = try fields(v, "message.delta")
|
|
373
|
-
case .messageEnd(let v): json = try fields(v, "message.end")
|
|
374
|
-
case .cleared(let v): json = try fields(v, "cleared")
|
|
375
|
-
case .app(let v): json = try fields(v, "app")
|
|
376
|
-
case .turn(let v): json = try fields(v, "turn")
|
|
377
|
-
case .state(let v): json = try fields(v, "state")
|
|
378
|
-
case .error(let v): json = try fields(v, "error")
|
|
379
|
-
case .gap(let v): json = try fields(v, "gap")
|
|
380
|
-
case .snapshot(let v): json = try fields(v, "snapshot")
|
|
381
|
-
case .streamError(let v): json = try fields(v, "error")
|
|
382
|
-
case .page(let v):
|
|
383
|
-
json = .object(["type": .string("page"), "messages": .array(try v.messages.map { try $0.wireJSON() }), "reachedFloor": .bool(v.reachedFloor), "logId": .string(v.logId), "clearedSeq": .number(Double(v.clearedSeq))])
|
|
384
|
-
case .replaced: json = .object(["type": .string("replaced")])
|
|
385
|
-
case .unknown(let type): json = .object(["type": .string(type)])
|
|
386
|
-
}
|
|
387
|
-
return json
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
/// One serialized application callback branch; requests have an independent observation.
|
|
393
|
-
public final class AgentSubscription: @unchecked Sendable {
|
|
394
|
-
private let lock = NSLock()
|
|
395
|
-
private let branch: AppStreamBranch
|
|
396
|
-
private let handler: @Sendable (RuntimeEvent) async -> Void
|
|
397
|
-
private var outcome: AppStreamEnd?
|
|
398
|
-
private var waits: [CheckedContinuation<AppStreamEnd, Never>] = []
|
|
399
|
-
private var silenced = false
|
|
400
|
-
private var consumer: Task<Void, Never>?
|
|
401
|
-
fileprivate init(branch: AppStreamBranch, handler: @escaping @Sendable (RuntimeEvent) async -> Void) {
|
|
402
|
-
self.branch = branch; self.handler = handler
|
|
403
|
-
branch.observeImmediateEnd { [weak self] event in self?.finish(event, notify: true) }
|
|
404
|
-
consumer = Task { [weak self] in
|
|
405
|
-
for await event in branch.stream {
|
|
406
|
-
guard let self else { return }
|
|
407
|
-
if self.lock.withLock({ self.outcome != nil }) { return }
|
|
408
|
-
if Self.reason(event) != nil { self.finish(event, notify: false) }
|
|
409
|
-
await handler(event)
|
|
410
|
-
}
|
|
411
|
-
self?.finish(nil, notify: false)
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
public var ended: AppStreamEnd {
|
|
415
|
-
get async {
|
|
416
|
-
await withCheckedContinuation { continuation in
|
|
417
|
-
lock.withLock {
|
|
418
|
-
if let outcome { continuation.resume(returning: outcome) }
|
|
419
|
-
else { waits.append(continuation) }
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
public func close() {
|
|
425
|
-
lock.withLock { silenced = true }
|
|
426
|
-
finish(nil, notify: false)
|
|
427
|
-
branch.finish(nil)
|
|
428
|
-
consumer?.cancel()
|
|
429
|
-
}
|
|
430
|
-
public func history(_ options: HistoryOptions) async throws { try await branch.history(options) }
|
|
431
|
-
private static func reason(_ event: RuntimeEvent?) -> String? {
|
|
432
|
-
switch event {
|
|
433
|
-
case .streamError(let error): return error.code
|
|
434
|
-
case .replaced: return "replaced"
|
|
435
|
-
default: return nil
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
private func finish(_ event: RuntimeEvent?, notify: Bool) {
|
|
439
|
-
let accepted = lock.withLock {
|
|
440
|
-
guard outcome == nil else { return false }
|
|
441
|
-
let result = AppStreamEnd(code: Self.reason(event) ?? "closed")
|
|
442
|
-
outcome = result
|
|
443
|
-
for continuation in waits { continuation.resume(returning: result) }
|
|
444
|
-
waits.removeAll(); return true
|
|
445
|
-
}
|
|
446
|
-
if accepted && notify, let event {
|
|
447
|
-
Task { [weak self] in
|
|
448
|
-
guard let self, !self.lock.withLock({ self.silenced }) else { return }
|
|
449
|
-
await self.handler(event)
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
}
|