@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
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import com.google.gson.JsonArray
|
|
4
|
-
import dev.croche.ffi.CoreProject
|
|
5
|
-
import dev.croche.ffi.CoreRuntime
|
|
6
|
-
import dev.croche.ffi.HostPal
|
|
7
|
-
import dev.croche.ffi.HostPalFactory
|
|
8
|
-
import java.util.concurrent.ConcurrentHashMap
|
|
9
|
-
import java.util.concurrent.CopyOnWriteArrayList
|
|
10
|
-
|
|
11
|
-
/** Same lifetime rule as RN AgentPals: a fresh host each time Core asks, including record/GC PALs. */
|
|
12
|
-
internal class ProjectPals(private val makeHost: (String) -> KotlinHost) : HostPalFactory {
|
|
13
|
-
private val all = CopyOnWriteArrayList<KotlinHost>()
|
|
14
|
-
private val agents = ConcurrentHashMap<String, KotlinHost>()
|
|
15
|
-
override fun pal(agent: String): HostPal {
|
|
16
|
-
keepAttached()
|
|
17
|
-
return makeHost(agent).also {
|
|
18
|
-
all.add(it)
|
|
19
|
-
if (!projectPalRoute(agent).maintenance) agents[agent] = it
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
internal val cachedAgentSlots: Set<String> get() = agents.keys.toSet()
|
|
23
|
-
fun host(core: CoreRuntime): KotlinHost = agents[slot(core)]
|
|
24
|
-
?: throw CrocheException("core_error", "Core opened an agent without requesting its host")
|
|
25
|
-
fun release() {
|
|
26
|
-
all.forEach { it.deliver = null; it.stop(); it.release() }
|
|
27
|
-
all.clear(); agents.clear()
|
|
28
|
-
}
|
|
29
|
-
companion object {
|
|
30
|
-
fun slot(core: CoreRuntime): String = core.instance()?.let { instance ->
|
|
31
|
-
JsonArray().apply { add(core.agentId()); add(instance) }.toString()
|
|
32
|
-
} ?: core.agentId()
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Core admission runs even for a cached wrapper, to validate overrides and instance identity. */
|
|
37
|
-
internal class ProjectBinding(private val core: CoreProject, private val pals: ProjectPals) {
|
|
38
|
-
private val agents = linkedMapOf<String, Pair<CoreRuntime, CrocheRuntime>>()
|
|
39
|
-
@Volatile private var closed = false
|
|
40
|
-
val agentIds: List<String> get() = call { core.agentIds() }
|
|
41
|
-
val user: String? get() = call { core.user() }
|
|
42
|
-
val installationId: String? get() = call { core.installationId() }
|
|
43
|
-
@Volatile private var cachedUserId: String? = null
|
|
44
|
-
val crocheUserId: String? get() = call { core.crocheUserId() }.also { if (it != null) cachedUserId = it }
|
|
45
|
-
/** Final paid-call usage can arrive while shutdown runs, after public getters are closed. */
|
|
46
|
-
internal val usageUserId: String? get() = try { core.crocheUserId() ?: cachedUserId }
|
|
47
|
-
catch (_: Exception) { cachedUserId }
|
|
48
|
-
private fun <T> call(body: () -> T): T {
|
|
49
|
-
if (closed) throw CrocheException("closed", "The project is closed")
|
|
50
|
-
return try { body() } catch (error: Exception) { throw crocheError(error) }
|
|
51
|
-
}
|
|
52
|
-
@Synchronized fun agent(id: String?, options: String): Pair<CoreRuntime, CrocheRuntime> = call {
|
|
53
|
-
val opened = core.agentWithOptions(id, options, null)
|
|
54
|
-
try {
|
|
55
|
-
core.crocheUserId()?.let { cachedUserId = it }
|
|
56
|
-
val slot = ProjectPals.slot(opened)
|
|
57
|
-
val existing = agents[slot]
|
|
58
|
-
if (existing != null && !existing.second.isClosed) {
|
|
59
|
-
opened.destroy()
|
|
60
|
-
return@call existing
|
|
61
|
-
}
|
|
62
|
-
val runtime = CrocheRuntime.adopt(opened, pals.host(opened))
|
|
63
|
-
(opened to runtime).also { agents[slot] = it }
|
|
64
|
-
} catch (error: Exception) { if (!opened.uniffiIsDestroyed) opened.destroy(); throw error }
|
|
65
|
-
}
|
|
66
|
-
fun close() {
|
|
67
|
-
synchronized(this) { if (closed) return; closed = true }
|
|
68
|
-
try { core.shutdown() }
|
|
69
|
-
catch (error: Exception) { throw crocheError(error) }
|
|
70
|
-
finally {
|
|
71
|
-
try {
|
|
72
|
-
var failed: Exception? = null
|
|
73
|
-
agents.values.forEach { try { it.second.close() } catch (error: Exception) { if (failed == null) failed = error } }
|
|
74
|
-
failed?.let { throw it }
|
|
75
|
-
}
|
|
76
|
-
finally { agents.clear(); core.destroy(); pals.release() }
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
package dev.croche
|
|
2
|
-
|
|
3
|
-
import java.io.File
|
|
4
|
-
import java.util.Locale
|
|
5
|
-
|
|
6
|
-
/** Android is discovered through its existing provider; the JVM artifact has no Android dependency. */
|
|
7
|
-
internal data class ProjectPlatform(
|
|
8
|
-
val directory: File,
|
|
9
|
-
val secretStorage: (String) -> RuntimeSecretStore,
|
|
10
|
-
val attestor: RuntimeAttestor?,
|
|
11
|
-
)
|
|
12
|
-
internal fun projectDeviceLanguage(): String = try {
|
|
13
|
-
Class.forName("dev.croche.android.CrocheProjectRecordProvider")
|
|
14
|
-
.getMethod("language").invoke(null) as String
|
|
15
|
-
} catch (_: ClassNotFoundException) { Locale.getDefault().toLanguageTag() }
|
|
16
|
-
|
|
17
|
-
internal fun projectPlatform(options: OpenOptions): ProjectPlatform {
|
|
18
|
-
val android = try { Class.forName("dev.croche.android.CrocheProjectRecordProvider") }
|
|
19
|
-
catch (_: ClassNotFoundException) { null }
|
|
20
|
-
val default = defaultProjectDirectory()
|
|
21
|
-
val directory = projectRecordDirectory(options.projectDirectory, default)
|
|
22
|
-
?: throw CrocheException("storage_error", "Croche.open requires projectDirectory on this platform")
|
|
23
|
-
if (android == null) return ProjectPlatform(directory,
|
|
24
|
-
{ name -> FileRuntimeSecretStore(File(directory, "$name.secrets")) }, null)
|
|
25
|
-
val attestor = if (options.attestation != Attestation.OFF) options.android?.cloudProjectNumber?.let { number ->
|
|
26
|
-
android.getMethod("attestor", java.lang.Long.TYPE).invoke(null, number) as RuntimeAttestor
|
|
27
|
-
} else null
|
|
28
|
-
return ProjectPlatform(File(directory, "croche"), { name ->
|
|
29
|
-
android.getMethod("secretStorage", String::class.java).invoke(null, name) as RuntimeSecretStore
|
|
30
|
-
}, attestor)
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
internal fun OpenOptions.hostJson(attestor: RuntimeAttestor?) = com.google.gson.JsonObject().apply {
|
|
34
|
-
cloudUrl?.let { addProperty("cloudUrl", it) }; addProperty("projectKey", projectKey)
|
|
35
|
-
debugKey?.let { addProperty("debugKey", it) }
|
|
36
|
-
requestTimeoutMs?.let { addProperty("requestTimeoutMs", it) }
|
|
37
|
-
maxPendingEvents?.let { addProperty("maxPendingEvents", it) }
|
|
38
|
-
syncIntervalMs?.let { addProperty("syncIntervalMs", it) }
|
|
39
|
-
maintenanceBackoffMs?.let { addProperty("maintenanceBackoffMs", it) }
|
|
40
|
-
retentionBytes?.let { addProperty("retentionBytes", it) }
|
|
41
|
-
debugVisibility?.let { addProperty("debugVisibility", "runtime") }
|
|
42
|
-
attestor?.let { addProperty("attestationPlatform", it.platform) }
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
internal fun OpenOptions.owned(): OpenOptions = copy(config = config.deepCopy(), handlers = handlers.toMap(),
|
|
46
|
-
language = language ?: projectDeviceLanguage())
|
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import Foundation
|
|
2
|
-
|
|
3
|
-
public typealias ControlSend = @Sendable (_ input: JSON, _ cancellation: RuntimeCancellation) async throws -> JSON
|
|
4
|
-
public typealias ControlCancel = @Sendable () async -> Bool
|
|
5
|
-
|
|
6
|
-
/// Opt-in attachment of an existing Runtime. This broker token is unrelated to Cloud
|
|
7
|
-
/// developer/project credentials. No Runtime identity or storage is opened here.
|
|
8
|
-
public actor RuntimeControl {
|
|
9
|
-
public nonisolated let runtimeInstanceId: String
|
|
10
|
-
public nonisolated let capabilities = ["status", "history", "send", "cancel", "sync", "budget.get", "budget.set", "tools"]
|
|
11
|
-
private let runtime: CrocheRuntime
|
|
12
|
-
private let url: String
|
|
13
|
-
private let token: String
|
|
14
|
-
private let clientId = UUID().uuidString
|
|
15
|
-
private let http: RuntimeHTTP
|
|
16
|
-
private let sendAdapter: ControlSend?
|
|
17
|
-
private let cancelAdapter: ControlCancel?
|
|
18
|
-
private let onError: (@Sendable (CrocheError) -> Void)?
|
|
19
|
-
private let lifetime = RuntimeCancellation()
|
|
20
|
-
private var loop: Task<Void, Never>?
|
|
21
|
-
private var closed = false
|
|
22
|
-
private var handled = Set<String>()
|
|
23
|
-
private var results: [String: JSON] = [:]
|
|
24
|
-
private var active: [String: RuntimeCancellation] = [:]
|
|
25
|
-
private var tasks: [String: Task<Void, Never>] = [:]
|
|
26
|
-
|
|
27
|
-
private init(runtime: CrocheRuntime, runtimeInstanceId: String, url: String, token: String,
|
|
28
|
-
http: @escaping RuntimeHTTP, send: ControlSend?, cancel: ControlCancel?,
|
|
29
|
-
onError: (@Sendable (CrocheError) -> Void)?) {
|
|
30
|
-
self.runtime = runtime; self.runtimeInstanceId = runtimeInstanceId; self.url = url; self.token = token
|
|
31
|
-
self.http = http; sendAdapter = send; cancelAdapter = cancel; self.onError = onError
|
|
32
|
-
}
|
|
33
|
-
public static func attach(runtime: CrocheRuntime, url: String = "http://127.0.0.1:8791", token: String,
|
|
34
|
-
http: @escaping RuntimeHTTP = { try await RuntimeURLSession.send($0, cancellation: $1, onDelta: $2) },
|
|
35
|
-
send: ControlSend? = nil, cancel: ControlCancel? = nil,
|
|
36
|
-
onError: (@Sendable (CrocheError) -> Void)? = nil) async throws -> RuntimeControl {
|
|
37
|
-
guard let parsed = URLComponents(string: url), parsed.scheme == "http",
|
|
38
|
-
["localhost", "127.0.0.1", "[::1]", "::1"].contains(parsed.host ?? ""),
|
|
39
|
-
parsed.user == nil, parsed.password == nil, parsed.query == nil, parsed.fragment == nil,
|
|
40
|
-
parsed.path.isEmpty || parsed.path == "/",
|
|
41
|
-
token.range(of: "^[A-Za-z0-9._~-]{24,4096}$", options: .regularExpression) != nil else {
|
|
42
|
-
throw CrocheError("invalid_configuration", "Control requires a loopback HTTP origin and explicit local token")
|
|
43
|
-
}
|
|
44
|
-
let status = try await runtime.inspect()["status"]
|
|
45
|
-
let id = status["runtimeInstanceId"].string ?? ""
|
|
46
|
-
guard validControlId(id) else { throw CrocheError("invalid_configuration", "Invalid Runtime identity") }
|
|
47
|
-
let control = RuntimeControl(runtime: runtime, runtimeInstanceId: id,
|
|
48
|
-
url: url.hasSuffix("/") ? String(url.dropLast()) : url, token: token,
|
|
49
|
-
http: http, send: send, cancel: cancel, onError: onError)
|
|
50
|
-
try await control.start(status)
|
|
51
|
-
return control
|
|
52
|
-
}
|
|
53
|
-
private var identity: [String: JSON] { ["client_id": .string(clientId), "runtime_instance_id": .string(runtimeInstanceId)] }
|
|
54
|
-
private func register(_ status: JSON) async throws {
|
|
55
|
-
_ = try await post("register", .object(["client_id": .string(clientId), "runtime": status,
|
|
56
|
-
"capabilities": .array(capabilities.map(JSON.string))]))
|
|
57
|
-
}
|
|
58
|
-
private func start(_ status: JSON) async throws {
|
|
59
|
-
try await register(status)
|
|
60
|
-
loop = Task { [weak self] in
|
|
61
|
-
while !Task.isCancelled {
|
|
62
|
-
guard let keep = await self?.tick(), keep else { break }
|
|
63
|
-
do { try await Task.sleep(nanoseconds: 100_000_000) } catch { break }
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
private func post(_ path: String, _ body: JSON) async throws -> JSON {
|
|
68
|
-
guard try body.encoded().count <= 1024 * 1024 else { throw CrocheError("control_capacity", "Control request exceeds 1MiB") }
|
|
69
|
-
let effect = JSON.object(["url": .string(url + "/v1/control/" + path), "method": .string("POST"),
|
|
70
|
-
"headers": .object(["Authorization": .string("Bearer " + token), "Content-Type": .string("application/json")]),
|
|
71
|
-
"body": body, "timeoutMs": .number(5000)])
|
|
72
|
-
let transport = http
|
|
73
|
-
let response = try await boundedEffect(milliseconds: 5000, cancellation: lifetime) { signal in try await transport(effect, signal) { _ in } }
|
|
74
|
-
let data = response["body"]
|
|
75
|
-
guard data.object != nil, try data.encoded().count <= 1024 * 1024 else { throw CrocheError("invalid_response", "Invalid bounded control response") }
|
|
76
|
-
guard let status = response["status"].number, (200..<300).contains(status) else {
|
|
77
|
-
throw CrocheError(data["error"]["code"].string ?? "control_error", "Local control broker rejected the request")
|
|
78
|
-
}
|
|
79
|
-
return data
|
|
80
|
-
}
|
|
81
|
-
private func tick() async -> Bool {
|
|
82
|
-
if closed { return false }
|
|
83
|
-
do {
|
|
84
|
-
for (id, result) in Array(results.prefix(8)) {
|
|
85
|
-
do { _ = try await post("results", result); results.removeValue(forKey: id) }
|
|
86
|
-
catch let error as CrocheError {
|
|
87
|
-
if ["not_found", "attachment_lost"].contains(error.code) { results.removeValue(forKey: id) }
|
|
88
|
-
throw error
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
if results.count < 32 && tasks.count < 16 {
|
|
92
|
-
let response = try await post("poll", .object(identity))
|
|
93
|
-
guard let commands = response["commands"].array else { throw CrocheError("invalid_response", "Broker command list is invalid") }
|
|
94
|
-
for command in commands.prefix(8) { try accept(command) }
|
|
95
|
-
}
|
|
96
|
-
} catch {
|
|
97
|
-
if !closed {
|
|
98
|
-
let issue = error as? CrocheError ?? CrocheError("control_error", "Local control failed")
|
|
99
|
-
onError?(issue)
|
|
100
|
-
if issue.code == "attachment_lost" {
|
|
101
|
-
do { try await register(runtime.inspect()["status"]) } catch {}
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
return !closed
|
|
106
|
-
}
|
|
107
|
-
private func accept(_ value: JSON) throws {
|
|
108
|
-
let id = value["request_id"].string ?? "", command = value["command"].string ?? ""
|
|
109
|
-
guard validControlId(id), capabilities.contains(command), let payload = value["payload"].object else {
|
|
110
|
-
throw CrocheError("invalid_command", "Invalid control command envelope")
|
|
111
|
-
}
|
|
112
|
-
if handled.contains(id) { return }
|
|
113
|
-
guard handled.count < 1000 else { throw CrocheError("control_capacity", "Reattach after 1000 control requests") }
|
|
114
|
-
handled.insert(id)
|
|
115
|
-
tasks[id] = Task { await self.perform(id, command, .object(payload)) }
|
|
116
|
-
}
|
|
117
|
-
private func perform(_ id: String, _ command: String, _ payload: JSON) async {
|
|
118
|
-
var response = identity; response["request_id"] = .string(id)
|
|
119
|
-
do {
|
|
120
|
-
let result = try await execute(command, payload, id)
|
|
121
|
-
guard try result.encoded().count <= 900_000 else { throw CrocheError("result_too_large", "Request a smaller result page") }
|
|
122
|
-
response["result"] = result
|
|
123
|
-
} catch {
|
|
124
|
-
response["error"] = .object(["code": .string(publicControlCode(error)),
|
|
125
|
-
"message": .string("The Runtime command failed. Inspect it before retrying."),
|
|
126
|
-
"uncertain": .bool(command == "send" || command == "budget.set")])
|
|
127
|
-
}
|
|
128
|
-
if !closed { results[id] = .object(response) }
|
|
129
|
-
tasks.removeValue(forKey: id)
|
|
130
|
-
}
|
|
131
|
-
private func execute(_ command: String, _ payload: JSON, _ id: String) async throws -> JSON {
|
|
132
|
-
guard !closed else { throw CrocheError("control_closed", "Control is closed") }
|
|
133
|
-
let keys = Set(payload.object!.keys)
|
|
134
|
-
if command == "send" {
|
|
135
|
-
guard keys.isSubset(of: ["id", "text"]), validControlId(payload["id"].string ?? ""),
|
|
136
|
-
let text = payload["text"].string, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
|
137
|
-
text.utf16.count <= 32000 else { throw CrocheError("invalid_command", "send needs immutable id and text only") }
|
|
138
|
-
let signal = RuntimeCancellation(); active[id] = signal; defer { active.removeValue(forKey: id) }
|
|
139
|
-
if let sendAdapter { return try await sendAdapter(payload, signal) }
|
|
140
|
-
let task = Task { try await runtime.send(payload) }
|
|
141
|
-
let listener = signal.observe { task.cancel() }; defer { signal.remove(listener) }
|
|
142
|
-
return try await task.value
|
|
143
|
-
}
|
|
144
|
-
if command == "history" {
|
|
145
|
-
guard keys.isSubset(of: ["offset", "limit"]) else { throw CrocheError("invalid_command", "Unsupported history fields") }
|
|
146
|
-
guard (!keys.contains("offset") || payload["offset"].number != nil), (!keys.contains("limit") || payload["limit"].number != nil) else { throw CrocheError("invalid_command", "History page values must be numbers") }
|
|
147
|
-
let offset = payload["offset"].number ?? 0, limit = payload["limit"].number ?? 100
|
|
148
|
-
guard offset.isFinite, offset >= 0, offset <= Double(Int.max / 2), offset.rounded() == offset,
|
|
149
|
-
limit >= 1, limit <= 200, limit.rounded() == limit else { throw CrocheError("invalid_command", "Invalid history page") }
|
|
150
|
-
let history = try await runtime.inspect()["history"].array ?? []
|
|
151
|
-
return .object(["messages": .array(Array(history.dropFirst(Int(offset)).prefix(Int(limit)))),
|
|
152
|
-
"total": .number(Double(history.count)), "offset": .number(offset), "limit": .number(limit)])
|
|
153
|
-
}
|
|
154
|
-
if command == "budget.set" {
|
|
155
|
-
guard keys == ["amount"], let amount = payload["amount"].number, amount.isFinite, amount >= 0 else {
|
|
156
|
-
throw CrocheError("invalid_command", "Budget needs a non-negative finite amount")
|
|
157
|
-
}
|
|
158
|
-
return try await runtime.adjustBudget(amount, absolute: true)
|
|
159
|
-
}
|
|
160
|
-
guard keys.isEmpty else { throw CrocheError("invalid_command", "Unsupported command fields") }
|
|
161
|
-
if command == "cancel" {
|
|
162
|
-
let hadActive = !active.isEmpty; for signal in active.values { signal.cancel() }
|
|
163
|
-
let host = await cancelAdapter?() ?? false
|
|
164
|
-
return .object(["requested": .bool(hadActive || host), "scope": .string(cancelAdapter == nil ? "control_client" : "host"), "rollback": .bool(false)])
|
|
165
|
-
}
|
|
166
|
-
if command == "sync" { _ = try await runtime.sync() }
|
|
167
|
-
let view = try await runtime.inspect()
|
|
168
|
-
switch command {
|
|
169
|
-
case "status":
|
|
170
|
-
var status = view["status"]; status["control"] = .object(["cancellation_scope": .string(cancelAdapter == nil ? "control_client" : "host")]); return status
|
|
171
|
-
case "sync": return view["status"]
|
|
172
|
-
case "tools": return view["tools"]
|
|
173
|
-
case "budget.get": return view["budget"]
|
|
174
|
-
default: throw CrocheError("unsupported_capability", "Unsupported Runtime command")
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
public func close() async {
|
|
178
|
-
if closed { return }; closed = true
|
|
179
|
-
for signal in active.values { signal.cancel() }
|
|
180
|
-
// Transport stays alive for unregister; closing attachment never closes Runtime.
|
|
181
|
-
_ = try? await post("unregister", .object(identity))
|
|
182
|
-
lifetime.cancel(); loop?.cancel(); await loop?.value; loop = nil
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
private func validControlId(_ value: String) -> Bool {
|
|
186
|
-
value.range(of: "^[A-Za-z0-9_.:-]{1,200}$", options: .regularExpression) != nil
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
private func publicControlCode(_ error: Error) -> String {
|
|
190
|
-
let code = (error as? CrocheError)?.code ?? "runtime_error"
|
|
191
|
-
return ["invalid_command", "control_closed", "unsupported_capability", "result_too_large", "busy", "closed", "storage_error", "context_limit", "budget_limit"].contains(code) ? code : "runtime_error"
|
|
192
|
-
}
|