@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.
- package/LICENSE +32 -0
- package/README.md +486 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/android/build.gradle +47 -0
- package/android/src/main/AndroidManifest.xml +8 -0
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +837 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +32 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +415 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +379 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +227 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -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/croche-react-native.podspec +28 -0
- package/ios/CrocheRuntimeBridge.swift +1008 -0
- package/ios/RNCrocheRuntime.mm +221 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +215 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +562 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
- package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +558 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +453 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +345 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
- package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
- 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 +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +40 -4
- package/scripts/vendor-native.sh +56 -0
- package/src/NativeCrocheRuntime.ts +162 -0
- package/src/index.ts +660 -0
- package/src/project-types.ts +35 -0
- package/src/project.ts +434 -0
- package/src/protocol.ts +28 -0
- 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,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
|
+
}
|