@bendyline/gezel-capacitor 0.0.0-stage → 1.0.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 (121) hide show
  1. package/LICENSE +21 -0
  2. package/Package.swift +26 -0
  3. package/README.md +230 -2
  4. package/android/build.gradle +30 -0
  5. package/android/src/main/AndroidManifest.xml +1 -0
  6. package/android/src/main/java/com/bendyline/gezel/capacitor/GezelKnowledgePlugin.java +153 -0
  7. package/android/src/main/java/com/bendyline/gezel/capacitor/GezelOfflineSpeechPlugin.java +216 -0
  8. package/android/src/main/java/com/bendyline/gezel/capacitor/GezelRuntimePlugin.java +84 -0
  9. package/android/src/main/java/com/bendyline/gezel/capacitor/KnowledgeFiles.java +101 -0
  10. package/android/src/main/java/com/bendyline/gezel/capacitor/SpeechModels.java +230 -0
  11. package/android/src/main/java/com/bendyline/gezel/speech/SpeechRuntime.java +38 -0
  12. package/dist/index.d.ts +561 -0
  13. package/dist/index.js +7512 -0
  14. package/dist/knowledge-worker.js +211 -0
  15. package/dist/licenses/npm/manifest.json +76 -0
  16. package/dist/licenses/npm/texts/1583809bf1155510d2961f94aa9bca6dc4b44b6f59fd773de33bd6c20860d781.txt +29 -0
  17. package/dist/licenses/npm/texts/1cd39aa4a566eba49eb206b969ef423295e79b50503df567bbdb2e8877d78892.txt +8 -0
  18. package/dist/licenses/npm/texts/3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8.txt +21 -0
  19. package/dist/licenses/npm/texts/5b37224c080cdcc97c871ada971c224e9926370fe74f11b539aa1cf9f3b1aca1.txt +21 -0
  20. package/dist/licenses/npm/texts/c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4.txt +201 -0
  21. package/dist/sqlite3.wasm +0 -0
  22. package/embedding-manifest.json +210 -0
  23. package/ios/Sources/GezelCapacitor/GezelKnowledgePlugin.swift +200 -0
  24. package/ios/Sources/GezelCapacitor/GezelOfflineSpeechPlugin.swift +484 -0
  25. package/ios/Sources/GezelCapacitor/GezelRuntimePlugin.swift +102 -0
  26. package/kokoro-lexicon/LICENSE +202 -0
  27. package/kokoro-lexicon/lexicon-gb-en.txt.gz +0 -0
  28. package/kokoro-lexicon/lexicon-us-en.txt.gz +0 -0
  29. package/native/android/LICENSE-gezel.txt +21 -0
  30. package/native/android/PUBLIC-DISTRIBUTION.md +97 -0
  31. package/native/android/THIRD_PARTY_LICENSES/LICENSE-arm-optimized-routines-MIT-OR-Apache-2.0.txt +249 -0
  32. package/native/android/THIRD_PARTY_LICENSES/LICENSE-cpp-httplib-MIT.txt +22 -0
  33. package/native/android/THIRD_PARTY_LICENSES/LICENSE-fp16-MIT.txt +11 -0
  34. package/native/android/THIRD_PARTY_LICENSES/LICENSE-ggml-MIT.txt +21 -0
  35. package/native/android/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-llamafile-sgemm-MIT.txt +21 -0
  36. package/native/android/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-openvino-APACHE.txt +201 -0
  37. package/native/android/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-pillow-MIT-CMU.txt +30 -0
  38. package/native/android/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-rotate-bits-MIT.txt +21 -0
  39. package/native/android/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-unicode-data-Unicode-3.0.txt +39 -0
  40. package/native/android/THIRD_PARTY_LICENSES/LICENSE-nlohmann-json-MIT.txt +21 -0
  41. package/native/android/THIRD_PARTY_LICENSES/LICENSE-nvidia-cub-BSD-3-Clause.txt +24 -0
  42. package/native/android/THIRD_PARTY_LICENSES/LICENSE-vulkan-headers-Apache-2.0-OR-MIT.txt +33 -0
  43. package/native/android/THIRD_PARTY_LICENSES/LICENSE-vulkan-loader-APACHE.txt +201 -0
  44. package/native/android/THIRD_PARTY_LICENSES/LICENSE-vulkan-loader-cjson-MIT.txt +32 -0
  45. package/native/android/THIRD_PARTY_LICENSES/LICENSE-yarn-MIT.txt +21 -0
  46. package/native/android/THIRD_PARTY_LICENSES/manifest.json +21 -0
  47. package/native/android/engine-manifest.json +88 -0
  48. package/native/android/maven/com/bendyline/gezel/gezel-llama/0.1.57/gezel-llama-0.1.57.aar +0 -0
  49. package/native/android/maven/com/bendyline/gezel/gezel-llama/0.1.57/gezel-llama-0.1.57.aar.sha256 +1 -0
  50. package/native/android/maven/com/bendyline/gezel/gezel-llama/0.1.57/gezel-llama-0.1.57.pom +8 -0
  51. package/native/android/maven/com/bendyline/gezel/gezel-llama/0.1.57/gezel-llama-0.1.57.pom.sha256 +1 -0
  52. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57-sources.jar +0 -0
  53. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57-sources.jar.md5 +1 -0
  54. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57-sources.jar.sha1 +1 -0
  55. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57-sources.jar.sha256 +1 -0
  56. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57-sources.jar.sha512 +1 -0
  57. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.aar +0 -0
  58. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.aar.md5 +1 -0
  59. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.aar.sha1 +1 -0
  60. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.aar.sha256 +1 -0
  61. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.aar.sha512 +1 -0
  62. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.module +118 -0
  63. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.module.md5 +1 -0
  64. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.module.sha1 +1 -0
  65. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.module.sha256 +1 -0
  66. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.module.sha512 +1 -0
  67. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.pom +51 -0
  68. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.pom.md5 +1 -0
  69. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.pom.sha1 +1 -0
  70. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.pom.sha256 +1 -0
  71. package/native/android/maven/com/bendyline/gezel/gezel-runtime/0.1.57/gezel-runtime-0.1.57.pom.sha512 +1 -0
  72. package/native/android/maven/com/bendyline/gezel/gezel-runtime/maven-metadata.xml +13 -0
  73. package/native/android/maven/com/bendyline/gezel/gezel-runtime/maven-metadata.xml.md5 +1 -0
  74. package/native/android/maven/com/bendyline/gezel/gezel-runtime/maven-metadata.xml.sha1 +1 -0
  75. package/native/android/maven/com/bendyline/gezel/gezel-runtime/maven-metadata.xml.sha256 +1 -0
  76. package/native/android/maven/com/bendyline/gezel/gezel-runtime/maven-metadata.xml.sha512 +1 -0
  77. package/native/android/sdk-manifest.json +98 -0
  78. package/native/ios/GezelLlama.xcframework/Info.plist +47 -0
  79. package/native/ios/GezelLlama.xcframework/ios-arm64/Headers/gezel_llama.h +290 -0
  80. package/native/ios/GezelLlama.xcframework/ios-arm64/Headers/module.modulemap +9 -0
  81. package/native/ios/GezelLlama.xcframework/ios-arm64/libGezelLlama.a +0 -0
  82. package/native/ios/GezelLlama.xcframework/ios-arm64-simulator/Headers/gezel_llama.h +290 -0
  83. package/native/ios/GezelLlama.xcframework/ios-arm64-simulator/Headers/module.modulemap +9 -0
  84. package/native/ios/GezelLlama.xcframework/ios-arm64-simulator/libGezelLlama.a +0 -0
  85. package/native/ios/LICENSE-gezel.txt +21 -0
  86. package/native/ios/LICENSE-ggml.txt +21 -0
  87. package/native/ios/LICENSE-llama-cpp.txt +21 -0
  88. package/native/ios/PUBLIC-DISTRIBUTION.md +97 -0
  89. package/native/ios/Package.swift +17 -0
  90. package/native/ios/Sources/GezelModelStorage/MobileModelStore.swift +286 -0
  91. package/native/ios/Sources/GezelModelStorage/ModelDownloadHTTP.swift +55 -0
  92. package/native/ios/Sources/GezelModelStorage/ModelDownloadSource.swift +46 -0
  93. package/native/ios/Sources/GezelModelStorage/ModelDownloads.swift +289 -0
  94. package/native/ios/Sources/GezelModelStorage/PrivacyInfo.xcprivacy +32 -0
  95. package/native/ios/Sources/GezelRuntime/AppleFoundationProvider.swift +292 -0
  96. package/native/ios/Sources/GezelRuntime/AppleNativeTools.swift +152 -0
  97. package/native/ios/Sources/GezelRuntime/GezelNativeRuntime.swift +1349 -0
  98. package/native/ios/Sources/GezelRuntime/NativeCall.swift +35 -0
  99. package/native/ios/Sources/GezelRuntime/PrivacyInfo.xcprivacy +31 -0
  100. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-arm-optimized-routines-MIT-OR-Apache-2.0.txt +249 -0
  101. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-cpp-httplib-MIT.txt +22 -0
  102. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-fp16-MIT.txt +11 -0
  103. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-ggml-MIT.txt +21 -0
  104. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-llamafile-sgemm-MIT.txt +21 -0
  105. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-openvino-APACHE.txt +201 -0
  106. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-pillow-MIT-CMU.txt +30 -0
  107. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-rotate-bits-MIT.txt +21 -0
  108. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-llama-cpp-unicode-data-Unicode-3.0.txt +39 -0
  109. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-nlohmann-json-MIT.txt +21 -0
  110. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-nvidia-cub-BSD-3-Clause.txt +24 -0
  111. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-vulkan-headers-Apache-2.0-OR-MIT.txt +33 -0
  112. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-vulkan-loader-APACHE.txt +201 -0
  113. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-vulkan-loader-cjson-MIT.txt +32 -0
  114. package/native/ios/THIRD_PARTY_LICENSES/LICENSE-yarn-MIT.txt +21 -0
  115. package/native/ios/THIRD_PARTY_LICENSES/manifest.json +21 -0
  116. package/native/ios/engine-manifest.json +102 -0
  117. package/native/ios/sdk-manifest.json +89 -0
  118. package/package.json +94 -3
  119. package/scripts/embedding-package.d.mts +23 -0
  120. package/scripts/embedding-package.mjs +185 -0
  121. package/scripts/stage-native.mjs +168 -0
@@ -0,0 +1,97 @@
1
+ # Public mobile SDK distribution
2
+
3
+ Reviewed 2026-10-04 against the sources linked below. These packages are reusable
4
+ libraries for Gezel and other developers' apps. Publishing the SDK does not
5
+ publish a consuming app's source, store listing, provisioning profile, or keys.
6
+ It does publish Gezel's included Swift/Java runtime sources and native libraries.
7
+
8
+ ## Contents and integration
9
+
10
+ `gezel-mobile-<version>-ios.tar.gz` contains a local Swift package: the shared
11
+ Apple Foundation Models adapter, model storage, and a static llama.cpp
12
+ XCFramework with device and simulator slices. Extract it and add the folder as
13
+ a package dependency in Xcode. Keep both Swift targets' privacy resource bundles.
14
+ Apple's framework and model weights are supplied by the OS, not redistributed
15
+ in this package. Availability still depends on device, OS and Apple Intelligence
16
+ readiness.
17
+
18
+ `gezel-mobile-<version>-android.tar.gz` contains a folder Maven repository.
19
+ Add its `maven/` folder as a repository and depend on
20
+ `com.bendyline.gezel:gezel-runtime:<version>`. Retain the POM and Gradle module
21
+ metadata: they resolve `gezel-llama` from the same repository and ML Kit / Kotlin
22
+ dependencies from Google's Maven repository and Maven Central. This includes
23
+ the `android-mlkit` adapter, not Gemini Nano weights or a repackaged Google SDK.
24
+ The published native engine currently targets arm64-v8a.
25
+
26
+ These packages exclude Gezel's web app, Capacitor, speech packs, test models,
27
+ APKs, AABs and Xcode app archives. They contain a file inventory, source commit,
28
+ engine provenance and license notices. Native release `SHA256SUMS` and build
29
+ attestations cover them alongside the desktop archives. Verify those against
30
+ the trusted release before using the SDK; its internal inventory alone is not
31
+ an authenticity guarantee.
32
+
33
+ ## Signing and store submissions
34
+
35
+ The mobile SDKs are **unsigned libraries**. No signing secrets are passed to
36
+ the mobile workflow. Desktop Developer ID / Authenticode signing remains a
37
+ separate operation on desktop executables. Each consuming developer builds and
38
+ signs their own app using their own team, bundle ID and store credentials.
39
+ Android libraries use AARs; app signing applies to the resulting app package.
40
+ See [Android library distribution](https://developer.android.com/studio/projects/android-library)
41
+ and [Android app signing](https://developer.android.com/studio/publish/app-signing).
42
+
43
+ Apple explicitly supports public binary framework distribution through Swift
44
+ packages. An SDK producer signature, when used, establishes origin and update
45
+ continuity; it does not require sharing the producer's private key or using
46
+ that identity to sign the consuming app. See
47
+ [Apple's binary package distribution guide](https://developer.apple.com/documentation/xcode/distributing-binary-frameworks-as-swift-packages)
48
+ and [SDK signature requirements](https://developer.apple.com/support/third-party-SDK-requirements/).
49
+
50
+ Gezel and llama.cpp are not on Apple's current required-signature SDK list.
51
+ Capacitor is listed, but is a separate dependency and is not bundled here.
52
+ Consumers must preserve its applicable privacy/signature requirements; adding
53
+ or repackaging another listed SDK requires revisiting the release policy.
54
+
55
+ Both Swift targets include `PrivacyInfo.xcprivacy`. The runtime declares local
56
+ model-file metadata and elapsed-time measurement (including the linked llama
57
+ engine). Model storage declares metadata for sandbox/user-selected files and
58
+ free-space checks before imports/downloads. No tracking or collected data is
59
+ declared by these iOS libraries. The embedding app remains responsible for its
60
+ own behavior, other SDKs, privacy labels and final archive validation. See
61
+ [required-reason API declarations](https://developer.apple.com/documentation/bundleresources/describing-use-of-required-reason-api)
62
+ and [approved reasons](https://developer.apple.com/documentation/bundleresources/app-privacy-configuration/nsprivacyaccessedapitypes/nsprivacyaccessedapitypereasons).
63
+
64
+ ## License and provider terms
65
+
66
+ Gezel, llama.cpp and ggml use MIT licenses, whose notices are included. MIT
67
+ permits public redistribution and use within proprietary apps while preserving
68
+ its notices. `THIRD_PARTY_LICENSES/` preserves the shared, commit-bound llama.cpp
69
+ notice inventory, including JSON, Unicode and optimized math dependencies.
70
+ That conservative inventory also names optional desktop backends; it does not
71
+ mean those backends are included in mobile builds. Android engine AARs carry the NDK and toolchain notices for
72
+ their bundled runtime libraries. An app's own source need not become public
73
+ because it uses these SDKs. Model weights have separate licenses and are not
74
+ included. The repository LICENSE and the package's LICENSE/NOTICE files are the
75
+ authoritative grants; this guide does not replace them. Preserve these notices
76
+ in the consuming app's third-party acknowledgements, including the texts outside
77
+ the Swift package resources / Android AARs.
78
+
79
+ Using ML Kit requires compliance with Google's API and ML Kit terms. The current
80
+ [GenAI additional terms](https://developers.google.com/ml-kit/genai-terms)
81
+ restrict clients directed at or likely accessed by people under 18, restrict
82
+ competing model/API products and model extraction, and prohibit production use
83
+ of services designated Preview/Experimental or similarly. Review the exact
84
+ Prompt API designation and intended app before a production release; a beta
85
+ dependency version alone is not a store approval. Safety and permitted-use
86
+ restrictions also apply. A general-audience app must resolve the age restriction
87
+ before enabling this adapter in production.
88
+
89
+ ML Kit processes inputs on-device but sends performance/utilization metrics to
90
+ Google; consumers must inform their users as required. Retain the dependency's
91
+ licenses and account for this behavior in the app's disclosures. See
92
+ [ML Kit Terms & Privacy](https://developers.google.com/ml-kit/terms).
93
+
94
+ Public SDK hosting is compatible with proprietary store apps; it is not blanket
95
+ App Store / Play approval or an exemption from provider terms. The coordinated
96
+ native workflow creates a draft. Store signing, device/provider qualification,
97
+ app submission and publication remain separate release decisions.
@@ -0,0 +1,17 @@
1
+ // swift-tools-version: 6.0
2
+ import PackageDescription
3
+ let package = Package(
4
+ name: "GezelRuntime",
5
+ platforms: [.iOS("16.4")],
6
+ products: [
7
+ .library(name: "GezelRuntime", targets: ["GezelRuntime"]),
8
+ .library(name: "GezelModelStorage", targets: ["GezelModelStorage"])
9
+ ],
10
+ targets: [
11
+ .binaryTarget(name: "GezelLlama", path: "GezelLlama.xcframework"),
12
+ .target(name: "GezelModelStorage", resources: [.copy("PrivacyInfo.xcprivacy")]),
13
+ .target(name: "GezelRuntime", dependencies: ["GezelLlama", "GezelModelStorage"],
14
+ resources: [.copy("PrivacyInfo.xcprivacy")])
15
+ ],
16
+ swiftLanguageModes: [.v5]
17
+ )
@@ -0,0 +1,286 @@
1
+ import Foundation
2
+
3
+ public struct MobileModel: Codable, Equatable, Sendable {
4
+ public let id: String
5
+ public let name: String
6
+ public let sizeBytes: Int64
7
+ public var source: MobileModelSource? = nil
8
+ }
9
+
10
+ public struct MobileModelLibrary: Codable, Equatable, Sendable {
11
+ public var models: [MobileModel]
12
+ public var selectedModelId: String?
13
+ }
14
+
15
+ public enum MobileStoreError: LocalizedError {
16
+ case invalidState, stateTooLarge, invalidModel, unknownModel, invalidLibrary, libraryFull, insufficientDisk
17
+
18
+ public var errorDescription: String? {
19
+ switch self {
20
+ case .invalidState: return "The saved conversation must be valid JSON."
21
+ case .stateTooLarge: return "The saved conversation exceeds the 16 MB limit."
22
+ case .invalidModel: return "Choose a GGUF model file."
23
+ case .unknownModel: return "This model is no longer available. Import it again."
24
+ case .invalidLibrary: return "The saved model library is invalid."
25
+ case .libraryFull: return "The model library is full. Remove a model before importing another."
26
+ case .insufficientDisk: return "There is not enough free space to copy this model."
27
+ }
28
+ }
29
+ }
30
+
31
+ /// Owns the app container's model inventory and copied models. Callers only exchange
32
+ /// opaque model IDs; no renderer-supplied path is ever resolved below this root.
33
+ open class MobileModelStore: @unchecked Sendable {
34
+ public static let maximumStateBytes = 16 * 1024 * 1024
35
+ public static let maximumModelBytes: Int64 = 4 * 1024 * 1024 * 1024
36
+ private static let maximumLibraryBytes = 1024 * 1024
37
+ private let root: URL
38
+ private let modelsRoot: URL
39
+ private let lock = NSRecursiveLock()
40
+ private let fm = FileManager.default
41
+
42
+ /// The OS may alias the app container's parent (/var on Apple platforms).
43
+ /// Resolve that parent, then check the storage boundary before following it.
44
+ public static func validatedRoot(_ root: URL) throws -> URL {
45
+ guard root.isFileURL, !root.lastPathComponent.isEmpty else { throw MobileStoreError.invalidModel }
46
+ let parent = root.deletingLastPathComponent().resolvingSymlinksInPath().standardizedFileURL
47
+ let resolved = parent.appendingPathComponent(root.lastPathComponent, isDirectory: true)
48
+ try requireUnaliased(resolved)
49
+ return resolved
50
+ }
51
+
52
+ private static func requireUnaliased(_ directory: URL) throws {
53
+ // destinationOfSymbolicLink also detects dangling links, unlike fileExists.
54
+ guard (try? FileManager.default.destinationOfSymbolicLink(atPath: directory.path)) == nil else {
55
+ throw MobileStoreError.invalidModel
56
+ }
57
+ }
58
+
59
+ public init(root: URL, recoverModels: Bool = true) throws {
60
+ self.root = try Self.validatedRoot(root)
61
+ self.modelsRoot = self.root.appendingPathComponent("models", isDirectory: true)
62
+ try Self.requireUnaliased(modelsRoot)
63
+ try fm.createDirectory(at: modelsRoot, withIntermediateDirectories: true)
64
+ var modelDirectory = modelsRoot
65
+ var values = URLResourceValues()
66
+ values.isExcludedFromBackup = true
67
+ try modelDirectory.setResourceValues(values)
68
+ // Product storage adapters may coexist with an already-running host.
69
+ guard recoverModels else { return }
70
+ // A killed import can leave only an unpublished temporary copy.
71
+ for file in try fm.contentsOfDirectory(at: modelsRoot, includingPropertiesForKeys: nil)
72
+ where file.pathExtension == "partial" {
73
+ try? fm.removeItem(at: file)
74
+ }
75
+ // A removal first renames its file, then atomically changes inventory.
76
+ // Restore or discard the tombstone based on which commit survived.
77
+ if let library = try? readLibrary() {
78
+ for file in try fm.contentsOfDirectory(at: modelsRoot, includingPropertiesForKeys: nil)
79
+ where file.pathExtension == "deleting" {
80
+ let id = file.deletingPathExtension().lastPathComponent
81
+ guard Self.canonicalID(id) else { continue }
82
+ if library.models.contains(where: { $0.id == id }) {
83
+ let original = modelsRoot.appendingPathComponent("\(id).gguf")
84
+ if !fm.fileExists(atPath: original.path) { try fm.moveItem(at: file, to: original) }
85
+ } else { try? fm.removeItem(at: file) }
86
+ }
87
+ }
88
+ }
89
+
90
+ private static func canonicalID(_ id: String) -> Bool {
91
+ UUID(uuidString: id)?.uuidString.lowercased() == id
92
+ }
93
+
94
+ private func synchronized<T>(_ body: () throws -> T) rethrows -> T {
95
+ lock.lock()
96
+ defer { lock.unlock() }
97
+ return try body()
98
+ }
99
+
100
+ public func downloadsDirectory() throws -> URL {
101
+ try synchronized {
102
+ let folder = root.appendingPathComponent("model-downloads", isDirectory: true)
103
+ try Self.requireUnaliased(folder)
104
+ try fm.createDirectory(at: folder, withIntermediateDirectories: true)
105
+ guard try folder.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { throw MobileStoreError.invalidModel }
106
+ var target = folder; var attributes = URLResourceValues(); attributes.isExcludedFromBackup = true
107
+ try target.setResourceValues(attributes)
108
+ return folder
109
+ }
110
+ }
111
+ public func downloadModelURL(id: String) throws -> URL {
112
+ guard Self.canonicalID(id) else { throw MobileStoreError.invalidModel }
113
+ return modelsRoot.appendingPathComponent("\(id).gguf")
114
+ }
115
+ /// The manager hashes the confined source before calling this atomic publication boundary.
116
+ public func publishDownloadedModel(id: String, name: String, source: MobileModelSource, file: URL) throws -> MobileModel {
117
+ try synchronized {
118
+ try source.validate(exact: true)
119
+ var library = try readLibrary()
120
+ if let existing = library.models.first(where: { $0.id == id }) {
121
+ guard existing.source == source else { throw MobileStoreError.invalidModel }
122
+ _ = try checkedModelURL(existing)
123
+ return existing
124
+ }
125
+ guard library.models.count < 100 else { throw MobileStoreError.libraryFull }
126
+ guard !name.isEmpty, name.utf16.count <= 200, !name.contains("\0") else { throw MobileStoreError.invalidModel }
127
+ let target = try downloadModelURL(id: id)
128
+ let partial = try downloadsDirectory().appendingPathComponent(id).appendingPathComponent("model.part")
129
+ guard file == target || file == partial else { throw MobileStoreError.invalidModel }
130
+ let values = try file.resourceValues(forKeys: [.fileSizeKey,.isRegularFileKey,.isSymbolicLinkKey])
131
+ guard values.isRegularFile == true, values.isSymbolicLink != true, Int64(values.fileSize ?? 0) == source.sizeBytes else { throw MobileStoreError.invalidModel }
132
+ let input = try FileHandle(forReadingFrom: file); defer { try? input.close() }
133
+ guard try input.read(upToCount: 4) == Data("GGUF".utf8) else { throw MobileStoreError.invalidModel }
134
+ let model = MobileModel(id: id, name: name, sizeBytes: source.sizeBytes!, source: source)
135
+ if file != target { try fm.moveItem(at: file, to: target) }
136
+ library.models.append(model)
137
+ // A surviving file before the inventory commit is rehashed by the
138
+ // durable download id on resume. It is never selected implicitly.
139
+ try writeLibrary(library)
140
+ return model
141
+ }
142
+ }
143
+
144
+ public func listModels() throws -> MobileModelLibrary {
145
+ try synchronized { try readLibrary() }
146
+ }
147
+
148
+ public func selectModel(id: String) throws -> MobileModel {
149
+ try synchronized {
150
+ var library = try readLibrary()
151
+ guard let model = library.models.first(where: { $0.id == id }) else { throw MobileStoreError.unknownModel }
152
+ _ = try checkedModelURL(model)
153
+ library.selectedModelId = id
154
+ try writeLibrary(library)
155
+ return model
156
+ }
157
+ }
158
+
159
+ public func modelURL(id: String) throws -> (MobileModel, URL) {
160
+ try synchronized {
161
+ guard let model = try readLibrary().models.first(where: { $0.id == id }) else {
162
+ throw MobileStoreError.unknownModel
163
+ }
164
+ return (model, try checkedModelURL(model))
165
+ }
166
+ }
167
+
168
+ public func selectedModelURL() throws -> (MobileModel, URL) {
169
+ try synchronized {
170
+ let library = try readLibrary()
171
+ guard let model = library.models.first(where: { $0.id == library.selectedModelId }) else {
172
+ throw MobileStoreError.unknownModel
173
+ }
174
+ return (model, try checkedModelURL(model))
175
+ }
176
+ }
177
+
178
+ /// The caller obtains the URL from the native document picker, and owns
179
+ /// its security-scoped access for this synchronous copy's duration.
180
+ public func importModel(from source: URL) throws -> MobileModel {
181
+ try synchronized {
182
+ guard source.pathExtension.lowercased() == "gguf" else { throw MobileStoreError.invalidModel }
183
+ var library = try readLibrary()
184
+ guard library.models.count < 100 else { throw MobileStoreError.libraryFull }
185
+ let values = try source.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey, .isSymbolicLinkKey])
186
+ let sourceSize = Int64(values.fileSize ?? 0)
187
+ guard values.isRegularFile == true, values.isSymbolicLink != true,
188
+ (4...Self.maximumModelBytes).contains(sourceSize) else { throw MobileStoreError.invalidModel }
189
+ let available = try fm.attributesOfFileSystem(forPath: modelsRoot.path)[.systemFreeSize] as? NSNumber
190
+ guard let available, available.int64Value >= sourceSize + 64 * 1024 * 1024 else { throw MobileStoreError.insufficientDisk }
191
+ let file = try FileHandle(forReadingFrom: source)
192
+ defer { try? file.close() }
193
+ let magic = try file.read(upToCount: 4)
194
+ guard magic == Data("GGUF".utf8) else { throw MobileStoreError.invalidModel }
195
+ let id = UUID().uuidString.lowercased()
196
+ let partial = modelsRoot.appendingPathComponent("\(id).partial")
197
+ let target = modelsRoot.appendingPathComponent("\(id).gguf")
198
+ defer { try? fm.removeItem(at: partial) }
199
+ guard fm.createFile(atPath: partial.path, contents: nil) else { throw MobileStoreError.insufficientDisk }
200
+ let output = try FileHandle(forWritingTo: partial)
201
+ defer { try? output.close() }
202
+ try output.write(contentsOf: magic!)
203
+ var bytes: Int64 = 4
204
+ while let chunk = try file.read(upToCount: 1024 * 1024), !chunk.isEmpty {
205
+ bytes += Int64(chunk.count)
206
+ guard bytes <= Self.maximumModelBytes, bytes <= sourceSize else { throw MobileStoreError.invalidModel }
207
+ try output.write(contentsOf: chunk)
208
+ }
209
+ guard bytes == sourceSize else { throw MobileStoreError.invalidModel }
210
+ try output.synchronize()
211
+ try output.close()
212
+ let model = MobileModel(id: id, name: String(decoding: source.lastPathComponent.utf16.prefix(200), as: UTF16.self), sizeBytes: bytes)
213
+ library.models.append(model)
214
+ if library.models.count == 1 { library.selectedModelId = id }
215
+ try fm.moveItem(at: partial, to: target)
216
+ do { try writeLibrary(library) }
217
+ catch {
218
+ try? fm.removeItem(at: target)
219
+ throw error
220
+ }
221
+ return model
222
+ }
223
+ }
224
+
225
+ public func removeModel(id: String) throws {
226
+ try synchronized {
227
+ var library = try readLibrary()
228
+ guard let index = library.models.firstIndex(where: { $0.id == id }) else { throw MobileStoreError.unknownModel }
229
+ let original = modelsRoot.appendingPathComponent("\(id).gguf")
230
+ let tombstone = modelsRoot.appendingPathComponent("\(id).deleting")
231
+ let exists = (try? original.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]))
232
+ if let exists {
233
+ guard exists.isRegularFile == true || exists.isSymbolicLink == true else { throw MobileStoreError.invalidModel }
234
+ try fm.moveItem(at: original, to: tombstone)
235
+ }
236
+ library.models.remove(at: index)
237
+ if library.selectedModelId == id { library.selectedModelId = nil }
238
+ do { try writeLibrary(library) }
239
+ catch {
240
+ if exists != nil { try? fm.moveItem(at: tombstone, to: original) }
241
+ throw error
242
+ }
243
+ // Inventory is already committed; an interrupted/unavailable delete
244
+ // is finished on next startup without resurrecting a removed model.
245
+ if exists != nil { try? fm.removeItem(at: tombstone) }
246
+ }
247
+ }
248
+
249
+ private func validateLibrary(_ library: MobileModelLibrary) throws {
250
+ guard library.models.count <= 100,
251
+ Set(library.models.map(\.id)).count == library.models.count,
252
+ library.models.allSatisfy({ Self.canonicalID($0.id) && !$0.name.isEmpty && $0.name.utf16.count <= 200 && !$0.name.contains("\0") && (4...Self.maximumModelBytes).contains($0.sizeBytes) }),
253
+ library.selectedModelId == nil || library.models.contains(where: { $0.id == library.selectedModelId })
254
+ else { throw MobileStoreError.invalidLibrary }
255
+ for model in library.models { if let source = model.source { try source.validate(exact: true); guard source.sizeBytes == model.sizeBytes else { throw MobileStoreError.invalidLibrary } } }
256
+ }
257
+
258
+ private func readLibrary() throws -> MobileModelLibrary {
259
+ let file = root.appendingPathComponent("models.json")
260
+ guard fm.fileExists(atPath: file.path) else { return MobileModelLibrary(models: [], selectedModelId: nil) }
261
+ let handle = try FileHandle(forReadingFrom: file)
262
+ defer { try? handle.close() }
263
+ guard try handle.seekToEnd() <= Self.maximumLibraryBytes else { throw MobileStoreError.invalidLibrary }
264
+ try handle.seek(toOffset: 0)
265
+ let data = try handle.read(upToCount: Self.maximumLibraryBytes + 1) ?? Data()
266
+ guard data.count <= Self.maximumLibraryBytes else { throw MobileStoreError.invalidLibrary }
267
+ let library = try JSONDecoder().decode(MobileModelLibrary.self, from: data)
268
+ try validateLibrary(library)
269
+ return library
270
+ }
271
+
272
+ private func writeLibrary(_ library: MobileModelLibrary) throws {
273
+ try validateLibrary(library)
274
+ let data = try JSONEncoder().encode(library)
275
+ guard data.count <= Self.maximumLibraryBytes else { throw MobileStoreError.invalidLibrary }
276
+ try data.write(to: root.appendingPathComponent("models.json"), options: .atomic)
277
+ }
278
+
279
+ private func checkedModelURL(_ model: MobileModel) throws -> URL {
280
+ guard Self.canonicalID(model.id) else { throw MobileStoreError.invalidLibrary }
281
+ let url = modelsRoot.appendingPathComponent("\(model.id).gguf")
282
+ let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
283
+ guard values.isRegularFile == true, values.isSymbolicLink != true, Int64(values.fileSize ?? 0) == model.sizeBytes else { throw MobileStoreError.unknownModel }
284
+ return url
285
+ }
286
+ }
@@ -0,0 +1,55 @@
1
+ import Foundation
2
+
3
+ /// Bounded redirect policy; URLSession retains ordinary system TLS validation.
4
+ final class ModelDownloadHTTP: NSObject, URLSessionDataDelegate, @unchecked Sendable {
5
+ typealias Headers = @Sendable (HTTPURLResponse) throws -> Void
6
+ typealias Chunk = @Sendable (Data) throws -> Void
7
+ typealias Completion = @Sendable (Error?) -> Void
8
+ private let headers: Headers
9
+ private let chunk: Chunk
10
+ private let completion: Completion
11
+ private var failure: Error?
12
+ private var redirects = 0
13
+ private var session: URLSession?
14
+ private var task: URLSessionDataTask?
15
+ init(url: URL, method: String, fields: [String:String], configuration: URLSessionConfiguration,
16
+ queue: DispatchQueue, headers: @escaping Headers, chunk: @escaping Chunk, completion: @escaping Completion) throws {
17
+ try MobileModelSource.validateURL(url)
18
+ self.headers = headers; self.chunk = chunk; self.completion = completion
19
+ super.init()
20
+ let operations = OperationQueue(); operations.maxConcurrentOperationCount = 1; operations.underlyingQueue = queue
21
+ let configuration = configuration.copy() as! URLSessionConfiguration
22
+ configuration.urlCache = nil; configuration.httpCookieStorage = nil; configuration.urlCredentialStorage = nil; configuration.httpShouldSetCookies = false
23
+ configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
24
+ configuration.timeoutIntervalForRequest = 30; configuration.timeoutIntervalForResource = 24 * 60 * 60
25
+ session = URLSession(configuration: configuration, delegate: self, delegateQueue: operations)
26
+ var request = URLRequest(url: url); request.httpMethod = method
27
+ request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
28
+ fields.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }
29
+ task = session!.dataTask(with: request)
30
+ }
31
+ func start() { task?.resume() }
32
+ func cancel() { task?.cancel() }
33
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
34
+ newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
35
+ do {
36
+ guard let url = request.url, redirects < 5 else { throw ModelDownloadError("Model source redirected too many times") }
37
+ try MobileModelSource.validateURL(url); redirects += 1
38
+ completionHandler(request)
39
+ } catch { failure = error; completionHandler(nil); task.cancel() }
40
+ }
41
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
42
+ completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
43
+ do {
44
+ guard let response = response as? HTTPURLResponse else { throw ModelDownloadError("Invalid model source response") }
45
+ try headers(response); completionHandler(.allow)
46
+ } catch { failure = error; completionHandler(.cancel) }
47
+ }
48
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
49
+ do { try chunk(data) } catch { failure = error; dataTask.cancel() }
50
+ }
51
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
52
+ completion(failure ?? error)
53
+ session.invalidateAndCancel(); self.session = nil; self.task = nil
54
+ }
55
+ }
@@ -0,0 +1,46 @@
1
+ import Foundation
2
+
3
+ public struct MobileModelSource: Codable, Equatable, Sendable {
4
+ public var catalogId: String
5
+ public var catalogVersion: String
6
+ public var sourceId: String
7
+ public var huggingfaceRepo: String
8
+ public var revision: String
9
+ public var filename: String
10
+ public var sha256: String
11
+ public var sizeBytes: Int64?
12
+
13
+ public func validate(exact: Bool) throws {
14
+ let fields = [(catalogId,160),(catalogVersion,80),(sourceId,160),(huggingfaceRepo,200),(filename,400)]
15
+ guard fields.allSatisfy({ !$0.0.isEmpty && $0.0.utf16.count <= $0.1 && !$0.0.unicodeScalars.contains(where: { $0.value < 32 || $0.value == 127 }) }),
16
+ huggingfaceRepo.range(of: "^[A-Za-z0-9_-][A-Za-z0-9_.-]*/[A-Za-z0-9_-][A-Za-z0-9_.-]*$", options: .regularExpression) != nil,
17
+ revision.range(of: "^[a-f0-9]{40}$", options: .regularExpression) != nil,
18
+ sha256.range(of: "^[a-f0-9]{64}$", options: .regularExpression) != nil,
19
+ filename.hasSuffix(".gguf"), !filename.contains("\\"),
20
+ filename.components(separatedBy: "/").allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else {
21
+ throw ModelDownloadError("A catalog model must pin a repository, immutable revision, GGUF filename and SHA-256")
22
+ }
23
+ if exact {
24
+ guard let sizeBytes, (4...MobileModelStore.maximumModelBytes).contains(sizeBytes) else { throw ModelDownloadError("An exact model length between 4 bytes and 4 GiB is required") }
25
+ }
26
+ }
27
+ public func url() throws -> URL {
28
+ try validate(exact: false)
29
+ let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))
30
+ let path = filename.components(separatedBy: "/").map { $0.addingPercentEncoding(withAllowedCharacters: allowed)! }.joined(separator: "/")
31
+ guard let result = URL(string: "https://huggingface.co/\(huggingfaceRepo)/resolve/\(revision)/\(path)") else { throw ModelDownloadError("Invalid model source") }
32
+ return result
33
+ }
34
+ static func validateURL(_ url: URL) throws {
35
+ guard url.scheme == "https", url.user == nil, url.password == nil, url.fragment == nil,
36
+ url.port == nil || url.port == 443, let host = url.host,
37
+ host == "huggingface.co" || host.hasSuffix(".huggingface.co") || host == "hf.co" || host.hasSuffix(".hf.co") else {
38
+ throw ModelDownloadError("Model download redirected outside its trusted HTTPS source")
39
+ }
40
+ }
41
+ }
42
+ public struct ModelDownloadError: LocalizedError, Sendable {
43
+ public let message: String
44
+ public init(_ message: String) { self.message = message }
45
+ public var errorDescription: String? { message }
46
+ }