@h1r-ai/croche-react-native 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +32 -4
- package/THIRD-PARTY-NOTICES +899 -6
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
- package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +1 -0
- package/dist/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +148 -25
- package/dist/react-native/src/core-wire.d.ts +20 -3
- package/dist/rn-shared-build.json +8 -8
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +53 -5
- package/dist/runtime/src/agent.js +69 -7
- package/dist/runtime/src/app-api.d.ts +307 -19
- package/dist/runtime/src/cancel.d.ts +2 -2
- package/dist/runtime/src/cancel.js +7 -4
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +48 -35
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -0
- package/dist/runtime/src/croche.d.ts +64 -9
- package/dist/runtime/src/croche.js +78 -17
- package/dist/runtime/src/errors.d.ts +7 -0
- package/dist/runtime/src/errors.js +15 -1
- package/dist/runtime/src/generated/app-stream.d.ts +155 -1
- package/dist/runtime/src/generated/app-stream.js +7 -4
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -21
- package/dist/runtime/src/index.native.js +2 -8
- package/dist/runtime/src/native-adapter.d.ts +1 -1
- package/dist/runtime/src/native-adapter.js +10 -4
- package/dist/runtime/src/pal/host.d.ts +3 -3
- package/dist/runtime/src/pal/host.js +34 -9
- package/dist/runtime/src/pal/platform.d.ts +11 -6
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -0
- package/dist/runtime/src/tools.d.ts +20 -4
- package/dist/runtime/src/tools.js +31 -7
- package/ios/CoreAgentTransport.swift +2 -2
- package/ios/CoreNativePal.swift +26 -21
- package/ios/CorePlatformTransport.swift +4 -4
- package/ios/CoreWireDispatch.swift +38 -8
- package/ios/CoreWireSupport.swift +179 -4
- package/ios/CrocheRuntimeBridge.swift +1 -1
- package/ios/ProjectPal.swift +15 -12
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
- package/package.json +3 -3
- package/scripts/README.md +1 -1
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +4 -3
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
- package/dist/runtime/src/pal/codec.d.ts +0 -15
- package/dist/runtime/src/pal/codec.js +0 -52
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
|
@@ -22,12 +22,6 @@ import java.util.concurrent.atomic.AtomicBoolean
|
|
|
22
22
|
/** The code the Runtime reads as "nothing ran" (croche_core::NOT_DISPATCHED). */
|
|
23
23
|
private const val NOT_DISPATCHED = "tool_not_dispatched"
|
|
24
24
|
|
|
25
|
-
/** Shared SDK/RN parser: TimeZone.getTimeZone(String) silently accepts unknown ids as GMT. */
|
|
26
|
-
internal fun projectTimeZone(id: String?): TimeZone? = id?.let {
|
|
27
|
-
try { TimeZone.getTimeZone(java.time.ZoneId.of(it)) }
|
|
28
|
-
catch (_: Exception) { throw CrocheError("invalid_configuration", "timeZone must be an IANA time zone") }
|
|
29
|
-
}
|
|
30
|
-
|
|
31
25
|
internal fun failure(error: Throwable): FfiException = when (error) {
|
|
32
26
|
is FfiException -> error
|
|
33
27
|
is CrocheError -> FfiException.Failure(error.code, error.message)
|
|
@@ -51,12 +45,7 @@ private fun signal(token: CancelToken): RuntimeCancellation = RuntimeCancellatio
|
|
|
51
45
|
token.onCancel(attached(object : CancelCallback { override fun cancelled() = signal.cancel() }))
|
|
52
46
|
}
|
|
53
47
|
|
|
54
|
-
|
|
55
|
-
override fun onEvent(event: String) = hostCallback {
|
|
56
|
-
val value = try { JsonParser.parseString(event) } catch (_: Exception) { return@hostCallback }
|
|
57
|
-
try { callback(value) } catch (_: Exception) {}
|
|
58
|
-
}
|
|
59
|
-
}
|
|
48
|
+
|
|
60
49
|
|
|
61
50
|
/** The `at`s (epoch ms) of a schedule set `[{id, at}]`. */
|
|
62
51
|
internal fun times(entries: JsonElement): List<Long> =
|
|
@@ -75,342 +64,3 @@ internal fun retryAt(value: JsonElement): Long? = try {
|
|
|
75
64
|
|
|
76
65
|
/** Each store object is one store; two Runtimes on it in a process are refused. */
|
|
77
66
|
private val identities: MutableMap<Any, String> = Collections.synchronizedMap(WeakHashMap())
|
|
78
|
-
|
|
79
|
-
/** The Kotlin PAL handed to the Rust Runtime. */
|
|
80
|
-
internal class KotlinHost(
|
|
81
|
-
private val storage: RuntimeStorage, private val secretStore: RuntimeSecretStore,
|
|
82
|
-
private val attestor: RuntimeAttestor?, private val transport: RuntimeHTTP,
|
|
83
|
-
tools: Map<String, ToolHandler>, private val background: Boolean,
|
|
84
|
-
private val osScheduler: RuntimeScheduler? = null,
|
|
85
|
-
projectDirectory: java.io.File? = null,
|
|
86
|
-
defaultDirectory: () -> java.io.File? = ::defaultProjectDirectory,
|
|
87
|
-
private val user: String? = null,
|
|
88
|
-
private val timeZone: TimeZone? = null
|
|
89
|
-
) : HostPal {
|
|
90
|
-
// This legacy host has no process-wide OS registrar. Its per-Runtime
|
|
91
|
-
// scheduler must not claim the fixed Core background registration succeeded.
|
|
92
|
-
override fun registerBackground(identifier: String, wake: CoreBackgroundWake) {
|
|
93
|
-
throw CorePalException.Failure("capability_unsupported", "This host has no OS background registrar.")
|
|
94
|
-
}
|
|
95
|
-
private val projectRecords = ProjectRecords { projectRecordDirectory(projectDirectory, defaultDirectory()) }
|
|
96
|
-
internal var beforeProjectLock: (() -> Unit)? = null
|
|
97
|
-
internal var afterProjectRead: ((String?) -> Unit)? = null
|
|
98
|
-
internal var beforeProjectWrite: (() -> Unit)? = null
|
|
99
|
-
// Accepted tools are never removed: a tool change waits its turn in the Core's queue, and turns queued before it
|
|
100
|
-
// still run the old list. The Core alone decides which commands a turn may call.
|
|
101
|
-
@Volatile private var handlers: Map<String, ToolHandler> = tools
|
|
102
|
-
private val staged = HashMap<String, Int>() // names whose only handler is from a call in flight
|
|
103
|
-
private var stamp = 0
|
|
104
|
-
/** Stages the handlers for names with none yet, or with one only staged by a call still in
|
|
105
|
-
* flight (a later call wins). Returns the stamp that [unstageTools] needs. */
|
|
106
|
-
fun stageTools(tools: Map<String, ToolHandler>): Int = synchronized(lock) {
|
|
107
|
-
stamp += 1
|
|
108
|
-
val names = tools.keys.filter { it !in handlers || it in staged }
|
|
109
|
-
handlers = handlers + tools.filterKeys { it in names }
|
|
110
|
-
names.forEach { staged[it] = stamp }
|
|
111
|
-
stamp
|
|
112
|
-
}
|
|
113
|
-
/** A refused call: removes what it staged, unless a later call has staged the name since. */
|
|
114
|
-
fun unstageTools(names: Set<String>, stamp: Int) = synchronized(lock) {
|
|
115
|
-
val mine = names.filter { staged[it] == stamp }
|
|
116
|
-
handlers = handlers - mine.toSet(); mine.forEach { staged.remove(it) }
|
|
117
|
-
}
|
|
118
|
-
/** An accepted call: its handlers serve every name it passed. */
|
|
119
|
-
fun acceptTools(tools: Map<String, ToolHandler>) = synchronized(lock) {
|
|
120
|
-
handlers = handlers + tools; tools.keys.forEach { staged.remove(it) }
|
|
121
|
-
}
|
|
122
|
-
/** A project instance's latest successful patched open: its table replaces the old one for future
|
|
123
|
-
* invocations, as in TypeScript. A call already running keeps the handler it started with. */
|
|
124
|
-
fun replaceTools(tools: Map<String, ToolHandler>) = synchronized(lock) {
|
|
125
|
-
handlers = tools; staged.clear()
|
|
126
|
-
}
|
|
127
|
-
private val effects = EffectExecutor()
|
|
128
|
-
private val tools = ToolExecutor()
|
|
129
|
-
private val identity = identities.getOrPut(storage) { "kotlin:" + UUID.randomUUID() }
|
|
130
|
-
private val lock = Any()
|
|
131
|
-
private var core: WeakReference<CoreRuntime>? = null
|
|
132
|
-
private var wakeTarget: Double? = null
|
|
133
|
-
private var timer: ScheduledFuture<*>? = null
|
|
134
|
-
private var scheduler: ScheduledExecutorService? = null
|
|
135
|
-
private var stopped = false
|
|
136
|
-
/** This Runtime's attachment to `osScheduler` (attached before the host is built), released
|
|
137
|
-
* once: a second stop, or a stale close after the scheduler was attached again for another
|
|
138
|
-
* Runtime, must not free a name someone else holds. Guarded by `lock`. */
|
|
139
|
-
private var osAttached = osScheduler != null
|
|
140
|
-
/** The wall clock (epoch ms) the Runtime and its timers read. Tests move it. */
|
|
141
|
-
@Volatile internal var clock: () -> Long = { System.currentTimeMillis() }
|
|
142
|
-
/** Runs `deliverDue()` on the Runtime when the earliest note's time comes. */
|
|
143
|
-
@Volatile internal var deliver: (() -> Unit)? = null
|
|
144
|
-
private var dueAt: Long? = null
|
|
145
|
-
private var fired: Long? = null
|
|
146
|
-
private var dueTimer: ScheduledFuture<*>? = null
|
|
147
|
-
private var deliveries: ScheduledExecutorService? = null
|
|
148
|
-
|
|
149
|
-
private inline fun <T> host(body: () -> T): T = try { body() } catch (error: Exception) { throw failure(error) }
|
|
150
|
-
|
|
151
|
-
internal val images = NativeImagePal()
|
|
152
|
-
private val decodedImages = platformDecodedImageCodec()
|
|
153
|
-
override fun streamPlatform(): HostStreamPlatform = HostStreamPlatform.OTHER
|
|
154
|
-
override fun imageCodecAvailable(): Boolean = decodedImages != null
|
|
155
|
-
override fun decodeImage(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken): PalDecodedImage = host {
|
|
156
|
-
(decodedImages ?: throw NativeImagePal.failure("image_unsupported")).decode(bytes, options, cancel)
|
|
157
|
-
}
|
|
158
|
-
override fun renderImage(request: PalImageRenderRequest, cancel: CancelToken): ByteArray = host {
|
|
159
|
-
(decodedImages ?: throw NativeImagePal.failure("image_unsupported")).render(request, cancel)
|
|
160
|
-
}
|
|
161
|
-
override fun releaseDecodedImage(handle: String) { decodedImages?.release(handle) }
|
|
162
|
-
override fun readImage(request: PalImageReadRequest, cancel: CancelToken): ByteArray = host { images.readBytes(request, cancel) }
|
|
163
|
-
override fun prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken): PalImageBytes =
|
|
164
|
-
host { images.prepare(source, plan, cancel) }
|
|
165
|
-
override fun releaseImage(capture: String) { images.release(capture) }
|
|
166
|
-
|
|
167
|
-
// Transitional legacy host extensions. S2's dedicated platform adapter supplies assets/list.
|
|
168
|
-
override fun platformFacts(): PalPlatformFacts = PalPlatformFacts(PalTargetKind.OTHER, null, java.util.Locale.getDefault().toLanguageTag(), null, false)
|
|
169
|
-
override fun readAsset(path: String): ByteArray? = host {
|
|
170
|
-
throw CrocheError("capability_unsupported", "App assets require the S2 platform PAL")
|
|
171
|
-
}
|
|
172
|
-
override fun list(prefix: String): List<String> = host {
|
|
173
|
-
throw CrocheError("capability_unsupported", "Key listing requires the S2 platform PAL")
|
|
174
|
-
}
|
|
175
|
-
override fun resolve(host: String, cancel: CancelToken): List<String> = this.host {
|
|
176
|
-
dev.croche.s7.pal.DirectHttpPal().resolve(host, signal(cancel))
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
// HTTP
|
|
180
|
-
override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) = host {
|
|
181
|
-
if (request.connectTo != null) throw CrocheError("capability_unsupported", "Pinned HTTP requires the S2 platform PAL")
|
|
182
|
-
if (request.responseMode != "standard") throw CrocheError("image_unsupported", "Native image inputs are not supported yet")
|
|
183
|
-
try {
|
|
184
|
-
effects.run(request.timeoutMs.toLong(), signal(cancel)) { local ->
|
|
185
|
-
if (transport is RuntimeHttpURLConnection) transport.stream(request, sink, local) else adapt(request, sink, local)
|
|
186
|
-
JsonNull.INSTANCE
|
|
187
|
-
}
|
|
188
|
-
} catch (error: java.io.IOException) {
|
|
189
|
-
// The call keeps a Runtime code; what failed underneath rides along as its class name
|
|
190
|
-
// (never the message, which may name hosts): Logs then say why (dev, 2026-10-05).
|
|
191
|
-
throw CrocheError(transportCode(error), "The HTTP transport failed")
|
|
192
|
-
}
|
|
193
|
-
Unit
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/** An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
|
|
197
|
-
* a response, and its stream deltas as server-sent events. */
|
|
198
|
-
internal fun adapt(request: PalHttpRequest, sink: HttpSink, signal: RuntimeCancellation) {
|
|
199
|
-
val headers = JsonObject().apply { request.headers.forEach { addProperty(it.name, it.value) } }
|
|
200
|
-
val body = request.body?.let { value -> try { JsonParser.parseString(value) } catch (_: Exception) { str(value) } } ?: JsonNull.INSTANCE
|
|
201
|
-
val effect = obj("url" to str(request.url), "method" to str(request.method), "headers" to headers,
|
|
202
|
-
"body" to body, "timeoutMs" to num(request.timeoutMs.toLong()))
|
|
203
|
-
val started = AtomicBoolean(false)
|
|
204
|
-
val eventStream = listOf(PalHeader("content-type", "text/event-stream"))
|
|
205
|
-
val reply = transport.execute(effect, signal) { data ->
|
|
206
|
-
if (started.compareAndSet(false, true)) sink.head(200u, eventStream)
|
|
207
|
-
val frame = data.split("\n").joinToString("") { "data: $it\n" } + "\n"
|
|
208
|
-
sink.chunk(frame.toByteArray(Charsets.UTF_8))
|
|
209
|
-
}
|
|
210
|
-
val status = reply.at("status").let { if (it.isJsonPrimitive) it.asInt else 0 }.toUShort()
|
|
211
|
-
if (reply.at("streamed").let { it.isJsonPrimitive && it.asBoolean }) {
|
|
212
|
-
if (started.compareAndSet(false, true)) sink.head(status, eventStream)
|
|
213
|
-
return
|
|
214
|
-
}
|
|
215
|
-
val fields = reply.at("headers").let { if (it.isJsonObject) it.asJsonObject.entrySet() else emptySet() }
|
|
216
|
-
.filter { (key, value) -> value.text().isNotEmpty() && !key.equals("content-type", ignoreCase = true) }
|
|
217
|
-
.map { (key, value) -> PalHeader(key, value.text()) } + PalHeader("content-type", "application/json")
|
|
218
|
-
sink.head(status, fields)
|
|
219
|
-
val data = if (!reply.at("body").isJsonNull) reply.at("body").toString() else reply.at("raw").text()
|
|
220
|
-
if (data.isNotEmpty()) sink.chunk(data.toByteArray(Charsets.UTF_8))
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// Storage
|
|
224
|
-
/** The Core names its snapshot by the key it locks, and other records `<key>.<entry>` (F19's
|
|
225
|
-
* held sends: `<key>.held`). Each goes to its own place: an entry never replaces the snapshot. */
|
|
226
|
-
@Volatile private var snapshotKey: String? = null
|
|
227
|
-
private fun entry(key: String): String? {
|
|
228
|
-
val main = snapshotKey ?: return null
|
|
229
|
-
if (key == main) return null
|
|
230
|
-
if (!key.startsWith("$main.") || key.length <= main.length + 1) throw CrocheError("storage_error", "Unknown storage key")
|
|
231
|
-
return key.substring(main.length + 1)
|
|
232
|
-
}
|
|
233
|
-
private inline fun <T> projectIO(body: () -> T): T = try { body() }
|
|
234
|
-
catch (_: java.io.IOException) { throw CrocheError("storage_error", "Could not access the project record") }
|
|
235
|
-
override fun read(key: String): String? = host {
|
|
236
|
-
if (isProjectKey(key)) return@host projectIO { projectRecords.read(key) }.also { afterProjectRead?.invoke(it) }
|
|
237
|
-
val name = entry(key)
|
|
238
|
-
val state = when {
|
|
239
|
-
name == null -> storage.load()
|
|
240
|
-
// A storage without entries never stored one.
|
|
241
|
-
storage is KeyedRuntimeStorage -> storage.load(name)
|
|
242
|
-
else -> JsonNull.INSTANCE
|
|
243
|
-
}
|
|
244
|
-
if (state.isJsonNull) null else state.toString()
|
|
245
|
-
}
|
|
246
|
-
override fun write(key: String, value: String) = persist {
|
|
247
|
-
if (isProjectKey(key)) { beforeProjectWrite?.invoke(); projectRecords.write(key, value); return@persist }
|
|
248
|
-
val name = entry(key)
|
|
249
|
-
when {
|
|
250
|
-
name == null -> storage.save(JsonParser.parseString(value))
|
|
251
|
-
storage is KeyedRuntimeStorage -> storage.save(name, JsonParser.parseString(value))
|
|
252
|
-
else -> throw CrocheError("storage_error", "This RuntimeStorage keeps only its snapshot")
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
override fun remove(key: String) = persist {
|
|
256
|
-
if (isProjectKey(key)) throw CrocheError("storage_error", "The project record is kept when agent data is removed")
|
|
257
|
-
val name = entry(key)
|
|
258
|
-
when {
|
|
259
|
-
name == null -> storage.remove()
|
|
260
|
-
storage is KeyedRuntimeStorage -> storage.remove(name)
|
|
261
|
-
storage is ArchiveRuntimeStorage && isLineStorageEntry(name) -> storage.remove(name)
|
|
262
|
-
else -> Unit // A snapshot-only storage has never held named entries.
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
override fun removeSecret(key: String) = persist { secretStore.remove() }
|
|
266
|
-
override fun readSecret(key: String): String? = host { secretStore.load().toString() }
|
|
267
|
-
override fun writeSecret(key: String, value: String) = persist { secretStore.save(JsonParser.parseString(value).asJsonObject) }
|
|
268
|
-
private fun persist(body: () -> Unit) = try { body() } catch (error: Exception) {
|
|
269
|
-
throw if (error is CrocheError) failure(error) else FfiException.Failure("storage_error", "Could not persist Runtime state")
|
|
270
|
-
}
|
|
271
|
-
override fun lock(key: String) = host {
|
|
272
|
-
if (isProjectKey(key)) projectIO { beforeProjectLock?.invoke(); projectRecords.acquire(key) }
|
|
273
|
-
else { storage.acquire(); snapshotKey = key }
|
|
274
|
-
PalLockOutcome.ACQUIRED
|
|
275
|
-
}
|
|
276
|
-
override fun unlock(key: String) {
|
|
277
|
-
if (isProjectKey(key)) { projectRecords.release(key); return }
|
|
278
|
-
stop(); try { storage.release() } catch (_: Exception) {}
|
|
279
|
-
}
|
|
280
|
-
override fun storeIdentity(): String = identity
|
|
281
|
-
|
|
282
|
-
// The turn archive (F20.6)
|
|
283
|
-
/** The storage's archive, or the typed "no archive": the Runtime then keeps none, and every
|
|
284
|
-
* turn, clearHistory and memory work as before. */
|
|
285
|
-
private fun <T> archive(body: (ArchiveRuntimeStorage) -> T): T = try {
|
|
286
|
-
val archive = storage as? ArchiveRuntimeStorage ?: throw CrocheError("archive_unavailable", "This host keeps no turn archive.")
|
|
287
|
-
body(archive)
|
|
288
|
-
} catch (error: Exception) {
|
|
289
|
-
throw if (error is CrocheError) failure(error) else FfiException.Failure("storage_error", "The turn archive could not be read or written")
|
|
290
|
-
}
|
|
291
|
-
override fun archiveAppendLine(entry: String, line: String) = archive { it.appendLine(entry, line) }
|
|
292
|
-
override fun archiveReadLines(entry: String): List<String> = archive { it.readLines(entry) }
|
|
293
|
-
override fun archiveReplaceLines(entry: String, lines: List<String>) = archive { it.replaceLines(entry, lines) }
|
|
294
|
-
override fun archiveRemove(entry: String) = archive { it.remove(entry) }
|
|
295
|
-
override fun archiveEntries(prefix: String): List<ArchiveEntry> =
|
|
296
|
-
archive { a -> a.entries(prefix).toSortedMap().map { (entry, bytes) -> ArchiveEntry(entry, bytes.toULong()) } }
|
|
297
|
-
|
|
298
|
-
/** Where the message log goes (S1, rev 4 §17.13): in lines when the storage appends them, in
|
|
299
|
-
* entries when it keeps entries, else inside the snapshot. Never refused. */
|
|
300
|
-
override fun storageCapability(): StorageCapability = when (storage) {
|
|
301
|
-
is ArchiveRuntimeStorage -> StorageCapability.LINES
|
|
302
|
-
is KeyedRuntimeStorage -> StorageCapability.KEYED
|
|
303
|
-
else -> StorageCapability.SNAPSHOT
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
// Tools and attestation
|
|
307
|
-
override fun tool(invocation: String, cancel: CancelToken): ToolOutput = host {
|
|
308
|
-
val call = JsonParser.parseString(invocation)
|
|
309
|
-
val name = call.at("tool").text()
|
|
310
|
-
val handler = handlers[name] ?: throw CrocheError(NOT_DISPATCHED, "The host tool is not available")
|
|
311
|
-
val context = call.at("context")
|
|
312
|
-
val request = CommandInvocation(name, call.at("command").text().ifEmpty { null }, call.at("key").text(),
|
|
313
|
-
call.at("args").let { if (it.isJsonObject) it.asJsonObject.deepCopy() else JsonObject() })
|
|
314
|
-
// No deadline here: the Runtime times the call and cancels it (H4). This returns when
|
|
315
|
-
// the handler does, so a stuck one keeps its slot (H1).
|
|
316
|
-
val sink = ToolImages()
|
|
317
|
-
val value = tools.run(signal(cancel)) { local ->
|
|
318
|
-
handler.execute(request, LegacyToolContext(context.at("callId").text(),
|
|
319
|
-
context.at("messageId").text(), context.at("userId").text(), local,
|
|
320
|
-
context.at("agentId").text().ifEmpty { null }, sink,
|
|
321
|
-
user,
|
|
322
|
-
context.at("causedBy").let { if (it.isJsonArray) it.asJsonArray.map { id -> id.asString } else emptyList() },
|
|
323
|
-
context.at("origin").text().ifEmpty { "app" }))
|
|
324
|
-
}
|
|
325
|
-
// A plain handler's JSON is the value as it was; a `withResult` one's images ride beside
|
|
326
|
-
// it, one sink per call (never shared between concurrent calls).
|
|
327
|
-
ToolOutput(value.toString(), sink.images.map { CrocheImages.record(it) })
|
|
328
|
-
}
|
|
329
|
-
override fun attest(request: String, timeoutMs: ULong): String = host {
|
|
330
|
-
val platform = attestor ?: throw CrocheError("attestation_unsupported", "This host has no attestor")
|
|
331
|
-
val effect = JsonParser.parseString(request)
|
|
332
|
-
val clientData = effect.at("clientData").text()
|
|
333
|
-
val hash = effect.at("clientDataHash").text()
|
|
334
|
-
if (clientData.isEmpty() || hash.isEmpty()) throw CrocheError("invalid_abi", "Malformed attest effect")
|
|
335
|
-
effects.run(timeoutMs.toLong(), RuntimeCancellation()) { signal ->
|
|
336
|
-
val proof = platform.attest(clientData, hash, signal)
|
|
337
|
-
obj("platform" to str(platform.platform), "token" to str(proof.token),
|
|
338
|
-
"keyId" to (proof.keyId?.let { str(it) } ?: JsonNull.INSTANCE))
|
|
339
|
-
}.toString()
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
// Clock, entropy, timer
|
|
343
|
-
override fun nowMs(): Double = clock().toDouble()
|
|
344
|
-
override fun utcOffsetMinutes(atMs: Double): Long = (timeZone ?: TimeZone.getDefault()).getOffset(atMs.toLong()).toLong() / 60_000
|
|
345
|
-
override fun random(): String = UUID.randomUUID().toString()
|
|
346
|
-
override fun wake(atMs: Double?) {
|
|
347
|
-
synchronized(lock) { wakeTarget = atMs }
|
|
348
|
-
arm()
|
|
349
|
-
}
|
|
350
|
-
/** The agent's whole pending schedule set (JSON `[{id, at}]`), after each durable change and
|
|
351
|
-
* at open: a timer while running, and the OS's deferred work (`osScheduler`) for after. A
|
|
352
|
-
* refused registration fails this acknowledgement, which the Core reports as
|
|
353
|
-
* `schedule.degraded` with its code. */
|
|
354
|
-
override fun schedule(entries: String) = host { applySchedule(target(times(JsonParser.parseString(entries)))) }
|
|
355
|
-
@Volatile private var retryFloor: Long? = null
|
|
356
|
-
/** A failed delivery answered `retryAt`: a note already due waits until then. */
|
|
357
|
-
internal fun retryAfter(atMs: Long) { retryFloor = atMs }
|
|
358
|
-
/** When to wake for these notes: the earliest `at`, except that a note already due waits for
|
|
359
|
-
* a later `retryAt` (a delivery failed). */
|
|
360
|
-
internal fun target(times: List<Long>): Long? {
|
|
361
|
-
val now = clock()
|
|
362
|
-
val floor = retryFloor?.takeIf { it > now }
|
|
363
|
-
return times.map { if (floor != null && it <= now) floor else it }.minOrNull()
|
|
364
|
-
}
|
|
365
|
-
/** Arms the timer for `at` (null: nothing pending) and registers it with the OS. */
|
|
366
|
-
internal fun applySchedule(at: Long?) {
|
|
367
|
-
synchronized(lock) { dueAt = at }
|
|
368
|
-
armDelivery()
|
|
369
|
-
val os = osScheduler ?: return
|
|
370
|
-
try { if (at == null) os.cancel() else os.schedule(at) }
|
|
371
|
-
catch (error: CrocheError) { throw error }
|
|
372
|
-
catch (_: Exception) { throw CrocheError("schedule_failed", "The OS scheduler refused the request") }
|
|
373
|
-
}
|
|
374
|
-
/** The Runtime is open: a wake it asked for while opening can now fire. */
|
|
375
|
-
fun attach(core: CoreRuntime) { synchronized(lock) { this.core = WeakReference(core) }; arm(); armDelivery() }
|
|
376
|
-
fun stop() {
|
|
377
|
-
synchronized(lock) {
|
|
378
|
-
stopped = true; timer?.cancel(false); timer = null; scheduler?.shutdown()
|
|
379
|
-
dueTimer?.cancel(false); dueTimer = null; deliveries?.shutdown()
|
|
380
|
-
}
|
|
381
|
-
images.close()
|
|
382
|
-
decodedImages?.close()
|
|
383
|
-
val release = synchronized(lock) { osAttached.also { osAttached = false } }
|
|
384
|
-
if (release) try { osScheduler?.detach() } catch (_: Exception) {}
|
|
385
|
-
}
|
|
386
|
-
/** One timer at the earliest note, never firing a delivery before its time (a timer that
|
|
387
|
-
* ends early re-arms), and at most once per time: a delivery that was cut short leaves its
|
|
388
|
-
* notes for the next open, foreground or OS run rather than retrying at once. */
|
|
389
|
-
private fun armDelivery() = synchronized(lock) {
|
|
390
|
-
dueTimer?.cancel(false); dueTimer = null
|
|
391
|
-
val target = dueAt
|
|
392
|
-
if (stopped || core == null || target == null || fired?.let { target <= it } == true) return@synchronized
|
|
393
|
-
val pool = deliveries ?: Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "croche-schedule").apply { isDaemon = true } }
|
|
394
|
-
.also { deliveries = it }
|
|
395
|
-
val delay = (target - clock()).coerceAtLeast(0)
|
|
396
|
-
dueTimer = pool.schedule({ due(target) }, delay, TimeUnit.MILLISECONDS)
|
|
397
|
-
}
|
|
398
|
-
/** A delivery is starting: it covers every note due now, so the timer never retries one. */
|
|
399
|
-
internal fun attempted() = synchronized(lock) { fired = maxOf(fired ?: Long.MIN_VALUE, clock()) }
|
|
400
|
-
private fun due(target: Long) {
|
|
401
|
-
if (clock() < target) { armDelivery(); return }
|
|
402
|
-
synchronized(lock) { if (stopped) return; fired = target }
|
|
403
|
-
try { deliver?.invoke() } catch (_: Exception) {}
|
|
404
|
-
}
|
|
405
|
-
fun release() { stop(); projectRecords.releaseAll(); effects.close(); tools.close() }
|
|
406
|
-
private fun arm() = synchronized(lock) {
|
|
407
|
-
timer?.cancel(false); timer = null
|
|
408
|
-
val target = wakeTarget
|
|
409
|
-
val runtime = core
|
|
410
|
-
if (!background || stopped || target == null || runtime == null) return@synchronized
|
|
411
|
-
val pool = scheduler ?: Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "croche-upkeep").apply { isDaemon = true } }
|
|
412
|
-
.also { scheduler = it }
|
|
413
|
-
val delay = (target - System.currentTimeMillis()).toLong().coerceAtLeast(0)
|
|
414
|
-
timer = pool.schedule({ try { runtime.get()?.tick() } catch (_: Exception) {} }, delay, TimeUnit.MILLISECONDS)
|
|
415
|
-
}
|
|
416
|
-
}
|
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
package dev.croche
|
|
2
2
|
|
|
3
|
-
import com.google.gson.JsonElement
|
|
4
|
-
import com.google.gson.JsonNull
|
|
5
3
|
import com.google.gson.JsonObject
|
|
6
4
|
import com.google.gson.JsonPrimitive
|
|
7
5
|
import dev.croche.ffi.ToolImage
|
|
@@ -12,35 +10,14 @@ import java.util.Base64
|
|
|
12
10
|
* first frame). HIGH: as given, within the limits (3 MB each, 6 MB together), for text,
|
|
13
11
|
* screenshots and dense detail. An https `url` image is never changed. An image's own
|
|
14
12
|
* `"resolution"` (`"standard"` or `"high"`) wins over the send's or the tool result's. */
|
|
15
|
-
enum class ImageResolution {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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(),
|
|
23
|
-
/** For every image that does not name its own `"resolution"`. */
|
|
24
|
-
val imageResolution: ImageResolution? = null)
|
|
25
|
-
fun interface ToolResultHandler { fun execute(invocation: CommandInvocation, context: LegacyToolContext): LegacyToolResult }
|
|
26
|
-
|
|
27
|
-
/** The one way to return a [LegacyToolResult] (its value, plus images): `"room" to withResult { invocation, context -> LegacyToolResult(...) }`.
|
|
28
|
-
* The images go to the Runtime beside the value; a plain [ToolHandler]'s JSON is never looked inside. */
|
|
29
|
-
fun withResult(handler: ToolResultHandler): ToolHandler = ToolHandler { invocation, context ->
|
|
30
|
-
val result = handler.execute(invocation, context)
|
|
31
|
-
// The handler ran: what it returned is read once, here. Anything that cannot be read fails
|
|
32
|
-
// this call alone with our own invalid_tool_result, never another error (Atlas, #351 P1-2).
|
|
33
|
-
try {
|
|
34
|
-
val images = result.images.toList()
|
|
35
|
-
context.images?.images = images.map { CrocheImages.prepare(it, result.imageResolution) }
|
|
36
|
-
result.value
|
|
37
|
-
} catch (failed: Throwable) {
|
|
38
|
-
if (failed is InterruptedException) throw failed
|
|
39
|
-
throw CrocheError("invalid_tool_result", "The tool returned a result that could not be read. Its effects may have completed.")
|
|
40
|
-
}
|
|
13
|
+
enum class ImageResolution {
|
|
14
|
+
/** Use the standard size preparation path where supported. */
|
|
15
|
+
STANDARD,
|
|
16
|
+
/** Keep original encoded detail within Core's image input limits. */
|
|
17
|
+
HIGH
|
|
41
18
|
}
|
|
42
19
|
|
|
43
|
-
/**
|
|
20
|
+
/** Image buffer used by the former tool handler. */
|
|
44
21
|
class ToolImages internal constructor() {
|
|
45
22
|
@Volatile internal var images: List<JsonObject> = emptyList()
|
|
46
23
|
}
|
|
@@ -51,10 +28,19 @@ interface ImageCodec {
|
|
|
51
28
|
* is (a GIF's first frame): PNG, and JPEG unless a pixel can be transparent. Null when this
|
|
52
29
|
* platform cannot decode it. `changed`: resized or turned upright. */
|
|
53
30
|
fun render(bytes: ByteArray, maxSide: Int): Rendered?
|
|
31
|
+
/**
|
|
32
|
+
* Encoded outputs from the platform rendering step.
|
|
33
|
+
*
|
|
34
|
+
* @property changed Whether orientation or dimensions changed during rendering.
|
|
35
|
+
* @property jpeg JPEG candidate when the rendered image can be encoded without losing transparency.
|
|
36
|
+
* @property png Rendered PNG bytes.
|
|
37
|
+
*/
|
|
54
38
|
class Rendered(val png: ByteArray, val jpeg: ByteArray?, val changed: Boolean)
|
|
55
39
|
}
|
|
56
40
|
|
|
41
|
+
/** Helpers for preparing encoded images using the platform codec. */
|
|
57
42
|
object CrocheImages {
|
|
43
|
+
/** Longest side in pixels used for standard image preparation by these helpers. */
|
|
58
44
|
const val STANDARD_MAX_SIDE = 512
|
|
59
45
|
/** The codec standard images go through: on Android, the SDK's Bitmap codec; on a plain JVM
|
|
60
46
|
* none, and images are sent as given. */
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
package dev.croche
|
|
2
|
+
|
|
3
|
+
import com.google.gson.*
|
|
4
|
+
import java.time.Instant
|
|
5
|
+
|
|
6
|
+
// Pure legacy-event reader retained for its existing stream kernel and reader witnesses.
|
|
7
|
+
internal fun publicSequence(value: ULong): Long {
|
|
8
|
+
if (value > Long.MAX_VALUE.toULong()) throw CrocheError("invalid_input", "Core sequence exceeds Long.MAX_VALUE")
|
|
9
|
+
return value.toLong()
|
|
10
|
+
}
|
|
11
|
+
internal fun coreSequence(value: Long): ULong {
|
|
12
|
+
if (value < 0) throw CrocheError("invalid_input", "Sequence must not be negative")
|
|
13
|
+
return value.toULong()
|
|
14
|
+
}
|
|
15
|
+
private fun JsonElement.sequence(): Long {
|
|
16
|
+
val value = asString.toULongOrNull() ?: throw CrocheError("invalid_input", "Core sequence is not an unsigned integer")
|
|
17
|
+
return publicSequence(value)
|
|
18
|
+
}
|
|
19
|
+
private fun JsonObject.number(name: String) = get(name).sequence()
|
|
20
|
+
private fun JsonObject.optionalLong(name: String) = get(name)?.takeUnless { it.isJsonNull }?.sequence()
|
|
21
|
+
private fun JsonObject.flag(name: String) = get(name)?.takeUnless { it.isJsonNull }?.asBoolean ?: false
|
|
22
|
+
private fun JsonObject.list(name: String): List<JsonElement> = get(name)?.takeIf { it.isJsonArray }?.asJsonArray?.toList() ?: emptyList()
|
|
23
|
+
private fun JsonObject.strings(name: String) = list(name).map { it.asString }
|
|
24
|
+
private fun JsonObject.error() = get("error")?.takeIf { it.isJsonObject }?.asJsonObject?.let { RuntimeError(it.at("code").text(), it.at("message").text()) }
|
|
25
|
+
|
|
26
|
+
/** Decode the Core's tagged JSON; omission stays omission, unknown reader values keep their exact strings. */
|
|
27
|
+
internal fun nativeEvent(value: JsonObject): RuntimeEvent {
|
|
28
|
+
fun at() = Instant.parse(value.at("at").text())
|
|
29
|
+
fun state(v: JsonObject) = RuntimeEvent.State(AgentStatus(v.at("status").text()), v.number("queued").toInt(), v.flag("typing"),
|
|
30
|
+
v.get("activity")?.takeUnless { it.isJsonNull }?.let { AgentActivity(it.text()) },
|
|
31
|
+
v.get("tools")?.takeIf { it.isJsonArray }?.asJsonArray?.map { it.asString })
|
|
32
|
+
return when (val type = value.at("type").text()) {
|
|
33
|
+
"input" -> RuntimeEvent.Input(value.number("seq"), value.number("firstSeq"), value.at("id").text(), InputKind(value.at("kind").text()),
|
|
34
|
+
value.get("text")?.takeUnless { it.isJsonNull }?.asString, value.list("images").map { image -> image.asJsonObject.let {
|
|
35
|
+
ImageSummary(it.get("alt")?.asString, it.get("mime")?.asString, it.optionalLong("bytes"))
|
|
36
|
+
} }, InputStatus(value.at("status").text()), value.error(), at())
|
|
37
|
+
"message.start" -> RuntimeEvent.MessageStart(value.number("seq"), value.number("firstSeq"), value.at("id").text(), at())
|
|
38
|
+
"message.delta" -> RuntimeEvent.MessageDelta(value.at("id").text(), value.at("text").text())
|
|
39
|
+
"message.end" -> RuntimeEvent.MessageEnd(value.number("seq"), value.number("firstSeq"), value.at("id").text(), MessageStatus(value.at("status").text()),
|
|
40
|
+
value.at("text").text(), value.strings("markers"), value.get("output")?.takeUnless { it.isJsonNull }?.deepCopy(),
|
|
41
|
+
value.strings("inReplyTo"), value.strings("causedBy"), value.error(), at())
|
|
42
|
+
"state" -> state(value)
|
|
43
|
+
"snapshot" -> RuntimeEvent.Snapshot(value.at("logId").text(), state(value.getAsJsonObject("state")), value.get("streaming")?.takeIf { it.isJsonObject }?.asJsonObject?.let {
|
|
44
|
+
Streaming(it.at("messageId").text(), it.number("firstSeq"), it.at("text").text())
|
|
45
|
+
})
|
|
46
|
+
"page" -> RuntimeEvent.Page(value.list("messages").map { nativeEvent(it.asJsonObject) }, value.flag("reachedFloor"), value.at("logId").text(), value.number("clearedSeq"))
|
|
47
|
+
"gap" -> RuntimeEvent.Gap(value.number("afterSeq"), value.number("throughSeq"), GapReason(value.at("reason").text()))
|
|
48
|
+
"cleared" -> RuntimeEvent.Cleared(value.number("seq"), value.at("id").text(), at())
|
|
49
|
+
"turn" -> RuntimeEvent.Turn(value.number("seq"), value.at("id").text(), value.strings("causedBy"), value.strings("inputs"), value.at("purpose").text(),
|
|
50
|
+
value.get("usage")?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet()?.associate { it.key to it.value.asLong } ?: emptyMap(),
|
|
51
|
+
value.get("costUsd")?.asDouble ?: 0.0, CostStatus(value.at("costStatus").text()), value.at("model").text(), value.optionalLong("imagesOmitted")?.toInt(), at())
|
|
52
|
+
"app" -> value.getAsJsonObject("source").let { RuntimeEvent.App(value.number("seq"), value.at("id").text(), value.at("name").text(), value.get("data").deepCopy(),
|
|
53
|
+
ToolSource(it.at("command").text(), it.at("callId").text()), at()) }
|
|
54
|
+
"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())
|
|
55
|
+
else RuntimeEvent.StreamError(value.at("code").text(), value.at("message").text(), value.flag("poisoned"))
|
|
56
|
+
"replaced" -> RuntimeEvent.Replaced
|
|
57
|
+
else -> RuntimeEvent.Unknown(type, value.deepCopy())
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
package dev.croche
|
|
2
|
+
|
|
3
|
+
import dev.croche.ffi.*
|
|
4
|
+
import java.lang.ref.WeakReference
|
|
5
|
+
import java.lang.reflect.InvocationTargetException
|
|
6
|
+
import java.lang.reflect.Method
|
|
7
|
+
import java.lang.reflect.Proxy
|
|
8
|
+
|
|
9
|
+
/** Pointer ownership only. UniFFI's call counter keeps already-entered foreign calls alive during destroy. */
|
|
10
|
+
internal object NativeHandleOwner {
|
|
11
|
+
private class Key(value: Any) : WeakReference<Any>(value) {
|
|
12
|
+
private val hash = System.identityHashCode(value)
|
|
13
|
+
override fun hashCode() = hash
|
|
14
|
+
override fun equals(other: Any?): Boolean {
|
|
15
|
+
if (this === other) return true
|
|
16
|
+
val value = get() ?: return false
|
|
17
|
+
return other is Key && value === other.get()
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
private val scopes = mutableMapOf<Key, WeakReference<Scope>>()
|
|
21
|
+
private fun scope(raw: Any): Scope = synchronized(scopes) {
|
|
22
|
+
scopes.entries.removeAll { it.key.get() == null || it.value.get() == null }
|
|
23
|
+
val key = Key(raw)
|
|
24
|
+
scopes[key]?.get() ?: Scope(raw).also { scopes[key] = WeakReference(it) }
|
|
25
|
+
}
|
|
26
|
+
fun <T : Any> wrap(type: Class<T>, raw: T): T {
|
|
27
|
+
val owner = scope(raw)
|
|
28
|
+
return type.cast(Proxy.newProxyInstance(type.classLoader, arrayOf(type)) { proxy, method, args ->
|
|
29
|
+
when (method.name) {
|
|
30
|
+
"equals" -> proxy === args?.firstOrNull()
|
|
31
|
+
"hashCode" -> System.identityHashCode(proxy)
|
|
32
|
+
"toString" -> "Core owner"
|
|
33
|
+
"shutdown" -> owner.shutdown(method)
|
|
34
|
+
else -> owner.invoke(method, args ?: emptyArray())
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
private fun closed() = CrocheError("closed", "This handle is closed.", ErrorCategory.CLOSED)
|
|
39
|
+
private class Scope(private var raw: Any?) {
|
|
40
|
+
private val lock = Object()
|
|
41
|
+
private val children = mutableSetOf<Scope>()
|
|
42
|
+
private val snapshot = mutableMapOf<String, Any?>()
|
|
43
|
+
private var closing = false
|
|
44
|
+
private var disposed = when (val value = raw) {
|
|
45
|
+
is CoreAgent -> value.uniffiIsDestroyed
|
|
46
|
+
is CoreCroche -> value.uniffiIsDestroyed
|
|
47
|
+
is CoreSubscription -> value.uniffiIsDestroyed
|
|
48
|
+
else -> false
|
|
49
|
+
}
|
|
50
|
+
init { if (disposed) raw = null }
|
|
51
|
+
private fun capture(value: Any) {
|
|
52
|
+
if (value !is CoreAgentInterface) return
|
|
53
|
+
for (key in listOf("id", "instance")) try {
|
|
54
|
+
snapshot[key] = CoreAgentInterface::class.java.getMethod(key).invoke(value)
|
|
55
|
+
} catch (_: Exception) { /* recovery */ }
|
|
56
|
+
}
|
|
57
|
+
fun invoke(method: Method, args: Array<out Any?>): Any? {
|
|
58
|
+
val value = synchronized(lock) {
|
|
59
|
+
if (disposed || closing) {
|
|
60
|
+
if (method.name == "ended") return true
|
|
61
|
+
if (snapshot.containsKey(method.name)) return snapshot[method.name]
|
|
62
|
+
throw closed()
|
|
63
|
+
}
|
|
64
|
+
raw ?: throw closed()
|
|
65
|
+
}
|
|
66
|
+
return try {
|
|
67
|
+
val result = method.invoke(value, *args)
|
|
68
|
+
if (result is CoreAgent || result is CoreSubscription) {
|
|
69
|
+
val child = scope(result)
|
|
70
|
+
synchronized(lock) { if (disposed) child.release() else children.add(child) }
|
|
71
|
+
}
|
|
72
|
+
result
|
|
73
|
+
} catch (error: InvocationTargetException) {
|
|
74
|
+
val cause = error.targetException
|
|
75
|
+
if (cause is IllegalStateException && synchronized(lock) { disposed || closing }) throw closed()
|
|
76
|
+
throw cause
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
fun shutdown(method: Method) {
|
|
80
|
+
val value = synchronized(lock) {
|
|
81
|
+
while (closing) lock.wait()
|
|
82
|
+
if (disposed) return
|
|
83
|
+
val value = raw ?: return
|
|
84
|
+
capture(value); closing = true; value
|
|
85
|
+
}
|
|
86
|
+
var succeeded = false
|
|
87
|
+
try { method.invoke(value); succeeded = true }
|
|
88
|
+
catch (error: InvocationTargetException) { throw error.targetException }
|
|
89
|
+
finally {
|
|
90
|
+
val disposal = synchronized(lock) {
|
|
91
|
+
closing = false
|
|
92
|
+
val disposal = if (succeeded) take() else null
|
|
93
|
+
lock.notifyAll(); disposal
|
|
94
|
+
}
|
|
95
|
+
disposal?.let { destroy(it) }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
private fun take(): Pair<Any, List<Scope>>? {
|
|
99
|
+
if (disposed) return null
|
|
100
|
+
val value = raw ?: return null
|
|
101
|
+
capture(value); disposed = true; raw = null
|
|
102
|
+
val nested = children.toList(); children.clear()
|
|
103
|
+
return value to nested
|
|
104
|
+
}
|
|
105
|
+
private fun destroy(disposal: Pair<Any, List<Scope>>) {
|
|
106
|
+
disposal.second.forEach { it.release() }
|
|
107
|
+
(disposal.first as? Disposable)?.destroy()
|
|
108
|
+
}
|
|
109
|
+
fun release() {
|
|
110
|
+
val disposal = synchronized(lock) {
|
|
111
|
+
// An already-running shutdown owns its final drop; never free it early.
|
|
112
|
+
if (closing) return
|
|
113
|
+
take()
|
|
114
|
+
}
|
|
115
|
+
disposal?.let { destroy(it) }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|