@h1r-ai/croche-react-native 0.0.0-stage → 0.5.1

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 (77) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +486 -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 +837 -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/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
  11. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  12. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  16. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +32 -0
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  18. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +415 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +379 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +227 -0
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  40. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  41. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  42. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  43. package/croche-react-native.podspec +28 -0
  44. package/ios/CrocheRuntimeBridge.swift +1008 -0
  45. package/ios/RNCrocheRuntime.mm +221 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  48. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  49. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +215 -0
  50. package/ios/vendor/CrocheRuntimeSDK/Host.swift +562 -0
  51. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  52. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  53. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
  54. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  55. package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
  56. package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
  57. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +558 -0
  58. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  59. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +453 -0
  60. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  61. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +345 -0
  62. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  63. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  64. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  65. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  66. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  67. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  68. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  69. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  70. package/package.json +40 -4
  71. package/scripts/vendor-native.sh +56 -0
  72. package/src/NativeCrocheRuntime.ts +162 -0
  73. package/src/index.ts +660 -0
  74. package/src/project-types.ts +35 -0
  75. package/src/project.ts +434 -0
  76. package/src/protocol.ts +28 -0
  77. package/src/types.ts +9 -0
@@ -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
+ }
@@ -0,0 +1,42 @@
1
+ import Foundation
2
+
3
+ // Linux has no CryptoKit. Only the storage slot is hashed; no SDK cryptographic identity.
4
+ enum PortableSHA256 {
5
+ private static let constants: [UInt32] = [
6
+ 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
7
+ 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
8
+ 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
9
+ 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
10
+ 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
11
+ 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
12
+ 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
13
+ 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]
14
+ private static func rotate(_ value: UInt32, _ n: UInt32) -> UInt32 { (value >> n) | (value << (32 - n)) }
15
+ static func hex(_ bytes: [UInt8]) -> String {
16
+ var input = bytes
17
+ let bits = UInt64(input.count) * 8
18
+ input.append(0x80)
19
+ while input.count % 64 != 56 { input.append(0) }
20
+ for shift in stride(from: 56, through: 0, by: -8) { input.append(UInt8(truncatingIfNeeded: bits >> shift)) }
21
+ var h: [UInt32] = [0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]
22
+ for offset in stride(from: 0, to: input.count, by: 64) {
23
+ var w = [UInt32](repeating: 0, count: 64)
24
+ for i in 0..<16 {
25
+ let j = offset + 4 * i
26
+ w[i] = UInt32(input[j]) << 24 | UInt32(input[j+1]) << 16 | UInt32(input[j+2]) << 8 | UInt32(input[j+3])
27
+ }
28
+ for i in 16..<64 {
29
+ let x = w[i-15], y = w[i-2]
30
+ w[i] = w[i-16] &+ (rotate(x,7) ^ rotate(x,18) ^ (x >> 3)) &+ w[i-7] &+ (rotate(y,17) ^ rotate(y,19) ^ (y >> 10))
31
+ }
32
+ var a=h[0], b=h[1], c=h[2], d=h[3], e=h[4], f=h[5], g=h[6], v=h[7]
33
+ for i in 0..<64 {
34
+ let first = v &+ (rotate(e,6) ^ rotate(e,11) ^ rotate(e,25)) &+ ((e & f) ^ (~e & g)) &+ constants[i] &+ w[i]
35
+ let second = (rotate(a,2) ^ rotate(a,13) ^ rotate(a,22)) &+ ((a & b) ^ (a & c) ^ (b & c))
36
+ v=g; g=f; f=e; e=d &+ first; d=c; c=b; b=a; a=first &+ second
37
+ }
38
+ for (i,value) in [a,b,c,d,e,f,g,v].enumerated() { h[i] = h[i] &+ value }
39
+ }
40
+ return h.map { String(format: "%08x", $0) }.joined()
41
+ }
42
+ }
@@ -0,0 +1,271 @@
1
+ import Foundation
2
+
3
+ /// Code overrides and instance admission go unchanged to Core.
4
+ public struct AgentOptions: Sendable {
5
+ public var instance: String?
6
+ public var fresh: Bool?
7
+ public var config: JSON?
8
+ public init(instance: String? = nil, fresh: Bool? = nil, config: JSON? = nil) {
9
+ self.instance = instance; self.fresh = fresh; self.config = config
10
+ }
11
+ var json: JSON {
12
+ var value: [String: JSON] = [:]
13
+ if let instance { value["instance"] = .string(instance) }
14
+ if let fresh { value["fresh"] = .bool(fresh) }
15
+ if let config { value["config"] = config }
16
+ return .object(value)
17
+ }
18
+ }
19
+
20
+ public typealias ProjectToolContext = ToolContext
21
+ public typealias ProjectUsageEvent = JSON
22
+ public typealias RuntimeDebugEvent = JSON
23
+ public typealias MemoryChangedEvent = JSON
24
+
25
+ /// The project-returned agent uses the existing Runtime's port, subscriptions and memory.
26
+ public final class CrocheAgent: Sendable {
27
+ private let core: CoreRuntime
28
+ private let runtime: CrocheRuntime
29
+ private let lifetime = ProjectAgentLifetime()
30
+ private let hub: StreamHub
31
+ public let id: String
32
+ public let instance: String?
33
+ public let created: Bool
34
+ public let logId: String
35
+ init(core: CoreRuntime, runtime: CrocheRuntime, hub: StreamHub) {
36
+ self.hub = hub
37
+ self.core = core; self.runtime = runtime
38
+ id = core.agentId(); instance = core.instance(); created = core.created(); logId = runtime.logId
39
+ }
40
+ public var name: String? { core.name() }
41
+ public var mode: String? { core.mode() }
42
+ public var visibleTools: [String]? { core.visibleTools() }
43
+ public var closed: Bool { lifetime.closed }
44
+ public var memory: CrocheMemory { runtime.memory }
45
+ private func check() throws { if closed { throw CrocheError("closed", "The agent is closed.") } }
46
+ public func setTools(_ visible: [String]?) async throws {
47
+ try check(); let core = self.core
48
+ _ = try await CrocheRuntime.offload { try core.setTools(visible: visible); return true }
49
+ }
50
+ public func setMode(_ mode: String?) async throws {
51
+ try check(); let core = self.core
52
+ _ = try await CrocheRuntime.offload { try core.setMode(mode: mode); return true }
53
+ }
54
+ public func sync() async throws { try check(); _ = try await runtime.sync() }
55
+ public func send(_ input: SendInput, _ options: SendOptions = SendOptions()) async throws -> Receipt {
56
+ try check(); return try await runtime.send(input, options: options)
57
+ }
58
+ public func request(_ input: SendInput, _ options: RequestOptions = RequestOptions()) async throws -> RequestResult {
59
+ try check()
60
+ let result = try await runtime.request(input, options: SendOptions(responseFormat: options.responseFormat), wait: options.wait)
61
+ try? await runtime.refreshMemory()
62
+ return result
63
+ }
64
+ public func subscribe(_ options: SubscribeOptions) -> AgentSubscription { hub.subscribe(options) }
65
+ public func history(_ options: HistoryOptions) async throws {
66
+ try check(); try await runtime.history(before: options.before, limit: options.limit)
67
+ }
68
+ public func cancel(_ id: String? = nil) async throws {
69
+ try check()
70
+ if let id { try await runtime.cancel(id) }
71
+ else {
72
+ let core = self.core
73
+ _ = try await CrocheRuntime.offload { core.cancelTurn(); return true }
74
+ }
75
+ }
76
+ public func clearHistory() async throws { try check(); try await runtime.clearHistory(); try? await runtime.refreshMemory() }
77
+ public func close() async throws {
78
+ let task = lifetime.close { try await self.runtime.close() }
79
+ try await task.value
80
+ }
81
+ }
82
+
83
+ private final class ProjectAgentLifetime: @unchecked Sendable {
84
+ private let lock = NSLock()
85
+ private var closing: Task<Void, Error>?
86
+ var closed: Bool { lock.withLock { closing != nil } }
87
+ func close(_ body: @escaping @Sendable () async throws -> Void) -> Task<Void, Error> {
88
+ lock.withLock {
89
+ if let closing { return closing }
90
+ let task = Task { try await body() }; closing = task; return task
91
+ }
92
+ }
93
+ }
94
+
95
+ // Internal host construction, shared by platform-owned storage and host tests.
96
+ struct NativeProjectOptions: Sendable {
97
+ var host: JSON
98
+ var config: JSON
99
+ var user: String?
100
+ var language: String?
101
+ var handlers: [String: ToolHandler] = [:]
102
+ var streaming = true
103
+ var backgroundSync = true
104
+ var maintenanceIntervalMs = 60_000.0
105
+ var storage: @Sendable (String) -> any RuntimeStorage
106
+ var secretStorage: @Sendable (String) -> any RuntimeSecretStore
107
+ var attestor: (any RuntimeAttestor)?
108
+ var fetch: RuntimeHTTP?
109
+ var timeZone: TimeZone?
110
+ var records: @Sendable () -> ProjectRecordFiles
111
+ var onUsage: (@Sendable (JSON) -> Void)?
112
+ var onDebugEvent: (@Sendable (JSON) -> Void)?
113
+ }
114
+
115
+ final class NativeProjectPals: HostPalFactory, @unchecked Sendable {
116
+ private let lock = NSLock()
117
+ private var hosts: [String: SwiftHost] = [:]
118
+ private var all: [SwiftHost] = []
119
+ let options: NativeProjectOptions
120
+ init(_ options: NativeProjectOptions) { self.options = options }
121
+ func pal(agent: String) -> any HostPal {
122
+ let options = self.options
123
+ let slot = NativeProjectSlot.storageLabel(agent)
124
+ let handlers = options.handlers.mapValues { handler -> ToolHandler in
125
+ { invocation, context in
126
+ var data = context.data.object ?? [:]
127
+ let issued = data.removeValue(forKey: "userId")?.string
128
+ data["user"] = options.user.map(JSON.string) ?? .null
129
+ data["crocheUserId"] = issued.flatMap { $0.isEmpty ? nil : $0 }.map(JSON.string) ?? .null
130
+ do { return try await handler(invocation, ToolContext(data: .object(data), cancellation: context.cancellation, images: context.images)) }
131
+ catch { throw CrocheError("effect_failed", "The tool handler failed.") }
132
+ }
133
+ }
134
+ // A fresh host for every request: record and default-agent PALs are separate.
135
+ let host = SwiftHost(storage: options.storage(slot), secrets: options.secretStorage(slot),
136
+ attestor: options.attestor, http: options.fetch, tools: handlers,
137
+ background: options.backgroundSync, projectRecords: options.records())
138
+ host.timeZone = options.timeZone
139
+ lock.withLock { if !NativeProjectSlot.isMaintenance(agent) { hosts[agent] = host }; all.append(host) }
140
+ return host
141
+ }
142
+ func host(_ slot: String) throws -> SwiftHost {
143
+ try lock.withLock {
144
+ guard let host = hosts[slot] else { throw CrocheError("core_error", "Core opened an agent without requesting its host.") }
145
+ return host
146
+ }
147
+ }
148
+ func stop() {
149
+ let stopped = lock.withLock { () -> [SwiftHost] in
150
+ defer { all.removeAll(); hosts.removeAll() }; return all
151
+ }
152
+ for host in stopped { host.stop(); host.session.close() }
153
+ }
154
+ }
155
+
156
+ /// Core owns configuration selection, agent census, instances, locks and project identity.
157
+ public final class Croche: Sendable {
158
+ private let core: CoreProject
159
+ private let pals: NativeProjectPals
160
+ private let session: NativeProjectSession
161
+ private init(core: CoreProject, pals: NativeProjectPals) {
162
+ self.core = core; self.pals = pals; session = NativeProjectSession(core: core, pals: pals)
163
+ }
164
+ public var user: String? { core.user() }
165
+ public var installationId: String? { core.installationId() }
166
+ public var crocheUserId: String? { core.crocheUserId() }
167
+ public var agentIds: [String] { core.agentIds() }
168
+ var applied: JSON { (try? JSON(core.applied())) ?? .null }
169
+ public static func open(_ options: OpenOptions) async throws -> Croche {
170
+ let native = try await CrocheRuntime.offload { try options.native() }
171
+ return try await open(native)
172
+ }
173
+ public static func deleteStore(_ options: OpenOptions, agent: String? = nil) async throws {
174
+ let native = try await CrocheRuntime.offload { try options.native() }
175
+ try await deleteStore(native, agent: agent)
176
+ }
177
+ static func open(_ options: NativeProjectOptions) async throws -> Croche {
178
+ CrocheRuntime.warnIfReleaseBuildCarriesDebugKey(options.host)
179
+ let pals = NativeProjectPals(options)
180
+ let context = ProjectObserverContext(user: options.user)
181
+ var host = options.host
182
+ if let attestor = options.attestor { host["attestationPlatform"] = .string(attestor.platform) }
183
+ let wire = ProjectOpenOptions(host: try projectText(host), user: options.user,
184
+ config: try projectText(options.config), handlers: Array(options.handlers.keys), language: options.language,
185
+ streaming: options.streaming, backgroundSync: options.backgroundSync,
186
+ maintenanceIntervalMs: options.maintenanceIntervalMs)
187
+ do {
188
+ let core = try await CrocheRuntime.offload {
189
+ try CoreProject.open(pals: pals, options: wire, onUsage: options.onUsage.map { listener in EventHook { listener(context.usage($0)) } },
190
+ onDebug: options.onDebugEvent.map(EventHook.init))
191
+ }
192
+ context.attach(core)
193
+ return Croche(core: core, pals: pals)
194
+ } catch { pals.stop(); throw error }
195
+ }
196
+ static func deleteStore(_ options: NativeProjectOptions, agent: String? = nil) async throws {
197
+ let pals = NativeProjectPals(options); defer { pals.stop() }
198
+ let host = try projectText(options.host), config = try projectText(options.config)
199
+ _ = try await CrocheRuntime.offload {
200
+ try ffiProjectDelete(pals: pals, host: host, user: options.user, config: config, agent: agent); return true
201
+ }
202
+ }
203
+ public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
204
+ try await session.agent(id, options)
205
+ }
206
+ public func close() async throws { try await session.close() }
207
+ }
208
+
209
+ private actor NativeProjectSession {
210
+ private let core: CoreProject
211
+ private let pals: NativeProjectPals
212
+ private var agents: [String: CrocheAgent] = [:]
213
+ private var closing: Task<Void, Error>?
214
+ private var admission: Task<Void, Never>?
215
+ init(core: CoreProject, pals: NativeProjectPals) { self.core = core; self.pals = pals }
216
+ public func agent(_ id: String? = nil, _ options: AgentOptions = AgentOptions()) async throws -> CrocheAgent {
217
+ guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
218
+ let previous = admission
219
+ let task = Task { await previous?.value; return try await self.openAgent(id, options: options) }
220
+ admission = Task { _ = try? await task.value }
221
+ return try await task.value
222
+ }
223
+ private func openAgent(_ id: String?, options: AgentOptions) async throws -> CrocheAgent {
224
+ guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
225
+ let core = self.core, text = try projectText(options.json)
226
+ // Cached calls still go to Core, which checks overrides and admission.
227
+ let handle = try await CrocheRuntime.offload { try core.agentWithOptions(id: id, options: text) }
228
+ guard closing == nil else { throw CrocheError("closed", "The project is closed.") }
229
+ let slot = try handle.instance().map { try projectText(.array([.string(handle.agentId()), .string($0)])) } ?? handle.agentId()
230
+ if let existing = agents[slot], !existing.closed { return existing }
231
+ let runtime = try await CrocheRuntime.adopt(core: handle, host: pals.host(slot))
232
+ let agent = CrocheAgent(core: handle, runtime: runtime, hub: await runtime.subscriptionHub!)
233
+ if closing != nil { try await agent.close(); throw CrocheError("closed", "The project is closed.") }
234
+ agents[slot] = agent
235
+ return agent
236
+ }
237
+ public func close() async throws {
238
+ if let closing { return try await closing.value }
239
+ let core = self.core, pals = self.pals
240
+ let task = Task {
241
+ _ = try await CrocheRuntime.offload { core.close(); return true }
242
+ for agent in self.agents.values { try await agent.close() }
243
+ pals.stop()
244
+ }
245
+ closing = task
246
+ try await task.value
247
+ }
248
+ }
249
+ private func projectText(_ value: JSON) throws -> String {
250
+ let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
251
+ do { return String(decoding: try encoder.encode(value), as: UTF8.self) }
252
+ catch { throw CrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
253
+ }
254
+ private func ffiProjectDelete(pals: any HostPalFactory, host: String, user: String?, config: String, agent: String?) throws {
255
+ try deleteStore(pals: pals, host: host, user: user, config: config, agent: agent)
256
+ }
257
+
258
+ private final class ProjectObserverContext: @unchecked Sendable {
259
+ private let lock = NSLock()
260
+ private weak var core: CoreProject?
261
+ private let user: String?
262
+ init(user: String?) { self.user = user }
263
+ func attach(_ core: CoreProject) { lock.withLock { self.core = core } }
264
+ func usage(_ event: JSON) -> JSON {
265
+ let core = lock.withLock { self.core }
266
+ var value = event
267
+ value["user"] = (core?.user() ?? user).map(JSON.string) ?? .null
268
+ value["crocheUserId"] = core?.crocheUserId().map(JSON.string) ?? .null
269
+ return value
270
+ }
271
+ }