From 482a2fde95f121b827cea1e7ab29bb6f54859601 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 13 Jul 2026 12:34:33 +1000 Subject: [PATCH 1/2] Document SDK embedding --- website/src/_data/docs.js | 11 +++ website/src/docs/pages/sdk-kotlin.md | 143 +++++++++++++++++++++++++++ website/src/docs/pages/sdk-node.md | 129 ++++++++++++++++++++++++ website/src/docs/pages/sdk-rust.md | 118 ++++++++++++++++++++++ website/src/docs/pages/sdk-swift.md | 137 +++++++++++++++++++++++++ website/src/docs/pages/sdk.md | 85 ++++++++++++++++ 6 files changed, 623 insertions(+) create mode 100644 website/src/docs/pages/sdk-kotlin.md create mode 100644 website/src/docs/pages/sdk-node.md create mode 100644 website/src/docs/pages/sdk-rust.md create mode 100644 website/src/docs/pages/sdk-swift.md create mode 100644 website/src/docs/pages/sdk.md diff --git a/website/src/_data/docs.js b/website/src/_data/docs.js index 3ef5a3574c..be705d87f0 100644 --- a/website/src/_data/docs.js +++ b/website/src/_data/docs.js @@ -41,6 +41,17 @@ export default [ ["Structured outputs", "/docs/pages/openai-compatible-api/#structured-outputs"] ] }, + { + title: "SDKs", + description: "Embed mesh clients and local serving into Rust, Node.js, JVM/Android, and Swift apps.", + links: [ + ["SDK overview", "/docs/pages/sdk/"], + ["Rust", "/docs/pages/sdk-rust/"], + ["Node.js & Electron", "/docs/pages/sdk-node/"], + ["Java / Kotlin / Android", "/docs/pages/sdk-kotlin/"], + ["Swift & Apple platforms", "/docs/pages/sdk-swift/"] + ] + }, { title: "Plugins", description: "Extend mesh-llm with managed plugin processes, MCP tools, and HTTP bindings.", diff --git a/website/src/docs/pages/sdk-kotlin.md b/website/src/docs/pages/sdk-kotlin.md new file mode 100644 index 0000000000..19d922789d --- /dev/null +++ b/website/src/docs/pages/sdk-kotlin.md @@ -0,0 +1,143 @@ +--- +title: Java, Kotlin, and Android SDK +--- + +# Java, Kotlin, and Android SDK + +The Android/JVM SDK is published as `ai.meshllm:meshllm-android`. The public API is authored in Kotlin and uses coroutines and `Flow`; Java applications can consume the same AAR, while the examples here use Kotlin because it matches the native API most closely. + +## Install + +Add the GitHub Packages Maven registry and the SDK dependency: + +```kotlin +repositories { + maven { + url = uri("https://maven.pkg.github.com/Mesh-LLM/mesh-llm") + credentials { + username = providers.gradleProperty("gpr.user") + .orElse(System.getenv("GITHUB_ACTOR")).get() + password = providers.gradleProperty("gpr.key") + .orElse(System.getenv("GITHUB_TOKEN")).get() + } + } +} + +dependencies { + implementation("ai.meshllm:meshllm-android:0.72.1") +} +``` + +For local development, build the AAR with `./gradlew assembleAar` from `sdk/kotlin`. + +## Connect as a client + +```kotlin +import ai.meshllm.ChatMessage +import ai.meshllm.ChatRequest +import ai.meshllm.Client +import ai.meshllm.Event +import ai.meshllm.InviteToken +import kotlinx.coroutines.flow.collect +import uniffi.mesh_ffi.generateOwnerKeypairHex + +val client = Client( + InviteToken(System.getenv("MESH_INVITE_TOKEN")), + generateOwnerKeypairHex(), +) + +client.start() +try { + val models = client.inference.listModels() + client.inference.chatFlow( + ChatRequest( + models.first().id, + listOf(ChatMessage("user", "Say hello from Kotlin.")), + ), + ).collect { event -> + if (event is Event.TokenDelta) print(event.delta) + if (event is Event.Completed) println() + } +} finally { + client.stop() +} +``` + +For public mesh discovery, use `Client.connectPublic(ownerKeypair, PublicMeshQuery(...))`. Keep the owner keypair in app storage so reconnects retain the same identity. + +## JVM local serving + +Local serving is currently supported for validated JVM targets with a matching native runtime. Resolve a bundled or downloadable runtime first: + +```kotlin +import ai.meshllm.NativeRuntime +import ai.meshllm.NativeRuntimeResolveOptions +import java.io.File + +val runtime = NativeRuntime.resolve( + NativeRuntimeResolveOptions( + artifactDir = System.getenv("MESHLLM_NATIVE_RUNTIME_ARTIFACT_DIR")?.let(::File), + allowDownload = System.getenv("MESH_SDK_RUNTIME_ALLOW_DOWNLOAD") == "1", + ), +) +println("using ${runtime.nativeRuntimeId} from ${runtime.path}") +``` + +Then use `Node` for model management and serving: + +```kotlin +import ai.meshllm.ChatMessage +import ai.meshllm.ChatRequest +import ai.meshllm.DevicePolicy +import ai.meshllm.InviteToken +import ai.meshllm.LoadModelOptions +import ai.meshllm.Node +import ai.meshllm.UnloadModelOptions +import uniffi.mesh_ffi.generateOwnerKeypairHex + +val node = Node( + InviteToken(System.getenv("MESH_INVITE_TOKEN")), + generateOwnerKeypairHex(), +) + +node.start() +try { + val modelRef = System.getenv("MESH_SDK_MODEL_REF") ?: "Qwen2.5-3B-Instruct-Q4_K_M" + node.models.download(modelRef) + val served = node.serving.load(modelRef, LoadModelOptions(DevicePolicy.Auto)) + node.inference.chatFlow( + ChatRequest( + served.modelId, + listOf(ChatMessage("user", "Say hello from JVM serving.")), + ), + ).collect { event -> + if (event is Event.TokenDelta) print(event.delta) + if (event is Event.Completed) println() + } + node.serving.unloadModel( + served.modelId, + UnloadModelOptions(drainTimeoutMs = 1_000UL, force = false), + ) +} finally { + node.stop() +} +``` + +Catch `MeshException.ServingUnsupported` and show an actionable message when the selected JVM/native artifact does not provide local serving. + +## Android support + +Android apps can use the SDK for mesh inference and model-management APIs. Local serving is not currently advertised for Android, so an Android app should use `Client` to reach a serving node or display the typed unsupported error rather than trying to load a desktop runtime into the APK. + +When Android serving is validated, the packaging contract will need an ABI-specific native runtime, app-compatible storage, lifecycle handling, and a verified memory budget. Keep those concerns behind the SDK rather than copying desktop runtime paths into the app. + +## Console assets + +JVM/Android packages may include the console as resources. Extract packaged resources before starting the static console server: + +```kotlin +val console = node.startConsole(ConsoleAssets.packagedOptions(port = 3131u.toUShort())) +println(console.url()) +``` + +Treat the console as optional and bind it only to an interface your app can protect. diff --git a/website/src/docs/pages/sdk-node.md b/website/src/docs/pages/sdk-node.md new file mode 100644 index 0000000000..557b2408fd --- /dev/null +++ b/website/src/docs/pages/sdk-node.md @@ -0,0 +1,129 @@ +--- +title: Node.js and Electron SDK +--- + +# Node.js and Electron SDK + +Use [`@meshllm/sdk`](https://www.npmjs.com/package/@meshllm/sdk) in Node.js services, desktop apps, and Electron applications. The package uses a native N-API addon and the same embedded serving path as the Swift and Kotlin SDKs. + +## Install + +```json +{ + "dependencies": { + "@meshllm/sdk": "0.72.1" + } +} +``` + +When building from the repository, build the addon first: + +```bash +cd sdk/node +npm run build:native +``` + +## Connect as a client + +```js +const { Client, generateOwnerKeypairHex } = require('@meshllm/sdk') + +const client = Client.create({ + ownerKeypairHex: generateOwnerKeypairHex(), + inviteToken: process.env.MESH_INVITE_TOKEN +}) + +await client.start() +try { + const models = await client.inference.listModels() + const result = await client.inference.chat({ + model: models[0].id, + messages: [{ role: 'user', content: 'Say hello from Node.js.' }] + }) + console.log(result.content) +} finally { + await client.stop() +} +``` + +The current package expects an invite token selected by the app or service. Use the same `Client` lifecycle for public or private meshes; only the token source changes. + +## Embed local serving + +Serving needs a verified native runtime artifact. Bundle one with the app or explicitly allow the SDK to download a compatible release runtime: + +```js +const { resolveNativeRuntime } = require('@meshllm/sdk') + +const runtime = await resolveNativeRuntime({ + artifactDir: process.env.MESHLLM_NATIVE_RUNTIME_ARTIFACT_DIR, + allowDownload: process.env.MESH_SDK_RUNTIME_ALLOW_DOWNLOAD === '1', + onProgress: event => console.log(event) +}) +console.log(`using ${runtime.nativeRuntimeId} from ${runtime.path}`) +``` + +Create a `Node`, download or locate the model, load it through the serving API, and unload it during shutdown: + +```js +const { + Node, + generateOwnerKeypairHex, + resolveNativeRuntime +} = require('@meshllm/sdk') + +await resolveNativeRuntime({ + artifactDir: process.env.MESHLLM_NATIVE_RUNTIME_ARTIFACT_DIR, + allowDownload: process.env.MESH_SDK_RUNTIME_ALLOW_DOWNLOAD === '1' +}) + +const modelRef = process.env.MESH_SDK_MODEL_REF || 'Qwen2.5-3B-Instruct-Q4_K_M' +const node = Node.create({ + ownerKeypairHex: generateOwnerKeypairHex(), + inviteToken: process.env.MESH_INVITE_TOKEN, + servingEnabled: true, + cacheDir: process.env.MESH_SDK_CACHE_DIR, + runtimeDir: process.env.MESH_SDK_RUNTIME_DIR +}) + +await node.start() +try { + await node.models.download(modelRef) + const served = await node.serving.load(modelRef, { devicePolicy: 'auto' }) + const result = await node.inference.chat({ + model: served.modelId, + messages: [{ role: 'user', content: 'Say hello from local serving.' }] + }) + console.log(result.content) + await node.serving.unloadModel(served.modelId, { drainTimeoutMs: 1000 }) +} finally { + await node.stop() +} +``` + +Use `serving.unloadInstance(instanceId)` when the load call returns an instance id and the application manages multiple copies of a model. + +## Electron packaging + +Package these items for each target platform and architecture: + +- `native/-/mesh_llm_nodejs.node` +- the matching `meshllm-native-runtime-*` directory +- optional `console/` assets when the app calls `node.startConsole()` + +Resolve the runtime from the packaged artifact directory rather than relying on a writable global install. Keep the runtime cache and model cache in Electron's app-specific data directory. + +## Optional console + +When console assets are included in the npm package: + +```js +const consoleHandle = await node.startConsole({ port: 0 }) +console.log(consoleHandle.url) +``` + +For a repository checkout, pass an explicit asset directory such as `crates/mesh-llm-ui/dist`. Do not expose the console on all interfaces unless the app has its own authentication and network policy. + +## Runtime and errors + +The Node API exposes `Client` for remote inference and `Node` for serving, model management, status, reconnect, and console hosting. Handle runtime resolution failures, unavailable endpoints, model download failures, and serving errors as application errors. Persist the owner keypair instead of generating a new one each time the Electron window opens. diff --git a/website/src/docs/pages/sdk-rust.md b/website/src/docs/pages/sdk-rust.md new file mode 100644 index 0000000000..61235de538 --- /dev/null +++ b/website/src/docs/pages/sdk-rust.md @@ -0,0 +1,118 @@ +--- +title: Rust SDK +--- + +# Rust SDK + +Use [`mesh-llm-sdk`](https://crates.io/crates/mesh-llm-sdk) for Rust applications. The default `client` feature is lightweight; enable `serving` when the app should manage local models and run an embedded node. + +## Install + +Client-only application: + +```toml +[dependencies] +anyhow = "1" +mesh-llm-sdk = "0.72.1" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +``` + +Serving application: + +```toml +[dependencies] +anyhow = "1" +mesh-llm-sdk = { version = "0.72.1", features = ["serving"] } +serde_json = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +``` + +Add the `console` feature when the app also packages the web console. + +## Connect as a client + +The direct mesh transport avoids requiring a local OpenAI-compatible HTTP listener: + +```rust,no_run +use mesh_llm_sdk::{ClientBuilder, InviteToken, OwnerKeypair}; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let owner = OwnerKeypair::generate(); + let invite = std::env::var("MESH_INVITE_TOKEN")?.parse::()?; + let mut client = ClientBuilder::new(owner, invite) + .with_direct_mesh_transport() + .build()?; + + client.join().await?; + let models = client.list_models().await?; + println!("models: {}", models.len()); + // Stream chat or responses through the client inference API here. + client.disconnect().await; + Ok(()) +} +``` + +For public-mesh discovery, use `select_public_mesh(PublicMeshQuery { .. })` and build the client from the selected mesh. Keep the owner keypair stable across reconnects. + +## Embed local serving + +Resolve or install the native runtime into an app-owned cache before starting a serving node: + +```rust,no_run +use mesh_llm_sdk::native_runtime::{ + install_native_runtime, NativeRuntimeInstallOptions, RuntimeSelection, +}; + +let outcome = install_native_runtime(NativeRuntimeInstallOptions { + selection: RuntimeSelection::Recommended, + cache_dir: Some(app_cache_dir.join("mesh-llm-native-runtimes")), + bundle_dirs: vec![app_resources.join("meshllm-native-runtime")], + ..Default::default() +}) +.await?; +println!("runtime: {}", outcome.runtime.path.display()); +``` + +Then embed the node. This example serves a local model and joins a public mesh; replace `auto_join_public_mesh()` with `join_token(...)` for a private mesh: + +```rust,no_run +use mesh_llm_sdk::MeshNode; + +let node = MeshNode::builder() + .serve() + .model("unsloth/Qwen3-0.6B-GGUF:Q4_K_M") + .auto_join_public_mesh() + .api_port(0) + .console_port(0) + .start() + .await?; + +let models = node.openai_client().models().await?; +println!("served models: {models}"); +node.shutdown().await?; +``` + +`MeshNode` also exposes `status()`, `api_base_url()`, `console_url()`, `invite_token()`, and an `openai_client()` for chat completions and responses. If the application supplies its own serving implementation, the lower-level `mesh-llm-api-server` API can bind a `ServingController`; most applications should start with `mesh-llm-sdk`. + +## Console assets + +Enable `console` and package the generated console directory with the application: + +```rust,no_run +let console = mesh_llm_sdk::console::start_file_console( + mesh_llm_sdk::console::ConsoleServerOptions { + asset_dir: app_resources.join("console"), + port: 0, + listen_all: false, + }, +) +.await?; +println!("console: {}", console.url()); +``` + +Keep console hosting optional so client-only applications do not carry web assets. + +## Errors and shutdown + +Return `MeshApiError`/`anyhow::Error` to the application boundary, report download and serving progress, and always unload a served model before shutting down when requests may still be in flight. Use an app-owned cache and avoid sharing one mutable runtime directory between concurrent nodes. diff --git a/website/src/docs/pages/sdk-swift.md b/website/src/docs/pages/sdk-swift.md new file mode 100644 index 0000000000..5779ad04f1 --- /dev/null +++ b/website/src/docs/pages/sdk-swift.md @@ -0,0 +1,137 @@ +--- +title: Swift and Apple SDK +--- + +# Swift and Apple SDK + +Use the `MeshLLM` SwiftPM product in macOS, Mac Catalyst, and iOS applications. Tagged releases resolve the prebuilt `MeshLLMFFI.xcframework` automatically; local checkout builds use the same UniFFI-backed implementation. + +## Install + +Add the tagged Mesh-LLM package to `Package.swift`: + +```swift +dependencies: [ + .package(url: "https://github.com/Mesh-LLM/mesh-llm", from: "0.72.1"), +], +targets: [ + .target( + name: "YourApp", + dependencies: [ + .product(name: "MeshLLM", package: "mesh-llm"), + ] + ), +] +``` + +For local checkout development, build the XCFramework before building or testing the Swift package: + +```bash +./sdk/swift/scripts/build-xcframework.sh +``` + +## Connect as a client + +```swift +import MeshLLM + +let client = try await Client.connectPublic( + ownerKeypairBytesHex: generateOwnerKeypairHex(), + query: PublicMeshQuery(model: "Qwen3") +) + +try await client.start() +defer { Task { await client.stop() } } + +let models = try await client.inference.listModels() +let request = ChatRequest( + model: models[0].id, + messages: [ChatMessage(role: "user", content: "Say hello from Swift.")] +) + +for try await event in client.inference.chat(request) { + switch event { + case .tokenDelta(_, let delta): + print(delta, terminator: "") + case .completed: + print() + default: + break + } +} +``` + +For a private mesh, initialize `Client` with `InviteToken(...)` and the app's persisted owner keypair instead of `Client.connectPublic(...)`. + +## Embed local serving + +Resolve a matching native runtime before loading a local model: + +```swift +import MeshLLM + +let runtime = try await NativeRuntime.resolve( + NativeRuntimeResolveOptions( + artifactDirectory: ProcessInfo.processInfo.environment["MESHLLM_NATIVE_RUNTIME_ARTIFACT_DIR"] + .map(URL.init(fileURLWithPath:)), + allowDownload: ProcessInfo.processInfo.environment["MESH_SDK_RUNTIME_ALLOW_DOWNLOAD"] == "1" + ) +) +print("using \(runtime.nativeRuntimeId) from \(runtime.path)") +``` + +Create a `Node`, load the model, stream inference, and unload it before stopping: + +```swift +let node = try Node( + inviteToken: InviteToken(ProcessInfo.processInfo.environment["MESH_INVITE_TOKEN"]!), + ownerKeypairBytesHex: generateOwnerKeypairHex() +) + +try await node.start() +defer { Task { try? await node.stop() } } + +let modelRef = ProcessInfo.processInfo.environment["MESH_SDK_MODEL_REF"] + ?? "Qwen2.5-3B-Instruct-Q4_K_M" +_ = try await node.models.download(modelRef) +let served = try await node.serving.load( + modelRef, + options: LoadModelOptions(devicePolicy: .auto) +) + +let request = ChatRequest( + model: served.modelId, + messages: [ChatMessage(role: "user", content: "Say hello from local serving.")] +) +for try await event in node.inference.chat(request) { + if case .tokenDelta(_, let delta) = event { + print(delta, terminator: "") + } +} + +try await node.serving.unloadModel( + served.modelId, + options: UnloadModelOptions(drainTimeoutMs: 1_000, force: false) +) +``` + +Handle `MeshError.ServingUnsupported` for iOS and other targets without validated local serving. The current support line is macOS local serving; Mac Catalyst is under validation and iOS should use `Client` to reach another serving node. + +## Console assets + +Tagged packages can include the console as SwiftPM resources: + +```swift +let console = try await node.startConsole(.packaged(port: 0)) +print(console.url) +``` + +Keep the console optional and stop it with the app's lifecycle. For local package development, prepare assets with `scripts/package-sdk-console-assets.sh --sdk swift`. + +## Apple integration notes + +- Persist the owner keypair in Keychain or another app-owned secure store. +- Reconnect from `UIApplication.willEnterForegroundNotification` after iOS backgrounding. +- The SDK uses QUIC/TLS; configure `ITSAppUsesNonExemptEncryption` in `Info.plist` according to the app's export-compliance status. +- The distributed XCFramework includes a `PrivacyInfo.xcprivacy` manifest; verify it remains inside each framework slice when repackaging. +- Do not spawn the `mesh-llm` CLI as a sidecar. The Swift SDK uses the native bridge directly. diff --git a/website/src/docs/pages/sdk.md b/website/src/docs/pages/sdk.md new file mode 100644 index 0000000000..13434e80b2 --- /dev/null +++ b/website/src/docs/pages/sdk.md @@ -0,0 +1,85 @@ +--- +title: SDKs +--- + +# Embed Mesh in your app + +The Mesh SDKs let an application either connect to an existing mesh or embed a complete mesh node with local model serving. The public APIs are intentionally shaped the same way across Rust, Node.js, JVM/Android, and Swift. + +## Choose a role + +| Role | What it does | What it needs | +| --- | --- | --- | +| `Client` | Joins a private mesh or connects to a selected public mesh and runs inference. | SDK package, owner keypair, and invite token or public-mesh discovery. | +| `Node` | Includes the client role, model search/download, local model loading, serving, and optional console hosting. | SDK package plus a compatible native runtime artifact for local serving. | + +Use `Client` when another machine already serves the model. Use `Node` when the application should own local model files, load/unload decisions, and serving lifecycle. + +## Common lifecycle + +Client-only applications usually follow this shape: + +```text +load or create owner keypair +create Client with an invite token +start +list models +stream chat or responses +stop +``` + +Serving applications add runtime and model lifecycle: + +```text +resolve a native runtime +create Node +start +download or locate a model +load the model through serving +run inference +unload the model or instance +stop +``` + +Persist the owner keypair in the host application's secure storage. Generate an ephemeral key only for demos; changing it on every launch creates a new mesh identity. + +## Platform support + +| SDK / target | Mesh inference | Model management | Local serving | +| --- | ---: | ---: | ---: | +| Rust on macOS/Linux | yes | yes | yes with `serving` and a compatible native runtime | +| Node.js on macOS/Linux/Windows | yes | yes | yes with a compatible native runtime | +| JVM on macOS/Linux | yes | yes | yes with a matching native runtime library | +| Android | yes | yes | not currently advertised | +| Swift on macOS | yes | yes | yes with a matching native runtime | +| Swift on Mac Catalyst | yes | yes | planned validation | +| Swift on iOS | yes | limited by app filesystem policy | no | + +Targets without validated local serving should surface the typed `ServingUnsupported` error. Do not silently fall back to a fake local implementation. + +## Native runtime artifacts + +The language package provides the API and native bridge. Local inference also needs a release runtime artifact for the host platform and backend, such as Metal on Apple Silicon or CUDA on Linux. Runtime artifacts are selected and verified against the Mesh release and exact Skippy ABI; they are not compiled implicitly by npm, SwiftPM, Maven, or Cargo. + +Serving apps can either: + +- bundle the matching `meshllm-native-runtime-*` directory with the app, or +- allow the SDK runtime manager to download a verified artifact at startup. + +For offline or packaged applications, pass the artifact directory directly to the language SDK resolver. For online development, opt into downloads explicitly with `allowDownload` or `MESH_SDK_RUNTIME_ALLOW_DOWNLOAD=1`. + +## Pick a language guide + +- [Rust SDK](/docs/pages/sdk-rust/) — crates.io client facade and embedded `MeshNode`. +- [Node.js and Electron SDK](/docs/pages/sdk-node/) — npm package, N-API addon, runtime packaging, and console assets. +- [Java, Kotlin, and Android SDK](/docs/pages/sdk-kotlin/) — GitHub Packages AAR, JVM serving, Android client mode, and coroutines. +- [Swift SDK](/docs/pages/sdk-swift/) — SwiftPM, XCFrameworks, async streams, macOS, iOS, and App Store notes. + +## Shared rules + +- Pass identity and join tokens explicitly; SDKs do not read credentials from global CLI config directories. +- Keep API and console ports isolated when embedding more than one node in a process or test suite. +- Treat model downloads as application work: show progress, choose an app-owned cache, and handle cancellation. +- Stop or reconnect nodes with the host application's lifecycle. On mobile, reconnect when returning to the foreground. +- Handle typed errors, especially invalid tokens, discovery failures, model-management failures, stream failures, and unsupported serving. +- Package console assets only when the app needs a local web console; the default native runtime should stay smaller without them. From 7aa823e2875cd6aea39dbc4f9487066d250e8d17 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 14 Jul 2026 08:07:52 +1000 Subject: [PATCH 2/2] Fix SDK embedding review feedback --- website/src/_data/site.js | 14 ++++- website/src/docs/pages/sdk-kotlin.md | 2 +- website/src/docs/pages/sdk-node.md | 2 +- website/src/docs/pages/sdk-rust.md | 5 +- website/src/docs/pages/sdk-swift.md | 85 ++++++++++++++++------------ 5 files changed, 66 insertions(+), 42 deletions(-) diff --git a/website/src/_data/site.js b/website/src/_data/site.js index 2a171e686c..35a1d14665 100644 --- a/website/src/_data/site.js +++ b/website/src/_data/site.js @@ -1,3 +1,14 @@ +import { readFileSync } from 'node:fs'; + +const cargoToml = readFileSync(new URL('../../../Cargo.toml', import.meta.url), 'utf8'); +const sdkVersion = cargoToml.match( + /\[workspace\.package\][\s\S]*?\nversion\s*=\s*"([^"]+)"/ +)?.[1]; + +if (!sdkVersion) { + throw new Error('Unable to determine the SDK version from Cargo.toml'); +} + const site = { title: 'Mesh LLM', description: 'Mesh serves large local models across multiple machines through one OpenAI-compatible endpoint.', @@ -6,7 +17,8 @@ const site = { githubUrl: 'https://github.com/Mesh-LLM/mesh-llm', githubRepo: 'Mesh-LLM/mesh-llm', githubStarsFallback: '1.1k', - githubReleaseFallback: 'v0.71.0', + githubReleaseFallback: `v${sdkVersion}`, + sdkVersion, }; const fetchLatestReleaseTag = async (repo) => { diff --git a/website/src/docs/pages/sdk-kotlin.md b/website/src/docs/pages/sdk-kotlin.md index 19d922789d..f4570139cb 100644 --- a/website/src/docs/pages/sdk-kotlin.md +++ b/website/src/docs/pages/sdk-kotlin.md @@ -24,7 +24,7 @@ repositories { } dependencies { - implementation("ai.meshllm:meshllm-android:0.72.1") + implementation("ai.meshllm:meshllm-android:{{ site.sdkVersion }}") } ``` diff --git a/website/src/docs/pages/sdk-node.md b/website/src/docs/pages/sdk-node.md index 557b2408fd..320cfbb911 100644 --- a/website/src/docs/pages/sdk-node.md +++ b/website/src/docs/pages/sdk-node.md @@ -11,7 +11,7 @@ Use [`@meshllm/sdk`](https://www.npmjs.com/package/@meshllm/sdk) in Node.js serv ```json { "dependencies": { - "@meshllm/sdk": "0.72.1" + "@meshllm/sdk": "{{ site.sdkVersion }}" } } ``` diff --git a/website/src/docs/pages/sdk-rust.md b/website/src/docs/pages/sdk-rust.md index 61235de538..95a02b1d85 100644 --- a/website/src/docs/pages/sdk-rust.md +++ b/website/src/docs/pages/sdk-rust.md @@ -13,7 +13,7 @@ Client-only application: ```toml [dependencies] anyhow = "1" -mesh-llm-sdk = "0.72.1" +mesh-llm-sdk = "{{ site.sdkVersion }}" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` @@ -22,7 +22,7 @@ Serving application: ```toml [dependencies] anyhow = "1" -mesh-llm-sdk = { version = "0.72.1", features = ["serving"] } +mesh-llm-sdk = { version = "{{ site.sdkVersion }}", features = ["serving"] } serde_json = "1" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` @@ -68,6 +68,7 @@ let outcome = install_native_runtime(NativeRuntimeInstallOptions { selection: RuntimeSelection::Recommended, cache_dir: Some(app_cache_dir.join("mesh-llm-native-runtimes")), bundle_dirs: vec![app_resources.join("meshllm-native-runtime")], + allow_download: false, ..Default::default() }) .await?; diff --git a/website/src/docs/pages/sdk-swift.md b/website/src/docs/pages/sdk-swift.md index 5779ad04f1..cd49a04a41 100644 --- a/website/src/docs/pages/sdk-swift.md +++ b/website/src/docs/pages/sdk-swift.md @@ -12,7 +12,7 @@ Add the tagged Mesh-LLM package to `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/Mesh-LLM/mesh-llm", from: "0.72.1"), + .package(url: "https://github.com/Mesh-LLM/mesh-llm", from: "{{ site.sdkVersion }}"), ], targets: [ .target( @@ -40,25 +40,31 @@ let client = try await Client.connectPublic( query: PublicMeshQuery(model: "Qwen3") ) -try await client.start() -defer { Task { await client.stop() } } +do { + try await client.start() -let models = try await client.inference.listModels() -let request = ChatRequest( - model: models[0].id, - messages: [ChatMessage(role: "user", content: "Say hello from Swift.")] -) + let models = try await client.inference.listModels() + let request = ChatRequest( + model: models[0].id, + messages: [ChatMessage(role: "user", content: "Say hello from Swift.")] + ) -for try await event in client.inference.chat(request) { - switch event { - case .tokenDelta(_, let delta): - print(delta, terminator: "") - case .completed: - print() - default: - break + for try await event in client.inference.chat(request) { + switch event { + case .tokenDelta(_, let delta): + print(delta, terminator: "") + case .completed: + print() + default: + break + } } +} catch { + await client.stop() + throw error } + +await client.stop() ``` For a private mesh, initialize `Client` with `InviteToken(...)` and the app's persisted owner keypair instead of `Client.connectPublic(...)`. @@ -88,31 +94,36 @@ let node = try Node( ownerKeypairBytesHex: generateOwnerKeypairHex() ) -try await node.start() -defer { Task { try? await node.stop() } } +do { + try await node.start() -let modelRef = ProcessInfo.processInfo.environment["MESH_SDK_MODEL_REF"] - ?? "Qwen2.5-3B-Instruct-Q4_K_M" -_ = try await node.models.download(modelRef) -let served = try await node.serving.load( - modelRef, - options: LoadModelOptions(devicePolicy: .auto) -) + let modelRef = ProcessInfo.processInfo.environment["MESH_SDK_MODEL_REF"] + ?? "Qwen2.5-3B-Instruct-Q4_K_M" + _ = try await node.models.download(modelRef) + let served = try await node.serving.load( + modelRef, + options: LoadModelOptions(devicePolicy: .auto) + ) -let request = ChatRequest( - model: served.modelId, - messages: [ChatMessage(role: "user", content: "Say hello from local serving.")] -) -for try await event in node.inference.chat(request) { - if case .tokenDelta(_, let delta) = event { - print(delta, terminator: "") + let request = ChatRequest( + model: served.modelId, + messages: [ChatMessage(role: "user", content: "Say hello from local serving.")] + ) + for try await event in node.inference.chat(request) { + if case .tokenDelta(_, let delta) = event { + print(delta, terminator: "") + } } -} -try await node.serving.unloadModel( - served.modelId, - options: UnloadModelOptions(drainTimeoutMs: 1_000, force: false) -) + try await node.serving.unloadModel( + served.modelId, + options: UnloadModelOptions(drainTimeoutMs: 1_000, force: false) + ) + try await node.stop() +} catch { + try? await node.stop() + throw error +} ``` Handle `MeshError.ServingUnsupported` for iOS and other targets without validated local serving. The current support line is macOS local serving; Mac Catalyst is under validation and iOS should use `Client` to reach another serving node.