@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,73 @@
|
|
|
1
|
+
package dev.croche.android.pal
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.security.keystore.KeyGenParameterSpec
|
|
5
|
+
import android.security.keystore.KeyProperties
|
|
6
|
+
import android.system.Os
|
|
7
|
+
import android.system.OsConstants
|
|
8
|
+
import dev.croche.ffi.CoreStoragePal
|
|
9
|
+
import dev.croche.ffi.PalLockOutcome
|
|
10
|
+
import dev.croche.s7.storageCallback
|
|
11
|
+
import dev.croche.s7.pal.AtomicKeyFiles
|
|
12
|
+
import java.io.File
|
|
13
|
+
import java.security.KeyStore
|
|
14
|
+
import java.util.Base64
|
|
15
|
+
import javax.crypto.Cipher
|
|
16
|
+
import javax.crypto.KeyGenerator
|
|
17
|
+
import javax.crypto.SecretKey
|
|
18
|
+
import javax.crypto.spec.GCMParameterSpec
|
|
19
|
+
|
|
20
|
+
/** S2 ordinary values and secrets have separate no-backup roots. No JSON/snapshot fallback. */
|
|
21
|
+
internal class AndroidStoragePal(context: Context) : CoreStoragePal {
|
|
22
|
+
private val root = File(context.noBackupFilesDir, "croche-pal-v1")
|
|
23
|
+
private val values = AtomicKeyFiles(File(root, "state"), ::syncDirectory)
|
|
24
|
+
private val secrets = AtomicKeyFiles(File(root, "secrets"), ::syncDirectory)
|
|
25
|
+
override fun read(key: String) = storageCallback { values.read(key) }
|
|
26
|
+
override fun write(key: String, value: String) = storageCallback {
|
|
27
|
+
values.write(key, value)
|
|
28
|
+
}
|
|
29
|
+
override fun remove(key: String) = storageCallback { values.remove(key) }
|
|
30
|
+
override fun list(prefix: String) = storageCallback { values.list(prefix) }
|
|
31
|
+
override fun lock(name: String): PalLockOutcome = storageCallback {
|
|
32
|
+
if (values.lock(name)) PalLockOutcome.ACQUIRED else PalLockOutcome.HELD
|
|
33
|
+
}
|
|
34
|
+
override fun unlock(name: String) = storageCallback { values.unlock(name) }
|
|
35
|
+
override fun removeSecret(key: String) = storageCallback { secrets.remove(key) }
|
|
36
|
+
override fun readSecret(key: String): String? = secretOperation {
|
|
37
|
+
val encoded = secrets.read(key) ?: return@secretOperation null
|
|
38
|
+
val bytes = Base64.getDecoder().decode(encoded)
|
|
39
|
+
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
|
40
|
+
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, bytes, 0, 12))
|
|
41
|
+
cipher.updateAAD(key.toByteArray(Charsets.UTF_8))
|
|
42
|
+
String(cipher.doFinal(bytes, 12, bytes.size - 12), Charsets.UTF_8)
|
|
43
|
+
}
|
|
44
|
+
override fun writeSecret(key: String, value: String) = secretOperation {
|
|
45
|
+
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
|
46
|
+
cipher.init(Cipher.ENCRYPT_MODE, secretKey())
|
|
47
|
+
cipher.updateAAD(key.toByteArray(Charsets.UTF_8))
|
|
48
|
+
secrets.write(key, Base64.getEncoder().encodeToString(cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8))))
|
|
49
|
+
}
|
|
50
|
+
@Synchronized private fun secretKey(): SecretKey {
|
|
51
|
+
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
|
52
|
+
(store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
|
53
|
+
if (!secrets.lock("keystore-key")) throw java.io.IOException("Keystore key creation is held by another process")
|
|
54
|
+
try {
|
|
55
|
+
// Another process may have created the alias while we acquired the OS lock.
|
|
56
|
+
(store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
|
57
|
+
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").run {
|
|
58
|
+
init(KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
|
59
|
+
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
|
60
|
+
.setKeySize(256).build())
|
|
61
|
+
generateKey()
|
|
62
|
+
}
|
|
63
|
+
} finally { secrets.unlock("keystore-key") }
|
|
64
|
+
}
|
|
65
|
+
private inline fun <T> secretOperation(block: () -> T): T = storageCallback(block)
|
|
66
|
+
private companion object { const val ALIAS = "croche.pal.v1.secrets" }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
internal fun syncDirectory(directory: File) {
|
|
70
|
+
// O_RDONLY is public Android API; fsync still checkpoints the directory entry changes.
|
|
71
|
+
val fd = Os.open(directory.path, OsConstants.O_RDONLY, 0)
|
|
72
|
+
try { Os.fsync(fd) } finally { Os.close(fd) }
|
|
73
|
+
}
|
|
@@ -7,3 +7,12 @@
|
|
|
7
7
|
|
|
8
8
|
# The JVM host discovers Android's app-private project location through this startup hook.
|
|
9
9
|
-keep class dev.croche.android.CrocheProjectRecordProvider { public static java.io.File directory(); public static java.lang.String language(); public static dev.croche.RuntimeSecretStore secretStorage(java.lang.String); public static dev.croche.RuntimeAttestor attestor(long); }
|
|
10
|
+
|
|
11
|
+
# The SDK finds Android's image codecs by name (Class.forName), so R8 must keep them and their
|
|
12
|
+
# no-argument constructors.
|
|
13
|
+
-keep class dev.croche.android.BitmapPalCodec { public <init>(); }
|
|
14
|
+
-keep class dev.croche.android.BitmapDecodedImageCodec { public <init>(); }
|
|
15
|
+
-keep class dev.croche.android.BitmapImageCodec { public <init>(); }
|
|
16
|
+
|
|
17
|
+
# Common Kotlin facade loads the Android-only PAL provider by name.
|
|
18
|
+
-keep class dev.croche.android.pal.AndroidPublicPlatform { public <init>(); *; }
|
|
@@ -70,7 +70,9 @@ internal class AppStreamBranch {
|
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
private val eventJson = GsonBuilder().disableHtmlEscaping().
|
|
73
|
+
private val eventJson = GsonBuilder().disableHtmlEscaping().registerTypeHierarchyAdapter(ReaderString::class.java,
|
|
74
|
+
com.google.gson.JsonSerializer<ReaderString> { value, _, _ -> com.google.gson.JsonPrimitive(value.value) }
|
|
75
|
+
).registerTypeAdapter(Instant::class.java, object : TypeAdapter<Instant>() {
|
|
74
76
|
override fun write(out: JsonWriter, value: Instant?) { if (value == null) out.nullValue() else out.value(value.toString()) }
|
|
75
77
|
override fun read(input: JsonReader): Instant = Instant.parse(input.nextString())
|
|
76
78
|
}).create()
|
|
@@ -83,12 +85,13 @@ internal fun RuntimeEvent.owned(): RuntimeEvent = when (this) {
|
|
|
83
85
|
is RuntimeEvent.Turn -> copy(causedBy = causedBy.toList(), inputs = inputs.toList(), usage = usage.toMap())
|
|
84
86
|
is RuntimeEvent.Error -> copy(inputs = inputs.toList())
|
|
85
87
|
is RuntimeEvent.Page -> copy(messages = messages.map { it.owned() })
|
|
88
|
+
is RuntimeEvent.Unknown -> copy(fields = fields.deepCopy())
|
|
86
89
|
else -> this
|
|
87
90
|
}
|
|
88
91
|
|
|
89
92
|
/** Tagged delivery payload, UTF-8 bytes including event structure as in S2's queue. */
|
|
90
93
|
internal fun RuntimeEvent.serialized(): String {
|
|
91
|
-
val json = eventJson.toJsonTree(this).asJsonObject
|
|
94
|
+
val json = if (this is RuntimeEvent.Unknown) fields.deepCopy() else eventJson.toJsonTree(this).asJsonObject
|
|
92
95
|
val type = when (this) {
|
|
93
96
|
is RuntimeEvent.Input -> "input"
|
|
94
97
|
is RuntimeEvent.MessageStart -> "message.start"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
package dev.croche
|
|
2
|
+
|
|
3
|
+
/** The binding facts Core reports to Cloud with each Runtime (docs/RUNTIME-CLOUD-PROTOCOL.md):
|
|
4
|
+
* `{sdk, sdk_version, platform}`, passed beside the open JSON, never an OpenOptions member. They are
|
|
5
|
+
* diagnostic and carry no logic; Core adds its own runtime_version. */
|
|
6
|
+
internal object BindingFacts {
|
|
7
|
+
/** This package's version. scripts/release-version.mjs sets it with every other SDK version, and
|
|
8
|
+
* its --check refuses a value that differs from sdk/kotlin/build.gradle.kts. */
|
|
9
|
+
const val SDK_VERSION = "0.6.0"
|
|
10
|
+
val platform: String get() =
|
|
11
|
+
if (System.getProperty("java.vm.name") == "Dalvik") "android" else platformOf(System.getProperty("os.name"))
|
|
12
|
+
|
|
13
|
+
/** A JVM OS name as Core's label (1-40 of `[a-z0-9-]`, starting with a letter): the three known
|
|
14
|
+
* names, otherwise the lowercased name itself ("FreeBSD" -> "freebsd", "SunOS" -> "sunos"), and
|
|
15
|
+
* "unknown" when no label can be made. Never "server": an unlisted OS is not guessed. */
|
|
16
|
+
internal fun platformOf(osName: String?): String {
|
|
17
|
+
val os = osName.orEmpty().lowercase()
|
|
18
|
+
return when {
|
|
19
|
+
os.startsWith("mac") -> "macos"
|
|
20
|
+
os.startsWith("windows") -> "windows"
|
|
21
|
+
os.startsWith("linux") -> "linux"
|
|
22
|
+
else -> os.replace(Regex("[^a-z0-9]+"), "-").trim('-').take(40).trimEnd('-')
|
|
23
|
+
.takeIf { it.isNotEmpty() && it[0] in 'a'..'z' } ?: "unknown"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** `sdk` is "kotlin", or "react-native" from the RN Android bridge, which builds these sources. */
|
|
27
|
+
fun json(sdk: String = "kotlin"): String =
|
|
28
|
+
obj("sdk" to str(sdk), "sdk_version" to str(SDK_VERSION), "platform" to str(platform)).toString()
|
|
29
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
package dev.croche
|
|
2
|
+
|
|
3
|
+
import com.google.gson.JsonObject
|
|
4
|
+
|
|
5
|
+
/** Schema-6 context settings. Core owns defaults and validation. */
|
|
6
|
+
data class ContextConfig(
|
|
7
|
+
/** Target average input tokens per model call, 1..16_777_216. */
|
|
8
|
+
val turnTokens: Int? = null,
|
|
9
|
+
/** 0..0.5, default 0.25; controls memory inclusion; zero disables it. Ignored when memory is disabled. */
|
|
10
|
+
val memoryShare: Double? = null,
|
|
11
|
+
/** Hard input-token cap per model call, independent of the model's own window, 1..16_777_216. */
|
|
12
|
+
val maxTokens: Int? = null,
|
|
13
|
+
) {
|
|
14
|
+
fun toJson(): JsonObject = JsonObject().apply {
|
|
15
|
+
turnTokens?.let { addProperty("turnTokens", it) }
|
|
16
|
+
memoryShare?.let { addProperty("memoryShare", it) }
|
|
17
|
+
maxTokens?.let { addProperty("maxTokens", it) }
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Input size contracts (`limits`), in UTF-16 code units ([String.length]). An input over one
|
|
22
|
+
* fails with `input_too_large` and is never truncated; [Croche.truncate] cuts text to fit.
|
|
23
|
+
* Core owns defaults and validation. */
|
|
24
|
+
data class LimitsConfig(
|
|
25
|
+
/** Total user and app-event text of one send, 1_000..200_000 (default 32_000). */
|
|
26
|
+
val userTextChars: Int? = null,
|
|
27
|
+
/** Total app-state text of one send, 1_000..200_000 (default 32_000). */
|
|
28
|
+
val appStateChars: Int? = null,
|
|
29
|
+
/** One tool result's value as compact JSON, 1_000..1_000_000 (default 200_000). Over it, the turn fails. */
|
|
30
|
+
val toolResultChars: Int? = null,
|
|
31
|
+
) {
|
|
32
|
+
fun toJson(): JsonObject = JsonObject().apply {
|
|
33
|
+
userTextChars?.let { addProperty("userTextChars", it) }
|
|
34
|
+
appStateChars?.let { addProperty("appStateChars", it) }
|
|
35
|
+
toolResultChars?.let { addProperty("toolResultChars", it) }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Application memory settings. Core owns defaults and validation. */
|
|
40
|
+
data class MemoryConfig(val enabled: Boolean? = null, val policy: String? = null) {
|
|
41
|
+
fun toJson(): JsonObject = JsonObject().apply {
|
|
42
|
+
enabled?.let { addProperty("enabled", it) }
|
|
43
|
+
policy?.let { addProperty("policy", it) }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -2,7 +2,22 @@ package dev.croche
|
|
|
2
2
|
|
|
3
3
|
import com.google.gson.*
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
/** The ONE closed set (APP-API), generated from Core's contract (R6: one ErrorCategory per binding). */
|
|
6
|
+
typealias ErrorCategory = AppStreamContract.ErrorCategory
|
|
7
|
+
|
|
8
|
+
/** Core supplies code, category and path; the wrapper does not classify errors. */
|
|
9
|
+
class CrocheError internal constructor(val code: String, override val message: String,
|
|
10
|
+
val category: ErrorCategory, val path: String? = null, val retryAfter: ULong? = null) : Exception(message) {
|
|
11
|
+
// Only the retained legacy implementation calls this constructor; S1 uses the full envelope.
|
|
12
|
+
internal constructor(code: String, message: String) : this(code, message, ErrorCategory.INTERNAL, null)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Known agent error codes; other Core and host codes reach [CrocheError.code] verbatim. */
|
|
16
|
+
object CrocheErrorCode {
|
|
17
|
+
/** The id is open with another configuration or parent, or already holds a child's data. */
|
|
18
|
+
const val AGENT_CONFLICT = "agent_conflict"
|
|
19
|
+
const val INVALID_CONFIGURATION = "invalid_configuration"
|
|
20
|
+
}
|
|
6
21
|
|
|
7
22
|
internal fun obj(vararg fields: Pair<String, JsonElement>): JsonObject = JsonObject().apply { fields.forEach { add(it.first, it.second) } }
|
|
8
23
|
internal fun str(value: String): JsonElement = JsonPrimitive(value)
|
|
@@ -1,120 +1,75 @@
|
|
|
1
1
|
package dev.croche
|
|
2
2
|
|
|
3
3
|
import com.google.gson.*
|
|
4
|
-
import dev.croche.ffi
|
|
5
|
-
import dev.croche.
|
|
6
|
-
import kotlinx.coroutines.Dispatchers
|
|
7
|
-
import kotlinx.coroutines.withContext
|
|
8
|
-
import kotlinx.coroutines.sync.Mutex
|
|
9
|
-
import kotlinx.coroutines.sync.withLock
|
|
10
|
-
import java.io.File
|
|
4
|
+
import dev.croche.ffi.*
|
|
5
|
+
import dev.croche.s7.*
|
|
11
6
|
|
|
12
|
-
/**
|
|
13
|
-
class Croche
|
|
14
|
-
private val
|
|
15
|
-
|
|
16
|
-
val
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
suspend fun
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}
|
|
7
|
+
/** One Core owner; no wrapper agent registry, resolved config or admission decisions. */
|
|
8
|
+
class Croche internal constructor(private val core: CoreCrocheInterface, private val pals: NativePlatformPals,
|
|
9
|
+
private val lifecycle: LifecycleBinding = GeneratedLifecycleBinding) {
|
|
10
|
+
suspend fun runTool(name: String, args: JsonObject, id: String): RunToolResult = dev.croche.runTool(core, name, args, id)
|
|
11
|
+
val agentIds: List<String> get() = publicSync { core.agentIds() }
|
|
12
|
+
suspend fun agent(id: String, options: AgentOptions? = null): CrocheAgent = publicCall {
|
|
13
|
+
CrocheAgent(core.agent(id, options?.json()?.toString()), pals.eventDispatcher)
|
|
14
|
+
}
|
|
15
|
+
suspend fun deliverDue(): DueDelivery = publicCall { cancel -> PublicResults.delivery(core.deliverDue(null, cancel)) }
|
|
16
|
+
val wiki = Wiki()
|
|
17
|
+
inner class Wiki internal constructor() {
|
|
18
|
+
suspend fun put(doc: WikiDoc) { publicCall { core.wikiPut(doc.json().toString()) } }
|
|
19
|
+
suspend fun remove(path: String) { publicCall { core.wikiRemove(path) } }
|
|
20
|
+
suspend fun list(): List<WikiDoc> = publicCall { PublicResults.wiki(core.wikiList()) }
|
|
21
|
+
}
|
|
22
|
+
val debugger = Debugger()
|
|
23
|
+
inner class Debugger internal constructor() {
|
|
24
|
+
suspend fun attach(options: DebugAttachOptions): AttachedDebugger = publicCall {
|
|
25
|
+
PublicResults.debug(core.debugAttach(options.json().toString()))
|
|
32
26
|
}
|
|
27
|
+
suspend fun detach() { publicCall { core.debugDetach() } }
|
|
33
28
|
}
|
|
34
|
-
|
|
35
|
-
|
|
29
|
+
/** Local data only. Omitted/empty scope deletes declared stores, registered instances and tool runtime.
|
|
30
|
+
* Agent selects its main and named instances; agent + instance selects one. Core validates all scopes.
|
|
31
|
+
* Other users, the install record and undeclared legacy main stores remain. Recovery accepts only empty scope.
|
|
32
|
+
* The handle stays open. Core owns closure of in-scope agents, locks and retryable partial progress. */
|
|
33
|
+
suspend fun deleteData(scope: DeleteDataOptions? = null) {
|
|
34
|
+
publicCall { lifecycle.deleteData(core, scope?.json()?.toString()) }
|
|
36
35
|
}
|
|
36
|
+
suspend fun close() { publicCall { core.shutdown() } }
|
|
37
|
+
|
|
37
38
|
companion object {
|
|
38
|
-
suspend fun open(options: OpenOptions): Croche
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
try {
|
|
54
|
-
val core = CoreProject.open(pals,
|
|
55
|
-
ProjectOpenOptions(owned.hostJson(platform.attestor).toString(), owned.user,
|
|
56
|
-
owned.config.toString(), owned.handlers.keys.toList(), owned.language,
|
|
57
|
-
owned.streaming ?: true, owned.backgroundSync ?: true,
|
|
58
|
-
(owned.maintenanceIntervalMs ?: 60_000).toDouble()),
|
|
59
|
-
owned.onUsage?.let { EventHook(::usage) },
|
|
60
|
-
owned.onDebugEvent?.let { callback -> EventHook { event -> try { callback(event.asJsonObject) } catch (_: Throwable) {} } })
|
|
61
|
-
val bound = ProjectBinding(core, pals)
|
|
62
|
-
synchronized(lock) { binding = bound; pending.forEach { notifyUsage(owned, bound, it) }; pending.clear() }
|
|
63
|
-
Croche(bound).also { created = it; ProjectOpenSeam.opened?.invoke(it) }
|
|
64
|
-
} catch (error: Exception) { pals.release(); throw crocheError(error) }
|
|
65
|
-
} } catch (cancelled: kotlinx.coroutines.CancellationException) {
|
|
66
|
-
// IO's cancellable return must not strand a project the caller never received.
|
|
67
|
-
withContext(kotlinx.coroutines.NonCancellable) { created?.close() }
|
|
68
|
-
throw cancelled
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
suspend fun deleteStore(options: OpenOptions, agent: String? = null) {
|
|
72
|
-
val owned = options.copy(config = options.config.deepCopy(), handlers = emptyMap(),
|
|
73
|
-
backgroundSync = false, attestation = Attestation.OFF)
|
|
74
|
-
projectIO {
|
|
75
|
-
val platform = projectPlatform(owned)
|
|
76
|
-
val pals = factory(owned, platform)
|
|
77
|
-
try { dev.croche.ffi.deleteStore(pals, owned.hostJson(null).toString(), owned.user, owned.config.toString(), agent) }
|
|
78
|
-
finally { pals.release() }
|
|
39
|
+
suspend fun open(options: OpenOptions): Croche = opening(options, null)
|
|
40
|
+
/** Only deleteData and close work on a recovery handle. Core rejects malformed recovery modes. */
|
|
41
|
+
suspend fun open(options: OpenOptions, recovery: RecoveryOptions): Croche = opening(options, recovery)
|
|
42
|
+
private suspend fun opening(options: OpenOptions, recovery: RecoveryOptions?): Croche =
|
|
43
|
+
openBound(options, recovery, nativePlatform(options.platform, options.storage), GeneratedLifecycleBinding)
|
|
44
|
+
|
|
45
|
+
/** Immutable binding seam for transport tests; production always uses the generated native binding. */
|
|
46
|
+
internal suspend fun openBound(options: OpenOptions, recovery: RecoveryOptions?, pals: NativePlatformPals,
|
|
47
|
+
lifecycle: LifecycleBinding): Croche {
|
|
48
|
+
val encoded = CoreOptionsEncoding.encode(options.json(), options.tools?.map { it.registration() },
|
|
49
|
+
pals.storage, options.storage?.let { pals.storage })
|
|
50
|
+
return publicCall(discard = { abandoned: Croche -> abandoned.core.shutdown() }) {
|
|
51
|
+
val owner = lifecycle.open(encoded.optionsJson, encoded.registrations, attached(encoded.storage),
|
|
52
|
+
attached(pals.host), BindingFacts.json(), recovery?.json()?.toString())
|
|
53
|
+
Croche(owner, pals, lifecycle)
|
|
79
54
|
}
|
|
80
55
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
event.add("crocheUserId", binding.usageUserId?.let(::JsonPrimitive) ?: JsonNull.INSTANCE)
|
|
86
|
-
options.onUsage?.invoke(event)
|
|
87
|
-
} catch (_: Throwable) { /* observers cannot break Core */ }
|
|
56
|
+
suspend fun wakeTimes(options: OpenOptions, query: WakeQuery? = null): WakeTimes {
|
|
57
|
+
val pals = nativePlatform(options.platform, options.storage)
|
|
58
|
+
val encoded = CoreOptionsEncoding.encode(options.json(), options.tools?.map { it.registration() }, pals.storage, options.storage?.let { pals.storage })
|
|
59
|
+
return publicCall { PublicResults.wakes(coreWakeTimes(encoded.optionsJson, query?.json()?.toString(), attached(encoded.storage), attached(pals.host))) }
|
|
88
60
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
val
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
KotlinHost(FileRuntimeStorage(File(platform.directory, "$safe.json")), platform.secretStorage(safe),
|
|
97
|
-
platform.attestor, options.http ?: RuntimeHttpURLConnection(), options.handlers.mapValues { (_, handler) ->
|
|
98
|
-
ToolHandler { invocation, context ->
|
|
99
|
-
try { handler.execute(invocation, context) }
|
|
100
|
-
catch (error: Throwable) {
|
|
101
|
-
if (error is CrocheException && error.code == "invalid_tool_result") throw error
|
|
102
|
-
throw CrocheException("effect_failed", "The application tool failed")
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
},
|
|
106
|
-
options.backgroundSync ?: true, projectDirectory = options.projectDirectory,
|
|
107
|
-
user = options.user, timeZone = zone)
|
|
61
|
+
/** Android supplies its Context at startup; no SDK enrollment list or wake policy. */
|
|
62
|
+
fun registerBackground(context: Any, options: BackgroundOptions? = null) {
|
|
63
|
+
val pals = nativePlatform(context, options?.storage)
|
|
64
|
+
val listener = options?.sink?.let { backgroundSink(pals.eventDispatcher, it) }
|
|
65
|
+
val encoded = JsonObject().apply {
|
|
66
|
+
listener?.let { add("sink", JsonNull.INSTANCE) }
|
|
67
|
+
options?.storage?.let { add("storage", JsonNull.INSTANCE) }
|
|
108
68
|
}
|
|
69
|
+
publicSync { coreRegisterBackground(encoded.toString(), attached(listener), attached(pals.storage), attached(pals.platformStorage), attached(pals.host), BindingFacts.json()) }
|
|
70
|
+
}
|
|
71
|
+
internal fun truncate(text: String, max: Int): String = publicSync {
|
|
72
|
+
dev.croche.ffi.truncate(text, max.toDouble())
|
|
109
73
|
}
|
|
110
74
|
}
|
|
111
75
|
}
|
|
112
|
-
|
|
113
|
-
internal suspend fun <T> projectIO(body: () -> T): T = withContext(Dispatchers.IO) {
|
|
114
|
-
try { body() } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } catch (error: Exception) { throw crocheError(error) }
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** Host-only race gate at IO's cancellable return; never set by an app. */
|
|
118
|
-
internal object ProjectOpenSeam { @Volatile var opened: ((Croche) -> Unit)? = null }
|
|
119
|
-
|
|
120
|
-
internal object ProjectUsageSeam { @Volatile var beforeObserver: (() -> Unit)? = null }
|
|
@@ -1,116 +1,56 @@
|
|
|
1
1
|
package dev.croche
|
|
2
2
|
|
|
3
3
|
import com.google.gson.*
|
|
4
|
-
import dev.croche.ffi
|
|
5
|
-
import
|
|
6
|
-
import
|
|
4
|
+
import dev.croche.ffi.*
|
|
5
|
+
import dev.croche.s7.*
|
|
6
|
+
import kotlinx.coroutines.CoroutineDispatcher
|
|
7
7
|
|
|
8
|
-
/**
|
|
9
|
-
class CrocheAgent
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
suspend fun setTools(
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
33
|
-
suspend fun
|
|
34
|
-
suspend fun sync() { projectIO { native { core.sync() } } }
|
|
35
|
-
suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt {
|
|
36
|
-
requireOpen(); return runtime.send(input, options)
|
|
37
|
-
}
|
|
38
|
-
suspend fun request(input: SendInput, options: RequestOptions = RequestOptions()): RequestResult {
|
|
39
|
-
requireOpen()
|
|
40
|
-
return runtime.request(input, SendOptions(options.responseFormat), options.wait).also { memory.refreshQuietly() }
|
|
41
|
-
}
|
|
42
|
-
fun subscribe(options: SubscribeOptions): AgentSubscription {
|
|
43
|
-
// Opening synchronously preserves replacement order and an immediate history call's generation.
|
|
44
|
-
val collection = runtime.openSubscription(options.initialMessages ?: if (options.after == null) 50 else null, options.after)
|
|
45
|
-
return AgentSubscription(collection, options.onEvent, callbacks)
|
|
46
|
-
}
|
|
47
|
-
suspend fun history(options: HistoryOptions) { requireOpen(); runtime.history(options.before, options.limit) }
|
|
48
|
-
suspend fun clearHistory() { requireOpen(); runtime.clearHistory(); memory.refreshQuietly() }
|
|
49
|
-
suspend fun cancel(id: String? = null) {
|
|
50
|
-
requireOpen()
|
|
51
|
-
if (id != null) runtime.cancel(id) else projectIO { native { core.cancelTurn() } }
|
|
52
|
-
}
|
|
53
|
-
suspend fun close() {
|
|
54
|
-
lifecycle.lock()
|
|
55
|
-
try {
|
|
56
|
-
if (!retired.compareAndSet(false, true)) return
|
|
57
|
-
projectIO { runtime.close() }
|
|
58
|
-
} finally { lifecycle.unlock() }
|
|
59
|
-
}
|
|
8
|
+
/** All identity, accepted work and scope live in Core. Every operation calls that same handle. */
|
|
9
|
+
class CrocheAgent internal constructor(internal val core: CoreAgentInterface, private val dispatcher: CoroutineDispatcher) {
|
|
10
|
+
val id: String get() = publicSync { core.id() }
|
|
11
|
+
val instance: String? get() = publicSync { core.instance() }
|
|
12
|
+
suspend fun send(text: String, options: SendOptions? = null): SendReceipt = sendJson(JsonPrimitive(text).toString(), emptyList(), options)
|
|
13
|
+
suspend fun send(input: SendInput, options: SendOptions? = null): SendReceipt =
|
|
14
|
+
sendJson(input.encoded().toString(), input.imageCaptures().map { CoreImageInput(it.first.toUInt(), it.second) }, options)
|
|
15
|
+
private suspend fun sendJson(input: String, images: List<CoreImageInput>, options: SendOptions?): SendReceipt = publicCall { token ->
|
|
16
|
+
AppStreamContract.decodeSendReceipt(JsonParser.parseString(core.send(input, images, sendOptions(options), token)).asJsonObject)
|
|
17
|
+
}
|
|
18
|
+
suspend fun request(text: String, options: RequestOptions? = null): RequestResult = requestJson(JsonPrimitive(text).toString(), emptyList(), options)
|
|
19
|
+
suspend fun request(input: SendInput, options: RequestOptions? = null): RequestResult =
|
|
20
|
+
requestJson(input.encoded().toString(), input.imageCaptures().map { CoreImageInput(it.first.toUInt(), it.second) }, options)
|
|
21
|
+
private suspend fun requestJson(input: String, images: List<CoreImageInput>, options: RequestOptions?): RequestResult = publicCall { token ->
|
|
22
|
+
AppStreamContract.decodeRequestResult(JsonParser.parseString(core.request(input, images, options?.json()?.toString(), token)).asJsonObject)
|
|
23
|
+
}
|
|
24
|
+
fun subscribe(options: SubscribeOptions): AgentSubscription = publicSync {
|
|
25
|
+
AgentSubscription(core.subscribe(options.json().toString(), attached(appEventSink(dispatcher, options.onEvent))))
|
|
26
|
+
}
|
|
27
|
+
suspend fun cancel(id: String? = null) { publicCall { core.cancel(id) } }
|
|
28
|
+
suspend fun clearHistory() { publicCall { core.clearHistory() } }
|
|
29
|
+
suspend fun setTools(scope: ToolSelection) { publicCall { core.setTools(scope.json().toString()) } }
|
|
30
|
+
suspend fun resetTools() { publicCall { core.resetTools() } }
|
|
31
|
+
suspend fun setWiki(scope: WikiSelection) { publicCall { core.setWiki(scope.json().toString()) } }
|
|
32
|
+
suspend fun resetWiki() { publicCall { core.resetWiki() } }
|
|
33
|
+
suspend fun close() { publicCall { core.shutdown() } }
|
|
60
34
|
val memory = Memory()
|
|
61
|
-
inner class Memory {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
if (!deferred) refreshQuietly()
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
internal suspend fun refreshQuietly() {
|
|
73
|
-
if (closed) return
|
|
74
|
-
try { snapshot = projectIO { runtime.memory().asJsonObject.deepCopy() } } catch (_: CrocheException) {}
|
|
75
|
-
}
|
|
76
|
-
suspend fun list(): JsonArray = operation { runtime.memory.list() }
|
|
77
|
-
suspend fun delete(id: String): JsonObject = operation { runtime.memory.delete(id) }
|
|
78
|
-
suspend fun clear(): JsonObject = operation { runtime.memory.clear() }
|
|
79
|
-
suspend fun enabled(on: Boolean): WriteResult<Boolean> = operation { runtime.memory.enabled(on) }
|
|
80
|
-
suspend fun export(): JsonObject = operation { runtime.memory.export() }
|
|
81
|
-
fun onChanged(listener: ((MemoryChangedEvent) -> Unit)?) {
|
|
82
|
-
requireOpen()
|
|
83
|
-
try { runtime.memory.onChanged(listener?.let { callback -> { value -> try { callback(value.asJsonObject) } catch (_: Throwable) {} } }) }
|
|
84
|
-
catch (error: Exception) { throw crocheError(error) }
|
|
85
|
-
}
|
|
35
|
+
inner class Memory internal constructor() {
|
|
36
|
+
suspend fun list(): List<MemoryItem> = publicCall { PublicResults.memories(core.memoryList()) }
|
|
37
|
+
suspend fun delete(id: String) { publicCall { core.memoryDelete(id) } }
|
|
38
|
+
suspend fun clear() { publicCall { core.memoryClear() } }
|
|
39
|
+
suspend fun enabled(on: Boolean) { publicCall { core.memoryEnabled(on) } }
|
|
40
|
+
}
|
|
41
|
+
private fun sendOptions(options: SendOptions?): String? = options?.let {
|
|
42
|
+
JsonObject().apply { it.responseFormat?.let { add("responseFormat", it.deepCopy()) } }.toString()
|
|
86
43
|
}
|
|
87
|
-
internal companion object { fun adopt(core: CoreRuntime, runtime: CrocheRuntime) = CrocheAgent(core, runtime) }
|
|
88
44
|
}
|
|
45
|
+
/** `send`'s answer: Core has ACCEPTED the input. `error` is set when the input already failed. */
|
|
46
|
+
typealias SendReceipt = AppStreamContract.SendReceipt
|
|
47
|
+
/** `request`'s answer: the input is final. `gap` is true when Core says so, null when absent. */
|
|
48
|
+
typealias RequestResult = AppStreamContract.RequestResult
|
|
49
|
+
/** `{code, category, message}` on a failed receipt, result, input or message. */
|
|
50
|
+
typealias EventError = AppStreamContract.EventError
|
|
89
51
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
scope: CoroutineScope,
|
|
95
|
-
) {
|
|
96
|
-
private val completion = CompletableDeferred<AppStreamEnd>()
|
|
97
|
-
val ended: Deferred<AppStreamEnd> get() = completion
|
|
98
|
-
init {
|
|
99
|
-
scope.launch {
|
|
100
|
-
var code = "closed"
|
|
101
|
-
try {
|
|
102
|
-
collection.deliver { event ->
|
|
103
|
-
if (event is RuntimeEvent.StreamError) code = event.code
|
|
104
|
-
if (event === RuntimeEvent.Replaced) code = "replaced"
|
|
105
|
-
onEvent(event)
|
|
106
|
-
}
|
|
107
|
-
} catch (failure: Throwable) {
|
|
108
|
-
code = "handler_failed"
|
|
109
|
-
collection.close()
|
|
110
|
-
try { onEvent(RuntimeEvent.StreamError(code, "Event handler failed", false)) } catch (_: Throwable) {}
|
|
111
|
-
} finally { completion.complete(AppStreamEnd(code)) }
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
fun close() = collection.close()
|
|
115
|
-
suspend fun history(options: HistoryOptions) = collection.history(options.before, options.limit)
|
|
52
|
+
class AgentSubscription internal constructor(private val core: CoreSubscriptionInterface) {
|
|
53
|
+
suspend fun history(options: HistoryOptions) { publicCall { core.history(options.json().toString()) } }
|
|
54
|
+
fun close() = publicSync { core.shutdown() }
|
|
55
|
+
val ended: Boolean get() = publicSync { core.ended() }
|
|
116
56
|
}
|