@h1r-ai/croche-react-native 0.0.0-stage → 0.5.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 (66) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +475 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/android/build.gradle +47 -0
  5. package/android/src/main/AndroidManifest.xml +8 -0
  6. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +836 -0
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
  9. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  11. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  12. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  13. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  16. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  17. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  18. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  32. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  33. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  34. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  35. package/croche-react-native.podspec +28 -0
  36. package/ios/CrocheRuntimeBridge.swift +986 -0
  37. package/ios/RNCrocheRuntime.mm +221 -0
  38. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  39. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  40. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  41. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
  42. package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
  43. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  44. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  45. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  48. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
  49. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  50. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
  51. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  52. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  53. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  54. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  55. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  56. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  57. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  58. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  59. package/package.json +40 -4
  60. package/scripts/vendor-native.sh +56 -0
  61. package/src/NativeCrocheRuntime.ts +162 -0
  62. package/src/index.ts +660 -0
  63. package/src/project-types.ts +35 -0
  64. package/src/project.ts +426 -0
  65. package/src/protocol.ts +28 -0
  66. package/src/types.ts +9 -0
@@ -0,0 +1,178 @@
1
+ import Foundation
2
+ #if canImport(ImageIO)
3
+ import ImageIO
4
+ import CoreGraphics
5
+ #endif
6
+
7
+ /// How an image is sent (F30, H3). `standard` (the default): at most 512 px on its longest side,
8
+ /// never upscaled, as PNG or JPEG, whichever is smaller (transparency kept as PNG; a GIF becomes
9
+ /// its first frame). `high`: as given, within the limits (3 MB each, 6 MB together), for text,
10
+ /// screenshots and dense detail. An https `url` image is never changed. An image's own
11
+ /// `"resolution"` wins over the send's or the tool result's.
12
+
13
+
14
+ /// A tool's result with images beside its value (H3): the same image kinds and limits as a
15
+ /// message's (`{"data", "mime", "alt"}` or `{"url"}`, at most 4); a violation fails that call
16
+ /// with `invalid_tool_result`, and the turn goes on. Return it from a handler made with
17
+ /// `withResult`.
18
+ public struct ToolResult: Sendable {
19
+ public var value: JSON
20
+ public var images: [JSON]
21
+ /// For every image that does not name its own `"resolution"`.
22
+ public var imageResolution: ImageResolution?
23
+ public init(value: JSON = .null, images: [JSON] = [], imageResolution: ImageResolution? = nil) {
24
+ self.value = value; self.images = images; self.imageResolution = imageResolution
25
+ }
26
+ }
27
+
28
+ /// The one way to return a `ToolResult` (its value, plus images):
29
+ /// `tools: ["room": withResult { invocation, context in ToolResult(value: ..., images: [...]) }]`.
30
+ /// The images go to the Runtime beside the value; a plain `ToolHandler`'s JSON is never looked
31
+ /// inside.
32
+ public func withResult(_ handler: @escaping @Sendable (_ invocation: JSON, _ context: ToolContext) async throws -> ToolResult) -> ToolHandler {
33
+ { invocation, context in
34
+ let result = try await handler(invocation, context)
35
+ // The handler ran: what it returned (plain values, nothing that can throw) is read once,
36
+ // here; a malformed image passes unchanged and fails this call alone in the Core.
37
+ context.images?.put(result.images.map { Images.prepare($0, fallback: result.imageResolution) })
38
+ return result.value
39
+ }
40
+ }
41
+
42
+ /// Where a `withResult` handler leaves its images for the call that ran it.
43
+ final class ImageSink: @unchecked Sendable {
44
+ private let lock = NSLock()
45
+ private var images: [JSON] = []
46
+ func put(_ images: [JSON]) { lock.withLock { self.images = images } }
47
+ func take() -> [JSON] { lock.withLock { images } }
48
+ }
49
+
50
+ enum Images {
51
+ static let standardMaxSide = 512
52
+ static let jpegQuality = 0.7
53
+
54
+ /// A send's input with its single or stacked images prepared.
55
+ static func prepareInput(_ input: JSON, fallback: ImageResolution?) -> JSON {
56
+ guard let stack = input["inputs"].array else {
57
+ guard let images = input["images"].array else { return input }
58
+ var out = input
59
+ out["images"] = .array(images.map { prepare($0, fallback: fallback) })
60
+ return out
61
+ }
62
+ var out = input
63
+ out["inputs"] = .array(stack.map { item in
64
+ guard let images = item["images"].array else { return item }
65
+ var item = item
66
+ item["images"] = .array(images.map { prepare($0, fallback: fallback) })
67
+ return item
68
+ })
69
+ return out
70
+ }
71
+
72
+ /// The image as it is sent: its resolution resolved and removed. Anything it cannot read
73
+ /// passes unchanged, for the Core to judge.
74
+ static func prepare(_ image: JSON, fallback: ImageResolution?) -> JSON {
75
+ // Malformed: exactly as given, for the Core to refuse (never rebuilt into a clean image).
76
+ guard var given = image.object, wellFormed(given) != nil else { return image }
77
+ let resolution = given.removeValue(forKey: "resolution")?.string.flatMap(ImageResolution.init) ?? fallback ?? .standard
78
+ guard resolution == .standard, let data = given["data"]?.string, let (mime, bytes) = decoded(data, given["mime"]?.string),
79
+ let best = reencoded(bytes, mime) else { return .object(given) }
80
+ var sent: [String: JSON] = ["data": .string(best.data.base64EncodedString()), "mime": .string(best.mime)]
81
+ if let alt = given["alt"] { sent["alt"] = alt }
82
+ return .object(sent)
83
+ }
84
+
85
+ static let mimes: Set<String> = ["image/png", "image/jpeg", "image/webp", "image/gif"]
86
+ /// A base64 image the Core would accept as given, by its shape (the Core's own rules: `data`
87
+ /// and no `url`, its mime one of the four and agreeing with a data URL's, base64 text, an
88
+ /// `alt` of at most 500 characters): its mime, or nil. Only such an image is re-encoded
89
+ /// (Atlas, #351 P1-3); anything else passes unchanged, so the Core refuses it as it would with
90
+ /// no codec. Sizes are judged on what is sent, after re-encoding.
91
+ static func wellFormed(_ image: [String: JSON]) -> String? {
92
+ func absent(_ key: String) -> Bool { image[key] == nil || image[key] == .null }
93
+ guard image["url"] == nil, let data = image["data"]?.string else { return nil }
94
+ var mime: String? = nil
95
+ if !absent("mime") {
96
+ guard let m = image["mime"]?.string, mimes.contains(m) else { return nil }
97
+ mime = m
98
+ }
99
+ if !absent("alt") {
100
+ guard let alt = image["alt"]?.string, alt.utf16.count <= 500 else { return nil }
101
+ }
102
+ var body = Substring(data)
103
+ if data.hasPrefix("data:") {
104
+ guard let comma = data.firstIndex(of: ",") else { return nil }
105
+ let head = data[data.index(data.startIndex, offsetBy: 5)..<comma]
106
+ guard head.hasSuffix(";base64") else { return nil }
107
+ let given = String(head.dropLast(";base64".count))
108
+ if let mime, mime != given { return nil }
109
+ mime = given
110
+ body = data[data.index(after: comma)...]
111
+ }
112
+ guard let mime, mimes.contains(mime) else { return nil }
113
+ let bare = body.reversed().drop(while: { $0 == "=" }).reversed()
114
+ guard !bare.isEmpty, body.count - bare.count <= 2,
115
+ bare.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "+" || $0 == "/") }) else { return nil }
116
+ return mime
117
+ }
118
+
119
+ private static func decoded(_ data: String, _ mime: String?) -> (String, Data)? {
120
+ var body = Substring(data), type = mime
121
+ if data.hasPrefix("data:") {
122
+ guard let comma = data.firstIndex(of: ","), data[..<comma].hasSuffix(";base64") else { return nil }
123
+ type = String(data[data.index(data.startIndex, offsetBy: 5)..<comma].dropLast(";base64".count))
124
+ body = data[data.index(after: comma)...]
125
+ }
126
+ guard let type, let bytes = Data(base64Encoded: String(body)) else { return nil }
127
+ return (type, bytes)
128
+ }
129
+
130
+ /// The smallest of PNG, JPEG (when no pixel can be transparent) and, when no resize was
131
+ /// needed, the original; nil when the original is the smallest or cannot be decoded.
132
+ static func reencoded(_ bytes: Data, _ mime: String) -> (data: Data, mime: String)? {
133
+ #if canImport(ImageIO)
134
+ guard let source = CGImageSourceCreateWithData(bytes as CFData, nil),
135
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
136
+ let width = properties[kCGImagePropertyPixelWidth] as? Int,
137
+ let height = properties[kCGImagePropertyPixelHeight] as? Int else { return nil }
138
+ let longest = max(width, height)
139
+ // Drawn through the thumbnail path even at full size: it applies the EXIF orientation,
140
+ // which a re-encoded image would otherwise lose. A GIF gives its first frame.
141
+ let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true,
142
+ kCGImageSourceCreateThumbnailWithTransform: true,
143
+ kCGImageSourceThumbnailMaxPixelSize: min(longest, standardMaxSide)]
144
+ guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }
145
+ let opaque = [.none, .noneSkipFirst, .noneSkipLast].contains(image.alphaInfo)
146
+ var candidates: [(data: Data, mime: String)] = []
147
+ if let png = encode(image, "public.png", nil) { candidates.append((png, "image/png")) }
148
+ if opaque, let jpeg = encode(image, "public.jpeg", jpegQuality) { candidates.append((jpeg, "image/jpeg")) }
149
+ guard let best = candidates.min(by: { $0.data.count < $1.data.count }) else { return nil }
150
+ if longest <= standardMaxSide && mime != "image/gif" && bytes.count <= best.data.count { return nil }
151
+ return best
152
+ #else
153
+ return nil
154
+ #endif
155
+ }
156
+
157
+ #if canImport(ImageIO)
158
+ private static func encode(_ image: CGImage, _ type: String, _ quality: Double?) -> Data? {
159
+ let out = NSMutableData()
160
+ guard let destination = CGImageDestinationCreateWithData(out, type as CFString, 1, nil) else { return nil }
161
+ CGImageDestinationAddImage(destination, image, quality.map { [kCGImageDestinationLossyCompressionQuality: $0] as CFDictionary })
162
+ return CGImageDestinationFinalize(destination) ? out as Data : nil
163
+ }
164
+ #endif
165
+
166
+ /// The FFI's image record; a field present but not text fails the call, as the Core would.
167
+ static func record(_ image: JSON) throws -> ToolImage {
168
+ func text(_ key: String) throws -> String? {
169
+ switch image[key] {
170
+ case .null: return nil
171
+ case .string(let v): return v
172
+ default: throw FfiError.Failure(code: "invalid_tool_result", message: "A tool result image's \(key) is text. Its effects may have completed.")
173
+ }
174
+ }
175
+ guard image.object != nil else { throw FfiError.Failure(code: "invalid_tool_result", message: "A tool result image is an object. Its effects may have completed.") }
176
+ return ToolImage(data: try text("data"), url: try text("url"), mime: try text("mime") ?? "", alt: try text("alt"))
177
+ }
178
+ }
@@ -0,0 +1,63 @@
1
+ import Foundation
2
+
3
+ /// A value-semantic JSON tree. Core state and machine stay opaque to the host.
4
+ public enum JSON: Codable, Sendable, Equatable {
5
+ case null, bool(Bool), number(Double), string(String), array([JSON]), object([String: JSON])
6
+ public init(from decoder: Decoder) throws {
7
+ let c = try decoder.singleValueContainer()
8
+ if c.decodeNil() { self = .null }
9
+ else if let v = try? c.decode(Bool.self) { self = .bool(v) }
10
+ else if let v = try? c.decode(Double.self) { self = .number(v) }
11
+ else if let v = try? c.decode(String.self) { self = .string(v) }
12
+ else if let v = try? c.decode([JSON].self) { self = .array(v) }
13
+ else { self = .object(try c.decode([String: JSON].self)) }
14
+ }
15
+ public func encode(to encoder: Encoder) throws {
16
+ var c = encoder.singleValueContainer()
17
+ switch self {
18
+ case .null: try c.encodeNil()
19
+ case .bool(let v): try c.encode(v)
20
+ case .number(let v): try c.encode(v)
21
+ case .string(let v): try c.encode(v)
22
+ case .array(let v): try c.encode(v)
23
+ case .object(let v): try c.encode(v)
24
+ }
25
+ }
26
+ public init(data: Data) throws { self = try JSONDecoder().decode(JSON.self, from: data) }
27
+ public init(_ text: String) throws { try self.init(data: Data(text.utf8)) }
28
+ public func encoded() throws -> Data { try JSONEncoder().encode(self) }
29
+ public subscript(_ key: String) -> JSON {
30
+ get { if case .object(let v) = self { return v[key] ?? .null }; return .null }
31
+ set { var v = object ?? [:]; v[key] = newValue; self = .object(v) }
32
+ }
33
+ public var object: [String: JSON]? { if case .object(let v) = self { return v }; return nil }
34
+ public var array: [JSON]? { if case .array(let v) = self { return v }; return nil }
35
+ public var string: String? { if case .string(let v) = self { return v }; return nil }
36
+ public var number: Double? { if case .number(let v) = self { return v }; return nil }
37
+ public var bool: Bool? { if case .bool(let v) = self { return v }; return nil }
38
+ }
39
+
40
+ public struct CrocheError: Error, Sendable, CustomStringConvertible {
41
+ public let code: String
42
+ public let message: String
43
+ public let receipt: Receipt?
44
+ public init(_ code: String, _ message: String, receipt: Receipt? = nil) { self.code = code; self.message = message; self.receipt = receipt }
45
+ public var description: String { "\(code): \(message)" }
46
+ }
47
+
48
+ // Bridge the existing Core identity key until S1 renames it. No store identity is minted here.
49
+ func publicStorageIdentity(_ value: JSON) -> JSON {
50
+ guard var fields = value.object else { return value }
51
+ if fields["storageKey"] == nil { fields["storageKey"] = fields["defaultStorageKey"] }
52
+ fields.removeValue(forKey: "defaultStorageKey")
53
+ return .object(fields)
54
+ }
55
+
56
+ // OPEN(Project→Agent): wire this at Croche.open once the reviewed Swift open surface lands.
57
+ // The SDK neither chooses a default nor validates the retention budget; Core owns both.
58
+ func coreOpenConfig(_ config: JSON, retentionBytes: Int?) -> JSON {
59
+ guard let retentionBytes else { return config }
60
+ var bound = config
61
+ bound["retentionBytes"] = .number(Double(retentionBytes))
62
+ return bound
63
+ }
@@ -0,0 +1,275 @@
1
+ import Foundation
2
+ #if canImport(Glibc)
3
+ import Glibc
4
+ #else
5
+ import Darwin
6
+ #endif
7
+
8
+ // Platform Abstraction Layer. The Rust Core decides; these perform what only the platform
9
+ // can: keep a credential in hardware-backed storage, and vouch for the app binary.
10
+ // See docs/MOBILE-SDK-AND-PAL.md.
11
+
12
+ /// Where the Runtime credential lives, apart from the general state file. load returns an
13
+ /// object (empty when nothing is stored). save replaces the whole object atomically.
14
+ public protocol RuntimeSecretStore: Sendable {
15
+ func load() throws -> JSON
16
+ func save(_ secrets: JSON) throws
17
+ /// Removes the credential item for real; absence succeeds. No default implementation.
18
+ func remove() throws
19
+ }
20
+
21
+ /// The platform's attestation of this app binary, bound to `clientDataHash`.
22
+ public struct RuntimeAttestation: Sendable {
23
+ public let token: String
24
+ public let keyId: String?
25
+ public init(token: String, keyId: String?) { self.token = token; self.keyId = keyId }
26
+ }
27
+
28
+ public protocol RuntimeAttestor: Sendable {
29
+ /// "ios-app-attest" or "android-play-integrity"; declared to the Core in config.
30
+ var platform: String { get }
31
+ /// `clientDataHash` is SHA-256(`clientData`), exactly as Cloud recomputes it.
32
+ func attest(clientData: String, clientDataHash: Data) async throws -> RuntimeAttestation
33
+ }
34
+
35
+ /// The OS's deferred work for the agent's scheduled notes while the app is not running (founder
36
+ /// 17:14Z): `AppRefreshScheduler` (BGTaskScheduler) on iOS. The Runtime calls it with the earliest
37
+ /// pending note after every change, at every open, and after every `deliverDue()`. The work it
38
+ /// registers runs `deliverDue()`: inexact, never before that time. No exact alarms,
39
+ /// notifications or permissions.
40
+ public protocol RuntimeScheduler: Sendable {
41
+ /// Replaces any earlier request with one at or after `earliest`. Idempotent: one request at a
42
+ /// time, by identifier. Throw `CrocheError("not_configured", ...)` when the app is not set up
43
+ /// for it: the Runtime reports `schedule.degraded` with that code and still delivers while
44
+ /// running and at the next foreground or open.
45
+ func schedule(earliest: Date) throws
46
+ /// Nothing is pending: withdraw the request.
47
+ func cancel()
48
+ /// A Runtime is opening with this scheduler. Throw `CrocheError("scheduler_conflict", ...)`
49
+ /// to refuse it when its identifier is already another open Runtime's: that identifier's
50
+ /// runs could deliver through only one of them, including when the same scheduler object is
51
+ /// given to a second Runtime.
52
+ func attach() throws
53
+ /// That Runtime closed (or failed to open): the identifier is free again. The Runtime calls
54
+ /// this at most once per successful `attach`, however often it is closed.
55
+ func detach()
56
+ }
57
+ public extension RuntimeScheduler {
58
+ func attach() throws {}
59
+ func detach() {}
60
+ }
61
+
62
+ /// One open Runtime per OS identity (an iOS task identifier): the rule the OS schedulers share,
63
+ /// kept in one place so the tests' schedulers run the same code as `AppRefreshScheduler` (Atlas,
64
+ /// #323 P1-2 and the NO at dc38bf0). `claim` is refused while the identity is held by anyone, the
65
+ /// claiming object included: `create` claims once per Runtime, so one object given to two
66
+ /// Runtimes is refused the second time. `release` frees it only for its holder.
67
+ final class SchedulerClaims: @unchecked Sendable {
68
+ private let lock = NSLock()
69
+ private var holders: [String: AnyObject] = [:]
70
+ private let what: String
71
+ init(what: String) { self.what = what }
72
+ func claim(_ identity: String, by: AnyObject) throws {
73
+ try lock.withLock {
74
+ if holders[identity] != nil {
75
+ throw CrocheError("scheduler_conflict", "Another open Runtime uses the \(what) \(identity); give each Runtime its own, or close it first")
76
+ }
77
+ holders[identity] = by
78
+ }
79
+ }
80
+ func release(_ identity: String, by: AnyObject) { lock.withLock { if holders[identity] === by { holders[identity] = nil } } }
81
+ func held(_ identity: String) -> Bool { lock.withLock { holders[identity] != nil } }
82
+ }
83
+
84
+ /// One background run the OS granted (a BGTaskScheduler launch): opens or reaches the app's
85
+ /// Runtime, delivers what is due, and reports whether that finished. `expire()` (the OS ending
86
+ /// background time) cancels this run's own delivery, waiting behind another turn or running,
87
+ /// never another turn of the Runtime (Atlas, #323 P1-1); after the run ended it does nothing.
88
+ /// The delivery's notes stay pending, registered again, for the next run or foreground.
89
+ final class BackgroundDelivery: @unchecked Sendable {
90
+ private let open: @Sendable () async throws -> CrocheRuntime
91
+ private let lock = NSLock()
92
+ private var task: Task<Void, Never>?
93
+ private var expired = false
94
+ init(open: @escaping @Sendable () async throws -> CrocheRuntime) { self.open = open }
95
+ func start(_ done: @escaping @Sendable (Bool) -> Void) {
96
+ let open = self.open
97
+ let task = Task {
98
+ let runtime: CrocheRuntime
99
+ do { runtime = try await open() } catch { done(false); return }
100
+ // Cancelling this Task cancels this delivery only (`deliverDue`). Expired before it
101
+ // began, it is cancelled at once, and its notes are registered again.
102
+ let result = try? await runtime.deliverDue()
103
+ done(!Task.isCancelled && (result.map { $0["ran"].bool != true || $0["delivered"].bool == true } ?? false))
104
+ }
105
+ if lock.withLock({ self.task = task; return expired }) { task.cancel() }
106
+ }
107
+ func expire() { lock.withLock { expired = true; return task }?.cancel() }
108
+ }
109
+
110
+ /// A 0600 file beside the state file. For hosts without a secret store (Linux, tests,
111
+ /// command-line tools). On iOS and macOS apps, use KeychainSecretStore.
112
+ public final class FileRuntimeSecretStore: RuntimeSecretStore, @unchecked Sendable {
113
+ private let url: URL
114
+ private let mutex = NSLock()
115
+ public init(url: URL) { self.url = url }
116
+ public func load() throws -> JSON {
117
+ mutex.lock(); defer { mutex.unlock() }
118
+ guard FileManager.default.fileExists(atPath: url.path) else { return .object([:]) }
119
+ let saved: JSON
120
+ do { saved = try JSON(data: Data(contentsOf: url)) }
121
+ catch { throw CrocheError("corrupt_store", "Runtime credentials are unreadable; remove them to register again") }
122
+ guard saved.object != nil else { throw CrocheError("corrupt_store", "Runtime credentials must be an object") }
123
+ return saved
124
+ }
125
+ public func save(_ secrets: JSON) throws {
126
+ mutex.lock(); defer { mutex.unlock() }
127
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
128
+ try secrets.encoded().write(to: url, options: .atomic)
129
+ _ = chmod(url.path, S_IRUSR | S_IWUSR)
130
+ }
131
+ public func remove() throws {
132
+ try mutex.withLock {
133
+ if unlink(url.path) != 0 && errno != ENOENT { throw CrocheError("storage_error", "Could not remove Runtime credentials") }
134
+ }
135
+ }
136
+
137
+ }
138
+
139
+ #if canImport(Security) && !os(Linux)
140
+ import Security
141
+
142
+ /// Keychain generic password, `AfterFirstUnlockThisDeviceOnly`: readable by background work
143
+ /// after the first unlock, never synced or restored to another device. It survives app
144
+ /// reinstall on iOS, so a reinstall keeps the same Runtime (and its credit) rather than
145
+ /// minting a new one.
146
+ public final class KeychainSecretStore: RuntimeSecretStore, @unchecked Sendable {
147
+ private let service: String
148
+ private let account: String
149
+ /// `account` should be the Runtime's storage key, so each agent's store has its own item.
150
+ public init(service: String = "ai.croche.runtime", account: String) {
151
+ self.service = service; self.account = account
152
+ }
153
+ private var query: [String: Any] {
154
+ [kSecClass as String: kSecClassGenericPassword,
155
+ kSecAttrService as String: service,
156
+ kSecAttrAccount as String: account]
157
+ }
158
+ public func load() throws -> JSON {
159
+ var lookup = query
160
+ lookup[kSecReturnData as String] = true
161
+ lookup[kSecMatchLimit as String] = kSecMatchLimitOne
162
+ var item: CFTypeRef?
163
+ let status = SecItemCopyMatching(lookup as CFDictionary, &item)
164
+ if status == errSecItemNotFound { return .object([:]) }
165
+ guard status == errSecSuccess, let data = item as? Data else {
166
+ throw CrocheError("storage_error", "Keychain read failed (\(status))")
167
+ }
168
+ guard let saved = try? JSON(data: data), saved.object != nil else {
169
+ throw CrocheError("corrupt_store", "Runtime credentials are unreadable; remove them to register again")
170
+ }
171
+ return saved
172
+ }
173
+ public func save(_ secrets: JSON) throws {
174
+ let data = try secrets.encoded()
175
+ let update = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary)
176
+ if update == errSecSuccess { return }
177
+ guard update == errSecItemNotFound else { throw CrocheError("storage_error", "Keychain write failed (\(update))") }
178
+ var add = query
179
+ add[kSecValueData as String] = data
180
+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
181
+ let status = SecItemAdd(add as CFDictionary, nil)
182
+ guard status == errSecSuccess else { throw CrocheError("storage_error", "Keychain write failed (\(status))") }
183
+ }
184
+ public func remove() throws {
185
+ let status = SecItemDelete(query as CFDictionary)
186
+ guard status == errSecSuccess || status == errSecItemNotFound else {
187
+ throw CrocheError("storage_error", "Keychain delete failed (\(status))")
188
+ }
189
+ }
190
+
191
+ }
192
+ #endif
193
+
194
+ #if canImport(DeviceCheck)
195
+ import DeviceCheck
196
+
197
+ /// Apple App Attest. Each registration generates a fresh key and attests it against the
198
+ /// Cloud challenge; Cloud checks the chain to Apple's root, the app id, and the nonce.
199
+ /// Simulators cannot attest: use a development project with attestation off there.
200
+ public struct AppAttestAttestor: RuntimeAttestor {
201
+ public let platform = "ios-app-attest"
202
+ public init() {}
203
+ public func attest(clientData: String, clientDataHash: Data) async throws -> RuntimeAttestation {
204
+ let service = DCAppAttestService.shared
205
+ guard service.isSupported else {
206
+ throw CrocheError("attestation_unsupported", "App Attest is not available here (simulators cannot attest)")
207
+ }
208
+ let keyId = try await service.generateKey()
209
+ let object = try await service.attestKey(keyId, clientDataHash: clientDataHash)
210
+ return RuntimeAttestation(token: object.base64EncodedString(), keyId: keyId)
211
+ }
212
+ }
213
+ #endif
214
+
215
+ func base64URLDecode(_ text: String) -> Data? {
216
+ var value = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
217
+ while value.count % 4 != 0 { value += "=" }
218
+ return Data(base64Encoded: value)
219
+ }
220
+
221
+ /// Incremental text/event-stream framing, over bytes: a read can split anywhere, including
222
+ /// inside a UTF-8 character or between CR and LF. Blocks are decoded only once complete.
223
+ /// The same rules as packages/runtime/src/sse.ts.
224
+ struct EventStreamParser {
225
+ struct Event: Equatable { let event: String; let data: String }
226
+ private var buffer = [UInt8]()
227
+ private var carriageReturn = false
228
+
229
+ mutating func push(_ bytes: [UInt8]) -> [Event] {
230
+ for byte in bytes {
231
+ if carriageReturn {
232
+ carriageReturn = false
233
+ buffer.append(0x0A)
234
+ if byte == 0x0A { continue }
235
+ }
236
+ if byte == 0x0D { carriageReturn = true } else { buffer.append(byte) }
237
+ }
238
+ return drain()
239
+ }
240
+ /// End of stream: a held CR can no longer be half of a CRLF, so it ends its line.
241
+ mutating func end() -> [Event] {
242
+ guard carriageReturn else { return [] }
243
+ carriageReturn = false; buffer.append(0x0A)
244
+ return drain()
245
+ }
246
+ private mutating func drain() -> [Event] {
247
+ var events: [Event] = []
248
+ var start = 0
249
+ var index = 0
250
+ while index + 1 < buffer.count {
251
+ if buffer[index] == 0x0A && buffer[index + 1] == 0x0A {
252
+ if let event = Self.block(String(decoding: buffer[start..<index], as: UTF8.self)) { events.append(event) }
253
+ index += 2; start = index
254
+ } else { index += 1 }
255
+ }
256
+ if start > 0 { buffer.removeFirst(start) }
257
+ return events
258
+ }
259
+ private static func block(_ text: String) -> Event? {
260
+ var name = "message"
261
+ var data: [String] = []
262
+ for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
263
+ if line.isEmpty || line.hasPrefix(":") { continue }
264
+ let field: Substring, value: Substring
265
+ if let colon = line.firstIndex(of: ":") {
266
+ field = line[..<colon]
267
+ var rest = line[line.index(after: colon)...]
268
+ if rest.hasPrefix(" ") { rest = rest.dropFirst() }
269
+ value = rest
270
+ } else { field = line; value = "" }
271
+ if field == "event" { name = String(value) } else if field == "data" { data.append(String(value)) }
272
+ }
273
+ return data.isEmpty ? nil : Event(event: name, data: data.joined(separator: "\n"))
274
+ }
275
+ }