@h1r-ai/croche-react-native 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -2,6 +2,7 @@ package dev.croche
2
2
 
3
3
  import com.google.gson.*
4
4
  import dev.croche.ffi.CancelToken
5
+ import dev.croche.s7.attached
5
6
  import dev.croche.ffi.CoreRuntime
6
7
  import dev.croche.ffi.PendingSend
7
8
  import dev.croche.ffi.RuntimeOpenOptions
@@ -10,14 +11,14 @@ import java.io.File
10
11
 
11
12
  /** Grouped command invocation, already parsed/validated by Rust. */
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
+ data class LegacyToolContext(val callId: String, val messageId: String, val userId: String, val cancellation: RuntimeCancellation,
14
15
  /** Present when the Runtime config has an agentId. Last, with a default, so existing destructuring is unchanged. */
15
16
  val agentId: String? = null,
16
17
  /** Where a [withResult] handler leaves its images for this call (set by the Runtime). */
17
18
  val images: ToolImages? = null,
18
- val user: String? = null, val crocheUserId: String? = null,
19
+ val user: String? = null,
19
20
  val causedBy: List<String> = emptyList(), val origin: String = "app")
20
- fun interface ToolHandler { fun execute(invocation: CommandInvocation, context: ToolContext): JsonElement }
21
+ fun interface ToolHandler { fun execute(invocation: CommandInvocation, context: LegacyToolContext): JsonElement }
21
22
 
22
23
  /** One wiki document: a path such as `menu/stew.md` and its markdown (at most 64 KB; 2,000
23
24
  * documents and 8 MB in all). The title is the first `#` heading; optional frontmatter may set
@@ -34,7 +35,7 @@ data class WikiDocument(val path: String, val markdown: String, val agents: List
34
35
  fun fromDirectory(dir: java.io.File): List<WikiDocument> {
35
36
  val root = dir.toPath()
36
37
  if (!java.nio.file.Files.isDirectory(root, java.nio.file.LinkOption.NOFOLLOW_LINKS))
37
- throw CrocheException("invalid_wiki", "${dir.path}: not a folder")
38
+ throw CrocheError("invalid_wiki", "${dir.path}: not a folder")
38
39
  return fromTree(
39
40
  list = { path ->
40
41
  val at = if (path.isEmpty()) root else root.resolve(path)
@@ -62,7 +63,7 @@ data class WikiDocument(val path: String, val markdown: String, val agents: List
62
63
  if (!children.isNullOrEmpty()) walk(path)
63
64
  else if (name.endsWith(".md")) {
64
65
  val markdown = read(path) ?: continue
65
- if (out.size >= MAX_DOCUMENTS) throw CrocheException("invalid_wiki", "The wiki holds at most $MAX_DOCUMENTS documents")
66
+ if (out.size >= MAX_DOCUMENTS) throw CrocheError("invalid_wiki", "The wiki holds at most $MAX_DOCUMENTS documents")
66
67
  out.add(WikiDocument(path, markdown))
67
68
  }
68
69
  }
@@ -78,19 +79,22 @@ data class WikiDocument(val path: String, val markdown: String, val agents: List
78
79
  * Kotlin types; `KotlinHost` performs what only the platform can (the PAL).
79
80
  * Blocking: call from an IO executor/coroutine, never Android's main thread. Methods return
80
81
  * detached JSON values. */
81
- class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, private val nativeHost: KotlinHost?,
82
+ internal class LegacyAgentEngine private constructor(private val nativeCore: CoreRuntime?, private val nativeHost: KotlinHost?,
82
83
  private val subscription: StreamHub? = null, private val subscriptionPort: CoreStreamPort? = null) : AutoCloseable {
83
84
  private val core: CoreRuntime get() = checkNotNull(nativeCore) { "Legacy API requires native Core" }
84
85
  internal val host: KotlinHost get() = checkNotNull(nativeHost) { "Legacy host requires native Core" }
85
86
  /** Fake-port host seam; create() installs NativeCoreStreamPort. */
86
87
  internal constructor(port: CoreStreamPort) : this(null, null, StreamHub(port), port)
87
88
  internal val boundStreamPort: CoreStreamPort get() = checkNotNull(subscriptionPort)
88
- private fun subscriptions(): StreamHub = subscription ?: throw CrocheException(
89
+ private fun subscriptions(): StreamHub = subscription ?: throw CrocheError(
89
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)
90
94
  suspend fun send(input: SendInput, options: SendOptions = SendOptions()): Receipt = subscriptions().send(input, options)
91
95
  fun events(initialMessages: Int = 50): kotlinx.coroutines.flow.Flow<RuntimeEvent> = subscriptions().events(initialMessages)
92
96
  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)
97
+ suspend fun request(input: SendInput, options: SendOptions = SendOptions(), wait: RequestWait? = null): LegacyRequestResult = subscriptions().request(input, options, wait)
94
98
  suspend fun cancel(id: String) { subscriptions().cancel(id) }
95
99
  suspend fun history(before: Long? = null, limit: Int) { subscriptions().history(before, limit) }
96
100
  val logId: String get() = subscriptions().logId
@@ -118,6 +122,8 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
118
122
  * `model` is the gateway-reported answering model (`modelSource: "response"`), or the
119
123
  * request primary when unavailable (`modelSource: "requested"`). `requestedModel` is
120
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.
121
127
  * At least once, from the start: open itself reports a call
122
128
  * the process died during. It runs on a Runtime thread; do not call the Runtime from it.
123
129
  * `scheduler` registers the agent's scheduled notes with the OS for when the app is not
@@ -132,7 +138,7 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
132
138
  onDebugEvent: ((JsonElement) -> Unit)? = null, libraryName: String = LIBRARY,
133
139
  backgroundSync: Boolean = true, maintenanceIntervalMs: Long = 60_000,
134
140
  wiki: List<WikiDocument>? = null, onUsage: ((JsonElement) -> Unit)? = null,
135
- scheduler: RuntimeScheduler? = null, projectDirectory: File? = null): CrocheRuntime {
141
+ scheduler: RuntimeScheduler? = null, projectDirectory: File? = null): LegacyAgentEngine {
136
142
  useLibrary(libraryName)
137
143
  val bound = config.deepCopy().apply {
138
144
  if (attestor != null) addProperty("attestationPlatform", attestor.platform) else add("attestationPlatform", JsonNull.INSTANCE)
@@ -144,7 +150,7 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
144
150
  val host = KotlinHost(storage, secrets, attestor, http, tools.toMap(), backgroundSync, scheduler, projectDirectory)
145
151
  // The app chose the store, so the Runtime binds its identity to it (a custom storage key).
146
152
  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) }) }
153
+ val core = try { CoreRuntime.open(attached(host), bound.toString(), options, onEvent?.let { EventHook(it) }, onUsage?.let { EventHook(it) }) }
148
154
  catch (error: Exception) { host.release(); throw crocheError(error) }
149
155
  if (onDebugEvent != null) try { core.setDebugObserver(EventHook(onDebugEvent), false) } catch (_: Exception) {}
150
156
  val runtime = adopt(core, host)
@@ -152,10 +158,10 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
152
158
  return runtime
153
159
  }
154
160
  /** Adopts a project-owned Runtime through the same production stream boundary as create. */
155
- internal fun adopt(core: CoreRuntime, host: KotlinHost): CrocheRuntime {
161
+ internal fun adopt(core: CoreRuntime, host: KotlinHost): LegacyAgentEngine {
156
162
  val port = NativeCoreStreamPort(core, host)
157
163
  val hub = try { StreamHub(port) } catch (error: Exception) { port.close(); throw crocheError(error) }
158
- val runtime = CrocheRuntime(core, host, hub, port)
164
+ val runtime = LegacyAgentEngine(core, host, hub, port)
159
165
  val weak = java.lang.ref.WeakReference(runtime)
160
166
  host.deliver = { weak.get()?.deliverDue(); Unit }
161
167
  host.attach(core)
@@ -171,7 +177,7 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
171
177
  }
172
178
  }
173
179
  private fun run(body: (CoreRuntime) -> String?): JsonElement {
174
- if (closed) throw CrocheException("closed", "Runtime is closed")
180
+ if (closed) throw CrocheError("closed", "Runtime is closed")
175
181
  return try { body(core)?.let { JsonParser.parseString(it) } ?: JsonNull.INSTANCE } catch (error: Exception) { throw crocheError(error) }
176
182
  }
177
183
  /** Runs one turn. `cancellation` cancels this turn only, from any thread; one fired before
@@ -188,7 +194,7 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
188
194
  internal fun beginSend(input: JsonObject, cancellation: RuntimeCancellation = RuntimeCancellation(), responseFormat: JsonObject? = null,
189
195
  imageResolution: ImageResolution? = null): PendingTurn {
190
196
  cancellation.check()
191
- if (closed) throw CrocheException("closed", "Runtime is closed")
197
+ if (closed) throw CrocheError("closed", "Runtime is closed")
192
198
  // Standard images are re-encoded here, before admission, so sends keep their order.
193
199
  val prepared = CrocheImages.prepareInput(input, imageResolution)
194
200
  val token = CancelToken()
@@ -201,8 +207,9 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
201
207
  /**
202
208
  * One round of background upkeep: deliver the outbox of call reports, then sync balances,
203
209
  * 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
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
206
213
  * it waits on Cloud. Never throws; the result says what happened. Blocking.
207
214
  */
208
215
  fun maintain(force: Boolean = false): JsonElement =
@@ -257,7 +264,7 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
257
264
  * wait is on a thread of its own, so calling it from the main thread does not block it. */
258
265
  suspend fun clearHistory() {
259
266
  subscription?.let { it.clearHistory(); return }
260
- if (closed) throw CrocheException("closed", "Runtime is closed")
267
+ if (closed) throw CrocheError("closed", "Runtime is closed")
261
268
  val pending = try { core.beginClearHistory() } catch (error: Exception) { throw crocheError(error) }
262
269
  offload {
263
270
  try { pending.finish(); Unit } catch (error: Exception) { throw crocheError(error) } finally { pending.close() }
@@ -268,12 +275,6 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
268
275
  Thread({ OffloadSeam.starting?.invoke(); continuation.resumeWith(runCatching(body)) }, "croche-offload")
269
276
  .apply { isDaemon = true }.start()
270
277
  }
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
278
  /** Internal until `memory history` (B3): turns `from..to` from the turn archive, as
278
279
  * `{"records":[...]}`; `archive_unavailable` when the storage keeps none. */
279
280
  internal fun archiveRead(from: Long, to: Long): JsonElement = run { it.archiveRead(from.toULong(), to.toULong()) }
@@ -289,7 +290,7 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
289
290
  subscription?.let { it.setTools(tools, handlers); return@synchronized }
290
291
  // One change at a time (Swift gets this from its actor): two threads' acceptances must
291
292
  // install handlers in the order the Core accepted the lists.
292
- if (closed) throw CrocheException("closed", "Runtime is closed")
293
+ if (closed) throw CrocheError("closed", "Runtime is closed")
293
294
  // New names first: the Core cannot call them before it accepts the list. Replacements
294
295
  // only after it accepts; a refusal removes what it staged, so every handler is as it was.
295
296
  val stamp = host.stageTools(handlers)
@@ -306,20 +307,20 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
306
307
  inner class Memory {
307
308
  operator fun invoke(): JsonElement = inspect().at("memory")
308
309
  /** AI-written facts with ids, turn/time stamps, refs and replacement links. */
309
- fun list(): JsonArray = this@CrocheRuntime.run { it.memoryList() }.asJsonArray
310
+ fun list(): JsonArray = this@LegacyAgentEngine.run { it.memoryList() }.asJsonArray
310
311
  /** `{deleted}`, or `{deferred: true}` (see [WriteResult]). */
311
- fun delete(id: String): JsonObject = this@CrocheRuntime.run { it.memoryDelete(id) }.asJsonObject
312
+ fun delete(id: String): JsonObject = this@LegacyAgentEngine.run { it.memoryDelete(id) }.asJsonObject
312
313
  /** Removes every AI-written fact; the summary and conversation stay. `{cleared}`, or
313
314
  * `{deferred: true}` (see [WriteResult]). */
314
- fun clear(): JsonObject = this@CrocheRuntime.run { it.memoryClear() }.asJsonObject
315
+ fun clear(): JsonObject = this@LegacyAgentEngine.run { it.memoryClear() }.asJsonObject
315
316
  /** Turns memory on or off for this person; the choice outlives `clearHistory()`. Applied,
316
317
  * it carries the setting now in force. */
317
- fun enabled(on: Boolean): WriteResult<Boolean> = WriteResult.of(this@CrocheRuntime.run { it.memorySetEnabled(on) }) { on }
318
+ fun enabled(on: Boolean): WriteResult<Boolean> = WriteResult.of(this@LegacyAgentEngine.run { it.memorySetEnabled(on) }) { on }
318
319
  /** Current and replaced AI-written facts: `{enabled, items}`, not the summary. */
319
- fun export(): JsonObject = this@CrocheRuntime.run { it.memoryExport() }.asJsonObject
320
+ fun export(): JsonObject = this@LegacyAgentEngine.run { it.memoryExport() }.asJsonObject
320
321
  /** Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's). */
321
322
  fun onChanged(listener: ((JsonElement) -> Unit)?) {
322
- if (closed) throw CrocheException("closed", "Runtime is closed")
323
+ if (closed) throw CrocheError("closed", "Runtime is closed")
323
324
  core.setMemoryObserver(listener?.let { EventHook(it) })
324
325
  }
325
326
  }
@@ -338,31 +339,31 @@ class CrocheRuntime private constructor(private val nativeCore: CoreRuntime?, pr
338
339
  }.toString()
339
340
  /** Replaces every document and answers what it installed: `{documents, bytes, digest}`.
340
341
  * On an error nothing changes. */
341
- fun set(docs: List<WikiDocument>): JsonObject = this@CrocheRuntime.run { it.wikiSet(encode(docs)) }.asJsonObject
342
+ fun set(docs: List<WikiDocument>): JsonObject = this@LegacyAgentEngine.run { it.wikiSet(encode(docs)) }.asJsonObject
342
343
  /** `set`, without the digest. */
343
344
  fun load(docs: List<WikiDocument>) { set(docs) }
344
345
  /** This user's own documents (saved recipes, lesson notes): stored with their state (at
345
346
  * most 200 documents and 256 KB as stored), under `user/` (which the app's may not use), and durable
346
347
  * when this returns. `clearHistory` keeps them. To share one with another character, put it to that character's
347
348
  * 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
+ fun putUser(docs: List<WikiDocument>): JsonObject = this@LegacyAgentEngine.run { it.wikiPutUser(encode(docs)) }.asJsonObject
349
350
  /** Removes one of this user's own documents; whether it existed. */
350
351
  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
+ WriteResult.of(this@LegacyAgentEngine.run { it.wikiRemoveUser(path) }) { r -> r.at("removed").let { it.isJsonPrimitive && it.asBoolean } }
352
353
  /** Removes every one of this user's own documents; how many. */
353
354
  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
+ WriteResult.of(this@LegacyAgentEngine.run { it.wikiClearUser() }) { r -> r.at("cleared").let { if (it.isJsonPrimitive) it.asInt else 0 } }
355
356
  /** 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(docs: List<WikiDocument>) { this@LegacyAgentEngine.run { it.wikiPut(encode(docs)); null } }
357
358
  fun put(doc: WikiDocument) = put(listOf(doc))
358
359
  /** Whether the document existed. */
359
- fun remove(path: String): Boolean = this@CrocheRuntime.run { JsonPrimitive(it.wikiRemove(path)).toString() }.asBoolean
360
+ fun remove(path: String): Boolean = this@LegacyAgentEngine.run { JsonPrimitive(it.wikiRemove(path)).toString() }.asBoolean
360
361
  /** `[{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
+ fun list(folder: String? = null): JsonArray = this@LegacyAgentEngine.run { it.wikiList(folder) }.asJsonArray
362
363
  /** 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
+ fun read(path: String, part: Int = 1): JsonElement = this@LegacyAgentEngine.run { it.wikiRead(path, part.coerceAtLeast(0).toUInt()) }
364
365
  /** 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
+ fun search(query: String, limit: Int = 5): JsonArray = this@LegacyAgentEngine.run { it.wikiSearch(query, limit.coerceIn(0, 5).toUInt()) }.asJsonArray
366
367
  }
367
368
  /** Stops the running turn only: messages sent while it ran still go, together, as the next turn. */
368
369
  fun cancel() { if (!closed) core.cancelTurn() }
@@ -397,7 +398,7 @@ sealed class WriteResult<out T> {
397
398
  }
398
399
  }
399
400
 
400
- /** A send [CrocheRuntime.beginSend] admitted: [result] blocks until its outcome, once. */
401
+ /** A send [LegacyAgentEngine.beginSend] admitted: [result] blocks until its outcome, once. */
401
402
  /** Croche's own tests: runs first on each offload thread, so a test can delay it the way the OS
402
403
  * may (#346). Null in every app. */
403
404
  internal object OffloadSeam { @Volatile var starting: (() -> Unit)? = null }
@@ -0,0 +1,67 @@
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
+ data class Bound(val tool: ToolDefinition, val bind: JsonObject) : ToolRegistration
14
+ }
15
+ internal fun ToolRegistration.registration(): CoreToolRegistration = when (this) {
16
+ is ToolDefinition -> ToolDefinitionCalls.registration(core)
17
+ is ToolRegistration.Bound -> ToolDefinitionCalls.registration(tool.core, JsonObject().apply { add("bind", bind.deepCopy()) })
18
+ }
19
+ class ToolDefinition internal constructor(internal val core: CoreToolDefinition) : ToolRegistration {
20
+ val name: String get() = publicSync { core.name() }
21
+ }
22
+ object CrocheTools {
23
+ val webSearch: ToolDefinition get() = publicSync { ToolDefinition(coreWebSearch()) }
24
+ }
25
+
26
+ data class ToolCall(val key: String, val args: JsonObject)
27
+ data class ToolContext(val callId: String, val agentId: String, val instance: String?, val user: String?, val causedBy: List<String>)
28
+ class ToolError(override val message: String) : Exception(message)
29
+ /** Brand has no public constructor; only toolResult creates a result, never a lookalike object. */
30
+ class ToolResult private constructor(internal val content: JsonElement) {
31
+ internal companion object { fun of(value: JsonElement) = ToolResult(value.deepCopy()) }
32
+ }
33
+ fun toolResult(value: JsonElement): ToolResult = ToolResult.of(value)
34
+ fun toolResult(value: String): ToolResult = ToolResult.of(JsonPrimitive(value))
35
+ fun toolResult(value: List<JsonObject>): ToolResult = ToolResult.of(JsonArray().apply { value.forEach { add(it.deepCopy()) } })
36
+ typealias ToolExecute = suspend (ToolCall, ToolContext) -> Any?
37
+
38
+ fun defineTool(manifest: JsonElement, execute: ToolExecute): ToolDefinition = publicSync {
39
+ ToolDefinition(ToolDefinitionCalls.defineTool(manifest, toolExecute(execute)))
40
+ }
41
+
42
+ /** Core supplies an effect worker. A suspend app handler runs there; native cancellation cancels
43
+ * its coroutine. Only transport outcomes cross back: Core chooses policy and all error codes. */
44
+ internal fun toolExecute(execute: ToolExecute): CoreToolExecute = object : CoreToolExecute {
45
+ override fun execute(callJson: String, contextJson: String, cancel: CancelToken): String {
46
+ val job = Job()
47
+ cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { job.cancel() } }))
48
+ if (cancel.isCancelled()) job.cancel()
49
+ val completion = try {
50
+ val call = JsonParser.parseString(callJson).asJsonObject
51
+ val context = JsonParser.parseString(contextJson).asJsonObject
52
+ val ctx = ToolContext(context.get("callId").asString, context.get("agentId").asString,
53
+ context.get("instance")?.takeUnless { it.isJsonNull }?.asString,
54
+ context.get("user")?.takeUnless { it.isJsonNull }?.asString,
55
+ context.getAsJsonArray("causedBy").map { it.asString })
56
+ val value = runBlocking(job) { execute(ToolCall(call.get("key").asString, call.getAsJsonObject("args")), ctx) }
57
+ ToolCompletionEncoding.returned(value)
58
+ } catch (_: CancellationException) { """{"type":"cancelled"}""" }
59
+ catch (error: ToolError) { JsonObject().apply { addProperty("type", "tool_error"); addProperty("message", error.message) }.toString() }
60
+ catch (error: Throwable) { JsonObject().apply {
61
+ addProperty("type", "handler_error")
62
+ add("error", JsonObject().apply { addProperty("type", error.javaClass.simpleName); addProperty("message", error.message) })
63
+ }.toString() }
64
+ finally { job.complete() }
65
+ return completion // The handler outcome is a fact; Core decides cancellation precedence.
66
+ }
67
+ }
@@ -0,0 +1,20 @@
1
+ package dev.croche
2
+
3
+ import dev.croche.ffi.CancelToken
4
+ import dev.croche.ffi.PalDecodedImage
5
+ import dev.croche.ffi.PalImageDecodeOptions
6
+ import dev.croche.ffi.PalImageRenderRequest
7
+
8
+ /** Native codec effects only. All sizing, formats, limits and candidate selection are Core's. */
9
+ internal interface DecodedImageCodec : AutoCloseable {
10
+ fun decode(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken): PalDecodedImage
11
+ fun render(request: PalImageRenderRequest, cancel: CancelToken): ByteArray
12
+ fun release(handle: String)
13
+ }
14
+
15
+ /** A JVM without the Android platform artifact has no decoder, with no acquisition fallback. */
16
+ internal fun platformDecodedImageCodec(): DecodedImageCodec? = try {
17
+ Class.forName("dev.croche.android.BitmapDecodedImageCodec").getDeclaredConstructor().newInstance() as DecodedImageCodec
18
+ } catch (_: ClassNotFoundException) {
19
+ null
20
+ }
@@ -16,7 +16,7 @@ class RuntimeCancellation {
16
16
  private val cancelled = AtomicBoolean(false)
17
17
  private val callbacks = ConcurrentHashMap<Any, () -> Unit>()
18
18
  val isCancelled: Boolean get() = cancelled.get()
19
- fun check() { if (isCancelled) throw CrocheException("cancelled", "The operation was cancelled") }
19
+ fun check() { if (isCancelled) throw CrocheError("cancelled", "The operation was cancelled") }
20
20
  fun cancel() { if (cancelled.compareAndSet(false, true)) { callbacks.values.forEach { it() }; callbacks.clear() } }
21
21
  internal fun observe(callback: () -> Unit): Any {
22
22
  val key = Any(); callbacks[key] = callback
@@ -52,10 +52,10 @@ class RuntimeHttpURLConnection : RuntimeHTTP {
52
52
  return request(effect.at("url").text(), effect.at("method").text(), headers, body, effect.at("timeoutMs").asInt, cancellation) { connection, status ->
53
53
  val fields = JsonObject()
54
54
  connection.headerFields.forEach { (key, values) -> if (key != null) fields.addProperty(key, values.joinToString(", ")) }
55
- if (connection.contentLengthLong > MAX_RESPONSE_BYTES) throw CrocheException("invalid_response", "HTTP response exceeds 2MiB")
55
+ if (connection.contentLengthLong > MAX_RESPONSE_BYTES) throw CrocheError("invalid_response", "HTTP response exceeds 2MiB")
56
56
  val data = ByteArrayOutputStream()
57
57
  read(connection, status, cancellation) { buffer, count ->
58
- if (data.size() + count > MAX_RESPONSE_BYTES) throw CrocheException("invalid_response", "HTTP response exceeds 2MiB")
58
+ if (data.size() + count > MAX_RESPONSE_BYTES) throw CrocheError("invalid_response", "HTTP response exceeds 2MiB")
59
59
  data.write(buffer, 0, count); true
60
60
  }
61
61
  val result = obj("status" to num(status), "headers" to fields)
@@ -71,7 +71,7 @@ class RuntimeHttpURLConnection : RuntimeHTTP {
71
71
  override fun chunk(bytes: ByteArray) = sink.chunk(bytes)
72
72
  }, cancellation)
73
73
  internal fun stream(request: PalHttpRequest, sink: ResponseSink, cancellation: RuntimeCancellation) {
74
- request(request.url, request.method, request.headers.map { it.name to it.value }, request.body.toByteArray(Charsets.UTF_8),
74
+ request(request.url, request.method, request.headers.map { it.name to it.value }, request.body?.toByteArray(Charsets.UTF_8) ?: byteArrayOf(),
75
75
  request.timeoutMs.coerceAtMost(Int.MAX_VALUE.toULong()).toInt(), cancellation) { connection, status ->
76
76
  val fields = connection.headerFields.mapNotNull { (key, values) -> key?.let { PalHeader(it, values.joinToString(", ")) } }
77
77
  sink.head(status, fields)
@@ -82,9 +82,9 @@ class RuntimeHttpURLConnection : RuntimeHTTP {
82
82
  private fun <T> request(url: String, method: String, headers: List<Pair<String, String>>, body: ByteArray, timeoutMs: Int,
83
83
  cancellation: RuntimeCancellation, respond: (HttpURLConnection, Int) -> T): T {
84
84
  cancellation.check()
85
- if (CookieHandler.getDefault() != null) throw CrocheException("network_error", "Default transport requires no process CookieHandler")
85
+ if (CookieHandler.getDefault() != null) throw CrocheError("network_error", "Default transport requires no process CookieHandler")
86
86
  val connection = URI(url).toURL().openConnection() as HttpURLConnection
87
- if (CookieHandler.getDefault() != null) { connection.disconnect(); throw CrocheException("network_error", "Process CookieHandler changed during request creation") }
87
+ if (CookieHandler.getDefault() != null) { connection.disconnect(); throw CrocheError("network_error", "Process CookieHandler changed during request creation") }
88
88
  val listener = cancellation.observe { connection.disconnect() }
89
89
  try {
90
90
  connection.instanceFollowRedirects = false
@@ -126,18 +126,17 @@ internal class EffectExecutor : AutoCloseable {
126
126
  fun run(timeoutMs: Long?, cancellation: RuntimeCancellation, block: (RuntimeCancellation) -> JsonElement): JsonElement {
127
127
  cancellation.check()
128
128
  val local = RuntimeCancellation()
129
- val future = try { pool.submit(Callable { local.check(); block(local).also { local.check() } }) }
130
- catch (_: RejectedExecutionException) { throw CrocheException("effect_failed", "Host effect workers are occupied") }
129
+ val future = pool.submit(Callable { local.check(); block(local).also { local.check() } })
131
130
  val listener = cancellation.observe { local.cancel(); future.cancel(true) }
132
131
  try { return if (timeoutMs == null) future.get() else future.get(timeoutMs.coerceAtLeast(1), TimeUnit.MILLISECONDS) }
133
- catch (_: TimeoutException) { local.cancel(); future.cancel(true); throw CrocheException("timeout", "The effect deadline expired") }
134
- catch (_: CancellationException) { throw CrocheException("cancelled", "The operation was cancelled") }
132
+ catch (_: TimeoutException) { local.cancel(); future.cancel(true); throw CrocheError("timeout", "The effect deadline expired") }
133
+ catch (_: CancellationException) { throw CrocheError("cancelled", "The operation was cancelled") }
135
134
  catch (_: InterruptedException) {
136
135
  local.cancel(); future.cancel(true)
137
136
  // Clear interruption so the following required durable write is not aborted.
138
- Thread.interrupted(); throw CrocheException("cancelled", "The operation was cancelled")
137
+ Thread.interrupted(); throw CrocheError("cancelled", "The operation was cancelled")
139
138
  }
140
- catch (error: ExecutionException) { throw (error.cause as? Exception ?: CrocheException("effect_failed", "The host effect failed")) }
139
+ catch (error: ExecutionException) { throw (error.cause ?: error) }
141
140
  finally { cancellation.remove(listener) }
142
141
  }
143
142
  override fun close() { pool.shutdownNow() }
@@ -163,7 +162,7 @@ internal class ToolExecutor : AutoCloseable {
163
162
  try { local.check(); block(local).also { local.check() } }
164
163
  finally { synchronized(lock) { runner = null }; Thread.interrupted() }
165
164
  })
166
- } catch (_: RejectedExecutionException) { throw CrocheException("host_unresponsive", "The application's command workers are closed") }
165
+ } catch (_: RejectedExecutionException) { throw CrocheError("host_unresponsive", "The application's command workers are closed") }
167
166
  val listener = cancellation.observe { local.cancel(); synchronized(lock) { runner?.interrupt() } }
168
167
  try {
169
168
  while (true) {
@@ -172,8 +171,8 @@ internal class ToolExecutor : AutoCloseable {
172
171
  }
173
172
  }
174
173
  catch (error: ExecutionException) {
175
- if (local.isCancelled) throw CrocheException("cancelled", "The operation was cancelled")
176
- throw handlerError(error.cause)
174
+ if (local.isCancelled) throw CrocheError("cancelled", "The operation was cancelled")
175
+ throw handlerError(error.cause ?: error)
177
176
  }
178
177
  finally { cancellation.remove(listener) }
179
178
  }
@@ -187,9 +186,8 @@ internal class ToolNotDispatched : RuntimeException("No handler ran for this too
187
186
  /** An error from a tool handler. "Nothing ran" is the host's to say, never a handler's: a
188
187
  * handler that throws `tool_not_dispatched` or `host_unresponsive` (perhaps passing on another
189
188
  * Runtime's error) may already have had its effect, so the call fails as `tool_failed`. */
190
- internal fun handlerError(error: Throwable?): Exception = when {
191
- error is ToolNotDispatched -> CrocheException("tool_not_dispatched", "No handler ran for this tool")
192
- error is CrocheException && error.code in setOf("tool_not_dispatched", "host_unresponsive") -> CrocheException("tool_failed", error.message)
193
- error is Exception -> error
194
- else -> CrocheException("effect_failed", "The host effect failed")
189
+ internal fun handlerError(error: Throwable): Throwable = when {
190
+ error is ToolNotDispatched -> CrocheError("tool_not_dispatched", "No handler ran for this tool")
191
+ error is CrocheError && error.code in setOf("tool_not_dispatched", "host_unresponsive") -> CrocheError("tool_failed", error.message)
192
+ else -> error
195
193
  }