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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a
3
- size: 37950976 bytes
4
- sha256: 1b910d91be50fb46d31f10bb8349115b2bd9487b5216ae31e707e0db9be51690
3
+ size: 49566328 bytes
4
+ sha256: 7c0e254abf63f9a0bb1dbb955bd3d4c3d05279e1d3262cd75a43566a403d0396
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@h1r-ai/croche-react-native",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -21,11 +21,11 @@
21
21
  "THIRD-PARTY-NOTICES"
22
22
  ],
23
23
  "peerDependencies": {
24
- "@h1r-ai/croche": "0.6.0",
24
+ "@h1r-ai/croche": "0.7.0",
25
25
  "react-native": ">=0.76"
26
26
  },
27
27
  "devDependencies": {
28
- "@h1r-ai/croche": "0.6.0"
28
+ "@h1r-ai/croche": "0.7.0"
29
29
  },
30
30
  "codegenConfig": {
31
31
  "name": "CrocheRuntimeSpec",
package/scripts/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # RN shared-facade build
2
2
 
3
- `build-shared.mjs` compiles the canonical TypeScript facade from `packages/runtime/src` into the RN artifact. It does not keep an RN copy of those source files. Only `core/wasm.ts` is replaced. The explicit native entry withholds the optional decision method and its five types until a Mac/Android bridge witness passes (Keel #1187 6883440525). The RN entry selects the native platform and the narrowed native declarations; the public facade and tool brand use the same source.
3
+ `build-shared.mjs` compiles the canonical TypeScript facade from `packages/runtime/src` into the RN artifact. It does not keep an RN copy of those source files. Only `core/wasm.ts` is replaced. The native entry exports the same decision method and types; the optional Core capability forwards only through explicit native decide dispatch backed by host bridge acceptance. The RN entry selects the native platform and shared declarations; the public facade and tool brand use the same source.
4
4
 
5
5
  ```
6
6
  node packages/react-native/scripts/build-shared.mjs --adapter <native-adapter.ts> --out <empty-artifact-directory>
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env bash
2
+ # CocoaPods compiles these SPM sources and bindings into a single RN module.
3
+ set -euo pipefail
4
+ root=$(cd "$(dirname "$0")/../../.." && pwd)
5
+ sources=("$root/sdk/swift/Sources/CrocheRuntime")
6
+ bindings="$root/sdk/swift/Sources/CrocheFFI"
7
+ if [[ -d "$bindings" ]]; then sources+=("$bindings"); fi
8
+ if grep -rnE --include='*.swift' '(^|[^[:alnum:]_])(CrocheRuntime|CrocheFFI)[[:space:]]*\.' \
9
+ "${sources[@]}"; then
10
+ echo 'RN vendors these Swift sources into its own module. Call the SDK or binding helper unqualified.' >&2
11
+ exit 1
12
+ else
13
+ status=$?
14
+ if [[ $status != 1 ]]; then exit "$status"; fi
15
+ fi
@@ -13,6 +13,7 @@ what=${1:-all}
13
13
  if [[ $what == ios || $what == all ]]; then
14
14
  work=$(mktemp -d)
15
15
  CROCHE_SWIFT_OUTPUT="$work/out" "$root/sdk/swift/build-xcframework.sh"
16
+ bash "$package/scripts/check-swift-vendor-modules.sh"
16
17
  rm -rf "$package/ios/vendor"; mkdir -p "$package/ios/vendor"
17
18
  cp -R "$work/out/CrocheRuntime/croche_ffiFFI.xcframework" "$package/ios/vendor/"
18
19
  cp -R "$root/sdk/swift/Sources/CrocheRuntime" "$package/ios/vendor/CrocheRuntimeSDK"
@@ -21,9 +22,6 @@ if [[ $what == ios || $what == all ]]; then
21
22
  # Recursive: the App API sources live in a subfolder (S1/).
22
23
  find "$package/ios/vendor/CrocheRuntimeSDK" -name '*.swift' -exec sed -i.bak '/^import CrocheFFI$/d' {} +
23
24
  find "$package/ios/vendor/CrocheRuntimeSDK" -name '*.bak' -delete
24
- if grep -rq --include='*.swift' 'CrocheFFI\.' "$package/ios/vendor/CrocheRuntimeSDK"; then
25
- echo 'The SDK names the CrocheFFI module; the pod has none. Call the binding unqualified.' >&2; exit 1
26
- fi
27
25
  rm -rf "$work"
28
26
  echo "iOS: ios/vendor/croche_ffiFFI.xcframework and ios/vendor/CrocheRuntimeSDK ready; run pod install."
29
27
  fi
@@ -34,6 +32,9 @@ if [[ $what == android || $what == all ]]; then
34
32
  for target in aarch64-linux-android armv7-linux-androideabi x86_64-linux-android; do
35
33
  rustup target list --installed | grep -Fxq "$target" || { echo "rustup target add $target" >&2; exit 1; }
36
34
  done
35
+ "$root/sdk/kotlin/generate-bindings.sh"
36
+ bindings="$root/sdk/kotlin/src/main/kotlin/dev/croche/ffi/croche_ffi.kt"
37
+ [[ -s "$bindings" ]] || { echo "Missing Android Kotlin bindings: $bindings" >&2; exit 1; }
37
38
  rm -rf "$package/android/vendor"; mkdir -p "$package/android/vendor/CrocheRuntimeSDK"
38
39
  # The Android SDK sources (sdk/kotlin, with its UniFFI bindings) are compiled into the bridge
39
40
  # module; Gradle cannot reach sdk/ from node_modules, so they ship inside the package.
@@ -1,32 +0,0 @@
1
- package dev.croche.android
2
-
3
- import android.content.ContentProvider
4
- import android.content.ContentValues
5
- import android.database.Cursor
6
- import android.net.Uri
7
- import java.io.File
8
-
9
- /** Internal Android startup hook: the install's records use filesDir, regardless of its stores. */
10
- internal class CrocheProjectRecordProvider : ContentProvider() {
11
- override fun onCreate(): Boolean {
12
- app = context?.applicationContext
13
- location = app?.filesDir
14
- return true
15
- }
16
- override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
17
- override fun getType(uri: Uri): String? = null
18
- override fun insert(uri: Uri, values: ContentValues?): Uri? = null
19
- override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
20
- override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
21
-
22
- companion object {
23
- @Volatile private var app: android.content.Context? = null
24
- @Volatile private var location: File? = null
25
- @JvmStatic fun directory(): File? = location
26
- @JvmStatic fun language(): String = android.os.LocaleList.getDefault()[0].toLanguageTag()
27
- @JvmStatic fun secretStorage(name: String): dev.croche.RuntimeSecretStore =
28
- KeystoreSecretStore(checkNotNull(app) { "Croche startup provider is not initialized" }, name)
29
- @JvmStatic fun attestor(number: Long): dev.croche.RuntimeAttestor =
30
- PlayIntegrityAttestor(checkNotNull(app) { "Croche startup provider is not initialized" }, number)
31
- }
32
- }
@@ -1,146 +0,0 @@
1
- package dev.croche.android
2
-
3
- import android.app.Activity
4
- import android.app.Application
5
- import android.content.Context
6
- import android.os.Bundle
7
- import androidx.work.Constraints
8
- import androidx.work.Data
9
- import androidx.work.NetworkType
10
- import androidx.work.OneTimeWorkRequestBuilder
11
- import androidx.work.WorkInfo
12
- import androidx.work.WorkManager
13
- import androidx.work.Worker
14
- import androidx.work.WorkerParameters
15
- import dev.croche.CrocheError
16
- import dev.croche.LegacyAgentEngine
17
- import dev.croche.RuntimeCancellation
18
- import dev.croche.RuntimeScheduler
19
- import java.util.concurrent.TimeUnit
20
-
21
- // The agent's scheduled notes on Android while the app is not running (founder 17:14Z): one
22
- // waiting WorkManager request per Runtime, at the earliest note. Inexact: WorkManager runs it at
23
- // or after its delay, when the device allows (Doze, App Standby buckets), with network. No exact
24
- // alarms, no notifications, no permissions, no manifest entries.
25
- // CI compiles it in the AAR job, and runs the scheduler against the real WorkManager on an
26
- // emulator (examples/android-aar-sample, WorkManagerSchedulerTest); a delivery run needs a device.
27
-
28
- /**
29
- * Registers the earliest pending note as one `OneTimeWorkRequest`, tagged with `name`, whose
30
- * worker runs `deliverDue()`. Pass it to `LegacyAgentEngine.create(..., scheduler = ...)`, and call
31
- * `WorkManagerScheduler.install(application, name)` once in `Application.onCreate` so a run can
32
- * reach that Runtime.
33
- *
34
- * A registration replaces only requests that are still waiting: it never cancels a run in
35
- * progress, so a run that re-registers what is left (or whose delivery changes the pending set)
36
- * never stops itself (rook, #323 A). Each Runtime uses its own `name`, and its runs deliver
37
- * through the Runtime installed for that name; a second open Runtime with the same name is
38
- * refused (`scheduler_conflict`), including a second Runtime given this same object.
39
- */
40
- internal class WorkManagerScheduler(context: Context, val name: String = DEFAULT_NAME) : RuntimeScheduler {
41
- private val context = context.applicationContext
42
-
43
- override fun schedule(earliestAtMs: Long) = synchronized(lockFor(name)) {
44
- val manager = manager()
45
- val request = OneTimeWorkRequestBuilder<CrocheDeliveryWorker>()
46
- .setInitialDelay((earliestAtMs - System.currentTimeMillis()).coerceAtLeast(0), TimeUnit.MILLISECONDS)
47
- .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
48
- .setInputData(Data.Builder().putString(KEY_NAME, name).build())
49
- .addTag(tag(name))
50
- .build()
51
- withdrawWaiting(manager)
52
- manager.enqueue(request)
53
- Unit
54
- }
55
-
56
- override fun cancel() = synchronized(lockFor(name)) { withdrawWaiting(manager()) }
57
-
58
- /** One open Runtime per name, this scheduler object included: `create` attaches once per
59
- * Runtime, so a second attach while the name is held (by another object, or by this one for
60
- * another open Runtime) is refused (Atlas, #323 at dc38bf0). Close-and-reuse stays valid. */
61
- override fun attach() = claims.claim(name, this)
62
-
63
- override fun detach() = claims.release(name, this)
64
-
65
- /** Cancels this name's requests that are waiting (enqueued, or blocked), never one that runs. */
66
- private fun withdrawWaiting(manager: WorkManager) {
67
- val infos = try { manager.getWorkInfosByTag(tag(name)).get() } catch (_: Exception) { emptyList() }
68
- for (id in waiting(infos.map { it.id to it.state })) manager.cancelWorkById(id)
69
- }
70
-
71
- private fun manager(): WorkManager = try { WorkManager.getInstance(context) }
72
- // The app turned WorkManager's initializer off without providing a Configuration.
73
- catch (_: IllegalStateException) { throw CrocheError("not_configured", "WorkManager is not initialized in this app") }
74
-
75
- companion object {
76
- const val DEFAULT_NAME = "croche.schedule"
77
- internal const val KEY_NAME = "dev.croche.schedule.name"
78
- private val claims = dev.croche.SchedulerClaims("WorkManager name")
79
- private val locks = java.util.concurrent.ConcurrentHashMap<String, Any>()
80
- private fun lockFor(name: String) = locks.getOrPut(name) { Any() }
81
- internal val providers = java.util.concurrent.ConcurrentHashMap<String, (Context) -> LegacyAgentEngine?>()
82
-
83
- /** The tag that marks `name`'s requests. */
84
- fun tag(name: String) = "dev.croche.schedule:$name"
85
-
86
- /** Of these requests, the ones a registration may cancel: those still waiting. Never a
87
- * running one, which may be the very run registering. */
88
- fun <T> waiting(requests: List<Pair<T, WorkInfo.State>>): List<T> =
89
- requests.filter { (_, state) -> state == WorkInfo.State.ENQUEUED || state == WorkInfo.State.BLOCKED }.map { it.first }
90
-
91
- /** What `name`'s WorkManager runs deliver through: the app's Runtime, opened if need be,
92
- * or null when there is none to reach (the run ends; the next open delivers). A run never
93
- * closes it. */
94
- fun deliverThrough(name: String = DEFAULT_NAME, runtime: (Context) -> LegacyAgentEngine?) { providers[name] = runtime }
95
-
96
- /**
97
- * `deliverThrough(name, runtime)`, and a delivery at each return to the foreground (the
98
- * first activity started), off the main thread. Call once per name in
99
- * `Application.onCreate`.
100
- */
101
- fun install(application: Application, name: String = DEFAULT_NAME, runtime: (Context) -> LegacyAgentEngine) {
102
- deliverThrough(name, runtime)
103
- application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
104
- private var started = 0
105
- override fun onActivityStarted(activity: Activity) {
106
- if (started++ == 0) Thread({ try { runtime(application).deliverDue() } catch (_: Exception) {} }, "croche-foreground").start()
107
- }
108
- override fun onActivityStopped(activity: Activity) { started = (started - 1).coerceAtLeast(0) }
109
- override fun onActivityCreated(activity: Activity, state: Bundle?) {}
110
- override fun onActivityResumed(activity: Activity) {}
111
- override fun onActivityPaused(activity: Activity) {}
112
- override fun onActivitySaveInstanceState(activity: Activity, state: Bundle) {}
113
- override fun onActivityDestroyed(activity: Activity) {}
114
- })
115
- }
116
- }
117
- }
118
-
119
- /**
120
- * One WorkManager run: `deliverDue()` through the Runtime installed for its name.
121
- *
122
- * It always ends `success`: the Runtime has already registered what is still pending (a request
123
- * of its own, never this one), so a WorkManager retry would only add a second request. A
124
- * delivery already in flight (`inFlight`) ends it at once, with nothing registered: the
125
- * delivery in flight registers what is left when it ends (rook, #323 B). Only a Runtime that
126
- * could not be opened asks WorkManager to retry.
127
- *
128
- * When WorkManager stops the run (its time is up, or the constraints are lost), this run's own
129
- * delivery is cancelled, whether it is waiting behind another turn or running: never another
130
- * turn of the Runtime. Its notes stay pending, and registered.
131
- */
132
- class CrocheDeliveryWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
133
- private val cancellation = RuntimeCancellation()
134
-
135
- override fun doWork(): Result {
136
- val name = inputData.getString(WorkManagerScheduler.KEY_NAME) ?: WorkManagerScheduler.DEFAULT_NAME
137
- // Not installed for this name: the next open delivers.
138
- val open = WorkManagerScheduler.providers[name] ?: return Result.success()
139
- val runtime = try { open(applicationContext) } catch (_: Exception) { return Result.retry() } ?: return Result.success()
140
- if (isStopped) return Result.success()
141
- try { runtime.deliverDue(cancellation) } catch (_: Exception) { /* registered again by the Runtime */ }
142
- return Result.success()
143
- }
144
-
145
- override fun onStopped() { cancellation.cancel() }
146
- }
@@ -1,113 +0,0 @@
1
- package dev.croche
2
-
3
- import com.google.gson.GsonBuilder
4
- import com.google.gson.TypeAdapter
5
- import com.google.gson.stream.JsonReader
6
- import com.google.gson.stream.JsonWriter
7
- import kotlinx.coroutines.channels.Channel
8
- import java.time.Instant
9
-
10
- /** Isolated serial delivery, bounded including the event currently in the collector. */
11
- internal class AppStreamBranch {
12
- private data class Item(val event: RuntimeEvent, val bytes: Int)
13
- private val lock = Any()
14
- private val wake = Channel<Unit>(Channel.CONFLATED)
15
- private val queue = ArrayDeque<Item>()
16
- private var count = 0
17
- private var bytes = 0
18
- private var ended = false
19
- private var terminal: RuntimeEvent? = null
20
- val isEnded get() = synchronized(lock) { ended }
21
-
22
- /** Core-delivered events stay ordered, including a final StreamError behind the backlog. */
23
- fun push(event: RuntimeEvent) = synchronized(lock) {
24
- if (ended) return@synchronized
25
- val item = try {
26
- val json = event.serialized()
27
- Item(event.owned(), json.toByteArray(Charsets.UTF_8).size)
28
- } catch (failure: Exception) {
29
- end(RuntimeEvent.StreamError("handler_failed", "Event could not be queued", false))
30
- return@synchronized
31
- }
32
- if (count + 1 > 256 || bytes.toLong() + item.bytes > 1_048_576) {
33
- end(RuntimeEvent.StreamError("subscriber_overflow", "Collector fell behind", false))
34
- return@synchronized
35
- }
36
- queue.addLast(item)
37
- count++
38
- bytes += item.bytes
39
- if (event is RuntimeEvent.StreamError || event === RuntimeEvent.Replaced) ended = true
40
- wake.trySend(Unit)
41
- }
42
- /** SDK-side termination drops queued work; an in-flight delivery settles before last. */
43
- fun end(last: RuntimeEvent? = null) = synchronized(lock) {
44
- if (ended) return@synchronized
45
- ended = true
46
- queue.clear()
47
- terminal = last
48
- wake.trySend(Unit)
49
- }
50
- fun close() = end()
51
-
52
- suspend fun deliver(emit: suspend (RuntimeEvent) -> Unit) {
53
- while (true) {
54
- val delivery = synchronized(lock) { Triple(queue.removeFirstOrNull(), ended, terminal) }
55
- val item = delivery.first
56
- if (item != null) {
57
- // Flow's downstream exception/cancellation belongs to the collecting coroutine.
58
- // The Kotlin page explicitly requires a downstream collector exception to
59
- // leave collect and detach only this branch; never emit after that exception.
60
- try { emit(item.event) }
61
- finally { synchronized(lock) { count--; bytes -= item.bytes } }
62
- continue
63
- }
64
- if (delivery.second) {
65
- delivery.third?.let { emit(it) }
66
- return
67
- }
68
- wake.receive()
69
- }
70
- }
71
- }
72
-
73
- private val eventJson = GsonBuilder().disableHtmlEscaping().registerTypeHierarchyAdapter(ReaderString::class.java,
74
- com.google.gson.JsonSerializer<ReaderString> { value, _, _ -> com.google.gson.JsonPrimitive(value.value) }
75
- ).registerTypeAdapter(Instant::class.java, object : TypeAdapter<Instant>() {
76
- override fun write(out: JsonWriter, value: Instant?) { if (value == null) out.nullValue() else out.value(value.toString()) }
77
- override fun read(input: JsonReader): Instant = Instant.parse(input.nextString())
78
- }).create()
79
-
80
- /** Copy nested app-owned containers; Page requires recursive copying of polymorphic messages. */
81
- internal fun RuntimeEvent.owned(): RuntimeEvent = when (this) {
82
- is RuntimeEvent.Input -> copy(images = images.toList())
83
- is RuntimeEvent.MessageEnd -> copy(markers = markers.toList(), output = output?.deepCopy(), inReplyTo = inReplyTo.toList(), causedBy = causedBy.toList())
84
- is RuntimeEvent.App -> copy(data = data.deepCopy())
85
- is RuntimeEvent.Turn -> copy(causedBy = causedBy.toList(), inputs = inputs.toList(), usage = usage.toMap())
86
- is RuntimeEvent.Error -> copy(inputs = inputs.toList())
87
- is RuntimeEvent.Page -> copy(messages = messages.map { it.owned() })
88
- is RuntimeEvent.Unknown -> copy(fields = fields.deepCopy())
89
- else -> this
90
- }
91
-
92
- /** Tagged delivery payload, UTF-8 bytes including event structure as in S2's queue. */
93
- internal fun RuntimeEvent.serialized(): String {
94
- val json = if (this is RuntimeEvent.Unknown) fields.deepCopy() else eventJson.toJsonTree(this).asJsonObject
95
- val type = when (this) {
96
- is RuntimeEvent.Input -> "input"
97
- is RuntimeEvent.MessageStart -> "message.start"
98
- is RuntimeEvent.MessageDelta -> "message.delta"
99
- is RuntimeEvent.MessageEnd -> "message.end"
100
- is RuntimeEvent.Cleared -> "cleared"
101
- is RuntimeEvent.App -> "app"
102
- is RuntimeEvent.Turn -> "turn"
103
- is RuntimeEvent.Error, is RuntimeEvent.StreamError -> "error"
104
- is RuntimeEvent.State -> "state"
105
- is RuntimeEvent.Page -> "page"
106
- is RuntimeEvent.Gap -> "gap"
107
- is RuntimeEvent.Snapshot -> "snapshot"
108
- RuntimeEvent.Replaced -> "replaced"
109
- is RuntimeEvent.Unknown -> this.type
110
- }
111
- json.addProperty("type", type)
112
- return eventJson.toJson(json)
113
- }
@@ -1,201 +0,0 @@
1
- package dev.croche
2
-
3
- import com.google.gson.*
4
- import dev.croche.ffi.CoreRuntime
5
- import dev.croche.ffi.EventListener
6
- import dev.croche.s7.hostCallback
7
- import kotlinx.coroutines.Dispatchers
8
- import kotlinx.coroutines.withContext
9
- import java.time.Instant
10
- import java.util.concurrent.atomic.AtomicBoolean
11
- import kotlin.coroutines.suspendCoroutine
12
-
13
- /** The only native subscription boundary. Core owns projection, capture and durable ordering. */
14
- internal class NativeCoreStreamPort(private val core: CoreRuntime, private val host: KotlinHost) : CoreStreamPort {
15
- private val closed = AtomicBoolean()
16
- private val observationDetached = AtomicBoolean()
17
- /** Test-only pause after Core dispatch/decoding, before forwarding to the SDK branch. */
18
- @Volatile internal var projectionDeliveryStarting: ((RuntimeEvent) -> Unit)? = null
19
- @Volatile internal var projectionDeliveryFinished: ((RuntimeEvent) -> Unit)? = null
20
- @Volatile internal var projectionCloseFenced: (() -> Unit)? = null
21
- @Volatile private var currentState = RuntimeEvent.State(AgentStatus.IDLE, 0, false)
22
- override val state get() = currentState
23
- override val logId get() = call { core.logId() }
24
- private fun <T> call(body: () -> T): T {
25
- if (closed.get()) throw CrocheError("closed", "Runtime is closed")
26
- return try { nativeCall(body) } catch (error: Exception) { throw crocheError(error) }
27
- }
28
- private fun <T> nativeCall(body: () -> T): T {
29
- LegacyAgentEngine.offloadStarting?.invoke()
30
- return body()
31
- }
32
- private suspend fun <T> blocking(body: () -> T): T = withContext(Dispatchers.IO) { call(body) }
33
- private fun listener(callback: (JsonObject) -> Unit) = object : EventListener {
34
- override fun onEvent(event: String) = hostCallback { callback(JsonParser.parseString(event).asJsonObject) }
35
- }
36
- override fun observe(event: (RuntimeEvent) -> Unit, end: (Throwable?) -> Unit): AutoCloseable {
37
- call {
38
- core.observe(listener { value ->
39
- // Core's consuming-unit record is internal, never projected as an app event.
40
- if (value.at("type").text() != "unit.end") {
41
- val decoded = nativeEvent(value)
42
- if (decoded is RuntimeEvent.State) currentState = decoded
43
- event(decoded)
44
- }
45
- }, listener { value ->
46
- end(CoreStreamFailure(value.at("code").text(), value.at("message").text(), value.flag("poisoned")))
47
- })
48
- }
49
- observationDetached.set(false)
50
- return AutoCloseable { unobserve() }
51
- }
52
- internal fun unobserve() {
53
- if (observationDetached.compareAndSet(false, true) && !closed.get()) call { core.unobserve() }
54
- }
55
- override fun select(initialMessages: Int?, after: Cursor?, event: (RuntimeEvent) -> Unit): CoreStreamPort.Projection {
56
- val selection = JsonObject().apply {
57
- if (after != null) add("after", JsonObject().apply { addProperty("logId", after.logId); add("seq", JsonParser.parseString(coreSequence(after.seq).toString())) })
58
- else initialMessages?.let { addProperty("initialMessages", it) }
59
- }
60
- val delivery = Any()
61
- val detached = AtomicBoolean()
62
- val id = call { core.select(selection.toString(), listener {
63
- val decoded = nativeEvent(it)
64
- projectionDeliveryStarting?.invoke(decoded)
65
- // Stop forwarding once detached. Core close then joins the complete callback,
66
- // including decoding and these hooks, unless it is this callback's own close.
67
- try { synchronized(delivery) { if (!detached.get()) event(decoded) } }
68
- finally { projectionDeliveryFinished?.invoke(decoded) }
69
- }) }
70
- return object : CoreStreamPort.Projection {
71
- override fun close() {
72
- val first = synchronized(delivery) { detached.compareAndSet(false, true) }
73
- // The callback may still need delivery. Never hold its monitor across the
74
- // Core listener-completion wait; a self-close stays on the callback thread.
75
- if (first && !closed.get()) {
76
- projectionCloseFenced?.invoke()
77
- call { core.closeProjection(id) }
78
- }
79
- }
80
- override suspend fun history(before: Long?, limit: Int) {
81
- blocking { core.history(id, before?.let(::coreSequence), limit.toUInt()) }
82
- }
83
- }
84
- }
85
- override suspend fun send(input: JsonObject, options: SendOptions): Receipt = blocking {
86
- // The only receipt-send FFI call site.
87
- val value = JsonParser.parseString(core.send(input.toString(), null, options.responseFormat?.toString())).asJsonObject
88
- Receipt(value.at("requestId").text(), InputStatus(value.at("status").text()), value.optionalLong("seq"))
89
- }
90
- override suspend fun sendWithImages(input: SendInput, options: SendOptions): Receipt {
91
- val images = input.imageCaptures()
92
- // Reserve Core's admission place, hand it owned bytes as captures, then offload only the
93
- // wait. Core takes and releases each capture; on a refused submit the tokens are ours.
94
- val token = dev.croche.ffi.CancelToken()
95
- val pending = blocking {
96
- val entry = core.reserveSend()
97
- val tokens = ArrayList<String>(images.size)
98
- try {
99
- val captures = images.map { (element, bytes) ->
100
- dev.croche.ffi.PalCapturedImageSource(element.toUInt(), "encoded-v1", host.images.capture(bytes).also { tokens += it })
101
- }
102
- entry.submit(input.encoded(options).toString(), captures, token, options.responseFormat?.toString())
103
- } catch (error: Throwable) {
104
- tokens.forEach(host.images::release); throw error
105
- } finally { nativeCall { entry.close() } }
106
- }
107
- val value = try {
108
- kotlinx.coroutines.suspendCancellableCoroutine<String> { continuation ->
109
- continuation.invokeOnCancellation { token.cancel() }
110
- Thread({
111
- OffloadSeam.starting?.invoke()
112
- continuation.resumeWith(runCatching { call { pending.wait() } })
113
- }, "croche-offload").apply { isDaemon = true }.start()
114
- }
115
- } finally { nativeCall { pending.close(); token.close() } }
116
- val receipt = JsonParser.parseString(value).asJsonObject
117
- return Receipt(receipt.at("requestId").text(), InputStatus(receipt.at("status").text()), receipt.optionalLong("seq"))
118
- }
119
- override suspend fun readOutcome(id: String, fromSeq: Long, captured: (CapturedOutcome) -> Unit): RetainedEnds = blocking {
120
- val value = JsonParser.parseString(core.readOutcome(id, coreSequence(fromSeq), listener { at ->
121
- captured(CapturedOutcome(at.number("head"), at.number("floor"), InputStatus(at.at("status").text()), at.flag("idle")))
122
- })).asJsonObject
123
- RetainedEnds(value.list("messages").map { nativeEvent(it.asJsonObject) as RuntimeEvent.MessageEnd }, value.flag("gap"))
124
- }
125
- override suspend fun cancel(id: String) = blocking { core.cancel(id) }
126
- override suspend fun clearHistory() {
127
- // Take the Core's admission place on the caller before offloading only the wait.
128
- val pending = call { core.beginClearHistory() }
129
- suspendCoroutine<Unit> { continuation ->
130
- Thread({
131
- OffloadSeam.starting?.invoke()
132
- continuation.resumeWith(runCatching { try { call { pending.finish() }; Unit } finally { nativeCall { pending.close() } } })
133
- }, "croche-offload").apply { isDaemon = true }.start()
134
- }
135
- }
136
- override fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) {
137
- val stamp = host.stageTools(handlers)
138
- try { call { core.setToolDeclarations(tools.toString()) } }
139
- catch (error: Exception) { host.unstageTools(handlers.keys, stamp); throw error }
140
- host.acceptTools(handlers)
141
- }
142
- override fun close() {
143
- if (!closed.compareAndSet(false, true)) return
144
- host.stop()
145
- try { nativeCall { core.shutdown() } } catch (error: Exception) { throw crocheError(error) } finally { nativeCall { core.destroy() }; host.release() }
146
- }
147
- }
148
-
149
- internal fun publicSequence(value: ULong): Long {
150
- if (value > Long.MAX_VALUE.toULong()) throw CrocheError("invalid_input", "Core sequence exceeds Long.MAX_VALUE")
151
- return value.toLong()
152
- }
153
- internal fun coreSequence(value: Long): ULong {
154
- if (value < 0) throw CrocheError("invalid_input", "Sequence must not be negative")
155
- return value.toULong()
156
- }
157
- private fun JsonElement.sequence(): Long {
158
- val value = asString.toULongOrNull() ?: throw CrocheError("invalid_input", "Core sequence is not an unsigned integer")
159
- return publicSequence(value)
160
- }
161
- private fun JsonObject.number(name: String) = get(name).sequence()
162
- private fun JsonObject.optionalLong(name: String) = get(name)?.takeUnless { it.isJsonNull }?.sequence()
163
- private fun JsonObject.flag(name: String) = get(name)?.takeUnless { it.isJsonNull }?.asBoolean ?: false
164
- private fun JsonObject.list(name: String): List<JsonElement> = get(name)?.takeIf { it.isJsonArray }?.asJsonArray?.toList() ?: emptyList()
165
- private fun JsonObject.strings(name: String) = list(name).map { it.asString }
166
- private fun JsonObject.error() = get("error")?.takeIf { it.isJsonObject }?.asJsonObject?.let { RuntimeError(it.at("code").text(), it.at("message").text()) }
167
-
168
- /** Decode the Core's tagged JSON; omission stays omission, unknown reader values keep their exact strings. */
169
- internal fun nativeEvent(value: JsonObject): RuntimeEvent {
170
- fun at() = Instant.parse(value.at("at").text())
171
- fun state(v: JsonObject) = RuntimeEvent.State(AgentStatus(v.at("status").text()), v.number("queued").toInt(), v.flag("typing"),
172
- v.get("activity")?.takeUnless { it.isJsonNull }?.let { AgentActivity(it.text()) },
173
- v.get("tools")?.takeIf { it.isJsonArray }?.asJsonArray?.map { it.asString })
174
- return when (val type = value.at("type").text()) {
175
- "input" -> RuntimeEvent.Input(value.number("seq"), value.number("firstSeq"), value.at("id").text(), InputKind(value.at("kind").text()),
176
- value.get("text")?.takeUnless { it.isJsonNull }?.asString, value.list("images").map { image -> image.asJsonObject.let {
177
- ImageSummary(it.get("alt")?.asString, it.get("mime")?.asString, it.optionalLong("bytes"))
178
- } }, InputStatus(value.at("status").text()), value.error(), at())
179
- "message.start" -> RuntimeEvent.MessageStart(value.number("seq"), value.number("firstSeq"), value.at("id").text(), at())
180
- "message.delta" -> RuntimeEvent.MessageDelta(value.at("id").text(), value.at("text").text())
181
- "message.end" -> RuntimeEvent.MessageEnd(value.number("seq"), value.number("firstSeq"), value.at("id").text(), MessageStatus(value.at("status").text()),
182
- value.at("text").text(), value.strings("markers"), value.get("output")?.takeUnless { it.isJsonNull }?.deepCopy(),
183
- value.strings("inReplyTo"), value.strings("causedBy"), value.error(), at())
184
- "state" -> state(value)
185
- "snapshot" -> RuntimeEvent.Snapshot(value.at("logId").text(), state(value.getAsJsonObject("state")), value.get("streaming")?.takeIf { it.isJsonObject }?.asJsonObject?.let {
186
- Streaming(it.at("messageId").text(), it.number("firstSeq"), it.at("text").text())
187
- })
188
- "page" -> RuntimeEvent.Page(value.list("messages").map { nativeEvent(it.asJsonObject) }, value.flag("reachedFloor"), value.at("logId").text(), value.number("clearedSeq"))
189
- "gap" -> RuntimeEvent.Gap(value.number("afterSeq"), value.number("throughSeq"), GapReason(value.at("reason").text()))
190
- "cleared" -> RuntimeEvent.Cleared(value.number("seq"), value.at("id").text(), at())
191
- "turn" -> RuntimeEvent.Turn(value.number("seq"), value.at("id").text(), value.strings("causedBy"), value.strings("inputs"), value.at("purpose").text(),
192
- value.get("usage")?.takeIf { it.isJsonObject }?.asJsonObject?.entrySet()?.associate { it.key to it.value.asLong } ?: emptyMap(),
193
- value.get("costUsd")?.asDouble ?: 0.0, CostStatus(value.at("costStatus").text()), value.at("model").text(), value.optionalLong("imagesOmitted")?.toInt(), at())
194
- "app" -> value.getAsJsonObject("source").let { RuntimeEvent.App(value.number("seq"), value.at("id").text(), value.at("name").text(), value.get("data").deepCopy(),
195
- ToolSource(it.at("command").text(), it.at("callId").text()), at()) }
196
- "error" -> if (value.has("seq")) RuntimeEvent.Error(value.number("seq"), value.at("id").text(), value.at("code").text(), value.at("message").text(), value.strings("inputs"), at())
197
- else RuntimeEvent.StreamError(value.at("code").text(), value.at("message").text(), value.flag("poisoned"))
198
- "replaced" -> RuntimeEvent.Replaced
199
- else -> RuntimeEvent.Unknown(type, value.deepCopy())
200
- }
201
- }
@@ -1,25 +0,0 @@
1
- package dev.croche
2
-
3
- import com.google.gson.JsonObject
4
- import com.google.gson.JsonParser
5
-
6
- /** Core's PAL labels are routing metadata, never an agentId to hash literally. */
7
- internal data class ProjectPalRoute(val agent: String, val instance: String? = null, val maintenance: Boolean = false) {
8
- // OPEN(Keel/Atlas): install-wide GC labels omit the target user; binding by Core lock key is proposed.
9
- fun identity(host: JsonObject, user: String?): JsonObject = host.deepCopy().apply {
10
- addProperty("agentId", agent)
11
- remove("agentInstance")
12
- instance?.let { addProperty("agentInstance", it) }
13
- user?.let { addProperty("user", it) }
14
- }
15
- }
16
- internal fun projectPalRoute(label: String): ProjectPalRoute {
17
- if (!label.startsWith("[")) return ProjectPalRoute(label)
18
- val parts = JsonParser.parseString(label).asJsonArray.map { it.asString }
19
- return when {
20
- parts == listOf("\$gc", "pass") -> ProjectPalRoute("default", maintenance = true)
21
- parts.size == 3 && parts[0] == "\$gc" -> ProjectPalRoute(parts[1], parts[2], maintenance = true)
22
- parts.size == 2 -> ProjectPalRoute(parts[0], parts[1])
23
- else -> throw CrocheError("invalid_configuration", "Invalid project PAL label")
24
- }
25
- }