@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
package/package.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "@h1r-ai/croche-react-native",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
7
  "license": "SEE LICENSE IN LICENSE",
8
8
  "description": "Croche Runtime for React Native: the shared Rust Core through the native iOS and Android SDKs, with app attestation and Keychain/Keystore credentials.",
9
- "main": "src/index.ts",
10
- "types": "src/index.ts",
11
- "react-native": "src/index.ts",
9
+ "main": "dist/runtime/src/rn-entry.js",
10
+ "types": "dist/runtime/src/rn-entry.d.ts",
11
+ "react-native": "dist/runtime/src/rn-entry.js",
12
12
  "files": [
13
- "src",
13
+ "dist",
14
+ "src/NativeCrocheRuntime.ts",
14
15
  "ios",
15
16
  "android",
16
17
  "scripts",
@@ -20,11 +21,11 @@
20
21
  "THIRD-PARTY-NOTICES"
21
22
  ],
22
23
  "peerDependencies": {
23
- "@h1r-ai/croche": "0.5.4",
24
+ "@h1r-ai/croche": "0.6.0",
24
25
  "react-native": ">=0.76"
25
26
  },
26
27
  "devDependencies": {
27
- "@h1r-ai/croche": "0.5.4"
28
+ "@h1r-ai/croche": "0.6.0"
28
29
  },
29
30
  "codegenConfig": {
30
31
  "name": "CrocheRuntimeSpec",
@@ -37,6 +38,15 @@
37
38
  "scripts": {
38
39
  "typecheck": "tsc --noEmit -p tsconfig.json",
39
40
  "vendor:native": "scripts/vendor-native.sh",
40
- "test": "vitest run --root ../.. packages/react-native/tests"
41
+ "test": "vitest run --root ../.. packages/react-native/tests",
42
+ "build": "node scripts/build.mjs",
43
+ "prepack": "npm run build"
44
+ },
45
+ "exports": {
46
+ ".": {
47
+ "types": "./dist/runtime/src/rn-entry.d.ts",
48
+ "react-native": "./dist/runtime/src/rn-entry.js",
49
+ "default": "./dist/runtime/src/rn-entry.js"
50
+ }
41
51
  }
42
52
  }
@@ -0,0 +1,11 @@
1
+ # RN shared-facade build
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.
4
+
5
+ ```
6
+ node packages/react-native/scripts/build-shared.mjs --adapter <native-adapter.ts> --out <empty-artifact-directory>
7
+ ```
8
+
9
+ The adapter is compiled at the shared source root and supplies `coreModule()` and `nativePlatform`, typed against `core/port.ts` and `pal/platform.ts`. It may import the RN native adapter through a relative path. The build records canonical source hashes, refuses a nonempty output, and refuses a dependency graph containing WASM. No additional `@h1r-ai/croche` package export is used.
10
+
11
+ The focused `app-five-scenarios.test.ts` build supplies an explicitly test-only adapter. Its fake Core is not the production adapter, and that fixture artifact must not ship. Native adapter registration and the public package entrypoint switch land together in the RN unit.
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ // Compile the ONE TS facade into the RN artifact. Only the platform/core-loader
3
+ // modules differ. No new @h1r-ai/croche export and no WASM in the RN build.
4
+ import ts from 'typescript';
5
+ import {readFile,mkdir,writeFile,readdir} from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {createHash} from 'node:crypto';
9
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../../..');
10
+ const args=process.argv.slice(2),option=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1];};
11
+ const adapter=option('--adapter'),output=option('--out');
12
+ if(!adapter||!output)throw Error('Usage: build-shared.mjs --adapter <native adapter source> --out <RN artifact directory>');
13
+ const out=path.resolve(output),source=path.join(root,'packages/runtime/src');
14
+ try { if((await readdir(out)).length)throw Error('RN build output must be empty: '+out); }
15
+ catch(error){if(error.code!=='ENOENT')throw error;}
16
+ const adapterFile=path.resolve(adapter),adapterSource=await readFile(adapterFile,'utf8');
17
+ // The public facade is compiled unchanged. This RN entry selects the native PAL
18
+ // using the explicit native surface; only core/wasm.ts is replaced.
19
+ const nativeEntry="export * from './index.native.js';\nimport {usePlatform} from './pal/platform.js';\nimport {nativePlatform} from './native-adapter.js';\nusePlatform(nativePlatform);\n";
20
+ const virtual=new Map([
21
+ [path.join(source,'rn-entry.ts'),nativeEntry],
22
+ [path.join(source,'native-adapter.ts'),adapterSource],
23
+ [path.join(source,'core/wasm.ts'),"// Native Core transport selected at RN build time.\nexport {coreModule} from '../native-adapter.js'\n"],
24
+ ]);
25
+ const options={target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext,moduleResolution:ts.ModuleResolutionKind.Bundler,
26
+ strict:true,skipLibCheck:true,declaration:true,noEmitOnError:true,rootDir:path.join(root,'packages'),outDir:out,
27
+ baseUrl:root,paths:{'react-native':['packages/react-native/types/react-native.d.ts']}};
28
+ const host=ts.createCompilerHost(options),read=host.readFile.bind(host),exists=host.fileExists.bind(host),get=host.getSourceFile.bind(host);
29
+ host.fileExists=file=>virtual.has(path.resolve(file))||exists(file);
30
+ host.readFile=file=>virtual.get(path.resolve(file))??read(file);
31
+ host.getSourceFile=(file,languageVersion,onError,create)=>virtual.has(path.resolve(file))
32
+ ?ts.createSourceFile(file,virtual.get(path.resolve(file)),languageVersion,true):get(file,languageVersion,onError,create);
33
+ const program=ts.createProgram([path.join(source,'rn-entry.ts')],options,host);
34
+ const diagnostics=ts.getPreEmitDiagnostics(program);
35
+ if(diagnostics.length){process.stderr.write(ts.formatDiagnosticsWithColorAndContext(diagnostics,{getCurrentDirectory:()=>root,getCanonicalFileName:x=>x,getNewLine:()=> '\n'}));process.exit(1);}
36
+ const result=program.emit();if(result.emitSkipped)throw Error('Shared RN emit skipped');
37
+ const forbidden=program.getSourceFiles().filter(file=>/[/\\](core-wasm|core-wasm-bytes|core-bindgen)\.ts$/.test(file.fileName));
38
+ if(forbidden.length)throw Error('RN facade imported WASM: '+forbidden.map(file=>file.fileName).join(', '));
39
+ const hashes={};
40
+ for(const file of ['index.native.ts','croche.ts','agent.ts','tools.ts','app-api.ts','json.ts','errors.ts','cancel.ts','core/port.ts']){
41
+ const bytes=await readFile(path.join(source,file));hashes[file]=createHash('sha256').update(bytes).digest('hex');
42
+ }
43
+ await mkdir(out,{recursive:true});await writeFile(path.join(out,'package.json'),JSON.stringify({type:'module'})+'\n');
44
+ const metadata={entry:'runtime/src/rn-entry.js',adapter:path.relative(root,adapterFile),sharedSources:hashes,wasm:false};
45
+ await writeFile(path.join(out,'rn-shared-build.json'),JSON.stringify(metadata,null,2)+'\n');
46
+ console.log(JSON.stringify({status:'PASS',entry:path.join(out,metadata.entry),wasm:false}));
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ // Only this package's generated dist is replaced. build-shared itself keeps its
3
+ // nonempty-output guard, so stale/foreign artifact directories are never reused.
4
+ import {rmSync} from 'node:fs';
5
+ import {execFileSync} from 'node:child_process';
6
+ import {fileURLToPath} from 'node:url';
7
+ import path from 'node:path';
8
+ const directory=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
9
+ const out=path.join(directory,'dist');
10
+ rmSync(out,{recursive:true,force:true});
11
+ execFileSync(process.execPath,[path.join(directory,'scripts/build-shared.mjs'),'--adapter',path.join(directory,'src/shared-adapter.ts'),'--out',out],{stdio:'inherit'});
@@ -18,9 +18,10 @@ if [[ $what == ios || $what == all ]]; then
18
18
  cp -R "$root/sdk/swift/Sources/CrocheRuntime" "$package/ios/vendor/CrocheRuntimeSDK"
19
19
  cp "$root/sdk/swift/Sources/CrocheFFI/croche_ffi.swift" "$package/ios/vendor/CrocheRuntimeSDK/"
20
20
  # The pod compiles the SDK and its bindings into one module: no CrocheFFI module to import.
21
- sed -i.bak '/^import CrocheFFI$/d' "$package/ios/vendor/CrocheRuntimeSDK/"*.swift
22
- rm -f "$package/ios/vendor/CrocheRuntimeSDK/"*.bak
23
- if grep -q 'CrocheFFI\.' "$package/ios/vendor/CrocheRuntimeSDK/"*.swift; then
21
+ # Recursive: the App API sources live in a subfolder (S1/).
22
+ find "$package/ios/vendor/CrocheRuntimeSDK" -name '*.swift' -exec sed -i.bak '/^import CrocheFFI$/d' {} +
23
+ find "$package/ios/vendor/CrocheRuntimeSDK" -name '*.bak' -delete
24
+ if grep -rq --include='*.swift' 'CrocheFFI\.' "$package/ios/vendor/CrocheRuntimeSDK"; then
24
25
  echo 'The SDK names the CrocheFFI module; the pod has none. Call the binding unqualified.' >&2; exit 1
25
26
  fi
26
27
  rm -rf "$work"
@@ -47,7 +48,7 @@ if [[ $what == android || $what == all ]]; then
47
48
  # extracts for crash symbolication before it strips the APK's copy (Atlas, #213). Keep it so.
48
49
  nm=$(ls "$ANDROID_NDK_HOME"/toolchains/llvm/prebuilt/*/bin/llvm-nm | head -1)
49
50
  for so in "$package/android/vendor/jniLibs/"*/libcroche_ffi.so; do
50
- "$nm" "$so" | grep -c '11croche_core7runtimeNtB._4Core5admit' >/dev/null || { echo "$so lost its symbol table (Core::admit)" >&2; exit 1; }
51
+ "$nm" "$so" | grep -cE '11croche_core.*4Core5admit' >/dev/null || { echo "$so lost its symbol table (Core::admit)" >&2; exit 1; }
51
52
  done
52
53
  for abi in arm64-v8a armeabi-v7a x86_64; do
53
54
  [[ -f "$package/android/vendor/jniLibs/$abi/libcroche_ffi.so" ]] || { echo "Missing libcroche_ffi.so for $abi" >&2; exit 1; }
@@ -1,162 +1,15 @@
1
- // TurboModule spec (React Native codegen reads this file). Every structured value crosses
2
- // the bridge as a JSON string, so numbers, keys and nesting arrive exactly as the Rust Core
3
- // produced them. The native side is a thin driver over the platform SDK: iOS CrocheRuntime
4
- // (Swift) and Android dev.croche (Kotlin), which run the shared Rust Core.
5
- import type { TurboModule } from 'react-native';
6
- import { TurboModuleRegistry } from 'react-native';
7
-
1
+ // Private S1 transport. Core owns all handles, validation, scheduling and events.
2
+ // React Native codegen reads this file; JSON is opaque at this boundary.
3
+ import type {TurboModule} from 'react-native';
4
+ import {TurboModuleRegistry} from 'react-native';
5
+ export type OwnedImage = {element:number; bytes:ReadonlyArray<number>};
8
6
  export interface Spec extends TurboModule {
9
- /**
10
- * Opens (or reopens) one Runtime under `handle`. `configJson` is Core configuration, with
11
- * tool metadata but no callbacks. `optionsJson` carries host choices: `storageKey`,
12
- * `attestation` ("platform" | "off"), `backgroundSync` (boolean), `maintenanceIntervalMs`,
13
- * `android.cloudProjectNumber` and `backgroundDelivery` ({iosTaskIdentifier} or absent).
14
- * Resolves the Runtime's inspection JSON.
15
- */
16
- open(handle: string, configJson: string, optionsJson: string): Promise<string>;
17
- /**
18
- * Resolves the TurnResult JSON. Several sends may be in flight per handle. `responseFormatJson`:
19
- * the structured-output format, or "null" for none. `callId` names this call, unique per handle:
20
- * a retry of the same input id is another call, with its own cancellation.
21
- */
22
- send(handle: string, inputJson: string, responseFormatJson: string, callId: string): Promise<string>;
23
- /**
24
- * Stops the handle's running turn only; sends held behind it still run, together, as the next
25
- * turn. The running send's promise still resolves with the outcome.
26
- */
27
- cancel(handle: string): void;
28
- /**
29
- * Cancels one send call: held, it is dropped; running, its turn stops (a turn several sends
30
- * share stops for all of them). A call not yet registered natively is remembered and starts
31
- * cancelled, so an abort right after `send` is never lost.
32
- */
33
- cancelSend(handle: string, callId: string): void;
34
- /** Drops the sends held behind the running turn (each ends `cancelled`); resolves how many. */
35
- clearQueued(handle: string): Promise<number>;
36
- inspect(handle: string): Promise<string>;
37
- /**
38
- * One round of background upkeep (deliver call reports, then sync). The native SDK also
39
- * runs it by itself after each turn and on a timer; call it when the app returns to the
40
- * foreground. Resolves the MaintenanceResult JSON. Never delays a send.
41
- */
42
- maintain(handle: string, force: boolean): Promise<string>;
43
- /**
44
- * The platform SDK's `deliverDue()`: the agent's scheduled notes that are due, as one turn.
45
- * Resolves `{ran: false}` (none due, or one being delivered: `inFlight`) or
46
- * `{ran, ids, delivered, turn}` JSON.
47
- */
48
- deliverDue(handle: string): Promise<string>;
49
- /** The platform SDK's `schedules()`: `{pending: [{id, at, note}], due}` JSON. */
50
- schedules(handle: string): Promise<string>;
51
- /**
52
- * Asks Cloud to raise (`absolute` false) or set (`absolute` true) this user's allowance
53
- * within the project's ceilings. `id` ("" for none) makes a retry safe: Cloud applies an
54
- * id once. Resolves the BudgetAdjustment JSON.
55
- */
56
- adjustBudget(handle: string, amount: number, absolute: boolean, id: string): Promise<string>;
57
- /**
58
- * Replaces the tool list: `toolsJson` is tool metadata as in `open`'s config (no callbacks;
59
- * JavaScript keeps the handlers). Rejects, changing nothing, when the Core refuses the list.
60
- */
61
- setTools(handle: string, toolsJson: string): Promise<void>;
62
- /** Starts a new session: forgets history and memory, keeps money and identity. */
63
- clearHistory(handle: string): Promise<void>;
64
- /**
65
- * One wiki operation on the platform SDK's `runtime.wiki`, as JSON both ways:
66
- * `set` {docs} → digest; `put` {docs} → null; `remove` {path} → boolean; `list` {folder?}
67
- * → entries; `read` {path, part} → page or null; `search` {query, limit} → hits;
68
- * `putUser` {docs} → {documents, bytes}; `removeUser` {path} → boolean; `clearUser` {} →
69
- * count; `bundled` {folder} → the documents shipped in the app (iOS bundle folder, Android
70
- * assets), with `handle` unused. Docs are [{path, markdown, agents?}].
71
- */
72
- wiki(handle: string, op: string, argsJson: string): Promise<string>;
73
- /**
74
- * One operation on the platform SDK's `runtime.memory`, as JSON both ways: `list` {} → items;
75
- * `delete` {id} → {deleted}; `clear` {} → {cleared};
76
- * `enabled` {on} → null; `export` {} → {enabled, items}; `observe` {on} → null,
77
- * attaching (or removing) the SDK's onChanged so each change arrives as a `memoryChanged`
78
- * message.
79
- */
80
- memory(handle: string, op: string, argsJson: string): Promise<string>;
81
- close(handle: string): Promise<void>;
82
- /** Answers a `tool` event. When `ok`, `resultJson` is `{value, images?, imageResolution?}`:
83
- * the images beside the value (H3). Otherwise `{code}`, set by this bridge alone:
84
- * `tool_not_dispatched` (no handler ran), `invalid_tool_result` (it ran and returned something
85
- * unreadable: that call fails alone) or `effect_failed` (the handler threw). */
86
- resolveTool(callId: string, ok: boolean, resultJson: string): void;
87
- // The project API (Keel #339 6093822222: RN mirrors TS `Croche` / `CrocheAgent`). A thin
88
- // binding of the FFI's `CoreProject` (#377): `project` names one open project, and each
89
- // agent it opens is an FFI `CoreRuntime` under its own `handle`, which every per-agent method
90
- // below (and `clearHistory`, `close`, `resolveTool`) takes. The native side builds the
91
- // `HostPalFactory` from its platform SDK's PAL pieces (storage, HTTP, tools, attestation).
92
- // JavaScript runs the TypeScript SDK's StreamHub over the stream port, so subscriptions
93
- // behave as in TypeScript. Every callback arrives as a `CrocheRuntimeEvent` NativeMessage
94
- // (protocol.ts: {handle, type, json}) emitted from ONE serial queue per handle, in the order
95
- // the Core called it: observe events, projection events and readOutcome's capture share that
96
- // order (the hub relies on it). Tool calls use the existing `tool`/`toolCancel` messages and
97
- // `resolveTool`, with the Core's tool context passed through unchanged.
98
- /**
99
- * `Croche.open`. `optionsJson`: `{host, user?, config, handlers, language?, streaming,
100
- * backgroundSync, maintenanceIntervalMs}` as the FFI's `ProjectOpenOptions` (host and config
101
- * as JSON values, not text), plus RN host choices `attestation` ("platform" | "off"),
102
- * `android.cloudProjectNumber`. Usage arrives as `{handle: project, type: "usage", json}`.
103
- * Resolves `projectInfo`'s JSON. Rejects with the Core's code; nothing stays open.
104
- */
105
- projectOpen(project: string, optionsJson: string): Promise<string>;
106
- /** Synchronous (in-memory getters): `{user, installationId, crocheUserId, agentIds, applied}`. */
107
- // Sync getters (projectInfo, agentState) either throw a coded error or return {"error":{"code","message"}}.
108
- projectInfo(project: string): string;
109
- /** `Croche.deleteStore` (R8): `optionsJson` is `{host, user?, config, agent?}`, as TypeScript's wire. */
110
- projectDeleteStore(optionsJson: string): Promise<void>;
111
- /**
112
- * `croche.agent(id?, {instance?, fresh?, config?})` (#406): opens (or returns again) that agent
113
- * as `handle`; `id` "" is the default agent, `optionsJson` `{instance?, fresh?, config?}`.
114
- * Resolves `{id, name, mode, visibleTools, logId, instance, created}`. Rejects with the Core's
115
- * code (override mismatch, closed).
116
- */
117
- projectAgent(project: string, handle: string, id: string, optionsJson: string): Promise<string>;
118
- /** Closes every agent of the project, then the project. */
119
- projectClose(project: string): Promise<void>;
120
- /**
121
- * One agent control, JSON both ways: `setTools` {visible: string[] | null} → null; `setMode`
122
- * {mode: string | null} → null; `sync` {} → null.
123
- */
124
- agentControl(handle: string, op: string, argsJson: string): Promise<string>;
125
- /** Synchronous (in-memory getters): `{id, name, mode, visibleTools, closed}`. */
126
- agentState(handle: string): string;
127
- /**
128
- * Starts the agent's one observation: type `observe` (json: the Core event) per event, then one
129
- * `observeEnd` (json: the Core error, or "null"). Rejects with the
130
- * Core's code (for example `invalid_configuration` when observed already), observing nothing.
131
- */
132
- observe(handle: string): Promise<void>;
133
- unobserve(handle: string): void;
134
- /**
135
- * Opens a projection, `selectionJson` `{"initialMessages": n}` or `{"after": {logId, seq}}`.
136
- * Resolves its id; each event arrives as type `projection`, json `{"projection": id, "event": …}`.
137
- */
138
- select(handle: string, selectionJson: string): Promise<number>;
139
- closeProjection(handle: string, projection: number): void;
140
- /** Places one history page (`before` -1: from the loaded edge); the page arrives on the projection. */
141
- history(handle: string, projection: number, before: number, limit: number): Promise<void>;
142
- /**
143
- * The retained ends of input `id` from `fromSeq`. The capture is emitted, in order, as type
144
- * `captured`, json `{"readId": …, "state": …}`, before this resolves `{messages, gap?}` JSON;
145
- * JavaScript waits for both.
146
- */
147
- readOutcome(handle: string, id: string, fromSeq: number, readId: string): Promise<string>;
148
- /**
149
- * The receipt send: resolves `{id, status, seq}` JSON once the input is accepted. `cancelSend`
150
- * with this `callId` applies before acceptance only.
151
- */
152
- sendReceipt(handle: string, inputJson: string, responseFormatJson: string, callId: string): Promise<string>;
153
- /** Core `cancel(id)`: resolves once durable; rejects `unknown_id` or `closed`. */
154
- cancelInput(handle: string, id: string): Promise<void>;
155
- /** Core `cancel_turn`: stops the running turn at the call (FFI #397 returns at once). */
156
- cancelTurn(handle: string): Promise<void>;
157
- /** Emitter bookkeeping for the `CrocheRuntimeEvent` stream. */
158
- addListener(eventName: string): void;
159
- removeListeners(count: number): void;
7
+ coreCall(handle:string, method:string, argsJson:string, images:ReadonlyArray<OwnedImage>):Promise<string>;
8
+ coreCallSync(handle:string, method:string, argsJson:string):string;
9
+ coreReply(call:string, completionJson:string):void;
10
+ platformCall(method:string, argsJson:string):Promise<string>;
11
+ platformCallSync(method:string, argsJson:string):string;
12
+ addListener(eventName:string):void;
13
+ removeListeners(count:number):void;
160
14
  }
161
-
162
15
  export default TurboModuleRegistry.getEnforcing<Spec>('CrocheRuntime');
@@ -1,25 +0,0 @@
1
- package dev.croche.reactnative
2
-
3
- import com.google.gson.JsonObject
4
- import dev.croche.CrocheException
5
- import dev.croche.ffi.CoreRuntimeInterface
6
- import dev.croche.ffi.EventListener
7
- import dev.croche.keepAttached
8
-
9
- /** Agent entries own an FFI CoreRuntime, rather than the legacy SDK Runtime wrapper. */
10
- internal fun agentMemory(core: CoreRuntimeInterface, op: String, args: JsonObject, changed: (String) -> Unit): String = when (op) {
11
- "list" -> core.memoryList()
12
- "set" -> throw CrocheException("invalid_memory", "memory.set was removed: only the AI writes memories.")
13
- "delete" -> core.memoryDelete(args.get("id")?.takeIf { it.isJsonPrimitive }?.asString ?: "")
14
- "clear" -> core.memoryClear()
15
- "enabled" -> core.memorySetEnabled(args.get("on")?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean }?.asBoolean == true)
16
- "export" -> core.memoryExport()
17
- "observe" -> {
18
- val on = args.get("on")?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean }?.asBoolean == true
19
- core.setMemoryObserver(if (on) object : EventListener {
20
- override fun onEvent(event: String) { keepAttached(); changed(event) }
21
- } else null)
22
- "null"
23
- }
24
- else -> throw CrocheException("invalid_memory", "Unknown memory operation $op")
25
- }
@@ -1,17 +0,0 @@
1
- package dev.croche.reactnative
2
-
3
- import com.google.gson.JsonObject
4
- import dev.croche.RuntimeAttestor
5
-
6
- /** The project's attestor, shared by its agents: Play Integrity when the app gave its Cloud
7
- * project number and did not turn attestation off; otherwise none (unverified). */
8
- internal fun projectAttestor(options: JsonObject, playIntegrity: (Long) -> RuntimeAttestor): RuntimeAttestor? {
9
- val number = options.getAsJsonObject("android")?.get("cloudProjectNumber")?.asLong
10
- return if (options.get("attestation")?.asString != "off" && number != null) playIntegrity(number) else null
11
- }
12
-
13
- /** The host fields Core receives. They name the platform only when there is an attestor, as
14
- * CrocheRuntime.create does: otherwise no agent asks to attest and every install registers
15
- * unverified (sdk-internal #24). */
16
- internal fun projectHost(options: JsonObject, attestor: RuntimeAttestor?): JsonObject =
17
- options.getAsJsonObject("host").deepCopy().apply { attestor?.let { addProperty("attestationPlatform", it.platform) } }
@@ -1,14 +0,0 @@
1
- package dev.croche.reactnative
2
-
3
- import com.google.gson.JsonObject
4
- import dev.croche.CrocheException
5
- import dev.croche.projectTimeZone
6
- import java.util.TimeZone
7
-
8
- /** Parse before CoreProject.open; never silently fall back to GMT for an unknown zone. */
9
- internal fun projectZone(options: JsonObject): TimeZone? =
10
- projectTimeZone(options.get("timeZone")?.takeUnless { it.isJsonNull }?.let {
11
- if (!it.isJsonPrimitive || !it.asJsonPrimitive.isString)
12
- throw CrocheException("invalid_configuration", "timeZone must be an IANA time zone")
13
- it.asString
14
- })
@@ -1,178 +0,0 @@
1
- package dev.croche
2
-
3
- import com.google.gson.*
4
- import java.net.URI
5
- import java.util.UUID
6
- import java.util.concurrent.*
7
- import java.util.concurrent.atomic.AtomicBoolean
8
-
9
- fun interface ControlSend { fun send(input: JsonObject, cancellation: RuntimeCancellation): JsonElement }
10
- fun interface ControlCancel { fun cancel(): Boolean }
11
-
12
- /** Explicit local attachment, independent of Cloud credentials and Runtime ownership.
13
- * Close this connection separately; it never opens/closes the Runtime's private store. */
14
- class RuntimeControl private constructor(
15
- private val runtime: CrocheRuntime, private val url: String, private val token: String,
16
- private val http: RuntimeHTTP, private val sendAdapter: ControlSend?, private val cancelAdapter: ControlCancel?,
17
- private val onError: ((String) -> Unit)?
18
- ) : AutoCloseable {
19
- val runtimeInstanceId = runtime.inspect().at("status").at("runtimeInstanceId").text()
20
- val capabilities: List<String> = listOf("status", "history", "send", "cancel", "sync", "budget.get", "budget.set", "tools")
21
- private val clientId = UUID.randomUUID().toString()
22
- private val lifetime = RuntimeCancellation()
23
- private val effects = EffectExecutor()
24
- private val closed = AtomicBoolean(false)
25
- private val handled = ConcurrentHashMap.newKeySet<String>()
26
- private val results = ConcurrentHashMap<String, JsonObject>()
27
- private val active = ConcurrentHashMap<String, RuntimeCancellation>()
28
- private val tasks = ConcurrentHashMap.newKeySet<String>()
29
- private val workers = ThreadPoolExecutor(0, 16, 30, TimeUnit.SECONDS, SynchronousQueue(),
30
- ThreadFactory { task -> Thread(task, "croche-control-command").apply { isDaemon = true } })
31
- private var poller: Thread? = null
32
- companion object {
33
- fun attach(runtime: CrocheRuntime, token: String, url: String = "http://127.0.0.1:8791",
34
- http: RuntimeHTTP = RuntimeHttpURLConnection(), send: ControlSend? = null,
35
- cancel: ControlCancel? = null, onError: ((String) -> Unit)? = null): RuntimeControl {
36
- val parsed = try { URI(url) } catch (_: Exception) { throw CrocheException("invalid_configuration", "Invalid local control URL") }
37
- if (parsed.scheme != "http" || parsed.host !in listOf("127.0.0.1", "localhost", "[::1]", "::1") ||
38
- parsed.userInfo != null || parsed.query != null || parsed.fragment != null || parsed.path !in listOf("", "/") ||
39
- !Regex("^[A-Za-z0-9._~-]{24,4096}$").matches(token)) {
40
- throw CrocheException("invalid_configuration", "Control needs a loopback HTTP origin and explicit local token")
41
- }
42
- val control = RuntimeControl(runtime, url.removeSuffix("/"), token, http, send, cancel, onError)
43
- try { control.register(); control.start() }
44
- catch (error: Exception) { control.release(); throw error }
45
- return control
46
- }
47
- }
48
- private fun identity() = obj("client_id" to str(clientId), "runtime_instance_id" to str(runtimeInstanceId))
49
- private fun register() {
50
- val caps = JsonArray(); capabilities.forEach { caps.add(it) }
51
- post("register", obj("client_id" to str(clientId), "runtime" to runtime.inspect().at("status"), "capabilities" to caps))
52
- }
53
- private fun post(path: String, body: JsonObject): JsonObject {
54
- if (body.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("control_capacity", "Control request exceeds 1MiB")
55
- val effect = obj("url" to str("$url/v1/control/$path"), "method" to str("POST"),
56
- "headers" to obj("Authorization" to str("Bearer $token"), "Content-Type" to str("application/json")),
57
- "body" to body, "timeoutMs" to num(5000))
58
- val response = effects.run(5000, lifetime) { signal -> http.execute(effect, signal) {} }
59
- val data = response.at("body")
60
- if (!data.isJsonObject || data.toString().toByteArray(Charsets.UTF_8).size > 1024 * 1024) throw CrocheException("invalid_response", "Invalid bounded control response")
61
- if (response.at("status").asInt !in 200..299) {
62
- val code = data.at("error").at("code").text()
63
- throw CrocheException(if (code in setOf("attachment_lost", "not_found", "unauthorized", "runtime_already_attached")) code else "control_error", "Local control broker rejected the request")
64
- }
65
- return data.asJsonObject
66
- }
67
- private fun start() {
68
- poller = Thread({
69
- while (!closed.get()) {
70
- try {
71
- results.entries.take(8).forEach { (id, result) ->
72
- try { post("results", result); results.remove(id) }
73
- catch (error: CrocheException) { if (error.code in listOf("not_found", "attachment_lost")) results.remove(id); throw error }
74
- }
75
- if (results.size < 32 && tasks.size < 16) {
76
- val data = post("poll", identity())
77
- if (!data.at("commands").isJsonArray) throw CrocheException("invalid_response", "Invalid broker command list")
78
- data.at("commands").asJsonArray.take(8).forEach { accept(it) }
79
- }
80
- } catch (error: Exception) {
81
- if (!closed.get()) {
82
- try { onError?.invoke("Local control could not complete a request") } catch (_: Exception) {}
83
- if (error is CrocheException && error.code == "attachment_lost") try { register() } catch (_: Exception) {}
84
- }
85
- }
86
- try { Thread.sleep(100) } catch (_: InterruptedException) { if (closed.get()) break }
87
- }
88
- }, "croche-control-poll").apply { isDaemon = true; start() }
89
- }
90
- private fun accept(value: JsonElement) {
91
- val id = value.at("request_id").text(); val command = value.at("command").text(); val payload = value.at("payload")
92
- if (!validId(id) || command !in capabilities || !payload.isJsonObject) throw CrocheException("invalid_command", "Invalid broker command envelope")
93
- if (handled.contains(id)) return
94
- if (handled.size >= 1000) throw CrocheException("control_capacity", "Reattach after 1000 control requests")
95
- handled.add(id); tasks.add(id)
96
- val work = Runnable {
97
- val reply = identity().apply { addProperty("request_id", id) }
98
- try {
99
- val result = execute(command, payload.asJsonObject.deepCopy(), id)
100
- if (result.toString().toByteArray(Charsets.UTF_8).size > 900000) throw CrocheException("result_too_large", "Request a smaller result page")
101
- reply.add("result", result.deepCopy())
102
- } catch (error: Exception) {
103
- val code = (error as? CrocheException)?.code
104
- reply.add("error", obj("code" to str(if (code in publicCodes) code!! else "runtime_error"),
105
- "message" to str("The Runtime command failed. Inspect it before retrying."),
106
- "uncertain" to bool(command == "send" || command == "budget.set")))
107
- } finally { tasks.remove(id) }
108
- if (!closed.get()) results[id] = reply
109
- }
110
- try { workers.execute(work) }
111
- catch (_: RejectedExecutionException) {
112
- tasks.remove(id)
113
- results[id] = identity().apply {
114
- addProperty("request_id", id)
115
- add("error", obj("code" to str("control_capacity"), "message" to str("Control workers are occupied"), "uncertain" to bool(false)))
116
- }
117
- }
118
- }
119
- private fun execute(command: String, payload: JsonObject, id: String): JsonElement {
120
- if (closed.get()) throw CrocheException("control_closed", "Control is closed")
121
- fun keys(allowed: Set<String>) { if (!allowed.containsAll(payload.keySet())) throw CrocheException("invalid_command", "Unsupported command fields") }
122
- if (command == "send") {
123
- keys(setOf("id", "text"))
124
- val text = payload.at("text").text()
125
- if (!validId(payload.at("id").text()) || text.isBlank() || text.length > 32000) throw CrocheException("invalid_command", "send needs immutable id and text only")
126
- val signal = RuntimeCancellation(); active[id] = signal
127
- try { return sendAdapter?.send(payload, signal) ?: runtime.send(payload, signal) }
128
- finally { active.remove(id) }
129
- }
130
- if (command == "history") {
131
- keys(setOf("offset", "limit"))
132
- fun integer(key: String, default: Int, min: Int, max: Int): Int {
133
- if (!payload.has(key)) return default
134
- val value = payload[key]
135
- if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber) throw CrocheException("invalid_command", "Invalid history page")
136
- val number = value.asDouble
137
- if (!number.isFinite() || number < min || number > max || number != kotlin.math.floor(number)) throw CrocheException("invalid_command", "Invalid history page")
138
- return number.toInt()
139
- }
140
- val offset = integer("offset", 0, 0, 1000000); val limit = integer("limit", 100, 1, 200)
141
- val history = runtime.inspect().at("history").asJsonArray; val page = JsonArray()
142
- history.drop(offset).take(limit).forEach { page.add(it.deepCopy()) }
143
- return obj("messages" to page, "total" to num(history.size()), "offset" to num(offset), "limit" to num(limit))
144
- }
145
- if (command == "budget.set") {
146
- keys(setOf("amount")); val value = payload.at("amount")
147
- if (!value.isJsonPrimitive || !value.asJsonPrimitive.isNumber || !value.asDouble.isFinite() || value.asDouble < 0) throw CrocheException("invalid_command", "Budget requires a finite non-negative amount")
148
- return runtime.adjustBudget(value.asDouble, absolute = true)
149
- }
150
- keys(emptySet())
151
- if (command == "cancel") {
152
- val pending = active.isNotEmpty(); active.values.forEach { it.cancel() }
153
- val host = cancelAdapter?.cancel() ?: false
154
- return obj("requested" to bool(pending || host), "scope" to str(if (cancelAdapter != null) "host" else "control_client"), "rollback" to bool(false))
155
- }
156
- if (command == "sync") runtime.sync()
157
- val view = runtime.inspect()
158
- return when (command) {
159
- "status" -> view.at("status").deepCopy().asJsonObject.apply {
160
- add("control", obj("cancellation_scope" to str(if (cancelAdapter != null) "host" else "control_client")))
161
- }
162
- "sync" -> view.at("status")
163
- "tools" -> view.at("tools")
164
- "budget.get" -> view.at("budget")
165
- else -> throw CrocheException("unsupported_capability", "Unsupported Runtime command")
166
- }
167
- }
168
- override fun close() {
169
- if (!closed.compareAndSet(false, true)) return
170
- active.values.forEach { it.cancel() }
171
- try { post("unregister", identity()) } catch (_: Exception) {}
172
- release()
173
- if (Thread.currentThread() != poller) poller?.join(6000)
174
- }
175
- private fun release() { closed.set(true); lifetime.cancel(); effects.close(); workers.shutdown(); poller?.interrupt() }
176
- }
177
- private fun validId(value: String) = Regex("^[A-Za-z0-9_.:-]{1,200}$").matches(value)
178
- private val publicCodes = setOf("invalid_command", "control_closed", "unsupported_capability", "result_too_large", "busy", "closed", "storage_error", "context_limit", "budget_limit")