cactus-react-native 1.0.1 → 1.1.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 (128) hide show
  1. package/README.md +609 -56
  2. package/android/src/main/java/com/margelo/nitro/cactus/HybridCactusCrypto.kt +23 -15
  3. package/android/src/main/java/com/margelo/nitro/cactus/HybridCactusDeviceInfo.kt +12 -9
  4. package/android/src/main/java/com/margelo/nitro/cactus/HybridCactusFileSystem.kt +42 -41
  5. package/android/src/main/java/com/margelo/nitro/cactus/HybridCactusImage.kt +81 -0
  6. package/android/src/main/jniLibs/arm64-v8a/libcactus.a +0 -0
  7. package/cpp/HybridCactus.cpp +161 -44
  8. package/cpp/HybridCactus.hpp +34 -14
  9. package/cpp/HybridCactusUtil.cpp +13 -11
  10. package/cpp/HybridCactusUtil.hpp +9 -9
  11. package/cpp/cactus_ffi.h +28 -1
  12. package/ios/HybridCactusImage.swift +53 -0
  13. package/ios/cactus.xcframework/ios-arm64/cactus.framework/Headers/cactus_ffi.h +28 -1
  14. package/ios/cactus.xcframework/ios-arm64/cactus.framework/Headers/engine.h +237 -7
  15. package/ios/cactus.xcframework/ios-arm64/cactus.framework/Headers/ffi_utils.h +158 -43
  16. package/ios/cactus.xcframework/ios-arm64/cactus.framework/Headers/graph.h +23 -2
  17. package/ios/cactus.xcframework/ios-arm64/cactus.framework/Headers/kernel.h +52 -0
  18. package/ios/cactus.xcframework/ios-arm64/cactus.framework/cactus +0 -0
  19. package/ios/cactus.xcframework/ios-arm64-simulator/cactus.framework/Headers/cactus_ffi.h +28 -1
  20. package/ios/cactus.xcframework/ios-arm64-simulator/cactus.framework/Headers/engine.h +237 -7
  21. package/ios/cactus.xcframework/ios-arm64-simulator/cactus.framework/Headers/ffi_utils.h +158 -43
  22. package/ios/cactus.xcframework/ios-arm64-simulator/cactus.framework/Headers/graph.h +23 -2
  23. package/ios/cactus.xcframework/ios-arm64-simulator/cactus.framework/Headers/kernel.h +52 -0
  24. package/ios/cactus.xcframework/ios-arm64-simulator/cactus.framework/cactus +0 -0
  25. package/lib/module/api/Database.js +23 -0
  26. package/lib/module/api/Database.js.map +1 -1
  27. package/lib/module/api/RemoteLM.js +201 -0
  28. package/lib/module/api/RemoteLM.js.map +1 -0
  29. package/lib/module/classes/CactusLM.js +56 -28
  30. package/lib/module/classes/CactusLM.js.map +1 -1
  31. package/lib/module/classes/CactusSTT.js +137 -0
  32. package/lib/module/classes/CactusSTT.js.map +1 -0
  33. package/lib/module/config/CactusConfig.js +4 -0
  34. package/lib/module/config/CactusConfig.js.map +1 -1
  35. package/lib/module/constants/packageVersion.js +1 -1
  36. package/lib/module/hooks/useCactusLM.js +44 -16
  37. package/lib/module/hooks/useCactusLM.js.map +1 -1
  38. package/lib/module/hooks/useCactusSTT.js +234 -0
  39. package/lib/module/hooks/useCactusSTT.js.map +1 -0
  40. package/lib/module/index.js +2 -0
  41. package/lib/module/index.js.map +1 -1
  42. package/lib/module/native/Cactus.js +52 -3
  43. package/lib/module/native/Cactus.js.map +1 -1
  44. package/lib/module/native/CactusFileSystem.js +2 -3
  45. package/lib/module/native/CactusFileSystem.js.map +1 -1
  46. package/lib/module/native/CactusImage.js +13 -0
  47. package/lib/module/native/CactusImage.js.map +1 -0
  48. package/lib/module/native/index.js +1 -0
  49. package/lib/module/native/index.js.map +1 -1
  50. package/lib/module/specs/CactusImage.nitro.js +4 -0
  51. package/lib/module/specs/CactusImage.nitro.js.map +1 -0
  52. package/lib/module/telemetry/Telemetry.js +53 -1
  53. package/lib/module/telemetry/Telemetry.js.map +1 -1
  54. package/lib/module/types/CactusSTT.js +2 -0
  55. package/lib/module/types/CactusSTT.js.map +1 -0
  56. package/lib/typescript/src/api/Database.d.ts +1 -0
  57. package/lib/typescript/src/api/Database.d.ts.map +1 -1
  58. package/lib/typescript/src/api/RemoteLM.d.ts +14 -0
  59. package/lib/typescript/src/api/RemoteLM.d.ts.map +1 -0
  60. package/lib/typescript/src/classes/CactusLM.d.ts +8 -5
  61. package/lib/typescript/src/classes/CactusLM.d.ts.map +1 -1
  62. package/lib/typescript/src/classes/CactusSTT.d.ts +25 -0
  63. package/lib/typescript/src/classes/CactusSTT.d.ts.map +1 -0
  64. package/lib/typescript/src/config/CactusConfig.d.ts +1 -0
  65. package/lib/typescript/src/config/CactusConfig.d.ts.map +1 -1
  66. package/lib/typescript/src/constants/packageVersion.d.ts +1 -1
  67. package/lib/typescript/src/hooks/useCactusLM.d.ts +5 -4
  68. package/lib/typescript/src/hooks/useCactusLM.d.ts.map +1 -1
  69. package/lib/typescript/src/hooks/useCactusSTT.d.ts +20 -0
  70. package/lib/typescript/src/hooks/useCactusSTT.d.ts.map +1 -0
  71. package/lib/typescript/src/index.d.ts +4 -1
  72. package/lib/typescript/src/index.d.ts.map +1 -1
  73. package/lib/typescript/src/native/Cactus.d.ts +10 -3
  74. package/lib/typescript/src/native/Cactus.d.ts.map +1 -1
  75. package/lib/typescript/src/native/CactusFileSystem.d.ts +1 -1
  76. package/lib/typescript/src/native/CactusFileSystem.d.ts.map +1 -1
  77. package/lib/typescript/src/native/CactusImage.d.ts +6 -0
  78. package/lib/typescript/src/native/CactusImage.d.ts.map +1 -0
  79. package/lib/typescript/src/native/index.d.ts +1 -0
  80. package/lib/typescript/src/native/index.d.ts.map +1 -1
  81. package/lib/typescript/src/specs/Cactus.nitro.d.ts +4 -1
  82. package/lib/typescript/src/specs/Cactus.nitro.d.ts.map +1 -1
  83. package/lib/typescript/src/specs/CactusImage.nitro.d.ts +9 -0
  84. package/lib/typescript/src/specs/CactusImage.nitro.d.ts.map +1 -0
  85. package/lib/typescript/src/telemetry/Telemetry.d.ts +5 -1
  86. package/lib/typescript/src/telemetry/Telemetry.d.ts.map +1 -1
  87. package/lib/typescript/src/types/CactusLM.d.ts +11 -6
  88. package/lib/typescript/src/types/CactusLM.d.ts.map +1 -1
  89. package/lib/typescript/src/types/CactusSTT.d.ts +37 -0
  90. package/lib/typescript/src/types/CactusSTT.d.ts.map +1 -0
  91. package/nitro.json +4 -0
  92. package/nitrogen/generated/android/c++/JHybridCactusImageSpec.cpp +81 -0
  93. package/nitrogen/generated/android/c++/JHybridCactusImageSpec.hpp +66 -0
  94. package/nitrogen/generated/android/cactus+autolinking.cmake +2 -0
  95. package/nitrogen/generated/android/cactusOnLoad.cpp +10 -0
  96. package/nitrogen/generated/android/kotlin/com/margelo/nitro/cactus/HybridCactusImageSpec.kt +62 -0
  97. package/nitrogen/generated/ios/Cactus-Swift-Cxx-Bridge.cpp +17 -0
  98. package/nitrogen/generated/ios/Cactus-Swift-Cxx-Bridge.hpp +17 -0
  99. package/nitrogen/generated/ios/Cactus-Swift-Cxx-Umbrella.hpp +5 -0
  100. package/nitrogen/generated/ios/CactusAutolinking.mm +8 -0
  101. package/nitrogen/generated/ios/CactusAutolinking.swift +15 -0
  102. package/nitrogen/generated/ios/c++/HybridCactusImageSpecSwift.cpp +11 -0
  103. package/nitrogen/generated/ios/c++/HybridCactusImageSpecSwift.hpp +85 -0
  104. package/nitrogen/generated/ios/swift/HybridCactusImageSpec.swift +58 -0
  105. package/nitrogen/generated/ios/swift/HybridCactusImageSpec_cxx.swift +158 -0
  106. package/nitrogen/generated/shared/c++/HybridCactusImageSpec.cpp +22 -0
  107. package/nitrogen/generated/shared/c++/HybridCactusImageSpec.hpp +64 -0
  108. package/nitrogen/generated/shared/c++/HybridCactusSpec.cpp +3 -0
  109. package/nitrogen/generated/shared/c++/HybridCactusSpec.hpp +4 -1
  110. package/package.json +1 -1
  111. package/src/api/Database.ts +27 -0
  112. package/src/api/RemoteLM.ts +273 -0
  113. package/src/classes/CactusLM.ts +76 -40
  114. package/src/classes/CactusSTT.ts +182 -0
  115. package/src/config/CactusConfig.ts +4 -0
  116. package/src/constants/packageVersion.ts +1 -1
  117. package/src/hooks/useCactusLM.ts +53 -22
  118. package/src/hooks/useCactusSTT.ts +285 -0
  119. package/src/index.tsx +14 -2
  120. package/src/native/Cactus.ts +100 -6
  121. package/src/native/CactusFileSystem.ts +2 -2
  122. package/src/native/CactusImage.ts +20 -0
  123. package/src/native/index.ts +1 -0
  124. package/src/specs/Cactus.nitro.ts +14 -1
  125. package/src/specs/CactusImage.nitro.ts +12 -0
  126. package/src/telemetry/Telemetry.ts +78 -1
  127. package/src/types/CactusLM.ts +12 -6
  128. package/src/types/CactusSTT.ts +42 -0
@@ -0,0 +1,58 @@
1
+ ///
2
+ /// HybridCactusImageSpec.swift
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © 2025 Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ import Foundation
9
+ import NitroModules
10
+ import NitroModules
11
+
12
+ /// See ``HybridCactusImageSpec``
13
+ public protocol HybridCactusImageSpec_protocol: HybridObject {
14
+ // Properties
15
+
16
+
17
+ // Methods
18
+ func base64(path: String) throws -> Promise<String>
19
+ func resize(path: String, height: Double, width: Double, quality: Double) throws -> Promise<String>
20
+ }
21
+
22
+ public extension HybridCactusImageSpec_protocol {
23
+ /// Default implementation of ``HybridObject.toString``
24
+ func toString() -> String {
25
+ return "[HybridObject CactusImage]"
26
+ }
27
+ }
28
+
29
+ /// See ``HybridCactusImageSpec``
30
+ open class HybridCactusImageSpec_base {
31
+ private weak var cxxWrapper: HybridCactusImageSpec_cxx? = nil
32
+ public init() { }
33
+ public func getCxxWrapper() -> HybridCactusImageSpec_cxx {
34
+ #if DEBUG
35
+ guard self is HybridCactusImageSpec else {
36
+ fatalError("`self` is not a `HybridCactusImageSpec`! Did you accidentally inherit from `HybridCactusImageSpec_base` instead of `HybridCactusImageSpec`?")
37
+ }
38
+ #endif
39
+ if let cxxWrapper = self.cxxWrapper {
40
+ return cxxWrapper
41
+ } else {
42
+ let cxxWrapper = HybridCactusImageSpec_cxx(self as! HybridCactusImageSpec)
43
+ self.cxxWrapper = cxxWrapper
44
+ return cxxWrapper
45
+ }
46
+ }
47
+ }
48
+
49
+ /**
50
+ * A Swift base-protocol representing the CactusImage HybridObject.
51
+ * Implement this protocol to create Swift-based instances of CactusImage.
52
+ * ```swift
53
+ * class HybridCactusImage : HybridCactusImageSpec {
54
+ * // ...
55
+ * }
56
+ * ```
57
+ */
58
+ public typealias HybridCactusImageSpec = HybridCactusImageSpec_protocol & HybridCactusImageSpec_base
@@ -0,0 +1,158 @@
1
+ ///
2
+ /// HybridCactusImageSpec_cxx.swift
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © 2025 Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ import Foundation
9
+ import NitroModules
10
+ import NitroModules
11
+
12
+ /**
13
+ * A class implementation that bridges HybridCactusImageSpec over to C++.
14
+ * In C++, we cannot use Swift protocols - so we need to wrap it in a class to make it strongly defined.
15
+ *
16
+ * Also, some Swift types need to be bridged with special handling:
17
+ * - Enums need to be wrapped in Structs, otherwise they cannot be accessed bi-directionally (Swift bug: https://github.com/swiftlang/swift/issues/75330)
18
+ * - Other HybridObjects need to be wrapped/unwrapped from the Swift TCxx wrapper
19
+ * - Throwing methods need to be wrapped with a Result<T, Error> type, as exceptions cannot be propagated to C++
20
+ */
21
+ open class HybridCactusImageSpec_cxx {
22
+ /**
23
+ * The Swift <> C++ bridge's namespace (`margelo::nitro::cactus::bridge::swift`)
24
+ * from `Cactus-Swift-Cxx-Bridge.hpp`.
25
+ * This contains specialized C++ templates, and C++ helper functions that can be accessed from Swift.
26
+ */
27
+ public typealias bridge = margelo.nitro.cactus.bridge.swift
28
+
29
+ /**
30
+ * Holds an instance of the `HybridCactusImageSpec` Swift protocol.
31
+ */
32
+ private var __implementation: any HybridCactusImageSpec
33
+
34
+ /**
35
+ * Holds a weak pointer to the C++ class that wraps the Swift class.
36
+ */
37
+ private var __cxxPart: bridge.std__weak_ptr_HybridCactusImageSpec_
38
+
39
+ /**
40
+ * Create a new `HybridCactusImageSpec_cxx` that wraps the given `HybridCactusImageSpec`.
41
+ * All properties and methods bridge to C++ types.
42
+ */
43
+ public init(_ implementation: any HybridCactusImageSpec) {
44
+ self.__implementation = implementation
45
+ self.__cxxPart = .init()
46
+ /* no base class */
47
+ }
48
+
49
+ /**
50
+ * Get the actual `HybridCactusImageSpec` instance this class wraps.
51
+ */
52
+ @inline(__always)
53
+ public func getHybridCactusImageSpec() -> any HybridCactusImageSpec {
54
+ return __implementation
55
+ }
56
+
57
+ /**
58
+ * Casts this instance to a retained unsafe raw pointer.
59
+ * This acquires one additional strong reference on the object!
60
+ */
61
+ public func toUnsafe() -> UnsafeMutableRawPointer {
62
+ return Unmanaged.passRetained(self).toOpaque()
63
+ }
64
+
65
+ /**
66
+ * Casts an unsafe pointer to a `HybridCactusImageSpec_cxx`.
67
+ * The pointer has to be a retained opaque `Unmanaged<HybridCactusImageSpec_cxx>`.
68
+ * This removes one strong reference from the object!
69
+ */
70
+ public class func fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> HybridCactusImageSpec_cxx {
71
+ return Unmanaged<HybridCactusImageSpec_cxx>.fromOpaque(pointer).takeRetainedValue()
72
+ }
73
+
74
+ /**
75
+ * Gets (or creates) the C++ part of this Hybrid Object.
76
+ * The C++ part is a `std::shared_ptr<HybridCactusImageSpec>`.
77
+ */
78
+ public func getCxxPart() -> bridge.std__shared_ptr_HybridCactusImageSpec_ {
79
+ let cachedCxxPart = self.__cxxPart.lock()
80
+ if Bool(fromCxx: cachedCxxPart) {
81
+ return cachedCxxPart
82
+ } else {
83
+ let newCxxPart = bridge.create_std__shared_ptr_HybridCactusImageSpec_(self.toUnsafe())
84
+ __cxxPart = bridge.weakify_std__shared_ptr_HybridCactusImageSpec_(newCxxPart)
85
+ return newCxxPart
86
+ }
87
+ }
88
+
89
+
90
+
91
+ /**
92
+ * Get the memory size of the Swift class (plus size of any other allocations)
93
+ * so the JS VM can properly track it and garbage-collect the JS object if needed.
94
+ */
95
+ @inline(__always)
96
+ public var memorySize: Int {
97
+ return MemoryHelper.getSizeOf(self.__implementation) + self.__implementation.memorySize
98
+ }
99
+
100
+ /**
101
+ * Call dispose() on the Swift class.
102
+ * This _may_ be called manually from JS.
103
+ */
104
+ @inline(__always)
105
+ public func dispose() {
106
+ self.__implementation.dispose()
107
+ }
108
+
109
+ /**
110
+ * Call toString() on the Swift class.
111
+ */
112
+ @inline(__always)
113
+ public func toString() -> String {
114
+ return self.__implementation.toString()
115
+ }
116
+
117
+ // Properties
118
+
119
+
120
+ // Methods
121
+ @inline(__always)
122
+ public final func base64(path: std.string) -> bridge.Result_std__shared_ptr_Promise_std__string___ {
123
+ do {
124
+ let __result = try self.__implementation.base64(path: String(path))
125
+ let __resultCpp = { () -> bridge.std__shared_ptr_Promise_std__string__ in
126
+ let __promise = bridge.create_std__shared_ptr_Promise_std__string__()
127
+ let __promiseHolder = bridge.wrap_std__shared_ptr_Promise_std__string__(__promise)
128
+ __result
129
+ .then({ __result in __promiseHolder.resolve(std.string(__result)) })
130
+ .catch({ __error in __promiseHolder.reject(__error.toCpp()) })
131
+ return __promise
132
+ }()
133
+ return bridge.create_Result_std__shared_ptr_Promise_std__string___(__resultCpp)
134
+ } catch (let __error) {
135
+ let __exceptionPtr = __error.toCpp()
136
+ return bridge.create_Result_std__shared_ptr_Promise_std__string___(__exceptionPtr)
137
+ }
138
+ }
139
+
140
+ @inline(__always)
141
+ public final func resize(path: std.string, height: Double, width: Double, quality: Double) -> bridge.Result_std__shared_ptr_Promise_std__string___ {
142
+ do {
143
+ let __result = try self.__implementation.resize(path: String(path), height: height, width: width, quality: quality)
144
+ let __resultCpp = { () -> bridge.std__shared_ptr_Promise_std__string__ in
145
+ let __promise = bridge.create_std__shared_ptr_Promise_std__string__()
146
+ let __promiseHolder = bridge.wrap_std__shared_ptr_Promise_std__string__(__promise)
147
+ __result
148
+ .then({ __result in __promiseHolder.resolve(std.string(__result)) })
149
+ .catch({ __error in __promiseHolder.reject(__error.toCpp()) })
150
+ return __promise
151
+ }()
152
+ return bridge.create_Result_std__shared_ptr_Promise_std__string___(__resultCpp)
153
+ } catch (let __error) {
154
+ let __exceptionPtr = __error.toCpp()
155
+ return bridge.create_Result_std__shared_ptr_Promise_std__string___(__exceptionPtr)
156
+ }
157
+ }
158
+ }
@@ -0,0 +1,22 @@
1
+ ///
2
+ /// HybridCactusImageSpec.cpp
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © 2025 Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ #include "HybridCactusImageSpec.hpp"
9
+
10
+ namespace margelo::nitro::cactus {
11
+
12
+ void HybridCactusImageSpec::loadHybridMethods() {
13
+ // load base methods/properties
14
+ HybridObject::loadHybridMethods();
15
+ // load custom methods/properties
16
+ registerHybrids(this, [](Prototype& prototype) {
17
+ prototype.registerHybridMethod("base64", &HybridCactusImageSpec::base64);
18
+ prototype.registerHybridMethod("resize", &HybridCactusImageSpec::resize);
19
+ });
20
+ }
21
+
22
+ } // namespace margelo::nitro::cactus
@@ -0,0 +1,64 @@
1
+ ///
2
+ /// HybridCactusImageSpec.hpp
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © 2025 Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ #pragma once
9
+
10
+ #if __has_include(<NitroModules/HybridObject.hpp>)
11
+ #include <NitroModules/HybridObject.hpp>
12
+ #else
13
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
14
+ #endif
15
+
16
+
17
+
18
+ #include <string>
19
+ #include <NitroModules/Promise.hpp>
20
+
21
+ namespace margelo::nitro::cactus {
22
+
23
+ using namespace margelo::nitro;
24
+
25
+ /**
26
+ * An abstract base class for `CactusImage`
27
+ * Inherit this class to create instances of `HybridCactusImageSpec` in C++.
28
+ * You must explicitly call `HybridObject`'s constructor yourself, because it is virtual.
29
+ * @example
30
+ * ```cpp
31
+ * class HybridCactusImage: public HybridCactusImageSpec {
32
+ * public:
33
+ * HybridCactusImage(...): HybridObject(TAG) { ... }
34
+ * // ...
35
+ * };
36
+ * ```
37
+ */
38
+ class HybridCactusImageSpec: public virtual HybridObject {
39
+ public:
40
+ // Constructor
41
+ explicit HybridCactusImageSpec(): HybridObject(TAG) { }
42
+
43
+ // Destructor
44
+ ~HybridCactusImageSpec() override = default;
45
+
46
+ public:
47
+ // Properties
48
+
49
+
50
+ public:
51
+ // Methods
52
+ virtual std::shared_ptr<Promise<std::string>> base64(const std::string& path) = 0;
53
+ virtual std::shared_ptr<Promise<std::string>> resize(const std::string& path, double height, double width, double quality) = 0;
54
+
55
+ protected:
56
+ // Hybrid Setup
57
+ void loadHybridMethods() override;
58
+
59
+ protected:
60
+ // Tag for logging
61
+ static constexpr auto TAG = "CactusImage";
62
+ };
63
+
64
+ } // namespace margelo::nitro::cactus
@@ -16,7 +16,10 @@ namespace margelo::nitro::cactus {
16
16
  registerHybrids(this, [](Prototype& prototype) {
17
17
  prototype.registerHybridMethod("init", &HybridCactusSpec::init);
18
18
  prototype.registerHybridMethod("complete", &HybridCactusSpec::complete);
19
+ prototype.registerHybridMethod("transcribe", &HybridCactusSpec::transcribe);
19
20
  prototype.registerHybridMethod("embed", &HybridCactusSpec::embed);
21
+ prototype.registerHybridMethod("imageEmbed", &HybridCactusSpec::imageEmbed);
22
+ prototype.registerHybridMethod("audioEmbed", &HybridCactusSpec::audioEmbed);
20
23
  prototype.registerHybridMethod("reset", &HybridCactusSpec::reset);
21
24
  prototype.registerHybridMethod("stop", &HybridCactusSpec::stop);
22
25
  prototype.registerHybridMethod("destroy", &HybridCactusSpec::destroy);
@@ -52,9 +52,12 @@ namespace margelo::nitro::cactus {
52
52
 
53
53
  public:
54
54
  // Methods
55
- virtual std::shared_ptr<Promise<void>> init(const std::string& modelPath, double contextSize) = 0;
55
+ virtual std::shared_ptr<Promise<void>> init(const std::string& modelPath, double contextSize, const std::optional<std::string>& corpusDir) = 0;
56
56
  virtual std::shared_ptr<Promise<std::string>> complete(const std::string& messagesJson, double responseBufferSize, const std::optional<std::string>& optionsJson, const std::optional<std::string>& toolsJson, const std::optional<std::function<void(const std::string& /* token */, double /* tokenId */)>>& callback) = 0;
57
+ virtual std::shared_ptr<Promise<std::string>> transcribe(const std::string& audioFilePath, const std::string& prompt, double responseBufferSize, const std::optional<std::string>& optionsJson, const std::optional<std::function<void(const std::string& /* token */, double /* tokenId */)>>& callback) = 0;
57
58
  virtual std::shared_ptr<Promise<std::vector<double>>> embed(const std::string& text, double embeddingBufferSize) = 0;
59
+ virtual std::shared_ptr<Promise<std::vector<double>>> imageEmbed(const std::string& imagePath, double embeddingBufferSize) = 0;
60
+ virtual std::shared_ptr<Promise<std::vector<double>>> audioEmbed(const std::string& audioPath, double embeddingBufferSize) = 0;
58
61
  virtual std::shared_ptr<Promise<void>> reset() = 0;
59
62
  virtual std::shared_ptr<Promise<void>> stop() = 0;
60
63
  virtual std::shared_ptr<Promise<void>> destroy() = 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cactus-react-native",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "Run AI models locally on mobile devices",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -54,6 +54,33 @@ export class Database {
54
54
  return await CactusUtil.registerApp(await response.text());
55
55
  }
56
56
 
57
+ public static async getModel(slug: string): Promise<CactusModel> {
58
+ const response = await fetch(
59
+ `${this.url}/functions/v1/get-models?slug=${slug}&sdk_name=react&sdk_version=${packageVersion}`,
60
+ {
61
+ headers: { apikey: this.key, Authorization: `Bearer ${this.key}` },
62
+ }
63
+ );
64
+
65
+ if (!response.ok) {
66
+ throw new Error('Getting model failed');
67
+ }
68
+
69
+ const model = (await response.json()) as CactusModelResponse;
70
+
71
+ return {
72
+ name: model.name,
73
+ slug: model.slug,
74
+ quantization: model.quantization,
75
+ sizeMb: model.size_mb,
76
+ downloadUrl: model.download_url,
77
+ supportsToolCalling: model.supports_tool_calling,
78
+ supportsVision: model.supports_vision,
79
+ createdAt: model.created_at,
80
+ isDownloaded: false,
81
+ };
82
+ }
83
+
57
84
  public static async getModels(): Promise<CactusModel[]> {
58
85
  const response = await fetch(
59
86
  `${this.url}/functions/v1/get-models?sdk_name=react&sdk_version=${packageVersion}`,
@@ -0,0 +1,273 @@
1
+ import { CactusConfig } from '../config/CactusConfig';
2
+ import { CactusImage } from '../native/CactusImage';
3
+ import type {
4
+ CactusLMCompleteResult,
5
+ Message,
6
+ CompleteOptions,
7
+ Tool,
8
+ } from '../types/CactusLM';
9
+
10
+ export class RemoteLM {
11
+ private static readonly completionsUrl =
12
+ 'https://openrouter.ai/api/v1/chat/completions';
13
+
14
+ private static readonly defaultModel = 'google/gemini-2.5-flash-lite';
15
+
16
+ public static async complete(
17
+ messages: Message[],
18
+ options?: CompleteOptions,
19
+ tools?: { type: 'function'; function: Tool }[],
20
+ callback?: (token: string) => void
21
+ ): Promise<CactusLMCompleteResult> {
22
+ if (!CactusConfig.cactusToken) {
23
+ throw new Error('cactusToken is required for hybrid completions');
24
+ }
25
+
26
+ const payload = JSON.stringify({
27
+ model: this.defaultModel,
28
+ messages: await this.transformMessages(messages),
29
+ tools,
30
+ temperature: options?.temperature,
31
+ top_p: options?.topP,
32
+ top_k: options?.topK,
33
+ max_tokens: options?.maxTokens,
34
+ stop: options?.stopSequences,
35
+ stream: !!callback,
36
+ });
37
+
38
+ return callback
39
+ ? await this.streamXHR(payload, callback)
40
+ : await this.nonStreamFetch(payload);
41
+ }
42
+
43
+ private static getMimeType(filePath: string): string {
44
+ const extension = filePath.toLowerCase().split('.').pop();
45
+ switch (extension) {
46
+ case 'jpg':
47
+ case 'jpeg':
48
+ return 'image/jpeg';
49
+ case 'png':
50
+ return 'image/png';
51
+ case 'gif':
52
+ return 'image/gif';
53
+ case 'webp':
54
+ return 'image/webp';
55
+ default:
56
+ throw new Error(`Unsupported image format: .${extension}`);
57
+ }
58
+ }
59
+
60
+ private static async transformMessages(messages: Message[]) {
61
+ const transformedMessages = [];
62
+
63
+ for (const message of messages) {
64
+ const content: {
65
+ type: string;
66
+ text?: string;
67
+ image_url?: { url: string };
68
+ }[] = [];
69
+
70
+ if (message.content) {
71
+ content.push({
72
+ type: 'text',
73
+ text: message.content,
74
+ });
75
+ }
76
+
77
+ if (message.images) {
78
+ for (const image of message.images) {
79
+ const imagePath = image.replace('file://', '');
80
+ const mimeType = this.getMimeType(imagePath);
81
+ const base64Data = await CactusImage.base64(imagePath);
82
+
83
+ content.push({
84
+ type: 'image_url',
85
+ image_url: {
86
+ url: `data:${mimeType};base64,${base64Data}`,
87
+ },
88
+ });
89
+ }
90
+ }
91
+
92
+ transformedMessages.push({ role: message.role, content });
93
+ }
94
+
95
+ return transformedMessages;
96
+ }
97
+
98
+ private static streamXHR(
99
+ payload: string,
100
+ callback: (token: string) => void
101
+ ): Promise<CactusLMCompleteResult> {
102
+ return new Promise((resolve, reject) => {
103
+ const xhr = new XMLHttpRequest();
104
+
105
+ xhr.timeout = 3 * 60 * 1000; // 3 minutes
106
+ xhr.ontimeout = () =>
107
+ reject(new Error('Remote streaming completion timed out'));
108
+
109
+ xhr.open('POST', this.completionsUrl);
110
+ xhr.setRequestHeader(
111
+ 'Authorization',
112
+ `Bearer ${CactusConfig.cactusToken}`
113
+ );
114
+ xhr.setRequestHeader('HTTP-Referer', 'https://cactuscompute.com');
115
+ xhr.setRequestHeader('X-Title', 'Cactus React Native SDK');
116
+ xhr.setRequestHeader('Content-Type', 'application/json');
117
+
118
+ const startTime = performance.now();
119
+ let lastIndex = 0;
120
+ let buffer = '';
121
+ let response = '';
122
+ let toolCalls: { name: string; arguments: string }[] | undefined;
123
+ let timeToFirstTokenMs = 0;
124
+ let prefillTokens = 0;
125
+ let decodeTokens = 0;
126
+ let totalTokens = 0;
127
+
128
+ xhr.onprogress = () => {
129
+ const chunk = xhr.responseText.substring(lastIndex);
130
+ lastIndex = xhr.responseText.length;
131
+
132
+ buffer += chunk;
133
+
134
+ const lines = buffer.split('\n');
135
+ buffer = lines.pop() || '';
136
+
137
+ for (const line of lines) {
138
+ if (!line.startsWith('data: ')) {
139
+ continue;
140
+ }
141
+
142
+ const jsonStr = line.slice(6).trim();
143
+ if (jsonStr === '[DONE]') {
144
+ continue;
145
+ }
146
+
147
+ try {
148
+ const data = JSON.parse(jsonStr);
149
+
150
+ if (timeToFirstTokenMs === 0) {
151
+ timeToFirstTokenMs = performance.now() - startTime;
152
+ }
153
+
154
+ const toolCallChunks = data?.choices?.[0]?.delta?.tool_calls;
155
+ if (toolCallChunks) {
156
+ if (!toolCalls) {
157
+ toolCalls = [];
158
+ }
159
+
160
+ for (const toolCallChunk of toolCallChunks) {
161
+ const index = toolCallChunk.index;
162
+
163
+ if (!toolCalls[index]) {
164
+ toolCalls[index] = { name: '', arguments: '' };
165
+ }
166
+
167
+ if (toolCallChunk.function?.name) {
168
+ toolCalls[index].name = toolCallChunk.function.name;
169
+ }
170
+
171
+ if (toolCallChunk.function?.arguments) {
172
+ toolCalls[index].arguments +=
173
+ toolCallChunk.function.arguments;
174
+ }
175
+ }
176
+ }
177
+
178
+ const content = data?.choices?.[0]?.delta?.content;
179
+ if (content) {
180
+ response += content;
181
+ callback(content);
182
+ }
183
+
184
+ if (data?.usage) {
185
+ prefillTokens = data.usage.prompt_tokens;
186
+ decodeTokens = data.usage.completion_tokens;
187
+ totalTokens = data.usage.total_tokens;
188
+ }
189
+ } catch {}
190
+ }
191
+ };
192
+
193
+ xhr.onload = () => {
194
+ const totalTimeMs = performance.now() - startTime;
195
+ const functionCalls = toolCalls?.map((toolCall) => ({
196
+ name: toolCall.name,
197
+ arguments: JSON.parse(toolCall.arguments) as { [key: string]: any },
198
+ }));
199
+
200
+ resolve({
201
+ success: true,
202
+ response,
203
+ functionCalls,
204
+ timeToFirstTokenMs,
205
+ totalTimeMs,
206
+ tokensPerSecond: (decodeTokens * 1000) / totalTimeMs,
207
+ prefillTokens,
208
+ decodeTokens,
209
+ totalTokens,
210
+ });
211
+ };
212
+
213
+ xhr.onerror = () =>
214
+ reject(new Error('Remote streaming completion failed'));
215
+
216
+ xhr.send(payload);
217
+ });
218
+ }
219
+
220
+ private static async nonStreamFetch(
221
+ payload: string
222
+ ): Promise<CactusLMCompleteResult> {
223
+ const startTime = performance.now();
224
+
225
+ const request = await fetch(this.completionsUrl, {
226
+ method: 'POST',
227
+ headers: {
228
+ 'Authorization': `Bearer ${CactusConfig.cactusToken}`,
229
+ 'HTTP-Referer': 'https://cactuscompute.com',
230
+ 'X-Title': 'Cactus React Native SDK',
231
+ 'Content-Type': 'application/json',
232
+ },
233
+ body: payload,
234
+ });
235
+
236
+ if (!request.ok) {
237
+ throw new Error('Remote completion failed');
238
+ }
239
+
240
+ const data = await request.json();
241
+
242
+ const totalTimeMs = performance.now() - startTime;
243
+ const decodeTokens = data.usage.completion_tokens;
244
+
245
+ const toolCalls:
246
+ | {
247
+ function: {
248
+ name: string;
249
+ arguments: {
250
+ [key: string]: any;
251
+ };
252
+ };
253
+ }[]
254
+ | undefined = data.choices[0].message.tool_calls;
255
+
256
+ const functionCalls = toolCalls?.map((toolCall) => ({
257
+ name: toolCall.function.name,
258
+ arguments: toolCall.function.arguments,
259
+ }));
260
+
261
+ return {
262
+ success: true,
263
+ response: data.choices[0].message.content,
264
+ functionCalls,
265
+ timeToFirstTokenMs: totalTimeMs,
266
+ totalTimeMs,
267
+ tokensPerSecond: (decodeTokens * 1000) / totalTimeMs,
268
+ prefillTokens: data.usage.prompt_tokens,
269
+ decodeTokens,
270
+ totalTokens: data.usage.total_tokens,
271
+ };
272
+ }
273
+ }