catalyst-ai 0.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.
- package/README.md +30 -0
- package/android/.gradle/8.9/checksums/checksums.lock +0 -0
- package/android/.gradle/8.9/dependencies-accessors/gc.properties +0 -0
- package/android/.gradle/8.9/fileChanges/last-build.bin +0 -0
- package/android/.gradle/8.9/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/8.9/gc.properties +0 -0
- package/android/.gradle/9.2.0/checksums/checksums.lock +0 -0
- package/android/.gradle/9.2.0/fileChanges/last-build.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/9.2.0/gc.properties +0 -0
- package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
- package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
- package/android/.gradle/vcs-1/gc.properties +0 -0
- package/android/build.gradle.kts +47 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/io/catalyst/nativeai/AIBridge.kt +24 -0
- package/android/src/main/java/io/catalyst/nativeai/CatalystAIBridge.kt +79 -0
- package/android/src/main/java/io/catalyst/nativeai/NativeBridgeAI.kt +293 -0
- package/android/src/main/resources/META-INF/services/io.catalyst.nativeai.AIBridge +1 -0
- package/package.json +27 -0
- package/scripts/check-peer.js +11 -0
- package/src/buildAttachmentSystemPrompt.js +19 -0
- package/src/index.js +4 -0
- package/src/metrics.js +210 -0
- package/src/pricing.js +14 -0
- package/src/route.js +529 -0
- package/src/useCloudAI.js +315 -0
- package/src/useNativeAI.js +308 -0
- package/src/useWebAI.js +385 -0
package/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# catalyst-ai
|
|
2
|
+
|
|
3
|
+
Multi-provider AI integration for catalyst-core apps — OpenAI/Gemini SSE routes plus
|
|
4
|
+
`useCloudAI`, `useWebAI`, and `useNativeAI` React hooks.
|
|
5
|
+
|
|
6
|
+
## Security: authentication and rate limiting
|
|
7
|
+
|
|
8
|
+
The Express router exposed by this package (`src/route.js`, mounted at `AI_CONFIG.basePath`
|
|
9
|
+
— default `/ai` — by `catalyst-core`'s `expressServer.js`) does **not** implement its own
|
|
10
|
+
authentication, session checks, or rate limiting. It only gates requests on
|
|
11
|
+
`AI_CONFIG.enabled` and on a provider having a configured API key.
|
|
12
|
+
|
|
13
|
+
`catalyst-core` mounts app-defined middleware (`addMiddlewares` from `server/server.js`)
|
|
14
|
+
*before* this router, so any auth/session/rate-limit middleware your app registers via
|
|
15
|
+
`addMiddlewares` already applies to `/ai/*` routes. **If you expose these routes beyond a
|
|
16
|
+
trusted internal network, add authentication and per-caller rate limiting in your app's
|
|
17
|
+
`addMiddlewares` — the framework does not provide this for you.** Each request that reaches
|
|
18
|
+
`/ai/:provider/generate` or `/ai/:provider/stream` makes a real call to the configured
|
|
19
|
+
provider using your app's API key, so an unauthenticated deployment is an open proxy to
|
|
20
|
+
your provider account.
|
|
21
|
+
|
|
22
|
+
## `useWebAI` — remote script execution
|
|
23
|
+
|
|
24
|
+
`useWebAI` (the in-browser/Transformers.js provider) loads `@huggingface/transformers` from
|
|
25
|
+
a jsDelivr CDN URL at runtime inside a Web Worker, rather than bundling it as a dependency.
|
|
26
|
+
This is convenient for a zero-install experimental path but means the worker executes
|
|
27
|
+
third-party code fetched over the network at runtime. If your app has a Content-Security-Policy,
|
|
28
|
+
you'll need to allow `https://cdn.jsdelivr.net` for `worker-src`/`script-src`, or fork this
|
|
29
|
+
provider to bundle the library instead. Treat `useWebAI` as a demo/fallback path, not
|
|
30
|
+
production-ready, per the EXPERIMENTAL note in its source.
|
|
Binary file
|
|
File without changes
|
|
Binary file
|
|
Binary file
|
|
File without changes
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
File without changes
|
|
Binary file
|
|
File without changes
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
plugins {
|
|
2
|
+
id("com.android.library")
|
|
3
|
+
id("org.jetbrains.kotlin.android")
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
android {
|
|
7
|
+
namespace = "io.catalyst.nativeai"
|
|
8
|
+
compileSdk = 34
|
|
9
|
+
|
|
10
|
+
defaultConfig {
|
|
11
|
+
minSdk = 24
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
compileOptions {
|
|
15
|
+
sourceCompatibility = JavaVersion.VERSION_11
|
|
16
|
+
targetCompatibility = JavaVersion.VERSION_11
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
kotlinOptions {
|
|
20
|
+
jvmTarget = "11"
|
|
21
|
+
freeCompilerArgs += "-Xskip-metadata-version-check"
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
configurations.all {
|
|
28
|
+
resolutionStrategy.eachDependency {
|
|
29
|
+
if (requested.group == "org.jetbrains.kotlin" &&
|
|
30
|
+
(requested.name == "kotlin-stdlib" ||
|
|
31
|
+
requested.name == "kotlin-stdlib-jdk7" ||
|
|
32
|
+
requested.name == "kotlin-stdlib-jdk8" ||
|
|
33
|
+
requested.name == "kotlin-reflect")) {
|
|
34
|
+
useVersion("2.0.21")
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
dependencies {
|
|
40
|
+
// LiteRT-LM — on-device LLM inference
|
|
41
|
+
// Pinned: 0.14.0 introduced an OpenCL sampler regression (litertlm.cc OnError
|
|
42
|
+
// "Can not find OpenCL library" on first generate, even via Backend.CPU()).
|
|
43
|
+
implementation("com.google.ai.edge.litertlm:litertlm-android:0.13.1")
|
|
44
|
+
|
|
45
|
+
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
|
46
|
+
implementation("org.json:json:20231013")
|
|
47
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
package io.catalyst.nativeai
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.webkit.WebView
|
|
5
|
+
|
|
6
|
+
interface AIBridge {
|
|
7
|
+
fun attach(activity: Activity, webView: WebView, callbacks: AIBridgeCallbacks)
|
|
8
|
+
fun initAI(optionsRaw: String?)
|
|
9
|
+
fun generateNative(optionsRaw: String?)
|
|
10
|
+
fun clearConversation()
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Callbacks provided by the host app — decouples catalyst-ai from app internals. */
|
|
14
|
+
interface AIBridgeCallbacks {
|
|
15
|
+
fun onReady(streamUrl: String, port: Int, sessionId: String)
|
|
16
|
+
fun onProgress(phase: String, percent: Int, bytesLoaded: Long, bytesTotal: Long, detail: String)
|
|
17
|
+
fun onLog(message: String)
|
|
18
|
+
fun onError(message: String)
|
|
19
|
+
fun isFrameworkServerRunning(): Boolean
|
|
20
|
+
fun getFrameworkServerPort(): Int
|
|
21
|
+
fun getFrameworkServerSessionId(): String
|
|
22
|
+
fun setNativeAiSupplier(supplier: Any?)
|
|
23
|
+
fun setNativeSystemPrompt(prompt: String)
|
|
24
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
package io.catalyst.nativeai
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.webkit.WebView
|
|
5
|
+
import kotlinx.coroutines.CoroutineScope
|
|
6
|
+
import kotlinx.coroutines.Dispatchers
|
|
7
|
+
import kotlinx.coroutines.SupervisorJob
|
|
8
|
+
import kotlinx.coroutines.launch
|
|
9
|
+
import org.json.JSONObject
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* AIBridge implementation shipped by catalyst-ai.
|
|
13
|
+
* Self-registers via ServiceLoader — catalyst-core has zero knowledge of this class.
|
|
14
|
+
*
|
|
15
|
+
* ServiceLoader requires a no-arg constructor, so Activity/WebView/callbacks are injected
|
|
16
|
+
* lazily via attach() called from NativeBridge after ServiceLoader discovery.
|
|
17
|
+
*/
|
|
18
|
+
class CatalystAIBridge : AIBridge {
|
|
19
|
+
|
|
20
|
+
private var activity: Activity? = null
|
|
21
|
+
private var webView: WebView? = null
|
|
22
|
+
private var callbacks: AIBridgeCallbacks? = null
|
|
23
|
+
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
|
24
|
+
|
|
25
|
+
private var aiModule: NativeBridgeAI? = null
|
|
26
|
+
|
|
27
|
+
override fun attach(activity: Activity, webView: WebView, callbacks: AIBridgeCallbacks) {
|
|
28
|
+
this.activity = activity
|
|
29
|
+
this.webView = webView
|
|
30
|
+
this.callbacks = callbacks
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
override fun initAI(optionsRaw: String?) {
|
|
34
|
+
val act = activity ?: return
|
|
35
|
+
val cb = callbacks ?: return
|
|
36
|
+
|
|
37
|
+
if (!cb.isFrameworkServerRunning()) {
|
|
38
|
+
cb.onError("FrameworkServer not running — cannot expose AI stream")
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
val ai = aiModule ?: NativeBridgeAI(
|
|
43
|
+
context = act,
|
|
44
|
+
onLog = { msg -> cb.onLog(msg) },
|
|
45
|
+
onProgress = { phase, percent, bytesLoaded, bytesTotal, detail ->
|
|
46
|
+
cb.onProgress(phase, percent, bytesLoaded, bytesTotal, detail)
|
|
47
|
+
}
|
|
48
|
+
).also { aiModule = it }
|
|
49
|
+
|
|
50
|
+
scope.launch(Dispatchers.IO) {
|
|
51
|
+
when (val result = ai.init(optionsRaw)) {
|
|
52
|
+
is InitResult.AlreadyRunning -> { /* duplicate call, ignore */ }
|
|
53
|
+
is InitResult.Ready -> {
|
|
54
|
+
cb.setNativeAiSupplier(result.streamSupplier)
|
|
55
|
+
cb.setNativeSystemPrompt(result.systemPrompt)
|
|
56
|
+
|
|
57
|
+
val port = cb.getFrameworkServerPort()
|
|
58
|
+
val sessionId = cb.getFrameworkServerSessionId()
|
|
59
|
+
cb.onReady(
|
|
60
|
+
streamUrl = "http://localhost:$port/framework-$sessionId/ai/stream",
|
|
61
|
+
port = port,
|
|
62
|
+
sessionId = sessionId
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
is InitResult.Error -> {
|
|
66
|
+
cb.onError("Failed to load native AI model: ${result.cause.message}")
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
override fun generateNative(optionsRaw: String?) {
|
|
73
|
+
initAI(optionsRaw)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
override fun clearConversation() {
|
|
77
|
+
aiModule?.clearConversation()
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
package io.catalyst.nativeai
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.util.Log
|
|
5
|
+
import com.google.ai.edge.litertlm.Backend
|
|
6
|
+
import com.google.ai.edge.litertlm.Content
|
|
7
|
+
import com.google.ai.edge.litertlm.Conversation
|
|
8
|
+
import com.google.ai.edge.litertlm.ConversationConfig
|
|
9
|
+
import com.google.ai.edge.litertlm.Engine
|
|
10
|
+
import com.google.ai.edge.litertlm.EngineConfig
|
|
11
|
+
import kotlinx.coroutines.flow.Flow
|
|
12
|
+
import kotlinx.coroutines.flow.map
|
|
13
|
+
import org.json.JSONObject
|
|
14
|
+
import java.io.File
|
|
15
|
+
import java.net.HttpURLConnection
|
|
16
|
+
import java.net.URL
|
|
17
|
+
import java.util.UUID
|
|
18
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* All LiteRT-LM logic extracted from NativeBridge so catalyst-core has zero LiteRT imports.
|
|
22
|
+
*
|
|
23
|
+
* Usage (from the withAI source-set glue in the app):
|
|
24
|
+
* val ai = NativeBridgeAI(context, onLog, onProgress)
|
|
25
|
+
* ai.init(optionsJson) // downloads model + wires supplier
|
|
26
|
+
* FrameworkServerUtils.setNativeAiSupplier(ai::supply)
|
|
27
|
+
* FrameworkServerUtils.setNativeSystemPrompt(ai.systemPrompt)
|
|
28
|
+
*/
|
|
29
|
+
class NativeBridgeAI(
|
|
30
|
+
private val context: Context,
|
|
31
|
+
private val onLog: (String) -> Unit,
|
|
32
|
+
private val onProgress: (phase: String, percent: Int, bytesLoaded: Long, bytesTotal: Long, detail: String) -> Unit,
|
|
33
|
+
) {
|
|
34
|
+
private val TAG = "NativeBridgeAI"
|
|
35
|
+
|
|
36
|
+
private var engine: Engine? = null
|
|
37
|
+
private val isInitializing = AtomicBoolean(false)
|
|
38
|
+
|
|
39
|
+
private var nativeConversation: Conversation? = null
|
|
40
|
+
private var nativeConversationId: String? = null
|
|
41
|
+
|
|
42
|
+
var systemPrompt: String = ""
|
|
43
|
+
private set
|
|
44
|
+
|
|
45
|
+
private val MODEL_REGISTRY = mapOf(
|
|
46
|
+
"gemma-4-E2B" to ModelEntry(
|
|
47
|
+
url = "https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm",
|
|
48
|
+
filename = "gemma-4-E2B-it.litertlm",
|
|
49
|
+
sizeHint = 1_870_000_000L
|
|
50
|
+
),
|
|
51
|
+
"qwen3-0.6B" to ModelEntry(
|
|
52
|
+
url = "https://huggingface.co/litert-community/Qwen3-0.6B-it-litert-lm/resolve/main/Qwen3-0.6B-it-int4.litertlm",
|
|
53
|
+
filename = "Qwen3-0.6B-it-int4.litertlm",
|
|
54
|
+
sizeHint = 474_000_000L
|
|
55
|
+
),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
data class ModelEntry(val url: String, val filename: String, val sizeHint: Long)
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Returns false if init was already in progress (duplicate guard).
|
|
62
|
+
* Caller is responsible for running this on a background thread (Dispatchers.IO).
|
|
63
|
+
*/
|
|
64
|
+
suspend fun init(optionsRaw: String?): InitResult {
|
|
65
|
+
if (!isInitializing.compareAndSet(false, true)) {
|
|
66
|
+
return InitResult.AlreadyRunning
|
|
67
|
+
}
|
|
68
|
+
return try {
|
|
69
|
+
val options = try { JSONObject(optionsRaw ?: "{}") } catch (e: Exception) { JSONObject() }
|
|
70
|
+
|
|
71
|
+
buildSystemPrompt(options)
|
|
72
|
+
|
|
73
|
+
val modelPath = resolveModel(options)
|
|
74
|
+
ensureEngine(modelPath)
|
|
75
|
+
|
|
76
|
+
InitResult.Ready(
|
|
77
|
+
streamSupplier = ::supply,
|
|
78
|
+
systemPrompt = systemPrompt,
|
|
79
|
+
)
|
|
80
|
+
} catch (e: Exception) {
|
|
81
|
+
InitResult.Error(e)
|
|
82
|
+
} finally {
|
|
83
|
+
isInitializing.set(false)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
fun clearConversation() {
|
|
88
|
+
nativeConversation = null
|
|
89
|
+
nativeConversationId = null
|
|
90
|
+
log("Native conversation cleared — next call starts a fresh session")
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Called by FrameworkServerUtils supplier lambda
|
|
94
|
+
suspend fun supply(prompt: String, genConfig: JSONObject, incomingConvId: String?): Pair<String, Flow<String>> {
|
|
95
|
+
val eng = engine ?: throw IllegalStateException("Engine not initialized — call init() first")
|
|
96
|
+
|
|
97
|
+
val conversation = if (
|
|
98
|
+
incomingConvId != null &&
|
|
99
|
+
incomingConvId == nativeConversationId &&
|
|
100
|
+
nativeConversation != null
|
|
101
|
+
) {
|
|
102
|
+
log("Native session: reusing conversation $incomingConvId")
|
|
103
|
+
nativeConversation!!
|
|
104
|
+
} else {
|
|
105
|
+
log("Native session: creating new conversation")
|
|
106
|
+
val newConv = eng.createConversation(ConversationConfig())
|
|
107
|
+
nativeConversation = newConv
|
|
108
|
+
nativeConversationId = UUID.randomUUID().toString()
|
|
109
|
+
newConv
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
val activeConvId = nativeConversationId!!
|
|
113
|
+
val tokenFlow = conversation.sendMessageAsync(prompt).map { message ->
|
|
114
|
+
message.contents.contents
|
|
115
|
+
.filterIsInstance<Content.Text>()
|
|
116
|
+
.joinToString("") { it.text }
|
|
117
|
+
}
|
|
118
|
+
return Pair(activeConvId, tokenFlow)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// -------------------------------------------------------------------------
|
|
122
|
+
// Private
|
|
123
|
+
// -------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
private fun buildSystemPrompt(options: JSONObject) {
|
|
126
|
+
val attachmentComponents = options.optJSONObject("attachmentComponents")
|
|
127
|
+
if (attachmentComponents == null || attachmentComponents.length() == 0) {
|
|
128
|
+
log("[attachments] No attachmentComponents provided — skipping system prompt injection")
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
log("[attachments] Received ${attachmentComponents.length()} component(s): ${attachmentComponents.keys().asSequence().joinToString()}")
|
|
133
|
+
val appSystemPrompt = options.optString("systemPrompt", "").trim()
|
|
134
|
+
val sb = StringBuilder()
|
|
135
|
+
if (appSystemPrompt.isNotBlank()) {
|
|
136
|
+
sb.appendLine(appSystemPrompt)
|
|
137
|
+
sb.appendLine()
|
|
138
|
+
}
|
|
139
|
+
sb.appendLine("Never use markdown headers, bullet points, numbered lists, or bold. Instead use these components: <tool:create_attachment component='Name' [attr='val']>body</tool:create_attachment>")
|
|
140
|
+
sb.append("Available components: ")
|
|
141
|
+
val componentSummary = attachmentComponents.keys().asSequence().map { name ->
|
|
142
|
+
val def = attachmentComponents.optJSONObject(name)
|
|
143
|
+
val hint = def?.optString("hint", "")?.trim() ?: ""
|
|
144
|
+
if (hint.isNotBlank()) "$name ($hint)" else name
|
|
145
|
+
}.joinToString(", ")
|
|
146
|
+
sb.appendLine(componentSummary)
|
|
147
|
+
attachmentComponents.keys().forEach { name -> log("[attachments] Registered component: $name") }
|
|
148
|
+
systemPrompt = sb.toString().trim()
|
|
149
|
+
log("[attachments] System prompt set (${systemPrompt.length} chars)")
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private fun resolveModel(options: JSONObject): String {
|
|
153
|
+
val explicitPath = options.optString("modelPath", "")
|
|
154
|
+
if (explicitPath.isNotBlank()) {
|
|
155
|
+
log("Using explicit modelPath: $explicitPath")
|
|
156
|
+
return explicitPath
|
|
157
|
+
}
|
|
158
|
+
val modelKey = options.optString("model", "gemma-4-E2B")
|
|
159
|
+
val entry = MODEL_REGISTRY[modelKey]
|
|
160
|
+
?: throw Exception("Unknown model '$modelKey'. Available: ${MODEL_REGISTRY.keys.joinToString()}")
|
|
161
|
+
log("Model registry lookup: $modelKey")
|
|
162
|
+
progress("lookup", 0, 0, 0, modelKey)
|
|
163
|
+
return downloadModel(entry)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private fun ensureEngine(modelPath: String) {
|
|
167
|
+
if (engine != null) {
|
|
168
|
+
log("Engine already loaded — reusing warm instance")
|
|
169
|
+
return
|
|
170
|
+
}
|
|
171
|
+
progress("engine_init", 0, 0, 0, "loading")
|
|
172
|
+
engine = tryCreateEngine(modelPath)
|
|
173
|
+
log("LiteRT-LM engine ready")
|
|
174
|
+
progress("engine_init", 100, 0, 0, "ready")
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private fun tryCreateEngine(modelPath: String): Engine {
|
|
178
|
+
log("[tryCreateEngine] modelPath=$modelPath")
|
|
179
|
+
log("[tryCreateEngine] Attempting Backend.GPU()...")
|
|
180
|
+
return try {
|
|
181
|
+
val config = EngineConfig(modelPath = modelPath, backend = Backend.GPU())
|
|
182
|
+
log("[tryCreateEngine] EngineConfig created, constructing Engine...")
|
|
183
|
+
val eng = Engine(config)
|
|
184
|
+
log("[tryCreateEngine] Engine() constructed OK, calling initialize()...")
|
|
185
|
+
eng.initialize()
|
|
186
|
+
log("[tryCreateEngine] GPU engine initialized successfully")
|
|
187
|
+
eng
|
|
188
|
+
} catch (e: Exception) {
|
|
189
|
+
log("[tryCreateEngine] GPU failed at: ${e.javaClass.simpleName}: ${e.message}")
|
|
190
|
+
log("[tryCreateEngine] Falling back to Backend.CPU()...")
|
|
191
|
+
try {
|
|
192
|
+
val config = EngineConfig(modelPath = modelPath, backend = Backend.CPU())
|
|
193
|
+
val eng = Engine(config)
|
|
194
|
+
log("[tryCreateEngine] CPU Engine() constructed, calling initialize()...")
|
|
195
|
+
eng.initialize()
|
|
196
|
+
log("[tryCreateEngine] CPU engine initialized successfully")
|
|
197
|
+
eng
|
|
198
|
+
} catch (e2: Exception) {
|
|
199
|
+
log("[tryCreateEngine] CPU also failed: ${e2.javaClass.simpleName}: ${e2.message}")
|
|
200
|
+
throw e2
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private fun downloadModel(entry: ModelEntry): String {
|
|
206
|
+
val modelsDir = File(context.filesDir, "ai_models").also { it.mkdirs() }
|
|
207
|
+
val modelFile = File(modelsDir, entry.filename)
|
|
208
|
+
|
|
209
|
+
if (modelFile.exists() && modelFile.length() > 0) {
|
|
210
|
+
log("Model cache hit: ${entry.filename} (${modelFile.length() / 1_000_000}MB)")
|
|
211
|
+
progress("cache", 100, modelFile.length(), modelFile.length(), "cached")
|
|
212
|
+
return modelFile.absolutePath
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
log("Downloading model: ${entry.filename} from HuggingFace (~${entry.sizeHint / 1_000_000}MB)")
|
|
216
|
+
progress("download", 0, 0, entry.sizeHint, "starting")
|
|
217
|
+
|
|
218
|
+
val tempFile = File(modelsDir, "${entry.filename}.tmp")
|
|
219
|
+
try {
|
|
220
|
+
val conn = (URL(entry.url).openConnection() as HttpURLConnection).apply {
|
|
221
|
+
requestMethod = "GET"
|
|
222
|
+
connectTimeout = 30_000
|
|
223
|
+
readTimeout = 60_000
|
|
224
|
+
setRequestProperty("User-Agent", "CatalystCore/1.0 LiteRT-LM")
|
|
225
|
+
instanceFollowRedirects = true
|
|
226
|
+
connect()
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
val responseCode = conn.responseCode
|
|
230
|
+
if (responseCode !in 200..299) throw Exception("HTTP $responseCode from model server")
|
|
231
|
+
|
|
232
|
+
val contentLength = conn.contentLengthLong.takeIf { it > 0 } ?: entry.sizeHint
|
|
233
|
+
log("Content-Length: ${contentLength / 1_000_000}MB — downloading...")
|
|
234
|
+
|
|
235
|
+
conn.inputStream.use { input ->
|
|
236
|
+
tempFile.outputStream().use { output ->
|
|
237
|
+
val buf = ByteArray(128 * 1024)
|
|
238
|
+
var loaded = 0L
|
|
239
|
+
var lastPct = -1
|
|
240
|
+
var lastEmitMs = System.currentTimeMillis()
|
|
241
|
+
|
|
242
|
+
while (true) {
|
|
243
|
+
val n = input.read(buf)
|
|
244
|
+
if (n == -1) break
|
|
245
|
+
output.write(buf, 0, n)
|
|
246
|
+
loaded += n
|
|
247
|
+
|
|
248
|
+
val pct = if (contentLength > 0) ((loaded * 100) / contentLength).toInt() else -1
|
|
249
|
+
val now = System.currentTimeMillis()
|
|
250
|
+
if (pct != lastPct || now - lastEmitMs >= 200) {
|
|
251
|
+
lastPct = pct
|
|
252
|
+
lastEmitMs = now
|
|
253
|
+
val mb = loaded / 1_000_000
|
|
254
|
+
val totalMb = contentLength / 1_000_000
|
|
255
|
+
progress("download", maxOf(pct, 0), loaded, contentLength, "${mb}MB / ${totalMb}MB")
|
|
256
|
+
log("Download: $pct% (${mb}MB / ${totalMb}MB)")
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
conn.disconnect()
|
|
263
|
+
if (tempFile.length() == 0L) throw Exception("Downloaded file is empty")
|
|
264
|
+
tempFile.renameTo(modelFile)
|
|
265
|
+
log("Download complete: ${modelFile.length() / 1_000_000}MB saved to ${modelFile.absolutePath}")
|
|
266
|
+
progress("download", 100, modelFile.length(), modelFile.length(), "complete")
|
|
267
|
+
|
|
268
|
+
} catch (e: Exception) {
|
|
269
|
+
tempFile.delete()
|
|
270
|
+
throw Exception("Model download failed: ${e.message}", e)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return modelFile.absolutePath
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private fun log(msg: String) {
|
|
277
|
+
Log.d(TAG, "[AI] $msg")
|
|
278
|
+
onLog(msg)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private fun progress(phase: String, percent: Int, bytesLoaded: Long, bytesTotal: Long, detail: String) {
|
|
282
|
+
onProgress(phase, percent, bytesLoaded, bytesTotal, detail)
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
sealed class InitResult {
|
|
287
|
+
object AlreadyRunning : InitResult()
|
|
288
|
+
data class Ready(
|
|
289
|
+
val streamSupplier: suspend (String, JSONObject, String?) -> Pair<String, kotlinx.coroutines.flow.Flow<String>>,
|
|
290
|
+
val systemPrompt: String,
|
|
291
|
+
) : InitResult()
|
|
292
|
+
data class Error(val cause: Exception) : InitResult()
|
|
293
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
io.catalyst.nativeai.CatalystAIBridge
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "catalyst-ai",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AI provider for catalyst-core — cloud/web/native useAI hooks + OpenAI/Gemini SSE route",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.js",
|
|
8
|
+
"./route": "./src/route.js"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"preinstall": "node ./scripts/check-peer.js"
|
|
12
|
+
},
|
|
13
|
+
"peerDependencies": {
|
|
14
|
+
"catalyst-core": ">=0.3.0-0"
|
|
15
|
+
},
|
|
16
|
+
"peerDependenciesMeta": {
|
|
17
|
+
"catalyst-core": {
|
|
18
|
+
"optional": false
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "https://github.com/tata1mg/catalyst-core.git",
|
|
25
|
+
"directory": "packages/catalyst-ai"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
try {
|
|
2
|
+
require.resolve("catalyst-core")
|
|
3
|
+
} catch (_) {
|
|
4
|
+
// Non-fatal: in an npm workspace install, sibling packages aren't
|
|
5
|
+
// guaranteed to be linked yet when preinstall runs, so this can be a
|
|
6
|
+
// false positive. peerDependencies already declares the requirement;
|
|
7
|
+
// npm warns/errors on its own if catalyst-core is genuinely missing
|
|
8
|
+
// once the install finishes.
|
|
9
|
+
console.warn("\n\x1b[33m[WARN] catalyst-ai: catalyst-core not resolvable yet (expected during workspace install).\x1b[0m")
|
|
10
|
+
console.warn("\x1b[33mIf this persists after install completes, run: npm install catalyst-core\x1b[0m\n")
|
|
11
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export function buildAttachmentSystemPrompt(systemPrompt, attachmentComponents) {
|
|
2
|
+
const componentNames = Object.keys(attachmentComponents)
|
|
3
|
+
if (componentNames.length === 0 && !systemPrompt) return null
|
|
4
|
+
const parts = []
|
|
5
|
+
if (systemPrompt) parts.push(systemPrompt)
|
|
6
|
+
if (componentNames.length > 0) {
|
|
7
|
+
parts.push(
|
|
8
|
+
"Never use markdown headers, bullet points, numbered lists, or bold. Instead use these components: <tool:create_attachment component='Name' [attr='val']>content</tool:create_attachment>"
|
|
9
|
+
)
|
|
10
|
+
const summary = componentNames
|
|
11
|
+
.map((name) => {
|
|
12
|
+
const hint = attachmentComponents[name]?.hint
|
|
13
|
+
return hint ? `${name} (${hint})` : name
|
|
14
|
+
})
|
|
15
|
+
.join(", ")
|
|
16
|
+
parts.push(`Available components: ${summary}`)
|
|
17
|
+
}
|
|
18
|
+
return parts.join("\n")
|
|
19
|
+
}
|
package/src/index.js
ADDED