@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
|
@@ -1,34 +1,31 @@
|
|
|
1
1
|
package dev.croche
|
|
2
2
|
|
|
3
|
-
import com.google.gson
|
|
4
|
-
import dev.croche.ffi.CancelToken
|
|
5
|
-
import dev.croche.s7.attached
|
|
6
|
-
import dev.croche.ffi.CoreRuntime
|
|
7
|
-
import dev.croche.ffi.PendingSend
|
|
8
|
-
import dev.croche.ffi.RuntimeOpenOptions
|
|
9
|
-
import kotlin.coroutines.suspendCoroutine
|
|
10
|
-
import java.io.File
|
|
3
|
+
import com.google.gson.JsonObject
|
|
11
4
|
|
|
12
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Command invocation parsed and validated by Core.
|
|
7
|
+
*
|
|
8
|
+
* @property args Arguments selected for the invoked command.
|
|
9
|
+
* @property command Command name within the tool, when supplied.
|
|
10
|
+
* @property key Command key used to dispatch the invocation.
|
|
11
|
+
* @property tool Name of the invoked tool.
|
|
12
|
+
*/
|
|
13
13
|
data class CommandInvocation(val tool: String, val command: String?, val key: String, val args: JsonObject)
|
|
14
|
-
data class LegacyToolContext(val callId: String, val messageId: String, val userId: String, val cancellation: RuntimeCancellation,
|
|
15
|
-
/** Present when the Runtime config has an agentId. Last, with a default, so existing destructuring is unchanged. */
|
|
16
|
-
val agentId: String? = null,
|
|
17
|
-
/** Where a [withResult] handler leaves its images for this call (set by the Runtime). */
|
|
18
|
-
val images: ToolImages? = null,
|
|
19
|
-
val user: String? = null,
|
|
20
|
-
val causedBy: List<String> = emptyList(), val origin: String = "app")
|
|
21
|
-
fun interface ToolHandler { fun execute(invocation: CommandInvocation, context: LegacyToolContext): JsonElement }
|
|
22
14
|
|
|
23
|
-
/** One wiki document: a path such as `menu/stew.md` and its markdown (at most
|
|
24
|
-
*
|
|
15
|
+
/** One wiki document: a path such as `menu/stew.md` and its markdown (at most
|
|
16
|
+
* `wikiDocumentMaxBytes`, default 64 KiB; `wikiMaxBytes` in all, default 8 MiB; Core checks both,
|
|
17
|
+
* and the number of documents is not limited). The title is the first `#` heading; optional frontmatter may set
|
|
25
18
|
* `summary`, `keywords` and `agents` (only those agents see the document); `agents` given here
|
|
26
19
|
* overrides the frontmatter's. An agent's own path globs are config: `"wiki": {"include": [...],
|
|
27
|
-
* "exclude": [...]}`.
|
|
20
|
+
* "exclude": [...]}`.
|
|
21
|
+
*
|
|
22
|
+
* @property agents Optional list of agents to which the document is scoped. Overrides the frontmatter's agent list when set.
|
|
23
|
+
* @property markdown Contents of the document as Markdown.
|
|
24
|
+
* @property path Path relative to the wiki root, using forward slashes.
|
|
25
|
+
*/
|
|
28
26
|
data class WikiDocument(val path: String, val markdown: String, val agents: List<String>? = null) {
|
|
27
|
+
/** Load Markdown documents from a directory or a tree provided by the app. */
|
|
29
28
|
companion object {
|
|
30
|
-
private const val MAX_DOCUMENTS = 2000
|
|
31
|
-
|
|
32
29
|
/** The `.md` files under `dir`, paths relative to it with `/` (`menu/stew.md`), in name
|
|
33
30
|
* order. Subfolders are read; symbolic links and other files are skipped, as the other
|
|
34
31
|
* SDKs' loaders do. */
|
|
@@ -63,7 +60,6 @@ data class WikiDocument(val path: String, val markdown: String, val agents: List
|
|
|
63
60
|
if (!children.isNullOrEmpty()) walk(path)
|
|
64
61
|
else if (name.endsWith(".md")) {
|
|
65
62
|
val markdown = read(path) ?: continue
|
|
66
|
-
if (out.size >= MAX_DOCUMENTS) throw CrocheError("invalid_wiki", "The wiki holds at most $MAX_DOCUMENTS documents")
|
|
67
63
|
out.add(WikiDocument(path, markdown))
|
|
68
64
|
}
|
|
69
65
|
}
|
|
@@ -74,343 +70,6 @@ data class WikiDocument(val path: String, val markdown: String, val agents: List
|
|
|
74
70
|
}
|
|
75
71
|
}
|
|
76
72
|
|
|
77
|
-
/** The Croche Runtime for Kotlin. The Rust Core (crates/croche-ffi) is the Runtime: it holds
|
|
78
|
-
* the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
|
|
79
|
-
* Kotlin types; `KotlinHost` performs what only the platform can (the PAL).
|
|
80
|
-
* Blocking: call from an IO executor/coroutine, never Android's main thread. Methods return
|
|
81
|
-
* detached JSON values. */
|
|
82
|
-
internal class LegacyAgentEngine private constructor(private val nativeCore: CoreRuntime?, private val nativeHost: KotlinHost?,
|
|
83
|
-
private val subscription: StreamHub? = null, private val subscriptionPort: CoreStreamPort? = null) : AutoCloseable {
|
|
84
|
-
private val core: CoreRuntime get() = checkNotNull(nativeCore) { "Legacy API requires native Core" }
|
|
85
|
-
internal val host: KotlinHost get() = checkNotNull(nativeHost) { "Legacy host requires native Core" }
|
|
86
|
-
/** Fake-port host seam; create() installs NativeCoreStreamPort. */
|
|
87
|
-
internal constructor(port: CoreStreamPort) : this(null, null, StreamHub(port), port)
|
|
88
|
-
internal val boundStreamPort: CoreStreamPort get() = checkNotNull(subscriptionPort)
|
|
89
|
-
private fun subscriptions(): StreamHub = subscription ?: throw CrocheError(
|
|
90
|
-
"invalid_configuration", "Subscription binding is not installed")
|
|
91
|
-
/** String shorthand is one user text element; identity and admission belong to Core. */
|
|
92
|
-
suspend fun send(text: String, options: SendOptions = SendOptions()): Receipt =
|
|
93
|
-
send(SendInput(input = listOf(TextInput(text, AppStreamContract.InputKind.USER))), options)
|
|
94
|
-
suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt = subscriptions().send(input, options)
|
|
95
|
-
fun events(initialMessages: Int = 50): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(initialMessages)
|
|
96
|
-
fun events(after: Cursor): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(null, after)
|
|
97
|
-
suspend fun request(input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = null): LegacyRequestResult = subscriptions().request(input, options, wait)
|
|
98
|
-
suspend fun cancel(id: String) { subscriptions().cancel(id) }
|
|
99
|
-
suspend fun history(before: Long? = null, limit: Int) { subscriptions().history(before, limit) }
|
|
100
|
-
val logId: String get() = subscriptions().logId
|
|
101
|
-
internal val state: RuntimeEvent.State get() = subscriptions().state
|
|
102
|
-
@Volatile private var closed = false
|
|
103
|
-
internal val isClosed: Boolean get() = closed
|
|
104
|
-
internal fun openSubscription(initial: Int?, after: Cursor?) = subscriptions().openCollection(initial, after)
|
|
105
|
-
@Volatile private var onDelivery: ((JsonElement) -> Unit)? = null
|
|
106
|
-
companion object {
|
|
107
|
-
/** Test-only gate-10 probe; called on the thread that invokes each native stream-port call. */
|
|
108
|
-
@Volatile internal var offloadStarting: (() -> Unit)? = null
|
|
109
|
-
|
|
110
|
-
/** `secrets` keeps the Runtime credential apart from `storage`: KeystoreSecretStore on
|
|
111
|
-
* Android. `attestor` proves the genuine app to Cloud when the project requires it:
|
|
112
|
-
* PlayIntegrityAttestor on a device; null on an emulator or a host that cannot attest.
|
|
113
|
-
* Events may be delivered on an effect worker thread while a reply streams.
|
|
114
|
-
* `libraryName` names the native Runtime library (libcroche_ffi by default).
|
|
115
|
-
* `wiki` is the documents, set at open; this agent's path filter is the config's
|
|
116
|
-
* `"wiki": {"include": [...], "exclude": [...]}`.
|
|
117
|
-
* `onEvent` hears one `turn.started` per turn; a send carried into a running turn at a
|
|
118
|
-
* later model call is `{type:"turn.joined", turnId, inputIds}` (the ids newly carried).
|
|
119
|
-
* `onUsage` receives every paid call's cost (`{type:"usage", operationId, purpose, causedBy, instance,
|
|
120
|
-
* model, costUsd, costStatus, tokens?}`; `tokens` holds the reported counts, e.g. `prompt`,
|
|
121
|
-
* `cached`); `instance` is the named/generated instance key, or null for the main agent.
|
|
122
|
-
* `model` is the gateway-reported answering model (`modelSource: "response"`), or the
|
|
123
|
-
* request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
|
|
124
|
-
* present only when different. Reported cost is unchanged by a model substitution.
|
|
125
|
-
* `routedFor: "images"` and `routedFrom` mark a call whose images the app's (else the
|
|
126
|
-
* project's) model does not accept, sent to an image-capable project model instead.
|
|
127
|
-
* At least once, from the start: open itself reports a call
|
|
128
|
-
* the process died during. It runs on a Runtime thread; do not call the Runtime from it.
|
|
129
|
-
* `scheduler` registers the agent's scheduled notes with the OS for when the app is not
|
|
130
|
-
* running: `WorkManagerScheduler` on Android; null on a JVM host, where an in-process
|
|
131
|
-
* timer delivers them while it runs and the next open delivers what fell due meanwhile.
|
|
132
|
-
* A scheduler whose name another open Runtime holds refuses this one (`scheduler_conflict`).
|
|
133
|
-
* `projectDirectory` is required on a plain JVM and refused on Android, which always uses
|
|
134
|
-
* app-private filesDir. It is a host option, never part of the Core config. */
|
|
135
|
-
fun create(config: JsonObject, storage: RuntimeStorage, secrets: RuntimeSecretStore,
|
|
136
|
-
attestor: RuntimeAttestor? = null, tools: Map<String, ToolHandler> = emptyMap(),
|
|
137
|
-
http: RuntimeHTTP = RuntimeHttpURLConnection(), onEvent: ((JsonElement) -> Unit)? = null,
|
|
138
|
-
onDebugEvent: ((JsonElement) -> Unit)? = null, libraryName: String = LIBRARY,
|
|
139
|
-
backgroundSync: Boolean = true, maintenanceIntervalMs: Long = 60_000,
|
|
140
|
-
wiki: List<WikiDocument>? = null, onUsage: ((JsonElement) -> Unit)? = null,
|
|
141
|
-
scheduler: RuntimeScheduler? = null, projectDirectory: File? = null): LegacyAgentEngine {
|
|
142
|
-
useLibrary(libraryName)
|
|
143
|
-
val bound = config.deepCopy().apply {
|
|
144
|
-
if (attestor != null) addProperty("attestationPlatform", attestor.platform) else add("attestationPlatform", JsonNull.INSTANCE)
|
|
145
|
-
}
|
|
146
|
-
// This host can feed deltas, so it asks for a stream unless the app opted out.
|
|
147
|
-
val streaming = config.at("streaming").let { if (it.isJsonPrimitive && it.asJsonPrimitive.isBoolean) it.asBoolean else true }
|
|
148
|
-
scheduler?.attach()
|
|
149
|
-
// From here the host's stop (close, or a failed open) detaches the scheduler.
|
|
150
|
-
val host = KotlinHost(storage, secrets, attestor, http, tools.toMap(), backgroundSync, scheduler, projectDirectory)
|
|
151
|
-
// The app chose the store, so the Runtime binds its identity to it (a custom storage key).
|
|
152
|
-
val options = RuntimeOpenOptions("croche.kotlin", streaming, backgroundSync, maintenanceInterval(maintenanceIntervalMs).toDouble())
|
|
153
|
-
val core = try { CoreRuntime.open(attached(host), bound.toString(), options, onEvent?.let { EventHook(it) }, onUsage?.let { EventHook(it) }) }
|
|
154
|
-
catch (error: Exception) { host.release(); throw crocheError(error) }
|
|
155
|
-
if (onDebugEvent != null) try { core.setDebugObserver(EventHook(onDebugEvent), false) } catch (_: Exception) {}
|
|
156
|
-
val runtime = adopt(core, host)
|
|
157
|
-
if (wiki != null) try { runtime.wiki.set(wiki) } catch (error: Exception) { runtime.close(); throw error }
|
|
158
|
-
return runtime
|
|
159
|
-
}
|
|
160
|
-
/** Adopts a project-owned Runtime through the same production stream boundary as create. */
|
|
161
|
-
internal fun adopt(core: CoreRuntime, host: KotlinHost): LegacyAgentEngine {
|
|
162
|
-
val port = NativeCoreStreamPort(core, host)
|
|
163
|
-
val hub = try { StreamHub(port) } catch (error: Exception) { port.close(); throw crocheError(error) }
|
|
164
|
-
val runtime = LegacyAgentEngine(core, host, hub, port)
|
|
165
|
-
val weak = java.lang.ref.WeakReference(runtime)
|
|
166
|
-
host.deliver = { weak.get()?.deliverDue(); Unit }
|
|
167
|
-
host.attach(core)
|
|
168
|
-
return runtime
|
|
169
|
-
}
|
|
170
|
-
fun identity(config: JsonObject, libraryName: String = LIBRARY): JsonElement {
|
|
171
|
-
useLibrary(libraryName)
|
|
172
|
-
return try { JsonParser.parseString(dev.croche.ffi.identity(config.toString())) } catch (error: Exception) { throw crocheError(error) }
|
|
173
|
-
}
|
|
174
|
-
private const val LIBRARY = "croche_ffi"
|
|
175
|
-
private fun useLibrary(name: String) {
|
|
176
|
-
if (name != LIBRARY) System.setProperty("uniffi.component.croche_ffi.libraryOverride", name)
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
private fun run(body: (CoreRuntime) -> String?): JsonElement {
|
|
180
|
-
if (closed) throw CrocheError("closed", "Runtime is closed")
|
|
181
|
-
return try { body(core)?.let { JsonParser.parseString(it) } ?: JsonNull.INSTANCE } catch (error: Exception) { throw crocheError(error) }
|
|
182
|
-
}
|
|
183
|
-
/** Runs one turn. `cancellation` cancels this turn only, from any thread; one fired before
|
|
184
|
-
* the send starts throws `cancelled` here, and one fired while it runs is never missed.
|
|
185
|
-
* `responseFormat`: structured output, OpenAI's shape (`{"type":"json_schema",...}` or
|
|
186
|
-
* `{"type":"json_object"}`); the result's `output` is the reply as JSON the Core checked. */
|
|
187
|
-
fun send(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
|
|
188
|
-
/** For every image that does not name its own `"resolution"` (default standard). */
|
|
189
|
-
imageResolution: ImageResolution? = null): JsonElement =
|
|
190
|
-
beginSend(input, cancellation, responseFormat, imageResolution).result()
|
|
191
|
-
/** Admits a send at once on the calling thread, without waiting for its turn: sends are
|
|
192
|
-
* admitted in the order they are called (their place among held sends, and in a turn they
|
|
193
|
-
* share), whatever thread then waits. For a host that hops threads after (React Native). */
|
|
194
|
-
internal fun beginSend(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
|
|
195
|
-
imageResolution: ImageResolution? = null): PendingTurn {
|
|
196
|
-
cancellation.check()
|
|
197
|
-
if (closed) throw CrocheError("closed", "Runtime is closed")
|
|
198
|
-
// Standard images are re-encoded here, before admission, so sends keep their order.
|
|
199
|
-
val prepared = CrocheImages.prepareInput(input, imageResolution)
|
|
200
|
-
val token = CancelToken()
|
|
201
|
-
val listener = cancellation.observe { token.cancel() }
|
|
202
|
-
val pending = try { core.beginSend(prepared.toString(), token, responseFormat?.toString()) }
|
|
203
|
-
catch (error: Exception) { cancellation.remove(listener); token.close(); throw crocheError(error) }
|
|
204
|
-
return PendingTurn(pending, token) { cancellation.remove(listener) }
|
|
205
|
-
}
|
|
206
|
-
fun sync(): JsonElement = run { it.sync(); null }
|
|
207
|
-
/**
|
|
208
|
-
* One round of background upkeep: deliver the outbox of call reports, then sync balances,
|
|
209
|
-
* policy and the model key. The Core does work only when some is due and backs off after
|
|
210
|
-
* a failure. Timer upkeep follows backgroundSync; call it when the app returns to the foreground.
|
|
211
|
-
* Separately, Core delivers pending reports when the agent goes idle and after open,
|
|
212
|
-
* even with backgroundSync off. That delivery never folds or syncs. It never delays a turn: a send takes over while
|
|
213
|
-
* it waits on Cloud. Never throws; the result says what happened. Blocking.
|
|
214
|
-
*/
|
|
215
|
-
fun maintain(force: Boolean = false): JsonElement =
|
|
216
|
-
try { run { it.maintain(force) } } catch (_: Exception) { obj("ran" to bool(false)) }
|
|
217
|
-
/** Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
|
|
218
|
-
* is (no turn, no cost) or one is already being delivered, else `{ran, ids, delivered, turn}`.
|
|
219
|
-
* Never before a note's time. Call it at every foreground. Blocking.
|
|
220
|
-
*
|
|
221
|
-
* `cancellation` cancels this delivery only, from any thread: waiting behind another turn, it
|
|
222
|
-
* leaves without running; running, its turn stops. Either way its notes stay pending. Fired
|
|
223
|
-
* after the delivery ended, it does nothing: never another turn (`cancel()` stops whatever
|
|
224
|
-
* turn runs).
|
|
225
|
-
*
|
|
226
|
-
* Afterwards the pending set is handed to the OS scheduler again (a refusal is reported as
|
|
227
|
-
* `schedule.degraded`): the OS spends a request when it runs it, and a delivery cut short
|
|
228
|
-
* leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
|
|
229
|
-
* ends, and registering its past-due note again would only start another run at once. A
|
|
230
|
-
* failed delivery that answers `retryAt` waits until then. */
|
|
231
|
-
fun deliverDue(cancellation: RuntimeCancellation = RuntimeCancellation()): JsonElement {
|
|
232
|
-
host.attempted()
|
|
233
|
-
val token = CancelToken()
|
|
234
|
-
val listener = cancellation.observe { token.cancel() }
|
|
235
|
-
val result = try { run { it.deliverDue(token) } }
|
|
236
|
-
catch (error: Exception) { resync(); throw error }
|
|
237
|
-
finally { cancellation.remove(listener); token.close() }
|
|
238
|
-
if (result.at("inFlight").let { it.isJsonPrimitive && it.asBoolean }) return result
|
|
239
|
-
retryAt(result.at("retryAt"))?.let { host.retryAfter(it) }
|
|
240
|
-
resync()
|
|
241
|
-
if (result.at("ran").let { it.isJsonPrimitive && it.asBoolean }) onDelivery?.let { notify -> try { notify(result) } catch (_: Exception) {} }
|
|
242
|
-
return result
|
|
243
|
-
}
|
|
244
|
-
/** INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
|
|
245
|
-
* module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
|
|
246
|
-
* delivery turn (`ran: true`), whoever called it (the timer, a background run, the foreground,
|
|
247
|
-
* the app), once the turn is in `inspect()`'s history. Interim: the public subscription for
|
|
248
|
-
* agent-initiated messages (F25 on #264: `onBackgroundMessage` with replay on open) replaces it.
|
|
249
|
-
* It runs on that delivery's thread. */
|
|
250
|
-
@CrocheBridgeApi
|
|
251
|
-
fun observeDeliveries(observer: ((JsonElement) -> Unit)?) { onDelivery = observer }
|
|
252
|
-
/** Hands the pending set to the OS scheduler again, through the Core, which reports a refusal
|
|
253
|
-
* as `schedule.degraded`. */
|
|
254
|
-
private fun resync() {
|
|
255
|
-
if (closed) return
|
|
256
|
-
try { core.reschedule() } catch (_: Exception) { /* reported as schedule.degraded */ }
|
|
257
|
-
}
|
|
258
|
-
/** The agent's pending scheduled notes: `{pending: [{id, at, note}], due}`. */
|
|
259
|
-
fun schedules(): JsonElement = run { it.schedules() }
|
|
260
|
-
fun flush(): JsonElement = run { it.flush(); null }
|
|
261
|
-
/** Forgets this user's conversation and memory and starts over (money and identity stay).
|
|
262
|
-
* The clear takes its place on the calling thread, as `send` does: behind a running turn,
|
|
263
|
-
* ahead of every send called after this. It then suspends until the clear is done; only that
|
|
264
|
-
* wait is on a thread of its own, so calling it from the main thread does not block it. */
|
|
265
|
-
suspend fun clearHistory() {
|
|
266
|
-
subscription?.let { it.clearHistory(); return }
|
|
267
|
-
if (closed) throw CrocheError("closed", "Runtime is closed")
|
|
268
|
-
val pending = try { core.beginClearHistory() } catch (error: Exception) { throw crocheError(error) }
|
|
269
|
-
offload {
|
|
270
|
-
try { pending.finish(); Unit } catch (error: Exception) { throw crocheError(error) } finally { pending.close() }
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
/** Runs a blocking Core call on a thread of its own and resumes the caller with its outcome. */
|
|
274
|
-
private suspend fun <T> offload(body: () -> T): T = suspendCoroutine { continuation ->
|
|
275
|
-
Thread({ OffloadSeam.starting?.invoke(); continuation.resumeWith(runCatching(body)) }, "croche-offload")
|
|
276
|
-
.apply { isDaemon = true }.start()
|
|
277
|
-
}
|
|
278
|
-
/** Internal until `memory history` (B3): turns `from..to` from the turn archive, as
|
|
279
|
-
* `{"records":[...]}`; `archive_unavailable` when the storage keeps none. */
|
|
280
|
-
internal fun archiveRead(from: Long, to: Long): JsonElement = run { it.archiveRead(from.toULong(), to.toULong()) }
|
|
281
|
-
/** Internal: deletes archived turns, every one without a range. */
|
|
282
|
-
internal fun archiveClear(from: Long? = null, to: Long? = null) { run { it.archiveClear(from?.toULong(), to?.toULong()); null } }
|
|
283
|
-
fun inspect(): JsonElement = run { it.inspect() }
|
|
284
|
-
/** Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
|
|
285
|
-
* The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
|
|
286
|
-
* its place in the queue, so turns sent before it still offer the old list. A removed or
|
|
287
|
-
* changed command answers `withdrawn` once the swap applies. A handler given here also
|
|
288
|
-
* serves turns already queued under the same name. */
|
|
289
|
-
fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) = synchronized(toolChange) {
|
|
290
|
-
subscription?.let { it.setTools(tools, handlers); return@synchronized }
|
|
291
|
-
// One change at a time (Swift gets this from its actor): two threads' acceptances must
|
|
292
|
-
// install handlers in the order the Core accepted the lists.
|
|
293
|
-
if (closed) throw CrocheError("closed", "Runtime is closed")
|
|
294
|
-
// New names first: the Core cannot call them before it accepts the list. Replacements
|
|
295
|
-
// only after it accepts; a refusal removes what it staged, so every handler is as it was.
|
|
296
|
-
val stamp = host.stageTools(handlers)
|
|
297
|
-
try { run { it.setToolDeclarations(tools.toString()); null } }
|
|
298
|
-
catch (error: Exception) { host.unstageTools(handlers.keys, stamp); throw error }
|
|
299
|
-
host.acceptTools(handlers)
|
|
300
|
-
}
|
|
301
|
-
private val toolChange = Any()
|
|
302
|
-
/** The tool list the model is offered (metadata only). */
|
|
303
|
-
fun tools(): JsonArray = inspect().at("tools").let { if (it.isJsonArray) it.asJsonArray else JsonArray() }
|
|
304
|
-
|
|
305
|
-
/** Long-term memory: call it for a read-only snapshot, use its methods to manage it. */
|
|
306
|
-
val memory = Memory()
|
|
307
|
-
inner class Memory {
|
|
308
|
-
operator fun invoke(): JsonElement = inspect().at("memory")
|
|
309
|
-
/** AI-written facts with ids, turn/time stamps, refs and replacement links. */
|
|
310
|
-
fun list(): JsonArray = this@LegacyAgentEngine.run { it.memoryList() }.asJsonArray
|
|
311
|
-
/** `{deleted}`, or `{deferred: true}` (see [WriteResult]). */
|
|
312
|
-
fun delete(id: String): JsonObject = this@LegacyAgentEngine.run { it.memoryDelete(id) }.asJsonObject
|
|
313
|
-
/** Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
|
|
314
|
-
* `{deferred: true}` (see [WriteResult]). */
|
|
315
|
-
fun clear(): JsonObject = this@LegacyAgentEngine.run { it.memoryClear() }.asJsonObject
|
|
316
|
-
/** Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied,
|
|
317
|
-
* it carries the setting now in force. */
|
|
318
|
-
fun enabled(on: Boolean): WriteResult<Boolean> = WriteResult.of(this@LegacyAgentEngine.run { it.memorySetEnabled(on) }) { on }
|
|
319
|
-
/** Current and replaced AI-written facts: `{enabled, items}`, not the summary. */
|
|
320
|
-
fun export(): JsonObject = this@LegacyAgentEngine.run { it.memoryExport() }.asJsonObject
|
|
321
|
-
/** Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's). */
|
|
322
|
-
fun onChanged(listener: ((JsonElement) -> Unit)?) {
|
|
323
|
-
if (closed) throw CrocheError("closed", "Runtime is closed")
|
|
324
|
-
core.setMemoryObserver(listener?.let { EventHook(it) })
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/** The app's knowledge documents, held by the Rust Core in memory (never stored: load them
|
|
329
|
-
* on each open). The model searches and reads them with the built-in `wiki` command;
|
|
330
|
-
* `list`, `read` and `search` here are that same view. */
|
|
331
|
-
val wiki = Wiki()
|
|
332
|
-
inner class Wiki {
|
|
333
|
-
private fun encode(docs: List<WikiDocument>): String = JsonArray().apply {
|
|
334
|
-
docs.forEach { doc ->
|
|
335
|
-
add(obj("path" to str(doc.path), "markdown" to str(doc.markdown)).apply {
|
|
336
|
-
doc.agents?.let { a -> add("agents", JsonArray().apply { a.forEach { add(it) } }) }
|
|
337
|
-
})
|
|
338
|
-
}
|
|
339
|
-
}.toString()
|
|
340
|
-
/** Replaces every document and answers what it installed: `{documents, bytes, digest}`.
|
|
341
|
-
* On an error nothing changes. */
|
|
342
|
-
fun set(docs: List<WikiDocument>): JsonObject = this@LegacyAgentEngine.run { it.wikiSet(encode(docs)) }.asJsonObject
|
|
343
|
-
/** `set`, without the digest. */
|
|
344
|
-
fun load(docs: List<WikiDocument>) { set(docs) }
|
|
345
|
-
/** This user's own documents (saved recipes, lesson notes): stored with their state (at
|
|
346
|
-
* most 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable
|
|
347
|
-
* when this returns. `clearHistory` keeps them. To share one with another character, put it to that character's
|
|
348
|
-
* Runtime too. Answers `{documents, bytes}`, or `{deferred: true}` (see [WriteResult]). */
|
|
349
|
-
fun putUser(docs: List<WikiDocument>): JsonObject = this@LegacyAgentEngine.run { it.wikiPutUser(encode(docs)) }.asJsonObject
|
|
350
|
-
/** Removes one of this user's own documents; whether it existed. */
|
|
351
|
-
fun removeUser(path: String): WriteResult<Boolean> =
|
|
352
|
-
WriteResult.of(this@LegacyAgentEngine.run { it.wikiRemoveUser(path) }) { r -> r.at("removed").let { it.isJsonPrimitive && it.asBoolean } }
|
|
353
|
-
/** Removes every one of this user's own documents; how many. */
|
|
354
|
-
fun clearUser(): WriteResult<Int> =
|
|
355
|
-
WriteResult.of(this@LegacyAgentEngine.run { it.wikiClearUser() }) { r -> r.at("cleared").let { if (it.isJsonPrimitive) it.asInt else 0 } }
|
|
356
|
-
/** Adds documents or replaces those with the same path, atomically. */
|
|
357
|
-
fun put(docs: List<WikiDocument>) { this@LegacyAgentEngine.run { it.wikiPut(encode(docs)); null } }
|
|
358
|
-
fun put(doc: WikiDocument) = put(listOf(doc))
|
|
359
|
-
/** Whether the document existed. */
|
|
360
|
-
fun remove(path: String): Boolean = this@LegacyAgentEngine.run { JsonPrimitive(it.wikiRemove(path)).toString() }.asBoolean
|
|
361
|
-
/** `[{path, title, summary?, characters, parts}]` under `folder` (every document when null). */
|
|
362
|
-
fun list(folder: String? = null): JsonArray = this@LegacyAgentEngine.run { it.wikiList(folder) }.asJsonArray
|
|
363
|
-
/** One part (1-based) of a document, `{path, title, part, parts, text}`; JsonNull when none. */
|
|
364
|
-
fun read(path: String, part: Int = 1): JsonElement = this@LegacyAgentEngine.run { it.wikiRead(path, part.coerceAtLeast(0).toUInt()) }
|
|
365
|
-
/** The best matches, best first: at most `limit` (and 5). */
|
|
366
|
-
fun search(query: String, limit: Int = 5): JsonArray = this@LegacyAgentEngine.run { it.wikiSearch(query, limit.coerceIn(0, 5).toUInt()) }.asJsonArray
|
|
367
|
-
}
|
|
368
|
-
/** Stops the running turn only: messages sent while it ran still go, together, as the next turn. */
|
|
369
|
-
fun cancel() { if (!closed) core.cancelTurn() }
|
|
370
|
-
/** Drops the messages held behind the running turn (each send ends `cancelled`); returns how many. */
|
|
371
|
-
fun clearQueued(): Int = if (closed) 0 else try { core.clearQueued().toInt() } catch (error: Exception) { throw crocheError(error) }
|
|
372
|
-
/** Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
|
|
373
|
-
* call upkeep has in flight is finished and settled first.
|
|
374
|
-
* The Core projection fence does not await buffered Flow/UI consumers.
|
|
375
|
-
* An app callback that waits for work on the closer's thread deadlocks under any
|
|
376
|
-
* wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
|
|
377
|
-
override fun close() {
|
|
378
|
-
if (closed) return
|
|
379
|
-
closed = true
|
|
380
|
-
subscription?.let { it.close(); return }
|
|
381
|
-
host.stop()
|
|
382
|
-
try { core.shutdown() } finally { core.destroy(); host.release() }
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
/** What a write (memory, this user's own documents, the allowance) answers: [Applied], with what
|
|
387
|
-
* it did, or [Deferred]: it was called while another operation ran, was accepted, and applies in
|
|
388
|
-
* call order when that operation ends. A message sent after the write sees it; one sent before
|
|
389
|
-
* does not. It is held in this process until then: closing first drops it, and a write that
|
|
390
|
-
* cannot apply then is reported as a `write.failed` debug event. */
|
|
391
|
-
sealed class WriteResult<out T> {
|
|
392
|
-
data class Applied<out T>(val value: T) : WriteResult<T>()
|
|
393
|
-
object Deferred : WriteResult<Nothing>() { override fun toString() = "Deferred" }
|
|
394
|
-
internal companion object {
|
|
395
|
-
fun <T> of(answer: JsonElement, applied: (JsonElement) -> T): WriteResult<T> =
|
|
396
|
-
if (answer.at("deferred").let { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean && it.asBoolean }) Deferred
|
|
397
|
-
else Applied(applied(answer))
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
/** A send [LegacyAgentEngine.beginSend] admitted: [result] blocks until its outcome, once. */
|
|
402
73
|
/** Croche's own tests: runs first on each offload thread, so a test can delay it the way the OS
|
|
403
74
|
* may (#346). Null in every app. */
|
|
404
75
|
internal object OffloadSeam { @Volatile var starting: (() -> Unit)? = null }
|
|
405
|
-
internal class PendingTurn(private val pending: PendingSend, private val token: CancelToken, private val done: () -> Unit) {
|
|
406
|
-
private val lock = Any()
|
|
407
|
-
private var ended = false
|
|
408
|
-
fun result(): JsonElement = try {
|
|
409
|
-
JsonParser.parseString(pending.wait())
|
|
410
|
-
} catch (error: Exception) { throw crocheError(error) } finally {
|
|
411
|
-
done()
|
|
412
|
-
synchronized(lock) { ended = true; pending.close(); token.close() }
|
|
413
|
-
}
|
|
414
|
-
/** Cancels this send only: held, it is dropped; running, its turn stops. */
|
|
415
|
-
fun cancel() = synchronized(lock) { if (!ended) token.cancel() }
|
|
416
|
-
}
|
|
@@ -10,39 +10,108 @@ import kotlinx.coroutines.*
|
|
|
10
10
|
|
|
11
11
|
/** Registration options are exactly {tool,bind}; commands and guide are agent scopes only. */
|
|
12
12
|
sealed interface ToolRegistration {
|
|
13
|
+
/**
|
|
14
|
+
* Tool registration with app-supplied bindings.
|
|
15
|
+
*
|
|
16
|
+
* @property bind JSON bindings provided at registration.
|
|
17
|
+
* @property tool Definition of the tool being registered.
|
|
18
|
+
*/
|
|
13
19
|
data class Bound(val tool: ToolDefinition, val bind: JsonObject) : ToolRegistration
|
|
14
20
|
}
|
|
15
21
|
internal fun ToolRegistration.registration(): CoreToolRegistration = when (this) {
|
|
16
|
-
is ToolDefinition -> ToolDefinitionCalls.registration(
|
|
17
|
-
is ToolRegistration.Bound -> ToolDefinitionCalls.registration(tool.
|
|
22
|
+
is ToolDefinition -> ToolDefinitionCalls.registration(create())
|
|
23
|
+
is ToolRegistration.Bound -> ToolDefinitionCalls.registration(tool.create(), JsonObject().apply { add("bind", bind.deepCopy()) })
|
|
18
24
|
}
|
|
19
|
-
|
|
20
|
-
|
|
25
|
+
/** Definition for a built-in or app-defined tool that can be registered with Croche. */
|
|
26
|
+
class ToolDefinition internal constructor(internal val create: () -> CoreToolDefinition) : ToolRegistration {
|
|
27
|
+
/** Name used to identify this tool. */
|
|
28
|
+
val name: String = publicSync { val core = create(); try { core.name() } finally { core.destroy() } }
|
|
21
29
|
}
|
|
30
|
+
/** Carriers borrow fresh definitions only for the duration of the foreign call. */
|
|
31
|
+
internal inline fun <T> withToolRegistrations(tools: List<ToolRegistration>?, block: (List<CoreToolRegistration>?) -> T): T {
|
|
32
|
+
val registrations = mutableListOf<CoreToolRegistration>()
|
|
33
|
+
try {
|
|
34
|
+
tools?.forEach { registrations.add(it.registration()) }
|
|
35
|
+
return block(if (tools == null) null else registrations)
|
|
36
|
+
} finally { registrations.forEach { it.tool.destroy() } }
|
|
37
|
+
}
|
|
38
|
+
/** Built-in tool definitions that can be registered with Croche. */
|
|
22
39
|
object CrocheTools {
|
|
23
|
-
|
|
40
|
+
/** Definition for the built-in web search tool. */
|
|
41
|
+
val webSearch: ToolDefinition get() = publicSync { ToolDefinition { coreWebSearch() } }
|
|
42
|
+
/** Definition for the built-in image tool. */
|
|
43
|
+
val image: ToolDefinition get() = publicSync { ToolDefinition { coreImage() } }
|
|
24
44
|
}
|
|
25
45
|
|
|
46
|
+
/**
|
|
47
|
+
* One command and its arguments passed to an app tool handler.
|
|
48
|
+
*
|
|
49
|
+
* @property args JSON arguments supplied to the handler.
|
|
50
|
+
* @property key Command key selected for the call.
|
|
51
|
+
*/
|
|
26
52
|
data class ToolCall(val key: String, val args: JsonObject)
|
|
27
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Selects an attachment from an agent conversation.
|
|
55
|
+
*
|
|
56
|
+
* @property agent Agent definition ID.
|
|
57
|
+
* @property id Attachment ID in the selected conversation.
|
|
58
|
+
* @property instance Named conversation ID, or null to select the main conversation.
|
|
59
|
+
*/
|
|
60
|
+
data class AttachmentSource(val agent: String, val id: String, val instance: String? = null) {
|
|
61
|
+
internal fun json() = JsonObject().apply { addProperty("agent", agent); addProperty("id", id); instance?.let { addProperty("instance", it) } }
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Encoded content returned when the app reads a retained attachment.
|
|
65
|
+
*
|
|
66
|
+
* @property data Attachment bytes encoded as Base64.
|
|
67
|
+
* @property mediaType Media type of the decoded bytes.
|
|
68
|
+
*/
|
|
69
|
+
data class AttachmentData(val mediaType: String, val data: String)
|
|
70
|
+
/**
|
|
71
|
+
* Context and attachment access for the current app tool call.
|
|
72
|
+
*
|
|
73
|
+
* @property callId Core-assigned call ID shared by the tool event and its attachments.
|
|
74
|
+
* @property agentId ID of the agent invoking this tool.
|
|
75
|
+
* @property instance Named instance, when the call belongs to one.
|
|
76
|
+
* @property user User ID, when available.
|
|
77
|
+
* @property causedBy IDs of inputs that contributed to the call.
|
|
78
|
+
*/
|
|
79
|
+
class ToolContext internal constructor(val callId: String, val agentId: String, val instance: String?, val user: String?, val causedBy: List<String>, @Transient private val attachments: CoreAttachmentReader) {
|
|
80
|
+
/** Let an app tool read the file the user shared for that action. */
|
|
81
|
+
suspend fun attachment(id: String): AttachmentData = dev.croche.s7.publicCall {
|
|
82
|
+
val value = JsonParser.parseString(attachments.attachment(id)).asJsonObject
|
|
83
|
+
AttachmentData(value.get("mediaType").asString, value.get("data").asString)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Give the agent a useful explanation when an app action cannot proceed.
|
|
88
|
+
*
|
|
89
|
+
* @property message Explanation available to the agent when an app action cannot proceed.
|
|
90
|
+
*/
|
|
28
91
|
class ToolError(override val message: String) : Exception(message)
|
|
29
92
|
/** Brand has no public constructor; only toolResult creates a result, never a lookalike object. */
|
|
30
93
|
class ToolResult private constructor(internal val content: JsonElement) {
|
|
31
94
|
internal companion object { fun of(value: JsonElement) = ToolResult(value.deepCopy()) }
|
|
32
95
|
}
|
|
96
|
+
/** Return content the agent can use, such as a caption and a photo from the app. */
|
|
33
97
|
fun toolResult(value: JsonElement): ToolResult = ToolResult.of(value)
|
|
98
|
+
/** Return content the agent can use, such as a caption and a photo from the app. */
|
|
34
99
|
fun toolResult(value: String): ToolResult = ToolResult.of(JsonPrimitive(value))
|
|
100
|
+
/** Return content the agent can use, such as a caption and a photo from the app. */
|
|
35
101
|
fun toolResult(value: List<JsonObject>): ToolResult = ToolResult.of(JsonArray().apply { value.forEach { add(it.deepCopy()) } })
|
|
102
|
+
/** Let the app apply its own permissions and use its own data for an action the agent requests. */
|
|
36
103
|
typealias ToolExecute = suspend (ToolCall, ToolContext) -> Any?
|
|
37
104
|
|
|
105
|
+
/** Let the agent use app-owned features such as looking up an order. */
|
|
38
106
|
fun defineTool(manifest: JsonElement, execute: ToolExecute): ToolDefinition = publicSync {
|
|
39
|
-
|
|
107
|
+
val input = manifest.deepCopy(); val executor = toolExecute(execute)
|
|
108
|
+
ToolDefinition { ToolDefinitionCalls.defineTool(input, executor) }
|
|
40
109
|
}
|
|
41
110
|
|
|
42
111
|
/** Core supplies an effect worker. A suspend app handler runs there; native cancellation cancels
|
|
43
112
|
* its coroutine. Only transport outcomes cross back: Core chooses policy and all error codes. */
|
|
44
113
|
internal fun toolExecute(execute: ToolExecute): CoreToolExecute = object : CoreToolExecute {
|
|
45
|
-
override fun execute(callJson: String, contextJson: String, cancel: CancelToken): String {
|
|
114
|
+
override fun execute(callJson: String, contextJson: String, cancel: CancelToken, attachments: CoreAttachmentReader): String {
|
|
46
115
|
val job = Job()
|
|
47
116
|
cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { job.cancel() } }))
|
|
48
117
|
if (cancel.isCancelled()) job.cancel()
|
|
@@ -52,7 +121,7 @@ internal fun toolExecute(execute: ToolExecute): CoreToolExecute = object : CoreT
|
|
|
52
121
|
val ctx = ToolContext(context.get("callId").asString, context.get("agentId").asString,
|
|
53
122
|
context.get("instance")?.takeUnless { it.isJsonNull }?.asString,
|
|
54
123
|
context.get("user")?.takeUnless { it.isJsonNull }?.asString,
|
|
55
|
-
context.getAsJsonArray("causedBy").map { it.asString })
|
|
124
|
+
context.getAsJsonArray("causedBy").map { it.asString }, attachments)
|
|
56
125
|
val value = runBlocking(job) { execute(ToolCall(call.get("key").asString, call.getAsJsonObject("args")), ctx) }
|
|
57
126
|
ToolCompletionEncoding.returned(value)
|
|
58
127
|
} catch (_: CancellationException) { """{"type":"cancelled"}""" }
|
|
@@ -61,7 +130,7 @@ internal fun toolExecute(execute: ToolExecute): CoreToolExecute = object : CoreT
|
|
|
61
130
|
addProperty("type", "handler_error")
|
|
62
131
|
add("error", JsonObject().apply { addProperty("type", error.javaClass.simpleName); addProperty("message", error.message) })
|
|
63
132
|
}.toString() }
|
|
64
|
-
finally { job.complete() }
|
|
133
|
+
finally { job.complete(); cancel.destroy() }
|
|
65
134
|
return completion // The handler outcome is a fact; Core decides cancellation precedence.
|
|
66
135
|
}
|
|
67
136
|
}
|