@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
@@ -1,80 +1,151 @@
1
1
  import Foundation
2
2
 
3
- /// Code overrides and instance admission go unchanged to Core.
4
- public struct AgentOptions: Sendable {
5
- public var instance: String?
6
- public var fresh: Bool?
7
- public var config: JSON?
8
- public init(instance: String? = nil, fresh: Bool? = nil, config: JSON? = nil) {
9
- self.instance = instance; self.fresh = fresh; self.config = config
3
+ /// Opens a declared agent's main store, or one of its instances. `config` is an app-supplied
4
+ /// patch, the final layer over the definition's applied configuration; it needs an `instance`
5
+ /// and is never stored, so pass it on every open. `handlers` run the tools a patch adds.
6
+ struct LegacyAgentOptions: Sendable {
7
+ var instance: String?
8
+ var config: JSON?
9
+ var handlers: [String: ToolHandler]
10
+ init(instance: String? = nil, config: JSON? = nil, handlers: [String: ToolHandler] = [:]) {
11
+ self.instance = instance; self.config = config; self.handlers = handlers
10
12
  }
13
+ /// Handler callbacks never enter JSON: Core receives their names for its census.
11
14
  var json: JSON {
12
15
  var value: [String: JSON] = [:]
13
16
  if let instance { value["instance"] = .string(instance) }
14
- if let fresh { value["fresh"] = .bool(fresh) }
15
17
  if let config { value["config"] = config }
18
+ if config != nil || !handlers.isEmpty { value["handlers"] = .array(handlers.keys.sorted().map(JSON.string)) }
16
19
  return .object(value)
17
20
  }
18
21
  }
19
22
 
20
- public typealias ProjectToolContext = ToolContext
21
- public typealias ProjectUsageEvent = JSON
22
- public typealias RuntimeDebugEvent = JSON
23
- public typealias MemoryChangedEvent = JSON
23
+ /// One of a declared agent's instances for this project's user.
24
+ struct InstanceInfo: Sendable, Equatable {
25
+ /// Core's `[{instance}]`. A malformed listing fails typed (`core_error`); a key is never read as "".
26
+ static func listing(_ text: String) throws -> [InstanceInfo] {
27
+ guard let list = try JSON(text).array else { throw LegacyCrocheError("core_error", "Core's instance listing is not a list.") }
28
+ return try list.map { InstanceInfo(instance: try required($0, "instance", "instance listing")) }
29
+ }
30
+ let instance: String
31
+ init(instance: String) { self.instance = instance }
32
+ }
33
+
34
+ /// What `deleteData` deletes for this project's user: with no fields, the declared main stores and
35
+ /// every registered instance; with `agent`, that agent's; with `agent` and `instance`, that instance.
36
+ struct DeleteDataOptions: Sendable {
37
+ var agent: String?
38
+ var instance: String?
39
+ init(agent: String? = nil, instance: String? = nil) { self.agent = agent; self.instance = instance }
40
+ var json: JSON {
41
+ var value: [String: JSON] = [:]
42
+ if let agent { value["agent"] = .string(agent) }
43
+ if let instance { value["instance"] = .string(instance) }
44
+ return .object(value)
45
+ }
46
+ }
47
+
48
+ /// A required string in a Core reply. A missing one is a Core bug, so it fails, never as "".
49
+ private func required(_ value: JSON, _ key: String, _ what: String) throws -> String {
50
+ guard let text = value[key].string else { throw LegacyCrocheError("core_error", "Core's \(what) has no \(key).") }
51
+ return text
52
+ }
53
+
54
+ /// The local resolved view: the full resolved app configuration (an AgentConfig), never host or
55
+ /// user fields. Revision values are opaque: compare them for equality only; the effective and
56
+ /// patch revisions are meaningful within the same Core version.
57
+ struct EffectiveAgentConfig: Sendable, Equatable {
58
+ /// The resolved AgentConfig.
59
+ let config: JSON
60
+ /// Opaque identity of the full resolved app configuration, before host or user fields.
61
+ let effectiveRevision: String
62
+ /// Opaque identity of the selected bundled or released project snapshot.
63
+ let revisionId: String
64
+ /// Opaque identity of this instance's config patch; nil without a patch.
65
+ let patchRevision: String?
66
+ init(config: JSON, effectiveRevision: String, revisionId: String, patchRevision: String?) {
67
+ self.config = config; self.effectiveRevision = effectiveRevision; self.revisionId = revisionId; self.patchRevision = patchRevision
68
+ }
69
+ }
70
+
71
+ /// Known agent error codes; other Core and host codes reach `CrocheError.code` verbatim.
72
+ enum CrocheErrorCode {
73
+ /// The instance is open with another config patch.
74
+ static let agentConflict = "agent_conflict"
75
+ static let invalidConfiguration = "invalid_configuration"
76
+ }
77
+
78
+ typealias ProjectToolContext = LegacyToolContext
79
+ typealias ProjectUsageEvent = JSON
80
+ typealias RuntimeDebugEvent = JSON
81
+ typealias MemoryChangedEvent = JSON
24
82
 
25
83
  /// The project-returned agent uses the existing Runtime's port, subscriptions and memory.
26
- public final class CrocheAgent: Sendable {
84
+ final class LegacyCrocheAgent: Sendable {
27
85
  private let core: CoreRuntime
28
- private let runtime: CrocheRuntime
86
+ private let runtime: AgentEngine
29
87
  private let lifetime = ProjectAgentLifetime()
30
88
  private let hub: StreamHub
31
- public let id: String
32
- public let instance: String?
33
- public let created: Bool
34
- public let logId: String
35
- init(core: CoreRuntime, runtime: CrocheRuntime, hub: StreamHub) {
89
+ var engine: AgentEngine { runtime }
90
+ let id: String
91
+ let instance: String?
92
+ let created: Bool
93
+ let logId: String
94
+ init(core: CoreRuntime, runtime: AgentEngine, hub: StreamHub) {
36
95
  self.hub = hub
37
96
  self.core = core; self.runtime = runtime
38
97
  id = core.agentId(); instance = core.instance(); created = core.created(); logId = runtime.logId
39
98
  }
40
- public var name: String? { core.name() }
41
- public var mode: String? { core.mode() }
42
- public var visibleTools: [String]? { core.visibleTools() }
43
- public var closed: Bool { lifetime.closed }
44
- public var memory: CrocheMemory { runtime.memory }
45
- private func check() throws { if closed { throw CrocheError("closed", "The agent is closed.") } }
46
- public func setTools(_ visible: [String]?) async throws {
99
+ var name: String? { core.name() }
100
+ var mode: String? { core.mode() }
101
+ var visibleTools: [String]? { core.visibleTools() }
102
+ func effectiveConfig() throws -> EffectiveAgentConfig {
103
+ let core = self.core
104
+ let value: JSON
105
+ do { value = try JSON(core.effectiveConfig()) } catch { throw LegacyCrocheError(error) }
106
+ guard value["config"].object != nil else { throw LegacyCrocheError("core_error", "Core's effective config has no config.") }
107
+ return EffectiveAgentConfig(config: value["config"], effectiveRevision: try required(value, "effectiveRevision", "effective config"),
108
+ revisionId: try required(value, "revisionId", "effective config"), patchRevision: value["patchRevision"].string)
109
+ }
110
+ /// Closed by `close()`, by the project, or by Core (`deleteData` closes the agents in its scope).
111
+ var closed: Bool { lifetime.closed || core.isClosed() }
112
+ var memory: CrocheMemory { runtime.memory }
113
+ private func check() throws { if closed { throw LegacyCrocheError("closed", "The agent is closed.") } }
114
+ func setTools(_ visible: [String]?) async throws {
47
115
  try check(); let core = self.core
48
- _ = try await CrocheRuntime.offload { try core.setTools(visible: visible); return true }
116
+ _ = try await Offload.run { try core.setTools(visible: visible); return true }
49
117
  }
50
- public func setMode(_ mode: String?) async throws {
118
+ func setMode(_ mode: String?) async throws {
51
119
  try check(); let core = self.core
52
- _ = try await CrocheRuntime.offload { try core.setMode(mode: mode); return true }
120
+ _ = try await Offload.run { try core.setMode(mode: mode); return true }
53
121
  }
54
- public func sync() async throws { try check(); _ = try await runtime.sync() }
55
- public func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> Receipt {
122
+ /// Core's config sync, for Croche's own tests. Not public: Core refreshes before any money
123
+ /// refusal, so an app never syncs by hand (APP-API: sync() removed).
124
+ func sync() async throws { try check(); _ = try await runtime.sync() }
125
+ /// SDK shorthand only; Core generates the id and validates the request.
126
+ func send(_ text: String, _ options: SendOptions = SendOptions()) async throws -> LegacyReceipt {
127
+ try await send(SendInput(input: [.text(text, kind: .user)]), options)
128
+ }
129
+ func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> LegacyReceipt {
56
130
  try check(); return try await runtime.send(input, options: options)
57
131
  }
58
- public func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
132
+ func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> LegacyRequestResult {
59
133
  try check()
60
134
  let result = try await runtime.request(input, options: SendOptions(responseFormat: options.responseFormat), wait: options.wait)
61
135
  try? await runtime.refreshMemory()
62
136
  return result
63
137
  }
64
- public func subscribe(_ options: SubscribeOptions) -> AgentSubscription { hub.subscribe(options) }
65
- public func history(_ options: HistoryOptions) async throws {
66
- try check(); try await runtime.history(before: options.before, limit: options.limit)
67
- }
68
- public func cancel(_ id: String? = nil) async throws {
138
+ func subscribe(_ options: LegacySubscribeOptions) -> Subscription { hub.subscribe(options) }
139
+ func cancel(_ id: String? = nil) async throws {
69
140
  try check()
70
141
  if let id { try await runtime.cancel(id) }
71
142
  else {
72
143
  let core = self.core
73
- _ = try await CrocheRuntime.offload { core.cancelTurn(); return true }
144
+ _ = try await Offload.run { core.cancelTurn(); return true }
74
145
  }
75
146
  }
76
- public func clearHistory() async throws { try check(); try await runtime.clearHistory(); try? await runtime.refreshMemory() }
77
- public func close() async throws {
147
+ func clearHistory() async throws { try check(); try await runtime.clearHistory(); try? await runtime.refreshMemory() }
148
+ func close() async throws {
78
149
  let task = lifetime.close { try await self.runtime.close() }
79
150
  try await task.value
80
151
  }
@@ -95,7 +166,7 @@ private final class ProjectAgentLifetime: @unchecked Sendable {
95
166
  // Internal host construction, shared by platform-owned storage and host tests.
96
167
  struct NativeProjectOptions: Sendable {
97
168
  var host: JSON
98
- var config: JSON
169
+ var bundledConfig: JSON
99
170
  var user: String?
100
171
  var language: String?
101
172
  var handlers: [String: ToolHandler] = [:]
@@ -116,21 +187,21 @@ final class NativeProjectPals: HostPalFactory, @unchecked Sendable {
116
187
  private let lock = NSLock()
117
188
  private var hosts: [String: SwiftHost] = [:]
118
189
  private var all: [SwiftHost] = []
190
+ /// The in-flight open's own handlers and its definition id (nil: the default agent). The
191
+ /// session serializes opens, so at most one table is staged.
192
+ private var staged: (id: String?, handlers: [String: ToolHandler])?
119
193
  let options: NativeProjectOptions
120
194
  init(_ options: NativeProjectOptions) { self.options = options }
121
195
  func pal(agent: String) -> any HostPal {
122
196
  let options = self.options
123
197
  let slot = NativeProjectSlot.storageLabel(agent)
124
- let handlers = options.handlers.mapValues { handler -> ToolHandler in
125
- { invocation, context in
126
- var data = context.data.object ?? [:]
127
- let issued = data.removeValue(forKey: "userId")?.string
128
- data["user"] = options.user.map(JSON.string) ?? .null
129
- data["crocheUserId"] = issued.flatMap { $0.isEmpty ? nil : $0 }.map(JSON.string) ?? .null
130
- do { return try await handler(invocation, ToolContext(data: .object(data), cancellation: context.cancellation, images: context.images)) }
131
- catch { throw CrocheError("effect_failed", "The tool handler failed.") }
132
- }
198
+ // An open's own handlers bind by definition id while it is in flight (the session serializes opens).
199
+ let id = NativeProjectSlot.isMaintenance(agent) ? nil : ((try? JSON(agent).array?.first?.string) ?? agent)
200
+ let own = lock.withLock { () -> [String: ToolHandler] in
201
+ guard let id, let staged, staged.id == nil || staged.id == id else { return [:] }
202
+ return staged.handlers
133
203
  }
204
+ let handlers = tools(own)
134
205
  // A fresh host for every request: record and default-agent PALs are separate.
135
206
  let host = SwiftHost(storage: options.storage(slot), secrets: options.secretStorage(slot),
136
207
  attestor: options.attestor, http: options.fetch, tools: handlers,
@@ -139,9 +210,29 @@ final class NativeProjectPals: HostPalFactory, @unchecked Sendable {
139
210
  lock.withLock { if !NativeProjectSlot.isMaintenance(agent) { hosts[agent] = host }; all.append(host) }
140
211
  return host
141
212
  }
213
+ func stage(_ id: String?, _ handlers: [String: ToolHandler]) { lock.withLock { staged = (id, handlers) } }
214
+ func unstage() { lock.withLock { staged = nil } }
215
+ /// The project's handlers plus an instance's own (Core refuses a shadowing name), with the
216
+ /// project tool context.
217
+ private func tools(_ own: [String: ToolHandler]) -> [String: ToolHandler] {
218
+ let options = self.options
219
+ return options.handlers.merging(own) { _, child in child }.mapValues { handler -> ToolHandler in
220
+ { invocation, context in
221
+ var data = context.data.object ?? [:]
222
+ let issued = data.removeValue(forKey: "userId")?.string
223
+ data["user"] = options.user.map(JSON.string) ?? .null
224
+ data["crocheUserId"] = issued.flatMap { $0.isEmpty ? nil : $0 }.map(JSON.string) ?? .null
225
+ // The throw goes to Core as it is (APP-API: the tool_failed remap is Core's); the
226
+ // host's own "nothing ran" rule (handlerError) still applies on the way out.
227
+ return try await handler(invocation, LegacyToolContext(data: .object(data), cancellation: context.cancellation, images: context.images))
228
+ }
229
+ }
230
+ }
231
+ /// Latest successful open wins: that instance slot's future invocations use these handlers.
232
+ func rebind(_ slot: String, _ own: [String: ToolHandler]) throws { try host(slot).replaceTools(tools(own)) }
142
233
  func host(_ slot: String) throws -> SwiftHost {
143
234
  try lock.withLock {
144
- guard let host = hosts[slot] else { throw CrocheError("core_error", "Core opened an agent without requesting its host.") }
235
+ guard let host = hosts[slot] else { throw LegacyCrocheError("core_error", "Core opened an agent without requesting its host.") }
145
236
  return host
146
237
  }
147
238
  }
@@ -154,91 +245,117 @@ final class NativeProjectPals: HostPalFactory, @unchecked Sendable {
154
245
  }
155
246
 
156
247
  /// Core owns configuration selection, agent census, instances, locks and project identity.
157
- public final class Croche: Sendable {
248
+ final class LegacyCroche: Sendable {
158
249
  private let core: CoreProject
159
250
  private let pals: NativeProjectPals
160
251
  private let session: NativeProjectSession
161
252
  private init(core: CoreProject, pals: NativeProjectPals) {
162
253
  self.core = core; self.pals = pals; session = NativeProjectSession(core: core, pals: pals)
163
254
  }
164
- public var user: String? { core.user() }
165
- public var installationId: String? { core.installationId() }
166
- public var crocheUserId: String? { core.crocheUserId() }
167
- public var agentIds: [String] { core.agentIds() }
255
+ var user: String? { core.user() }
256
+ var installationId: String? { core.installationId() }
257
+ var crocheUserId: String? { core.crocheUserId() }
258
+ var agentIds: [String] { core.agentIds() }
168
259
  var applied: JSON { (try? JSON(core.applied())) ?? .null }
169
- public static func open(_ options: OpenOptions) async throws -> Croche {
170
- let native = try await CrocheRuntime.offload { try options.native() }
260
+ static func open(_ options: LegacyOpenOptions) async throws -> LegacyCroche {
261
+ let native = try await Offload.run { try options.native() }
171
262
  return try await open(native)
172
263
  }
173
- public static func deleteStore(_ options: OpenOptions, agent: String? = nil) async throws {
174
- let native = try await CrocheRuntime.offload { try options.native() }
175
- try await deleteStore(native, agent: agent)
176
- }
177
- static func open(_ options: NativeProjectOptions) async throws -> Croche {
178
- CrocheRuntime.warnIfReleaseBuildCarriesDebugKey(options.host)
264
+ static func open(_ options: NativeProjectOptions) async throws -> LegacyCroche {
265
+ AgentEngine.warnIfReleaseBuildCarriesDebugKey(options.host)
179
266
  let pals = NativeProjectPals(options)
180
267
  let context = ProjectObserverContext(user: options.user)
181
268
  var host = options.host
182
269
  if let attestor = options.attestor { host["attestationPlatform"] = .string(attestor.platform) }
183
270
  let wire = ProjectOpenOptions(host: try projectText(host), user: options.user,
184
- config: try projectText(options.config), handlers: Array(options.handlers.keys), language: options.language,
271
+ bundledConfig: try projectText(options.bundledConfig), handlers: Array(options.handlers.keys), language: options.language,
185
272
  streaming: options.streaming, backgroundSync: options.backgroundSync,
186
273
  maintenanceIntervalMs: options.maintenanceIntervalMs)
187
274
  do {
188
- let core = try await CrocheRuntime.offload {
275
+ let core = try await Offload.run {
189
276
  try CoreProject.open(pals: pals, options: wire, onUsage: options.onUsage.map { listener in EventHook { listener(context.usage($0)) } },
190
277
  onDebug: options.onDebugEvent.map(EventHook.init))
191
278
  }
192
279
  context.attach(core)
193
- return Croche(core: core, pals: pals)
280
+ return LegacyCroche(core: core, pals: pals)
194
281
  } catch { pals.stop(); throw error }
195
282
  }
196
- static func deleteStore(_ options: NativeProjectOptions, agent: String? = nil) async throws {
197
- let pals = NativeProjectPals(options); defer { pals.stop() }
198
- let host = try projectText(options.host), config = try projectText(options.config)
199
- _ = try await CrocheRuntime.offload {
200
- try ffiProjectDelete(pals: pals, host: host, user: options.user, config: config, agent: agent); return true
201
- }
202
- }
203
- public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
283
+ func agent(_ id: String? = nil, _ options: LegacyAgentOptions = LegacyAgentOptions()) async throws -> LegacyCrocheAgent {
204
284
  try await session.agent(id, options)
205
285
  }
206
- public func close() async throws { try await session.close() }
286
+ /// This user's instances of a declared agent, sorted by key.
287
+ func listInstances(_ id: String) async throws -> [InstanceInfo] {
288
+ let core = self.core
289
+ let text = try await Offload.run { try core.listInstances(agentId: id) }
290
+ return try InstanceInfo.listing(text)
291
+ }
292
+ /// Deletes this user's stores on this device. Core first closes this project's open agents in
293
+ /// scope; a store open elsewhere fails `store_busy` and nothing is deleted.
294
+ func deleteData(_ options: DeleteDataOptions = DeleteDataOptions()) async throws {
295
+ try await session.deleteData(options)
296
+ }
297
+ func close() async throws { try await session.close() }
207
298
  }
208
299
 
209
300
  private actor NativeProjectSession {
210
301
  private let core: CoreProject
211
302
  private let pals: NativeProjectPals
212
- private var agents: [String: CrocheAgent] = [:]
303
+ private var agents: [String: LegacyCrocheAgent] = [:]
213
304
  private var closing: Task<Void, Error>?
214
305
  private var admission: Task<Void, Never>?
215
306
  init(core: CoreProject, pals: NativeProjectPals) { self.core = core; self.pals = pals }
216
- public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
217
- guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
307
+ func agent(_ id: String? = nil, _ options: LegacyAgentOptions = LegacyAgentOptions()) async throws -> LegacyCrocheAgent {
308
+ try await admit { try await self.openAgent(id, options: options) }
309
+ }
310
+ func deleteData(_ options: DeleteDataOptions) async throws {
311
+ guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
312
+ let core = self.core, text = try projectText(options.json)
313
+ var failure: Error?
314
+ do { _ = try await Offload.run { try core.deleteData(options: text); return true } } catch { failure = error }
315
+ // Core owns the scope and the close decision, including closes before a failed deletion.
316
+ await evictClosed()
317
+ if let failure { throw failure }
318
+ }
319
+ /// Ends and forgets the wrappers whose runtime Core closed, so a later open gets a new one.
320
+ private func evictClosed() async {
321
+ for (slot, agent) in agents where agent.closed { agents[slot] = nil; try? await agent.close() }
322
+ }
323
+ private func admit(_ open: @escaping @Sendable () async throws -> LegacyCrocheAgent) async throws -> LegacyCrocheAgent {
324
+ guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
218
325
  let previous = admission
219
- let task = Task { await previous?.value; return try await self.openAgent(id, options: options) }
326
+ let task = Task { await previous?.value; return try await open() }
220
327
  admission = Task { _ = try? await task.value }
221
328
  return try await task.value
222
329
  }
223
- private func openAgent(_ id: String?, options: AgentOptions) async throws -> CrocheAgent {
224
- guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
225
- let core = self.core, text = try projectText(options.json)
226
- // Cached calls still go to Core, which checks overrides and admission.
227
- let handle = try await CrocheRuntime.offload { try core.agentWithOptions(id: id, options: text) }
228
- guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
330
+ private func openAgent(_ id: String?, options: LegacyAgentOptions) async throws -> LegacyCrocheAgent {
331
+ guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
332
+ let core = self.core, pals = self.pals, text = try projectText(options.json)
333
+ await evictClosed()
334
+ // Opens are serialized, so the staged table is this open's.
335
+ let patched = options.config != nil
336
+ if patched { pals.stage(id, options.handlers) }
337
+ defer { if patched { pals.unstage() } }
338
+ // Cached calls still go to Core, which checks admission and the patch's identity.
339
+ let handle = try await Offload.run { try core.agentWithOptions(id: id, options: text) }
340
+ return try await attach(handle, handlers: patched ? options.handlers : nil)
341
+ }
342
+ /// `handlers`: a patched open Core admitted, so its handlers replace that slot's (latest wins).
343
+ private func attach(_ handle: CoreRuntime, handlers: [String: ToolHandler]? = nil) async throws -> LegacyCrocheAgent {
344
+ guard closing == nil else { throw LegacyCrocheError("closed", "The project is closed.") }
229
345
  let slot = try handle.instance().map { try projectText(.array([.string(handle.agentId()), .string($0)])) } ?? handle.agentId()
346
+ if let handlers { try pals.rebind(slot, handlers) }
230
347
  if let existing = agents[slot], !existing.closed { return existing }
231
- let runtime = try await CrocheRuntime.adopt(core: handle, host: pals.host(slot))
232
- let agent = CrocheAgent(core: handle, runtime: runtime, hub: await runtime.subscriptionHub!)
233
- if closing != nil { try await agent.close(); throw CrocheError("closed", "The project is closed.") }
348
+ let runtime = try await AgentEngine.adopt(core: handle, host: pals.host(slot))
349
+ let agent = LegacyCrocheAgent(core: handle, runtime: runtime, hub: await runtime.subscriptionHub!)
350
+ if closing != nil { try await agent.close(); throw LegacyCrocheError("closed", "The project is closed.") }
234
351
  agents[slot] = agent
235
352
  return agent
236
353
  }
237
- public func close() async throws {
354
+ func close() async throws {
238
355
  if let closing { return try await closing.value }
239
356
  let core = self.core, pals = self.pals
240
357
  let task = Task {
241
- _ = try await CrocheRuntime.offload { core.close(); return true }
358
+ _ = try await Offload.run { core.close(); return true }
242
359
  for agent in self.agents.values { try await agent.close() }
243
360
  pals.stop()
244
361
  }
@@ -249,10 +366,7 @@ private actor NativeProjectSession {
249
366
  private func projectText(_ value: JSON) throws -> String {
250
367
  let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
251
368
  do { return String(decoding: try encoder.encode(value), as: UTF8.self) }
252
- catch { throw CrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
253
- }
254
- private func ffiProjectDelete(pals: any HostPalFactory, host: String, user: String?, config: String, agent: String?) throws {
255
- try deleteStore(pals: pals, host: host, user: user, config: config, agent: agent)
369
+ catch { throw LegacyCrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
256
370
  }
257
371
 
258
372
  private final class ProjectObserverContext: @unchecked Sendable {