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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -0,0 +1,146 @@
1
+ import Foundation
2
+
3
+ /// Native spelling of the same question union as the TS App API. Core validates every value.
4
+ public enum DecisionQuestion: Sendable {
5
+ /// One option of a `choice` question.
6
+ public struct Choice: Sendable {
7
+ /// The option id: 1-64 characters of `A-Z a-z 0-9 _ . : -`, distinct within the question.
8
+ public let id: String
9
+ /// What the option means, 1-4000 characters.
10
+ public let description: String?
11
+ /// Creates an option.
12
+ public init(id: String, description: String? = nil) { self.id = id; self.description = description }
13
+ }
14
+ /// A yes/no question. The optional descriptions explain what `true` and `false` mean.
15
+ case noul(id: String, instructions: String, trueDescription: String? = nil, falseDescription: String? = nil)
16
+ /// Pick one of 2-255 options, in order.
17
+ case choice(id: String, instructions: String, criteria: [Choice])
18
+ /// Rate on 2-10 levels, lowest first.
19
+ case score(id: String, instructions: String, criteria: [String])
20
+
21
+ var json: JSON {
22
+ let id: String, instructions: String, type: String
23
+ var criteria: JSON?
24
+ switch self {
25
+ case let .noul(key, text, yes, no):
26
+ id = key; instructions = text; type = "noul"
27
+ var values: [String: JSON] = [:]
28
+ if let yes { values["true"] = .string(yes) }; if let no { values["false"] = .string(no) }
29
+ if !values.isEmpty { criteria = .object(values) }
30
+ case let .choice(key, text, choices):
31
+ id = key; instructions = text; type = "choice"
32
+ criteria = .array(choices.map { choice in
33
+ var value: [String: JSON] = ["id": .string(choice.id)]
34
+ if let description = choice.description { value["description"] = .string(description) }
35
+ return .object(value)
36
+ })
37
+ case let .score(key, text, levels):
38
+ id = key; instructions = text; type = "score"; criteria = .array(levels.map(JSON.string))
39
+ }
40
+ var value: [String: JSON] = ["id": .string(id), "type": .string(type), "instructions": .string(instructions)]
41
+ if let criteria { value["criteria"] = criteria }
42
+ return .object(value)
43
+ }
44
+ }
45
+
46
+ /// A question in ``DecideInput``: the id of one configured on the decision agent, or a question given inline.
47
+ ///
48
+ /// Inline questions are checked against the model only at `decide`.
49
+ public enum DecisionQuestionRef: Sendable {
50
+ /// A question configured under the agent's `questions`.
51
+ case named(String)
52
+ /// A question supplied with this call.
53
+ case inline(DecisionQuestion)
54
+ var json: JSON { switch self { case .named(let id): return .string(id); case .inline(let question): return question.json } }
55
+ }
56
+ /// The input to ``CrocheAgent/decide(_:)``.
57
+ public struct DecideInput: Sendable {
58
+ /// A correlation id for ``CrocheAgent/cancel(_:)``, not a replay key: reusing it after the decision settles buys a
59
+ /// new decision, and reusing it while one is in flight is refused with `idempotency_conflict`.
60
+ public let id: String?
61
+ /// The app data to evaluate.
62
+ public let state: JSON
63
+ /// The questions to answer. `nil` asks the agent's configured questions; an agent with none configured needs them here.
64
+ public let questions: [DecisionQuestionRef]?
65
+ /// Creates a decision input.
66
+ public init(id: String? = nil, state: JSON, questions: [DecisionQuestionRef]? = nil) {
67
+ self.id = id; self.state = state; self.questions = questions
68
+ }
69
+ var json: JSON {
70
+ var value: [String: JSON] = ["state": state]
71
+ if let id { value["id"] = .string(id) }
72
+ if let questions { value["questions"] = .array(questions.map(\.json)) }
73
+ return .object(value)
74
+ }
75
+ }
76
+ /// A confidence the provider reported for one answer.
77
+ ///
78
+ /// Core keeps it only when it matches its own calculation from the answer's probabilities, within 0.01.
79
+ public struct DecisionConfidence: Decodable, Sendable {
80
+ /// The confidence, from 0 to 1.
81
+ public let value: Double
82
+ /// Open provider method, passed through without inference.
83
+ public let method: String
84
+ }
85
+ /// The answer to one question in a ``DecisionResult``.
86
+ public enum DecisionAnswer: Decodable, Sendable {
87
+ /// A yes/no answer. `value` is `probability >= 0.5`; `probability` is the probability of `true`.
88
+ case noul(value: Bool, probability: Double?, confidence: DecisionConfidence?)
89
+ /// The chosen option id, with a probability per option id when the provider gave them.
90
+ case choice(value: String, probabilities: [String: Double]?, confidence: DecisionConfidence?)
91
+ /// The expected level, a zero-based index weighted by `probabilities` (one per level, lowest first).
92
+ case score(value: Double, probabilities: [Double]?, confidence: DecisionConfidence?)
93
+ /// The provider declined to answer, with its reason when it gave one.
94
+ case refusal(reason: String?)
95
+ /// An answer type this SDK does not know, with its original type and fields.
96
+ case unknown(originalType: String, fields: JSON)
97
+
98
+ /// Decodes an answer by its `type`. An unrecognized type becomes ``unknown(originalType:fields:)``.
99
+ public init(from decoder: Decoder) throws {
100
+ let value = try JSON(from: decoder)
101
+ func read<T: Decodable>(_ type: T.Type, _ key: String) throws -> T {
102
+ try JSONDecoder().decode(type, from: value[key].encoded())
103
+ }
104
+ func optional<T: Decodable>(_ type: T.Type, _ key: String) throws -> T? {
105
+ value[key] == .null ? nil : try read(type, key)
106
+ }
107
+ let type = try read(String.self, "type")
108
+ switch type {
109
+ case "noul": self = .noul(value: try read(Bool.self, "value"), probability: try optional(Double.self, "probability"), confidence: try optional(DecisionConfidence.self, "confidence"))
110
+ case "choice": self = .choice(value: try read(String.self, "value"), probabilities: try optional([String: Double].self, "probabilities"), confidence: try optional(DecisionConfidence.self, "confidence"))
111
+ case "score": self = .score(value: try read(Double.self, "value"), probabilities: try optional([Double].self, "probabilities"), confidence: try optional(DecisionConfidence.self, "confidence"))
112
+ case "refusal": self = .refusal(reason: try optional(String.self, "reason"))
113
+ case "unknown": self = .unknown(originalType: try read(String.self, "originalType"), fields: value["fields"])
114
+ default: self = .unknown(originalType: type, fields: value)
115
+ }
116
+ }
117
+ }
118
+ /// The result of ``CrocheAgent/decide(_:)``.
119
+ public struct DecisionResult: Decodable, Sendable {
120
+ /// The decision's correlation id: the input's `id`, or the one Core assigned.
121
+ public let id: String
122
+ /// The model that answered.
123
+ public let model: String
124
+ /// One answer per question id.
125
+ public let answers: [String: DecisionAnswer]
126
+ /// Reported serving-provider label, when known. Diagnostic only.
127
+ public let provider: String?
128
+ /// The provider's token usage, as reported.
129
+ public let usage: JSON
130
+ /// Cost in credits, when reported.
131
+ public let cost: Double?
132
+ /// Open status; unknown costs stay nil, never the estimate.
133
+ public let costStatus: String
134
+ }
135
+ public extension CrocheAgent {
136
+ /// Classify app data for a workflow, such as routing a support ticket without starting a chat.
137
+ ///
138
+ /// Task cancellation fires the existing Core token; Core owns handoff and settlement.
139
+ func decide(_ input: DecideInput) async throws -> DecisionResult {
140
+ let core = try self.core, input = text(input.json)
141
+ let result = try await cancellable {
142
+ try core.decide(inputJson: input, optionsJson: nil, cancel: $0)
143
+ }
144
+ return try decode(DecisionResult.self, result)
145
+ }
146
+ }
@@ -1,10 +1,15 @@
1
1
  import Foundation
2
2
 
3
- /// The reader types are GENERATED from Core's Rust contract (GeneratedAppStream.swift), as in TS
4
- /// (APP-API: AgentEvent, MessageEnd and InputDisposition). A type this SDK does not know arrives
5
- /// as `.unknown(type:fields:)` with every field kept.
3
+ // The reader types are GENERATED from Core's Rust contract (GeneratedAppStream.swift), as in TS
4
+ // (APP-API: AgentEvent, MessageEnd and InputDisposition).
5
+ /// One subscription event. A type this SDK does not know arrives as `.unknown(type:fields:)` with
6
+ /// every field kept.
6
7
  public typealias AgentEvent = AppStreamContract.AgentEvent
8
+ /// The end of one agent reply, with its final text and status.
7
9
  public typealias MessageEnd = AppStreamContract.MessageEnd
10
+ /// A file kept with a conversation: an image the user sent, or one a tool produced.
11
+ public typealias Attachment = AppStreamContract.Attachment
12
+ /// What happened to one input: its status and, when it failed, the error.
8
13
  public typealias InputDisposition = AppStreamContract.InputDisposition
9
14
  /// `send`'s answer: Core has ACCEPTED the input. `error` is set when the input already failed.
10
15
  public typealias SendReceipt = AppStreamContract.SendReceipt
@@ -13,16 +18,20 @@ public typealias RequestResult = AppStreamContract.RequestResult
13
18
  /// `{code, category, message}` on a failed receipt, result, input or message.
14
19
  public typealias EventError = AppStreamContract.EventError
15
20
 
21
+ /// Options for ``CrocheAgent/subscribe(_:)``. Give `initialMessages` or `after`, not both.
16
22
  public struct SubscribeOptions: Sendable {
23
+ /// How many of the latest messages to deliver before the `snapshot`: 0-256, default 50.
17
24
  public var initialMessages: Int?
25
+ /// Resume after a cursor from an earlier subscription. Missed events arrive first, as events or as a `gap`.
26
+ /// A cursor from another log, or past its end, gets one `error` event with `cursor_reset` and the subscription ends.
18
27
  public var after: Cursor?
19
- /// How Core batches `messageDelta`. Nil = omitted: Core applies its platform default. The SDK
20
- /// sets none and passes a value (0 included) to Core unchanged.
21
- public var deltaMs: Int?
28
+ /// Update the transcript and controls together as the agent makes progress.
29
+ ///
22
30
  /// A throw reaches Core as the delivery's `threw` fact; Core decides what follows.
23
31
  public var onEvent: @Sendable (AgentEvent) async throws -> Void
24
- public init(initialMessages: Int? = nil, after: Cursor? = nil, deltaMs: Int? = nil,
32
+ /// Creates subscribe options. Core validates them when you subscribe.
33
+ public init(initialMessages: Int? = nil, after: Cursor? = nil,
25
34
  onEvent: @escaping @Sendable (AgentEvent) async throws -> Void) {
26
- self.initialMessages = initialMessages; self.after = after; self.deltaMs = deltaMs; self.onEvent = onEvent
35
+ self.initialMessages = initialMessages; self.after = after; self.onEvent = onEvent
27
36
  }
28
37
  }
@@ -0,0 +1,58 @@
1
+ import Foundation
2
+
3
+ /// Export ownership only. A borrowed strong reference protects an already-entered FFI call.
4
+ /// Views retain this holder, never a generated pointer. ARC drops the export after shutdown.
5
+ protocol S1OwnedHandle: AnyObject, Sendable { func release() }
6
+ final class S1HandleOwner<T: AnyObject & Sendable>: S1OwnedHandle, @unchecked Sendable {
7
+ private let condition = NSCondition()
8
+ private var raw: T?
9
+ private var closing = false
10
+ private var children: [any S1OwnedHandle] = []
11
+ init(_ raw: T) { self.raw = raw }
12
+ func value() throws -> T {
13
+ condition.lock(); defer { condition.unlock() }
14
+ guard !closing, let raw else { throw Self.closed() }
15
+ return raw
16
+ }
17
+ var ended: Bool {
18
+ condition.lock(); defer { condition.unlock() }; return raw == nil || closing
19
+ }
20
+ func adopt(_ child: any S1OwnedHandle) throws {
21
+ condition.lock()
22
+ guard raw != nil, !closing else {
23
+ condition.unlock(); child.release(); throw Self.closed()
24
+ }
25
+ children.append(child); condition.unlock()
26
+ }
27
+ func shutdown(_ stop: (T) throws -> Void) throws {
28
+ condition.lock()
29
+ while closing { condition.wait() }
30
+ guard let value = raw else { condition.unlock(); return }
31
+ closing = true; condition.unlock()
32
+ do { try stop(value) }
33
+ catch {
34
+ condition.lock(); closing = false; condition.broadcast(); condition.unlock()
35
+ throw error // Failed shutdown keeps the owner available for retry.
36
+ }
37
+ condition.lock()
38
+ raw = nil
39
+ let nested = children; children = []
40
+ closing = false; condition.broadcast(); condition.unlock()
41
+ withExtendedLifetime(value) {}
42
+ // Parent shutdown already fenced its children. Never shut down another shared alias.
43
+ nested.forEach { $0.release() }
44
+ }
45
+ func release() {
46
+ condition.lock()
47
+ // A pending explicit shutdown owns its eventual release.
48
+ guard !closing else { condition.unlock(); return }
49
+ let previous = raw, nested = children
50
+ raw = nil; children = []; condition.unlock()
51
+ nested.forEach { $0.release() }
52
+ // Generated deinit can call native code: never run it under the holder lock.
53
+ withExtendedLifetime(previous) {}
54
+ }
55
+ private static func closed() -> CrocheError {
56
+ CrocheError(code: "closed", message: "This handle is closed.", category: .closed)
57
+ }
58
+ }
@@ -3,13 +3,19 @@ import Foundation
3
3
  /// One entry = one tool, by its registered name. `bind` REPLACES the registration bind as a
4
4
  /// whole; nil keeps it. Core validates every field.
5
5
  public struct ToolEntry: Sendable, ExpressibleByStringLiteral {
6
+ /// The registered tool name.
6
7
  public var tool: String
8
+ /// Bound argument values for this agent; replaces the registration's `bind` as a whole.
7
9
  public var bind: [String: JSON]?
10
+ /// Narrows the tool to these stable command keys from its manifest. `nil` allows all of them.
8
11
  public var commands: [String]?
12
+ /// App guidance for this tool on this agent, added after the manifest guide and the agent's `toolGuide`.
9
13
  public var guide: String?
14
+ /// Creates a tool entry.
10
15
  public init(tool: String, bind: [String: JSON]? = nil, commands: [String]? = nil, guide: String? = nil) {
11
16
  self.tool = tool; self.bind = bind; self.commands = commands; self.guide = guide
12
17
  }
18
+ /// The tool by name, with nothing narrowed or bound.
13
19
  public init(stringLiteral name: String) { self.init(tool: name) }
14
20
  var json: JSON {
15
21
  guard bind != nil || commands != nil || guide != nil else { return .string(tool) }
@@ -23,9 +29,13 @@ public struct ToolEntry: Sendable, ExpressibleByStringLiteral {
23
29
 
24
30
  /// One entry = one path or glob, e.g. `"faq/**"`.
25
31
  public struct WikiEntry: Sendable, ExpressibleByStringLiteral {
32
+ /// A registered document path or a glob over them.
26
33
  public var doc: String
34
+ /// App guidance on when the agent should use these documents.
27
35
  public var guide: String?
36
+ /// Creates a wiki entry.
28
37
  public init(doc: String, guide: String? = nil) { self.doc = doc; self.guide = guide }
38
+ /// The path or glob, without a guide.
29
39
  public init(stringLiteral doc: String) { self.init(doc: doc) }
30
40
  var json: JSON {
31
41
  guard let guide else { return .string(doc) }
@@ -35,17 +45,24 @@ public struct WikiEntry: Sendable, ExpressibleByStringLiteral {
35
45
 
36
46
  /// `.all` = every registered; `[]` = none. In `AgentOptions`, nil also means all.
37
47
  public enum Scope<Entry: Sendable>: Sendable, ExpressibleByArrayLiteral {
48
+ /// Every registered entry.
38
49
  case all
50
+ /// Exactly these entries; an empty list means none.
39
51
  case list([Entry])
52
+ /// A list scope from an array literal.
40
53
  public init(arrayLiteral entries: Entry...) { self = .list(entries) }
41
54
  }
55
+ /// The tools an agent may use.
42
56
  public typealias ToolScope = Scope<ToolEntry>
57
+ /// The wiki documents an agent may read.
43
58
  public typealias WikiScope = Scope<WikiEntry>
44
59
 
45
60
  /// `{path, description, markdown}` or `{path, description, file}`. iOS resolves `file` as a
46
61
  /// main-bundle resource or a `file://` URL, when Core reads it.
47
62
  public enum WikiDoc: Sendable, Equatable {
63
+ /// A document given inline as Markdown text.
48
64
  case markdown(path: String, description: String, markdown: String)
65
+ /// A document read from a file when Core needs it. A missing file fails the turn that reads it.
49
66
  case file(path: String, description: String, file: String)
50
67
  var json: JSON {
51
68
  switch self {
@@ -65,19 +82,25 @@ public enum WikiDoc: Sendable, Equatable {
65
82
  }
66
83
  }
67
84
 
85
+ /// A named instance of an agent: its own conversation and memory.
68
86
  public struct AgentInstance: Sendable {
87
+ /// The instance id, chosen by the app.
69
88
  public var id: String
70
89
  /// A patch over the agent config. NOT saved: pass it on every open.
71
90
  public var config: JSON?
91
+ /// Creates an instance reference.
72
92
  public init(id: String, config: JSON? = nil) { self.id = id; self.config = config }
73
93
  }
74
94
 
95
+ /// Options for ``Croche/agent(_:_:)``.
75
96
  public struct AgentOptions: Sendable {
76
97
  /// nil = the agent's default instance.
77
98
  public var instance: AgentInstance?
78
99
  /// nil or `.all` = all registered; `[]` = none.
79
100
  public var tools: ToolScope?
101
+ /// nil or `.all` = all registered documents; `[]` = none.
80
102
  public var wiki: WikiScope?
103
+ /// Creates agent options.
81
104
  public init(instance: AgentInstance? = nil, tools: ToolScope? = nil, wiki: WikiScope? = nil) {
82
105
  self.instance = instance; self.tools = tools; self.wiki = wiki
83
106
  }
@@ -94,25 +117,63 @@ public struct AgentOptions: Sendable {
94
117
  }
95
118
  }
96
119
 
120
+ /// Options for ``Croche/open(_:)``. The SDK passes every value to Core unchanged, and Core validates it.
97
121
  public struct OpenOptions: Sendable {
122
+ /// Identifies the Croche Cloud project.
98
123
  public var projectKey: String
124
+ /// The app's stable id for the signed-in user. `nil` opens without a user.
99
125
  public var user: String?
100
- /// nil = omitted: Core chooses (ARCHITECTURE §2: the device locale is a PAL fact, never an SDK default).
126
+ // ARCHITECTURE §2: the device locale is a PAL fact, never an SDK default.
127
+ /// The user's language. `nil` omits it, and Core chooses from the device locale.
101
128
  public var language: String?
129
+ /// The project config the app ships (schema 7), used until Croche Cloud delivers one.
102
130
  public var bundledConfig: JSON
103
- /// nil = omitted; `[]` is sent as `[]` (APP-API gives an empty list its own meaning).
131
+ // APP-API gives an empty list its own meaning.
132
+ /// The tools to register. `nil` omits the field and `[]` is sent as an empty list; this SDK passes either to
133
+ /// Core unchanged.
104
134
  public var tools: [ToolRegistration]?
105
135
  /// nil = omitted; `[]` is sent as `[]`.
106
136
  public var wiki: [WikiDoc]?
107
- /// ARCHITECTURE §2a; nil = the platform default.
108
- public var storage: (any StoragePal)?
137
+ // ARCHITECTURE §2a.
138
+ /// App-supplied adapters. A kind left out uses the platform default; `nil` uses the defaults for all kinds.
139
+ public var adapters: [any Adapter]?
140
+ /// A server key, for a trusted backend only. Never ship one in an app.
109
141
  public var serverKey: String?
110
- public var debugKey: String?
142
+ /// A development key, for development builds only.
143
+ public var developmentKey: String?
144
+ /// Per-instance History and notes budgets.
145
+ public var archive: ArchiveOptions?
146
+ // Every storage size has a default and an app setting (founder 2026-11-19).
147
+ /// The byte budget of each instance's live stream log, the screen record used for replay.
148
+ /// `nil` omits it, and Core uses its default of 4 MiB. Core validates the value (2 MiB to 1 GiB); this SDK
149
+ /// passes it through unchanged.
150
+ public var retentionBytes: Int?
151
+ /// Total budget for the user's named instances, and each instance's budget for finished turns not yet sealed into
152
+ /// History; a send past it fails with `store_full`. Default 32 MiB, at most 1 GiB. nil = omitted.
153
+ public var instanceMaxBytes: Int?
154
+ // Founder 2026-11-19, B27.
155
+ /// The app wiki's limits: the largest document in markdown bytes
156
+ /// (default 64 KiB; a larger one is refused, so split it) and the wiki's total (default
157
+ /// 8 MiB). nil = omitted; Core validates and applies the defaults.
158
+ public var wikiDocumentMaxBytes: Int?
159
+ /// The wiki's total size limit (default 8 MiB). See `wikiDocumentMaxBytes`.
160
+ public var wikiMaxBytes: Int?
161
+ // B27.
162
+ /// App-wide input and scheduling guards for every agent. Only app code sets them: a bundle cannot
163
+ /// set them. nil = omitted; Core validates and applies the defaults.
164
+ public var limits: LimitsOptions?
165
+ /// Creates open options. Each `nil` is omitted, so Core applies its default.
111
166
  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) {
167
+ tools: [ToolRegistration]? = nil, wiki: [WikiDoc]? = nil, adapters: [any Adapter]? = nil,
168
+ serverKey: String? = nil, developmentKey: String? = nil, archive: ArchiveOptions? = nil,
169
+ retentionBytes: Int? = nil, instanceMaxBytes: Int? = nil,
170
+ wikiDocumentMaxBytes: Int? = nil, wikiMaxBytes: Int? = nil, limits: LimitsOptions? = nil) {
114
171
  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
172
+ self.tools = tools; self.wiki = wiki; self.adapters = adapters; self.serverKey = serverKey; self.developmentKey = developmentKey; self.archive = archive
173
+ self.retentionBytes = retentionBytes
174
+ self.instanceMaxBytes = instanceMaxBytes
175
+ self.wikiDocumentMaxBytes = wikiDocumentMaxBytes; self.wikiMaxBytes = wikiMaxBytes
176
+ self.limits = limits
116
177
  }
117
178
  /// The WHOLE options as JSON (Atlas's S1 ABI): only the opaque tool and storage references
118
179
  /// become null; the tools themselves travel beside it as registrations, in this order.
@@ -122,25 +183,64 @@ public struct OpenOptions: Sendable {
122
183
  if let language { fields["language"] = .string(language) }
123
184
  if let tools { fields["tools"] = .array(tools.map(\.json)) }
124
185
  if let wiki { fields["wiki"] = .array(wiki.map(\.json)) }
125
- if storage != nil { fields["storage"] = .null }
186
+ if let adapters { fields["adapters"] = .array(adapters.map { .object(["kind": .string($0.kind)]) }) }
126
187
  if let serverKey { fields["serverKey"] = .string(serverKey) }
127
- if let debugKey { fields["debugKey"] = .string(debugKey) }
188
+ if let developmentKey { fields["developmentKey"] = .string(developmentKey) }
189
+ if let archive { fields["archive"] = archive.json }
190
+ if let retentionBytes { fields["retentionBytes"] = .number(Double(retentionBytes)) }
191
+ if let instanceMaxBytes { fields["instanceMaxBytes"] = .number(Double(instanceMaxBytes)) }
192
+ if let wikiDocumentMaxBytes { fields["wikiDocumentMaxBytes"] = .number(Double(wikiDocumentMaxBytes)) }
193
+ if let wikiMaxBytes { fields["wikiMaxBytes"] = .number(Double(wikiMaxBytes)) }
194
+ if let limits { fields["limits"] = limits.json }
128
195
  return .object(fields)
129
196
  }
130
197
  }
131
198
 
199
+ /// `OpenOptions.limits`: each nil field is omitted and Core applies its default.
200
+ public struct LimitsOptions: Sendable, Equatable {
201
+ /// Total user and app-event text of one send, 1_000...200_000 UTF-16 units (default 32_000).
202
+ public var userTextChars: Int?
203
+ /// Total app-state text of one send, 1_000...200_000 (default 32_000).
204
+ public var appStateChars: Int?
205
+ /// One tool result's value as compact JSON, 1_000...1_000_000 (default 200_000).
206
+ public var toolResultChars: Int?
207
+ /// Images per message or tool result, 1...16 (default 4). Image byte limits stay fixed.
208
+ public var turnImages: Int?
209
+ /// Schedule notes pending at once, 1...20 (default 20).
210
+ public var pendingSchedules: Int?
211
+ /// Creates limits; each `nil` keeps Core's default.
212
+ public init(userTextChars: Int? = nil, appStateChars: Int? = nil, toolResultChars: Int? = nil,
213
+ turnImages: Int? = nil, pendingSchedules: Int? = nil) {
214
+ self.userTextChars = userTextChars; self.appStateChars = appStateChars
215
+ self.toolResultChars = toolResultChars; self.turnImages = turnImages
216
+ self.pendingSchedules = pendingSchedules
217
+ }
218
+ var json: JSON {
219
+ var value: [String: JSON] = [:]
220
+ if let userTextChars { value["userTextChars"] = .number(Double(userTextChars)) }
221
+ if let appStateChars { value["appStateChars"] = .number(Double(appStateChars)) }
222
+ if let toolResultChars { value["toolResultChars"] = .number(Double(toolResultChars)) }
223
+ if let turnImages { value["turnImages"] = .number(Double(turnImages)) }
224
+ if let pendingSchedules { value["pendingSchedules"] = .number(Double(pendingSchedules)) }
225
+ return .object(value)
226
+ }
227
+ }
228
+
132
229
  /// `Croche.registerBackground`. `storage` = the one `open()` uses.
133
230
  public struct BackgroundOptions: Sendable {
231
+ /// Let the app react when scheduled work was delivered or could not run.
134
232
  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
233
+ /// The same adapters as `open`, so background work uses the same stores.
234
+ public var adapters: [any Adapter]?
235
+ /// Creates background options.
236
+ public init(sink: (@Sendable (BackgroundEvent) -> Void)? = nil, adapters: [any Adapter]? = nil) {
237
+ self.sink = sink; self.adapters = adapters
138
238
  }
139
- /// As `OpenOptions.json`: the opaque sink and storage become null.
239
+ /// The opaque sink and selected StateStore become null transport markers.
140
240
  var json: JSON {
141
241
  var fields: [String: JSON] = [:]
142
242
  if sink != nil { fields["sink"] = .null }
143
- if storage != nil { fields["storage"] = .null }
243
+ if adapters?.contains(where: { $0.kind == "state" }) == true { fields["storage"] = .null }
144
244
  return .object(fields)
145
245
  }
146
246
  }
@@ -148,8 +248,11 @@ public struct BackgroundOptions: Sendable {
148
248
  /// `croche.deleteData(_:)` on an opened Croche: `{agent}`, `{agent, instance}` or `{}`. Core rejects
149
249
  /// `{instance}` alone. A recovery handle accepts only `{}` or no scope.
150
250
  public struct DataScope: Sendable {
251
+ /// The agent whose data to delete: its default and named instances.
151
252
  public var agent: String?
253
+ /// One named instance of `agent`. Requires `agent`.
152
254
  public var instance: String?
255
+ /// Creates a deletion scope.
153
256
  public init(agent: String? = nil, instance: String? = nil) { self.agent = agent; self.instance = instance }
154
257
  var json: JSON {
155
258
  var fields: [String: JSON] = [:]
@@ -171,7 +274,73 @@ extension Scope {
171
274
  /// The second argument of `Croche.open(_:recovery:)`. Swift serializes `{"recover": recover}`;
172
275
  /// Core alone validates it (`"delete"` today; anything else is `invalid_request`).
173
276
  public struct RecoveryOptions: Sendable, Equatable {
277
+ /// The recovery mode: `"delete"`.
174
278
  public let recover: String
279
+ /// Creates recovery options.
175
280
  public init(recover: String) { self.recover = recover }
176
281
  var json: JSON { .object(["recover": .string(recover)]) }
177
282
  }
283
+
284
+
285
+ /// The options of every paged public list: `listAttachments`, `memory.list` and `wiki.list`.
286
+ /// `limit` is a positive integer; a page holds at most 128 items, which is also the
287
+ /// default. `cursor` is the cursor of the previous page of the same list.
288
+ public struct ListOptions: Sendable, Equatable {
289
+ /// Items per page, at most 128 (also the default).
290
+ public var limit: Int?
291
+ /// The previous page's ``Page/cursor``; `nil` starts from the beginning.
292
+ public var cursor: String?
293
+ /// Creates list options.
294
+ public init(limit: Int? = nil, cursor: String? = nil) {
295
+ self.limit = limit
296
+ self.cursor = cursor
297
+ }
298
+ /// The `{limit?, cursor?}` text Core reads. The limit is written as an integer.
299
+ var optionsJson: String {
300
+ var fields: [String] = []
301
+ if let limit { fields.append("\"limit\":\(limit)") }
302
+ if let cursor { fields.append("\"cursor\":" + text(.string(cursor))) }
303
+ return "{" + fields.joined(separator: ",") + "}"
304
+ }
305
+ }
306
+
307
+ /// One page of a public list, in the list's stable order. `cursor` is present only when more
308
+ /// items follow: pass it back to the same list to continue strictly past this page.
309
+ public struct Page<Item: Sendable>: Sendable {
310
+ /// This page's items.
311
+ public var items: [Item]
312
+ /// Pass back as ``ListOptions/cursor`` for the next page; `nil` when no items follow.
313
+ public var cursor: String?
314
+ /// Creates a page.
315
+ public init(items: [Item], cursor: String? = nil) {
316
+ self.items = items
317
+ self.cursor = cursor
318
+ }
319
+ }
320
+
321
+ /// Reads Core's `{items, cursor?}` reply, turning each item with `item`.
322
+ func page<Item: Sendable>(_ replyText: String, _ what: String, _ item: (JSON) throws -> Item) throws -> Page<Item> {
323
+ let value = try reply(replyText)
324
+ guard let items = value["items"].array else { throw malformed(what) }
325
+ return Page(items: try items.map(item), cursor: value["cursor"].string)
326
+ }
327
+
328
+
329
+ /// App-wide host policy; the byte budget applies separately to every instance.
330
+ public struct ArchiveOptions: Sendable {
331
+ /// History budget per instance in bytes: 64 KiB to 1 GiB, default 8 MiB. Older records can be evicted to stay within it.
332
+ public var maxBytes: Double?
333
+ /// Budget for retired summary pieces and saved memory facts per instance: 64 KiB to 1 GiB, default 4 MiB.
334
+ public var notesMaxBytes: Double?
335
+ /// Creates archive options; each `nil` keeps the default.
336
+ public init(maxBytes: Double? = nil, notesMaxBytes: Double? = nil) {
337
+ self.maxBytes = maxBytes
338
+ self.notesMaxBytes = notesMaxBytes
339
+ }
340
+ var json: JSON {
341
+ var fields: [String: JSON] = [:]
342
+ if let maxBytes { fields["maxBytes"] = .number(maxBytes) }
343
+ if let notesMaxBytes { fields["notesMaxBytes"] = .number(notesMaxBytes) }
344
+ return .object(fields)
345
+ }
346
+ }
@@ -2,26 +2,52 @@ import Foundation
2
2
 
3
3
  /// Core's one result envelope. A plugin's output remains arbitrary JSON.
4
4
  public enum RunToolResult: Sendable {
5
+ /// The tool ran and returned a value.
5
6
  public struct Ok: Sendable {
7
+ /// The call id passed to `runTool`.
6
8
  public let id: String
9
+ /// The tool's output, as the tool returned it.
7
10
  public let output: JSON
11
+ /// Files the tool produced.
8
12
  public let attachments: [AppStreamContract.Attachment]
13
+ /// Cost in credits; `nil` unless reported.
9
14
  public let cost: Double?
15
+ /// `reported`, `unknown`, `none`, or a status this SDK does not know yet.
10
16
  public let costStatus: String
11
17
  }
18
+ /// The tool ran and failed.
12
19
  public struct Failed: Sendable {
13
- public let id: String, code: String, message: String
20
+ /// The call id passed to `runTool`.
21
+ public let id: String
22
+ /// Core's error code.
23
+ public let code: String
24
+ /// Core's description of the failure.
25
+ public let message: String
26
+ /// The error's category.
14
27
  public let category: ErrorCategory
28
+ /// Cost in credits; `nil` unless reported.
15
29
  public let cost: Double?
30
+ /// `reported`, `unknown`, `none`, or a status this SDK does not know yet.
16
31
  public let costStatus: String
17
32
  }
33
+ /// The process stopped while this call was running, so its outcome is unknown. Core does not run the same id again.
18
34
  public struct Lost: Sendable {
19
- public let id: String, code: String, message: String
35
+ /// The call id passed to `runTool`.
36
+ public let id: String
37
+ /// `outcome_unknown`.
38
+ public let code: String
39
+ /// Core's description.
40
+ public let message: String
41
+ /// `.closed`.
20
42
  public let category: ErrorCategory
21
43
  }
44
+ /// See ``Ok``.
22
45
  case ok(Ok)
46
+ /// See ``Failed``.
23
47
  case failed(Failed)
48
+ /// See ``Lost``.
24
49
  case lost(Lost)
50
+ /// A status this SDK does not know, with every field kept.
25
51
  case unknown(status: String, fields: JSON)
26
52
 
27
53
  init(_ value: JSON) throws {
@@ -51,9 +77,11 @@ public enum RunToolResult: Sendable {
51
77
  }
52
78
 
53
79
  public extension Croche {
80
+ /// Let an app button run a tool outside chat, such as generating an image for a form.
81
+ ///
54
82
  /// Cancelling the Task detaches this caller; Core owns the dispatched effect.
55
83
  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)]))
84
+ let core = try self.core, arguments = text(.object(args)), options = text(.object(["id": .string(id)]))
57
85
  return try RunToolResult(reply(try await cancellable {
58
86
  try core.runTool(name: name, argsJson: arguments, optionsJson: options, cancel: $0)
59
87
  }))