@h1r-ai/croche-react-native 0.5.5 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -458
- package/THIRD-PARTY-NOTICES +7 -8
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
- package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/dist/package.json +1 -0
- package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
- package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
- package/dist/react-native/src/core-native.d.ts +3 -0
- package/dist/react-native/src/core-native.js +193 -0
- package/dist/react-native/src/core-wire.d.ts +38 -0
- package/dist/react-native/src/core-wire.js +1 -0
- package/dist/react-native/src/native-module.d.ts +8 -0
- package/dist/react-native/src/native-module.js +53 -0
- package/dist/rn-shared-build.json +16 -0
- package/dist/runtime/src/agent.d.ts +43 -0
- package/dist/runtime/src/agent.js +75 -0
- package/dist/runtime/src/app-api.d.ts +284 -0
- package/dist/runtime/src/app-api.js +1 -0
- package/dist/runtime/src/cancel.d.ts +9 -0
- package/dist/runtime/src/cancel.js +24 -0
- package/dist/runtime/src/core/port.d.ts +234 -0
- package/dist/runtime/src/core/port.js +1 -0
- package/dist/runtime/src/core/wasm.d.ts +1 -0
- package/dist/runtime/src/core/wasm.js +2 -0
- package/dist/runtime/src/croche.d.ts +42 -0
- package/dist/runtime/src/croche.js +111 -0
- package/dist/runtime/src/errors.d.ts +26 -0
- package/dist/runtime/src/errors.js +49 -0
- package/dist/runtime/src/events.d.ts +5 -0
- package/dist/runtime/src/events.js +31 -0
- package/dist/runtime/src/generated/app-stream.d.ts +174 -0
- package/dist/runtime/src/generated/app-stream.js +124 -0
- package/dist/runtime/src/index.native.d.ts +21 -0
- package/dist/runtime/src/index.native.js +8 -0
- package/dist/runtime/src/json.d.ts +13 -0
- package/dist/runtime/src/json.js +120 -0
- package/dist/runtime/src/native-adapter.d.ts +3 -0
- package/dist/runtime/src/native-adapter.js +24 -0
- package/dist/runtime/src/pal/codec.d.ts +15 -0
- package/dist/runtime/src/pal/codec.js +52 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +35 -0
- package/dist/runtime/src/pal/platform.d.ts +16 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- package/dist/runtime/src/rn-entry.d.ts +1 -0
- package/dist/runtime/src/rn-entry.js +4 -0
- package/dist/runtime/src/run-tool.d.ts +33 -0
- package/dist/runtime/src/run-tool.js +7 -0
- package/dist/runtime/src/tools.d.ts +19 -0
- package/dist/runtime/src/tools.js +70 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +93 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +92 -0
- package/ios/CoreWireSupport.swift +111 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +46 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +18 -8
- package/scripts/README.md +11 -0
- package/scripts/build-shared.mjs +46 -0
- package/scripts/build.mjs +11 -0
- package/scripts/vendor-native.sh +5 -4
- package/src/NativeCrocheRuntime.ts +12 -159
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/src/index.ts +0 -664
- package/src/project-types.ts +0 -35
- package/src/project.ts +0 -434
- package/src/protocol.ts +0 -28
- package/src/types.ts +0 -9
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
public struct MemoryItem: Sendable, Equatable {
|
|
4
|
+
public let id: String
|
|
5
|
+
public let text: String
|
|
6
|
+
/// The whole item, including fields this SDK does not read.
|
|
7
|
+
public let fields: JSON
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/// One instance, self-contained.
|
|
11
|
+
public final class CrocheAgent: Sendable {
|
|
12
|
+
let core: CoreAgent
|
|
13
|
+
public let id: String
|
|
14
|
+
/// nil = the default instance.
|
|
15
|
+
public let instance: String?
|
|
16
|
+
init(core: CoreAgent) { self.core = core; id = core.id(); instance = core.instance() }
|
|
17
|
+
|
|
18
|
+
/// Returns when Core has ACCEPTED the input. Cancelling the Task before acceptance = never
|
|
19
|
+
/// queued; after it = `aborted` (the input continues).
|
|
20
|
+
public func send(_ text: String, _ options: SendOptions = SendOptions()) async throws -> SendReceipt {
|
|
21
|
+
try await send(SendInput(input: [.text(text)]), options)
|
|
22
|
+
}
|
|
23
|
+
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)
|
|
25
|
+
return try Self.receipt(try await cancellable { try core.send(inputJson: input, images: images, optionsJson: options, cancel: $0) })
|
|
26
|
+
}
|
|
27
|
+
/// Core's reply decodes straight into the generated contract type, `error` included.
|
|
28
|
+
static func receipt(_ value: String) throws -> SendReceipt { try decode(SendReceipt.self, value) }
|
|
29
|
+
|
|
30
|
+
/// Returns when the input is final; with `wait: .idle`, when the agent is idle too.
|
|
31
|
+
public func request(_ text: String, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
|
|
32
|
+
try await request(SendInput(input: [.text(text)]), options)
|
|
33
|
+
}
|
|
34
|
+
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)
|
|
36
|
+
return try Self.requestResult(try await cancellable { try core.request(inputJson: input, images: images, optionsJson: options, cancel: $0) })
|
|
37
|
+
}
|
|
38
|
+
static func requestResult(_ value: String) throws -> RequestResult { try decode(RequestResult.self, value) }
|
|
39
|
+
|
|
40
|
+
/// Byte images ride beside the JSON as owned bytes indexed into `input` (the element is
|
|
41
|
+
/// `{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) }
|
|
44
|
+
var options: [String: JSON] = [:]
|
|
45
|
+
if let responseFormat { options["responseFormat"] = responseFormat }
|
|
46
|
+
if wait == .idle { options["wait"] = .string("idle") }
|
|
47
|
+
return (text(try input.wireJSON()), images, options.isEmpty ? nil : text(.object(options)))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// `onEvent` runs serially on the main thread; a delivery counts as handled once it returns.
|
|
51
|
+
/// Core's refusal is thrown unchanged, as in every SDK.
|
|
52
|
+
public func subscribe(_ options: SubscribeOptions) throws -> Subscription {
|
|
53
|
+
var selection: [String: JSON] = [:]
|
|
54
|
+
if let initialMessages = options.initialMessages { selection["initialMessages"] = .number(Double(initialMessages)) }
|
|
55
|
+
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
|
+
let selectionJson = text(.object(selection))
|
|
58
|
+
do { return Subscription(core: try core.subscribe(selectionJson: selectionJson, eventSink: EventSinkAdapter(options.onEvent))) }
|
|
59
|
+
catch { throw CrocheError(error) }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// The one cross-handle cancel; returns once Core has durably recorded it.
|
|
63
|
+
public func cancel(_ id: String? = nil) async throws {
|
|
64
|
+
let core = self.core
|
|
65
|
+
try await blocking { try core.cancel(inputId: id) }
|
|
66
|
+
}
|
|
67
|
+
/// The app empties its list on the `cleared` event.
|
|
68
|
+
public func clearHistory() async throws {
|
|
69
|
+
let core = self.core
|
|
70
|
+
try await blocking { try core.clearHistory() }
|
|
71
|
+
}
|
|
72
|
+
public var memory: Memory { Memory(core: core) }
|
|
73
|
+
|
|
74
|
+
/// As if `agent()` had opened with this list, from the NEXT turn; may widen past it.
|
|
75
|
+
public func setTools(_ scope: ToolScope) async throws {
|
|
76
|
+
let core = self.core, scope = text(scope.json(\.json))
|
|
77
|
+
try await blocking { try core.setTools(scopeJson: scope) }
|
|
78
|
+
}
|
|
79
|
+
/// Back to `agent()`'s open scope.
|
|
80
|
+
public func resetTools() async throws {
|
|
81
|
+
let core = self.core
|
|
82
|
+
try await blocking { try core.resetTools() }
|
|
83
|
+
}
|
|
84
|
+
public func setWiki(_ scope: WikiScope) async throws {
|
|
85
|
+
let core = self.core, scope = text(scope.json(\.json))
|
|
86
|
+
try await blocking { try core.setWiki(scopeJson: scope) }
|
|
87
|
+
}
|
|
88
|
+
public func resetWiki() async throws {
|
|
89
|
+
let core = self.core
|
|
90
|
+
try await blocking { try core.resetWiki() }
|
|
91
|
+
}
|
|
92
|
+
public func close() async throws {
|
|
93
|
+
let core = self.core
|
|
94
|
+
try await blocking { try core.shutdown() }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
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
|
|
103
|
+
guard let id = item["id"].string, let text = item["text"].string else { throw malformed("memory item") }
|
|
104
|
+
return MemoryItem(id: id, text: text, fields: item)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
public func delete(_ id: String) async throws {
|
|
108
|
+
let core = self.core
|
|
109
|
+
try await blocking { try core.memoryDelete(id: id) }
|
|
110
|
+
}
|
|
111
|
+
public func clear() async throws {
|
|
112
|
+
let core = self.core
|
|
113
|
+
try await blocking { try core.memoryClear() }
|
|
114
|
+
}
|
|
115
|
+
public func enabled(_ on: Bool) async throws {
|
|
116
|
+
let core = self.core
|
|
117
|
+
try await blocking { try core.memoryEnabled(on: on) }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// Nested: a top-level `Subscription` collides with Combine's.
|
|
122
|
+
public final class Subscription: Sendable {
|
|
123
|
+
let core: CoreSubscription
|
|
124
|
+
init(core: CoreSubscription) { self.core = core }
|
|
125
|
+
/// Older pages, as `page` events on the same `onEvent`.
|
|
126
|
+
public func history(before: Int? = nil, limit: Int) async throws {
|
|
127
|
+
let core = self.core
|
|
128
|
+
var options: [String: JSON] = ["limit": .number(Double(limit))]
|
|
129
|
+
if let before { options["before"] = .number(Double(before)) }
|
|
130
|
+
let text = text(.object(options))
|
|
131
|
+
try await blocking { try core.history(optionsJson: text) }
|
|
132
|
+
}
|
|
133
|
+
public func close() { core.shutdown() }
|
|
134
|
+
public var ended: Bool { core.ended() }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
func decode<T: Decodable>(_ type: T.Type, _ text: String) throws -> T {
|
|
139
|
+
do { return try JSONDecoder().decode(type, from: Data(text.utf8)) }
|
|
140
|
+
catch { throw CrocheError(code: "internal", message: "Core's reply is malformed.", category: .internal) }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/// Core's event delivery. Decodes with the GENERATED reader, posts to the main thread; on THAT
|
|
144
|
+
/// stack, `tryEnter` immediately before the app's handler (false = no entry), then reports how it
|
|
145
|
+
/// finished: `returned`, or `threw` with the thrown value's facts (TS events.ts). Core assigns the
|
|
146
|
+
/// codes (`handler_failed`). No SDK queue, no wait at close: queue and close policy are Core's.
|
|
147
|
+
final class EventSinkAdapter: CoreEventSink, @unchecked Sendable {
|
|
148
|
+
private let onEvent: @Sendable (AgentEvent) async throws -> Void
|
|
149
|
+
init(_ onEvent: @escaping @Sendable (AgentEvent) async throws -> Void) { self.onEvent = onEvent }
|
|
150
|
+
|
|
151
|
+
static let returned = #"{"outcome":"returned"}"#
|
|
152
|
+
/// `{outcome:"threw", error:{name, message, code?}}`: facts only, as TS `thrownFacts`.
|
|
153
|
+
static func threw(_ error: Error) -> String {
|
|
154
|
+
var facts: [String: JSON] = ["name": .string(String(reflecting: type(of: error)))]
|
|
155
|
+
if let error = error as? CrocheError {
|
|
156
|
+
facts["message"] = .string(error.message); facts["code"] = .string(error.code)
|
|
157
|
+
} else {
|
|
158
|
+
facts["message"] = .string("\(error)")
|
|
159
|
+
}
|
|
160
|
+
return (strictText(.object(["outcome": .string("threw"), "error": .object(facts)]))) ?? #"{"outcome":"threw"}"#
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
func deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) throws {
|
|
164
|
+
try deliver(eventJson, delivery)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// The seam tests drive with a fake gate (Keel 14:40Z); Core's side of the fence is proven in
|
|
168
|
+
/// Rust/WASM with `for_tests`. Returns the main-actor task.
|
|
169
|
+
@discardableResult
|
|
170
|
+
func deliver(_ eventJson: String, _ delivery: any DeliveryGate) throws -> Task<Void, Never> {
|
|
171
|
+
let event: AgentEvent
|
|
172
|
+
do { event = try JSONDecoder().decode(AgentEvent.self, from: Data(eventJson.utf8)) }
|
|
173
|
+
catch { throw MalformedEvent(reason: "\(error)") }
|
|
174
|
+
let onEvent = self.onEvent
|
|
175
|
+
return Task { @MainActor in
|
|
176
|
+
guard delivery.tryEnter() else { return }
|
|
177
|
+
do { try await onEvent(event); delivery.complete(outcomeJson: Self.returned) }
|
|
178
|
+
catch { delivery.complete(outcomeJson: Self.threw(error)) }
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// A Core event the generated reader cannot read. The sink has NO error codes (Atlas's PAL error
|
|
184
|
+
/// contract): this untyped transport exception reaches Core, which classifies it (`internal`).
|
|
185
|
+
struct MalformedEvent: Error, CustomStringConvertible {
|
|
186
|
+
let reason: String
|
|
187
|
+
var description: String { "Core's event is not an AgentEvent: \(reason)" }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/// Core's per-delivery fence: entry is checked on the handler's own stack, then the outcome reported.
|
|
191
|
+
protocol DeliveryGate: Sendable {
|
|
192
|
+
func tryEnter() -> Bool
|
|
193
|
+
func complete(outcomeJson: String)
|
|
194
|
+
}
|
|
195
|
+
extension CoreDelivery: DeliveryGate {}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The binding facts Core reports to Cloud with each Runtime (docs/RUNTIME-CLOUD-PROTOCOL.md):
|
|
4
|
+
/// `{sdk, sdk_version, platform}`, passed beside the open JSON, never an OpenOptions member. They
|
|
5
|
+
/// are diagnostic and carry no logic; Core adds its own runtime_version.
|
|
6
|
+
enum BindingFacts {
|
|
7
|
+
/// This package's version. scripts/release-version.mjs sets it with every other SDK version,
|
|
8
|
+
/// and its --check refuses a value that differs from sdk/swift/VERSION.
|
|
9
|
+
static let sdkVersion = "0.6.0"
|
|
10
|
+
static var platform: String {
|
|
11
|
+
#if os(iOS)
|
|
12
|
+
return "ios"
|
|
13
|
+
#elseif os(macOS)
|
|
14
|
+
return "macos"
|
|
15
|
+
#elseif os(Linux)
|
|
16
|
+
return "linux"
|
|
17
|
+
#elseif os(Windows)
|
|
18
|
+
return "windows"
|
|
19
|
+
#elseif os(visionOS)
|
|
20
|
+
return "visionos"
|
|
21
|
+
#elseif os(tvOS)
|
|
22
|
+
return "tvos"
|
|
23
|
+
#elseif os(watchOS)
|
|
24
|
+
return "watchos"
|
|
25
|
+
#else
|
|
26
|
+
return "unknown" // never "server": an unlisted OS is reported as unknown, not guessed
|
|
27
|
+
#endif
|
|
28
|
+
}
|
|
29
|
+
/// `sdk` is "swift", or "react-native" from the RN iOS bridge, which builds these sources.
|
|
30
|
+
static func json(sdk: String = "swift") -> String {
|
|
31
|
+
text(.object(["sdk": .string(sdk), "sdk_version": .string(sdkVersion), "platform": .string(platform)]))
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// The 0.6 App API (docs/APP-API.md) over Core's S1 handle ABI: the module's public names. The
|
|
4
|
+
// legacy engine's facade stays internal (Legacy*) until its last caller, the RN iOS bridge, moves
|
|
5
|
+
// to S1 (Keel 21:58Z). Every value the app gives is passed to Core unchanged as JSON; this layer
|
|
6
|
+
// decides nothing.
|
|
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.
|
|
10
|
+
public typealias ErrorCategory = AppStreamContract.ErrorCategory
|
|
11
|
+
|
|
12
|
+
public struct CrocheError: Error, Sendable, CustomStringConvertible {
|
|
13
|
+
public let code: String
|
|
14
|
+
public let message: String
|
|
15
|
+
public let category: ErrorCategory
|
|
16
|
+
/// Where in the app's value Core found the fault (a manifest, scope or bind), when it says.
|
|
17
|
+
public let path: String?
|
|
18
|
+
public let retryAfter: UInt64?
|
|
19
|
+
init(code: String, message: String, category: ErrorCategory, path: String? = nil, retryAfter: UInt64? = nil) {
|
|
20
|
+
self.code = code; self.message = message; self.category = category; self.path = path; self.retryAfter = retryAfter
|
|
21
|
+
}
|
|
22
|
+
/// Core's carrier, passed through. A category outside the closed set is a Core bug: `internal`.
|
|
23
|
+
init(_ error: CoreApiError) {
|
|
24
|
+
switch error {
|
|
25
|
+
// Core's `detail` is the public message (UniFFI reserves `message`).
|
|
26
|
+
case let .Failure(code, detail, category, path, retryAfter):
|
|
27
|
+
self.init(code: code, message: detail, category: ErrorCategory(rawValue: category) ?? .internal, path: path, retryAfter: retryAfter)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/// Anything else a call threw (the binding's own errors) is code `internal`, literally, category internal (Keel #9).
|
|
31
|
+
init(_ error: Error) {
|
|
32
|
+
if let e = error as? CrocheError { self = e }
|
|
33
|
+
else if let e = error as? CoreApiError { self.init(e) }
|
|
34
|
+
else { self.init(code: "internal", message: "\(error)", category: .internal) }
|
|
35
|
+
}
|
|
36
|
+
public var description: String { "\(code): \(message)" }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Core's calls block their thread while the host performs effects: run them on a thread of
|
|
40
|
+
/// their own, never on the cooperative pool or the main thread.
|
|
41
|
+
func blocking<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {
|
|
42
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
43
|
+
Thread.detachNewThread {
|
|
44
|
+
Offload.starting?()
|
|
45
|
+
do { continuation.resume(returning: try body()) }
|
|
46
|
+
catch { continuation.resume(throwing: CrocheError(error)) }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/// As `blocking`, with a Core token the awaiting Task's cancellation fires (APP-API: cancelling
|
|
52
|
+
/// 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
|
|
54
|
+
/// the OS has task executors: GCD threads apart from Swift's cooperative pool, so app code that
|
|
55
|
+
/// blocks its thread never starves the SDK's own work or another call (#342).
|
|
56
|
+
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
|
57
|
+
final class ToolThreads: TaskExecutor, @unchecked Sendable {
|
|
58
|
+
static let shared = ToolThreads()
|
|
59
|
+
private let queue = DispatchQueue(label: "dev.croche.tools", attributes: .concurrent)
|
|
60
|
+
func enqueue(_ job: consuming ExecutorJob) {
|
|
61
|
+
let job = UnownedJob(job), executor = asUnownedTaskExecutor()
|
|
62
|
+
queue.async { job.runSynchronously(on: executor) }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Starts the app's async code for a Core callback on `ToolThreads` (the cooperative pool on an
|
|
67
|
+
/// OS without task executors).
|
|
68
|
+
@discardableResult
|
|
69
|
+
func appTask(_ body: @escaping @Sendable () async -> Void) -> Task<Void, Never> {
|
|
70
|
+
if #available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *) {
|
|
71
|
+
return Task(executorPreference: ToolThreads.shared) { await body() }
|
|
72
|
+
}
|
|
73
|
+
return Task { await body() }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// A Core call that hands back an OWNER (an open Croche, an agent). Cancelling the caller's Task
|
|
77
|
+
/// resumes the caller at once with `cancelled`; Core has no token for these calls, so the call
|
|
78
|
+
/// finishes on its own thread, and an owner that arrives after the cancellation is shut down
|
|
79
|
+
/// there (`discard`), never leaked holding its store or instance lock (Keel ruling #4).
|
|
80
|
+
func owner<T: Sendable>(_ body: @escaping @Sendable () throws -> T, discard: @escaping @Sendable (T) -> Void) async throws -> T {
|
|
81
|
+
let pending = Pending<T>()
|
|
82
|
+
return try await withTaskCancellationHandler {
|
|
83
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
84
|
+
guard pending.wait(continuation) else { return }
|
|
85
|
+
Thread.detachNewThread {
|
|
86
|
+
Offload.starting?()
|
|
87
|
+
let result = Result { try body() }.mapError { CrocheError($0) as Error }
|
|
88
|
+
if !pending.finish(result), case .success(let value) = result { discard(value) }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
} onCancel: { pending.cancel() }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// One caller's wait: whichever of the result and the cancellation comes first resumes it.
|
|
95
|
+
private final class Pending<T: Sendable>: @unchecked Sendable {
|
|
96
|
+
private let lock = NSLock()
|
|
97
|
+
private var continuation: CheckedContinuation<T, Error>?
|
|
98
|
+
private var cancelled = false, done = false
|
|
99
|
+
private static var cancellation: CrocheError {
|
|
100
|
+
CrocheError(code: "cancelled", message: "The caller's Task was cancelled.", category: .closed)
|
|
101
|
+
}
|
|
102
|
+
/// false = already cancelled (resumed here); start nothing.
|
|
103
|
+
func wait(_ continuation: CheckedContinuation<T, Error>) -> Bool {
|
|
104
|
+
let cancelled = lock.withLock { () -> Bool in
|
|
105
|
+
if self.cancelled { done = true; return true }
|
|
106
|
+
self.continuation = continuation; return false
|
|
107
|
+
}
|
|
108
|
+
if cancelled { continuation.resume(throwing: Self.cancellation) }
|
|
109
|
+
return !cancelled
|
|
110
|
+
}
|
|
111
|
+
func cancel() {
|
|
112
|
+
let waiting = lock.withLock { () -> CheckedContinuation<T, Error>? in
|
|
113
|
+
cancelled = true
|
|
114
|
+
guard !done, let continuation else { return nil }
|
|
115
|
+
done = true; return continuation
|
|
116
|
+
}
|
|
117
|
+
waiting?.resume(throwing: Self.cancellation)
|
|
118
|
+
}
|
|
119
|
+
/// false = the caller already left: the result is unclaimed.
|
|
120
|
+
func finish(_ result: Result<T, Error>) -> Bool {
|
|
121
|
+
let waiting = lock.withLock { () -> CheckedContinuation<T, Error>? in
|
|
122
|
+
guard !done, let continuation else { return nil }
|
|
123
|
+
done = true; return continuation
|
|
124
|
+
}
|
|
125
|
+
waiting?.resume(with: result)
|
|
126
|
+
return waiting != nil
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
func cancellable<T: Sendable>(_ body: @escaping @Sendable (CancelToken) throws -> T) async throws -> T {
|
|
131
|
+
let token = CancelToken()
|
|
132
|
+
return try await withTaskCancellationHandler {
|
|
133
|
+
try await blocking { try body(token) }
|
|
134
|
+
} onCancel: { token.cancel() }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// The app's value as the text Core reads. A Swift `JSON` cannot hold `undefined`. A non-finite
|
|
138
|
+
/// number has no JSON form: it is written as its bare token (`NaN`, `Infinity`, `-Infinity`), so
|
|
139
|
+
/// the text is not JSON and Core refuses it with its own code and category (Leo 18:40Z). Never
|
|
140
|
+
/// dropped, and no code or category is chosen here.
|
|
141
|
+
func text(_ value: JSON) -> String {
|
|
142
|
+
let mark = "croche-nonfinite-\(UUID().uuidString)"
|
|
143
|
+
let encoder = JSONEncoder()
|
|
144
|
+
encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: mark + "+", negativeInfinity: mark + "-", nan: mark + "n")
|
|
145
|
+
// JSON's cases are strings, numbers, bools, null, arrays and objects: encoding cannot otherwise fail.
|
|
146
|
+
let encoded = String(decoding: (try? encoder.encode(value)) ?? Data("null".utf8), as: UTF8.self)
|
|
147
|
+
guard encoded.contains(mark) else { return encoded }
|
|
148
|
+
return encoded.replacingOccurrences(of: "\"\(mark)+\"", with: "Infinity")
|
|
149
|
+
.replacingOccurrences(of: "\"\(mark)-\"", with: "-Infinity")
|
|
150
|
+
.replacingOccurrences(of: "\"\(mark)n\"", with: "NaN")
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/// A completion fact's JSON text, or nil when it has none (the caller sends its fallback fact).
|
|
154
|
+
func strictText(_ value: JSON) -> String? {
|
|
155
|
+
(try? value.encoded()).map { String(decoding: $0, as: UTF8.self) }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/// A Core reply. Unreadable = a Core bug, reported as such.
|
|
159
|
+
func reply(_ text: String) throws -> JSON {
|
|
160
|
+
do { return try JSON(text) } catch { throw CrocheError(code: "internal", message: "Core's reply is not JSON.", category: .internal) }
|
|
161
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
public struct BackgroundEvent: Sendable, Equatable {
|
|
4
|
+
/// `delivered`, `deadline`, `cancelled`, `skipped`, or a type this SDK does not know yet.
|
|
5
|
+
public let type: String
|
|
6
|
+
public let at: String?
|
|
7
|
+
/// `skipped`: `storage_unavailable`, or `os_registration_failed` (the OS refused the background
|
|
8
|
+
/// task: on iOS, BGTaskScheduler rejected `ai.croche.background` or it was registered after launch).
|
|
9
|
+
public let reason: String?
|
|
10
|
+
/// The whole event, so an app can log or forward what it does not read.
|
|
11
|
+
public let fields: JSON
|
|
12
|
+
init(_ value: JSON) {
|
|
13
|
+
type = value["type"].string ?? ""; at = value["at"].string; reason = value["reason"].string; fields = value
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
public struct WakeTimes: Sendable, Equatable {
|
|
18
|
+
public struct Wake: Sendable, Equatable { public let user: String; public let at: Double }
|
|
19
|
+
public let wakes: [Wake]
|
|
20
|
+
/// Epoch ms.
|
|
21
|
+
public let next: Double?
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
public struct DueDelivery: Sendable, Equatable {
|
|
25
|
+
public struct Deferred: Sendable, Equatable {
|
|
26
|
+
public let user: String, agent: String, instance: String?
|
|
27
|
+
/// `deadline` or `cancelled` today; open for codes Core adds.
|
|
28
|
+
public let code: String, message: String
|
|
29
|
+
}
|
|
30
|
+
public let ran: Bool
|
|
31
|
+
public let delivered: Int
|
|
32
|
+
public let deferred: [Deferred]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// `debugger.attach`'s options (APP-API `{url, token}`).
|
|
36
|
+
public struct DebugAttachOptions: Sendable, Equatable {
|
|
37
|
+
public var url: String
|
|
38
|
+
public var token: String
|
|
39
|
+
public init(url: String, token: String) { self.url = url; self.token = token }
|
|
40
|
+
var json: JSON { .object(["url": .string(url), "token": .string(token)]) }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
public struct AttachedDebugger: Sendable, Equatable {
|
|
44
|
+
/// The same value as the CLI/broker wire's `attachmentId`, so app logs match CLI logs.
|
|
45
|
+
public let debuggerId: String
|
|
46
|
+
/// `agents.list`, `status`, `history`, `send`, `cancel`, `tools`; open for more.
|
|
47
|
+
public let capabilities: [String]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// The shared-resource factory for one user's session.
|
|
51
|
+
public final class Croche: Sendable {
|
|
52
|
+
let core: CoreCroche
|
|
53
|
+
init(core: CoreCroche) { self.core = core }
|
|
54
|
+
|
|
55
|
+
/// Opening twice for the same (projectKey, user) is the SAME Core Croche, ref-counted in Core.
|
|
56
|
+
public static func open(_ options: OpenOptions) async throws -> Croche { try await opening(options, nil) }
|
|
57
|
+
|
|
58
|
+
/// RECOVERY OPEN (R1), for when `open(options)` fails because the project record is corrupt or
|
|
59
|
+
/// too new (`corrupt_store`, `store_too_new`) or a store refuses writes (`store_full`,
|
|
60
|
+
/// `store_refused`). Only `deleteData()` with an empty scope and `close()` work on the handle;
|
|
61
|
+
/// Core rejects every other member, and any recovery mode it does not know, with `invalid_request`.
|
|
62
|
+
public static func open(_ options: OpenOptions, recovery: RecoveryOptions) async throws -> Croche {
|
|
63
|
+
try await opening(options, recovery)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private static func opening(_ options: OpenOptions, _ recovery: RecoveryOptions?) async throws -> Croche {
|
|
67
|
+
let open = text(options.json), recoveryJson = recovery.map { text($0.json) }
|
|
68
|
+
let registrations = try (options.tools ?? []).map { try $0.core() }
|
|
69
|
+
#if CROCHE_TEST_HOOKS
|
|
70
|
+
if let serve = FixtureCloud.serve { return try await fixtureOpen(open, registrations, options.storage, recoveryJson, serve) }
|
|
71
|
+
#endif
|
|
72
|
+
let host = try platformHost(), storage = storageArgument(options.storage, host)
|
|
73
|
+
return Croche(core: try await owner({ try CoreCroche.open(openJson: open, registrations: registrations, storage: storage, host: host,
|
|
74
|
+
bindingFactsJson: BindingFacts.json(), recoveryJson: recoveryJson) },
|
|
75
|
+
discard: { try? $0.shutdown() }))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// Deletes this user's LOCAL data on the opened Croche. No scope (or an empty one): the declared
|
|
79
|
+
/// stores, registered instances and tool runtime; `agent`: that agent's main and named instances;
|
|
80
|
+
/// `agent` + `instance`: one instance. Core validates every scope. Other users, the install
|
|
81
|
+
/// record, undeclared legacy main stores and Cloud records remain. The Croche stays open; agents
|
|
82
|
+
/// in scope close, and a later `agent()` starts fresh stores. Core owns store locks and partial
|
|
83
|
+
/// progress: retry a failure with the same scope.
|
|
84
|
+
public func deleteData(_ scope: DataScope? = nil) async throws {
|
|
85
|
+
let core = self.core, scope = scope.map { text($0.json) }
|
|
86
|
+
try await blocking { try core.deleteData(scopeJson: scope) }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// Call once at launch (iOS: before didFinishLaunching returns). OS identifier `ai.croche.background`.
|
|
90
|
+
public static func registerBackground(_ options: BackgroundOptions = BackgroundOptions()) throws {
|
|
91
|
+
let host = try platformHost(), json = text(options.json)
|
|
92
|
+
do {
|
|
93
|
+
// With the app's store, Core also gets the platform store (its background markers);
|
|
94
|
+
// the default registration hands only the one store (Core: never a second wrapper).
|
|
95
|
+
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,
|
|
98
|
+
bindingFactsJson: BindingFacts.json())
|
|
99
|
+
} catch { throw CrocheError(error) }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/// When `deliverDue` is next needed (servers, serverless cron). Opens no project.
|
|
103
|
+
public static func wakeTimes(_ options: OpenOptions, before: Double? = nil, after: Double? = nil, limit: Int? = nil) async throws -> WakeTimes {
|
|
104
|
+
var query: [String: JSON] = [:]
|
|
105
|
+
if let before { query["before"] = .number(before) }
|
|
106
|
+
if let after { query["after"] = .number(after) }
|
|
107
|
+
if let limit { query["limit"] = .number(Double(limit)) }
|
|
108
|
+
let open = text(options.json), queryText = query.isEmpty ? nil : text(.object(query))
|
|
109
|
+
let host = try platformHost(), storage = storageArgument(options.storage, host)
|
|
110
|
+
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)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/// Delivery and config sync only. Cancel the Task to stop it.
|
|
119
|
+
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)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/// The same instance with the same or no config returns a handle to it; a different config
|
|
132
|
+
/// is Core's `invalid_configuration`.
|
|
133
|
+
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() }))
|
|
136
|
+
}
|
|
137
|
+
|
|
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) }
|
|
144
|
+
|
|
145
|
+
/// Returns once new work has stopped; the bounded final delivery continues.
|
|
146
|
+
public func close() async throws {
|
|
147
|
+
let core = self.core
|
|
148
|
+
try await blocking { try core.shutdown() }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// The project's original documents, in memory for this Croche; put/remove last until close().
|
|
152
|
+
public struct Wiki: Sendable {
|
|
153
|
+
let core: CoreCroche
|
|
154
|
+
public func put(_ doc: WikiDoc) async throws {
|
|
155
|
+
let core = self.core, doc = text(doc.json)
|
|
156
|
+
try await blocking { try core.wikiPut(docJson: doc) }
|
|
157
|
+
}
|
|
158
|
+
public func remove(_ path: String) async throws {
|
|
159
|
+
let core = self.core
|
|
160
|
+
try await blocking { try core.wikiRemove(path: path) }
|
|
161
|
+
}
|
|
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)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// The local debugger: loopback (iproxy), or LAN with the debug key.
|
|
171
|
+
public struct Debugger: Sendable {
|
|
172
|
+
let core: CoreCroche
|
|
173
|
+
public func attach(_ options: DebugAttachOptions) async throws -> AttachedDebugger {
|
|
174
|
+
let core = self.core, options = text(options.json)
|
|
175
|
+
let value = try reply(try await blocking { try core.debugAttach(optionsJson: options) })
|
|
176
|
+
guard let id = value["debuggerId"].string, let capabilities = value["capabilities"].array else { throw malformed("attached debugger") }
|
|
177
|
+
return AttachedDebugger(debuggerId: id, capabilities: capabilities.compactMap(\.string))
|
|
178
|
+
}
|
|
179
|
+
/// The last Croche alias close detaches the runtime.
|
|
180
|
+
public func detach() async throws {
|
|
181
|
+
let core = self.core
|
|
182
|
+
try await blocking { try core.debugDetach() }
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
func malformed(_ what: String) -> CrocheError {
|
|
188
|
+
CrocheError(code: "internal", message: "Core's \(what) is malformed.", category: .internal)
|
|
189
|
+
}
|
|
190
|
+
|
|
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)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/// Test-only: the OS launch handler table a host gate gives the platform PAL (macOS has none).
|
|
197
|
+
enum PlatformBackgroundTesting {
|
|
198
|
+
nonisolated(unsafe) static var launches: (any BackgroundLaunches)?
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/// The platform PAL (#820 seam): its storage is the default when the app gives none.
|
|
202
|
+
func platformHost() throws -> PlatformPal {
|
|
203
|
+
let directory = try NativeProjectFiles.directory(projectDirectory: nil)
|
|
204
|
+
return PlatformPal(directory: directory, secrets: PlatformPal.testingSecrets(directory),
|
|
205
|
+
backgroundLaunches: PlatformBackgroundTesting.launches ?? PlatformPal.osBackgroundLaunches())
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/// Background events, at least once, at the next registration in a live runtime. The same
|
|
209
|
+
/// delivery protocol as `subscribe` (#830 70a5ca8e): the app's sink runs only after `tryEnter`
|
|
210
|
+
/// succeeds, on the main actor, and every entered delivery is completed. The sink cannot throw, so
|
|
211
|
+
/// its outcome is always `returned`. An event that is not JSON is an untyped exception Core
|
|
212
|
+
/// classifies (no SDK-invented code).
|
|
213
|
+
final class BackgroundSink: CoreEventSink, @unchecked Sendable {
|
|
214
|
+
private let sink: @Sendable (BackgroundEvent) -> Void
|
|
215
|
+
init(_ sink: @escaping @Sendable (BackgroundEvent) -> Void) { self.sink = sink }
|
|
216
|
+
|
|
217
|
+
func deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) throws {
|
|
218
|
+
try deliver(eventJson, delivery)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/// The seam tests drive with a fake gate. Returns the main-actor task.
|
|
222
|
+
@discardableResult
|
|
223
|
+
func deliver(_ eventJson: String, _ delivery: any DeliveryGate) throws -> Task<Void, Never> {
|
|
224
|
+
guard let value = try? JSON(eventJson), value.object != nil else {
|
|
225
|
+
throw MalformedEvent(reason: "a background event must be a JSON object")
|
|
226
|
+
}
|
|
227
|
+
let event = BackgroundEvent(value), sink = self.sink
|
|
228
|
+
return Task { @MainActor in
|
|
229
|
+
guard delivery.tryEnter() else { return }
|
|
230
|
+
sink(event)
|
|
231
|
+
delivery.complete(outcomeJson: EventSinkAdapter.returned)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import Foundation
|
|
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.
|
|
6
|
+
public typealias AgentEvent = AppStreamContract.AgentEvent
|
|
7
|
+
public typealias MessageEnd = AppStreamContract.MessageEnd
|
|
8
|
+
public typealias InputDisposition = AppStreamContract.InputDisposition
|
|
9
|
+
/// `send`'s answer: Core has ACCEPTED the input. `error` is set when the input already failed.
|
|
10
|
+
public typealias SendReceipt = AppStreamContract.SendReceipt
|
|
11
|
+
/// `request`'s answer: the input is final. `gap` is true when Core says so, nil when absent.
|
|
12
|
+
public typealias RequestResult = AppStreamContract.RequestResult
|
|
13
|
+
/// `{code, category, message}` on a failed receipt, result, input or message.
|
|
14
|
+
public typealias EventError = AppStreamContract.EventError
|
|
15
|
+
|
|
16
|
+
public struct SubscribeOptions: Sendable {
|
|
17
|
+
public var initialMessages: Int?
|
|
18
|
+
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?
|
|
22
|
+
/// A throw reaches Core as the delivery's `threw` fact; Core decides what follows.
|
|
23
|
+
public var onEvent: @Sendable (AgentEvent) async throws -> Void
|
|
24
|
+
public init(initialMessages: Int? = nil, after: Cursor? = nil, deltaMs: Int? = nil,
|
|
25
|
+
onEvent: @escaping @Sendable (AgentEvent) async throws -> Void) {
|
|
26
|
+
self.initialMessages = initialMessages; self.after = after; self.deltaMs = deltaMs; self.onEvent = onEvent
|
|
27
|
+
}
|
|
28
|
+
}
|