@h1r-ai/croche-react-native 0.5.0 → 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 (31) hide show
  1. package/README.md +12 -1
  2. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +6 -5
  3. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
  4. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
  5. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +8 -1
  6. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +1 -1
  7. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
  8. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
  9. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +13 -3
  10. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +14 -3
  11. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
  12. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
  13. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
  14. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
  15. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +27 -11
  16. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  17. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  18. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  19. package/ios/CrocheRuntimeBridge.swift +26 -4
  20. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +4 -1
  21. package/ios/vendor/CrocheRuntimeSDK/Host.swift +2 -1
  22. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
  23. package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
  24. package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
  25. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +57 -10
  26. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +103 -9
  27. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +22 -0
  28. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  29. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  30. package/package.json +3 -3
  31. package/src/project.ts +9 -1
@@ -0,0 +1,44 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonObject
4
+ import java.io.File
5
+
6
+ data class OpenOptions(
7
+ val cloudUrl: String? = null,
8
+ val projectKey: String,
9
+ val config: JsonObject,
10
+ val user: String? = null,
11
+ val handlers: Map<String, ToolHandler> = emptyMap(),
12
+ val language: String? = null,
13
+ val timeZone: String? = null,
14
+ val streaming: Boolean? = null,
15
+ val backgroundSync: Boolean? = null,
16
+ val maintenanceIntervalMs: Long? = null,
17
+ val debugKey: String? = null,
18
+ val requestTimeoutMs: Long? = null,
19
+ val maxPendingEvents: Int? = null,
20
+ val syncIntervalMs: Long? = null,
21
+ val maintenanceBackoffMs: Long? = null,
22
+ val retentionBytes: Long? = null,
23
+ val onUsage: ((ProjectUsageEvent) -> Unit)? = null,
24
+ val onDebugEvent: ((RuntimeDebugEvent) -> Unit)? = null,
25
+ val debugVisibility: DebugVisibility? = null,
26
+ val attestation: Attestation? = null,
27
+ val android: AndroidOptions? = null,
28
+ val projectDirectory: File? = null,
29
+ val http: RuntimeHTTP? = null,
30
+ )
31
+ enum class DebugVisibility { RUNTIME }
32
+ enum class Attestation { PLATFORM, OFF }
33
+ data class AndroidOptions(val cloudProjectNumber: Long? = null)
34
+ typealias ProjectUsageEvent = JsonObject
35
+ typealias RuntimeDebugEvent = JsonObject
36
+ typealias MemoryChangedEvent = JsonObject
37
+ typealias ProjectToolContext = ToolContext
38
+
39
+ data class AgentOptions(val instance: String? = null, val fresh: Boolean? = null, val config: JsonObject? = null)
40
+ data class RequestOptions(val responseFormat: JsonObject? = null, val wait: RequestWait? = null)
41
+ data class SubscribeOptions(val initialMessages: Int? = null, val after: Cursor? = null,
42
+ val onEvent: suspend (RuntimeEvent) -> Unit)
43
+ data class HistoryOptions(val before: Long? = null, val limit: Int)
44
+ data class AppStreamEnd(val code: String)
@@ -53,7 +53,27 @@ internal class StreamHub(private val port: CoreStreamPort) : AutoCloseable {
53
53
  val logId get() = port.logId
54
54
  val state get() = port.state
55
55
 
56
- fun events(initialMessages: Int? = 50, after: Cursor? = null): Flow<RuntimeEvent> = flow {
56
+ internal inner class Collection(private val branch: AppStreamBranch, private val selected: CoreStreamPort.Projection?) {
57
+ suspend fun deliver(emit: suspend (RuntimeEvent) -> Unit) {
58
+ try { branch.deliver(emit) } finally { detach() }
59
+ }
60
+ fun close(last: RuntimeEvent? = RuntimeEvent.StreamError("closed", "Subscription is closed", false)) {
61
+ branch.end(last)
62
+ selected?.close()
63
+ }
64
+ private fun detach() {
65
+ branch.close()
66
+ selected?.close()
67
+ synchronized(lock) { if (app === branch) { app = null; projection = null } }
68
+ }
69
+ suspend fun history(before: Long?, limit: Int) {
70
+ if (limit !in 1..256) throw CrocheException("invalid_configuration", "history limit must be 1..256")
71
+ val current = synchronized(lock) { if (app === branch && !branch.isEnded) selected else null }
72
+ ?: throw CrocheException("invalid_configuration", "history requires an active subscription")
73
+ current.history(before, limit)
74
+ }
75
+ }
76
+ internal fun openCollection(initialMessages: Int?, after: Cursor?): Collection {
57
77
  val branch = AppStreamBranch()
58
78
  val selected = synchronized(lock) {
59
79
  if (ended) null else {
@@ -61,10 +81,8 @@ internal class StreamHub(private val port: CoreStreamPort) : AutoCloseable {
61
81
  projection = null
62
82
  app?.end(RuntimeEvent.Replaced)
63
83
  app = branch
64
- // A new collection replaces its predecessor even when its options are invalid,
65
- // matching S2. The error-only branch never selects Core.
66
- if (initialMessages != null && initialMessages !in 0..256) {
67
- branch.push(RuntimeEvent.StreamError("invalid_configuration", "initialMessages must be in 0..256", false))
84
+ if ((initialMessages != null && after != null) || (initialMessages != null && initialMessages !in 0..256)) {
85
+ branch.push(RuntimeEvent.StreamError("invalid_configuration", "Select initialMessages in 0..256 or after, not both", false))
68
86
  null
69
87
  } else try {
70
88
  port.select(initialMessages, after, branch::push).also { projection = it }
@@ -75,12 +93,10 @@ internal class StreamHub(private val port: CoreStreamPort) : AutoCloseable {
75
93
  }
76
94
  }
77
95
  if (selected == null && !branch.isEnded) branch.end(RuntimeEvent.StreamError("closed", "Runtime is closed", false))
78
- try { branch.deliver { emit(it) } }
79
- finally {
80
- branch.close()
81
- selected?.close()
82
- synchronized(lock) { if (app === branch) { app = null; projection = null } }
83
- }
96
+ return Collection(branch, selected)
97
+ }
98
+ fun events(initialMessages: Int? = 50, after: Cursor? = null): Flow<RuntimeEvent> = flow {
99
+ openCollection(initialMessages, after).deliver { emit(it) }
84
100
  }
85
101
 
86
102
  suspend fun send(input: SendInput, options: SendOptions): Receipt {
@@ -315,14 +315,22 @@ public final class CrocheRuntimeBridge: NSObject, @unchecked Sendable {
315
315
  private var hosts: [String: SwiftHost] = [:]
316
316
  private var pals: [String: ProjectPal] = [:]
317
317
  private var handles: [String: (String, DispatchQueue)] = [:]
318
+ private var maintenanceHosts: [SwiftHost] = []
318
319
  let directory: URL
319
320
  let namespace: String
320
321
  let names: [String]
321
322
  let background: Bool
323
+ let timeZone: TimeZone?
322
324
  let attestor: (any RuntimeAttestor)?
323
325
  weak var bridge: CrocheRuntimeBridge?
324
326
  init(_ bridge: CrocheRuntimeBridge, options: JSON) throws {
325
327
  self.bridge = bridge
328
+ if let name = options["timeZone"].string {
329
+ guard let zone = TimeZone(identifier: name) else {
330
+ throw CrocheError("invalid_configuration", "Unknown timeZone: " + name)
331
+ }
332
+ timeZone = zone
333
+ } else { timeZone = nil }
326
334
  directory = try CrocheRuntimeBridge.directory()
327
335
  var identityConfig = options["host"]
328
336
  identityConfig["user"] = options["user"]
@@ -344,9 +352,10 @@ public final class CrocheRuntimeBridge: NSObject, @unchecked Sendable {
344
352
  func pal(agent: String) -> HostPal { port(agent) }
345
353
  private func port(_ agent: String) -> ProjectPal {
346
354
  lock.withLock {
347
- if let pal = pals[agent] { return pal }
355
+ let maintenance = NativeProjectSlot.isMaintenance(agent)
356
+ if !maintenance, let pal = pals[agent] { return pal }
348
357
  // Fixed-size agent namespace, including ids with multibyte characters.
349
- let suffix = SHA256.hash(data: Data(agent.utf8)).map { String(format: "%02x", $0) }.joined()
358
+ let suffix = SHA256.hash(data: Data(NativeProjectSlot.storageLabel(agent).utf8)).map { String(format: "%02x", $0) }.joined()
350
359
  let key = namespace + ".agent." + suffix
351
360
  let replies = ToolReplies()
352
361
  var tools: [String: ToolHandler] = [:]
@@ -367,6 +376,7 @@ public final class CrocheRuntimeBridge: NSObject, @unchecked Sendable {
367
376
  secrets: KeychainSecretStore(account: key), attestor: attestor,
368
377
  http: nil, tools: tools, background: background)
369
378
  #endif
379
+ host.timeZone = timeZone
370
380
  let pal = ProjectPal(host, replies, begin: { [weak self] call, cancel in
371
381
  guard let self, let bridge = self.bridge,
372
382
  let name = call["tool"].string, self.names.contains(name),
@@ -375,7 +385,8 @@ public final class CrocheRuntimeBridge: NSObject, @unchecked Sendable {
375
385
  }
376
386
  return try bridge.beginProjectTool(handle, events: events, call: call, cancel: cancel)
377
387
  }, end: { [weak bridge = self.bridge] key, reply in bridge?.endProjectTool(key, reply: reply) })
378
- hosts[agent] = host; pals[agent] = pal
388
+ if maintenance { maintenanceHosts.append(host) }
389
+ else { hosts[agent] = host; pals[agent] = pal }
379
390
  return pal
380
391
  }
381
392
  }
@@ -390,11 +401,22 @@ public final class CrocheRuntimeBridge: NSObject, @unchecked Sendable {
390
401
  func stop(_ agent: String? = nil) {
391
402
  let stopped = lock.withLock { () -> [SwiftHost] in
392
403
  if let agent { handles.removeValue(forKey: agent); pals.removeValue(forKey: agent); return hosts.removeValue(forKey: agent).map { [$0] } ?? [] }
393
- let all = Array(hosts.values); hosts.removeAll(); pals.removeAll(); handles.removeAll(); return all
404
+ let all = Array(hosts.values) + maintenanceHosts; maintenanceHosts.removeAll(); hosts.removeAll(); pals.removeAll(); handles.removeAll(); return all
394
405
  }
395
406
  for host in stopped { host.stop(); host.session.close() }
396
407
  }
397
408
  }
409
+ #if CROCHE_BRIDGE
410
+ static func projectPalsForTesting(_ options: JSON) throws -> (any HostPalFactory, @Sendable () -> Void) {
411
+ let pals = try ProjectPals(CrocheRuntimeBridge(), options: options)
412
+ return (pals, { pals.stop() })
413
+ }
414
+ static func projectOffsetForTesting(_ options: JSON, atMs: Double) throws -> Int64 {
415
+ let pals = try ProjectPals(CrocheRuntimeBridge(), options: options)
416
+ defer { pals.stop() }
417
+ return pals.pal(agent: "default").utcOffsetMinutes(atMs: atMs)
418
+ }
419
+ #endif
398
420
  private static func text(_ value: JSON) throws -> String { String(decoding: try value.encoded(), as: UTF8.self) }
399
421
  private static func optional(_ value: String?) -> JSON { value.map(JSON.string) ?? .null }
400
422
  private static func strings(_ value: [String]?) -> JSON { value.map { .array($0.map(JSON.string)) } ?? .null }
@@ -83,7 +83,10 @@ final class FFIStreamPort: CoreStreamPort, @unchecked Sendable {
83
83
  try Self.blocking { [core] in try core.history(id: id, before: before, limit: limit) }
84
84
  }
85
85
  func send(_ input: JSON, options: SendOptions) async throws -> Receipt {
86
- try await send(input, options: options, cancel: nil)
86
+ let token = CancelToken()
87
+ return try await withTaskCancellationHandler {
88
+ try await send(input, options: options, cancel: token)
89
+ } onCancel: { token.cancel() }
87
90
  }
88
91
  func send(_ input: JSON, options: SendOptions, cancel: CancelToken?) async throws -> Receipt {
89
92
  let text = String(decoding: try input.encoded(), as: UTF8.self)
@@ -155,6 +155,7 @@ final class SwiftHost: HostPal, @unchecked Sendable {
155
155
  /// another Runtime, must not free an identifier someone else holds. Guarded by `lock`.
156
156
  private var osAttached = false
157
157
  private let osScheduler: (any RuntimeScheduler)?
158
+ var timeZone: TimeZone?
158
159
  private var wallClock: @Sendable () -> Double = { Date().timeIntervalSince1970 * 1000 }
159
160
  /// The wall clock (epoch ms) the Runtime and its timers read. Tests move it.
160
161
  var clock: @Sendable () -> Double {
@@ -368,7 +369,7 @@ final class SwiftHost: HostPal, @unchecked Sendable {
368
369
  // MARK: Clock, entropy, timer
369
370
  func nowMs() -> Double { clock() }
370
371
  func utcOffsetMinutes(atMs: Double) -> Int64 {
371
- Int64(TimeZone.current.secondsFromGMT(for: Date(timeIntervalSince1970: atMs / 1000)) / 60)
372
+ Int64((timeZone ?? TimeZone.current).secondsFromGMT(for: Date(timeIntervalSince1970: atMs / 1000)) / 60)
372
373
  }
373
374
  func random() -> String { UUID().uuidString }
374
375
  func wake(atMs: Double?) {
@@ -0,0 +1,172 @@
1
+ import Foundation
2
+ #if canImport(CryptoKit)
3
+ import CryptoKit
4
+ #endif
5
+
6
+ public enum DebugVisibility: String, Sendable { case runtime }
7
+ public enum Attestation: String, Sendable { case platform, off }
8
+ // Q9 recommendation: backgroundDelivery is deferred until the per-agent identifier rule.
9
+ public struct OpenOptions: Sendable {
10
+ public var cloudUrl: String?
11
+ public var projectKey: String
12
+ public var config: JSON
13
+ public var user: String?
14
+ public var handlers: [String: ToolHandler]
15
+ public var language: String?
16
+ public var timeZone: String?
17
+ public var streaming: Bool?
18
+ public var backgroundSync: Bool?
19
+ public var maintenanceIntervalMs: Double?
20
+ public var debugKey: String?
21
+ public var requestTimeoutMs: Double?
22
+ public var maxPendingEvents: Int?
23
+ public var syncIntervalMs: Double?
24
+ public var maintenanceBackoffMs: Double?
25
+ public var retentionBytes: Int?
26
+ public var onUsage: (@Sendable (ProjectUsageEvent) -> Void)?
27
+ public var onDebugEvent: (@Sendable (RuntimeDebugEvent) -> Void)?
28
+ public var debugVisibility: DebugVisibility?
29
+ public var attestation: Attestation?
30
+ public var projectDirectory: URL?
31
+ public var http: RuntimeHTTP?
32
+ public init(cloudUrl: String? = nil,
33
+ projectKey: String,
34
+ config: JSON,
35
+ user: String? = nil,
36
+ handlers: [String: ToolHandler] = [:],
37
+ language: String? = nil,
38
+ timeZone: String? = nil,
39
+ streaming: Bool? = nil,
40
+ backgroundSync: Bool? = nil,
41
+ maintenanceIntervalMs: Double? = nil,
42
+ debugKey: String? = nil,
43
+ requestTimeoutMs: Double? = nil,
44
+ maxPendingEvents: Int? = nil,
45
+ syncIntervalMs: Double? = nil,
46
+ maintenanceBackoffMs: Double? = nil,
47
+ retentionBytes: Int? = nil,
48
+ onUsage: (@Sendable (ProjectUsageEvent) -> Void)? = nil,
49
+ onDebugEvent: (@Sendable (RuntimeDebugEvent) -> Void)? = nil,
50
+ debugVisibility: DebugVisibility? = nil,
51
+ attestation: Attestation? = nil,
52
+ projectDirectory: URL? = nil,
53
+ http: RuntimeHTTP? = nil) {
54
+ self.cloudUrl = cloudUrl
55
+ self.projectKey = projectKey
56
+ self.config = config
57
+ self.user = user
58
+ self.handlers = handlers
59
+ self.language = language
60
+ self.timeZone = timeZone
61
+ self.streaming = streaming
62
+ self.backgroundSync = backgroundSync
63
+ self.maintenanceIntervalMs = maintenanceIntervalMs
64
+ self.debugKey = debugKey
65
+ self.requestTimeoutMs = requestTimeoutMs
66
+ self.maxPendingEvents = maxPendingEvents
67
+ self.syncIntervalMs = syncIntervalMs
68
+ self.maintenanceBackoffMs = maintenanceBackoffMs
69
+ self.retentionBytes = retentionBytes
70
+ self.onUsage = onUsage
71
+ self.onDebugEvent = onDebugEvent
72
+ self.debugVisibility = debugVisibility
73
+ self.attestation = attestation
74
+ self.projectDirectory = projectDirectory
75
+ self.http = http
76
+ }
77
+ func hostJSON() -> JSON {
78
+ var host: JSON = .object(["projectKey": .string(projectKey)])
79
+ if let cloudUrl { host["cloudUrl"] = .string(cloudUrl) }
80
+ if let debugKey { host["debugKey"] = .string(debugKey) }
81
+ if let debugVisibility { host["debugVisibility"] = .string(debugVisibility.rawValue) }
82
+ if let requestTimeoutMs { host["requestTimeoutMs"] = .number(requestTimeoutMs) }
83
+ if let maxPendingEvents { host["maxPendingEvents"] = .number(Double(maxPendingEvents)) }
84
+ if let syncIntervalMs { host["syncIntervalMs"] = .number(syncIntervalMs) }
85
+ if let maintenanceBackoffMs { host["maintenanceBackoffMs"] = .number(maintenanceBackoffMs) }
86
+ if let retentionBytes { host["retentionBytes"] = .number(Double(retentionBytes)) }
87
+ return host
88
+ }
89
+ func resolvedLanguage(preferredLanguages: [String] = Locale.preferredLanguages) -> String? {
90
+ language ?? preferredLanguages.first
91
+ }
92
+ func native() throws -> NativeProjectOptions {
93
+ do { _ = try hostJSON().encoded(); _ = try config.encoded() }
94
+ catch { throw CrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
95
+ let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
96
+ let directory = try NativeProjectFiles.directory(projectDirectory: projectDirectory)
97
+ var identity = hostJSON(); identity["user"] = user.map(JSON.string) ?? .null
98
+ let namespace = try CrocheRuntime.identity(config: identity)["storageKey"].string ?? "croche.runtime"
99
+ let zone: TimeZone?
100
+ if let timeZone {
101
+ guard let parsed = TimeZone(identifier: timeZone) else { throw CrocheError("invalid_configuration", "timeZone must name an IANA time zone") }
102
+ zone = parsed
103
+ } else { zone = nil }
104
+ let attestor: (any RuntimeAttestor)?
105
+ #if canImport(DeviceCheck) && os(iOS) && !targetEnvironment(simulator)
106
+ attestor = attestation == .off ? nil : AppAttestAttestor()
107
+ #else
108
+ attestor = nil
109
+ #endif
110
+ let test = NativeProjectFiles.testing
111
+ return NativeProjectOptions(host: hostJSON(), config: config, user: user,
112
+ language: resolvedLanguage(), handlers: handlers, streaming: streaming ?? true,
113
+ backgroundSync: backgroundSync ?? true, maintenanceIntervalMs: maintenanceIntervalMs ?? 60_000,
114
+ storage: { slot in FileRuntimeStorage(url: NativeProjectFiles.file(directory: directory, namespace: namespace, slot: slot)) },
115
+ secretStorage: { slot in
116
+ let key = NativeProjectFiles.key(namespace: namespace, slot: slot)
117
+ if let test { return FileRuntimeSecretStore(url: test.appendingPathComponent(key + ".secrets")) }
118
+ #if canImport(Security) && !os(Linux)
119
+ return KeychainSecretStore(account: key)
120
+ #else
121
+ return FileRuntimeSecretStore(url: directory.appendingPathComponent(key + ".secrets"))
122
+ #endif
123
+ }, attestor: attestor, fetch: http, timeZone: zone,
124
+ records: { test.map { dir in ProjectRecordFiles(directory: { dir }) } ?? records },
125
+ onUsage: onUsage, onDebugEvent: onDebugEvent)
126
+ }
127
+ }
128
+
129
+ // Test-only redirection keeps host gates inside their own worktree, out of Keychain/private app storage.
130
+ enum NativeProjectFiles {
131
+ nonisolated(unsafe) static var testing: URL?
132
+ static func directory(projectDirectory: URL?) throws -> URL {
133
+ if let testing { return testing }
134
+ #if os(Linux)
135
+ guard let projectDirectory else { throw CrocheError("storage_error", "This platform requires projectDirectory") }
136
+ return projectDirectory
137
+ #else
138
+ let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
139
+ let url = base.appendingPathComponent("croche", isDirectory: true)
140
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
141
+ var excluded = url, values = URLResourceValues(); values.isExcludedFromBackup = true
142
+ try? excluded.setResourceValues(values)
143
+ return url
144
+ #endif
145
+ }
146
+ static func file(directory: URL, namespace: String, slot: String) -> URL {
147
+ directory.appendingPathComponent(key(namespace: namespace, slot: slot) + ".json")
148
+ }
149
+ static func key(namespace: String, slot: String) -> String {
150
+ namespace + ".agent." + slotHash(slot)
151
+ }
152
+ static func slotHash(_ slot: String) -> String {
153
+ #if canImport(CryptoKit)
154
+ SHA256.hash(data: Data(slot.utf8)).map { String(format: "%02x", $0) }.joined()
155
+ #else
156
+ PortableSHA256.hex(Array(slot.utf8))
157
+ #endif
158
+ }
159
+ }
160
+
161
+ // Core's maintenance label selects the instance's physical store, never its live handle.
162
+ enum NativeProjectSlot {
163
+ static func isMaintenance(_ label: String) -> Bool {
164
+ (try? JSON(label).array?.first?.string) == "$gc"
165
+ }
166
+ static func storageLabel(_ label: String) -> String {
167
+ guard let parts = try? JSON(label).array, parts.count == 3,
168
+ parts[0].string == "$gc", parts[1].string != nil, parts[2].string != nil else { return label }
169
+ let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
170
+ return String(decoding: try! encoder.encode(JSON.array(Array(parts.dropFirst()))), as: UTF8.self)
171
+ }
172
+ }
@@ -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
+ }