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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -0,0 +1,177 @@
1
+ import Foundation
2
+
3
+ /// One entry = one tool, by its registered name. `bind` REPLACES the registration bind as a
4
+ /// whole; nil keeps it. Core validates every field.
5
+ public struct ToolEntry: Sendable, ExpressibleByStringLiteral {
6
+ public var tool: String
7
+ public var bind: [String: JSON]?
8
+ public var commands: [String]?
9
+ public var guide: String?
10
+ public init(tool: String, bind: [String: JSON]? = nil, commands: [String]? = nil, guide: String? = nil) {
11
+ self.tool = tool; self.bind = bind; self.commands = commands; self.guide = guide
12
+ }
13
+ public init(stringLiteral name: String) { self.init(tool: name) }
14
+ var json: JSON {
15
+ guard bind != nil || commands != nil || guide != nil else { return .string(tool) }
16
+ var fields: [String: JSON] = ["tool": .string(tool)]
17
+ if let bind { fields["bind"] = .object(bind) }
18
+ if let commands { fields["commands"] = .array(commands.map(JSON.string)) }
19
+ if let guide { fields["guide"] = .string(guide) }
20
+ return .object(fields)
21
+ }
22
+ }
23
+
24
+ /// One entry = one path or glob, e.g. `"faq/**"`.
25
+ public struct WikiEntry: Sendable, ExpressibleByStringLiteral {
26
+ public var doc: String
27
+ public var guide: String?
28
+ public init(doc: String, guide: String? = nil) { self.doc = doc; self.guide = guide }
29
+ public init(stringLiteral doc: String) { self.init(doc: doc) }
30
+ var json: JSON {
31
+ guard let guide else { return .string(doc) }
32
+ return .object(["doc": .string(doc), "guide": .string(guide)])
33
+ }
34
+ }
35
+
36
+ /// `.all` = every registered; `[]` = none. In `AgentOptions`, nil also means all.
37
+ public enum Scope<Entry: Sendable>: Sendable, ExpressibleByArrayLiteral {
38
+ case all
39
+ case list([Entry])
40
+ public init(arrayLiteral entries: Entry...) { self = .list(entries) }
41
+ }
42
+ public typealias ToolScope = Scope<ToolEntry>
43
+ public typealias WikiScope = Scope<WikiEntry>
44
+
45
+ /// `{path, description, markdown}` or `{path, description, file}`. iOS resolves `file` as a
46
+ /// main-bundle resource or a `file://` URL, when Core reads it.
47
+ public enum WikiDoc: Sendable, Equatable {
48
+ case markdown(path: String, description: String, markdown: String)
49
+ case file(path: String, description: String, file: String)
50
+ var json: JSON {
51
+ switch self {
52
+ case let .markdown(path, description, markdown):
53
+ .object(["path": .string(path), "description": .string(description), "markdown": .string(markdown)])
54
+ case let .file(path, description, file):
55
+ .object(["path": .string(path), "description": .string(description), "file": .string(file)])
56
+ }
57
+ }
58
+ init(_ value: JSON) throws {
59
+ guard let path = value["path"].string, let description = value["description"].string else {
60
+ throw CrocheError(code: "internal", message: "Core's wiki document has no path or description.", category: .internal)
61
+ }
62
+ if let markdown = value["markdown"].string { self = .markdown(path: path, description: description, markdown: markdown) }
63
+ else if let file = value["file"].string { self = .file(path: path, description: description, file: file) }
64
+ else { throw CrocheError(code: "internal", message: "Core's wiki document has no body.", category: .internal) }
65
+ }
66
+ }
67
+
68
+ public struct AgentInstance: Sendable {
69
+ public var id: String
70
+ /// A patch over the agent config. NOT saved: pass it on every open.
71
+ public var config: JSON?
72
+ public init(id: String, config: JSON? = nil) { self.id = id; self.config = config }
73
+ }
74
+
75
+ public struct AgentOptions: Sendable {
76
+ /// nil = the agent's default instance.
77
+ public var instance: AgentInstance?
78
+ /// nil or `.all` = all registered; `[]` = none.
79
+ public var tools: ToolScope?
80
+ public var wiki: WikiScope?
81
+ public init(instance: AgentInstance? = nil, tools: ToolScope? = nil, wiki: WikiScope? = nil) {
82
+ self.instance = instance; self.tools = tools; self.wiki = wiki
83
+ }
84
+ var json: JSON {
85
+ var fields: [String: JSON] = [:]
86
+ if let instance {
87
+ var value: [String: JSON] = ["id": .string(instance.id)]
88
+ if let config = instance.config { value["config"] = config }
89
+ fields["instance"] = .object(value)
90
+ }
91
+ if let tools { fields["tools"] = tools.json(\.json) }
92
+ if let wiki { fields["wiki"] = wiki.json(\.json) }
93
+ return .object(fields)
94
+ }
95
+ }
96
+
97
+ public struct OpenOptions: Sendable {
98
+ public var projectKey: String
99
+ public var user: String?
100
+ /// nil = omitted: Core chooses (ARCHITECTURE §2: the device locale is a PAL fact, never an SDK default).
101
+ public var language: String?
102
+ public var bundledConfig: JSON
103
+ /// nil = omitted; `[]` is sent as `[]` (APP-API gives an empty list its own meaning).
104
+ public var tools: [ToolRegistration]?
105
+ /// nil = omitted; `[]` is sent as `[]`.
106
+ public var wiki: [WikiDoc]?
107
+ /// ARCHITECTURE §2a; nil = the platform default.
108
+ public var storage: (any StoragePal)?
109
+ public var serverKey: String?
110
+ public var debugKey: String?
111
+ public init(projectKey: String, bundledConfig: JSON, user: String? = nil, language: String? = nil,
112
+ tools: [ToolRegistration]? = nil, wiki: [WikiDoc]? = nil, storage: (any StoragePal)? = nil,
113
+ serverKey: String? = nil, debugKey: String? = nil) {
114
+ self.projectKey = projectKey; self.bundledConfig = bundledConfig; self.user = user; self.language = language
115
+ self.tools = tools; self.wiki = wiki; self.storage = storage; self.serverKey = serverKey; self.debugKey = debugKey
116
+ }
117
+ /// The WHOLE options as JSON (Atlas's S1 ABI): only the opaque tool and storage references
118
+ /// become null; the tools themselves travel beside it as registrations, in this order.
119
+ var json: JSON {
120
+ var fields: [String: JSON] = ["projectKey": .string(projectKey), "bundledConfig": bundledConfig]
121
+ if let user { fields["user"] = .string(user) }
122
+ if let language { fields["language"] = .string(language) }
123
+ if let tools { fields["tools"] = .array(tools.map(\.json)) }
124
+ if let wiki { fields["wiki"] = .array(wiki.map(\.json)) }
125
+ if storage != nil { fields["storage"] = .null }
126
+ if let serverKey { fields["serverKey"] = .string(serverKey) }
127
+ if let debugKey { fields["debugKey"] = .string(debugKey) }
128
+ return .object(fields)
129
+ }
130
+ }
131
+
132
+ /// `Croche.registerBackground`. `storage` = the one `open()` uses.
133
+ public struct BackgroundOptions: Sendable {
134
+ public var sink: (@Sendable (BackgroundEvent) -> Void)?
135
+ public var storage: (any StoragePal)?
136
+ public init(sink: (@Sendable (BackgroundEvent) -> Void)? = nil, storage: (any StoragePal)? = nil) {
137
+ self.sink = sink; self.storage = storage
138
+ }
139
+ /// As `OpenOptions.json`: the opaque sink and storage become null.
140
+ var json: JSON {
141
+ var fields: [String: JSON] = [:]
142
+ if sink != nil { fields["sink"] = .null }
143
+ if storage != nil { fields["storage"] = .null }
144
+ return .object(fields)
145
+ }
146
+ }
147
+
148
+ /// `croche.deleteData(_:)` on an opened Croche: `{agent}`, `{agent, instance}` or `{}`. Core rejects
149
+ /// `{instance}` alone. A recovery handle accepts only `{}` or no scope.
150
+ public struct DataScope: Sendable {
151
+ public var agent: String?
152
+ public var instance: String?
153
+ public init(agent: String? = nil, instance: String? = nil) { self.agent = agent; self.instance = instance }
154
+ var json: JSON {
155
+ var fields: [String: JSON] = [:]
156
+ if let agent { fields["agent"] = .string(agent) }
157
+ if let instance { fields["instance"] = .string(instance) }
158
+ return .object(fields)
159
+ }
160
+ }
161
+
162
+ extension Scope {
163
+ func json(_ entry: (Entry) -> JSON) -> JSON {
164
+ switch self {
165
+ case .all: .string("all")
166
+ case .list(let entries): .array(entries.map(entry))
167
+ }
168
+ }
169
+ }
170
+
171
+ /// The second argument of `Croche.open(_:recovery:)`. Swift serializes `{"recover": recover}`;
172
+ /// Core alone validates it (`"delete"` today; anything else is `invalid_request`).
173
+ public struct RecoveryOptions: Sendable, Equatable {
174
+ public let recover: String
175
+ public init(recover: String) { self.recover = recover }
176
+ var json: JSON { .object(["recover": .string(recover)]) }
177
+ }
@@ -0,0 +1,61 @@
1
+ import Foundation
2
+
3
+ /// Core's one result envelope. A plugin's output remains arbitrary JSON.
4
+ public enum RunToolResult: Sendable {
5
+ public struct Ok: Sendable {
6
+ public let id: String
7
+ public let output: JSON
8
+ public let attachments: [AppStreamContract.Attachment]
9
+ public let cost: Double?
10
+ public let costStatus: String
11
+ }
12
+ public struct Failed: Sendable {
13
+ public let id: String, code: String, message: String
14
+ public let category: ErrorCategory
15
+ public let cost: Double?
16
+ public let costStatus: String
17
+ }
18
+ public struct Lost: Sendable {
19
+ public let id: String, code: String, message: String
20
+ public let category: ErrorCategory
21
+ }
22
+ case ok(Ok)
23
+ case failed(Failed)
24
+ case lost(Lost)
25
+ case unknown(status: String, fields: JSON)
26
+
27
+ init(_ value: JSON) throws {
28
+ func string(_ key: String) throws -> String {
29
+ guard let result = value[key].string else { throw malformed("runTool \(key)") }
30
+ return result
31
+ }
32
+ func category() throws -> ErrorCategory {
33
+ guard let result = ErrorCategory(rawValue: try string("category")) else { throw malformed("runTool category") }
34
+ return result
35
+ }
36
+ switch try string("status") {
37
+ case "ok":
38
+ guard value.object?["output"] != nil else { throw malformed("runTool output") }
39
+ let attachments = try JSONDecoder().decode([AppStreamContract.Attachment].self,
40
+ from: Data(text(value["attachments"]).utf8))
41
+ self = .ok(Ok(id: try string("id"), output: value["output"], attachments: attachments,
42
+ cost: value["cost"].number, costStatus: try string("costStatus")))
43
+ case "failed":
44
+ self = .failed(Failed(id: try string("id"), code: try string("code"), message: try string("message"),
45
+ category: try category(), cost: value["cost"].number, costStatus: try string("costStatus")))
46
+ case "lost":
47
+ self = .lost(Lost(id: try string("id"), code: try string("code"), message: try string("message"), category: try category()))
48
+ case let status: self = .unknown(status: status, fields: value)
49
+ }
50
+ }
51
+ }
52
+
53
+ public extension Croche {
54
+ /// Cancelling the Task detaches this caller; Core owns the dispatched effect.
55
+ func runTool(_ name: String, args: [String: JSON], id: String) async throws -> RunToolResult {
56
+ let core = self.core, arguments = text(.object(args)), options = text(.object(["id": .string(id)]))
57
+ return try RunToolResult(reply(try await cancellable {
58
+ try core.runTool(name: name, argsJson: arguments, optionsJson: options, cancel: $0)
59
+ }))
60
+ }
61
+ }
@@ -0,0 +1,95 @@
1
+ import Foundation
2
+
3
+ /// ARCHITECTURE §2a: the ONE storage interface, the same methods on every SDK. Omitted in
4
+ /// `OpenOptions` = the platform default (Application Support files, Keychain secrets). A custom
5
+ /// store (servers: KV, Redis, S3) implements exactly this. Keys and layout are Core's.
6
+ public protocol StoragePal: Sendable {
7
+ /// nil = absent.
8
+ func read(_ key: String) async throws -> String?
9
+ /// ATOMIC REPLACE, durable on return.
10
+ func write(_ key: String, _ value: String) async throws
11
+ /// A real delete; absent = ok.
12
+ func remove(_ key: String) async throws
13
+ /// Keys starting with `prefix`, any order.
14
+ func list(_ prefix: String) async throws -> [String]
15
+ /// Exclusive across processes; never waits. Another owner holding it is the FACT
16
+ /// `.held`, not an error; Core maps it. A throw is a failure (Core's `storage_error`).
17
+ func lock(_ name: String) async throws -> LockOutcome
18
+ func unlock(_ name: String) async throws
19
+ var secrets: any SecretsPal { get }
20
+ }
21
+
22
+ /// What `lock` found (ARCHITECTURE §2a).
23
+ public enum LockOutcome: Sendable, Equatable { case acquired, held }
24
+
25
+ public protocol SecretsPal: Sendable {
26
+ func read(_ key: String) async throws -> String?
27
+ func write(_ key: String, _ value: String) async throws
28
+ func remove(_ key: String) async throws
29
+ }
30
+
31
+ /// A storage failure reports facts only (ARCHITECTURE §2/§2a, Leo 12:39Z): its text, for
32
+ /// debugging. No code or category crosses, whatever the app threw; Core reports `storage_error`.
33
+ func storageFailure(_ error: Error) -> CoreStorageFailure {
34
+ if let error = error as? CoreStorageFailure { return error }
35
+ if let error = error as? CrocheError { return .Failure(detail: error.message) }
36
+ if case let .Failure(_, message)? = error as? FfiError { return .Failure(detail: message) }
37
+ return .Failure(detail: "\(error)")
38
+ }
39
+
40
+ /// The app's `StoragePal` as Core's callback. Core calls it on a Core thread (never the
41
+ /// cooperative pool: see `blocking`), so waiting for the app's async method is safe there.
42
+ /// Whatever the app throws reaches Core as text only; contention is `lock`'s `.held`.
43
+ final class CoreStorageAdapter: CoreStoragePal, @unchecked Sendable {
44
+ let storage: any StoragePal
45
+ init(_ storage: any StoragePal) { self.storage = storage }
46
+
47
+ private func wait<T: Sendable>(_ body: @escaping @Sendable () async throws -> T) throws -> T {
48
+ let done = DispatchSemaphore(value: 0)
49
+ nonisolated(unsafe) var result: Result<T, Error>!
50
+ appTask { result = await Result { try await body() }; done.signal() }
51
+ done.wait()
52
+ do { return try result.get() } catch { throw storageFailure(error) }
53
+ }
54
+
55
+ func read(key: String) throws -> String? { let s = storage; return try wait { try await s.read(key) } }
56
+ func write(key: String, value: String) throws { let s = storage; try wait { try await s.write(key, value) } }
57
+ func remove(key: String) throws { let s = storage; try wait { try await s.remove(key) } }
58
+ func list(prefix: String) throws -> [String] { let s = storage; return try wait { try await s.list(prefix) } }
59
+ func lock(name: String) throws -> PalLockOutcome {
60
+ let s = storage
61
+ switch try wait({ try await s.lock(name) }) { case .acquired: return .acquired; case .held: return .held }
62
+ }
63
+ func unlock(name: String) throws { let s = storage; try wait { try await s.unlock(name) } }
64
+ func readSecret(key: String) throws -> String? { let s = storage.secrets; return try wait { try await s.read(key) } }
65
+ func writeSecret(key: String, value: String) throws { let s = storage.secrets; try wait { try await s.write(key, value) } }
66
+ func removeSecret(key: String) throws { let s = storage.secrets; try wait { try await s.remove(key) } }
67
+ }
68
+
69
+ private extension Result where Failure == Error {
70
+ init(_ body: () async throws -> Success) async {
71
+ do { self = .success(try await body()) } catch { self = .failure(error) }
72
+ }
73
+ }
74
+
75
+ /// The platform default store as Core's storage argument (Keel 16:08Z): the argument always
76
+ /// carries a PAL, the app's or this one; Core has no storage default of its own. The options JSON
77
+ /// still omits `storage` here, so Core can tell the default from an app store.
78
+ final class PlatformStorageAdapter: CoreStoragePal, @unchecked Sendable {
79
+ let pal: PlatformPal
80
+ init(_ pal: PlatformPal) { self.pal = pal }
81
+
82
+ private func call<T>(_ body: () throws -> T) throws -> T {
83
+ do { return try body() } catch { throw storageFailure(error) }
84
+ }
85
+
86
+ func read(key: String) throws -> String? { try call { try pal.read(key: key) } }
87
+ func write(key: String, value: String) throws { try call { try pal.write(key: key, value: value) } }
88
+ func remove(key: String) throws { try call { try pal.remove(key: key) } }
89
+ func list(prefix: String) throws -> [String] { try call { try pal.list(prefix: prefix) } }
90
+ func lock(name: String) throws -> PalLockOutcome { try call { try pal.lock(key: name) } }
91
+ func unlock(name: String) throws { pal.unlock(key: name) }
92
+ func readSecret(key: String) throws -> String? { try call { try pal.readSecret(key: key) } }
93
+ func writeSecret(key: String, value: String) throws { try call { try pal.writeSecret(key: key, value: value) } }
94
+ func removeSecret(key: String) throws { try call { try pal.removeSecret(key: key) } }
95
+ }
@@ -0,0 +1,105 @@
1
+ #if CROCHE_TEST_HOOKS
2
+ import Foundation
3
+
4
+ // TEST-HOOKS BUILDS ONLY (CROCHE_SWIFT_TEST_HOOKS=1, Atlas's shared recipe): the private
5
+ // `openForTests` entry with a fixture Cloud origin. Never compiled into a release; the release
6
+ // bindings have no `openForTests`.
7
+
8
+ /// While a test sets `serve`, `Croche.open` opens through `openForTests` with the fixture origin,
9
+ /// and every HTTP effect is answered in-process by `serve`. No request leaves the process.
10
+ enum FixtureCloud {
11
+ /// The origin Core is given. Nothing listens there: the host answers in-process.
12
+ static let origin = "http://127.0.0.1:9"
13
+ /// Hosts the fixture may name besides the origin (its registration's gateway).
14
+ static let gatewayHosts: Set<String> = ["gateway.example"]
15
+ nonisolated(unsafe) static var serve: RuntimeHTTP?
16
+ /// Image bytes by URL, served to a pinned fetch where the platform dials pins (macOS).
17
+ nonisolated(unsafe) static var images: [String: Data] = [:]
18
+ /// `(url, connectTo)` of every image fetch served, so a test can assert the pin.
19
+ nonisolated(unsafe) static var pinned: [(url: String, pin: String?)] = []
20
+ /// URLs refused because they were outside the fixture: a test asserts this stays empty.
21
+ nonisolated(unsafe) static var refused: [String] = []
22
+ static let lock = NSLock()
23
+ }
24
+
25
+ /// The platform PAL with HTTP and DNS answered by the fixture; everything else is the real PAL.
26
+ final class FixtureHost: HostPal, @unchecked Sendable {
27
+ let base: PlatformPal
28
+ private let serve: RuntimeHTTP
29
+ init(base: PlatformPal, serve: @escaping RuntimeHTTP) { self.base = base; self.serve = serve }
30
+
31
+ func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws {
32
+ // The platform's own pin rule first (iOS: a named pin is capability_unsupported).
33
+ if request.connectTo != nil && !PlatformHTTP.dialsNamedPins { try effect { try PlatformHTTP.check(request) } }
34
+ if let image = FixtureCloud.lock.withLock({ FixtureCloud.images[request.url] }) {
35
+ FixtureCloud.lock.withLock { FixtureCloud.pinned.append((request.url, request.connectTo)) }
36
+ sink.head(status: 200, headers: [PalHeader(name: "content-type", value: "image/png")])
37
+ _ = sink.chunk(bytes: image)
38
+ return
39
+ }
40
+ let host = URL(string: request.url)?.host ?? ""
41
+ guard request.url.hasPrefix(FixtureCloud.origin + "/") || FixtureCloud.gatewayHosts.contains(host) else {
42
+ FixtureCloud.lock.withLock { FixtureCloud.refused.append(request.url) }
43
+ throw CorePalError.Failure(code: "host_unavailable", detail: "Outside the fixture: \(request.url)")
44
+ }
45
+ let serve = self.serve
46
+ try effect {
47
+ _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
48
+ try await SwiftHost.adapt(serve, request, sink, signal); return true
49
+ }
50
+ }
51
+ }
52
+ /// A fixed public answer: no DNS query leaves the process.
53
+ func resolve(host: String, cancel: CancelToken) throws -> [String] { ["93.184.216.34"] }
54
+
55
+ func streamPlatform() -> HostStreamPlatform { base.streamPlatform() }
56
+ func imageCodecAvailable() -> Bool { base.imageCodecAvailable() }
57
+ func readImage(request: PalImageReadRequest, cancel: CancelToken) throws -> Data { try base.readImage(request: request, cancel: cancel) }
58
+ func prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) throws -> PalImageBytes { try base.prepareImage(source: source, plan: plan, cancel: cancel) }
59
+ func releaseImage(capture: String) { base.releaseImage(capture: capture) }
60
+ func decodeImage(bytes: Data, options: PalImageDecodeOptions, cancel: CancelToken) throws -> PalDecodedImage { try base.decodeImage(bytes: bytes, options: options, cancel: cancel) }
61
+ func renderImage(request: PalImageRenderRequest, cancel: CancelToken) throws -> Data { try base.renderImage(request: request, cancel: cancel) }
62
+ func releaseDecodedImage(handle: String) { base.releaseDecodedImage(handle: handle) }
63
+ func platformFacts() -> PalPlatformFacts { base.platformFacts() }
64
+ func readAsset(path: String) throws -> Data? { try base.readAsset(path: path) }
65
+ func list(prefix: String) throws -> [String] { try base.list(prefix: prefix) }
66
+ func read(key: String) throws -> String? { try base.read(key: key) }
67
+ func write(key: String, value: String) throws { try base.write(key: key, value: value) }
68
+ func readSecret(key: String) throws -> String? { try base.readSecret(key: key) }
69
+ func writeSecret(key: String, value: String) throws { try base.writeSecret(key: key, value: value) }
70
+ func remove(key: String) throws { try base.remove(key: key) }
71
+ func removeSecret(key: String) throws { try base.removeSecret(key: key) }
72
+ func lock(key: String) throws -> PalLockOutcome { try base.lock(key: key) }
73
+ func unlock(key: String) throws { try base.unlock(key: key) }
74
+ func storeIdentity() -> String { base.storeIdentity() }
75
+ func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput { try base.tool(invocation: invocation, cancel: cancel) }
76
+ func attest(request: String, timeoutMs: UInt64) throws -> String { try base.attest(request: request, timeoutMs: timeoutMs) }
77
+ func nowMs() -> Double { base.nowMs() }
78
+ func utcOffsetMinutes(atMs: Double) -> Int64 { base.utcOffsetMinutes(atMs: atMs) }
79
+ func random() -> String { base.random() }
80
+ func wake(atMs: Double?) { base.wake(atMs: atMs) }
81
+ func schedule(entries: String) throws { try base.schedule(entries: entries) }
82
+ func registerBackground(identifier: String, wake: CoreBackgroundWake) throws { try base.registerBackground(identifier: identifier, wake: wake) }
83
+ func archiveAppendLine(entry: String, line: String) throws { try base.archiveAppendLine(entry: entry, line: line) }
84
+ func archiveReadLines(entry: String) throws -> [String] { try base.archiveReadLines(entry: entry) }
85
+ func archiveReplaceLines(entry: String, lines: [String]) throws { try base.archiveReplaceLines(entry: entry, lines: lines) }
86
+ func archiveRemove(entry: String) throws { try base.archiveRemove(entry: entry) }
87
+ func archiveEntries(prefix: String) throws -> [ArchiveEntry] { try base.archiveEntries(prefix: prefix) }
88
+ func storageCapability() -> StorageCapability { base.storageCapability() }
89
+ }
90
+
91
+ extension Croche {
92
+ /// `open` through the private test entry, when a test has set `FixtureCloud.serve`.
93
+ static func fixtureOpen(_ open: String, _ registrations: [CoreToolRegistration], _ storage: (any StoragePal)?,
94
+ _ recoveryJson: String?, _ serve: @escaping RuntimeHTTP) async throws -> Croche {
95
+ let base = try platformHost(), host = FixtureHost(base: base, serve: serve)
96
+ let store = storageArgument(storage, base)
97
+ return Croche(core: try await owner({ try CoreCroche.openForTests(openJson: open, registrations: registrations,
98
+ storage: store, host: host, bindingFactsJson: BindingFacts.json(),
99
+ intervalsJson: fixtureSettings, recoveryJson: recoveryJson) },
100
+ discard: { try? $0.shutdown() }))
101
+ }
102
+
103
+ private static let fixtureSettings = #"{"cloudOrigin":"\#(FixtureCloud.origin)"}"#
104
+ }
105
+ #endif
@@ -0,0 +1,209 @@
1
+ import Foundation
2
+
3
+ /// What the model asked for. Bound arguments are already merged in by Core.
4
+ public struct ToolCall: Sendable {
5
+ public let key: String
6
+ public let args: [String: JSON]
7
+ }
8
+
9
+ /// Who the call works for. Cancellation is the Task's: it fires on cancel, agent close and teardown.
10
+ public struct ToolContext: Sendable {
11
+ public let callId: String
12
+ public let agentId: String
13
+ /// nil = the default instance.
14
+ public let instance: String?
15
+ public let user: String?
16
+ /// The input ids this call works for (avoid buying twice).
17
+ public let causedBy: [String]
18
+ }
19
+
20
+ public enum ToolContent: Sendable, Equatable {
21
+ case text(String)
22
+ /// Base64 bytes.
23
+ case image(mediaType: String, data: String)
24
+ /// A `file://` URL, read by the native PAL.
25
+ case imageFile(mediaType: String, uri: String)
26
+ }
27
+
28
+ /// A tool's tagged result. Returning nil is the empty result.
29
+ public enum ToolResult: Sendable, Equatable {
30
+ case content([ToolContent])
31
+ case json(JSON)
32
+ }
33
+
34
+ /// Its message reaches the model verbatim. Core chooses every code.
35
+ public struct ToolError: Error, Sendable {
36
+ public let message: String
37
+ public init(_ message: String) { self.message = message }
38
+ }
39
+
40
+ public typealias ToolExecute = @Sendable (ToolCall, ToolContext) async throws -> ToolResult?
41
+
42
+ /// A manifest (JSON, the same on every SDK) plus its execute. Core validates the manifest
43
+ /// here: an invalid one throws `invalid_tool` with Core's path.
44
+ public final class ToolDefinition: Sendable {
45
+ let core: CoreToolDefinition
46
+ public var name: String { core.name() }
47
+ init(core: CoreToolDefinition) { self.core = core }
48
+ init(manifest: JSON, execute: @escaping ToolExecute) throws {
49
+ let text = text(manifest)
50
+ do { core = try CoreToolDefinition(manifestJson: text, execute: ToolExecuteAdapter(execute)) }
51
+ catch { throw CrocheError(error) }
52
+ }
53
+ }
54
+
55
+ public func defineTool(_ manifest: JSON, _ execute: @escaping ToolExecute) throws -> ToolDefinition {
56
+ try ToolDefinition(manifest: manifest, execute: execute)
57
+ }
58
+
59
+ /// The same, for a handler that returns a plain Swift value (Leo 17:23Z): String, a number,
60
+ /// Bool, nil, a Dictionary or Array of those, or any `Encodable`. It is serialized to JSON
61
+ /// mechanically (no policy); a `ToolResult` passes through and nil is "nothing to report", as
62
+ /// for `ToolExecute`. A value that has no JSON form (a non-finite number, a non-string key, a
63
+ /// class instance) reaches Core as `invalid_result`; Core chooses the code.
64
+ public func defineTool(_ manifest: JSON, _ execute: @escaping @Sendable (ToolCall, ToolContext) async throws -> (any Sendable)?) throws -> ToolDefinition {
65
+ try ToolDefinition(manifest: manifest, execute: PlainToolValue.execute(execute))
66
+ }
67
+
68
+ /// Mechanical Swift value -> JSON for tool returns. Serialization only.
69
+ enum PlainToolValue {
70
+ /// The value had no JSON form: the adapter reports `invalid_result`.
71
+ struct Unconvertible: Error, CustomStringConvertible {
72
+ let reason: String
73
+ var description: String { "The tool's return value has no JSON form: \(reason)" }
74
+ }
75
+
76
+ /// The plain handler as a `ToolExecute`: a `ToolResult` passes through, nil is nothing to report.
77
+ static func execute(_ plain: @escaping @Sendable (ToolCall, ToolContext) async throws -> (any Sendable)?) -> ToolExecute {
78
+ { call, context in
79
+ guard let value = try await plain(call, context) else { return nil }
80
+ if let result = value as? ToolResult { return result }
81
+ let json = try json(value)
82
+ return json == .null ? nil : .json(json)
83
+ }
84
+ }
85
+
86
+ static func json(_ value: Any) throws -> JSON {
87
+ let mirror = Mirror(reflecting: value)
88
+ if mirror.displayStyle == .optional { return try mirror.children.first.map { try json($0.value) } ?? .null }
89
+ if value is NSNull { return .null }
90
+ switch value {
91
+ case let value as JSON: return value
92
+ case let value as String: return .string(value)
93
+ case let value as Bool: return .bool(value)
94
+ case let value as Int: return try number(Double(exactly: value), "\(value)")
95
+ case let value as Int8: return .number(Double(value))
96
+ case let value as Int16: return .number(Double(value))
97
+ case let value as Int32: return .number(Double(value))
98
+ case let value as Int64: return try number(Double(exactly: value), "\(value)")
99
+ case let value as UInt: return try number(Double(exactly: value), "\(value)")
100
+ case let value as UInt8: return .number(Double(value))
101
+ case let value as UInt16: return .number(Double(value))
102
+ case let value as UInt32: return .number(Double(value))
103
+ case let value as UInt64: return try number(Double(exactly: value), "\(value)")
104
+ // A non-finite number has no JSON text: the adapter's encoding fallback sends invalid_result.
105
+ case let value as Double: return .number(value)
106
+ case let value as Float: return .number(Double(value))
107
+ case let value as [String: Any]: return .object(try value.mapValues { try json($0) })
108
+ case let value as [Any]: return .array(try value.map { try json($0) })
109
+ case let value as any Encodable:
110
+ do { return try JSON(data: JSONEncoder().encode(value)) }
111
+ catch { throw Unconvertible(reason: "\(type(of: value)) did not encode: \(error)") }
112
+ default: throw Unconvertible(reason: "\(type(of: value)) is not String, a number, Bool, nil, a Dictionary or Array of those, or Encodable")
113
+ }
114
+ }
115
+
116
+ private static func number(_ value: Double?, _ text: String) throws -> JSON {
117
+ guard let value else { throw Unconvertible(reason: "\(text) is not a number JSON can carry exactly") }
118
+ return .number(value)
119
+ }
120
+ }
121
+
122
+ /// `Croche.open` registration: a tool, or a tool with a bind for every agent. No commands or guide here.
123
+ public enum ToolRegistration: Sendable {
124
+ case tool(ToolDefinition)
125
+ /// `[:]` is an explicit empty bind and reaches Core as `{}`, distinct from `.tool`.
126
+ case bound(ToolDefinition, bind: [String: JSON])
127
+
128
+ /// The entry as the app wrote it, with only the opaque tool replaced by null (Atlas's S1
129
+ /// ABI): a bare tool = null; a wrapper keeps every key. Core validates, never this layer.
130
+ var json: JSON {
131
+ switch self {
132
+ case .tool: .null
133
+ case .bound(_, let bind): .object(["tool": .null, "bind": .object(bind)])
134
+ }
135
+ }
136
+
137
+ func core() throws -> CoreToolRegistration {
138
+ switch self {
139
+ case .tool(let tool): CoreToolRegistration(tool: tool.core, optionsJson: nil)
140
+ case .bound(let tool, _): CoreToolRegistration(tool: tool.core, optionsJson: text(json))
141
+ }
142
+ }
143
+ }
144
+
145
+ /// Core-owned tools. Registered name `webSearch`.
146
+ public enum CrocheTools {
147
+ public static var webSearch: ToolDefinition { ToolDefinition(core: coreWebSearch()) }
148
+ }
149
+
150
+ /// Core's execute callback, on a Core worker thread. Reports one tagged fact; Core applies policy
151
+ /// (tool_failed, cancelled, timeouts): empty | json | result | tool_error | handler_error | cancelled |
152
+ /// unavailable | invalid_result, discriminated by `type` (Atlas's pin, 10-30).
153
+ final class ToolExecuteAdapter: CoreToolExecute, @unchecked Sendable {
154
+ private let execute: ToolExecute
155
+ init(_ execute: @escaping ToolExecute) { self.execute = execute }
156
+
157
+ func execute(callJson: String, contextJson: String, cancel: CancelToken) throws -> String {
158
+ let call = try JSON(callJson), context = try JSON(contextJson)
159
+ let toolCall = ToolCall(key: call["key"].string ?? "", args: call["args"].object ?? [:])
160
+ let toolContext = ToolContext(callId: context["callId"].string ?? "", agentId: context["agentId"].string ?? "", instance: context["instance"].string,
161
+ user: context["user"].string, causedBy: context["causedBy"].array?.compactMap(\.string) ?? [])
162
+ let execute = self.execute
163
+ let box = ResultBox<ToolResult?>()
164
+ let done = DispatchSemaphore(value: 0)
165
+ let task = appTask {
166
+ do { box.set(.success(try await execute(toolCall, toolContext))) } catch { box.set(.failure(error)) }
167
+ done.signal()
168
+ }
169
+ cancel.onCancel(callback: TaskCancel(task))
170
+ done.wait()
171
+ // A result JSON cannot carry (a non-finite number) is a transport fact; Core picks the code.
172
+ return (strictText(Self.completion(box, cancelled: cancel.isCancelled()))) ?? #"{"type":"invalid_result"}"#
173
+ }
174
+
175
+ static func completion(_ box: ResultBox<ToolResult?>, cancelled: Bool) -> JSON {
176
+ do {
177
+ switch try box.get() {
178
+ case nil: return .object(["type": .string("empty")])
179
+ case .json(let value)?: return .object(["type": .string("json"), "value": value])
180
+ case .content(let content)?: return .object(["type": .string("result"), "content": .array(content.map(\.json))])
181
+ }
182
+ } catch is PlainToolValue.Unconvertible {
183
+ return .object(["type": .string("invalid_result")])
184
+ } catch let error as ToolError {
185
+ return .object(["type": .string("tool_error"), "message": .string(error.message)])
186
+ } catch {
187
+ if error is CancellationError || cancelled { return .object(["type": .string("cancelled")]) }
188
+ // The throw passes unchanged; Core applies tool_failed and maps no code here.
189
+ return .object(["type": .string("handler_error"),
190
+ "error": .object(["type": .string(String(reflecting: type(of: error))), "message": .string("\(error)")])])
191
+ }
192
+ }
193
+ }
194
+
195
+ private final class TaskCancel: CancelCallback, @unchecked Sendable {
196
+ private let task: Task<Void, Never>
197
+ init(_ task: Task<Void, Never>) { self.task = task }
198
+ func cancelled() { task.cancel() }
199
+ }
200
+
201
+ extension ToolContent {
202
+ var json: JSON {
203
+ switch self {
204
+ case .text(let text): .object(["type": .string("text"), "text": .string(text)])
205
+ case .image(let mediaType, let data): .object(["type": .string("image"), "mediaType": .string(mediaType), "data": .string(data)])
206
+ case .imageFile(let mediaType, let uri): .object(["type": .string("image"), "mediaType": .string(mediaType), "uri": .string(uri)])
207
+ }
208
+ }
209
+ }