@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
@@ -0,0 +1,322 @@
1
+ // GENERATED by scripts/generate-app-stream.mjs from the Rust app contract. Do not edit.
2
+ package dev.croche
3
+
4
+ import com.google.gson.*
5
+ import com.google.gson.annotations.JsonAdapter
6
+ import com.google.gson.stream.*
7
+
8
+ object AppStreamContract {
9
+ sealed interface InputDisposition {
10
+ val rawValue: String
11
+ object QUEUED: InputDisposition { override val rawValue = "queued" }
12
+ object SEEN: InputDisposition { override val rawValue = "seen" }
13
+ object ANSWERED: InputDisposition { override val rawValue = "answered" }
14
+ object NO_REPLY: InputDisposition { override val rawValue = "no_reply" }
15
+ object FAILED: InputDisposition { override val rawValue = "failed" }
16
+ object CANCELLED: InputDisposition { override val rawValue = "cancelled" }
17
+ data class Unknown(val type: String, val fields: JsonElement): InputDisposition { override val rawValue = type }
18
+ }
19
+ sealed interface InputKind {
20
+ val rawValue: String
21
+ object USER: InputKind { override val rawValue = "user" }
22
+ object APP_EVENT: InputKind { override val rawValue = "app_event" }
23
+ object APP_STATE: InputKind { override val rawValue = "app_state" }
24
+ data class Unknown(val type: String, val fields: JsonElement): InputKind { override val rawValue = type }
25
+ }
26
+ sealed interface MessageStatus {
27
+ val rawValue: String
28
+ object COMPLETED: MessageStatus { override val rawValue = "completed" }
29
+ object FAILED: MessageStatus { override val rawValue = "failed" }
30
+ object CANCELLED: MessageStatus { override val rawValue = "cancelled" }
31
+ object INTERRUPTED: MessageStatus { override val rawValue = "interrupted" }
32
+ data class Unknown(val type: String, val fields: JsonElement): MessageStatus { override val rawValue = type }
33
+ }
34
+ sealed interface AgentStatus {
35
+ val rawValue: String
36
+ object IDLE: AgentStatus { override val rawValue = "idle" }
37
+ object RUNNING: AgentStatus { override val rawValue = "running" }
38
+ object WAITING: AgentStatus { override val rawValue = "waiting" }
39
+ data class Unknown(val type: String, val fields: JsonElement): AgentStatus { override val rawValue = type }
40
+ }
41
+ sealed interface TurnPurpose {
42
+ val rawValue: String
43
+ object SUMMARY: TurnPurpose { override val rawValue = "summary" }
44
+ data class Unknown(val type: String, val fields: JsonElement): TurnPurpose { override val rawValue = type }
45
+ }
46
+ sealed interface MemoryOp {
47
+ val rawValue: String
48
+ object DELETE: MemoryOp { override val rawValue = "delete" }
49
+ object CLEAR: MemoryOp { override val rawValue = "clear" }
50
+ object ENABLED: MemoryOp { override val rawValue = "enabled" }
51
+ data class Unknown(val type: String, val fields: JsonElement): MemoryOp { override val rawValue = type }
52
+ }
53
+ data class Attachment(
54
+ val id: String,
55
+ val kind: String,
56
+ val origin: String,
57
+ val mediaType: String,
58
+ val bytes: Long,
59
+ val sha256: String,
60
+ val width: Long? = null,
61
+ val height: Long? = null,
62
+ val alt: String? = null,
63
+ val callId: String? = null,
64
+ val deleted: Boolean? = null,
65
+ val deletedReason: String? = null
66
+ )
67
+ data class EventError(
68
+ val code: String,
69
+ val category: ErrorCategory,
70
+ val message: String,
71
+ /** Integer seconds, present only on the hourly app-paid rate_limited refusal. */
72
+ val retryAfter: Long? = null
73
+ )
74
+ @ConsistentCopyVisibility
75
+ data class SendReceipt internal constructor(
76
+ val requestId: String,
77
+ val status: InputDisposition,
78
+ val seq: Long,
79
+ val error: EventError? = null
80
+ )
81
+ @ConsistentCopyVisibility
82
+ data class RequestResult internal constructor(
83
+ val id: String,
84
+ val status: InputDisposition,
85
+ val messages: List<MessageEnd>,
86
+ val gap: Boolean? = null,
87
+ val error: EventError? = null
88
+ )
89
+ data class InputEvent(
90
+ val id: String,
91
+ val seq: Long,
92
+ val firstSeq: Long,
93
+ val kind: InputKind,
94
+ val status: InputDisposition,
95
+ val at: String,
96
+ val text: String? = null,
97
+ val error: EventError? = null
98
+ )
99
+ data class MessageStart(
100
+ val id: String,
101
+ val seq: Long,
102
+ val firstSeq: Long,
103
+ val at: String
104
+ )
105
+ data class MessageDelta(
106
+ val id: String,
107
+ val text: String
108
+ )
109
+ data class MessageEnd(
110
+ val id: String,
111
+ val seq: Long,
112
+ val firstSeq: Long,
113
+ val at: String,
114
+ val status: MessageStatus,
115
+ val text: String,
116
+ val markers: List<String>,
117
+ val causedBy: List<String>,
118
+ val inReplyTo: List<String>,
119
+ val output: JsonElement? = null,
120
+ val error: EventError? = null
121
+ )
122
+ data class TurnEvent(
123
+ val id: String,
124
+ val inputs: List<String>,
125
+ val causedBy: List<String>,
126
+ val usage: JsonElement,
127
+ val cost: Double?,
128
+ val costStatus: String,
129
+ val model: String,
130
+ val at: String,
131
+ val purpose: TurnPurpose? = null,
132
+ /** Reported serving-provider label; absent when unavailable. Diagnostic only; never changes pricing or settlement. */
133
+ val provider: String? = null
134
+ )
135
+ data class ToolEvent(
136
+ val id: String,
137
+ val seq: Long,
138
+ val firstSeq: Long,
139
+ val origin: String,
140
+ val causedBy: List<String>,
141
+ val tool: String,
142
+ val key: String,
143
+ val args: JsonElement,
144
+ val status: String,
145
+ val cost: Double?,
146
+ val costStatus: String,
147
+ val startedAt: String,
148
+ val at: String,
149
+ val requestedBy: String? = null,
150
+ val delivered: JsonElement? = null,
151
+ val outputs: JsonElement? = null
152
+ )
153
+ data class StateEvent(
154
+ val status: AgentStatus,
155
+ val queued: Long,
156
+ val typing: Boolean,
157
+ val activity: String?,
158
+ val tools: List<String>? = null
159
+ )
160
+ data class SnapshotEvent(
161
+ val logId: String,
162
+ val state: JsonElement,
163
+ val streaming: JsonElement
164
+ )
165
+ data class PageEvent(
166
+ val messages: List<AgentEvent>,
167
+ val reachedFloor: Boolean,
168
+ val logId: String,
169
+ val clearedSeq: Long
170
+ )
171
+ data class ClearedEvent(
172
+ val id: String,
173
+ val at: String
174
+ )
175
+ data class MemoryEvent(
176
+ val id: String,
177
+ val op: MemoryOp,
178
+ val at: String,
179
+ val item: String? = null,
180
+ val enabled: Boolean? = null,
181
+ val removed: Long? = null
182
+ )
183
+ data class GapEvent(
184
+ val afterSeq: Long,
185
+ val throughSeq: Long,
186
+ val reason: String
187
+ )
188
+ data class SubscriptionError(
189
+ val code: String,
190
+ val message: String,
191
+ val poisoned: Boolean? = null
192
+ )
193
+ class ReplacedEvent
194
+ sealed interface AgentEvent {
195
+ data class InputEventEvent(val value: AppStreamContract.InputEvent): AgentEvent
196
+ data class MessageStartEvent(val value: AppStreamContract.MessageStart): AgentEvent
197
+ data class MessageDeltaEvent(val value: AppStreamContract.MessageDelta): AgentEvent
198
+ data class MessageEndEvent(val value: AppStreamContract.MessageEnd): AgentEvent
199
+ data class TurnEventEvent(val value: AppStreamContract.TurnEvent): AgentEvent
200
+ data class ToolEventEvent(val value: AppStreamContract.ToolEvent): AgentEvent
201
+ data class StateEventEvent(val value: AppStreamContract.StateEvent): AgentEvent
202
+ data class SnapshotEventEvent(val value: AppStreamContract.SnapshotEvent): AgentEvent
203
+ data class PageEventEvent(val value: AppStreamContract.PageEvent): AgentEvent
204
+ data class ClearedEventEvent(val value: AppStreamContract.ClearedEvent): AgentEvent
205
+ data class MemoryEventEvent(val value: AppStreamContract.MemoryEvent): AgentEvent
206
+ data class GapEventEvent(val value: AppStreamContract.GapEvent): AgentEvent
207
+ data class SubscriptionErrorEvent(val value: AppStreamContract.SubscriptionError): AgentEvent
208
+ data class ReplacedEventEvent(val value: AppStreamContract.ReplacedEvent): AgentEvent
209
+ data class Unknown(val type: String, val fields: JsonObject): AgentEvent
210
+ }
211
+ private class StringReaderAdapter<T>(val read: (String) -> T, val write: (T) -> String): JsonDeserializer<T>, JsonSerializer<T> {
212
+ override fun deserialize(json: JsonElement, type: java.lang.reflect.Type, context: JsonDeserializationContext): T = read(json.asString)
213
+ override fun serialize(value: T, type: java.lang.reflect.Type, context: JsonSerializationContext): JsonElement = JsonPrimitive(write(value))
214
+ }
215
+ private val gson: Gson = GsonBuilder()
216
+ .registerTypeAdapter(InputDisposition::class.java, StringReaderAdapter<InputDisposition>({ value -> when (value) {
217
+ "queued" -> InputDisposition.QUEUED
218
+ "seen" -> InputDisposition.SEEN
219
+ "answered" -> InputDisposition.ANSWERED
220
+ "no_reply" -> InputDisposition.NO_REPLY
221
+ "failed" -> InputDisposition.FAILED
222
+ "cancelled" -> InputDisposition.CANCELLED
223
+ else -> InputDisposition.Unknown(value, JsonPrimitive(value))
224
+ } }, { it.rawValue }))
225
+ .registerTypeAdapter(InputKind::class.java, StringReaderAdapter<InputKind>({ value -> when (value) {
226
+ "user" -> InputKind.USER
227
+ "app_event" -> InputKind.APP_EVENT
228
+ "app_state" -> InputKind.APP_STATE
229
+ else -> InputKind.Unknown(value, JsonPrimitive(value))
230
+ } }, { it.rawValue }))
231
+ .registerTypeAdapter(MessageStatus::class.java, StringReaderAdapter<MessageStatus>({ value -> when (value) {
232
+ "completed" -> MessageStatus.COMPLETED
233
+ "failed" -> MessageStatus.FAILED
234
+ "cancelled" -> MessageStatus.CANCELLED
235
+ "interrupted" -> MessageStatus.INTERRUPTED
236
+ else -> MessageStatus.Unknown(value, JsonPrimitive(value))
237
+ } }, { it.rawValue }))
238
+ .registerTypeAdapter(AgentStatus::class.java, StringReaderAdapter<AgentStatus>({ value -> when (value) {
239
+ "idle" -> AgentStatus.IDLE
240
+ "running" -> AgentStatus.RUNNING
241
+ "waiting" -> AgentStatus.WAITING
242
+ else -> AgentStatus.Unknown(value, JsonPrimitive(value))
243
+ } }, { it.rawValue }))
244
+ .registerTypeAdapter(TurnPurpose::class.java, StringReaderAdapter<TurnPurpose>({ value -> when (value) {
245
+ "summary" -> TurnPurpose.SUMMARY
246
+ else -> TurnPurpose.Unknown(value, JsonPrimitive(value))
247
+ } }, { it.rawValue }))
248
+ .registerTypeAdapter(MemoryOp::class.java, StringReaderAdapter<MemoryOp>({ value -> when (value) {
249
+ "delete" -> MemoryOp.DELETE
250
+ "clear" -> MemoryOp.CLEAR
251
+ "enabled" -> MemoryOp.ENABLED
252
+ else -> MemoryOp.Unknown(value, JsonPrimitive(value))
253
+ } }, { it.rawValue }))
254
+ .registerTypeAdapter(AgentEvent::class.java, JsonDeserializer<AgentEvent> { json, _, _ -> decode(json.asJsonObject) }).create()
255
+ fun decode(value: JsonObject): AgentEvent = when (value.get("type").asString) {
256
+ "input" -> AgentEvent.InputEventEvent(gson.fromJson(value, InputEvent::class.java))
257
+ "message.start" -> AgentEvent.MessageStartEvent(gson.fromJson(value, MessageStart::class.java))
258
+ "message.delta" -> AgentEvent.MessageDeltaEvent(gson.fromJson(value, MessageDelta::class.java))
259
+ "message.end" -> AgentEvent.MessageEndEvent(gson.fromJson(value, MessageEnd::class.java))
260
+ "turn" -> AgentEvent.TurnEventEvent(gson.fromJson(value, TurnEvent::class.java))
261
+ "tool" -> AgentEvent.ToolEventEvent(gson.fromJson(value, ToolEvent::class.java))
262
+ "state" -> AgentEvent.StateEventEvent(gson.fromJson(value, StateEvent::class.java))
263
+ "snapshot" -> AgentEvent.SnapshotEventEvent(gson.fromJson(value, SnapshotEvent::class.java))
264
+ "page" -> AgentEvent.PageEventEvent(gson.fromJson(value, PageEvent::class.java))
265
+ "cleared" -> AgentEvent.ClearedEventEvent(gson.fromJson(value, ClearedEvent::class.java))
266
+ "memory" -> AgentEvent.MemoryEventEvent(gson.fromJson(value, MemoryEvent::class.java))
267
+ "gap" -> AgentEvent.GapEventEvent(gson.fromJson(value, GapEvent::class.java))
268
+ "error" -> AgentEvent.SubscriptionErrorEvent(gson.fromJson(value, SubscriptionError::class.java))
269
+ "replaced" -> AgentEvent.ReplacedEventEvent(gson.fromJson(value, ReplacedEvent::class.java))
270
+ else -> AgentEvent.Unknown(value.get("type").asString, value.deepCopy())
271
+ }
272
+ internal fun decodeSendReceipt(value: JsonObject): SendReceipt = gson.fromJson(value, SendReceipt::class.java)
273
+ internal fun decodeRequestResult(value: JsonObject): RequestResult = gson.fromJson(value, RequestResult::class.java)
274
+ /** The ONE closed set (APP-API): Core attaches it to every code, and a value outside it does not decode. */
275
+ @JsonAdapter(ErrorCategoryAdapter::class, nullSafe = false)
276
+ enum class ErrorCategory { OFFLINE, ALLOWANCE, PAUSED, SETUP, CLOSED, INVALID, INTERNAL }
277
+ private class ErrorCategoryAdapter: TypeAdapter<ErrorCategory>() {
278
+ override fun read(input: JsonReader): ErrorCategory {
279
+ if (input.peek() != JsonToken.STRING) throw JsonParseException("ErrorCategory must be a string.")
280
+ return when (input.nextString()) {
281
+ "offline" -> ErrorCategory.OFFLINE
282
+ "allowance" -> ErrorCategory.ALLOWANCE
283
+ "paused" -> ErrorCategory.PAUSED
284
+ "setup" -> ErrorCategory.SETUP
285
+ "closed" -> ErrorCategory.CLOSED
286
+ "invalid" -> ErrorCategory.INVALID
287
+ "internal" -> ErrorCategory.INTERNAL
288
+ else -> throw JsonParseException("Unknown ErrorCategory.")
289
+ }
290
+ }
291
+ override fun write(output: JsonWriter, value: ErrorCategory) {
292
+ output.value(when (value) {
293
+ ErrorCategory.OFFLINE -> "offline"
294
+ ErrorCategory.ALLOWANCE -> "allowance"
295
+ ErrorCategory.PAUSED -> "paused"
296
+ ErrorCategory.SETUP -> "setup"
297
+ ErrorCategory.CLOSED -> "closed"
298
+ ErrorCategory.INVALID -> "invalid"
299
+ ErrorCategory.INTERNAL -> "internal"
300
+ })
301
+ }
302
+ }
303
+ internal fun errorCategory(code: String): ErrorCategory {
304
+ if (Regex("^http_[1-5][0-9]{2}$").matches(code)) return ErrorCategory.OFFLINE
305
+ return when (code) {
306
+ "offline", "network_error", "request_timeout", "gateway_unavailable", "invalid_cloud_response", "stale_control", "http_<status>" -> ErrorCategory.OFFLINE
307
+ "account_credit_exhausted", "project_budget_exhausted", "user_allowance_exhausted", "development_allowance_exhausted", "unverified_allowance_exhausted", "gateway_key_exhausted", "provider_credit_unavailable" -> ErrorCategory.ALLOWANCE
308
+ "usage_paused", "runtime_blocked", "project_access_disabled", "account_disabled", "server_key_revoked", "debug_token_revoked", "rate_limited", "provider_rate_limited" -> ErrorCategory.PAUSED
309
+ "allowance_grants_disabled", "invalid_configuration", "model_missing", "model_withdrawn", "model_unavailable", "project_key_unknown", "server_key_invalid", "debug_token_invalid", "user_required", "gateway_key_rejected", "gateway_unsupported", "schema_unsupported", "capability_unsupported", "invalid_snapshot", "snapshot_mismatch", "invalid_tool", "invalid_wiki", "installation_unverified", "attestation_required", "attestation_rejected", "attestation_unverifiable", "attestation_failed", "attestation_unavailable", "attestation_unsupported", "attestation_timeout", "recovery_required", "host_unavailable", "core_unavailable" -> ErrorCategory.SETUP
310
+ "outcome_unknown", "closed", "target_closed", "runtime_detached", "cancelled", "interrupted", "preempted", "aborted", "observation_lost", "store_busy", "instance_busy" -> ErrorCategory.CLOSED
311
+ "invalid_input", "input_too_large", "invalid_memory", "invalid_response_format", "invalid_request", "tool_unauthorized", "agent_conflict", "unknown_id", "idempotency_conflict", "identity_conflict", "busy", "queue_full", "cursor_reset", "context_limit", "output_limit", "iteration_limit", "structured_output_unsupported" -> ErrorCategory.INVALID
312
+ "failure_unrecorded", "internal", "asset_read_failed", "stream_incomplete", "provider_error", "provider_rejected", "invalid_provider_response", "invalid_response", "output_too_large", "output_invalid", "empty_response", "unexpected_tool_call", "storage_error", "store_refused", "store_full", "corrupt_store", "store_too_new", "fresh_reservation_lost", "archive_unavailable", "archive_error", "host_error", "host_unresponsive", "thread_unavailable", "core_error", "invalid_abi", "no_lock", "handler_failed", "subscriber_overflow" -> ErrorCategory.INTERNAL
313
+ else -> ErrorCategory.INTERNAL
314
+ }
315
+ }
316
+ internal fun representationErrorCategory(code: String): ErrorCategory = when (code) {
317
+ "invalid_configuration" -> ErrorCategory.SETUP
318
+ "invalid_input" -> ErrorCategory.INVALID
319
+ "invalid_tool_result" -> ErrorCategory.INVALID
320
+ else -> errorCategory(code)
321
+ }
322
+ }
@@ -2,6 +2,8 @@ package dev.croche
2
2
 
3
3
  import com.google.gson.*
4
4
  import dev.croche.ffi.*
5
+ import dev.croche.s7.attached
6
+ import dev.croche.s7.hostCallback
5
7
  import java.lang.ref.WeakReference
6
8
  import java.util.Collections
7
9
  import java.util.TimeZone
@@ -23,12 +25,12 @@ private const val NOT_DISPATCHED = "tool_not_dispatched"
23
25
  /** Shared SDK/RN parser: TimeZone.getTimeZone(String) silently accepts unknown ids as GMT. */
24
26
  internal fun projectTimeZone(id: String?): TimeZone? = id?.let {
25
27
  try { TimeZone.getTimeZone(java.time.ZoneId.of(it)) }
26
- catch (_: Exception) { throw CrocheException("invalid_configuration", "timeZone must be an IANA time zone") }
28
+ catch (_: Exception) { throw CrocheError("invalid_configuration", "timeZone must be an IANA time zone") }
27
29
  }
28
30
 
29
31
  internal fun failure(error: Throwable): FfiException = when (error) {
30
32
  is FfiException -> error
31
- is CrocheException -> FfiException.Failure(error.code, error.message)
33
+ is CrocheError -> FfiException.Failure(error.code, error.message)
32
34
  else -> FfiException.Failure("host_error", "The host operation failed")
33
35
  }
34
36
  /** `request_timeout.SocketTimeoutException`, `network_error.SocketException`, …: a call code and the class. */
@@ -37,28 +39,21 @@ internal fun transportCode(error: java.io.IOException): String {
37
39
  val name = error.javaClass.simpleName.filter { it.isLetterOrDigit() || it == '_' }.take(60)
38
40
  return if (name.isEmpty()) base else "$base.$name"
39
41
  }
40
- internal fun crocheError(error: Throwable): CrocheException = when (error) {
41
- is CrocheException -> error
42
- is FfiException.Failure -> CrocheException(error.code, error.detail)
43
- else -> CrocheException("host_error", "The host operation failed")
42
+ internal fun crocheError(error: Throwable): CrocheError = when (error) {
43
+ is CrocheError -> error
44
+ is FfiException.Failure -> CrocheError(error.code, error.detail)
45
+ else -> CrocheError("host_error", "The host operation failed")
44
46
  }
45
47
 
46
- /** The Runtime calls this host on its own worker threads, which JNA attaches for the length of
47
- * one callback. A callback that calls back into the Runtime (a sink fed on the callback's stack,
48
- * an observer that inspects) nests a second callback on that thread, and JNA's default detaches
49
- * after the inner one while the outer one is still running: "JNA: could not detach thread".
50
- * Keeping the thread attached until it exits avoids that; the worker threads are short-lived. */
51
- internal fun keepAttached() = com.sun.jna.Native.detach(false)
52
48
 
53
49
  /** A Runtime cancellation, tied to the token the Runtime handed this effect. */
54
50
  private fun signal(token: CancelToken): RuntimeCancellation = RuntimeCancellation().also { signal ->
55
- token.onCancel(object : CancelCallback { override fun cancelled() = signal.cancel() })
51
+ token.onCancel(attached(object : CancelCallback { override fun cancelled() = signal.cancel() }))
56
52
  }
57
53
 
58
54
  internal class EventHook(private val callback: (JsonElement) -> Unit) : EventListener {
59
- override fun onEvent(event: String) {
60
- keepAttached()
61
- val value = try { JsonParser.parseString(event) } catch (_: Exception) { return }
55
+ override fun onEvent(event: String) = hostCallback {
56
+ val value = try { JsonParser.parseString(event) } catch (_: Exception) { return@hostCallback }
62
57
  try { callback(value) } catch (_: Exception) {}
63
58
  }
64
59
  }
@@ -92,6 +87,11 @@ internal class KotlinHost(
92
87
  private val user: String? = null,
93
88
  private val timeZone: TimeZone? = null
94
89
  ) : HostPal {
90
+ // This legacy host has no process-wide OS registrar. Its per-Runtime
91
+ // scheduler must not claim the fixed Core background registration succeeded.
92
+ override fun registerBackground(identifier: String, wake: CoreBackgroundWake) {
93
+ throw CorePalException.Failure("capability_unsupported", "This host has no OS background registrar.")
94
+ }
95
95
  private val projectRecords = ProjectRecords { projectRecordDirectory(projectDirectory, defaultDirectory()) }
96
96
  internal var beforeProjectLock: (() -> Unit)? = null
97
97
  internal var afterProjectRead: ((String?) -> Unit)? = null
@@ -119,6 +119,11 @@ internal class KotlinHost(
119
119
  fun acceptTools(tools: Map<String, ToolHandler>) = synchronized(lock) {
120
120
  handlers = handlers + tools; tools.keys.forEach { staged.remove(it) }
121
121
  }
122
+ /** A project instance's latest successful patched open: its table replaces the old one for future
123
+ * invocations, as in TypeScript. A call already running keeps the handler it started with. */
124
+ fun replaceTools(tools: Map<String, ToolHandler>) = synchronized(lock) {
125
+ handlers = tools; staged.clear()
126
+ }
122
127
  private val effects = EffectExecutor()
123
128
  private val tools = ToolExecutor()
124
129
  private val identity = identities.getOrPut(storage) { "kotlin:" + UUID.randomUUID() }
@@ -141,10 +146,40 @@ internal class KotlinHost(
141
146
  private var dueTimer: ScheduledFuture<*>? = null
142
147
  private var deliveries: ScheduledExecutorService? = null
143
148
 
144
- private inline fun <T> host(body: () -> T): T = try { keepAttached(); body() } catch (error: Exception) { throw failure(error) }
149
+ private inline fun <T> host(body: () -> T): T = try { body() } catch (error: Exception) { throw failure(error) }
150
+
151
+ internal val images = NativeImagePal()
152
+ private val decodedImages = platformDecodedImageCodec()
153
+ override fun streamPlatform(): HostStreamPlatform = HostStreamPlatform.OTHER
154
+ override fun imageCodecAvailable(): Boolean = decodedImages != null
155
+ override fun decodeImage(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken): PalDecodedImage = host {
156
+ (decodedImages ?: throw NativeImagePal.failure("image_unsupported")).decode(bytes, options, cancel)
157
+ }
158
+ override fun renderImage(request: PalImageRenderRequest, cancel: CancelToken): ByteArray = host {
159
+ (decodedImages ?: throw NativeImagePal.failure("image_unsupported")).render(request, cancel)
160
+ }
161
+ override fun releaseDecodedImage(handle: String) { decodedImages?.release(handle) }
162
+ override fun readImage(request: PalImageReadRequest, cancel: CancelToken): ByteArray = host { images.readBytes(request, cancel) }
163
+ override fun prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken): PalImageBytes =
164
+ host { images.prepare(source, plan, cancel) }
165
+ override fun releaseImage(capture: String) { images.release(capture) }
166
+
167
+ // Transitional legacy host extensions. S2's dedicated platform adapter supplies assets/list.
168
+ override fun platformFacts(): PalPlatformFacts = PalPlatformFacts(PalTargetKind.OTHER, null, java.util.Locale.getDefault().toLanguageTag(), null, false)
169
+ override fun readAsset(path: String): ByteArray? = host {
170
+ throw CrocheError("capability_unsupported", "App assets require the S2 platform PAL")
171
+ }
172
+ override fun list(prefix: String): List<String> = host {
173
+ throw CrocheError("capability_unsupported", "Key listing requires the S2 platform PAL")
174
+ }
175
+ override fun resolve(host: String, cancel: CancelToken): List<String> = this.host {
176
+ dev.croche.s7.pal.DirectHttpPal().resolve(host, signal(cancel))
177
+ }
145
178
 
146
179
  // HTTP
147
180
  override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) = host {
181
+ if (request.connectTo != null) throw CrocheError("capability_unsupported", "Pinned HTTP requires the S2 platform PAL")
182
+ if (request.responseMode != "standard") throw CrocheError("image_unsupported", "Native image inputs are not supported yet")
148
183
  try {
149
184
  effects.run(request.timeoutMs.toLong(), signal(cancel)) { local ->
150
185
  if (transport is RuntimeHttpURLConnection) transport.stream(request, sink, local) else adapt(request, sink, local)
@@ -153,7 +188,7 @@ internal class KotlinHost(
153
188
  } catch (error: java.io.IOException) {
154
189
  // The call keeps a Runtime code; what failed underneath rides along as its class name
155
190
  // (never the message, which may name hosts): Logs then say why (dev, 2026-10-05).
156
- throw CrocheException(transportCode(error), "The HTTP transport failed")
191
+ throw CrocheError(transportCode(error), "The HTTP transport failed")
157
192
  }
158
193
  Unit
159
194
  }
@@ -161,9 +196,8 @@ internal class KotlinHost(
161
196
  /** An app transport speaks whole effects (`RuntimeHTTP`): its answer goes to the Runtime as
162
197
  * a response, and its stream deltas as server-sent events. */
163
198
  internal fun adapt(request: PalHttpRequest, sink: HttpSink, signal: RuntimeCancellation) {
164
- keepAttached()
165
199
  val headers = JsonObject().apply { request.headers.forEach { addProperty(it.name, it.value) } }
166
- val body = try { JsonParser.parseString(request.body) } catch (_: Exception) { str(request.body) }
200
+ val body = request.body?.let { value -> try { JsonParser.parseString(value) } catch (_: Exception) { str(value) } } ?: JsonNull.INSTANCE
167
201
  val effect = obj("url" to str(request.url), "method" to str(request.method), "headers" to headers,
168
202
  "body" to body, "timeoutMs" to num(request.timeoutMs.toLong()))
169
203
  val started = AtomicBoolean(false)
@@ -193,11 +227,11 @@ internal class KotlinHost(
193
227
  private fun entry(key: String): String? {
194
228
  val main = snapshotKey ?: return null
195
229
  if (key == main) return null
196
- if (!key.startsWith("$main.") || key.length <= main.length + 1) throw CrocheException("storage_error", "Unknown storage key")
230
+ if (!key.startsWith("$main.") || key.length <= main.length + 1) throw CrocheError("storage_error", "Unknown storage key")
197
231
  return key.substring(main.length + 1)
198
232
  }
199
233
  private inline fun <T> projectIO(body: () -> T): T = try { body() }
200
- catch (_: java.io.IOException) { throw CrocheException("storage_error", "Could not access the project record") }
234
+ catch (_: java.io.IOException) { throw CrocheError("storage_error", "Could not access the project record") }
201
235
  override fun read(key: String): String? = host {
202
236
  if (isProjectKey(key)) return@host projectIO { projectRecords.read(key) }.also { afterProjectRead?.invoke(it) }
203
237
  val name = entry(key)
@@ -215,11 +249,11 @@ internal class KotlinHost(
215
249
  when {
216
250
  name == null -> storage.save(JsonParser.parseString(value))
217
251
  storage is KeyedRuntimeStorage -> storage.save(name, JsonParser.parseString(value))
218
- else -> throw CrocheException("storage_error", "This RuntimeStorage keeps only its snapshot")
252
+ else -> throw CrocheError("storage_error", "This RuntimeStorage keeps only its snapshot")
219
253
  }
220
254
  }
221
255
  override fun remove(key: String) = persist {
222
- if (isProjectKey(key)) throw CrocheException("storage_error", "The project record is kept when agent data is removed")
256
+ if (isProjectKey(key)) throw CrocheError("storage_error", "The project record is kept when agent data is removed")
223
257
  val name = entry(key)
224
258
  when {
225
259
  name == null -> storage.remove()
@@ -232,11 +266,12 @@ internal class KotlinHost(
232
266
  override fun readSecret(key: String): String? = host { secretStore.load().toString() }
233
267
  override fun writeSecret(key: String, value: String) = persist { secretStore.save(JsonParser.parseString(value).asJsonObject) }
234
268
  private fun persist(body: () -> Unit) = try { body() } catch (error: Exception) {
235
- throw if (error is CrocheException) failure(error) else FfiException.Failure("storage_error", "Could not persist Runtime state")
269
+ throw if (error is CrocheError) failure(error) else FfiException.Failure("storage_error", "Could not persist Runtime state")
236
270
  }
237
271
  override fun lock(key: String) = host {
238
272
  if (isProjectKey(key)) projectIO { beforeProjectLock?.invoke(); projectRecords.acquire(key) }
239
273
  else { storage.acquire(); snapshotKey = key }
274
+ PalLockOutcome.ACQUIRED
240
275
  }
241
276
  override fun unlock(key: String) {
242
277
  if (isProjectKey(key)) { projectRecords.release(key); return }
@@ -248,10 +283,10 @@ internal class KotlinHost(
248
283
  /** The storage's archive, or the typed "no archive": the Runtime then keeps none, and every
249
284
  * turn, clearHistory and memory work as before. */
250
285
  private fun <T> archive(body: (ArchiveRuntimeStorage) -> T): T = try {
251
- val archive = storage as? ArchiveRuntimeStorage ?: throw CrocheException("archive_unavailable", "This host keeps no turn archive.")
286
+ val archive = storage as? ArchiveRuntimeStorage ?: throw CrocheError("archive_unavailable", "This host keeps no turn archive.")
252
287
  body(archive)
253
288
  } catch (error: Exception) {
254
- throw if (error is CrocheException) failure(error) else FfiException.Failure("storage_error", "The turn archive could not be read or written")
289
+ throw if (error is CrocheError) failure(error) else FfiException.Failure("storage_error", "The turn archive could not be read or written")
255
290
  }
256
291
  override fun archiveAppendLine(entry: String, line: String) = archive { it.appendLine(entry, line) }
257
292
  override fun archiveReadLines(entry: String): List<String> = archive { it.readLines(entry) }
@@ -272,7 +307,7 @@ internal class KotlinHost(
272
307
  override fun tool(invocation: String, cancel: CancelToken): ToolOutput = host {
273
308
  val call = JsonParser.parseString(invocation)
274
309
  val name = call.at("tool").text()
275
- val handler = handlers[name] ?: throw CrocheException(NOT_DISPATCHED, "The host tool is not available")
310
+ val handler = handlers[name] ?: throw CrocheError(NOT_DISPATCHED, "The host tool is not available")
276
311
  val context = call.at("context")
277
312
  val request = CommandInvocation(name, call.at("command").text().ifEmpty { null }, call.at("key").text(),
278
313
  call.at("args").let { if (it.isJsonObject) it.asJsonObject.deepCopy() else JsonObject() })
@@ -280,10 +315,10 @@ internal class KotlinHost(
280
315
  // the handler does, so a stuck one keeps its slot (H1).
281
316
  val sink = ToolImages()
282
317
  val value = tools.run(signal(cancel)) { local ->
283
- handler.execute(request, ToolContext(context.at("callId").text(),
318
+ handler.execute(request, LegacyToolContext(context.at("callId").text(),
284
319
  context.at("messageId").text(), context.at("userId").text(), local,
285
320
  context.at("agentId").text().ifEmpty { null }, sink,
286
- user, context.at("userId").text().ifEmpty { null },
321
+ user,
287
322
  context.at("causedBy").let { if (it.isJsonArray) it.asJsonArray.map { id -> id.asString } else emptyList() },
288
323
  context.at("origin").text().ifEmpty { "app" }))
289
324
  }
@@ -292,11 +327,11 @@ internal class KotlinHost(
292
327
  ToolOutput(value.toString(), sink.images.map { CrocheImages.record(it) })
293
328
  }
294
329
  override fun attest(request: String, timeoutMs: ULong): String = host {
295
- val platform = attestor ?: throw CrocheException("attestation_unsupported", "This host has no attestor")
330
+ val platform = attestor ?: throw CrocheError("attestation_unsupported", "This host has no attestor")
296
331
  val effect = JsonParser.parseString(request)
297
332
  val clientData = effect.at("clientData").text()
298
333
  val hash = effect.at("clientDataHash").text()
299
- if (clientData.isEmpty() || hash.isEmpty()) throw CrocheException("invalid_abi", "Malformed attest effect")
334
+ if (clientData.isEmpty() || hash.isEmpty()) throw CrocheError("invalid_abi", "Malformed attest effect")
300
335
  effects.run(timeoutMs.toLong(), RuntimeCancellation()) { signal ->
301
336
  val proof = platform.attest(clientData, hash, signal)
302
337
  obj("platform" to str(platform.platform), "token" to str(proof.token),
@@ -333,8 +368,8 @@ internal class KotlinHost(
333
368
  armDelivery()
334
369
  val os = osScheduler ?: return
335
370
  try { if (at == null) os.cancel() else os.schedule(at) }
336
- catch (error: CrocheException) { throw error }
337
- catch (_: Exception) { throw CrocheException("schedule_failed", "The OS scheduler refused the request") }
371
+ catch (error: CrocheError) { throw error }
372
+ catch (_: Exception) { throw CrocheError("schedule_failed", "The OS scheduler refused the request") }
338
373
  }
339
374
  /** The Runtime is open: a wake it asked for while opening can now fire. */
340
375
  fun attach(core: CoreRuntime) { synchronized(lock) { this.core = WeakReference(core) }; arm(); armDelivery() }
@@ -343,6 +378,8 @@ internal class KotlinHost(
343
378
  stopped = true; timer?.cancel(false); timer = null; scheduler?.shutdown()
344
379
  dueTimer?.cancel(false); dueTimer = null; deliveries?.shutdown()
345
380
  }
381
+ images.close()
382
+ decodedImages?.close()
346
383
  val release = synchronized(lock) { osAttached.also { osAttached = false } }
347
384
  if (release) try { osScheduler?.detach() } catch (_: Exception) {}
348
385
  }