@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,183 @@
|
|
|
1
|
+
package dev.croche
|
|
2
|
+
|
|
3
|
+
import dev.croche.ffi.CancelToken
|
|
4
|
+
import dev.croche.ffi.PalImageBytes
|
|
5
|
+
import dev.croche.ffi.PalImagePreparePlan
|
|
6
|
+
import dev.croche.ffi.PalImageReadRequest
|
|
7
|
+
import dev.croche.ffi.PalImageReadSource
|
|
8
|
+
import java.security.MessageDigest
|
|
9
|
+
import java.util.UUID
|
|
10
|
+
import kotlin.math.max
|
|
11
|
+
import kotlin.math.min
|
|
12
|
+
import kotlin.math.roundToInt
|
|
13
|
+
import kotlin.math.sqrt
|
|
14
|
+
|
|
15
|
+
/** A platform decoder for the private image PAL. Android supplies `dev.croche.android.BitmapPalCodec`;
|
|
16
|
+
* a plain JVM has none, so Core refuses image inputs with `image_unsupported` before acquiring. */
|
|
17
|
+
internal interface PalImageCodec {
|
|
18
|
+
/** Upright dimensions from the header only, or null when this platform cannot decode it or it
|
|
19
|
+
* has more than [maxPixels] pixels. No full decode happens here. */
|
|
20
|
+
fun open(bytes: ByteArray, maxPixels: Long): Opened?
|
|
21
|
+
interface Opened : AutoCloseable {
|
|
22
|
+
val width: Int
|
|
23
|
+
val height: Int
|
|
24
|
+
/** EXIF turns the stored pixels, so the unchanged source is not upright as encoded. */
|
|
25
|
+
val reoriented: Boolean
|
|
26
|
+
/** Upright, exactly [width]×[height] given: PNG, and JPEG (quality 70) unless a pixel can be
|
|
27
|
+
* have alpha (an alpha channel, as TypeScript's sharp codec). Decodes downsampled when it can. */
|
|
28
|
+
fun render(width: Int, height: Int): Rendered
|
|
29
|
+
override fun close() {}
|
|
30
|
+
}
|
|
31
|
+
class Rendered(val png: ByteArray, val jpeg: ByteArray?)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Private native image PAL (Rev 4a), the Kotlin twin of the TypeScript and Swift `ImagePal`. Core
|
|
35
|
+
* owns admission, sizing plans, budgets, deadlines and every URL; this only holds owned captures
|
|
36
|
+
* and decodes/encodes to Core's plan. Names, codes and messages match TypeScript. */
|
|
37
|
+
internal class NativeImagePal(
|
|
38
|
+
private val codec: PalImageCodec? = defaultCodec(),
|
|
39
|
+
/** Native platform limit (TypeScript has none), checked from the header before any decode. */
|
|
40
|
+
val maxInputPixels: Long = DEFAULT_MAX_INPUT_PIXELS,
|
|
41
|
+
) {
|
|
42
|
+
companion object {
|
|
43
|
+
const val SOURCE_MAX_BYTES = 16 * 1024 * 1024
|
|
44
|
+
const val PREPARED_MAX_BYTES = 3 * 1024 * 1024
|
|
45
|
+
const val DEFAULT_MAX_INPUT_PIXELS = 50_000_000L
|
|
46
|
+
fun defaultCodec(): PalImageCodec? = try {
|
|
47
|
+
Class.forName("dev.croche.android.BitmapPalCodec").getDeclaredConstructor().newInstance() as PalImageCodec
|
|
48
|
+
} catch (_: Throwable) { null }
|
|
49
|
+
|
|
50
|
+
fun failure(code: String) = CrocheError(code,
|
|
51
|
+
if (code == "image_fetch_failed") "The image could not be read." else "The image could not be prepared.")
|
|
52
|
+
|
|
53
|
+
/** Core's token is authoritative; its own terminal code wins over this one. */
|
|
54
|
+
fun check(cancel: CancelToken) {
|
|
55
|
+
if (cancel.isCancelled()) throw CrocheError("cancelled", "Image preparation was cancelled.")
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
fun mime(bytes: ByteArray): String? {
|
|
59
|
+
fun at(vararg values: Int) = bytes.size >= values.size && values.indices.all { bytes[it].toInt() and 0xFF == values[it] }
|
|
60
|
+
return when {
|
|
61
|
+
at(137, 80, 78, 71, 13, 10, 26, 10) -> "image/png"
|
|
62
|
+
at(255, 216, 255) -> "image/jpeg"
|
|
63
|
+
at(71, 73, 70, 56) && bytes.size >= 6 && (bytes[4].toInt() == 55 || bytes[4].toInt() == 57) && bytes[5].toInt() == 97 -> "image/gif"
|
|
64
|
+
bytes.size >= 12 && at(82, 73, 70, 70) && bytes[8].toInt() == 87 && bytes[9].toInt() == 69 && bytes[10].toInt() == 66 && bytes[11].toInt() == 80 -> "image/webp"
|
|
65
|
+
else -> null
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Platform decoders draw a truncated JPEG or PNG with filler; TypeScript codecs refuse it. A
|
|
70
|
+
* JPEG must carry its end-of-image marker near the end (trailing camera data is allowed), a
|
|
71
|
+
* PNG its IEND chunk. */
|
|
72
|
+
fun complete(bytes: ByteArray, mime: String): Boolean {
|
|
73
|
+
val marker = when (mime) {
|
|
74
|
+
"image/jpeg" -> byteArrayOf(0xFF.toByte(), 0xD9.toByte())
|
|
75
|
+
"image/png" -> byteArrayOf(0x49, 0x45, 0x4E, 0x44, 0xAE.toByte(), 0x42, 0x60, 0x82.toByte())
|
|
76
|
+
else -> return true
|
|
77
|
+
}
|
|
78
|
+
val from = max(0, bytes.size - 64 * 1024)
|
|
79
|
+
for (i in bytes.size - marker.size downTo from) {
|
|
80
|
+
if (marker.indices.all { bytes[i + it] == marker[it] }) return true
|
|
81
|
+
}
|
|
82
|
+
return false
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
fun sha256(bytes: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(bytes)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private val lock = Any()
|
|
89
|
+
private val captures = HashMap<String, ByteArray>()
|
|
90
|
+
private var closed = false
|
|
91
|
+
|
|
92
|
+
/** A platform decoder is present. No I/O. */
|
|
93
|
+
val codecAvailable: Boolean get() = codec != null
|
|
94
|
+
|
|
95
|
+
/** Snapshot encoded bytes at the reserved entry boundary; returns the capture token. */
|
|
96
|
+
fun capture(bytes: ByteArray): String {
|
|
97
|
+
if (bytes.isEmpty() || bytes.size > SOURCE_MAX_BYTES) throw failure("image_fetch_failed")
|
|
98
|
+
val owned = bytes.copyOf()
|
|
99
|
+
val token = UUID.randomUUID().toString()
|
|
100
|
+
synchronized(lock) {
|
|
101
|
+
if (closed) throw CrocheError("closed", "The Runtime is closed.")
|
|
102
|
+
captures[token] = owned
|
|
103
|
+
}
|
|
104
|
+
return token
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Current PAL: owned bytes only; Core sniffs the format and computes the source digest. */
|
|
108
|
+
fun readBytes(request: PalImageReadRequest, cancel: CancelToken): ByteArray {
|
|
109
|
+
check(cancel)
|
|
110
|
+
val maxBytes = request.maxBytes.toLong()
|
|
111
|
+
if (maxBytes < 1 || maxBytes > SOURCE_MAX_BYTES) throw failure("image_fetch_failed")
|
|
112
|
+
// Local URIs are not a native input form; https/data belong to Core's transport.
|
|
113
|
+
val source = request.source as? PalImageReadSource.Capture ?: throw failure("image_fetch_failed")
|
|
114
|
+
// A capture is taken once; a second read finds nothing.
|
|
115
|
+
val bytes = synchronized(lock) { captures.remove(source.token) }
|
|
116
|
+
if (bytes == null || bytes.size > maxBytes) throw failure("image_fetch_failed")
|
|
117
|
+
check(cancel)
|
|
118
|
+
return bytes
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Retained prepare-fixture helper; the HostPal readImage entry never uses its metadata.
|
|
122
|
+
fun read(request: PalImageReadRequest, cancel: CancelToken): PalImageBytes {
|
|
123
|
+
val bytes = readBytes(request, cancel)
|
|
124
|
+
return PalImageBytes(bytes, mime(bytes) ?: "", sha256(bytes))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
fun prepare(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken): PalImageBytes {
|
|
128
|
+
check(cancel)
|
|
129
|
+
val maxSide = plan.maxSide?.toLong()
|
|
130
|
+
val maxBytes = plan.maxBytes.toLong()
|
|
131
|
+
if (maxSide != null && maxSide < 1 || maxBytes < 1 || maxBytes > PREPARED_MAX_BYTES || codec == null) throw failure("image_unsupported")
|
|
132
|
+
return try {
|
|
133
|
+
prepareVerified(source, maxSide?.toInt(), maxBytes.toInt(), codec, cancel)
|
|
134
|
+
} catch (error: Throwable) {
|
|
135
|
+
if (error is InterruptedException) Thread.currentThread().interrupt()
|
|
136
|
+
check(cancel)
|
|
137
|
+
throw failure("image_unsupported")
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Idempotent. */
|
|
142
|
+
fun release(token: String) { synchronized(lock) { captures.remove(token) } }
|
|
143
|
+
|
|
144
|
+
fun close() { synchronized(lock) { closed = true; captures.clear() } }
|
|
145
|
+
|
|
146
|
+
// Same steps as TypeScript `prepareImageBytes`.
|
|
147
|
+
private fun prepareVerified(asset: PalImageBytes, maxSide: Int?, maxBytes: Int, codec: PalImageCodec, cancel: CancelToken): PalImageBytes {
|
|
148
|
+
val bytes = asset.bytes.copyOf()
|
|
149
|
+
val mime = mime(bytes)
|
|
150
|
+
if (bytes.isEmpty() || bytes.size > SOURCE_MAX_BYTES || mime == null || !complete(bytes, mime)) throw failure("image_unsupported")
|
|
151
|
+
val digest = sha256(bytes)
|
|
152
|
+
if (!asset.sha256.contentEquals(digest)) throw failure("image_unsupported")
|
|
153
|
+
check(cancel)
|
|
154
|
+
val opened = codec.open(bytes, maxInputPixels) ?: throw failure("image_unsupported")
|
|
155
|
+
opened.use {
|
|
156
|
+
val sourceWidth = opened.width; val sourceHeight = opened.height
|
|
157
|
+
if (sourceWidth < 1 || sourceHeight < 1) throw failure("image_unsupported")
|
|
158
|
+
val scale = maxSide?.let { min(1.0, it.toDouble() / max(sourceWidth, sourceHeight)) } ?: 1.0
|
|
159
|
+
var width = max(1, (sourceWidth * scale).roundToInt())
|
|
160
|
+
var height = max(1, (sourceHeight * scale).roundToInt())
|
|
161
|
+
for (attempt in 0 until 8) {
|
|
162
|
+
check(cancel)
|
|
163
|
+
val rendered = opened.render(width, height)
|
|
164
|
+
check(cancel)
|
|
165
|
+
val candidates = ArrayList<PalImageBytes>(3)
|
|
166
|
+
if (rendered.png.size <= maxBytes) candidates += PalImageBytes(rendered.png, "image/png", sha256(rendered.png))
|
|
167
|
+
rendered.jpeg?.takeIf { it.size <= maxBytes }?.let { candidates += PalImageBytes(it, "image/jpeg", sha256(it)) }
|
|
168
|
+
if (width == sourceWidth && height == sourceHeight && mime != "image/gif" && !opened.reoriented) {
|
|
169
|
+
candidates += PalImageBytes(bytes, mime, digest)
|
|
170
|
+
}
|
|
171
|
+
val best = candidates.minByOrNull { it.bytes.size }
|
|
172
|
+
if (best != null && best.bytes.size <= maxBytes) return best
|
|
173
|
+
if (width == 1 && height == 1) break
|
|
174
|
+
// As TypeScript: an oversized source candidate also guides the shrink.
|
|
175
|
+
val bestLength = minOf(rendered.png.size, rendered.jpeg?.size ?: Int.MAX_VALUE, best?.bytes?.size ?: Int.MAX_VALUE).toDouble()
|
|
176
|
+
val shrink = max(0.1, min(0.8, sqrt(maxBytes / bestLength) * 0.9))
|
|
177
|
+
width = if (attempt == 6) 1 else max(1, (width * shrink).toInt())
|
|
178
|
+
height = if (attempt == 6) 1 else max(1, (height * shrink).toInt())
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
throw failure("image_unsupported")
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -15,14 +15,16 @@ import java.util.Base64
|
|
|
15
15
|
enum class ImageResolution { STANDARD, HIGH }
|
|
16
16
|
|
|
17
17
|
/** A tool's result with images beside its value (H3): the same image kinds and limits as a
|
|
18
|
-
* message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4)
|
|
19
|
-
* `invalid_tool_result`, and the turn goes on
|
|
20
|
-
|
|
18
|
+
* message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4). A malformed list fails that call
|
|
19
|
+
* with `invalid_tool_result`, and the turn goes on; a size limit broken (more than 4 images, an
|
|
20
|
+
* `alt` over 500 characters) ends the turn with `input_too_large`. Return it from a handler made
|
|
21
|
+
* with [withResult]. */
|
|
22
|
+
data class LegacyToolResult(val value: JsonElement = JsonNull.INSTANCE, val images: List<JsonObject> = emptyList(),
|
|
21
23
|
/** For every image that does not name its own `"resolution"`. */
|
|
22
24
|
val imageResolution: ImageResolution? = null)
|
|
23
|
-
fun interface ToolResultHandler { fun execute(invocation: CommandInvocation, context:
|
|
25
|
+
fun interface ToolResultHandler { fun execute(invocation: CommandInvocation, context: LegacyToolContext): LegacyToolResult }
|
|
24
26
|
|
|
25
|
-
/** The one way to return a [
|
|
27
|
+
/** The one way to return a [LegacyToolResult] (its value, plus images): `"room" to withResult { invocation, context -> LegacyToolResult(...) }`.
|
|
26
28
|
* The images go to the Runtime beside the value; a plain [ToolHandler]'s JSON is never looked inside. */
|
|
27
29
|
fun withResult(handler: ToolResultHandler): ToolHandler = ToolHandler { invocation, context ->
|
|
28
30
|
val result = handler.execute(invocation, context)
|
|
@@ -34,7 +36,7 @@ fun withResult(handler: ToolResultHandler): ToolHandler = ToolHandler { invocati
|
|
|
34
36
|
result.value
|
|
35
37
|
} catch (failed: Throwable) {
|
|
36
38
|
if (failed is InterruptedException) throw failed
|
|
37
|
-
throw
|
|
39
|
+
throw CrocheError("invalid_tool_result", "The tool returned a result that could not be read. Its effects may have completed.")
|
|
38
40
|
}
|
|
39
41
|
}
|
|
40
42
|
|
|
@@ -153,7 +155,7 @@ object CrocheImages {
|
|
|
153
155
|
val v = image.get(key) ?: return null
|
|
154
156
|
if (v.isJsonNull) return null
|
|
155
157
|
if (!v.isJsonPrimitive || !v.asJsonPrimitive.isString)
|
|
156
|
-
throw
|
|
158
|
+
throw CrocheError("invalid_tool_result", "A tool result image's $key is text. Its effects may have completed.")
|
|
157
159
|
return v.asString
|
|
158
160
|
}
|
|
159
161
|
return ToolImage(text("data"), text("url"), text("mime") ?: "", text("alt"))
|
|
@@ -3,6 +3,7 @@ package dev.croche
|
|
|
3
3
|
import com.google.gson.*
|
|
4
4
|
import dev.croche.ffi.CoreRuntime
|
|
5
5
|
import dev.croche.ffi.EventListener
|
|
6
|
+
import dev.croche.s7.hostCallback
|
|
6
7
|
import kotlinx.coroutines.Dispatchers
|
|
7
8
|
import kotlinx.coroutines.withContext
|
|
8
9
|
import java.time.Instant
|
|
@@ -21,16 +22,16 @@ internal class NativeCoreStreamPort(private val core: CoreRuntime, private val h
|
|
|
21
22
|
override val state get() = currentState
|
|
22
23
|
override val logId get() = call { core.logId() }
|
|
23
24
|
private fun <T> call(body: () -> T): T {
|
|
24
|
-
if (closed.get()) throw
|
|
25
|
+
if (closed.get()) throw CrocheError("closed", "Runtime is closed")
|
|
25
26
|
return try { nativeCall(body) } catch (error: Exception) { throw crocheError(error) }
|
|
26
27
|
}
|
|
27
28
|
private fun <T> nativeCall(body: () -> T): T {
|
|
28
|
-
|
|
29
|
+
LegacyAgentEngine.offloadStarting?.invoke()
|
|
29
30
|
return body()
|
|
30
31
|
}
|
|
31
32
|
private suspend fun <T> blocking(body: () -> T): T = withContext(Dispatchers.IO) { call(body) }
|
|
32
33
|
private fun listener(callback: (JsonObject) -> Unit) = object : EventListener {
|
|
33
|
-
override fun onEvent(event: String) {
|
|
34
|
+
override fun onEvent(event: String) = hostCallback { callback(JsonParser.parseString(event).asJsonObject) }
|
|
34
35
|
}
|
|
35
36
|
override fun observe(event: (RuntimeEvent) -> Unit, end: (Throwable?) -> Unit): AutoCloseable {
|
|
36
37
|
call {
|
|
@@ -84,11 +85,40 @@ internal class NativeCoreStreamPort(private val core: CoreRuntime, private val h
|
|
|
84
85
|
override suspend fun send(input: JsonObject, options: SendOptions): Receipt = blocking {
|
|
85
86
|
// The only receipt-send FFI call site.
|
|
86
87
|
val value = JsonParser.parseString(core.send(input.toString(), null, options.responseFormat?.toString())).asJsonObject
|
|
87
|
-
Receipt(value.at("
|
|
88
|
+
Receipt(value.at("requestId").text(), InputStatus(value.at("status").text()), value.optionalLong("seq"))
|
|
89
|
+
}
|
|
90
|
+
override suspend fun sendWithImages(input: SendInput, options: SendOptions): Receipt {
|
|
91
|
+
val images = input.imageCaptures()
|
|
92
|
+
// Reserve Core's admission place, hand it owned bytes as captures, then offload only the
|
|
93
|
+
// wait. Core takes and releases each capture; on a refused submit the tokens are ours.
|
|
94
|
+
val token = dev.croche.ffi.CancelToken()
|
|
95
|
+
val pending = blocking {
|
|
96
|
+
val entry = core.reserveSend()
|
|
97
|
+
val tokens = ArrayList<String>(images.size)
|
|
98
|
+
try {
|
|
99
|
+
val captures = images.map { (element, bytes) ->
|
|
100
|
+
dev.croche.ffi.PalCapturedImageSource(element.toUInt(), "encoded-v1", host.images.capture(bytes).also { tokens += it })
|
|
101
|
+
}
|
|
102
|
+
entry.submit(input.encoded(options).toString(), captures, token, options.responseFormat?.toString())
|
|
103
|
+
} catch (error: Throwable) {
|
|
104
|
+
tokens.forEach(host.images::release); throw error
|
|
105
|
+
} finally { nativeCall { entry.close() } }
|
|
106
|
+
}
|
|
107
|
+
val value = try {
|
|
108
|
+
kotlinx.coroutines.suspendCancellableCoroutine<String> { continuation ->
|
|
109
|
+
continuation.invokeOnCancellation { token.cancel() }
|
|
110
|
+
Thread({
|
|
111
|
+
OffloadSeam.starting?.invoke()
|
|
112
|
+
continuation.resumeWith(runCatching { call { pending.wait() } })
|
|
113
|
+
}, "croche-offload").apply { isDaemon = true }.start()
|
|
114
|
+
}
|
|
115
|
+
} finally { nativeCall { pending.close(); token.close() } }
|
|
116
|
+
val receipt = JsonParser.parseString(value).asJsonObject
|
|
117
|
+
return Receipt(receipt.at("requestId").text(), InputStatus(receipt.at("status").text()), receipt.optionalLong("seq"))
|
|
88
118
|
}
|
|
89
119
|
override suspend fun readOutcome(id: String, fromSeq: Long, captured: (CapturedOutcome) -> Unit): RetainedEnds = blocking {
|
|
90
120
|
val value = JsonParser.parseString(core.readOutcome(id, coreSequence(fromSeq), listener { at ->
|
|
91
|
-
captured(CapturedOutcome(at.number("head"), at.number("floor"),
|
|
121
|
+
captured(CapturedOutcome(at.number("head"), at.number("floor"), InputStatus(at.at("status").text()), at.flag("idle")))
|
|
92
122
|
})).asJsonObject
|
|
93
123
|
RetainedEnds(value.list("messages").map { nativeEvent(it.asJsonObject) as RuntimeEvent.MessageEnd }, value.flag("gap"))
|
|
94
124
|
}
|
|
@@ -117,15 +147,15 @@ internal class NativeCoreStreamPort(private val core: CoreRuntime, private val h
|
|
|
117
147
|
}
|
|
118
148
|
|
|
119
149
|
internal fun publicSequence(value: ULong): Long {
|
|
120
|
-
if (value > Long.MAX_VALUE.toULong()) throw
|
|
150
|
+
if (value > Long.MAX_VALUE.toULong()) throw CrocheError("invalid_input", "Core sequence exceeds Long.MAX_VALUE")
|
|
121
151
|
return value.toLong()
|
|
122
152
|
}
|
|
123
153
|
internal fun coreSequence(value: Long): ULong {
|
|
124
|
-
if (value < 0) throw
|
|
154
|
+
if (value < 0) throw CrocheError("invalid_input", "Sequence must not be negative")
|
|
125
155
|
return value.toULong()
|
|
126
156
|
}
|
|
127
157
|
private fun JsonElement.sequence(): Long {
|
|
128
|
-
val value = asString.toULongOrNull() ?: throw
|
|
158
|
+
val value = asString.toULongOrNull() ?: throw CrocheError("invalid_input", "Core sequence is not an unsigned integer")
|
|
129
159
|
return publicSequence(value)
|
|
130
160
|
}
|
|
131
161
|
private fun JsonObject.number(name: String) = get(name).sequence()
|
|
@@ -133,24 +163,22 @@ private fun JsonObject.optionalLong(name: String) = get(name)?.takeUnless { it.i
|
|
|
133
163
|
private fun JsonObject.flag(name: String) = get(name)?.takeUnless { it.isJsonNull }?.asBoolean ?: false
|
|
134
164
|
private fun JsonObject.list(name: String): List<JsonElement> = get(name)?.takeIf { it.isJsonArray }?.asJsonArray?.toList() ?: emptyList()
|
|
135
165
|
private fun JsonObject.strings(name: String) = list(name).map { it.asString }
|
|
136
|
-
private inline fun <reified E : Enum<E>> nativeEnum(value: JsonElement): E =
|
|
137
|
-
enumValues<E>().firstOrNull { it.name.equals(value.text(), ignoreCase = true) } ?: enumValueOf("UNKNOWN")
|
|
138
166
|
private fun JsonObject.error() = get("error")?.takeIf { it.isJsonObject }?.asJsonObject?.let { RuntimeError(it.at("code").text(), it.at("message").text()) }
|
|
139
167
|
|
|
140
|
-
/** Decode the Core's tagged JSON; omission stays omission, unknown
|
|
168
|
+
/** Decode the Core's tagged JSON; omission stays omission, unknown reader values keep their exact strings. */
|
|
141
169
|
internal fun nativeEvent(value: JsonObject): RuntimeEvent {
|
|
142
170
|
fun at() = Instant.parse(value.at("at").text())
|
|
143
|
-
fun state(v: JsonObject) = RuntimeEvent.State(
|
|
144
|
-
v.get("activity")?.takeUnless { it.isJsonNull }?.let {
|
|
171
|
+
fun state(v: JsonObject) = RuntimeEvent.State(AgentStatus(v.at("status").text()), v.number("queued").toInt(), v.flag("typing"),
|
|
172
|
+
v.get("activity")?.takeUnless { it.isJsonNull }?.let { AgentActivity(it.text()) },
|
|
145
173
|
v.get("tools")?.takeIf { it.isJsonArray }?.asJsonArray?.map { it.asString })
|
|
146
174
|
return when (val type = value.at("type").text()) {
|
|
147
|
-
"input" -> RuntimeEvent.Input(value.number("seq"), value.number("firstSeq"), value.at("id").text(),
|
|
175
|
+
"input" -> RuntimeEvent.Input(value.number("seq"), value.number("firstSeq"), value.at("id").text(), InputKind(value.at("kind").text()),
|
|
148
176
|
value.get("text")?.takeUnless { it.isJsonNull }?.asString, value.list("images").map { image -> image.asJsonObject.let {
|
|
149
177
|
ImageSummary(it.get("alt")?.asString, it.get("mime")?.asString, it.optionalLong("bytes"))
|
|
150
|
-
} },
|
|
178
|
+
} }, InputStatus(value.at("status").text()), value.error(), at())
|
|
151
179
|
"message.start" -> RuntimeEvent.MessageStart(value.number("seq"), value.number("firstSeq"), value.at("id").text(), at())
|
|
152
180
|
"message.delta" -> RuntimeEvent.MessageDelta(value.at("id").text(), value.at("text").text())
|
|
153
|
-
"message.end" -> RuntimeEvent.MessageEnd(value.number("seq"), value.number("firstSeq"), value.at("id").text(),
|
|
181
|
+
"message.end" -> RuntimeEvent.MessageEnd(value.number("seq"), value.number("firstSeq"), value.at("id").text(), MessageStatus(value.at("status").text()),
|
|
154
182
|
value.at("text").text(), value.strings("markers"), value.get("output")?.takeUnless { it.isJsonNull }?.deepCopy(),
|
|
155
183
|
value.strings("inReplyTo"), value.strings("causedBy"), value.error(), at())
|
|
156
184
|
"state" -> state(value)
|
|
@@ -158,16 +186,16 @@ internal fun nativeEvent(value: JsonObject): RuntimeEvent {
|
|
|
158
186
|
Streaming(it.at("messageId").text(), it.number("firstSeq"), it.at("text").text())
|
|
159
187
|
})
|
|
160
188
|
"page" -> RuntimeEvent.Page(value.list("messages").map { nativeEvent(it.asJsonObject) }, value.flag("reachedFloor"), value.at("logId").text(), value.number("clearedSeq"))
|
|
161
|
-
"gap" -> RuntimeEvent.Gap(value.number("afterSeq"), value.number("throughSeq"),
|
|
189
|
+
"gap" -> RuntimeEvent.Gap(value.number("afterSeq"), value.number("throughSeq"), GapReason(value.at("reason").text()))
|
|
162
190
|
"cleared" -> RuntimeEvent.Cleared(value.number("seq"), value.at("id").text(), at())
|
|
163
191
|
"turn" -> RuntimeEvent.Turn(value.number("seq"), value.at("id").text(), value.strings("causedBy"), value.strings("inputs"), value.at("purpose").text(),
|
|
164
192
|
value.get("usage")?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet()?.associate { it.key to it.value.asLong } ?: emptyMap(),
|
|
165
|
-
value.get("costUsd")?.asDouble ?: 0.0,
|
|
193
|
+
value.get("costUsd")?.asDouble ?: 0.0, CostStatus(value.at("costStatus").text()), value.at("model").text(), value.optionalLong("imagesOmitted")?.toInt(), at())
|
|
166
194
|
"app" -> value.getAsJsonObject("source").let { RuntimeEvent.App(value.number("seq"), value.at("id").text(), value.at("name").text(), value.get("data").deepCopy(),
|
|
167
195
|
ToolSource(it.at("command").text(), it.at("callId").text()), at()) }
|
|
168
196
|
"error" -> if (value.has("seq")) RuntimeEvent.Error(value.number("seq"), value.at("id").text(), value.at("code").text(), value.at("message").text(), value.strings("inputs"), at())
|
|
169
197
|
else RuntimeEvent.StreamError(value.at("code").text(), value.at("message").text(), value.flag("poisoned"))
|
|
170
198
|
"replaced" -> RuntimeEvent.Replaced
|
|
171
|
-
else -> RuntimeEvent.Unknown(type)
|
|
199
|
+
else -> RuntimeEvent.Unknown(type, value.deepCopy())
|
|
172
200
|
}
|
|
173
201
|
}
|
|
@@ -40,13 +40,13 @@ interface RuntimeAttestor {
|
|
|
40
40
|
*/
|
|
41
41
|
interface RuntimeScheduler {
|
|
42
42
|
/** Replaces any earlier request with one at or after `earliestAtMs` (epoch ms). Idempotent:
|
|
43
|
-
* one request at a time, by a unique name. Throw `
|
|
43
|
+
* one request at a time, by a unique name. Throw `CrocheError("not_configured", ...)` when
|
|
44
44
|
* the app is not set up for it: the Runtime reports `schedule.degraded` with that code and
|
|
45
45
|
* still delivers while running and at the next open. */
|
|
46
46
|
fun schedule(earliestAtMs: Long)
|
|
47
47
|
/** Nothing is pending: withdraw the request. */
|
|
48
48
|
fun cancel()
|
|
49
|
-
/** A Runtime is opening with this scheduler. Throw `
|
|
49
|
+
/** A Runtime is opening with this scheduler. Throw `CrocheError("scheduler_conflict",
|
|
50
50
|
* ...)` to refuse it when its request name is already another open Runtime's: that name's
|
|
51
51
|
* runs could deliver through only one of them, including when the same scheduler object is
|
|
52
52
|
* given to a second Runtime. */
|
|
@@ -62,8 +62,8 @@ class FileRuntimeSecretStore(private val file: File) : RuntimeSecretStore {
|
|
|
62
62
|
@Synchronized override fun load(): JsonObject {
|
|
63
63
|
if (!file.exists()) return JsonObject()
|
|
64
64
|
val saved = try { JsonParser.parseString(file.readText(Charsets.UTF_8)) }
|
|
65
|
-
catch (_: Exception) { throw
|
|
66
|
-
if (!saved.isJsonObject) throw
|
|
65
|
+
catch (_: Exception) { throw CrocheError("corrupt_store", "Runtime credentials are unreadable; remove them to register again") }
|
|
66
|
+
if (!saved.isJsonObject) throw CrocheError("corrupt_store", "Runtime credentials must be an object")
|
|
67
67
|
return saved.asJsonObject
|
|
68
68
|
}
|
|
69
69
|
@Synchronized override fun remove() { Files.deleteIfExists(file.toPath()) }
|
|
@@ -88,7 +88,7 @@ internal class SchedulerClaims(private val what: String) {
|
|
|
88
88
|
private val holders = HashMap<String, Any>()
|
|
89
89
|
@Synchronized fun claim(identity: String, by: Any) {
|
|
90
90
|
if (holders[identity] != null) {
|
|
91
|
-
throw
|
|
91
|
+
throw CrocheError("scheduler_conflict", "Another open Runtime uses the $what \"$identity\"; give each Runtime its own, or close it first")
|
|
92
92
|
}
|
|
93
93
|
holders[identity] = by
|
|
94
94
|
}
|
|
@@ -20,6 +20,6 @@ internal fun projectPalRoute(label: String): ProjectPalRoute {
|
|
|
20
20
|
parts == listOf("\$gc", "pass") -> ProjectPalRoute("default", maintenance = true)
|
|
21
21
|
parts.size == 3 && parts[0] == "\$gc" -> ProjectPalRoute(parts[1], parts[2], maintenance = true)
|
|
22
22
|
parts.size == 2 -> ProjectPalRoute(parts[0], parts[1])
|
|
23
|
-
else -> throw
|
|
23
|
+
else -> throw CrocheError("invalid_configuration", "Invalid project PAL label")
|
|
24
24
|
}
|
|
25
25
|
}
|
|
@@ -16,7 +16,7 @@ internal fun defaultProjectDirectory(): File? = try {
|
|
|
16
16
|
/** Explicit locations are allowed only on hosts without an app-private default. */
|
|
17
17
|
internal fun projectRecordDirectory(option: File?, default: File?): File? {
|
|
18
18
|
if (option != null && default != null)
|
|
19
|
-
throw
|
|
19
|
+
throw CrocheError("invalid_configuration", "this platform keeps the project record in the app's private storage")
|
|
20
20
|
return option ?: default
|
|
21
21
|
}
|
|
22
22
|
|
|
@@ -29,26 +29,26 @@ internal class ProjectRecords(private val directory: () -> File?) {
|
|
|
29
29
|
|
|
30
30
|
private fun record(key: String): File {
|
|
31
31
|
if (!Regex("croche\\.project\\.v1\\.[0-9a-f]{64}").matches(key))
|
|
32
|
-
throw
|
|
33
|
-
val location = directory() ?: throw
|
|
32
|
+
throw CrocheError("storage_error", "Invalid project record key")
|
|
33
|
+
val location = directory() ?: throw CrocheError("storage_error",
|
|
34
34
|
"Project records require projectDirectory on this platform; no app-private default exists")
|
|
35
35
|
return File(location, "$key.json")
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
@Synchronized fun acquire(key: String) {
|
|
39
39
|
val target = record(key)
|
|
40
|
-
if (key in owned) throw
|
|
40
|
+
if (key in owned) throw CrocheError("store_busy", "Project record is already owned")
|
|
41
41
|
target.parentFile.mkdirs()
|
|
42
42
|
val opened = RandomAccessFile(File(target.path + ".lock"), "rw")
|
|
43
43
|
try {
|
|
44
|
-
val lock = opened.channel.tryLock() ?: throw
|
|
44
|
+
val lock = opened.channel.tryLock() ?: throw CrocheError("store_busy", "Project record is already owned")
|
|
45
45
|
owned[key] = Ownership(opened, lock)
|
|
46
46
|
} catch (failure: Exception) {
|
|
47
47
|
opened.close()
|
|
48
|
-
if (failure is
|
|
48
|
+
if (failure is CrocheError) throw failure
|
|
49
49
|
if (failure is java.nio.channels.OverlappingFileLockException)
|
|
50
|
-
throw
|
|
51
|
-
throw
|
|
50
|
+
throw CrocheError("store_busy", "Project record is already owned")
|
|
51
|
+
throw CrocheError("storage_error", "Could not lock the project record")
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
54
|
|
|
@@ -76,7 +76,7 @@ internal class ProjectRecords(private val directory: () -> File?) {
|
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
private fun requireOwnership(key: String) {
|
|
79
|
-
if (key !in owned) throw
|
|
79
|
+
if (key !in owned) throw CrocheError("storage_error", "Project record is not locked")
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
@Synchronized fun release(key: String) {
|
|
@@ -1,46 +1,117 @@
|
|
|
1
1
|
package dev.croche
|
|
2
2
|
|
|
3
|
-
import com.google.gson
|
|
4
|
-
import java.io.File
|
|
3
|
+
import com.google.gson.*
|
|
5
4
|
|
|
6
5
|
data class OpenOptions(
|
|
7
|
-
val cloudUrl: String? = null,
|
|
8
6
|
val projectKey: String,
|
|
9
|
-
|
|
10
|
-
* Structured calls always omit it; remote configs require schema 4 / 0.5.3+. */
|
|
11
|
-
val config: JsonObject,
|
|
7
|
+
val bundledConfig: JsonElement,
|
|
12
8
|
val user: String? = null,
|
|
13
|
-
val handlers: Map<String, ToolHandler> = emptyMap(),
|
|
14
9
|
val language: String? = null,
|
|
15
|
-
val
|
|
16
|
-
val
|
|
17
|
-
val
|
|
18
|
-
|
|
10
|
+
val tools: List<ToolRegistration>? = null,
|
|
11
|
+
val wiki: List<WikiDoc>? = null,
|
|
12
|
+
val storage: StoragePal? = null,
|
|
13
|
+
/** Android Context; opaque to the common wrapper, never serialized as an object. */
|
|
14
|
+
val platform: Any? = null,
|
|
15
|
+
val serverKey: String? = null,
|
|
19
16
|
val debugKey: String? = null,
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
val android: AndroidOptions? = null,
|
|
30
|
-
val projectDirectory: File? = null,
|
|
31
|
-
val http: RuntimeHTTP? = null,
|
|
32
|
-
)
|
|
33
|
-
enum class DebugVisibility { RUNTIME }
|
|
34
|
-
enum class Attestation { PLATFORM, OFF }
|
|
35
|
-
data class AndroidOptions(val cloudProjectNumber: Long? = null)
|
|
36
|
-
typealias ProjectUsageEvent = JsonObject
|
|
37
|
-
typealias RuntimeDebugEvent = JsonObject
|
|
38
|
-
typealias MemoryChangedEvent = JsonObject
|
|
39
|
-
typealias ProjectToolContext = ToolContext
|
|
17
|
+
) {
|
|
18
|
+
internal fun json() = JsonObject().apply {
|
|
19
|
+
addProperty("projectKey", projectKey); add("bundledConfig", bundledConfig.deepCopy())
|
|
20
|
+
user?.let { addProperty("user", it) }; language?.let { addProperty("language", it) }
|
|
21
|
+
serverKey?.let { addProperty("serverKey", it) }; debugKey?.let { addProperty("debugKey", it) }
|
|
22
|
+
wiki?.let { docs -> add("wiki", JsonArray().apply { docs.forEach { add(it.json()) } }) }
|
|
23
|
+
platform?.let { add("platform", JsonNull.INSTANCE) }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
40
26
|
|
|
41
|
-
|
|
42
|
-
data class
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
data class
|
|
46
|
-
|
|
27
|
+
/** A patch is sent on every open; Core decides identity, conflicts and the effective config. */
|
|
28
|
+
data class Instance(val id: String, val config: JsonElement? = null) {
|
|
29
|
+
internal fun json() = JsonObject().apply { addProperty("id", id); config?.let { add("config", it.deepCopy()) } }
|
|
30
|
+
}
|
|
31
|
+
data class AgentOptions(val instance: Instance? = null, val tools: ToolSelection? = null, val wiki: WikiSelection? = null) {
|
|
32
|
+
internal fun json() = JsonObject().apply {
|
|
33
|
+
instance?.let { add("instance", it.json()) }; tools?.let { add("tools", it.json()) }; wiki?.let { add("wiki", it.json()) }
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
data class ToolEntry(val tool: String, val bind: JsonObject? = null, val commands: List<String>? = null, val guide: String? = null) {
|
|
38
|
+
internal fun json() = JsonObject().apply {
|
|
39
|
+
addProperty("tool", tool); bind?.let { add("bind", it.deepCopy()) }
|
|
40
|
+
commands?.let { names -> add("commands", JsonArray().apply { names.forEach(::add) }) }
|
|
41
|
+
guide?.let { addProperty("guide", it) }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
sealed interface ToolSelection {
|
|
45
|
+
data object All : ToolSelection
|
|
46
|
+
data class Only(val entries: List<ToolEntry>) : ToolSelection
|
|
47
|
+
fun json(): JsonElement = when (this) {
|
|
48
|
+
All -> JsonPrimitive("all")
|
|
49
|
+
is Only -> JsonArray().apply { entries.forEach { add(it.json()) } }
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
data class WikiEntry(val doc: String, val guide: String? = null) {
|
|
53
|
+
internal fun json() = JsonObject().apply { addProperty("doc", doc); guide?.let { addProperty("guide", it) } }
|
|
54
|
+
}
|
|
55
|
+
sealed interface WikiSelection {
|
|
56
|
+
data object All : WikiSelection
|
|
57
|
+
data class Only(val entries: List<WikiEntry>) : WikiSelection
|
|
58
|
+
fun json(): JsonElement = when (this) {
|
|
59
|
+
All -> JsonPrimitive("all")
|
|
60
|
+
is Only -> JsonArray().apply { entries.forEach { add(it.json()) } }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
sealed interface WikiDoc {
|
|
64
|
+
val path: String
|
|
65
|
+
val description: String
|
|
66
|
+
data class Markdown(override val path: String, override val description: String, val markdown: String) : WikiDoc
|
|
67
|
+
data class File(override val path: String, override val description: String, val file: String) : WikiDoc
|
|
68
|
+
fun json() = JsonObject().apply {
|
|
69
|
+
addProperty("path", path); addProperty("description", description)
|
|
70
|
+
when (val doc = this@WikiDoc) {
|
|
71
|
+
is Markdown -> addProperty("markdown", doc.markdown)
|
|
72
|
+
is File -> addProperty("file", doc.file)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Separate second argument to Croche.open; Core validates the recover string. */
|
|
77
|
+
data class RecoveryOptions(val recover: String) {
|
|
78
|
+
internal fun json() = JsonObject().apply { addProperty("recover", recover) }
|
|
79
|
+
}
|
|
80
|
+
data class DeleteDataOptions(val agent: String? = null, val instance: String? = null) {
|
|
81
|
+
internal fun json() = JsonObject().apply { agent?.let { addProperty("agent", it) }; instance?.let { addProperty("instance", it) } }
|
|
82
|
+
}
|
|
83
|
+
data class RequestOptions(val responseFormat: JsonObject? = null, val wait: RequestWait? = null) {
|
|
84
|
+
internal fun json() = JsonObject().apply {
|
|
85
|
+
responseFormat?.let { add("responseFormat", it.deepCopy()) }; wait?.let { addProperty("wait", it.name.lowercase()) }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
data class SubscribeOptions(val initialMessages: Int? = null, val after: Cursor? = null, val deltaMs: Long? = null,
|
|
89
|
+
val onEvent: suspend (AppStreamContract.AgentEvent) -> Unit) {
|
|
90
|
+
internal fun json() = JsonObject().apply {
|
|
91
|
+
initialMessages?.let { addProperty("initialMessages", it) }
|
|
92
|
+
after?.let { add("after", JsonObject().apply { addProperty("logId", it.logId); addProperty("seq", it.seq) }) }
|
|
93
|
+
deltaMs?.let { addProperty("deltaMs", it) }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
data class HistoryOptions(val before: Long? = null, val limit: Int) {
|
|
97
|
+
internal fun json() = JsonObject().apply { before?.let { addProperty("before", it) }; addProperty("limit", limit) }
|
|
98
|
+
}
|
|
99
|
+
data class WakeQuery(val before: Long? = null, val after: Long? = null, val limit: Int? = null) {
|
|
100
|
+
internal fun json() = JsonObject().apply {
|
|
101
|
+
before?.let { addProperty("before", it) }; after?.let { addProperty("after", it) }; limit?.let { addProperty("limit", it) }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Core's background notification, forwarded unchanged. A skipped event's known reasons are
|
|
106
|
+
* `storage_unavailable` and `os_registration_failed`; future reasons remain readable strings.
|
|
107
|
+
* OS registration failure has only type/reason/at and never contains host failure details.
|
|
108
|
+
*/
|
|
109
|
+
data class BackgroundEvent(val type: String, val at: String?, val reason: String?, val fields: JsonObject)
|
|
110
|
+
|
|
111
|
+
/** Background uses the same PAL selection and custom-storage marker as open. */
|
|
112
|
+
data class BackgroundOptions(val sink: ((BackgroundEvent) -> Unit)? = null, val storage: StoragePal? = null)
|
|
113
|
+
|
|
114
|
+
/** Same options object as APP-API debugger.attach(options). */
|
|
115
|
+
data class DebugAttachOptions(val url: String, val token: String) {
|
|
116
|
+
internal fun json() = JsonObject().apply { addProperty("url", url); addProperty("token", token) }
|
|
117
|
+
}
|