@h1r-ai/croche-react-native 0.5.5 → 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.
Files changed (248) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +90 -451
  3. package/THIRD-PARTY-NOTICES +906 -14
  4. package/android/build.gradle +6 -1
  5. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
  6. package/android/src/main/AndroidManifest.xml +0 -5
  7. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
  8. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
  9. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
  10. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
  11. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  12. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
  13. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
  14. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  15. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  16. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -0
  17. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  18. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  19. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  20. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  21. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  22. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  33. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  34. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
  35. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  36. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  37. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  38. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  39. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
  40. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  82. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  83. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
  84. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  85. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  86. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
  87. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  88. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  89. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  90. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  91. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
  92. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  93. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  94. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  95. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  96. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  97. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  98. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  99. package/croche-react-native.podspec +1 -0
  100. package/dist/package.json +1 -0
  101. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  102. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  103. package/dist/react-native/src/core-native.d.ts +6 -0
  104. package/dist/react-native/src/core-native.js +316 -0
  105. package/dist/react-native/src/core-wire.d.ts +55 -0
  106. package/dist/react-native/src/core-wire.js +1 -0
  107. package/dist/react-native/src/native-module.d.ts +8 -0
  108. package/dist/react-native/src/native-module.js +53 -0
  109. package/dist/rn-shared-build.json +16 -0
  110. package/dist/runtime/src/adapters.d.ts +8 -0
  111. package/dist/runtime/src/adapters.js +29 -0
  112. package/dist/runtime/src/agent.d.ts +91 -0
  113. package/dist/runtime/src/agent.js +137 -0
  114. package/dist/runtime/src/app-api.d.ts +572 -0
  115. package/dist/runtime/src/app-api.js +1 -0
  116. package/dist/runtime/src/cancel.d.ts +9 -0
  117. package/dist/runtime/src/cancel.js +27 -0
  118. package/dist/runtime/src/core/foreground.d.ts +3 -0
  119. package/dist/runtime/src/core/foreground.js +40 -0
  120. package/dist/runtime/src/core/port.d.ts +247 -0
  121. package/dist/runtime/src/core/port.js +1 -0
  122. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  123. package/dist/runtime/src/core/wasm-owner.js +237 -0
  124. package/dist/runtime/src/core/wasm.d.ts +1 -0
  125. package/dist/runtime/src/core/wasm.js +2 -0
  126. package/dist/runtime/src/croche.d.ts +97 -0
  127. package/dist/runtime/src/croche.js +172 -0
  128. package/dist/runtime/src/errors.d.ts +33 -0
  129. package/dist/runtime/src/errors.js +63 -0
  130. package/dist/runtime/src/events.d.ts +5 -0
  131. package/dist/runtime/src/events.js +31 -0
  132. package/dist/runtime/src/generated/app-stream.d.ts +328 -0
  133. package/dist/runtime/src/generated/app-stream.js +127 -0
  134. package/dist/runtime/src/image-input.d.ts +5 -0
  135. package/dist/runtime/src/image-input.js +60 -0
  136. package/dist/runtime/src/index.d.ts +6 -0
  137. package/dist/runtime/src/index.js +5 -0
  138. package/dist/runtime/src/index.native.d.ts +1 -0
  139. package/dist/runtime/src/index.native.js +2 -0
  140. package/dist/runtime/src/json.d.ts +13 -0
  141. package/dist/runtime/src/json.js +120 -0
  142. package/dist/runtime/src/native-adapter.d.ts +3 -0
  143. package/dist/runtime/src/native-adapter.js +30 -0
  144. package/dist/runtime/src/pal/host.d.ts +5 -0
  145. package/dist/runtime/src/pal/host.js +60 -0
  146. package/dist/runtime/src/pal/platform.d.ts +21 -0
  147. package/dist/runtime/src/pal/platform.js +7 -0
  148. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  149. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  150. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  151. package/dist/runtime/src/pal/state-store.js +1 -0
  152. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  153. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  154. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  155. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  156. package/dist/runtime/src/rn-entry.d.ts +1 -0
  157. package/dist/runtime/src/rn-entry.js +4 -0
  158. package/dist/runtime/src/run-tool.d.ts +33 -0
  159. package/dist/runtime/src/run-tool.js +7 -0
  160. package/dist/runtime/src/tools.d.ts +35 -0
  161. package/dist/runtime/src/tools.js +94 -0
  162. package/ios/CoreAgentTransport.swift +14 -0
  163. package/ios/CoreDeliveryTransport.swift +58 -0
  164. package/ios/CoreNativePal.swift +98 -0
  165. package/ios/CorePlatformTransport.swift +44 -0
  166. package/ios/CoreWireDispatch.swift +122 -0
  167. package/ios/CoreWireSupport.swift +286 -0
  168. package/ios/CrocheRuntimeBridge.swift +34 -994
  169. package/ios/ProjectPal.swift +49 -0
  170. package/ios/RNCrocheRuntime.mm +18 -201
  171. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  172. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  173. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
  174. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  175. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  176. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  177. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
  178. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
  179. package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
  180. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  181. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  182. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  183. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
  184. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  185. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
  186. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
  187. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
  188. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
  189. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  190. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
  191. package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
  192. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
  193. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  194. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  195. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
  196. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  197. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  198. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
  199. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
  200. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  201. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
  202. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  203. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
  204. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
  205. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
  206. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
  207. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
  208. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  209. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  210. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  211. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
  212. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
  213. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  214. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
  215. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
  216. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  217. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +899 -608
  218. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  219. package/package.json +18 -8
  220. package/scripts/README.md +11 -0
  221. package/scripts/build-shared.mjs +46 -0
  222. package/scripts/build.mjs +11 -0
  223. package/scripts/check-swift-vendor-modules.sh +15 -0
  224. package/scripts/vendor-native.sh +8 -6
  225. package/src/NativeCrocheRuntime.ts +12 -159
  226. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  227. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  228. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  229. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  230. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  231. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
  232. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  233. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
  234. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  235. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  236. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  237. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  238. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  239. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
  240. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  241. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  242. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
  243. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
  244. package/src/index.ts +0 -664
  245. package/src/project-types.ts +0 -35
  246. package/src/project.ts +0 -434
  247. package/src/protocol.ts +0 -28
  248. package/src/types.ts +0 -9
@@ -1,40 +1,38 @@
1
1
  package dev.croche
2
2
 
3
- import com.google.gson.*
4
- import dev.croche.ffi.CancelToken
5
- import dev.croche.ffi.CoreRuntime
6
- import dev.croche.ffi.PendingSend
7
- import dev.croche.ffi.RuntimeOpenOptions
8
- import kotlin.coroutines.suspendCoroutine
9
- import java.io.File
3
+ import com.google.gson.JsonObject
10
4
 
11
- /** Grouped command invocation, already parsed/validated by Rust. */
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
+ */
12
13
  data class CommandInvocation(val tool: String, val command: String?, val key: String, val args: JsonObject)
13
- data class ToolContext(val callId: String, val messageId: String, val userId: String, val cancellation: RuntimeCancellation,
14
- /** Present when the Runtime config has an agentId. Last, with a default, so existing destructuring is unchanged. */
15
- val agentId: String? = null,
16
- /** Where a [withResult] handler leaves its images for this call (set by the Runtime). */
17
- val images: ToolImages? = null,
18
- val user: String? = null, val crocheUserId: String? = null,
19
- val causedBy: List<String> = emptyList(), val origin: String = "app")
20
- fun interface ToolHandler { fun execute(invocation: CommandInvocation, context: ToolContext): JsonElement }
21
14
 
22
- /** One wiki document: a path such as `menu/stew.md` and its markdown (at most 64 KB; 2,000
23
- * documents and 8 MB in all). The title is the first `#` heading; optional frontmatter may set
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
24
18
  * `summary`, `keywords` and `agents` (only those agents see the document); `agents` given here
25
19
  * overrides the frontmatter's. An agent's own path globs are config: `"wiki": {"include": [...],
26
- * "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
+ */
27
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. */
28
28
  companion object {
29
- private const val MAX_DOCUMENTS = 2000
30
-
31
29
  /** The `.md` files under `dir`, paths relative to it with `/` (`menu/stew.md`), in name
32
30
  * order. Subfolders are read; symbolic links and other files are skipped, as the other
33
31
  * SDKs' loaders do. */
34
32
  fun fromDirectory(dir: java.io.File): List<WikiDocument> {
35
33
  val root = dir.toPath()
36
34
  if (!java.nio.file.Files.isDirectory(root, java.nio.file.LinkOption.NOFOLLOW_LINKS))
37
- throw CrocheException("invalid_wiki", "${dir.path}: not a folder")
35
+ throw CrocheError("invalid_wiki", "${dir.path}: not a folder")
38
36
  return fromTree(
39
37
  list = { path ->
40
38
  val at = if (path.isEmpty()) root else root.resolve(path)
@@ -62,7 +60,6 @@ data class WikiDocument(val path: String, val markdown: String, val agents: List
62
60
  if (!children.isNullOrEmpty()) walk(path)
63
61
  else if (name.endsWith(".md")) {
64
62
  val markdown = read(path) ?: continue
65
- if (out.size >= MAX_DOCUMENTS) throw CrocheException("invalid_wiki", "The wiki holds at most $MAX_DOCUMENTS documents")
66
63
  out.add(WikiDocument(path, markdown))
67
64
  }
68
65
  }
@@ -73,343 +70,6 @@ data class WikiDocument(val path: String, val markdown: String, val agents: List
73
70
  }
74
71
  }
75
72
 
76
- /** The Croche Runtime for Kotlin. The Rust Core (crates/croche-ffi) is the Runtime: it holds
77
- * the state and runs the turn, upkeep, cancellation and persistence. This type exposes it with
78
- * Kotlin types; `KotlinHost` performs what only the platform can (the PAL).
79
- * Blocking: call from an IO executor/coroutine, never Android's main thread. Methods return
80
- * detached JSON values. */
81
- class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, private val nativeHost: KotlinHost?,
82
- private val subscription: StreamHub? = null, private val subscriptionPort: CoreStreamPort? = null) : AutoCloseable {
83
- private val core: CoreRuntime get() = checkNotNull(nativeCore) { "Legacy API requires native Core" }
84
- internal val host: KotlinHost get() = checkNotNull(nativeHost) { "Legacy host requires native Core" }
85
- /** Fake-port host seam; create() installs NativeCoreStreamPort. */
86
- internal constructor(port: CoreStreamPort) : this(null, null, StreamHub(port), port)
87
- internal val boundStreamPort: CoreStreamPort get() = checkNotNull(subscriptionPort)
88
- private fun subscriptions(): StreamHub = subscription ?: throw CrocheException(
89
- "invalid_configuration", "Subscription binding is not installed")
90
- suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt = subscriptions().send(input, options)
91
- fun events(initialMessages: Int = 50): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(initialMessages)
92
- fun events(after: Cursor): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(null, after)
93
- suspend fun request(input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = null): RequestResult = subscriptions().request(input, options, wait)
94
- suspend fun cancel(id: String) { subscriptions().cancel(id) }
95
- suspend fun history(before: Long? = null, limit: Int) { subscriptions().history(before, limit) }
96
- val logId: String get() = subscriptions().logId
97
- internal val state: RuntimeEvent.State get() = subscriptions().state
98
- @Volatile private var closed = false
99
- internal val isClosed: Boolean get() = closed
100
- internal fun openSubscription(initial: Int?, after: Cursor?) = subscriptions().openCollection(initial, after)
101
- @Volatile private var onDelivery: ((JsonElement) -> Unit)? = null
102
- companion object {
103
- /** Test-only gate-10 probe; called on the thread that invokes each native stream-port call. */
104
- @Volatile internal var offloadStarting: (() -> Unit)? = null
105
-
106
- /** `secrets` keeps the Runtime credential apart from `storage`: KeystoreSecretStore on
107
- * Android. `attestor` proves the genuine app to Cloud when the project requires it:
108
- * PlayIntegrityAttestor on a device; null on an emulator or a host that cannot attest.
109
- * Events may be delivered on an effect worker thread while a reply streams.
110
- * `libraryName` names the native Runtime library (libcroche_ffi by default).
111
- * `wiki` is the documents, set at open; this agent's path filter is the config's
112
- * `"wiki": {"include": [...], "exclude": [...]}`.
113
- * `onEvent` hears one `turn.started` per turn; a send carried into a running turn at a
114
- * later model call is `{type:"turn.joined", turnId, inputIds}` (the ids newly carried).
115
- * `onUsage` receives every paid call's cost (`{type:"usage", operationId, purpose, causedBy, instance,
116
- * model, costUsd, costStatus, tokens?}`; `tokens` holds the reported counts, e.g. `prompt`,
117
- * `cached`); `instance` is the named/generated instance key, or null for the main agent.
118
- * `model` is the gateway-reported answering model (`modelSource: "response"`), or the
119
- * request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
120
- * present only when different. Reported cost is unchanged by a model substitution.
121
- * At least once, from the start: open itself reports a call
122
- * the process died during. It runs on a Runtime thread; do not call the Runtime from it.
123
- * `scheduler` registers the agent's scheduled notes with the OS for when the app is not
124
- * running: `WorkManagerScheduler` on Android; null on a JVM host, where an in-process
125
- * timer delivers them while it runs and the next open delivers what fell due meanwhile.
126
- * A scheduler whose name another open Runtime holds refuses this one (`scheduler_conflict`).
127
- * `projectDirectory` is required on a plain JVM and refused on Android, which always uses
128
- * app-private filesDir. It is a host option, never part of the Core config. */
129
- fun create(config: JsonObject, storage: RuntimeStorage, secrets: RuntimeSecretStore,
130
- attestor: RuntimeAttestor? = null, tools: Map<String, ToolHandler> = emptyMap(),
131
- http: RuntimeHTTP = RuntimeHttpURLConnection(), onEvent: ((JsonElement) -> Unit)? = null,
132
- onDebugEvent: ((JsonElement) -> Unit)? = null, libraryName: String = LIBRARY,
133
- backgroundSync: Boolean = true, maintenanceIntervalMs: Long = 60_000,
134
- wiki: List<WikiDocument>? = null, onUsage: ((JsonElement) -> Unit)? = null,
135
- scheduler: RuntimeScheduler? = null, projectDirectory: File? = null): CrocheRuntime {
136
- useLibrary(libraryName)
137
- val bound = config.deepCopy().apply {
138
- if (attestor != null) addProperty("attestationPlatform", attestor.platform) else add("attestationPlatform", JsonNull.INSTANCE)
139
- }
140
- // This host can feed deltas, so it asks for a stream unless the app opted out.
141
- val streaming = config.at("streaming").let { if (it.isJsonPrimitive && it.asJsonPrimitive.isBoolean) it.asBoolean else true }
142
- scheduler?.attach()
143
- // From here the host's stop (close, or a failed open) detaches the scheduler.
144
- val host = KotlinHost(storage, secrets, attestor, http, tools.toMap(), backgroundSync, scheduler, projectDirectory)
145
- // The app chose the store, so the Runtime binds its identity to it (a custom storage key).
146
- val options = RuntimeOpenOptions("croche.kotlin", streaming, backgroundSync, maintenanceInterval(maintenanceIntervalMs).toDouble())
147
- val core = try { CoreRuntime.open(host, bound.toString(), options, onEvent?.let { EventHook(it) }, onUsage?.let { EventHook(it) }) }
148
- catch (error: Exception) { host.release(); throw crocheError(error) }
149
- if (onDebugEvent != null) try { core.setDebugObserver(EventHook(onDebugEvent), false) } catch (_: Exception) {}
150
- val runtime = adopt(core, host)
151
- if (wiki != null) try { runtime.wiki.set(wiki) } catch (error: Exception) { runtime.close(); throw error }
152
- return runtime
153
- }
154
- /** Adopts a project-owned Runtime through the same production stream boundary as create. */
155
- internal fun adopt(core: CoreRuntime, host: KotlinHost): CrocheRuntime {
156
- val port = NativeCoreStreamPort(core, host)
157
- val hub = try { StreamHub(port) } catch (error: Exception) { port.close(); throw crocheError(error) }
158
- val runtime = CrocheRuntime(core, host, hub, port)
159
- val weak = java.lang.ref.WeakReference(runtime)
160
- host.deliver = { weak.get()?.deliverDue(); Unit }
161
- host.attach(core)
162
- return runtime
163
- }
164
- fun identity(config: JsonObject, libraryName: String = LIBRARY): JsonElement {
165
- useLibrary(libraryName)
166
- return try { JsonParser.parseString(dev.croche.ffi.identity(config.toString())) } catch (error: Exception) { throw crocheError(error) }
167
- }
168
- private const val LIBRARY = "croche_ffi"
169
- private fun useLibrary(name: String) {
170
- if (name != LIBRARY) System.setProperty("uniffi.component.croche_ffi.libraryOverride", name)
171
- }
172
- }
173
- private fun run(body: (CoreRuntime) -> String?): JsonElement {
174
- if (closed) throw CrocheException("closed", "Runtime is closed")
175
- return try { body(core)?.let { JsonParser.parseString(it) } ?: JsonNull.INSTANCE } catch (error: Exception) { throw crocheError(error) }
176
- }
177
- /** Runs one turn. `cancellation` cancels this turn only, from any thread; one fired before
178
- * the send starts throws `cancelled` here, and one fired while it runs is never missed.
179
- * `responseFormat`: structured output, OpenAI's shape (`{"type":"json_schema",...}` or
180
- * `{"type":"json_object"}`); the result's `output` is the reply as JSON the Core checked. */
181
- fun send(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
182
- /** For every image that does not name its own `"resolution"` (default standard). */
183
- imageResolution: ImageResolution? = null): JsonElement =
184
- beginSend(input, cancellation, responseFormat, imageResolution).result()
185
- /** Admits a send at once on the calling thread, without waiting for its turn: sends are
186
- * admitted in the order they are called (their place among held sends, and in a turn they
187
- * share), whatever thread then waits. For a host that hops threads after (React Native). */
188
- internal fun beginSend(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
189
- imageResolution: ImageResolution? = null): PendingTurn {
190
- cancellation.check()
191
- if (closed) throw CrocheException("closed", "Runtime is closed")
192
- // Standard images are re-encoded here, before admission, so sends keep their order.
193
- val prepared = CrocheImages.prepareInput(input, imageResolution)
194
- val token = CancelToken()
195
- val listener = cancellation.observe { token.cancel() }
196
- val pending = try { core.beginSend(prepared.toString(), token, responseFormat?.toString()) }
197
- catch (error: Exception) { cancellation.remove(listener); token.close(); throw crocheError(error) }
198
- return PendingTurn(pending, token) { cancellation.remove(listener) }
199
- }
200
- fun sync(): JsonElement = run { it.sync(); null }
201
- /**
202
- * One round of background upkeep: deliver the outbox of call reports, then sync balances,
203
- * policy and the model key. The Core does work only when some is due and backs off after
204
- * a failure. It runs by itself after each turn and on a timer (backgroundSync); call it
205
- * when the app returns to the foreground. It never delays a turn: a send takes over while
206
- * it waits on Cloud. Never throws; the result says what happened. Blocking.
207
- */
208
- fun maintain(force: Boolean = false): JsonElement =
209
- try { run { it.maintain(force) } } catch (_: Exception) { obj("ran" to bool(false)) }
210
- /** Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none
211
- * is (no turn, no cost) or one is already being delivered, else `{ran, ids, delivered, turn}`.
212
- * Never before a note's time. Call it at every foreground. Blocking.
213
- *
214
- * `cancellation` cancels this delivery only, from any thread: waiting behind another turn, it
215
- * leaves without running; running, its turn stops. Either way its notes stay pending. Fired
216
- * after the delivery ended, it does nothing: never another turn (`cancel()` stops whatever
217
- * turn runs).
218
- *
219
- * Afterwards the pending set is handed to the OS scheduler again (a refusal is reported as
220
- * `schedule.degraded`): the OS spends a request when it runs it, and a delivery cut short
221
- * leaves its notes. Not after an `inFlight` answer: the delivery in flight does that when it
222
- * ends, and registering its past-due note again would only start another run at once. A
223
- * failed delivery that answers `retryAt` waits until then. */
224
- fun deliverDue(cancellation: RuntimeCancellation = RuntimeCancellation()): JsonElement {
225
- host.attempted()
226
- val token = CancelToken()
227
- val listener = cancellation.observe { token.cancel() }
228
- val result = try { run { it.deliverDue(token) } }
229
- catch (error: Exception) { resync(); throw error }
230
- finally { cancellation.remove(listener); token.close() }
231
- if (result.at("inFlight").let { it.isJsonPrimitive && it.asBoolean }) return result
232
- retryAt(result.at("retryAt"))?.let { host.retryAfter(it) }
233
- resync()
234
- if (result.at("ran").let { it.isJsonPrimitive && it.asBoolean }) onDelivery?.let { notify -> try { notify(result) } catch (_: Exception) {} }
235
- return result
236
- }
237
- /** INTERNAL, not frozen: the React Native bridge's hook (it compiles these sources into its own
238
- * module); apps do not use it. `observer` receives the result of each `deliverDue()` that ran a
239
- * delivery turn (`ran: true`), whoever called it (the timer, a background run, the foreground,
240
- * the app), once the turn is in `inspect()`'s history. Interim: the public subscription for
241
- * agent-initiated messages (F25 on #264: `onBackgroundMessage` with replay on open) replaces it.
242
- * It runs on that delivery's thread. */
243
- @CrocheBridgeApi
244
- fun observeDeliveries(observer: ((JsonElement) -> Unit)?) { onDelivery = observer }
245
- /** Hands the pending set to the OS scheduler again, through the Core, which reports a refusal
246
- * as `schedule.degraded`. */
247
- private fun resync() {
248
- if (closed) return
249
- try { core.reschedule() } catch (_: Exception) { /* reported as schedule.degraded */ }
250
- }
251
- /** The agent's pending scheduled notes: `{pending: [{id, at, note}], due}`. */
252
- fun schedules(): JsonElement = run { it.schedules() }
253
- fun flush(): JsonElement = run { it.flush(); null }
254
- /** Forgets this user's conversation and memory and starts over (money and identity stay).
255
- * The clear takes its place on the calling thread, as `send` does: behind a running turn,
256
- * ahead of every send called after this. It then suspends until the clear is done; only that
257
- * wait is on a thread of its own, so calling it from the main thread does not block it. */
258
- suspend fun clearHistory() {
259
- subscription?.let { it.clearHistory(); return }
260
- if (closed) throw CrocheException("closed", "Runtime is closed")
261
- val pending = try { core.beginClearHistory() } catch (error: Exception) { throw crocheError(error) }
262
- offload {
263
- try { pending.finish(); Unit } catch (error: Exception) { throw crocheError(error) } finally { pending.close() }
264
- }
265
- }
266
- /** Runs a blocking Core call on a thread of its own and resumes the caller with its outcome. */
267
- private suspend fun <T> offload(body: () -> T): T = suspendCoroutine { continuation ->
268
- Thread({ OffloadSeam.starting?.invoke(); continuation.resumeWith(runCatching(body)) }, "croche-offload")
269
- .apply { isDaemon = true }.start()
270
- }
271
- /** Asks Cloud to raise (or, `absolute`, set) this user's allowance within the project's
272
- * ceilings. Pass `id` (e.g. the purchase id) to make a retry safe: Cloud applies it once.
273
- * Called while another operation runs, it answers `{deferred: true}` at once instead (see
274
- * [WriteResult]). */
275
- fun adjustBudget(amount: Double, absolute: Boolean = false, id: String? = null): JsonElement =
276
- run { it.adjustBudget(amount, absolute, id) }
277
- /** Internal until `memory history` (B3): turns `from..to` from the turn archive, as
278
- * `{"records":[...]}`; `archive_unavailable` when the storage keeps none. */
279
- internal fun archiveRead(from: Long, to: Long): JsonElement = run { it.archiveRead(from.toULong(), to.toULong()) }
280
- /** Internal: deletes archived turns, every one without a range. */
281
- internal fun archiveClear(from: Long? = null, to: Long? = null) { run { it.archiveClear(from?.toULong(), to?.toULong()); null } }
282
- fun inspect(): JsonElement = run { it.inspect() }
283
- /** Replaces the tool list (metadata as in config `tools`) and their handlers, as on the web.
284
- * The Core validates it at once, all or nothing (a refusal changes nothing); the swap takes
285
- * its place in the queue, so turns sent before it still offer the old list. A removed or
286
- * changed command answers `withdrawn` once the swap applies. A handler given here also
287
- * serves turns already queued under the same name. */
288
- fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) = synchronized(toolChange) {
289
- subscription?.let { it.setTools(tools, handlers); return@synchronized }
290
- // One change at a time (Swift gets this from its actor): two threads' acceptances must
291
- // install handlers in the order the Core accepted the lists.
292
- if (closed) throw CrocheException("closed", "Runtime is closed")
293
- // New names first: the Core cannot call them before it accepts the list. Replacements
294
- // only after it accepts; a refusal removes what it staged, so every handler is as it was.
295
- val stamp = host.stageTools(handlers)
296
- try { run { it.setToolDeclarations(tools.toString()); null } }
297
- catch (error: Exception) { host.unstageTools(handlers.keys, stamp); throw error }
298
- host.acceptTools(handlers)
299
- }
300
- private val toolChange = Any()
301
- /** The tool list the model is offered (metadata only). */
302
- fun tools(): JsonArray = inspect().at("tools").let { if (it.isJsonArray) it.asJsonArray else JsonArray() }
303
-
304
- /** Long-term memory: call it for a read-only snapshot, use its methods to manage it. */
305
- val memory = Memory()
306
- inner class Memory {
307
- operator fun invoke(): JsonElement = inspect().at("memory")
308
- /** AI-written facts with ids, turn/time stamps, refs and replacement links. */
309
- fun list(): JsonArray = this@CrocheRuntime.run { it.memoryList() }.asJsonArray
310
- /** `{deleted}`, or `{deferred: true}` (see [WriteResult]). */
311
- fun delete(id: String): JsonObject = this@CrocheRuntime.run { it.memoryDelete(id) }.asJsonObject
312
- /** Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
313
- * `{deferred: true}` (see [WriteResult]). */
314
- fun clear(): JsonObject = this@CrocheRuntime.run { it.memoryClear() }.asJsonObject
315
- /** Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied,
316
- * it carries the setting now in force. */
317
- fun enabled(on: Boolean): WriteResult<Boolean> = WriteResult.of(this@CrocheRuntime.run { it.memorySetEnabled(on) }) { on }
318
- /** Current and replaced AI-written facts: `{enabled, items}`, not the summary. */
319
- fun export(): JsonObject = this@CrocheRuntime.run { it.memoryExport() }.asJsonObject
320
- /** Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's). */
321
- fun onChanged(listener: ((JsonElement) -> Unit)?) {
322
- if (closed) throw CrocheException("closed", "Runtime is closed")
323
- core.setMemoryObserver(listener?.let { EventHook(it) })
324
- }
325
- }
326
-
327
- /** The app's knowledge documents, held by the Rust Core in memory (never stored: load them
328
- * on each open). The model searches and reads them with the built-in `wiki` command;
329
- * `list`, `read` and `search` here are that same view. */
330
- val wiki = Wiki()
331
- inner class Wiki {
332
- private fun encode(docs: List<WikiDocument>): String = JsonArray().apply {
333
- docs.forEach { doc ->
334
- add(obj("path" to str(doc.path), "markdown" to str(doc.markdown)).apply {
335
- doc.agents?.let { a -> add("agents", JsonArray().apply { a.forEach { add(it) } }) }
336
- })
337
- }
338
- }.toString()
339
- /** Replaces every document and answers what it installed: `{documents, bytes, digest}`.
340
- * On an error nothing changes. */
341
- fun set(docs: List<WikiDocument>): JsonObject = this@CrocheRuntime.run { it.wikiSet(encode(docs)) }.asJsonObject
342
- /** `set`, without the digest. */
343
- fun load(docs: List<WikiDocument>) { set(docs) }
344
- /** This user's own documents (saved recipes, lesson notes): stored with their state (at
345
- * most 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable
346
- * when this returns. `clearHistory` keeps them. To share one with another character, put it to that character's
347
- * Runtime too. Answers `{documents, bytes}`, or `{deferred: true}` (see [WriteResult]). */
348
- fun putUser(docs: List<WikiDocument>): JsonObject = this@CrocheRuntime.run { it.wikiPutUser(encode(docs)) }.asJsonObject
349
- /** Removes one of this user's own documents; whether it existed. */
350
- fun removeUser(path: String): WriteResult<Boolean> =
351
- WriteResult.of(this@CrocheRuntime.run { it.wikiRemoveUser(path) }) { r -> r.at("removed").let { it.isJsonPrimitive && it.asBoolean } }
352
- /** Removes every one of this user's own documents; how many. */
353
- fun clearUser(): WriteResult<Int> =
354
- WriteResult.of(this@CrocheRuntime.run { it.wikiClearUser() }) { r -> r.at("cleared").let { if (it.isJsonPrimitive) it.asInt else 0 } }
355
- /** Adds documents or replaces those with the same path, atomically. */
356
- fun put(docs: List<WikiDocument>) { this@CrocheRuntime.run { it.wikiPut(encode(docs)); null } }
357
- fun put(doc: WikiDocument) = put(listOf(doc))
358
- /** Whether the document existed. */
359
- fun remove(path: String): Boolean = this@CrocheRuntime.run { JsonPrimitive(it.wikiRemove(path)).toString() }.asBoolean
360
- /** `[{path, title, summary?, characters, parts}]` under `folder` (every document when null). */
361
- fun list(folder: String? = null): JsonArray = this@CrocheRuntime.run { it.wikiList(folder) }.asJsonArray
362
- /** One part (1-based) of a document, `{path, title, part, parts, text}`; JsonNull when none. */
363
- fun read(path: String, part: Int = 1): JsonElement = this@CrocheRuntime.run { it.wikiRead(path, part.coerceAtLeast(0).toUInt()) }
364
- /** The best matches, best first: at most `limit` (and 5). */
365
- fun search(query: String, limit: Int = 5): JsonArray = this@CrocheRuntime.run { it.wikiSearch(query, limit.coerceIn(0, 5).toUInt()) }.asJsonArray
366
- }
367
- /** Stops the running turn only: messages sent while it ran still go, together, as the next turn. */
368
- fun cancel() { if (!closed) core.cancelTurn() }
369
- /** Drops the messages held behind the running turn (each send ends `cancelled`); returns how many. */
370
- fun clearQueued(): Int = if (closed) 0 else try { core.clearQueued().toInt() } catch (error: Exception) { throw crocheError(error) }
371
- /** Closing never waits on Cloud: unsent reports stay in the outbox for the next open. A paid
372
- * call upkeep has in flight is finished and settled first.
373
- * The Core projection fence does not await buffered Flow/UI consumers.
374
- * An app callback that waits for work on the closer's thread deadlocks under any
375
- * wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
376
- override fun close() {
377
- if (closed) return
378
- closed = true
379
- subscription?.let { it.close(); return }
380
- host.stop()
381
- try { core.shutdown() } finally { core.destroy(); host.release() }
382
- }
383
- }
384
-
385
- /** What a write (memory, this user's own documents, the allowance) answers: [Applied], with what
386
- * it did, or [Deferred]: it was called while another operation ran, was accepted, and applies in
387
- * call order when that operation ends. A message sent after the write sees it; one sent before
388
- * does not. It is held in this process until then: closing first drops it, and a write that
389
- * cannot apply then is reported as a `write.failed` debug event. */
390
- sealed class WriteResult<out T> {
391
- data class Applied<out T>(val value: T) : WriteResult<T>()
392
- object Deferred : WriteResult<Nothing>() { override fun toString() = "Deferred" }
393
- internal companion object {
394
- fun <T> of(answer: JsonElement, applied: (JsonElement) -> T): WriteResult<T> =
395
- if (answer.at("deferred").let { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean && it.asBoolean }) Deferred
396
- else Applied(applied(answer))
397
- }
398
- }
399
-
400
- /** A send [CrocheRuntime.beginSend] admitted: [result] blocks until its outcome, once. */
401
73
  /** Croche's own tests: runs first on each offload thread, so a test can delay it the way the OS
402
74
  * may (#346). Null in every app. */
403
75
  internal object OffloadSeam { @Volatile var starting: (() -> Unit)? = null }
404
- internal class PendingTurn(private val pending: PendingSend, private val token: CancelToken, private val done: () -> Unit) {
405
- private val lock = Any()
406
- private var ended = false
407
- fun result(): JsonElement = try {
408
- JsonParser.parseString(pending.wait())
409
- } catch (error: Exception) { throw crocheError(error) } finally {
410
- done()
411
- synchronized(lock) { ended = true; pending.close(); token.close() }
412
- }
413
- /** Cancels this send only: held, it is dropped; running, its turn stops. */
414
- fun cancel() = synchronized(lock) { if (!ended) token.cancel() }
415
- }
@@ -0,0 +1,136 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.*
5
+ import dev.croche.s7.ToolCompletionEncoding
6
+ import dev.croche.s7.ToolDefinitionCalls
7
+ import dev.croche.s7.attached
8
+ import dev.croche.s7.publicSync
9
+ import kotlinx.coroutines.*
10
+
11
+ /** Registration options are exactly {tool,bind}; commands and guide are agent scopes only. */
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
+ */
19
+ data class Bound(val tool: ToolDefinition, val bind: JsonObject) : ToolRegistration
20
+ }
21
+ internal fun ToolRegistration.registration(): CoreToolRegistration = when (this) {
22
+ is ToolDefinition -> ToolDefinitionCalls.registration(create())
23
+ is ToolRegistration.Bound -> ToolDefinitionCalls.registration(tool.create(), JsonObject().apply { add("bind", bind.deepCopy()) })
24
+ }
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() } }
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. */
39
+ object CrocheTools {
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() } }
44
+ }
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
+ */
52
+ data class ToolCall(val key: String, val args: JsonObject)
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
+ */
91
+ class ToolError(override val message: String) : Exception(message)
92
+ /** Brand has no public constructor; only toolResult creates a result, never a lookalike object. */
93
+ class ToolResult private constructor(internal val content: JsonElement) {
94
+ internal companion object { fun of(value: JsonElement) = ToolResult(value.deepCopy()) }
95
+ }
96
+ /** Return content the agent can use, such as a caption and a photo from the app. */
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. */
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. */
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. */
103
+ typealias ToolExecute = suspend (ToolCall, ToolContext) -> Any?
104
+
105
+ /** Let the agent use app-owned features such as looking up an order. */
106
+ fun defineTool(manifest: JsonElement, execute: ToolExecute): ToolDefinition = publicSync {
107
+ val input = manifest.deepCopy(); val executor = toolExecute(execute)
108
+ ToolDefinition { ToolDefinitionCalls.defineTool(input, executor) }
109
+ }
110
+
111
+ /** Core supplies an effect worker. A suspend app handler runs there; native cancellation cancels
112
+ * its coroutine. Only transport outcomes cross back: Core chooses policy and all error codes. */
113
+ internal fun toolExecute(execute: ToolExecute): CoreToolExecute = object : CoreToolExecute {
114
+ override fun execute(callJson: String, contextJson: String, cancel: CancelToken, attachments: CoreAttachmentReader): String {
115
+ val job = Job()
116
+ cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { job.cancel() } }))
117
+ if (cancel.isCancelled()) job.cancel()
118
+ val completion = try {
119
+ val call = JsonParser.parseString(callJson).asJsonObject
120
+ val context = JsonParser.parseString(contextJson).asJsonObject
121
+ val ctx = ToolContext(context.get("callId").asString, context.get("agentId").asString,
122
+ context.get("instance")?.takeUnless { it.isJsonNull }?.asString,
123
+ context.get("user")?.takeUnless { it.isJsonNull }?.asString,
124
+ context.getAsJsonArray("causedBy").map { it.asString }, attachments)
125
+ val value = runBlocking(job) { execute(ToolCall(call.get("key").asString, call.getAsJsonObject("args")), ctx) }
126
+ ToolCompletionEncoding.returned(value)
127
+ } catch (_: CancellationException) { """{"type":"cancelled"}""" }
128
+ catch (error: ToolError) { JsonObject().apply { addProperty("type", "tool_error"); addProperty("message", error.message) }.toString() }
129
+ catch (error: Throwable) { JsonObject().apply {
130
+ addProperty("type", "handler_error")
131
+ add("error", JsonObject().apply { addProperty("type", error.javaClass.simpleName); addProperty("message", error.message) })
132
+ }.toString() }
133
+ finally { job.complete(); cancel.destroy() }
134
+ return completion // The handler outcome is a fact; Core decides cancellation precedence.
135
+ }
136
+ }