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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -1,7 +1,10 @@
1
1
  import Foundation
2
2
 
3
+ /// One fact the agent remembers, as listed by ``CrocheAgent/Memory/list(_:)``.
3
4
  public struct MemoryItem: Sendable, Equatable {
5
+ /// Core's id for the item; pass it to ``CrocheAgent/Memory/delete(_:)``.
4
6
  public let id: String
7
+ /// The remembered text.
5
8
  public let text: String
6
9
  /// The whole item, including fields this SDK does not read.
7
10
  public let fields: JSON
@@ -9,129 +12,179 @@ public struct MemoryItem: Sendable, Equatable {
9
12
 
10
13
  /// One instance, self-contained.
11
14
  public final class CrocheAgent: Sendable {
12
- let core: CoreAgent
15
+ let handle: S1HandleOwner<CoreAgent>
16
+ var core: CoreAgent { get throws { try handle.value() } }
17
+ /// The agent id this handle was opened for.
13
18
  public let id: String
14
19
  /// nil = the default instance.
15
20
  public let instance: String?
16
- init(core: CoreAgent) { self.core = core; id = core.id(); instance = core.instance() }
17
-
21
+ init(core: CoreAgent) { self.handle = S1HandleOwner(core); id = core.id(); instance = core.instance() }
22
+
23
+ /// Load an attachment when someone opens it from this conversation.
24
+ public func attachment(_ id: String) async throws -> AttachmentData { let core = try self.core; return try decode(AttachmentData.self, await blocking { try core.attachment(id: id) }) }
25
+ /// Let a user remove a file they no longer want kept with this conversation.
26
+ public func deleteAttachment(_ id: String) async throws { let core = try self.core; try await blocking { try core.deleteAttachment(id: id) } }
27
+ /// Show the files a user can revisit from this conversation.
28
+ public func listAttachments(_ options: ListOptions? = nil) async throws -> Page<Attachment> {
29
+ let core = try self.core, options = options?.optionsJson
30
+ return try page(try await blocking { try core.listAttachments(optionsJson: options) }, "attachment list") { try decode(Attachment.self, text($0)) }
31
+ }
32
+ /// Bring a file from another conversation into this one before sharing it here.
33
+ public func copyAttachment(_ source: AttachmentSource) async throws -> Attachment { let core = try self.core, json = text(source.json); return try decode(Attachment.self, await blocking { try core.copyAttachment(sourceJson: json) }) }
34
+ /// Let the app drop its hold on a file when the user removes it from a draft.
35
+ public func releaseAttachment(_ id: String) async throws { let core = try self.core; try await blocking { try core.releaseAttachment(id: id) } }
36
+
37
+ /// Accept input from chat without making the UI wait for the reply.
38
+ ///
18
39
  /// Returns when Core has ACCEPTED the input. Cancelling the Task before acceptance = never
19
40
  /// queued; after it = `aborted` (the input continues).
20
41
  public func send(_ text: String, _ options: SendOptions = SendOptions()) async throws -> SendReceipt {
21
42
  try await send(SendInput(input: [.text(text)]), options)
22
43
  }
44
+ /// Accept input from chat without making the UI wait for the reply.
23
45
  public func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> SendReceipt {
24
- let core = self.core, (input, images, options) = try Self.wire(input, options.responseFormat, wait: nil)
46
+ let core = try self.core, (input, images, options) = try Self.wire(input, options.responseFormat, wait: nil)
25
47
  return try Self.receipt(try await cancellable { try core.send(inputJson: input, images: images, optionsJson: options, cancel: $0) })
26
48
  }
27
49
  /// Core's reply decodes straight into the generated contract type, `error` included.
28
50
  static func receipt(_ value: String) throws -> SendReceipt { try decode(SendReceipt.self, value) }
29
51
 
52
+ /// Wait for an outcome when an app workflow needs to decide what happens next.
53
+ ///
30
54
  /// Returns when the input is final; with `wait: .idle`, when the agent is idle too.
31
55
  public func request(_ text: String, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
32
56
  try await request(SendInput(input: [.text(text)]), options)
33
57
  }
58
+ /// Wait for an outcome when an app workflow needs to decide what happens next.
34
59
  public func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
35
- let core = self.core, (input, images, options) = try Self.wire(input, options.responseFormat, wait: options.wait)
60
+ let core = try self.core, (input, images, options) = try Self.wire(input, options.responseFormat, wait: options.wait)
36
61
  return try Self.requestResult(try await cancellable { try core.request(inputJson: input, images: images, optionsJson: options, cancel: $0) })
37
62
  }
38
63
  static func requestResult(_ value: String) throws -> RequestResult { try decode(RequestResult.self, value) }
39
64
 
40
65
  /// Byte images ride beside the JSON as owned bytes indexed into `input` (the element is
41
66
  /// `{type: image, alt?}`; Core joins the position); never base64. Core sniffs and validates them.
42
- static func wire(_ input: SendInput, _ responseFormat: JSON?, wait: RequestWait?) throws -> (String, [CoreImageInput], String?) {
43
- let images = input.imageCaptures().map { CoreImageInput(element: UInt32($0.element), bytes: $0.bytes) }
67
+ static func wire(_ input: SendInput, _ responseFormat: JSON?, wait: RequestWait?) throws -> (String, [CoreAttachmentInput], String?) {
68
+ let images = input.imageCaptures().map { CoreAttachmentInput(element: UInt32($0.element), bytes: $0.bytes) }
44
69
  var options: [String: JSON] = [:]
45
70
  if let responseFormat { options["responseFormat"] = responseFormat }
46
71
  if wait == .idle { options["wait"] = .string("idle") }
47
72
  return (text(try input.wireJSON()), images, options.isEmpty ? nil : text(.object(options)))
48
73
  }
49
74
 
75
+ /// Keep a chat screen in step with the agent as messages and tool activity arrive.
76
+ ///
50
77
  /// `onEvent` runs serially on the main thread; a delivery counts as handled once it returns.
51
78
  /// Core's refusal is thrown unchanged, as in every SDK.
52
79
  public func subscribe(_ options: SubscribeOptions) throws -> Subscription {
53
80
  var selection: [String: JSON] = [:]
54
81
  if let initialMessages = options.initialMessages { selection["initialMessages"] = .number(Double(initialMessages)) }
55
82
  if let after = options.after { selection["after"] = .object(["logId": .string(after.logId), "seq": .number(Double(after.seq))]) }
56
- if let deltaMs = options.deltaMs { selection["deltaMs"] = .number(Double(deltaMs)) }
57
83
  let selectionJson = text(.object(selection))
58
- do { return Subscription(core: try core.subscribe(selectionJson: selectionJson, eventSink: EventSinkAdapter(options.onEvent))) }
84
+ do {
85
+ let subscription = Subscription(core: try core.subscribe(selectionJson: selectionJson, eventSink: EventSinkAdapter(options.onEvent)))
86
+ try handle.adopt(subscription.handle)
87
+ return subscription
88
+ }
59
89
  catch { throw CrocheError(error) }
60
90
  }
61
91
 
92
+ /// Let the user stop a reply or withdraw input they no longer want processed.
93
+ ///
62
94
  /// The one cross-handle cancel; returns once Core has durably recorded it.
63
95
  public func cancel(_ id: String? = nil) async throws {
64
- let core = self.core
96
+ let core = try self.core
65
97
  try await blocking { try core.cancel(inputId: id) }
66
98
  }
67
- /// The app empties its list on the `cleared` event.
99
+ /// Let a user clear the conversation they see while keeping the agent available.
100
+ ///
101
+ /// Clears the whole conversation. The app empties its list on the `cleared` event.
68
102
  public func clearHistory() async throws {
69
- let core = self.core
70
- try await blocking { try core.clearHistory() }
103
+ let core = try self.core
104
+ try await blocking { try core.clearHistory(optionsJson: nil) }
71
105
  }
72
- public var memory: Memory { Memory(core: core) }
106
+ /// The agent's memory for this instance: list, delete, clear and turn it on or off.
107
+ public var memory: Memory { Memory(handle: handle) }
73
108
 
109
+ /// Limit an agent to the actions appropriate for the user’s current workflow.
110
+ ///
74
111
  /// As if `agent()` had opened with this list, from the NEXT turn; may widen past it.
75
112
  public func setTools(_ scope: ToolScope) async throws {
76
- let core = self.core, scope = text(scope.json(\.json))
113
+ let core = try self.core, scope = text(scope.json(\.json))
77
114
  try await blocking { try core.setTools(scopeJson: scope) }
78
115
  }
116
+ /// Restore the usual actions after the user leaves a restricted workflow.
117
+ ///
79
118
  /// Back to `agent()`'s open scope.
80
119
  public func resetTools() async throws {
81
- let core = self.core
120
+ let core = try self.core
82
121
  try await blocking { try core.resetTools() }
83
122
  }
123
+ /// Give an agent help material relevant to the screen or workspace the user is in.
84
124
  public func setWiki(_ scope: WikiScope) async throws {
85
- let core = self.core, scope = text(scope.json(\.json))
125
+ let core = try self.core, scope = text(scope.json(\.json))
86
126
  try await blocking { try core.setWiki(scopeJson: scope) }
87
127
  }
128
+ /// Restore the usual help material after the user leaves a specialized workspace.
88
129
  public func resetWiki() async throws {
89
- let core = self.core
130
+ let core = try self.core
90
131
  try await blocking { try core.resetWiki() }
91
132
  }
133
+ /// Release an agent when the app leaves its conversation and no longer needs the handle.
92
134
  public func close() async throws {
93
- let core = self.core
94
- try await blocking { try core.shutdown() }
135
+ let handle = self.handle
136
+ try await blocking { try handle.shutdown { try $0.shutdown() } }
95
137
  }
96
138
 
139
+ /// Memory operations for one agent instance. It shares the agent's handle, so it stops working once the agent is closed.
97
140
  public struct Memory: Sendable {
98
- let core: CoreAgent
99
- public func list() async throws -> [MemoryItem] {
100
- let core = self.core
101
- guard let items = try reply(try await blocking { try core.memoryList() }).array else { throw malformed("memory list") }
102
- return try items.map { item in
141
+ let handle: S1HandleOwner<CoreAgent>
142
+ var core: CoreAgent { get throws { try handle.value() } }
143
+ /// Show the user what the agent remembers so they can review it.
144
+ public func list(_ options: ListOptions? = nil) async throws -> Page<MemoryItem> {
145
+ let core = try self.core, options = options?.optionsJson
146
+ return try page(try await blocking { try core.memoryList(optionsJson: options) }, "memory list") { item in
103
147
  guard let id = item["id"].string, let text = item["text"].string else { throw malformed("memory item") }
104
148
  return MemoryItem(id: id, text: text, fields: item)
105
149
  }
106
150
  }
151
+ /// Let the user remove one remembered fact without clearing the rest.
107
152
  public func delete(_ id: String) async throws {
108
- let core = self.core
153
+ let core = try self.core
109
154
  try await blocking { try core.memoryDelete(id: id) }
110
155
  }
156
+ /// Let the user start over with a clean memory while keeping their conversation.
111
157
  public func clear() async throws {
112
- let core = self.core
158
+ let core = try self.core
113
159
  try await blocking { try core.memoryClear() }
114
160
  }
161
+ /// Let the user choose whether the agent uses memory in this conversation.
115
162
  public func enabled(_ on: Bool) async throws {
116
- let core = self.core
163
+ let core = try self.core
117
164
  try await blocking { try core.memoryEnabled(on: on) }
118
165
  }
119
166
  }
120
167
 
121
168
  /// Nested: a top-level `Subscription` collides with Combine's.
122
169
  public final class Subscription: Sendable {
123
- let core: CoreSubscription
124
- init(core: CoreSubscription) { self.core = core }
170
+ let handle: S1HandleOwner<CoreSubscription>
171
+ var core: CoreSubscription { get throws { try handle.value() } }
172
+ init(core: CoreSubscription) { self.handle = S1HandleOwner(core) }
173
+ /// Load older messages into the same chat view when the user scrolls back.
174
+ ///
125
175
  /// Older pages, as `page` events on the same `onEvent`.
126
176
  public func history(before: Int? = nil, limit: Int) async throws {
127
- let core = self.core
177
+ let core = try self.core
128
178
  var options: [String: JSON] = ["limit": .number(Double(limit))]
129
179
  if let before { options["before"] = .number(Double(before)) }
130
180
  let text = text(.object(options))
131
181
  try await blocking { try core.history(optionsJson: text) }
132
182
  }
133
- public func close() { core.shutdown() }
134
- public var ended: Bool { core.ended() }
183
+ /// Stop routing updates to a chat view that has been dismissed.
184
+ public func close() { try? handle.shutdown { $0.shutdown() } }
185
+ /// `true` once the subscription delivers no more events: after ``close()``, after an `error` or `replaced`
186
+ /// event, or once its agent handle is released.
187
+ public var ended: Bool { (try? handle.value().ended()) ?? true }
135
188
  }
136
189
  }
137
190
 
@@ -0,0 +1,20 @@
1
+ import Foundation
2
+
3
+ extension Croche {
4
+ /// The per-user daily spending limit for this Croche's user.
5
+ public var allowance: Allowance { Allowance(handle: handle) }
6
+
7
+ /// This Croche's user's allowance. All validation and admission logic is Core's.
8
+ public struct Allowance: Sendable {
9
+ let handle: S1HandleOwner<CoreCroche>
10
+ var core: CoreCroche { get throws { try handle.value() } }
11
+ // Founder 2026-11-21; the same call as TS/RN `croche.allowance.set` and Kotlin `allowance.set`.
12
+ /// Set this user's allowance: the most credits the runtime lets this user spend per UTC day.
13
+ /// Absolute, it replaces the earlier value; `nil` returns the user to Studio's default. The runtime
14
+ /// counts and enforces it from its own storage; Croche Cloud keeps no per-user ledger.
15
+ public func set(_ limit: Double?) async throws {
16
+ let core = try self.core, input = text(limit.map(JSON.number) ?? .null)
17
+ try await blocking { try core.allowanceSet(limitJson: input) }
18
+ }
19
+ }
20
+ }
@@ -6,7 +6,7 @@ import Foundation
6
6
  enum BindingFacts {
7
7
  /// This package's version. scripts/release-version.mjs sets it with every other SDK version,
8
8
  /// and its --check refuses a value that differs from sdk/swift/VERSION.
9
- static let sdkVersion = "0.6.0"
9
+ static let sdkVersion = "0.7.0"
10
10
  static var platform: String {
11
11
  #if os(iOS)
12
12
  return "ios"
@@ -5,16 +5,24 @@ import Foundation
5
5
  // to S1 (Keel 21:58Z). Every value the app gives is passed to Core unchanged as JSON; this layer
6
6
  // decides nothing.
7
7
 
8
- /// The ONE closed set (APP-API), generated from Core's contract. Core attaches it to every code; the
9
- /// SDK never derives it.
8
+ // The ONE closed set (APP-API), generated from Core's contract; the SDK never derives it.
9
+ /// What the app does about an error. Core attaches a category to every code, and a code outside Core's table
10
+ /// has category `.internal`.
10
11
  public typealias ErrorCategory = AppStreamContract.ErrorCategory
11
12
 
13
+ /// The error every Croche call throws. Core assigns the code and category; the SDK passes them through unchanged.
14
+ ///
15
+ /// Errors raised inside the binding itself have code `internal` and category `.internal`.
12
16
  public struct CrocheError: Error, Sendable, CustomStringConvertible {
17
+ /// Core's error code, such as `invalid_input` or `rate_limited`.
13
18
  public let code: String
19
+ /// Core's human-readable description. Do not parse it: match on `code`.
14
20
  public let message: String
21
+ /// The closed category Core attached to the code. An unknown category from Core becomes `.internal`.
15
22
  public let category: ErrorCategory
16
23
  /// Where in the app's value Core found the fault (a manifest, scope or bind), when it says.
17
24
  public let path: String?
25
+ /// Integer seconds to wait before trying again. Present only on the hourly app-paid `rate_limited` refusal.
18
26
  public let retryAfter: UInt64?
19
27
  init(code: String, message: String, category: ErrorCategory, path: String? = nil, retryAfter: UInt64? = nil) {
20
28
  self.code = code; self.message = message; self.category = category; self.path = path; self.retryAfter = retryAfter
@@ -33,6 +41,7 @@ public struct CrocheError: Error, Sendable, CustomStringConvertible {
33
41
  else if let e = error as? CoreApiError { self.init(e) }
34
42
  else { self.init(code: "internal", message: "\(error)", category: .internal) }
35
43
  }
44
+ /// `code: message`.
36
45
  public var description: String { "\(code): \(message)" }
37
46
  }
38
47
 
@@ -50,7 +59,7 @@ func blocking<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async thr
50
59
 
51
60
  /// As `blocking`, with a Core token the awaiting Task's cancellation fires (APP-API: cancelling
52
61
  /// the Task is Swift's signal). A fresh token even when nothing cancels: Core requires one.
53
- /// Where the app's async code runs when Core calls it (a tool's execute, a custom StoragePal), where
62
+ /// Where the app's async code runs when Core calls it (a tool's execute, a custom StateStore), where
54
63
  /// the OS has task executors: GCD threads apart from Swift's cooperative pool, so app code that
55
64
  /// blocks its thread never starves the SDK's own work or another call (#342).
56
65
  @available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
@@ -1,8 +1,10 @@
1
1
  import Foundation
2
2
 
3
+ /// One background-delivery outcome, passed to the ``BackgroundOptions`` sink.
3
4
  public struct BackgroundEvent: Sendable, Equatable {
4
5
  /// `delivered`, `deadline`, `cancelled`, `skipped`, or a type this SDK does not know yet.
5
6
  public let type: String
7
+ /// When Core recorded the event, as an ISO 8601 UTC timestamp. `nil` if Core sent none.
6
8
  public let at: String?
7
9
  /// `skipped`: `storage_unavailable`, or `os_registration_failed` (the OS refused the background
8
10
  /// task: on iOS, BGTaskScheduler rejected `ai.croche.background` or it was registered after launch).
@@ -14,32 +16,56 @@ public struct BackgroundEvent: Sendable, Equatable {
14
16
  }
15
17
  }
16
18
 
19
+ /// When users of a project next have background work due, from ``Croche/wakeTimes(_:before:after:limit:)``.
17
20
  public struct WakeTimes: Sendable, Equatable {
18
- public struct Wake: Sendable, Equatable { public let user: String; public let at: Double }
21
+ /// One user's next due time.
22
+ public struct Wake: Sendable, Equatable {
23
+ /// nil for a Croche opened with no user (Core sends `user: null`).
24
+ public let user: String?
25
+ /// Epoch ms.
26
+ public let at: Double
27
+ }
28
+ /// Due users within the query's bounds.
19
29
  public let wakes: [Wake]
20
30
  /// Epoch ms.
21
31
  public let next: Double?
22
32
  }
23
33
 
34
+ /// The result of ``Croche/deliverDue()``.
24
35
  public struct DueDelivery: Sendable, Equatable {
36
+ /// An agent instance whose due work did not finish in this call; it stays due.
25
37
  public struct Deferred: Sendable, Equatable {
26
- public let user: String, agent: String, instance: String?
38
+ /// nil for a Croche opened with no user (Core sends `user: null`).
39
+ public let user: String?
40
+ /// The agent id.
41
+ public let agent: String
42
+ /// The instance, or `nil` for the default instance.
43
+ public let instance: String?
27
44
  /// `deadline` or `cancelled` today; open for codes Core adds.
28
45
  public let code: String, message: String
29
46
  }
47
+ /// Whether a due instance's delivery ran. `false`, with nothing delivered, when another delivery on this Croche
48
+ /// already owns the work or nothing was due.
30
49
  public let ran: Bool
50
+ /// How many pending usage reports this call delivered.
31
51
  public let delivered: Int
52
+ /// Work that was due but not finished, for example because the deadline passed.
32
53
  public let deferred: [Deferred]
33
54
  }
34
55
 
35
- /// `debugger.attach`'s options (APP-API `{url, token}`).
56
+ // APP-API `debugger.attach({url, token})`.
57
+ /// Connection details for ``Croche/Debugger/attach(_:)``.
36
58
  public struct DebugAttachOptions: Sendable, Equatable {
59
+ /// The debugger's control origin.
37
60
  public var url: String
61
+ /// The control origin's ingest credential. Keep it out of logs, URLs and committed files.
38
62
  public var token: String
63
+ /// Creates attach options from the control origin and its credential.
39
64
  public init(url: String, token: String) { self.url = url; self.token = token }
40
65
  var json: JSON { .object(["url": .string(url), "token": .string(token)]) }
41
66
  }
42
67
 
68
+ /// A successful ``Croche/Debugger/attach(_:)``.
43
69
  public struct AttachedDebugger: Sendable, Equatable {
44
70
  /// The same value as the CLI/broker wire's `attachmentId`, so app logs match CLI logs.
45
71
  public let debuggerId: String
@@ -49,13 +75,29 @@ public struct AttachedDebugger: Sendable, Equatable {
49
75
 
50
76
  /// The shared-resource factory for one user's session.
51
77
  public final class Croche: Sendable {
52
- let core: CoreCroche
53
- init(core: CoreCroche) { self.core = core }
78
+ let handle: S1HandleOwner<CoreCroche>
79
+ var core: CoreCroche { get throws { try handle.value() } }
80
+ init(core: CoreCroche) { self.handle = S1HandleOwner(core) }
81
+ /// Load a shared attachment when the user opens its preview.
82
+ public func attachment(_ id: String) async throws -> AttachmentData { let core = try self.core; return try decode(AttachmentData.self, await blocking { try core.attachment(id: id) }) }
83
+ /// Let the user remove a shared attachment they no longer want to keep.
84
+ public func deleteAttachment(_ id: String) async throws { let core = try self.core; try await blocking { try core.deleteAttachment(id: id) } }
85
+ /// Populate a picker of attachments shared by this user’s agents, newest first, one page at a time.
86
+ public func listAttachments(_ options: ListOptions? = nil) async throws -> Page<Attachment> {
87
+ let core = try self.core, options = options?.optionsJson
88
+ return try page(try await blocking { try core.listAttachments(optionsJson: options) }, "attachment list") { try decode(Attachment.self, text($0)) }
89
+ }
90
+
54
91
 
92
+ /// Open the app’s user session before letting that user talk to an agent or run a tool.
93
+ ///
55
94
  /// Opening twice for the same (projectKey, user) is the SAME Core Croche, ref-counted in Core.
56
95
  public static func open(_ options: OpenOptions) async throws -> Croche { try await opening(options, nil) }
57
96
 
58
- /// RECOVERY OPEN (R1), for when `open(options)` fails because the project record is corrupt or
97
+ // RECOVERY OPEN (R1).
98
+ /// Give a user a way to erase local data even when the app can no longer open their session.
99
+ ///
100
+ /// Use it when `open(options)` fails because the project record is corrupt or
59
101
  /// too new (`corrupt_store`, `store_too_new`) or a store refuses writes (`store_full`,
60
102
  /// `store_refused`). Only `deleteData()` with an empty scope and `close()` work on the handle;
61
103
  /// Core rejects every other member, and any recovery mode it does not know, with `invalid_request`.
@@ -64,17 +106,20 @@ public final class Croche: Sendable {
64
106
  }
65
107
 
66
108
  private static func opening(_ options: OpenOptions, _ recovery: RecoveryOptions?) async throws -> Croche {
109
+ let selected = try adaptersFor(options.adapters)
67
110
  let open = text(options.json), recoveryJson = recovery.map { text($0.json) }
68
111
  let registrations = try (options.tools ?? []).map { try $0.core() }
69
112
  #if CROCHE_TEST_HOOKS
70
- if let serve = FixtureCloud.serve { return try await fixtureOpen(open, registrations, options.storage, recoveryJson, serve) }
113
+ if let serve = FixtureCloud.serve { return try await fixtureOpen(open, registrations, selected, recoveryJson, serve) }
71
114
  #endif
72
- let host = try platformHost(), storage = storageArgument(options.storage, host)
115
+ let host = try platformHost(image: selected.image), storage = PlatformStorageAdapter(host, state: selected.state)
73
116
  return Croche(core: try await owner({ try CoreCroche.open(openJson: open, registrations: registrations, storage: storage, host: host,
74
117
  bindingFactsJson: BindingFacts.json(), recoveryJson: recoveryJson) },
75
118
  discard: { try? $0.shutdown() }))
76
119
  }
77
120
 
121
+ /// Honor a user’s request to erase one workspace or all their local Croche data.
122
+ ///
78
123
  /// Deletes this user's LOCAL data on the opened Croche. No scope (or an empty one): the declared
79
124
  /// stores, registered instances and tool runtime; `agent`: that agent's main and named instances;
80
125
  /// `agent` + `instance`: one instance. Core validates every scope. Other users, the install
@@ -82,115 +127,149 @@ public final class Croche: Sendable {
82
127
  /// in scope close, and a later `agent()` starts fresh stores. Core owns store locks and partial
83
128
  /// progress: retry a failure with the same scope.
84
129
  public func deleteData(_ scope: DataScope? = nil) async throws {
85
- let core = self.core, scope = scope.map { text($0.json) }
130
+ let core = try self.core, scope = scope.map { text($0.json) }
86
131
  try await blocking { try core.deleteData(scopeJson: scope) }
87
132
  }
88
133
 
134
+ /// Let the app keep up with due work when its UI is no longer in the foreground.
135
+ ///
89
136
  /// Call once at launch (iOS: before didFinishLaunching returns). OS identifier `ai.croche.background`.
90
137
  public static func registerBackground(_ options: BackgroundOptions = BackgroundOptions()) throws {
91
- let host = try platformHost(), json = text(options.json)
138
+ let selected = try adaptersFor(options.adapters)
139
+ let host = try platformHost(image: selected.image), json = text(options.json)
92
140
  do {
93
141
  // With the app's store, Core also gets the platform store (its background markers);
94
142
  // the default registration hands only the one store (Core: never a second wrapper).
95
143
  try coreRegisterBackground(optionsJson: json, sink: options.sink.map(BackgroundSink.init),
96
- storage: storageArgument(options.storage, host),
97
- platformStorage: options.storage.map { _ in PlatformStorageAdapter(host) }, host: host,
144
+ storage: PlatformStorageAdapter(host, state: selected.state),
145
+ platformStorage: selected.state.map { _ in PlatformStorageAdapter(host) }, host: host,
98
146
  bindingFactsJson: BindingFacts.json())
99
147
  } catch { throw CrocheError(error) }
100
148
  }
101
149
 
150
+ /// Let a server schedule just the users whose background work is due.
151
+ ///
102
152
  /// When `deliverDue` is next needed (servers, serverless cron). Opens no project.
103
153
  public static func wakeTimes(_ options: OpenOptions, before: Double? = nil, after: Double? = nil, limit: Int? = nil) async throws -> WakeTimes {
104
154
  var query: [String: JSON] = [:]
105
155
  if let before { query["before"] = .number(before) }
106
156
  if let after { query["after"] = .number(after) }
107
157
  if let limit { query["limit"] = .number(Double(limit)) }
158
+ let selected = try adaptersFor(options.adapters)
108
159
  let open = text(options.json), queryText = query.isEmpty ? nil : text(.object(query))
109
- let host = try platformHost(), storage = storageArgument(options.storage, host)
160
+ let host = try platformHost(image: selected.image), storage = PlatformStorageAdapter(host, state: selected.state)
110
161
  let value = try reply(try await blocking { try coreWakeTimes(openJson: open, queryJson: queryText, storage: storage, host: host) })
111
- let wakes = try (value["wakes"].array ?? []).map { wake -> WakeTimes.Wake in
112
- guard let user = wake["user"].string, let at = wake["at"].number else { throw malformed("wake") }
113
- return WakeTimes.Wake(user: user, at: at)
114
- }
115
- return WakeTimes(wakes: wakes, next: value["next"].number)
162
+ return try decodeWakeTimes(value)
116
163
  }
117
164
 
165
+ /// Let a host deliver scheduled work when its timer or alarm fires.
166
+ ///
118
167
  /// Delivery and config sync only. Cancel the Task to stop it.
119
168
  public func deliverDue() async throws -> DueDelivery {
120
- let core = self.core
121
- let value = try reply(try await cancellable { try core.deliverDue(optionsJson: nil, cancel: $0) })
122
- guard let ran = value["ran"].bool, let delivered = value["delivered"].number else { throw malformed("delivery") }
123
- let deferred = try (value["deferred"].array ?? []).map { item -> DueDelivery.Deferred in
124
- guard let user = item["user"].string, let agent = item["agent"].string,
125
- let code = item["code"].string, let message = item["message"].string else { throw malformed("deferral") }
126
- return DueDelivery.Deferred(user: user, agent: agent, instance: item["instance"].string, code: code, message: message)
127
- }
128
- return DueDelivery(ran: ran, delivered: Int(delivered), deferred: deferred)
169
+ let core = try self.core
170
+ return try decodeDueDelivery(try reply(try await cancellable { try core.deliverDue(optionsJson: nil, cancel: $0) }))
129
171
  }
130
172
 
173
+ /// Give each chat, case, or workspace its own conversation while reusing the app’s agent definition.
174
+ ///
131
175
  /// The same instance with the same or no config returns a handle to it; a different config
132
176
  /// is Core's `invalid_configuration`.
133
177
  public func agent(_ id: String, _ options: AgentOptions? = nil) async throws -> CrocheAgent {
134
- let core = self.core, scope = options.map { text($0.json) }
135
- return CrocheAgent(core: try await owner({ try core.agent(id: id, scopeJson: scope) }, discard: { try? $0.shutdown() }))
178
+ let core = try self.core, scope = options.map { text($0.json) }
179
+ let agent = CrocheAgent(core: try await owner({ try core.agent(id: id, scopeJson: scope) }, discard: { try? $0.shutdown() }))
180
+ try handle.adopt(agent.handle)
181
+ return agent
136
182
  }
137
183
 
138
- public var agentIds: [String] {
139
- get throws { do { return try core.agentIds() } catch { throw CrocheError(error) } }
140
- }
141
-
142
- public var wiki: Wiki { Wiki(core: core) }
143
- public var debugger: Debugger { Debugger(core: core) }
184
+ /// The project's documents for this Croche.
185
+ public var wiki: Wiki { Wiki(handle: handle) }
186
+ /// Attach the local Croche debugger to this Croche.
187
+ public var debugger: Debugger { Debugger(handle: handle) }
144
188
 
189
+ /// Release the user’s session when they sign out or the app switches accounts.
190
+ ///
145
191
  /// Returns once new work has stopped; the bounded final delivery continues.
146
192
  public func close() async throws {
147
- let core = self.core
148
- try await blocking { try core.shutdown() }
193
+ let handle = self.handle
194
+ try await blocking { try handle.shutdown { try $0.shutdown() } }
149
195
  }
150
196
 
151
197
  /// The project's original documents, in memory for this Croche; put/remove last until close().
152
198
  public struct Wiki: Sendable {
153
- let core: CoreCroche
199
+ let handle: S1HandleOwner<CoreCroche>
200
+ var core: CoreCroche { get throws { try handle.value() } }
201
+ /// Make an updated help article available to agents in the current app session.
154
202
  public func put(_ doc: WikiDoc) async throws {
155
- let core = self.core, doc = text(doc.json)
203
+ let core = try self.core, doc = text(doc.json)
156
204
  try await blocking { try core.wikiPut(docJson: doc) }
157
205
  }
206
+ /// Stop agents from using a help article the app has withdrawn.
158
207
  public func remove(_ path: String) async throws {
159
- let core = self.core
208
+ let core = try self.core
160
209
  try await blocking { try core.wikiRemove(path: path) }
161
210
  }
162
- public func list() async throws -> [WikiDoc] {
163
- let core = self.core
164
- let value = try reply(try await blocking { try core.wikiList() })
165
- guard let docs = value.array else { throw malformed("wiki list") }
166
- return try docs.map(WikiDoc.init)
211
+ /// Show which help articles the app has made available to its agents.
212
+ public func list(_ options: ListOptions? = nil) async throws -> Page<WikiDoc> {
213
+ let core = try self.core, options = options?.optionsJson
214
+ return try page(try await blocking { try core.wikiList(optionsJson: options) }, "wiki list", WikiDoc.init)
167
215
  }
168
216
  }
169
217
 
170
- /// The local debugger: loopback (iproxy), or LAN with the debug key.
218
+ /// The local debugger: loopback (iproxy), or LAN with the development key.
171
219
  public struct Debugger: Sendable {
172
- let core: CoreCroche
220
+ let handle: S1HandleOwner<CoreCroche>
221
+ var core: CoreCroche { get throws { try handle.value() } }
222
+ /// Inspect a running session when a development build behaves unexpectedly.
173
223
  public func attach(_ options: DebugAttachOptions) async throws -> AttachedDebugger {
174
- let core = self.core, options = text(options.json)
224
+ let core = try self.core, options = text(options.json)
175
225
  let value = try reply(try await blocking { try core.debugAttach(optionsJson: options) })
176
226
  guard let id = value["debuggerId"].string, let capabilities = value["capabilities"].array else { throw malformed("attached debugger") }
177
227
  return AttachedDebugger(debuggerId: id, capabilities: capabilities.compactMap(\.string))
178
228
  }
229
+ /// End diagnostic access after the developer is done or the user withdraws permission.
230
+ ///
179
231
  /// The last Croche alias close detaches the runtime.
180
232
  public func detach() async throws {
181
- let core = self.core
233
+ let core = try self.core
182
234
  try await blocking { try core.debugDetach() }
183
235
  }
184
236
  }
185
237
  }
186
238
 
187
- func malformed(_ what: String) -> CrocheError {
188
- CrocheError(code: "internal", message: "Core's \(what) is malformed.", category: .internal)
239
+ /// Core's `user` on a wake or deferral: a string, or null (absent) for a Croche with no user.
240
+ /// Any other type is malformed.
241
+ private func optionalUser(_ value: JSON, _ what: String) throws -> String? {
242
+ switch value["user"] {
243
+ case .null: return nil
244
+ case .string(let user): return user
245
+ default: throw malformed(what)
246
+ }
189
247
  }
190
248
 
191
- /// Core's storage argument: the app's store, else the platform default. Never nil.
192
- func storageArgument(_ storage: (any StoragePal)?, _ host: PlatformPal) -> CoreStoragePal {
193
- storage.map { CoreStorageAdapter($0) } ?? PlatformStorageAdapter(host)
249
+ /// `wakeTimes`' reply. Unknown fields are ignored.
250
+ func decodeWakeTimes(_ value: JSON) throws -> WakeTimes {
251
+ let wakes = try (value["wakes"].array ?? []).map { wake -> WakeTimes.Wake in
252
+ let user = try optionalUser(wake, "wake")
253
+ guard let at = wake["at"].number else { throw malformed("wake") }
254
+ return WakeTimes.Wake(user: user, at: at)
255
+ }
256
+ return WakeTimes(wakes: wakes, next: value["next"].number)
257
+ }
258
+
259
+ /// `deliverDue`'s reply. Unknown fields are ignored.
260
+ func decodeDueDelivery(_ value: JSON) throws -> DueDelivery {
261
+ guard let ran = value["ran"].bool, let delivered = value["delivered"].number else { throw malformed("delivery") }
262
+ let deferred = try (value["deferred"].array ?? []).map { item -> DueDelivery.Deferred in
263
+ let user = try optionalUser(item, "deferral")
264
+ guard let agent = item["agent"].string, let code = item["code"].string,
265
+ let message = item["message"].string else { throw malformed("deferral") }
266
+ return DueDelivery.Deferred(user: user, agent: agent, instance: item["instance"].string, code: code, message: message)
267
+ }
268
+ return DueDelivery(ran: ran, delivered: Int(delivered), deferred: deferred)
269
+ }
270
+
271
+ func malformed(_ what: String) -> CrocheError {
272
+ CrocheError(code: "internal", message: "Core's \(what) is malformed.", category: .internal)
194
273
  }
195
274
 
196
275
  /// Test-only: the OS launch handler table a host gate gives the platform PAL (macOS has none).
@@ -199,10 +278,10 @@ enum PlatformBackgroundTesting {
199
278
  }
200
279
 
201
280
  /// The platform PAL (#820 seam): its storage is the default when the app gives none.
202
- func platformHost() throws -> PlatformPal {
281
+ func platformHost(image: (any ImageAdapter)? = nil) throws -> PlatformPal {
203
282
  let directory = try NativeProjectFiles.directory(projectDirectory: nil)
204
283
  return PlatformPal(directory: directory, secrets: PlatformPal.testingSecrets(directory),
205
- backgroundLaunches: PlatformBackgroundTesting.launches ?? PlatformPal.osBackgroundLaunches())
284
+ backgroundLaunches: PlatformBackgroundTesting.launches ?? PlatformPal.osBackgroundLaunches(), imageAdapter: image)
206
285
  }
207
286
 
208
287
  /// Background events, at least once, at the next registration in a live runtime. The same