@h1r-ai/croche-react-native 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +32 -4
- package/THIRD-PARTY-NOTICES +899 -6
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
- package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +1 -0
- package/dist/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +148 -25
- package/dist/react-native/src/core-wire.d.ts +20 -3
- package/dist/rn-shared-build.json +8 -8
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +53 -5
- package/dist/runtime/src/agent.js +69 -7
- package/dist/runtime/src/app-api.d.ts +307 -19
- package/dist/runtime/src/cancel.d.ts +2 -2
- package/dist/runtime/src/cancel.js +7 -4
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +48 -35
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -0
- package/dist/runtime/src/croche.d.ts +64 -9
- package/dist/runtime/src/croche.js +78 -17
- package/dist/runtime/src/errors.d.ts +7 -0
- package/dist/runtime/src/errors.js +15 -1
- package/dist/runtime/src/generated/app-stream.d.ts +155 -1
- package/dist/runtime/src/generated/app-stream.js +7 -4
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -21
- package/dist/runtime/src/index.native.js +2 -8
- package/dist/runtime/src/native-adapter.d.ts +1 -1
- package/dist/runtime/src/native-adapter.js +10 -4
- package/dist/runtime/src/pal/host.d.ts +3 -3
- package/dist/runtime/src/pal/host.js +34 -9
- package/dist/runtime/src/pal/platform.d.ts +11 -6
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -0
- package/dist/runtime/src/tools.d.ts +20 -4
- package/dist/runtime/src/tools.js +31 -7
- package/ios/CoreAgentTransport.swift +2 -2
- package/ios/CoreNativePal.swift +26 -21
- package/ios/CorePlatformTransport.swift +4 -4
- package/ios/CoreWireDispatch.swift +38 -8
- package/ios/CoreWireSupport.swift +179 -4
- package/ios/CrocheRuntimeBridge.swift +1 -1
- package/ios/ProjectPal.swift +15 -12
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
- package/package.json +3 -3
- package/scripts/README.md +1 -1
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +4 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
- package/dist/runtime/src/pal/codec.d.ts +0 -15
- package/dist/runtime/src/pal/codec.js +0 -52
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
|
@@ -55,344 +55,6 @@ struct WikiDocument: Sendable, Equatable {
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
/// The Croche Runtime for Swift. The Rust Core (crates/croche-ffi) is the Runtime: it holds
|
|
59
|
-
/// the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
|
|
60
|
-
/// Swift types; `SwiftHost` performs what only the platform can (the PAL). Pass only
|
|
61
|
-
/// serializable Runtime configuration in config.
|
|
62
|
-
actor AgentEngine {
|
|
63
|
-
nonisolated let core: CoreRuntime
|
|
64
|
-
let host: SwiftHost
|
|
65
|
-
nonisolated let memoryCache = RuntimeMemoryCache()
|
|
66
|
-
private var closed = false
|
|
67
|
-
var subscriptionHub: StreamHub?
|
|
68
|
-
nonisolated let logId: String
|
|
69
|
-
#if canImport(UIKit) && os(iOS)
|
|
70
|
-
private var foreground: (any NSObjectProtocol)?
|
|
71
|
-
#endif
|
|
72
|
-
|
|
73
|
-
private var onDelivery: (@Sendable (JSON) -> Void)?
|
|
74
|
-
private init(core: CoreRuntime, host: SwiftHost, logId: String) { self.core = core; self.host = host; self.logId = logId }
|
|
75
|
-
private func bind(_ hub: StreamHub) { subscriptionHub = hub }
|
|
76
|
-
/// INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
|
|
77
|
-
/// module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
|
|
78
|
-
/// delivery turn (`ran: true`), whoever called it (the timer, a background run, the foreground,
|
|
79
|
-
/// the app), once the turn is in `inspect()`'s history. Interim: the subscription for
|
|
80
|
-
/// agent-initiated messages (F25 on #264: `onBackgroundMessage` with replay on open) replaces it.
|
|
81
|
-
func observeDeliveries(_ observer: (@Sendable (JSON) -> Void)?) { onDelivery = observer }
|
|
82
|
-
/// `secrets` keeps the Runtime credential apart from `storage`: KeychainSecretStore on
|
|
83
|
-
/// Apple platforms. `attestor` proves the genuine app to Cloud when the project requires
|
|
84
|
-
/// it: AppAttestAttestor on a device; nil on a simulator or a host that cannot attest.
|
|
85
|
-
/// `http` replaces the default URLSession transport with one that answers whole requests.
|
|
86
|
-
/// `wiki` is the documents, set at open; this agent's path filter is the config's
|
|
87
|
-
/// `"wiki": {"include": [...], "exclude": [...]}`.
|
|
88
|
-
/// `onEvent` hears one `turn.started` per turn; a send carried into a running turn at a later
|
|
89
|
-
/// model call is `{type:"turn.joined", turnId, inputIds}` (the ids newly carried).
|
|
90
|
-
/// `onUsage` receives every paid call's cost (`{type:"usage", operationId, purpose, causedBy, instance, model,
|
|
91
|
-
/// costUsd, costStatus, tokens?}`; `tokens` holds the reported counts, e.g. `prompt`, `cached`),
|
|
92
|
-
/// `instance` is the named/generated instance key, or null for the main agent.
|
|
93
|
-
/// `purpose` is "model" or "summary"; `causedBy` holds the inputs served (empty for upkeep).
|
|
94
|
-
/// `model` is the gateway-reported answering model (`modelSource: "response"`), or the
|
|
95
|
-
/// request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
|
|
96
|
-
/// present only when different. Reported cost is unchanged by a model substitution.
|
|
97
|
-
/// `routedFor: "images"` and `routedFrom` mark a call whose images the app's (else the
|
|
98
|
-
/// project's) model does not accept, sent to an image-capable project model instead.
|
|
99
|
-
/// at least once, from the start: open itself reports a call the process
|
|
100
|
-
/// died during. It runs on a Runtime thread; do not call the Runtime from it.
|
|
101
|
-
/// `scheduler` registers the agent's scheduled notes with the OS for when the app is not
|
|
102
|
-
/// running: `AppRefreshScheduler` (BGTaskScheduler) on iOS; nil elsewhere, where a timer
|
|
103
|
-
/// delivers them while the Runtime is open and the next open delivers what fell due meanwhile.
|
|
104
|
-
/// On iOS the Runtime also calls `deliverDue()` each time the app enters the foreground. A
|
|
105
|
-
/// scheduler whose identifier another open Runtime holds refuses this one
|
|
106
|
-
/// (`scheduler_conflict`).
|
|
107
|
-
/// `projectDirectory` is required on Linux, which has no app-private default.
|
|
108
|
-
/// On Apple platforms it must be nil: the record stays in Application Support.
|
|
109
|
-
static func create(config: JSON, storage: any RuntimeStorage, secrets: any RuntimeSecretStore,
|
|
110
|
-
attestor: (any RuntimeAttestor)? = nil,
|
|
111
|
-
tools: [String: ToolHandler] = [:],
|
|
112
|
-
http: RuntimeHTTP? = nil,
|
|
113
|
-
onEvent: (@Sendable (JSON) -> Void)? = nil,
|
|
114
|
-
onDebugEvent: (@Sendable (JSON) -> Void)? = nil,
|
|
115
|
-
onUsage: (@Sendable (JSON) -> Void)? = nil,
|
|
116
|
-
backgroundSync: Bool = true,
|
|
117
|
-
maintenanceInterval: TimeInterval = 60,
|
|
118
|
-
wiki: [WikiDocument]? = nil,
|
|
119
|
-
scheduler: (any RuntimeScheduler)? = nil,
|
|
120
|
-
projectDirectory: URL? = nil) async throws -> AgentEngine {
|
|
121
|
-
let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
|
|
122
|
-
let interval = try clampedMaintenanceInterval(maintenanceInterval)
|
|
123
|
-
warnIfReleaseBuildCarriesDebugKey(config)
|
|
124
|
-
var bound = config
|
|
125
|
-
bound["attestationPlatform"] = attestor.map { .string($0.platform) } ?? .null
|
|
126
|
-
let host = SwiftHost(storage: storage, secrets: secrets, attestor: attestor, http: http, tools: tools,
|
|
127
|
-
background: backgroundSync, scheduler: scheduler, projectRecords: records)
|
|
128
|
-
// The app chose the store, so the Runtime binds its identity to it (a custom storage key).
|
|
129
|
-
let options = RuntimeOpenOptions(storageKey: "croche.swift", streaming: config["streaming"].bool ?? true,
|
|
130
|
-
backgroundSync: backgroundSync,
|
|
131
|
-
maintenanceIntervalMs: interval * 1000)
|
|
132
|
-
let configText = String(decoding: try bound.encoded(), as: UTF8.self)
|
|
133
|
-
let listener = onEvent.map { EventHook($0) }
|
|
134
|
-
let usage = onUsage.map { EventHook($0) }
|
|
135
|
-
try host.attachScheduler()
|
|
136
|
-
// From here the host's stop (close, or a failed open) detaches the scheduler, once.
|
|
137
|
-
let core: CoreRuntime
|
|
138
|
-
do { core = try await Offload.run { try CoreRuntime.open(pal: host, config: configText, options: options, onEvent: listener, onUsage: usage) } }
|
|
139
|
-
catch { host.stop(); host.session.close(); throw error }
|
|
140
|
-
if let onDebugEvent { try? core.setDebugObserver(observer: EventHook(onDebugEvent), full: false) }
|
|
141
|
-
let hub: StreamHub
|
|
142
|
-
do { hub = try await Offload.run { try StreamHub(port: FFIStreamPort(core: core, images: host.images)) } }
|
|
143
|
-
catch { _ = try? await Offload.run { core.close(); return true }; host.stop(); host.session.close(); throw error }
|
|
144
|
-
let runtime = AgentEngine(core: core, host: host, logId: hub.logId)
|
|
145
|
-
await runtime.bind(hub)
|
|
146
|
-
try await runtime.refreshMemory()
|
|
147
|
-
host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
|
|
148
|
-
host.attach(core)
|
|
149
|
-
#if canImport(UIKit) && os(iOS)
|
|
150
|
-
await runtime.observeForeground()
|
|
151
|
-
#endif
|
|
152
|
-
if let wiki {
|
|
153
|
-
do { try await runtime.wiki.set(wiki) } catch { try? await runtime.close(); throw error }
|
|
154
|
-
}
|
|
155
|
-
return runtime
|
|
156
|
-
}
|
|
157
|
-
/// Adopts the Core returned by CoreProject; it never opens a second Runtime.
|
|
158
|
-
static func adopt(core: CoreRuntime, host: SwiftHost) async throws -> AgentEngine {
|
|
159
|
-
let hub: StreamHub
|
|
160
|
-
do { hub = try await Offload.run { try StreamHub(port: FFIStreamPort(core: core, images: host.images)) } }
|
|
161
|
-
catch { _ = try? await Offload.run { core.close(); return true }; host.stop(); host.session.close(); throw error }
|
|
162
|
-
let runtime = AgentEngine(core: core, host: host, logId: hub.logId)
|
|
163
|
-
await runtime.bind(hub)
|
|
164
|
-
try await runtime.refreshMemory()
|
|
165
|
-
host.deliver = { [weak runtime] in _ = try? await runtime?.deliverDue() }
|
|
166
|
-
host.attach(core)
|
|
167
|
-
#if canImport(UIKit) && os(iOS)
|
|
168
|
-
await runtime.observeForeground()
|
|
169
|
-
#endif
|
|
170
|
-
return runtime
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
func refreshMemory() async throws { memoryCache.set(try inspect()["memory"]) }
|
|
174
|
-
|
|
175
|
-
/// The founder's condition for debug keys: never silent in a shipped build.
|
|
176
|
-
static func warnIfReleaseBuildCarriesDebugKey(_ config: JSON) {
|
|
177
|
-
#if !DEBUG
|
|
178
|
-
if config["debugKey"].string != nil {
|
|
179
|
-
FileHandle.standardError.write(Data("[Croche] A debug key (debugKey) is set in a RELEASE build. It admits any install of this project without App Attest and must not ship.\n".utf8))
|
|
180
|
-
}
|
|
181
|
-
#endif
|
|
182
|
-
}
|
|
183
|
-
fileprivate func run(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
|
|
184
|
-
guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
|
|
185
|
-
let core = self.core
|
|
186
|
-
return try JSON(try await Offload.run { try body(core) })
|
|
187
|
-
}
|
|
188
|
-
/// Runs one turn. Cancelling the calling Task cancels this turn only (from any thread, never
|
|
189
|
-
/// missed): it ends `cancelled`, keeping what was said and charging an unanswered call.
|
|
190
|
-
/// `responseFormat`: structured output, OpenAI's shape (`{"type":"json_schema",...}` or
|
|
191
|
-
/// `{"type":"json_object"}`); the result's `output` is the reply as JSON the Core checked.
|
|
192
|
-
///
|
|
193
|
-
/// Sends are admitted in the order the calls reach the Runtime (one task's sends in program
|
|
194
|
-
/// order): that order is their place among held sends and in a turn they share.
|
|
195
|
-
/// `imageResolution`: for every image that does not name its own (default standard).
|
|
196
|
-
func send(_ input: JSON, responseFormat: JSON? = nil, imageResolution: ImageResolution? = nil) async throws -> JSON {
|
|
197
|
-
guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
|
|
198
|
-
// Admitted here, on the actor, before the hop to a thread of its own.
|
|
199
|
-
return try await beginSend(input, responseFormat: responseFormat, imageResolution: imageResolution).result()
|
|
200
|
-
}
|
|
201
|
-
/// Admits a send at once on the calling thread, without waiting for its turn: for a host
|
|
202
|
-
/// that must fix the order of sends before hopping threads (the React Native bridge).
|
|
203
|
-
nonisolated func beginSend(_ input: JSON, responseFormat: JSON? = nil, imageResolution: ImageResolution? = nil) throws -> PendingTurn {
|
|
204
|
-
// Standard images are re-encoded here, before admission, so sends keep their order.
|
|
205
|
-
let input = Images.prepareInput(input, fallback: imageResolution)
|
|
206
|
-
let text = String(decoding: try input.encoded(), as: UTF8.self)
|
|
207
|
-
let format = try responseFormat.map { String(decoding: try $0.encoded(), as: UTF8.self) }
|
|
208
|
-
let token = CancelToken()
|
|
209
|
-
do { return PendingTurn(try core.beginSend(input: text, cancel: token, responseFormat: format), token) }
|
|
210
|
-
catch { throw LegacyCrocheError(error) }
|
|
211
|
-
}
|
|
212
|
-
func sync() async throws -> JSON { try await run { try $0.sync(); return "null" } }
|
|
213
|
-
/// One round of background upkeep: deliver the outbox of call reports, then sync balances,
|
|
214
|
-
/// policy and the model key. The Core does work only when some is due and backs off after
|
|
215
|
-
/// a failure. Timer upkeep follows backgroundSync; call it when the app returns to the foreground.
|
|
216
|
-
/// Separately, Core delivers pending reports when the agent goes idle and after open,
|
|
217
|
-
/// even with backgroundSync off. That delivery never folds or syncs. It never delays a turn: a send takes over
|
|
218
|
-
/// while it waits on Cloud. Never throws; the result says what happened.
|
|
219
|
-
@discardableResult
|
|
220
|
-
func maintain(force: Bool = false) async -> JSON {
|
|
221
|
-
(try? await run { $0.maintain(force: force) }) ?? .object(["ran": .bool(false)])
|
|
222
|
-
}
|
|
223
|
-
/// Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
|
|
224
|
-
/// is (no turn, no cost) or one is already being delivered, else `{ran, ids, delivered, turn}`.
|
|
225
|
-
/// Never before a note's time. The iOS Runtime calls it at every foreground; elsewhere, call
|
|
226
|
-
/// it when the app returns.
|
|
227
|
-
///
|
|
228
|
-
/// Cancelling the calling Task cancels this delivery only: waiting behind another turn, it
|
|
229
|
-
/// leaves without running; running, its turn stops. Either way its notes stay pending.
|
|
230
|
-
/// Cancelled after the delivery ended, nothing happens: never another turn (`cancel()` stops
|
|
231
|
-
/// whatever turn runs).
|
|
232
|
-
///
|
|
233
|
-
/// Afterwards the pending set is handed to the OS scheduler again (a refusal is reported as
|
|
234
|
-
/// `schedule.degraded`): the OS spends a request when it runs it, and a delivery cut short
|
|
235
|
-
/// leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
|
|
236
|
-
/// ends. A failed delivery that answers `retryAt` waits until then.
|
|
237
|
-
@discardableResult
|
|
238
|
-
func deliverDue() async throws -> JSON {
|
|
239
|
-
guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
|
|
240
|
-
host.attempted()
|
|
241
|
-
let core = self.core
|
|
242
|
-
let token = CancelToken()
|
|
243
|
-
let result: JSON
|
|
244
|
-
do {
|
|
245
|
-
result = try await withTaskCancellationHandler {
|
|
246
|
-
try JSON(try await Offload.run { try core.deliverDue(cancel: token) })
|
|
247
|
-
} onCancel: { token.cancel() }
|
|
248
|
-
} catch { await resync(); throw error }
|
|
249
|
-
if result["inFlight"].bool == true { return result }
|
|
250
|
-
if let retry = retryAt(result["retryAt"]) { host.retryAfter(retry) }
|
|
251
|
-
await resync()
|
|
252
|
-
if result["ran"].bool == true { onDelivery?(result) }
|
|
253
|
-
return result
|
|
254
|
-
}
|
|
255
|
-
/// Hands the pending set to the OS scheduler again, through the Core, which reports a refusal
|
|
256
|
-
/// as `schedule.degraded`.
|
|
257
|
-
private func resync() async {
|
|
258
|
-
guard !closed else { return }
|
|
259
|
-
let core = self.core
|
|
260
|
-
_ = try? await Offload.run { try core.reschedule(); return true }
|
|
261
|
-
}
|
|
262
|
-
#if canImport(UIKit) && os(iOS)
|
|
263
|
-
private func observeForeground() {
|
|
264
|
-
foreground = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification,
|
|
265
|
-
object: nil, queue: nil) { [weak self] _ in
|
|
266
|
-
Task { _ = try? await self?.deliverDue() }
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
#endif
|
|
270
|
-
/// The agent's pending scheduled notes: `{pending: [{id, at, note}], due}`.
|
|
271
|
-
func schedules() async throws -> JSON { try await run { try $0.schedules() } }
|
|
272
|
-
func flush() async throws -> JSON { try await run { try $0.flush(); return "null" } }
|
|
273
|
-
/// Forgets this user's conversation and memory and starts over (money and identity stay).
|
|
274
|
-
/// The clear takes its place on the actor, as `send` does: behind a running turn, ahead of
|
|
275
|
-
/// every send that reaches the Runtime after it. Only the wait for it is on a thread of its own.
|
|
276
|
-
func clearHistory() async throws {
|
|
277
|
-
guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
|
|
278
|
-
if let subscriptionHub { try await subscriptionHub.clearHistory(); return }
|
|
279
|
-
try await Self.finish(beginClearHistory())
|
|
280
|
-
}
|
|
281
|
-
/// Admits a clear at once on the calling thread, for a host that must fix its order against
|
|
282
|
-
/// sends before hopping threads (the React Native bridge); `finish` then waits for it.
|
|
283
|
-
nonisolated func beginClearHistory() -> PendingClear { core.beginClearHistory() }
|
|
284
|
-
/// Waits for an admitted clear on a thread of its own.
|
|
285
|
-
static func finish(_ pending: PendingClear) async throws {
|
|
286
|
-
_ = try await Offload.run { try pending.finish(); return true }
|
|
287
|
-
}
|
|
288
|
-
/// Internal until `memory history` (B3): turns `from...to` from the turn archive, as
|
|
289
|
-
/// `{"records":[...]}`; `archive_unavailable` when the storage keeps none.
|
|
290
|
-
func archiveRead(from: UInt64, to: UInt64) async throws -> JSON {
|
|
291
|
-
try await run { try $0.archiveRead(from: from, to: to) }
|
|
292
|
-
}
|
|
293
|
-
/// Internal: deletes archived turns, every one without a range.
|
|
294
|
-
func archiveClear(from: UInt64? = nil, to: UInt64? = nil) async throws {
|
|
295
|
-
_ = try await run { try $0.archiveClear(from: from, to: to); return "null" }
|
|
296
|
-
}
|
|
297
|
-
func inspect() throws -> JSON {
|
|
298
|
-
guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
|
|
299
|
-
do { return try JSON(try core.inspect()) } catch { throw LegacyCrocheError(error) }
|
|
300
|
-
}
|
|
301
|
-
/// Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
|
|
302
|
-
/// The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
|
|
303
|
-
/// its place in the queue, so turns sent before it still offer the old list. A removed or
|
|
304
|
-
/// changed command answers `withdrawn` once the swap applies. A handler given here also
|
|
305
|
-
/// serves turns already queued under the same name.
|
|
306
|
-
func setTools(_ tools: JSON, handlers: [String: ToolHandler]) throws {
|
|
307
|
-
guard !closed else { throw LegacyCrocheError("closed", "Runtime is closed") }
|
|
308
|
-
let text = String(decoding: try tools.encoded(), as: UTF8.self)
|
|
309
|
-
// New names first: the Core cannot call them before it accepts the list. Replacements
|
|
310
|
-
// only after it accepts; a refusal removes what it staged, so every handler is as it was.
|
|
311
|
-
let stamp = host.stageTools(handlers)
|
|
312
|
-
do { try core.setToolDeclarations(tools: text) } catch { host.unstageTools(handlers.keys, stamp: stamp); throw LegacyCrocheError(error) }
|
|
313
|
-
host.acceptTools(handlers)
|
|
314
|
-
}
|
|
315
|
-
/// The tool list the model is offered (metadata only).
|
|
316
|
-
func tools() throws -> JSON { try inspect()["tools"] }
|
|
317
|
-
/// Stops the running turn only: messages sent while it ran still go, together, as the next
|
|
318
|
-
/// turn. Cancelling a send's Task drops just that send while it is held; once its turn has
|
|
319
|
-
/// started, the turn stops, for every send it carries.
|
|
320
|
-
func cancel() { core.cancelTurn() }
|
|
321
|
-
/// Drops the messages held behind the running turn (each send ends `cancelled`); returns how many.
|
|
322
|
-
/// Resolves once the held record no longer lists them.
|
|
323
|
-
@discardableResult func clearQueued() async throws -> Int {
|
|
324
|
-
guard !closed else { return 0 }
|
|
325
|
-
let core = self.core
|
|
326
|
-
return Int(try await Offload.run { try core.clearQueued() })
|
|
327
|
-
}
|
|
328
|
-
/// Long-term memory: `snapshot()` for a read-only view, the other methods to manage it.
|
|
329
|
-
nonisolated var memory: CrocheMemory { CrocheMemory(runtime: self) }
|
|
330
|
-
/// The app's knowledge documents, held by the Rust Core in memory (never stored: load them
|
|
331
|
-
/// on each open). The model searches and reads them with the built-in `wiki` command;
|
|
332
|
-
/// `list`, `read` and `search` here are that same view.
|
|
333
|
-
nonisolated var wiki: CrocheWiki { CrocheWiki(runtime: self) }
|
|
334
|
-
/// Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
|
|
335
|
-
/// call upkeep has in flight is finished and settled first.
|
|
336
|
-
/// The Core projection fence does not await buffered AsyncStream/UI consumers.
|
|
337
|
-
/// An app callback that waits for work on the closer's thread deadlocks under any
|
|
338
|
-
/// wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself.
|
|
339
|
-
func close() async throws {
|
|
340
|
-
if closed { return }
|
|
341
|
-
closed = true
|
|
342
|
-
memoryCache.close()
|
|
343
|
-
subscriptionHub?.close()
|
|
344
|
-
host.stop()
|
|
345
|
-
#if canImport(UIKit) && os(iOS)
|
|
346
|
-
if let foreground { NotificationCenter.default.removeObserver(foreground) }
|
|
347
|
-
foreground = nil
|
|
348
|
-
#endif
|
|
349
|
-
let core = self.core
|
|
350
|
-
_ = try await Offload.run { core.close(); return true }
|
|
351
|
-
// After the Core: a paid call upkeep has in flight is finished first.
|
|
352
|
-
host.session.close()
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/// `runtime.memory`: this person's long-term memory, as the TS SDK's `runtime.memory`.
|
|
357
|
-
struct CrocheMemory: Sendable {
|
|
358
|
-
fileprivate let runtime: AgentEngine
|
|
359
|
-
/// The memory part of `inspect()`.
|
|
360
|
-
func callAsFunction() -> JSON { runtime.memoryCache.value }
|
|
361
|
-
func snapshot() async throws -> JSON { try await runtime.refreshMemory(); return callAsFunction() }
|
|
362
|
-
private func refreshed(_ body: @escaping @Sendable (CoreRuntime) throws -> String) async throws -> JSON {
|
|
363
|
-
let result = try await runtime.run(body)
|
|
364
|
-
if result["deferred"].bool != true { try? await runtime.refreshMemory() }
|
|
365
|
-
return result
|
|
366
|
-
}
|
|
367
|
-
/// AI-written facts with ids, turn/time stamps, refs and replacement links.
|
|
368
|
-
func list() async throws -> JSON { try await refreshed { try $0.memoryList() } }
|
|
369
|
-
/// `{deleted}`, or `{deferred: true}` (see `WriteResult`).
|
|
370
|
-
@discardableResult
|
|
371
|
-
func delete(_ id: String) async throws -> JSON { try await refreshed { try $0.memoryDelete(id: id) } }
|
|
372
|
-
/// Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
|
|
373
|
-
/// `{deferred: true}` (see `WriteResult`).
|
|
374
|
-
@discardableResult
|
|
375
|
-
func clear() async throws -> JSON { try await refreshed { try $0.memoryClear() } }
|
|
376
|
-
/// Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied, it
|
|
377
|
-
/// carries the setting now in force.
|
|
378
|
-
@discardableResult
|
|
379
|
-
func enabled(_ on: Bool) async throws -> WriteResult<Bool> {
|
|
380
|
-
WriteResult(try await refreshed { try $0.memorySetEnabled(enabled: on) }) { _ in on }
|
|
381
|
-
}
|
|
382
|
-
/// Current and replaced AI-written facts: `{enabled, items}`, not the summary.
|
|
383
|
-
func export() async throws -> JSON { try await refreshed { try $0.memoryExport() } }
|
|
384
|
-
/// Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's).
|
|
385
|
-
func onChanged(_ listener: (@Sendable (MemoryChangedEvent) -> Void)?) throws {
|
|
386
|
-
guard !runtime.memoryCache.closed else { throw LegacyCrocheError("closed", "The agent is closed.") }
|
|
387
|
-
do {
|
|
388
|
-
runtime.core.setMemoryObserver(observer: listener.map { callback in EventHook { event in
|
|
389
|
-
Task { try? await runtime.refreshMemory() }
|
|
390
|
-
callback(event)
|
|
391
|
-
} })
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
58
|
extension WikiDocument {
|
|
397
59
|
/// The `.md` files under `directory` as wiki documents, paths relative to it with `/`
|
|
398
60
|
/// (`menu/stew.md`), in name order. Subfolders are read; symbolic links and other files are
|
|
@@ -412,7 +74,6 @@ extension WikiDocument {
|
|
|
412
74
|
if type == .typeDirectory {
|
|
413
75
|
try walk(url, path)
|
|
414
76
|
} else if type == .typeRegular && name.hasSuffix(".md") {
|
|
415
|
-
if out.count >= 2000 { throw LegacyCrocheError("invalid_wiki", "The wiki holds at most 2000 documents") }
|
|
416
77
|
out.append(WikiDocument(path: path, markdown: String(decoding: try Data(contentsOf: url), as: UTF8.self)))
|
|
417
78
|
}
|
|
418
79
|
}
|
|
@@ -430,67 +91,6 @@ extension WikiDocument {
|
|
|
430
91
|
}
|
|
431
92
|
}
|
|
432
93
|
|
|
433
|
-
/// `runtime.wiki`: the app's documents, as the TS SDK's `runtime.wiki`.
|
|
434
|
-
struct CrocheWiki: Sendable {
|
|
435
|
-
fileprivate let runtime: AgentEngine
|
|
436
|
-
private static func json(_ docs: [WikiDocument]) throws -> String {
|
|
437
|
-
let value = JSON.array(docs.map { doc in
|
|
438
|
-
var o: [String: JSON] = ["path": .string(doc.path), "markdown": .string(doc.markdown)]
|
|
439
|
-
if let agents = doc.agents { o["agents"] = .array(agents.map { .string($0) }) }
|
|
440
|
-
return .object(o)
|
|
441
|
-
})
|
|
442
|
-
return String(decoding: try value.encoded(), as: UTF8.self)
|
|
443
|
-
}
|
|
444
|
-
/// Replaces every document and answers what it installed: `{documents, bytes, digest}`.
|
|
445
|
-
/// On an error nothing changes.
|
|
446
|
-
@discardableResult
|
|
447
|
-
func set(_ docs: [WikiDocument]) async throws -> JSON {
|
|
448
|
-
let text = try Self.json(docs)
|
|
449
|
-
return try await runtime.run { try $0.wikiSet(docs: text) }
|
|
450
|
-
}
|
|
451
|
-
/// `set`, without the digest.
|
|
452
|
-
func load(_ docs: [WikiDocument]) async throws { try await set(docs) }
|
|
453
|
-
/// This user's own documents (saved recipes, lesson notes): stored with their state (at most
|
|
454
|
-
/// 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable when
|
|
455
|
-
/// this returns. `clearHistory` keeps them. To share one with another character, put it to that character's Runtime too.
|
|
456
|
-
/// Answers `{documents, bytes}`, or `{deferred: true}` (see `WriteResult`).
|
|
457
|
-
@discardableResult
|
|
458
|
-
func putUser(_ docs: [WikiDocument]) async throws -> JSON {
|
|
459
|
-
let text = try Self.json(docs)
|
|
460
|
-
return try await runtime.run { try $0.wikiPutUser(docs: text) }
|
|
461
|
-
}
|
|
462
|
-
/// Removes one of this user's own documents; whether it existed.
|
|
463
|
-
@discardableResult
|
|
464
|
-
func removeUser(_ path: String) async throws -> WriteResult<Bool> {
|
|
465
|
-
WriteResult(try await runtime.run { try $0.wikiRemoveUser(path: path) }) { $0["removed"].bool ?? false }
|
|
466
|
-
}
|
|
467
|
-
/// Removes every one of this user's own documents; how many.
|
|
468
|
-
@discardableResult
|
|
469
|
-
func clearUser() async throws -> WriteResult<Int> {
|
|
470
|
-
WriteResult(try await runtime.run { try $0.wikiClearUser() }) { Int($0["cleared"].number ?? 0) }
|
|
471
|
-
}
|
|
472
|
-
/// Adds documents or replaces those with the same path, atomically.
|
|
473
|
-
func put(_ docs: [WikiDocument]) async throws {
|
|
474
|
-
let text = try Self.json(docs)
|
|
475
|
-
_ = try await runtime.run { try $0.wikiPut(docs: text); return "null" }
|
|
476
|
-
}
|
|
477
|
-
/// Whether the document existed.
|
|
478
|
-
@discardableResult
|
|
479
|
-
func remove(_ path: String) async throws -> Bool {
|
|
480
|
-
try await runtime.run { try $0.wikiRemove(path: path) ? "true" : "false" }.bool ?? false
|
|
481
|
-
}
|
|
482
|
-
/// `[{path, title, summary?, characters, parts}]` under `folder` (every document when nil).
|
|
483
|
-
func list(folder: String? = nil) async throws -> JSON { try await runtime.run { try $0.wikiList(folder: folder) } }
|
|
484
|
-
/// One part (1-based) of a document, `{path, title, part, parts, text}`; `.null` when none.
|
|
485
|
-
func read(_ path: String, part: Int = 1) async throws -> JSON {
|
|
486
|
-
try await runtime.run { try $0.wikiRead(path: path, part: UInt32(clamping: max(0, part))) }
|
|
487
|
-
}
|
|
488
|
-
/// The best matches, best first: at most `limit` (and 5).
|
|
489
|
-
func search(_ query: String, limit: Int = 5) async throws -> JSON {
|
|
490
|
-
try await runtime.run { try $0.wikiSearch(query: query, limit: UInt32(clamping: min(max(0, limit), 5))) }
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
|
|
494
94
|
/// What a write (memory, this user's own documents, the allowance) answers: `.applied`, with what
|
|
495
95
|
/// it did, or `.deferred`: it was called while another operation ran, was accepted, and applies in
|
|
496
96
|
/// call order when that operation ends. A message sent after the write sees it; one sent before
|
|
@@ -508,18 +108,7 @@ extension WriteResult: Equatable where Value: Equatable {}
|
|
|
508
108
|
|
|
509
109
|
/// A send `beginSend` admitted. Its result, once: `result()` blocks a thread of its own, and
|
|
510
110
|
/// cancelling the awaiting Task cancels this send only.
|
|
511
|
-
|
|
512
|
-
private let pending: PendingSend
|
|
513
|
-
private let token: CancelToken
|
|
514
|
-
fileprivate init(_ pending: PendingSend, _ token: CancelToken) { self.pending = pending; self.token = token }
|
|
515
|
-
func result() async throws -> JSON {
|
|
516
|
-
let pending = self.pending
|
|
517
|
-
return try await withTaskCancellationHandler {
|
|
518
|
-
try JSON(try await Offload.run { try pending.wait() })
|
|
519
|
-
} onCancel: { [token] in token.cancel() }
|
|
520
|
-
}
|
|
521
|
-
func cancel() { token.cancel() }
|
|
522
|
-
}
|
|
111
|
+
|
|
523
112
|
|
|
524
113
|
final class RuntimeMemoryCache: @unchecked Sendable {
|
|
525
114
|
private let lock = NSLock()
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Shared app-transport adapter for S1 and the native bridge test host.
|
|
4
|
+
enum RuntimeHTTPAdapter {
|
|
5
|
+
/// An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
|
|
6
|
+
/// a response, and its stream deltas as server-sent events.
|
|
7
|
+
static func adapt(_ transport: RuntimeHTTP, _ request: PalHttpRequest, _ sink: HttpSink,
|
|
8
|
+
_ signal: RuntimeCancellation) async throws {
|
|
9
|
+
var headers: [String: JSON] = [:]
|
|
10
|
+
for header in request.headers { headers[header.name] = .string(header.value) }
|
|
11
|
+
let effect = JSON.object(["url": .string(request.url), "method": .string(request.method), "headers": .object(headers),
|
|
12
|
+
"body": request.body.map { (try? JSON($0)) ?? .string($0) } ?? .null,
|
|
13
|
+
"timeoutMs": .number(Double(request.timeoutMs))])
|
|
14
|
+
let streaming = StreamStart()
|
|
15
|
+
let reply = try await transport(effect, signal) { data in
|
|
16
|
+
if streaming.begin() {
|
|
17
|
+
sink.head(status: 200, headers: [PalHeader(name: "content-type", value: "text/event-stream")])
|
|
18
|
+
}
|
|
19
|
+
let frame = data.split(separator: "\n", omittingEmptySubsequences: false).map { "data: \($0)\n" }.joined() + "\n"
|
|
20
|
+
_ = sink.chunk(bytes: Data(frame.utf8))
|
|
21
|
+
}
|
|
22
|
+
let status = UInt16(reply["status"].number ?? 0)
|
|
23
|
+
var fields = (reply["headers"].object ?? [:]).compactMap { key, value in value.string.map { PalHeader(name: key, value: $0) } }
|
|
24
|
+
if reply["streamed"] == .bool(true) {
|
|
25
|
+
if streaming.begin() { sink.head(status: status, headers: [PalHeader(name: "content-type", value: "text/event-stream")]) }
|
|
26
|
+
return
|
|
27
|
+
}
|
|
28
|
+
fields.removeAll { $0.name.lowercased() == "content-type" }
|
|
29
|
+
fields.append(PalHeader(name: "content-type", value: "application/json"))
|
|
30
|
+
sink.head(status: status, headers: fields)
|
|
31
|
+
let body = reply["body"] != .null ? try reply["body"].encoded() : Data((reply["raw"].string ?? "").utf8)
|
|
32
|
+
if !body.isEmpty { _ = sink.chunk(bytes: body) }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private final class StreamStart: @unchecked Sendable {
|
|
38
|
+
private let lock = NSLock()
|
|
39
|
+
private var started = false
|
|
40
|
+
/// True once: the first caller starts the stream.
|
|
41
|
+
func begin() -> Bool { lock.withLock { if started { return false }; started = true; return true } }
|
|
42
|
+
}
|
|
@@ -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
|
+
}
|