@h1r-ai/croche-react-native 0.5.5 → 0.6.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/README.md +69 -458
- package/THIRD-PARTY-NOTICES +7 -8
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -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/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -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/WorkManagerScheduler.kt +8 -8
- 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 +121 -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/AndroidStoragePal.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -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 +31 -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 +128 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -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 +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -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/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 +3 -0
- package/dist/react-native/src/core-native.js +193 -0
- package/dist/react-native/src/core-wire.d.ts +38 -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/agent.d.ts +43 -0
- package/dist/runtime/src/agent.js +75 -0
- package/dist/runtime/src/app-api.d.ts +284 -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 +24 -0
- package/dist/runtime/src/core/port.d.ts +234 -0
- package/dist/runtime/src/core/port.js +1 -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 +42 -0
- package/dist/runtime/src/croche.js +111 -0
- package/dist/runtime/src/errors.d.ts +26 -0
- package/dist/runtime/src/errors.js +49 -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 +174 -0
- package/dist/runtime/src/generated/app-stream.js +124 -0
- package/dist/runtime/src/index.native.d.ts +21 -0
- package/dist/runtime/src/index.native.js +8 -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 +24 -0
- package/dist/runtime/src/pal/codec.d.ts +15 -0
- package/dist/runtime/src/pal/codec.js +52 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +35 -0
- package/dist/runtime/src/pal/platform.d.ts +16 -0
- package/dist/runtime/src/pal/platform.js +7 -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 +19 -0
- package/dist/runtime/src/tools.js +70 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +93 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +92 -0
- package/ios/CoreWireSupport.swift +111 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +46 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
- 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 +1342 -218
- 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/vendor-native.sh +5 -4
- 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/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/src/index.ts +0 -664
- package/src/project-types.ts +0 -35
- package/src/project.ts +0 -434
- package/src/protocol.ts +0 -28
- package/src/types.ts +0 -9
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(CryptoKit)
|
|
3
|
+
import CryptoKit
|
|
4
|
+
#endif
|
|
5
|
+
#if canImport(ImageIO)
|
|
6
|
+
import ImageIO
|
|
7
|
+
#endif
|
|
8
|
+
#if canImport(UIKit)
|
|
9
|
+
import UIKit
|
|
10
|
+
#elseif canImport(AppKit)
|
|
11
|
+
import AppKit
|
|
12
|
+
#endif
|
|
13
|
+
|
|
14
|
+
/// Private native image PAL (Rev 4a), the Swift twin of the TypeScript `ImagePal`. Core owns
|
|
15
|
+
/// admission, sizing plans, budgets, deadlines and every URL; this only holds owned captures and
|
|
16
|
+
/// decodes/encodes to the plan Core gives. Names, codes and messages match TypeScript.
|
|
17
|
+
final class NativeImagePal: @unchecked Sendable {
|
|
18
|
+
// No size, byte or pixel limits of its own (Leo 18:40Z): Core owns admission and passes each
|
|
19
|
+
// bound it applies (read and plan maxBytes, render sizes). Only decoder facts refuse here.
|
|
20
|
+
|
|
21
|
+
private let lock = NSLock()
|
|
22
|
+
private var captures: [String: Data] = [:]
|
|
23
|
+
#if canImport(ImageIO)
|
|
24
|
+
/// Decoded pixels by handle: private to this process, never sent across the bridge.
|
|
25
|
+
private var decoded: [String: CGImage] = [:]
|
|
26
|
+
#endif
|
|
27
|
+
private var closed = false
|
|
28
|
+
|
|
29
|
+
/// A platform decoder is present (ImageIO). No I/O.
|
|
30
|
+
var codecAvailable: Bool {
|
|
31
|
+
#if canImport(ImageIO)
|
|
32
|
+
return true
|
|
33
|
+
#else
|
|
34
|
+
return false
|
|
35
|
+
#endif
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/// Snapshot encoded bytes at the reserved entry boundary; returns the capture token.
|
|
39
|
+
func capture(_ bytes: Data) throws -> String {
|
|
40
|
+
let owned = Data(bytes) // Value copy: later caller mutation cannot reach it.
|
|
41
|
+
let token = UUID().uuidString
|
|
42
|
+
try lock.withLock {
|
|
43
|
+
if closed { throw LegacyCrocheError("closed", "The Runtime is closed.") }
|
|
44
|
+
captures[token] = owned
|
|
45
|
+
}
|
|
46
|
+
return token
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// Raw bytes only (#830 b4ace3eb): Core sniffs the MIME type and hashes.
|
|
50
|
+
func read(_ request: PalImageReadRequest, _ cancel: CancelToken) throws -> Data {
|
|
51
|
+
try Self.check(cancel)
|
|
52
|
+
let token: String
|
|
53
|
+
switch request.source {
|
|
54
|
+
case .capture(let value): token = value
|
|
55
|
+
case .local(let uri): return try Self.readLocal(uri, maxBytes: Int(request.maxBytes), cancel)
|
|
56
|
+
}
|
|
57
|
+
// A capture is taken once; a second read finds nothing.
|
|
58
|
+
let bytes = lock.withLock { captures.removeValue(forKey: token) }
|
|
59
|
+
guard let bytes, UInt64(bytes.count) <= request.maxBytes else { throw Self.failure("image_fetch_failed") }
|
|
60
|
+
try Self.check(cancel)
|
|
61
|
+
return bytes
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
func prepare(_ source: PalImageBytes, _ plan: PalImagePreparePlan, _ cancel: CancelToken) throws -> PalImageBytes {
|
|
65
|
+
try Self.check(cancel)
|
|
66
|
+
if let side = plan.maxSide, side < 1 { throw Self.failure("image_unsupported") }
|
|
67
|
+
guard codecAvailable else { throw Self.failure("image_unsupported") }
|
|
68
|
+
do {
|
|
69
|
+
return try Self.prepareVerified(source, maxSide: plan.maxSide.map(Int.init), maxBytes: Int(plan.maxBytes), cancel)
|
|
70
|
+
} catch {
|
|
71
|
+
try Self.check(cancel)
|
|
72
|
+
throw Self.failure("image_unsupported")
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// Idempotent.
|
|
77
|
+
func release(_ token: String) { lock.withLock { _ = captures.removeValue(forKey: token) } }
|
|
78
|
+
|
|
79
|
+
func close() {
|
|
80
|
+
lock.withLock {
|
|
81
|
+
closed = true; captures.removeAll()
|
|
82
|
+
#if canImport(ImageIO)
|
|
83
|
+
decoded.removeAll()
|
|
84
|
+
#endif
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// MARK: Local URI (S3: iOS reads file:// only; ph:// is out for 0.6)
|
|
89
|
+
|
|
90
|
+
/// A `file://` URL into an owned buffer: bounded by `maxBytes`, read in pieces with a cancel
|
|
91
|
+
/// check between them. Anything else, a missing file, a directory or an oversize file is
|
|
92
|
+
/// `image_fetch_failed`.
|
|
93
|
+
static func readLocal(_ uri: String, maxBytes: Int, _ cancel: CancelToken) throws -> Data {
|
|
94
|
+
guard let url = URL(string: uri), url.isFileURL, !url.path.isEmpty,
|
|
95
|
+
let handle = try? FileHandle(forReadingFrom: url) else { throw failure("image_fetch_failed") }
|
|
96
|
+
defer { try? handle.close() }
|
|
97
|
+
var isDirectory: ObjCBool = false
|
|
98
|
+
guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), !isDirectory.boolValue else { throw failure("image_fetch_failed") }
|
|
99
|
+
var bytes = Data()
|
|
100
|
+
while true {
|
|
101
|
+
try check(cancel)
|
|
102
|
+
// One byte past the bound proves the file is too large without reading all of it.
|
|
103
|
+
let piece = (try? handle.read(upToCount: min(256 * 1024, maxBytes + 1 - bytes.count))) ?? nil
|
|
104
|
+
guard let piece, !piece.isEmpty else { break }
|
|
105
|
+
bytes.append(piece)
|
|
106
|
+
if bytes.count > maxBytes { throw failure("image_fetch_failed") }
|
|
107
|
+
}
|
|
108
|
+
guard !bytes.isEmpty else { throw failure("image_fetch_failed") }
|
|
109
|
+
try check(cancel)
|
|
110
|
+
return bytes
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// MARK: Codec primitives (S3): Core chooses frame, orientation, sizes and formats
|
|
114
|
+
|
|
115
|
+
/// Decodes `bytes` (no MIME selects a decoder) into private RGBA8 pixels. `hasAlpha` is true
|
|
116
|
+
/// only when a pixel is not opaque, never because the format could carry alpha.
|
|
117
|
+
func decode(_ bytes: Data, _ options: PalImageDecodeOptions, _ cancel: CancelToken) throws -> PalDecodedImage {
|
|
118
|
+
try Self.check(cancel)
|
|
119
|
+
#if canImport(ImageIO)
|
|
120
|
+
let image = try Self.decodePixels(bytes, frame: Int(options.frame), orient: options.applyOrientation, cancel)
|
|
121
|
+
let hasAlpha = try Self.anyTransparent(image, cancel)
|
|
122
|
+
let handle = UUID().uuidString
|
|
123
|
+
try lock.withLock {
|
|
124
|
+
if closed { throw LegacyCrocheError("closed", "The Runtime is closed.") }
|
|
125
|
+
decoded[handle] = image
|
|
126
|
+
}
|
|
127
|
+
// A cancel that lands after the store still wins; the handle is not leaked.
|
|
128
|
+
if cancel.isCancelled() { releaseDecoded(handle); throw Self.cancelled }
|
|
129
|
+
return PalDecodedImage(handle: handle, width: UInt32(image.width), height: UInt32(image.height), hasAlpha: hasAlpha)
|
|
130
|
+
#else
|
|
131
|
+
throw LegacyCrocheError("invalid_input", "The image could not be decoded.")
|
|
132
|
+
#endif
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Encodes a decoded handle at exactly `width`×`height`. `quality` (0...1) applies to JPEG.
|
|
136
|
+
func render(_ request: PalImageRenderRequest, _ cancel: CancelToken) throws -> Data {
|
|
137
|
+
try Self.check(cancel)
|
|
138
|
+
#if canImport(ImageIO)
|
|
139
|
+
guard let image = lock.withLock({ decoded[request.handle] }),
|
|
140
|
+
request.width >= 1, request.height >= 1 else {
|
|
141
|
+
throw Self.failure("image_unsupported")
|
|
142
|
+
}
|
|
143
|
+
if let quality = request.quality, !(0...1).contains(quality) { throw Self.failure("image_unsupported") }
|
|
144
|
+
let jpeg = request.format == .jpeg
|
|
145
|
+
let scaled = try Self.draw(image, width: Int(request.width), height: Int(request.height), opaque: jpeg)
|
|
146
|
+
try Self.check(cancel)
|
|
147
|
+
guard let out = Self.encode(scaled, jpeg ? "public.jpeg" : "public.png", jpeg ? request.quality : nil) else {
|
|
148
|
+
throw Self.failure("image_unsupported")
|
|
149
|
+
}
|
|
150
|
+
try Self.check(cancel)
|
|
151
|
+
return out
|
|
152
|
+
#else
|
|
153
|
+
throw Self.failure("image_unsupported")
|
|
154
|
+
#endif
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/// Live decoded handles (tests prove nothing leaks).
|
|
158
|
+
var decodedCount: Int {
|
|
159
|
+
#if canImport(ImageIO)
|
|
160
|
+
lock.withLock { decoded.count }
|
|
161
|
+
#else
|
|
162
|
+
0
|
|
163
|
+
#endif
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/// Synchronous and idempotent, including after a cancel.
|
|
167
|
+
func releaseDecoded(_ handle: String) {
|
|
168
|
+
#if canImport(ImageIO)
|
|
169
|
+
lock.withLock { _ = decoded.removeValue(forKey: handle) }
|
|
170
|
+
#endif
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
#if canImport(ImageIO)
|
|
174
|
+
|
|
175
|
+
private static func decodePixels(_ bytes: Data, frame: Int, orient: Bool, _ cancel: CancelToken) throws -> CGImage {
|
|
176
|
+
let undecodable = LegacyCrocheError("invalid_input", "The image could not be decoded.")
|
|
177
|
+
// A truncated JPEG/PNG would be drawn with filler; refuse it as TypeScript does.
|
|
178
|
+
if let mime = mime(bytes), !complete(bytes, mime) { throw undecodable }
|
|
179
|
+
guard let source = CGImageSourceCreateWithData(bytes as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),
|
|
180
|
+
frame >= 0, frame < CGImageSourceGetCount(source),
|
|
181
|
+
CGImageSourceGetStatusAtIndex(source, frame) == .statusComplete,
|
|
182
|
+
let properties = CGImageSourceCopyPropertiesAtIndex(source, frame, nil) as? [CFString: Any],
|
|
183
|
+
let w = properties[kCGImagePropertyPixelWidth] as? Int, let h = properties[kCGImagePropertyPixelHeight] as? Int,
|
|
184
|
+
w > 0, h > 0, !w.multipliedReportingOverflow(by: h).overflow else { throw undecodable }
|
|
185
|
+
try check(cancel)
|
|
186
|
+
guard let raw = CGImageSourceCreateImageAtIndex(source, frame, [kCGImageSourceShouldCacheImmediately: true] as CFDictionary) else { throw undecodable }
|
|
187
|
+
try check(cancel)
|
|
188
|
+
let orientation = orient ? ((properties[kCGImagePropertyOrientation] as? NSNumber)?.intValue ?? 1) : 1
|
|
189
|
+
return try upright(raw, orientation: (1...8).contains(orientation) ? orientation : 1)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/// Draws into an owned sRGB RGBA8 buffer, applying EXIF orientation 1-8.
|
|
193
|
+
private static func upright(_ image: CGImage, orientation: Int) throws -> CGImage {
|
|
194
|
+
let w = image.width, h = image.height, swapped = (5...8).contains(orientation)
|
|
195
|
+
let outW = swapped ? h : w, outH = swapped ? w : h
|
|
196
|
+
guard let context = CGContext(data: nil, width: outW, height: outH, bitsPerComponent: 8, bytesPerRow: outW * 4,
|
|
197
|
+
space: CGColorSpace(name: CGColorSpace.sRGB)!,
|
|
198
|
+
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { throw platformFault }
|
|
199
|
+
let W = CGFloat(outW), H = CGFloat(outH)
|
|
200
|
+
// EXIF orientation as a transform in Core Graphics' bottom-left coordinates.
|
|
201
|
+
let t: CGAffineTransform
|
|
202
|
+
switch orientation {
|
|
203
|
+
case 2: t = CGAffineTransform(a: -1, b: 0, c: 0, d: 1, tx: W, ty: 0)
|
|
204
|
+
case 3: t = CGAffineTransform(a: -1, b: 0, c: 0, d: -1, tx: W, ty: H)
|
|
205
|
+
case 4: t = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: H)
|
|
206
|
+
case 5: t = CGAffineTransform(a: 0, b: -1, c: -1, d: 0, tx: W, ty: H)
|
|
207
|
+
case 6: t = CGAffineTransform(a: 0, b: -1, c: 1, d: 0, tx: 0, ty: H)
|
|
208
|
+
case 7: t = CGAffineTransform(a: 0, b: 1, c: 1, d: 0, tx: 0, ty: 0)
|
|
209
|
+
case 8: t = CGAffineTransform(a: 0, b: 1, c: -1, d: 0, tx: W, ty: 0)
|
|
210
|
+
default: t = .identity
|
|
211
|
+
}
|
|
212
|
+
context.concatenate(t)
|
|
213
|
+
context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))
|
|
214
|
+
guard let out = context.makeImage() else { throw platformFault }
|
|
215
|
+
return out
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/// True when any pixel's alpha is below 255: a scan of the actual RGBA8 pixels.
|
|
219
|
+
private static func anyTransparent(_ image: CGImage, _ cancel: CancelToken) throws -> Bool {
|
|
220
|
+
guard let data = image.dataProvider?.data, let base = CFDataGetBytePtr(data) else { throw platformFault }
|
|
221
|
+
let row = image.bytesPerRow, w = image.width
|
|
222
|
+
for y in 0..<image.height {
|
|
223
|
+
if y % 256 == 0 { try check(cancel) }
|
|
224
|
+
let line = base + y * row
|
|
225
|
+
for x in 0..<w where line[x * 4 + 3] != 255 { return true }
|
|
226
|
+
}
|
|
227
|
+
return false
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private static func draw(_ image: CGImage, width: Int, height: Int, opaque: Bool) throws -> CGImage {
|
|
231
|
+
let info = opaque ? CGImageAlphaInfo.noneSkipLast.rawValue : CGImageAlphaInfo.premultipliedLast.rawValue
|
|
232
|
+
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
|
|
233
|
+
space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info) else { throw failure("image_unsupported") }
|
|
234
|
+
context.interpolationQuality = .high
|
|
235
|
+
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
|
|
236
|
+
guard let out = context.makeImage() else { throw failure("image_unsupported") }
|
|
237
|
+
return out
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private static func encode(_ image: CGImage, _ type: String, _ quality: Double?) -> Data? {
|
|
241
|
+
let out = NSMutableData()
|
|
242
|
+
guard let destination = CGImageDestinationCreateWithData(out, type as CFString, 1, nil) else { return nil }
|
|
243
|
+
CGImageDestinationAddImage(destination, image, quality.map { [kCGImageDestinationLossyCompressionQuality: $0] as CFDictionary })
|
|
244
|
+
return CGImageDestinationFinalize(destination) ? out as Data : nil
|
|
245
|
+
}
|
|
246
|
+
#endif
|
|
247
|
+
|
|
248
|
+
// MARK: Preparation (same steps as TypeScript `prepareImageBytes`)
|
|
249
|
+
|
|
250
|
+
private static func prepareVerified(_ asset: PalImageBytes, maxSide: Int?, maxBytes: Int, _ cancel: CancelToken) throws -> PalImageBytes {
|
|
251
|
+
let bytes = asset.bytes
|
|
252
|
+
guard let mime = mime(bytes), complete(bytes, mime) else { throw failure("image_unsupported") }
|
|
253
|
+
let digest = sha256(bytes)
|
|
254
|
+
guard asset.sha256 == digest else { throw failure("image_unsupported") }
|
|
255
|
+
try check(cancel)
|
|
256
|
+
#if canImport(ImageIO)
|
|
257
|
+
guard let opened = OpenedImage(bytes) else { throw failure("image_unsupported") }
|
|
258
|
+
let sourceWidth = opened.width, sourceHeight = opened.height
|
|
259
|
+
let scale = maxSide.map { min(1, Double($0) / Double(max(sourceWidth, sourceHeight))) } ?? 1
|
|
260
|
+
var width = max(1, Int((Double(sourceWidth) * scale).rounded()))
|
|
261
|
+
var height = max(1, Int((Double(sourceHeight) * scale).rounded()))
|
|
262
|
+
for attempt in 0..<8 {
|
|
263
|
+
try check(cancel)
|
|
264
|
+
let rendered = try opened.render(width: width, height: height)
|
|
265
|
+
try check(cancel)
|
|
266
|
+
var candidates: [PalImageBytes] = []
|
|
267
|
+
if rendered.png.count <= maxBytes { candidates.append(PalImageBytes(bytes: rendered.png, mime: "image/png", sha256: sha256(rendered.png))) }
|
|
268
|
+
if let jpeg = rendered.jpeg, jpeg.count <= maxBytes { candidates.append(PalImageBytes(bytes: jpeg, mime: "image/jpeg", sha256: sha256(jpeg))) }
|
|
269
|
+
if width == sourceWidth && height == sourceHeight && mime != "image/gif" && !opened.reoriented {
|
|
270
|
+
candidates.append(PalImageBytes(bytes: bytes, mime: mime, sha256: digest))
|
|
271
|
+
}
|
|
272
|
+
if let best = candidates.min(by: { $0.bytes.count < $1.bytes.count }), best.bytes.count <= maxBytes { return best }
|
|
273
|
+
if width == 1 && height == 1 { break }
|
|
274
|
+
// As TypeScript: an oversized source candidate also guides the shrink.
|
|
275
|
+
let bestLength = Double(min(rendered.png.count, rendered.jpeg?.count ?? .max, candidates.map(\.bytes.count).min() ?? .max))
|
|
276
|
+
let shrink = max(0.1, min(0.8, (Double(maxBytes) / bestLength).squareRoot() * 0.9))
|
|
277
|
+
width = attempt == 6 ? 1 : max(1, Int(Double(width) * shrink))
|
|
278
|
+
height = attempt == 6 ? 1 : max(1, Int(Double(height) * shrink))
|
|
279
|
+
}
|
|
280
|
+
#endif
|
|
281
|
+
throw failure("image_unsupported")
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
#if canImport(ImageIO)
|
|
285
|
+
/// One decoded source. Dimensions come from the header (upright, after EXIF orientation).
|
|
286
|
+
private final class OpenedImage {
|
|
287
|
+
let source: CGImageSource
|
|
288
|
+
let width: Int, height: Int
|
|
289
|
+
/// EXIF turns the stored pixels, so the unchanged source is not upright as encoded.
|
|
290
|
+
let reoriented: Bool
|
|
291
|
+
|
|
292
|
+
init?(_ bytes: Data) {
|
|
293
|
+
guard let source = CGImageSourceCreateWithData(bytes as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),
|
|
294
|
+
CGImageSourceGetCount(source) >= 1,
|
|
295
|
+
CGImageSourceGetStatusAtIndex(source, 0) == .statusComplete,
|
|
296
|
+
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
|
|
297
|
+
let w = properties[kCGImagePropertyPixelWidth] as? Int,
|
|
298
|
+
let h = properties[kCGImagePropertyPixelHeight] as? Int,
|
|
299
|
+
w > 0, h > 0,
|
|
300
|
+
!w.multipliedReportingOverflow(by: h).overflow else { return nil }
|
|
301
|
+
let orientation = (properties[kCGImagePropertyOrientation] as? NSNumber)?.intValue ?? 1
|
|
302
|
+
let swapped = (5...8).contains(orientation)
|
|
303
|
+
self.source = source
|
|
304
|
+
width = swapped ? h : w; height = swapped ? w : h
|
|
305
|
+
reoriented = orientation != 1
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/// Upright, exactly `width`×`height`: PNG, and JPEG unless a pixel can be transparent.
|
|
309
|
+
func render(width: Int, height: Int) throws -> (png: Data, jpeg: Data?) {
|
|
310
|
+
// The thumbnail path decodes at reduced size when it can (no full 12 MP bitmap for a
|
|
311
|
+
// 512 px target) and applies the EXIF orientation.
|
|
312
|
+
let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true,
|
|
313
|
+
kCGImageSourceCreateThumbnailWithTransform: true,
|
|
314
|
+
kCGImageSourceThumbnailMaxPixelSize: max(width, height)]
|
|
315
|
+
guard let thumb = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { throw NativeImagePal.failure("image_unsupported") }
|
|
316
|
+
let opaque = [.none, .noneSkipFirst, .noneSkipLast].contains(thumb.alphaInfo)
|
|
317
|
+
let image = try (thumb.width == width && thumb.height == height) ? thumb : Self.scaled(thumb, width, height, opaque)
|
|
318
|
+
guard let png = Self.encode(image, "public.png", nil) else { throw NativeImagePal.failure("image_unsupported") }
|
|
319
|
+
return (png, opaque ? Self.encode(image, "public.jpeg", Images.jpegQuality) : nil)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
private static func scaled(_ image: CGImage, _ width: Int, _ height: Int, _ opaque: Bool) throws -> CGImage {
|
|
323
|
+
let info = opaque ? CGImageAlphaInfo.noneSkipLast.rawValue : CGImageAlphaInfo.premultipliedLast.rawValue
|
|
324
|
+
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
|
|
325
|
+
space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info) else { throw NativeImagePal.failure("image_unsupported") }
|
|
326
|
+
context.interpolationQuality = .high
|
|
327
|
+
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
|
|
328
|
+
guard let out = context.makeImage() else { throw NativeImagePal.failure("image_unsupported") }
|
|
329
|
+
return out
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
private static func encode(_ image: CGImage, _ type: String, _ quality: Double?) -> Data? {
|
|
333
|
+
let out = NSMutableData()
|
|
334
|
+
guard let destination = CGImageDestinationCreateWithData(out, type as CFString, 1, nil) else { return nil }
|
|
335
|
+
CGImageDestinationAddImage(destination, image, quality.map { [kCGImageDestinationLossyCompressionQuality: $0] as CFDictionary })
|
|
336
|
+
return CGImageDestinationFinalize(destination) ? out as Data : nil
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
#endif
|
|
340
|
+
|
|
341
|
+
// MARK: Helpers
|
|
342
|
+
|
|
343
|
+
static func failure(_ code: String) -> LegacyCrocheError {
|
|
344
|
+
LegacyCrocheError(code, code == "image_fetch_failed" ? "The image could not be read." : "The image could not be prepared.")
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
static var cancelled: LegacyCrocheError { LegacyCrocheError("cancelled", "Image preparation was cancelled.") }
|
|
348
|
+
/// CoreGraphics or memory failed while handling bytes that did decode: not a fact about the
|
|
349
|
+
/// app's image (never invalid_input): `internal`, sent literally (Keel 19:10Z, 21:00Z).
|
|
350
|
+
static var platformFault: LegacyCrocheError { LegacyCrocheError("internal", "CoreGraphics could not hold the decoded pixels.") }
|
|
351
|
+
/// Core's token is authoritative; its own terminal code wins over this one.
|
|
352
|
+
static func check(_ cancel: CancelToken) throws {
|
|
353
|
+
if cancel.isCancelled() { throw cancelled }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
static func mime(_ bytes: Data) -> String? {
|
|
357
|
+
let b = [UInt8](bytes.prefix(12))
|
|
358
|
+
func at(_ values: [UInt8]) -> Bool { b.count >= values.count && Array(b[0..<values.count]) == values }
|
|
359
|
+
if at([137, 80, 78, 71, 13, 10, 26, 10]) { return "image/png" }
|
|
360
|
+
if at([255, 216, 255]) { return "image/jpeg" }
|
|
361
|
+
if at([71, 73, 70, 56]), b.count >= 6, b[4] == 55 || b[4] == 57, b[5] == 97 { return "image/gif" }
|
|
362
|
+
if b.count >= 12, at([82, 73, 70, 70]), b[8] == 87, b[9] == 69, b[10] == 66, b[11] == 80 { return "image/webp" }
|
|
363
|
+
return nil
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/// ImageIO draws a truncated JPEG or PNG with filler; the TypeScript codecs refuse it. A JPEG
|
|
367
|
+
/// must carry its end-of-image marker near the end (trailing camera data is allowed), a PNG
|
|
368
|
+
/// its IEND chunk.
|
|
369
|
+
static func complete(_ bytes: Data, _ mime: String) -> Bool {
|
|
370
|
+
let tail = [UInt8](bytes.suffix(64 * 1024))
|
|
371
|
+
func contains(_ marker: [UInt8]) -> Bool {
|
|
372
|
+
guard tail.count >= marker.count else { return false }
|
|
373
|
+
for i in stride(from: tail.count - marker.count, through: 0, by: -1) where tail[i] == marker[0] && Array(tail[i..<i + marker.count]) == marker { return true }
|
|
374
|
+
return false
|
|
375
|
+
}
|
|
376
|
+
switch mime {
|
|
377
|
+
case "image/jpeg": return contains([0xFF, 0xD9])
|
|
378
|
+
case "image/png": return contains([0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82])
|
|
379
|
+
default: return true
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
static func sha256(_ bytes: Data) -> Data {
|
|
384
|
+
#if canImport(CryptoKit)
|
|
385
|
+
return Data(SHA256.hash(data: bytes))
|
|
386
|
+
#else
|
|
387
|
+
let hex = PortableSHA256.hex([UInt8](bytes))
|
|
388
|
+
var out = Data(capacity: 32), index = hex.startIndex
|
|
389
|
+
while index < hex.endIndex {
|
|
390
|
+
let next = hex.index(index, offsetBy: 2)
|
|
391
|
+
out.append(UInt8(hex[index..<next], radix: 16)!); index = next
|
|
392
|
+
}
|
|
393
|
+
return out
|
|
394
|
+
#endif
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
#if canImport(ImageIO) && (canImport(UIKit) || canImport(AppKit))
|
|
399
|
+
extension NativeImagePal {
|
|
400
|
+
/// A platform image as PNG bytes, encoded once at capture time (no EXIF: drawn upright).
|
|
401
|
+
static func encodedPNG(_ cgImage: CGImage?) throws -> Data {
|
|
402
|
+
guard let cgImage else { throw failure("image_unsupported") }
|
|
403
|
+
let out = NSMutableData()
|
|
404
|
+
guard let destination = CGImageDestinationCreateWithData(out, "public.png" as CFString, 1, nil) else { throw failure("image_unsupported") }
|
|
405
|
+
CGImageDestinationAddImage(destination, cgImage, nil)
|
|
406
|
+
guard CGImageDestinationFinalize(destination) else { throw failure("image_fetch_failed") }
|
|
407
|
+
return out as Data
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
#endif
|
|
@@ -12,15 +12,16 @@ import CoreGraphics
|
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
/// A tool's result with images beside its value (H3): the same image kinds and limits as a
|
|
15
|
-
/// message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4)
|
|
16
|
-
/// with `invalid_tool_result`, and the turn goes on
|
|
17
|
-
/// `
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
/// message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4). A malformed list fails that
|
|
16
|
+
/// call with `invalid_tool_result`, and the turn goes on; a size limit broken (more than 4
|
|
17
|
+
/// images, an `alt` over 500 characters) ends the turn with `input_too_large`. Return it from a
|
|
18
|
+
/// handler made with `withResult`.
|
|
19
|
+
struct LegacyToolResult: Sendable {
|
|
20
|
+
var value: JSON
|
|
21
|
+
var images: [JSON]
|
|
21
22
|
/// For every image that does not name its own `"resolution"`.
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
var imageResolution: ImageResolution?
|
|
24
|
+
init(value: JSON = .null, images: [JSON] = [], imageResolution: ImageResolution? = nil) {
|
|
24
25
|
self.value = value; self.images = images; self.imageResolution = imageResolution
|
|
25
26
|
}
|
|
26
27
|
}
|
|
@@ -29,7 +30,7 @@ public struct ToolResult: Sendable {
|
|
|
29
30
|
/// `tools: ["room": withResult { invocation, context in ToolResult(value: ..., images: [...]) }]`.
|
|
30
31
|
/// The images go to the Runtime beside the value; a plain `ToolHandler`'s JSON is never looked
|
|
31
32
|
/// inside.
|
|
32
|
-
|
|
33
|
+
func withResult(_ handler: @escaping @Sendable (_ invocation: JSON, _ context: LegacyToolContext) async throws -> LegacyToolResult) -> ToolHandler {
|
|
33
34
|
{ invocation, context in
|
|
34
35
|
let result = try await handler(invocation, context)
|
|
35
36
|
// The handler ran: what it returned (plain values, nothing that can throw) is read once,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
3
|
/// A value-semantic JSON tree. Core state and machine stay opaque to the host.
|
|
4
|
-
public enum JSON: Codable, Sendable,
|
|
4
|
+
public enum JSON: Codable, Sendable, Hashable {
|
|
5
5
|
case null, bool(Bool), number(Double), string(String), array([JSON]), object([String: JSON])
|
|
6
6
|
public init(from decoder: Decoder) throws {
|
|
7
7
|
let c = try decoder.singleValueContainer()
|
|
@@ -37,11 +37,11 @@ public enum JSON: Codable, Sendable, Equatable {
|
|
|
37
37
|
public var bool: Bool? { if case .bool(let v) = self { return v }; return nil }
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
struct LegacyCrocheError: Error, Sendable, CustomStringConvertible {
|
|
41
41
|
public let code: String
|
|
42
42
|
public let message: String
|
|
43
|
-
public let receipt:
|
|
44
|
-
public init(_ code: String, _ message: String, receipt:
|
|
43
|
+
public let receipt: LegacyReceipt?
|
|
44
|
+
public init(_ code: String, _ message: String, receipt: LegacyReceipt? = nil) { self.code = code; self.message = message; self.receipt = receipt }
|
|
45
45
|
public var description: String { "\(code): \(message)" }
|
|
46
46
|
}
|
|
47
47
|
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Core's calls block their thread while the host performs effects: run them on a thread of
|
|
4
|
+
/// their own, never on the cooperative pool or the main thread.
|
|
5
|
+
enum Offload {
|
|
6
|
+
/// Croche's own tests: runs first on each offload thread, so a test can delay it the way the
|
|
7
|
+
/// OS may (#346). Nil in every app.
|
|
8
|
+
nonisolated(unsafe) static var starting: (@Sendable () -> Void)?
|
|
9
|
+
static func run<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
|
|
10
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
11
|
+
Thread.detachNewThread {
|
|
12
|
+
starting?()
|
|
13
|
+
do { continuation.resume(returning: try body()) }
|
|
14
|
+
catch { continuation.resume(throwing: LegacyCrocheError(error)) }
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/// Core's storage identity for a config: the key a store is bound to. Internal; apps never read it.
|
|
21
|
+
func storageIdentity(config: JSON) throws -> JSON {
|
|
22
|
+
do { return publicStorageIdentity(try JSON(ffiIdentity(String(decoding: try config.encoded(), as: UTF8.self)))) }
|
|
23
|
+
catch { throw LegacyCrocheError(error) }
|
|
24
|
+
}
|
|
@@ -3,37 +3,38 @@ import Foundation
|
|
|
3
3
|
import CryptoKit
|
|
4
4
|
#endif
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
enum DebugVisibility: String, Sendable { case runtime }
|
|
7
|
+
enum Attestation: String, Sendable { case platform, off }
|
|
8
8
|
// Q9 recommendation: backgroundDelivery is deferred until the per-agent identifier rule.
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
///
|
|
13
|
-
///
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
9
|
+
struct LegacyOpenOptions: Sendable {
|
|
10
|
+
var cloudUrl: String?
|
|
11
|
+
var projectKey: String
|
|
12
|
+
/// The app's bundled project configuration (a ProjectConfig or its release export); Core selects
|
|
13
|
+
/// it or a newer released config. `temperature`: number 0...2, absent uses a tuned default, `.null` = omit.
|
|
14
|
+
/// Structured calls always omit it. Remote temperature configs require schema 6 / 0.6+.
|
|
15
|
+
var bundledConfig: JSON
|
|
16
|
+
var user: String?
|
|
17
|
+
var handlers: [String: ToolHandler]
|
|
18
|
+
var language: String?
|
|
19
|
+
var timeZone: String?
|
|
20
|
+
var streaming: Bool?
|
|
21
|
+
var backgroundSync: Bool?
|
|
22
|
+
var maintenanceIntervalMs: Double?
|
|
23
|
+
var debugKey: String?
|
|
24
|
+
var requestTimeoutMs: Double?
|
|
25
|
+
var maxPendingEvents: Int?
|
|
26
|
+
var syncIntervalMs: Double?
|
|
27
|
+
var maintenanceBackoffMs: Double?
|
|
28
|
+
var retentionBytes: Int?
|
|
29
|
+
var onUsage: (@Sendable (ProjectUsageEvent) -> Void)?
|
|
30
|
+
var onDebugEvent: (@Sendable (RuntimeDebugEvent) -> Void)?
|
|
31
|
+
var debugVisibility: DebugVisibility?
|
|
32
|
+
var attestation: Attestation?
|
|
33
|
+
var projectDirectory: URL?
|
|
34
|
+
var http: RuntimeHTTP?
|
|
35
|
+
init(cloudUrl: String? = nil,
|
|
35
36
|
projectKey: String,
|
|
36
|
-
|
|
37
|
+
bundledConfig: JSON,
|
|
37
38
|
user: String? = nil,
|
|
38
39
|
handlers: [String: ToolHandler] = [:],
|
|
39
40
|
language: String? = nil,
|
|
@@ -55,7 +56,7 @@ public struct OpenOptions: Sendable {
|
|
|
55
56
|
http: RuntimeHTTP? = nil) {
|
|
56
57
|
self.cloudUrl = cloudUrl
|
|
57
58
|
self.projectKey = projectKey
|
|
58
|
-
self.
|
|
59
|
+
self.bundledConfig = bundledConfig
|
|
59
60
|
self.user = user
|
|
60
61
|
self.handlers = handlers
|
|
61
62
|
self.language = language
|
|
@@ -92,15 +93,15 @@ public struct OpenOptions: Sendable {
|
|
|
92
93
|
language ?? preferredLanguages.first
|
|
93
94
|
}
|
|
94
95
|
func native() throws -> NativeProjectOptions {
|
|
95
|
-
do { _ = try hostJSON().encoded(); _ = try
|
|
96
|
-
catch { throw
|
|
96
|
+
do { _ = try hostJSON().encoded(); _ = try bundledConfig.encoded() }
|
|
97
|
+
catch { throw LegacyCrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
|
|
97
98
|
let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
|
|
98
99
|
let directory = try NativeProjectFiles.directory(projectDirectory: projectDirectory)
|
|
99
100
|
var identity = hostJSON(); identity["user"] = user.map(JSON.string) ?? .null
|
|
100
|
-
let namespace = try
|
|
101
|
+
let namespace = try storageIdentity(config: identity)["storageKey"].string ?? "croche.runtime"
|
|
101
102
|
let zone: TimeZone?
|
|
102
103
|
if let timeZone {
|
|
103
|
-
guard let parsed = TimeZone(identifier: timeZone) else { throw
|
|
104
|
+
guard let parsed = TimeZone(identifier: timeZone) else { throw LegacyCrocheError("invalid_configuration", "timeZone must name an IANA time zone") }
|
|
104
105
|
zone = parsed
|
|
105
106
|
} else { zone = nil }
|
|
106
107
|
let attestor: (any RuntimeAttestor)?
|
|
@@ -110,7 +111,7 @@ public struct OpenOptions: Sendable {
|
|
|
110
111
|
attestor = nil
|
|
111
112
|
#endif
|
|
112
113
|
let test = NativeProjectFiles.testing
|
|
113
|
-
return NativeProjectOptions(host: hostJSON(),
|
|
114
|
+
return NativeProjectOptions(host: hostJSON(), bundledConfig: bundledConfig, user: user,
|
|
114
115
|
language: resolvedLanguage(), handlers: handlers, streaming: streaming ?? true,
|
|
115
116
|
backgroundSync: backgroundSync ?? true, maintenanceIntervalMs: maintenanceIntervalMs ?? 60_000,
|
|
116
117
|
storage: { slot in FileRuntimeStorage(url: NativeProjectFiles.file(directory: directory, namespace: namespace, slot: slot)) },
|
|
@@ -134,7 +135,7 @@ enum NativeProjectFiles {
|
|
|
134
135
|
static func directory(projectDirectory: URL?) throws -> URL {
|
|
135
136
|
if let testing { return testing }
|
|
136
137
|
#if os(Linux)
|
|
137
|
-
guard let projectDirectory else { throw
|
|
138
|
+
guard let projectDirectory else { throw LegacyCrocheError("storage_error", "This platform requires projectDirectory") }
|
|
138
139
|
return projectDirectory
|
|
139
140
|
#else
|
|
140
141
|
let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|