Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: add foundation models plugin with server management capabilities (#7744)
dev-miro26d5aa7d40227b
diff --git a/Makefile b/Makefileindex 8891c4a2e..10ed25fd2 100644--- a/Makefile+++ b/Makefile@@ -53,6 +53,7 @@ install-ios-rust-targets:dev: install-and-buildyarn download:binmake build-mlx-server-if-exists+ make build-foundation-models-server-if-existsmake build-cli-devyarn dev@@ -116,6 +117,7 @@ endifyarn copy:assets:tauriyarn build:iconyarn build:mlx-server+ make build-foundation-models-server-if-existsmake build-clicargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features test-tauri -- --test-threads=1cargo test --manifest-path src-tauri/plugins/tauri-plugin-hardware/Cargo.toml@@ -126,17 +128,21 @@ endifbuild-mlx-server:ifeq ($(shell uname -s),Darwin)@echo "Building MLX server for Apple Silicon..."-# cd mlx-server && swift build -c release- cd mlx-server && xcodebuild build -scheme mlx-server -destination 'platform=OS X' -configuration Release OTHER_LDFLAGS="-dead_strip"- @echo "Finding build products..."- @DERIVED_DATA=$$(find ~/Library/Developer/Xcode/DerivedData/mlx-server-*/Build/Products/Release -maxdepth 0 2>/dev/null | head -1); \- if [ -z "$$DERIVED_DATA" ]; then \+ cd mlx-server && swift build -c release+ @echo "Copying build products..."+ @BUILD_DIR=$$(cd mlx-server && swift build -c release --show-bin-path); \+ if [ -z "$$BUILD_DIR" ]; then \echo "Error: Could not find build products"; \exit 1; \fi; \- echo "Copying mlx-server from $$DERIVED_DATA..."; \- cp "$$DERIVED_DATA/mlx-server" src-tauri/resources/bin/mlx-server; \- cp -r "$$DERIVED_DATA/mlx-swift_Cmlx.bundle" src-tauri/resources/bin/; \+ mkdir -p src-tauri/resources/bin; \+ echo "Copying mlx-server from $$BUILD_DIR..."; \+ cp "$$BUILD_DIR/mlx-server" src-tauri/resources/bin/mlx-server; \+ if [ -d "$$BUILD_DIR/mlx-swift_Cmlx.bundle" ]; then \+ cp -r "$$BUILD_DIR/mlx-swift_Cmlx.bundle" src-tauri/resources/bin/; \+ else \+ mkdir -p src-tauri/resources/bin/mlx-swift_Cmlx.bundle; \+ fi; \chmod +x src-tauri/resources/bin/mlx-server; \echo "MLX server built and copied successfully"; \echo "Checking for code signing identity..."; \@@ -144,8 +150,10 @@ ifeq ($(shell uname -s),Darwin)if [ -n "$$SIGNING_IDENTITY" ]; then \echo "Signing mlx-server with identity: $$SIGNING_IDENTITY"; \codesign --force --options runtime --timestamp --sign "$$SIGNING_IDENTITY" src-tauri/resources/bin/mlx-server; \- echo "Signing mlx-swift_Cmlx.bundle..."; \- codesign --force --options runtime --timestamp --sign "$$SIGNING_IDENTITY" --deep src-tauri/resources/bin/mlx-swift_Cmlx.bundle; \+ if [ -d "src-tauri/resources/bin/mlx-swift_Cmlx.bundle" ]; then \+ echo "Signing mlx-swift_Cmlx.bundle..."; \+ codesign --force --options runtime --timestamp --sign "$$SIGNING_IDENTITY" --deep src-tauri/resources/bin/mlx-swift_Cmlx.bundle; \+ fi; \echo "Code signing completed successfully"; \else \echo "Warning: No Developer ID Application identity found. Skipping code signing (notarization will fail)."; \@@ -166,6 +174,40 @@ else@echo "Skipping MLX server build (macOS only)"endif+# Build Apple Foundation Models server (macOS 26+ only) - always builds+build-foundation-models-server:+ifeq ($(shell uname -s),Darwin)+ @echo "Building Foundation Models server for macOS 26+..."+ cd foundation-models-server && swift build -c release+ @echo "Copying foundation-models-server binary..."+ @cp foundation-models-server/.build/release/foundation-models-server src-tauri/resources/bin/foundation-models-server+ @chmod +x src-tauri/resources/bin/foundation-models-server+ @echo "Foundation Models server built and copied successfully"+ @echo "Checking for code signing identity..."+ @SIGNING_IDENTITY=$$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -1 | sed 's/.*"\(.*\)".*/\1/'); \+ if [ -n "$$SIGNING_IDENTITY" ]; then \+ echo "Signing foundation-models-server with identity: $$SIGNING_IDENTITY"; \+ codesign --force --options runtime --timestamp --sign "$$SIGNING_IDENTITY" src-tauri/resources/bin/foundation-models-server; \+ echo "Code signing completed successfully"; \+ else \+ echo "Warning: No Developer ID Application identity found. Skipping code signing."; \+ fi+else+ @echo "Skipping Foundation Models server build (macOS only)"+endif++# Build Foundation Models server only if not already present (for dev)+build-foundation-models-server-if-exists:+ifeq ($(shell uname -s),Darwin)+ @if [ -f "src-tauri/resources/bin/foundation-models-server" ]; then \+ echo "Foundation Models server already exists at src-tauri/resources/bin/foundation-models-server, skipping build..."; \+ else \+ make build-foundation-models-server; \+ fi+else+ @echo "Skipping Foundation Models server build (macOS only)"+endif+# Build jan CLI (release, platform-aware) → src-tauri/resources/bin/jan[.exe]build-cli:ifeq ($(shell uname -s),Darwin)diff --git a/extensions/foundation-models-extension/package.json b/extensions/foundation-models-extension/package.jsonnew file mode 100644index 000000000..5ccd7ae34--- /dev/null+++ b/extensions/foundation-models-extension/package.json@@ -0,0 +1,39 @@+{+ "name": "@janhq/foundation-models-extension",+ "productName": "Apple Foundation Models",+ "version": "1.0.0",+ "description": "Run Apple on-device Foundation Models (macOS 26+ with Apple Intelligence)",+ "main": "dist/index.js",+ "module": "dist/module.js",+ "engine": "foundation-models",+ "author": "Jan <[email protected]>",+ "license": "AGPL-3.0",+ "scripts": {+ "build": "rolldown -c rolldown.config.mjs",+ "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"+ },+ "devDependencies": {+ "cpx": "1.5.0",+ "rimraf": "3.0.2",+ "rolldown": "1.0.0-beta.1",+ "typescript": "5.9.2"+ },+ "dependencies": {+ "@janhq/core": "../../core/package.tgz",+ "@janhq/tauri-plugin-foundation-models-api": "link:../../src-tauri/plugins/tauri-plugin-foundation-models",+ "@tauri-apps/api": "2.8.0",+ "@tauri-apps/plugin-http": "2.5.0",+ "@tauri-apps/plugin-log": "^2.6.0"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "files": [+ "dist/*",+ "package.json"+ ],+ "installConfig": {+ "hoistingLimits": "workspaces"+ },+ "packageManager": "[email protected]"+}diff --git a/extensions/foundation-models-extension/rolldown.config.mjs b/extensions/foundation-models-extension/rolldown.config.mjsnew file mode 100644index 000000000..cc6abbcf4--- /dev/null+++ b/extensions/foundation-models-extension/rolldown.config.mjs@@ -0,0 +1,19 @@+import { defineConfig } from 'rolldown'+import pkgJson from './package.json' with { type: 'json' }+import settingJson from './settings.json' with { type: 'json' }++export default defineConfig({+ input: 'src/index.ts',+ output: {+ format: 'esm',+ file: 'dist/index.js',+ },+ platform: 'browser',+ define: {+ SETTINGS: JSON.stringify(settingJson),+ ENGINE: JSON.stringify(pkgJson.engine),+ },+ inject: process.env.IS_DEV ? {} : {+ fetch: ['@tauri-apps/plugin-http', 'fetch'],+ },+})diff --git a/extensions/foundation-models-extension/settings.json b/extensions/foundation-models-extension/settings.jsonnew file mode 100644index 000000000..fe51488c7--- /dev/null+++ b/extensions/foundation-models-extension/settings.json@@ -0,0 +1 @@+[]diff --git a/extensions/foundation-models-extension/src/env.d.ts b/extensions/foundation-models-extension/src/env.d.tsnew file mode 100644index 000000000..9a78d6680--- /dev/null+++ b/extensions/foundation-models-extension/src/env.d.ts@@ -0,0 +1,4 @@+/// <reference types="vite/client" />++declare const SETTINGS: any[]+declare const ENGINE: stringdiff --git a/extensions/foundation-models-extension/src/index.ts b/extensions/foundation-models-extension/src/index.tsnew file mode 100644index 000000000..9110b2154--- /dev/null+++ b/extensions/foundation-models-extension/src/index.ts@@ -0,0 +1,395 @@+/**+ * Apple Foundation Models Extension+ *+ * Provides access to Apple's on-device Foundation Models (macOS 26+ with Apple+ * Intelligence) as a Jan AI engine. The model runs fully locally — no internet+ * connection or external API key is required.+ *+ * Architecture:+ * Jan extension (TypeScript) → Tauri plugin (Rust) → foundation-models-server (Swift)+ * ↓+ * Apple FoundationModels.framework+ *+ * The extension spawns a lightweight OpenAI-compatible HTTP server (`foundation-models-server`)+ * that wraps the system Foundation Models API. Chat requests are proxied through that+ * local server, keeping the same pattern used by the MLX and llama.cpp engines.+ */++import {+ AIEngine,+ EngineManager,+ modelInfo,+ SessionInfo,+ UnloadResult,+ chatCompletion,+ chatCompletionChunk,+ ImportOptions,+ chatCompletionRequest,+} from '@janhq/core'++import { info, warn, error as logError } from '@tauri-apps/plugin-log'+import { invoke } from '@tauri-apps/api/core'+import {+ loadFoundationModelsServer,+ unloadFoundationModelsServer,+ isFoundationModelsProcessRunning,+ getFoundationModelsRandomPort,+ findFoundationModelsSession,+ checkFoundationModelsAvailability,+} from '@janhq/tauri-plugin-foundation-models-api'++// ─── Constants ───────────────────────────────────────────────────────────────++/** The stable model ID used throughout Jan for the Apple on-device model. */+const APPLE_MODEL_ID = 'apple/on-device'++/** Display name shown in the Jan UI. */+const APPLE_MODEL_NAME = 'Apple On-Device Model'++/** Shared API secret used to authorise requests to the local server. */+const API_SECRET = 'JanFoundationModels'++/** Seconds to wait for the server binary to become ready. */+const SERVER_STARTUP_TIMEOUT = 60++// ─── Logger ──────────────────────────────────────────────────────────────────++const logger = {+ info: (...args: any[]) => {+ console.log(...args)+ info(args.map(String).join(' '))+ },+ warn: (...args: any[]) => {+ console.warn(...args)+ warn(args.map(String).join(' '))+ },+ error: (...args: any[]) => {+ console.error(...args)+ logError(args.map(String).join(' '))+ },+}++// ─── Extension ───────────────────────────────────────────────────────────────++export default class FoundationModelsExtension extends AIEngine {+ readonly provider: string = 'foundation-models'+ readonly providerId: string = 'foundation-models'++ /** Seconds before a streaming request is considered timed out. */+ timeout: number = 300++ // ── Lifecycle ──────────────────────────────────────────────────────────────++ override async onLoad(): Promise<void> {+ super.onLoad() // registers into EngineManager++ // Check device eligibility and silently remove ourselves if not supported.+ // This prevents the provider from appearing in the UI on ineligible devices.+ try {+ const availability = await checkFoundationModelsAvailability()+ if (availability !== 'available') {+ logger.warn(+ `Foundation Models not available on this device (status: ${availability}). ` ++ 'Hiding provider.'+ )+ EngineManager.instance().engines.delete(this.provider)+ }+ } catch (err) {+ logger.warn('Could not determine Foundation Models availability — hiding provider.', err)+ EngineManager.instance().engines.delete(this.provider)+ }+ }++ override async onUnload(): Promise<void> {+ // Clean-up is handled by the Tauri plugin on app exit.+ }++ // ── Model catalogue ────────────────────────────────────────────────────────++ override async list(): Promise<modelInfo[]> {+ return [this.buildModelInfo()]+ }++ override async get(modelId: string): Promise<modelInfo | undefined> {+ if (modelId !== APPLE_MODEL_ID) return undefined+ return this.buildModelInfo()+ }++ private buildModelInfo(): modelInfo {+ return {+ id: APPLE_MODEL_ID,+ name: APPLE_MODEL_NAME,+ providerId: this.provider,+ port: 0,+ sizeBytes: 0,+ tags: ['on-device', 'apple-intelligence'],+ capabilities: ['tools'],+ }+ }++ // ── Session management ─────────────────────────────────────────────────────++ override async load(+ modelId: string,+ _overrideSettings?: any,+ _isEmbedding: boolean = false,+ _bypassAutoUnload: boolean = false+ ): Promise<SessionInfo> {+ if (modelId !== APPLE_MODEL_ID) {+ throw new Error(+ `Foundation Models extension only supports model '${APPLE_MODEL_ID}', got '${modelId}'`+ )+ }++ // Return existing session if already running+ const existing = await findFoundationModelsSession()+ if (existing) {+ logger.info('Foundation Models server already running on port', existing.port)+ return this.toSessionInfo(existing)+ }++ const port = await getFoundationModelsRandomPort()+ const apiKey = await this.generateApiKey(port)++ logger.info('Starting Foundation Models server on port', port)++ try {+ const session = await loadFoundationModelsServer(+ APPLE_MODEL_ID,+ port,+ apiKey,+ SERVER_STARTUP_TIMEOUT+ )+ logger.info('Foundation Models server started, PID', session.pid)+ return this.toSessionInfo(session)+ } catch (err) {+ logger.error('Failed to start Foundation Models server:', err)+ throw err+ }+ }++ override async unload(modelId: string): Promise<UnloadResult> {+ const session = await findFoundationModelsSession()+ if (!session) {+ logger.warn('No active Foundation Models session to unload')+ return { success: false, error: 'No active session found' }+ }++ try {+ const result = await unloadFoundationModelsServer(session.pid)+ if (result.success) {+ logger.info('Foundation Models server unloaded successfully')+ } else {+ logger.warn('Failed to unload Foundation Models server:', result.error)+ }+ return result+ } catch (err) {+ logger.error('Error unloading Foundation Models server:', err)+ return { success: false, error: String(err) }+ }+ }++ // ── Inference ──────────────────────────────────────────────────────────────++ override async chat(+ opts: chatCompletionRequest,+ abortController?: AbortController+ ): Promise<chatCompletion | AsyncIterable<chatCompletionChunk>> {+ const session = await findFoundationModelsSession()+ if (!session) {+ throw new Error(+ 'Apple Foundation Model is not loaded. Please load the model first.'+ )+ }++ // Verify the server process is still alive+ const alive = await isFoundationModelsProcessRunning(session.pid)+ if (!alive) {+ throw new Error(+ 'Apple Foundation Model server has crashed. Please reload the model.'+ )+ }++ // Health check+ try {+ await fetch(`http://localhost:${session.port}/health`)+ } catch {+ throw new Error(+ 'Apple Foundation Model server is not responding. Please reload the model.'+ )+ }++ const url = `http://localhost:${session.port}/v1/chat/completions`+ const headers: HeadersInit = {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.api_key}`,+ }+ const body = JSON.stringify(opts)++ if (opts.stream) {+ return this.handleStreamingResponse(url, headers, body, abortController)+ }++ const response = await fetch(url, {+ method: 'POST',+ headers,+ body,+ signal: abortController?.signal,+ })++ if (!response.ok) {+ const errData = await response.json().catch(() => null)+ throw new Error(+ `Foundation Models API request failed (${response.status}): ${JSON.stringify(errData)}`+ )+ }++ return (await response.json()) as chatCompletion+ }++ private async *handleStreamingResponse(+ url: string,+ headers: HeadersInit,+ body: string,+ abortController?: AbortController+ ): AsyncIterable<chatCompletionChunk> {+ const combinedController = new AbortController()+ const timeoutId = setTimeout(+ () => combinedController.abort(new Error('Request timed out')),+ this.timeout * 1000+ )++ if (abortController?.signal) {+ if (abortController.signal.aborted) {+ combinedController.abort(abortController.signal.reason)+ } else {+ abortController.signal.addEventListener(+ 'abort',+ () => combinedController.abort(abortController.signal.reason),+ { once: true }+ )+ }+ }++ const response = await fetch(url, {+ method: 'POST',+ headers,+ body,+ signal: combinedController.signal,+ }).finally(() => clearTimeout(timeoutId))++ if (!response.ok) {+ const errData = await response.json().catch(() => null)+ throw new Error(+ `Foundation Models streaming request failed (${response.status}): ${JSON.stringify(errData)}`+ )+ }++ if (!response.body) {+ throw new Error('Response body is null')+ }++ const reader = response.body.getReader()+ const decoder = new TextDecoder('utf-8')+ let buffer = ''++ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) break++ buffer += decoder.decode(value, { stream: true })+ const lines = buffer.split('\n')+ buffer = lines.pop() ?? ''++ for (const line of lines) {+ const trimmed = line.trim()+ if (!trimmed || trimmed === 'data: [DONE]') continue++ if (trimmed.startsWith('data: ')) {+ try {+ const data = JSON.parse(trimmed.slice(6)) as chatCompletionChunk+ yield data+ } catch (e) {+ logger.error('Error parsing Foundation Models stream JSON:', e)+ throw e+ }+ } else if (trimmed.startsWith('error: ')) {+ const errObj = JSON.parse(trimmed.slice(7))+ throw new Error(errObj.message ?? 'Unknown streaming error')+ }+ }+ }+ } finally {+ reader.releaseLock()+ }+ }++ // ── Unsupported operations ─────────────────────────────────────────────────+ // Foundation Models are built into the OS — there are no files to manage.++ override async delete(_modelId: string): Promise<void> {+ throw new Error(+ 'Apple Foundation Models are part of the operating system and cannot be deleted from Jan.'+ )+ }++ override async update(_modelId: string, _model: Partial<modelInfo>): Promise<void> {+ throw new Error(+ 'Apple Foundation Models are managed by the OS and cannot be updated from Jan.'+ )+ }++ override async import(_modelId: string, _opts: ImportOptions): Promise<void> {+ throw new Error(+ 'Apple Foundation Models are built into the OS — there is nothing to import.'+ )+ }++ override async abortImport(_modelId: string): Promise<void> {+ // No download to abort — the model is managed by the OS.+ }++ override async getLoadedModels(): Promise<string[]> {+ const session = await findFoundationModelsSession()+ return session ? [APPLE_MODEL_ID] : []+ }++ override async isToolSupported(_modelId: string): Promise<boolean> {+ // The Foundation Models framework supports function calling.+ return true+ }++ // ── Helpers ────────────────────────────────────────────────────────────────++ /**+ * Derive a per-session API key from the shared secret and port number.+ * Uses the same HMAC-SHA256 approach as the llamacpp extension so the+ * Tauri `generate_api_key` command can be reused.+ */+ private async generateApiKey(port: number): Promise<string> {+ return invoke<string>('plugin:llamacpp|generate_api_key', {+ modelId: APPLE_MODEL_ID + port,+ apiSecret: API_SECRET,+ })+ }++ /**+ * Map the plugin SessionInfo shape to the core SessionInfo shape.+ */+ private toSessionInfo(session: {+ pid: number+ port: number+ model_id: string+ api_key: string+ }): SessionInfo {+ return {+ pid: session.pid,+ port: session.port,+ model_id: session.model_id,+ model_path: '',+ is_embedding: false,+ api_key: session.api_key,+ }+ }+}diff --git a/extensions/foundation-models-extension/tsconfig.json b/extensions/foundation-models-extension/tsconfig.jsonnew file mode 100644index 000000000..34d31fe4a--- /dev/null+++ b/extensions/foundation-models-extension/tsconfig.json@@ -0,0 +1,15 @@+{+ "compilerOptions": {+ "target": "es2018",+ "module": "ES6",+ "moduleResolution": "node",+ "outDir": "./dist",+ "esModuleInterop": true,+ "forceConsistentCasingInFileNames": true,+ "strict": false,+ "skipLibCheck": true,+ "rootDir": "./src"+ },+ "include": ["./src"],+ "exclude": ["**/*.test.ts"]+}diff --git a/extensions/yarn.lock b/extensions/yarn.lockindex c0452b939..46c067f58 100644--- a/extensions/yarn.lock+++ b/extensions/yarn.lock@@ -342,85 +342,97 @@ __metadata:"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Fassistant-extension%40workspace%3Aassistant-extension":version: 0.1.10- resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=c49664&locator=%40janhq%2Fassistant-extension%40workspace%3Aassistant-extension"+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Fassistant-extension%40workspace%3Aassistant-extension"dependencies:rxjs: "npm:^7.8.1"ulidx: "npm:^2.3.0"peerDependencies:react: 19.0.0- checksum: 10c0/23394165c70d57aa556c9a09301d86a26bdf7f6268dfe07564e60e97e495f829745413ae30c542c53ad68ad1f4816b27b51e236685a0c68a8f0e3f9f36f959b5+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7languageName: nodelinkType: hard"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Fconversational-extension%40workspace%3Aconversational-extension":version: 0.1.10- resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=c49664&locator=%40janhq%2Fconversational-extension%40workspace%3Aconversational-extension"+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Fconversational-extension%40workspace%3Aconversational-extension"dependencies:rxjs: "npm:^7.8.1"ulidx: "npm:^2.3.0"peerDependencies:react: 19.0.0- checksum: 10c0/23394165c70d57aa556c9a09301d86a26bdf7f6268dfe07564e60e97e495f829745413ae30c542c53ad68ad1f4816b27b51e236685a0c68a8f0e3f9f36f959b5+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7languageName: nodelinkType: hard"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Fdownload-extension%40workspace%3Adownload-extension":version: 0.1.10- resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=c49664&locator=%40janhq%2Fdownload-extension%40workspace%3Adownload-extension"+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Fdownload-extension%40workspace%3Adownload-extension"dependencies:rxjs: "npm:^7.8.1"ulidx: "npm:^2.3.0"peerDependencies:react: 19.0.0- checksum: 10c0/23394165c70d57aa556c9a09301d86a26bdf7f6268dfe07564e60e97e495f829745413ae30c542c53ad68ad1f4816b27b51e236685a0c68a8f0e3f9f36f959b5+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7+ languageName: node+ linkType: hard++"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Ffoundation-models-extension%40workspace%3Afoundation-models-extension":+ version: 0.1.10+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Ffoundation-models-extension%40workspace%3Afoundation-models-extension"+ dependencies:+ rxjs: "npm:^7.8.1"+ ulidx: "npm:^2.3.0"+ peerDependencies:+ react: 19.0.0+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7languageName: nodelinkType: hard"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Fllamacpp-extension%40workspace%3Allamacpp-extension":version: 0.1.10- resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=c49664&locator=%40janhq%2Fllamacpp-extension%40workspace%3Allamacpp-extension"+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Fllamacpp-extension%40workspace%3Allamacpp-extension"dependencies:rxjs: "npm:^7.8.1"ulidx: "npm:^2.3.0"peerDependencies:react: 19.0.0- checksum: 10c0/23394165c70d57aa556c9a09301d86a26bdf7f6268dfe07564e60e97e495f829745413ae30c542c53ad68ad1f4816b27b51e236685a0c68a8f0e3f9f36f959b5+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7languageName: nodelinkType: hard"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Fmlx-extension%40workspace%3Amlx-extension":version: 0.1.10- resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=c49664&locator=%40janhq%2Fmlx-extension%40workspace%3Amlx-extension"+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Fmlx-extension%40workspace%3Amlx-extension"dependencies:rxjs: "npm:^7.8.1"ulidx: "npm:^2.3.0"peerDependencies:react: 19.0.0- checksum: 10c0/23394165c70d57aa556c9a09301d86a26bdf7f6268dfe07564e60e97e495f829745413ae30c542c53ad68ad1f4816b27b51e236685a0c68a8f0e3f9f36f959b5+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7languageName: nodelinkType: hard"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Frag-extension%40workspace%3Arag-extension":version: 0.1.10- resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=c49664&locator=%40janhq%2Frag-extension%40workspace%3Arag-extension"+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Frag-extension%40workspace%3Arag-extension"dependencies:rxjs: "npm:^7.8.1"ulidx: "npm:^2.3.0"peerDependencies:react: 19.0.0- checksum: 10c0/23394165c70d57aa556c9a09301d86a26bdf7f6268dfe07564e60e97e495f829745413ae30c542c53ad68ad1f4816b27b51e236685a0c68a8f0e3f9f36f959b5+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7languageName: nodelinkType: hard"@janhq/core@file:../../core/package.tgz::locator=%40janhq%2Fvector-db-extension%40workspace%3Avector-db-extension":version: 0.1.10- resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=c49664&locator=%40janhq%2Fvector-db-extension%40workspace%3Avector-db-extension"+ resolution: "@janhq/core@file:../../core/package.tgz#../../core/package.tgz::hash=4d03b5&locator=%40janhq%2Fvector-db-extension%40workspace%3Avector-db-extension"dependencies:rxjs: "npm:^7.8.1"ulidx: "npm:^2.3.0"peerDependencies:react: 19.0.0- checksum: 10c0/23394165c70d57aa556c9a09301d86a26bdf7f6268dfe07564e60e97e495f829745413ae30c542c53ad68ad1f4816b27b51e236685a0c68a8f0e3f9f36f959b5+ checksum: 10c0/c80736877d9b0d9498d76588a1e92664f467a84265aee7cb6be497b89ed4b1e1c9379c12686c4676bb438eb268ba97caae607b01686e3dc0d485933a4ab69af7languageName: nodelinkType: hard@@ -439,6 +451,21 @@ __metadata:languageName: unknownlinkType: soft+"@janhq/foundation-models-extension@workspace:foundation-models-extension":+ version: 0.0.0-use.local+ resolution: "@janhq/foundation-models-extension@workspace:foundation-models-extension"+ dependencies:+ "@janhq/core": ../../core/package.tgz+ "@janhq/tauri-plugin-foundation-models-api": "link:../../src-tauri/plugins/tauri-plugin-foundation-models"+ "@tauri-apps/api": "npm:2.8.0"+ "@tauri-apps/plugin-log": "npm:^2.6.0"+ cpx: "npm:1.5.0"+ rimraf: "npm:3.0.2"+ rolldown: "npm:1.0.0-beta.1"+ typescript: "npm:5.9.2"+ languageName: unknown+ linkType: soft+"@janhq/llamacpp-extension@workspace:llamacpp-extension":version: 0.0.0-use.localresolution: "@janhq/llamacpp-extension@workspace:llamacpp-extension"@@ -493,6 +520,12 @@ __metadata:languageName: unknownlinkType: soft+"@janhq/tauri-plugin-foundation-models-api@link:../../src-tauri/plugins/tauri-plugin-foundation-models::locator=%40janhq%2Ffoundation-models-extension%40workspace%3Afoundation-models-extension":+ version: 0.0.0-use.local+ resolution: "@janhq/tauri-plugin-foundation-models-api@link:../../src-tauri/plugins/tauri-plugin-foundation-models::locator=%40janhq%2Ffoundation-models-extension%40workspace%3Afoundation-models-extension"+ languageName: node+ linkType: soft+"@janhq/tauri-plugin-hardware-api@link:../../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fllamacpp-extension%40workspace%3Allamacpp-extension":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-hardware-api@link:../../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fllamacpp-extension%40workspace%3Allamacpp-extension"diff --git a/foundation-models-server/Package.swift b/foundation-models-server/Package.swiftnew file mode 100644index 000000000..d899a6925--- /dev/null+++ b/foundation-models-server/Package.swift@@ -0,0 +1,30 @@+// swift-tools-version: 6.2++import PackageDescription++let package = Package(+ name: "foundation-models-server",+ platforms: [+ .macOS(.v26)+ ],+ products: [+ .executable(name: "foundation-models-server", targets: ["FoundationModelsServer"])+ ],+ dependencies: [+ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"),+ .package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.19.0"),+ ],+ targets: [+ .executableTarget(+ name: "FoundationModelsServer",+ dependencies: [+ .product(name: "ArgumentParser", package: "swift-argument-parser"),+ .product(name: "Hummingbird", package: "hummingbird"),+ ],+ path: "Sources/FoundationModelsServer",+ swiftSettings: [+ .swiftLanguageMode(.v6)+ ]+ )+ ]+)diff --git a/foundation-models-server/README.md b/foundation-models-server/README.mdnew file mode 100644index 000000000..3d840b72c--- /dev/null+++ b/foundation-models-server/README.md@@ -0,0 +1,40 @@+# foundation-models-server++A lightweight OpenAI-compatible HTTP server that wraps Apple's Foundation Models framework, enabling Jan to use on-device Apple Intelligence models on macOS 26+.++## Requirements++- macOS 26 (Tahoe) or later+- Apple Silicon Mac with Apple Intelligence enabled+- Xcode 26 or later++## Building++```bash+swift build -c release+```++The binary will be at `.build/release/foundation-models-server`.++## Usage++```bash+# Check availability+foundation-models-server --check++# Start server on default port+foundation-models-server --port 8080++# Start server with API key+foundation-models-server --port 8080 --api-key <key>+```++## API++The server exposes an OpenAI-compatible API:++- `GET /health` — health check+- `GET /v1/models` — lists the `apple/on-device` model+- `POST /v1/chat/completions` — chat completions (streaming and non-streaming)++The model ID is always `apple/on-device`.diff --git a/foundation-models-server/Sources/FoundationModelsServer/FoundationModelsServerCommand.swift b/foundation-models-server/Sources/FoundationModelsServer/FoundationModelsServerCommand.swiftnew file mode 100644index 000000000..36d2d5ec8--- /dev/null+++ b/foundation-models-server/Sources/FoundationModelsServer/FoundationModelsServerCommand.swift@@ -0,0 +1,78 @@+import ArgumentParser+import Foundation+import Hummingbird+import FoundationModels++@main+struct FoundationModelsServerCommand: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "foundation-models-server",+ abstract: "Apple Foundation Models inference server with OpenAI-compatible API"+ )++ @Option(name: .long, help: "Port to listen on")+ var port: Int = 8080++ @Option(name: .long, help: "API key for authentication (optional)")+ var apiKey: String = ""++ @Flag(name: .long, help: "Check availability and exit with status 0 if available")+ var check: Bool = false++ func run() async throws {+ let availability = SystemLanguageModel.default.availability++ // In --check mode, always print a machine-readable status token and exit 0.+ // Callers (e.g. the Tauri plugin) parse this string to decide visibility.+ if check {+ switch availability {+ case .available:+ print("available")+ case .unavailable(.deviceNotEligible):+ print("notEligible")+ case .unavailable(.appleIntelligenceNotEnabled):+ print("appleIntelligenceNotEnabled")+ case .unavailable(.modelNotReady):+ print("modelNotReady")+ default:+ print("unavailable")+ }+ return+ }++ guard case .available = availability else {+ let reason: String+ switch availability {+ case .unavailable(.deviceNotEligible):+ reason = "Device is not eligible for Apple Intelligence"+ case .unavailable(.appleIntelligenceNotEnabled):+ reason = "Apple Intelligence is not enabled in System Settings"+ case .unavailable(.modelNotReady):+ reason = "Foundation model is downloading or not yet ready"+ default:+ reason = "Foundation model is unavailable on this system"+ }+ fputs("[foundation-models] ERROR: \(reason)\n", stderr)+ throw ExitCode(1)+ }++ log("[foundation-models] Foundation Models Server starting...")+ log("[foundation-models] Port: \(port)")++ let server = FoundationModelsHTTPServer(+ modelId: "apple/on-device",+ apiKey: apiKey+ )++ let router = server.buildRouter()+ let app = Application(+ router: router,+ configuration: .init(address: .hostname("127.0.0.1", port: port))+ )++ log("[foundation-models] http server listening on http://127.0.0.1:\(port)")+ log("[foundation-models] server is listening on 127.0.0.1:\(port)")++ try await app.run()+ }+}diff --git a/foundation-models-server/Sources/FoundationModelsServer/Logger.swift b/foundation-models-server/Sources/FoundationModelsServer/Logger.swiftnew file mode 100644index 000000000..34bb17517--- /dev/null+++ b/foundation-models-server/Sources/FoundationModelsServer/Logger.swift@@ -0,0 +1,6 @@+import Foundation++func log(_ message: String) {+ print(message)+ fflush(stdout)+}diff --git a/foundation-models-server/Sources/FoundationModelsServer/Server.swift b/foundation-models-server/Sources/FoundationModelsServer/Server.swiftnew file mode 100644index 000000000..b14eb3574--- /dev/null+++ b/foundation-models-server/Sources/FoundationModelsServer/Server.swift@@ -0,0 +1,299 @@+import Foundation+import Hummingbird+import FoundationModels++/// HTTP server exposing an OpenAI-compatible API backed by Apple Foundation Models+struct FoundationModelsHTTPServer: Sendable {+ let modelId: String+ let apiKey: String++ func buildRouter() -> Router<BasicRequestContext> {+ let router = Router()++ // Health check+ router.get("/health") { _, _ in+ let response = HealthResponse(status: "ok")+ return try encodeJSONResponse(response)+ }++ // List available models+ router.get("/v1/models") { _, _ in+ let response = ModelsListResponse(+ object: "list",+ data: [+ ModelData(+ id: self.modelId,+ object: "model",+ created: currentTimestamp(),+ owned_by: "apple"+ )+ ]+ )+ return try encodeJSONResponse(response)+ }++ // Chat completions (OpenAI-compatible)+ router.post("/v1/chat/completions") { request, _ in+ // Validate API key when configured+ if !self.apiKey.isEmpty {+ let authHeader = request.headers[.authorization]+ guard authHeader == "Bearer \(self.apiKey)" else {+ let errorResp = ErrorResponse(+ error: ErrorDetail(+ message: "Unauthorized: invalid or missing API key",+ type: "authentication_error",+ code: "unauthorized"+ )+ )+ return try Response(+ status: .unauthorized,+ headers: [.contentType: "application/json"],+ body: .init(byteBuffer: encodeJSONBuffer(errorResp))+ )+ }+ }++ let body = try await request.body.collect(upTo: 10 * 1024 * 1024)+ let chatRequest: ChatCompletionRequest+ do {+ chatRequest = try JSONDecoder().decode(ChatCompletionRequest.self, from: body)+ } catch {+ let errorResp = ErrorResponse(+ error: ErrorDetail(+ message: "Invalid request body: \(error.localizedDescription)",+ type: "invalid_request_error",+ code: nil+ )+ )+ return try Response(+ status: .badRequest,+ headers: [.contentType: "application/json"],+ body: .init(byteBuffer: encodeJSONBuffer(errorResp))+ )+ }+ let isStreaming = chatRequest.stream ?? false++ log("[foundation-models] Request: messages=\(chatRequest.messages.count), stream=\(isStreaming)")++ if isStreaming {+ return try await self.handleStreamingRequest(chatRequest)+ } else {+ return try await self.handleNonStreamingRequest(chatRequest)+ }+ }++ return router+ }++ // MARK: - Non-streaming++ private func handleNonStreamingRequest(_ chatRequest: ChatCompletionRequest) async throws -> Response {+ let session = buildSession(from: chatRequest.messages)+ let lastUserMessage = extractLastUserMessage(from: chatRequest.messages)++ let response = try await session.respond(to: lastUserMessage)+ let content = response.content++ let completionResponse = ChatCompletionResponse(+ id: "chatcmpl-\(UUID().uuidString)",+ object: "chat.completion",+ created: currentTimestamp(),+ model: modelId,+ choices: [+ ChatCompletionChoice(+ index: 0,+ message: ChatResponseMessage(role: "assistant", content: content),+ finish_reason: "stop"+ )+ ],+ usage: UsageInfo(+ prompt_tokens: 0,+ completion_tokens: 0,+ total_tokens: 0+ )+ )++ return try encodeJSONResponse(completionResponse)+ }++ // MARK: - Streaming++ private func handleStreamingRequest(_ chatRequest: ChatCompletionRequest) async throws -> Response {+ let requestId = "chatcmpl-\(UUID().uuidString)"+ let created = currentTimestamp()+ let modelId = self.modelId+ let messages = chatRequest.messages++ let (stream, continuation) = AsyncStream<ByteBuffer>.makeStream()++ let task = Task { [self] in+ do {+ let session = self.buildSession(from: messages)+ let lastUserMessage = self.extractLastUserMessage(from: messages)++ let roleDelta = ChatCompletionChunk(+ id: requestId,+ object: "chat.completion.chunk",+ created: created,+ model: modelId,+ choices: [+ ChunkChoice(+ index: 0,+ delta: DeltaContent(role: "assistant", content: nil),+ finish_reason: nil+ )+ ]+ )+ if let buffer = encodeSSEBuffer(roleDelta) {+ continuation.yield(buffer)+ }++ var previousText = ""+ for try await snapshot in session.streamResponse(to: lastUserMessage) {+ let currentText = snapshot.content+ let delta = String(currentText.dropFirst(previousText.count))+ previousText = currentText++ if delta.isEmpty { continue }++ let chunk = ChatCompletionChunk(+ id: requestId,+ object: "chat.completion.chunk",+ created: created,+ model: modelId,+ choices: [+ ChunkChoice(+ index: 0,+ delta: DeltaContent(role: nil, content: delta),+ finish_reason: nil+ )+ ]+ )+ if let buffer = encodeSSEBuffer(chunk) {+ continuation.yield(buffer)+ }+ }++ // Send stop chunk+ let stopChunk = ChatCompletionChunk(+ id: requestId,+ object: "chat.completion.chunk",+ created: created,+ model: modelId,+ choices: [+ ChunkChoice(+ index: 0,+ delta: DeltaContent(role: nil, content: nil),+ finish_reason: "stop"+ )+ ]+ )+ if let buffer = encodeSSEBuffer(stopChunk) {+ continuation.yield(buffer)+ }++ // SSE terminator+ var doneBuffer = ByteBufferAllocator().buffer(capacity: 16)+ doneBuffer.writeString("data: [DONE]\n\n")+ continuation.yield(doneBuffer)+ } catch {+ log("[foundation-models] Streaming error: \(error.localizedDescription)")+ var errBuffer = ByteBufferAllocator().buffer(capacity: 256)+ errBuffer.writeString("error: {\"message\":\"\(error.localizedDescription)\"}\n\n")+ continuation.yield(errBuffer)+ }+ continuation.finish()+ }++ // Cancel the generation task when the client disconnects+ continuation.onTermination = { @Sendable _ in+ log("[foundation-models] SSE continuation terminated by client disconnect")+ task.cancel()+ }++ return Response(+ status: .ok,+ headers: [+ .contentType: "text/event-stream",+ .cacheControl: "no-cache",+ .init("X-Accel-Buffering")!: "no"+ ],+ body: .init(asyncSequence: stream)+ )+ }++ // MARK: - Session Construction++ /// Build a `LanguageModelSession` from the OpenAI message list.+ ///+ /// System messages become the session instructions.+ /// Prior user/assistant turns are serialised into the instructions block so+ /// the model has full conversation context without re-running inference.+ /// (The Foundation Models `Transcript` API is not used for history injection+ /// because it is designed for observing an already-live session's state, not+ /// for priming a fresh one with arbitrary history.)+ private func buildSession(from messages: [ChatMessage]) -> LanguageModelSession {+ let systemContent = messages.first(where: { $0.role == "system" })?.content ?? ""+ let nonSystem = messages.filter { $0.role != "system" }+ let history = nonSystem.dropLast() // all turns except the last user message++ var instructionsText: String+ if systemContent.isEmpty {+ instructionsText = "You are a helpful assistant."+ } else {+ instructionsText = systemContent+ }++ // Append prior turns so the model understands conversation context+ if !history.isEmpty {+ instructionsText += "\n\n[Previous conversation]\n"+ for msg in history {+ let label = msg.role == "assistant" ? "Assistant" : "User"+ instructionsText += "\(label): \(msg.content ?? "")\n"+ }+ instructionsText += "[End of previous conversation]"+ }++ return LanguageModelSession(instructions: instructionsText)+ }++ private func extractLastUserMessage(from messages: [ChatMessage]) -> String {+ let nonSystem = messages.filter { $0.role != "system" }+ return nonSystem.last?.content ?? ""+ }+}++// MARK: - Helpers++private func currentTimestamp() -> Int {+ Int(Date().timeIntervalSince1970)+}++private func encodeJSONResponse<T: Encodable>(_ value: T) throws -> Response {+ let data = try JSONEncoder().encode(value)+ var buffer = ByteBufferAllocator().buffer(capacity: data.count)+ buffer.writeBytes(data)+ return Response(+ status: .ok,+ headers: [.contentType: "application/json"],+ body: .init(byteBuffer: buffer)+ )+}++private func encodeJSONBuffer<T: Encodable>(_ value: T) -> ByteBuffer {+ let data = (try? JSONEncoder().encode(value)) ?? Data()+ var buffer = ByteBufferAllocator().buffer(capacity: data.count)+ buffer.writeBytes(data)+ return buffer+}++private func encodeSSEBuffer<T: Encodable>(_ value: T) -> ByteBuffer? {+ guard let json = try? JSONEncoder().encode(value),+ let jsonString = String(data: json, encoding: .utf8) else {+ return nil+ }+ let line = "data: \(jsonString)\n\n"+ var buffer = ByteBufferAllocator().buffer(capacity: line.utf8.count)+ buffer.writeString(line)+ return buffer+}diff --git a/foundation-models-server/Sources/FoundationModelsServer/Types.swift b/foundation-models-server/Sources/FoundationModelsServer/Types.swiftnew file mode 100644index 000000000..86dc656f7--- /dev/null+++ b/foundation-models-server/Sources/FoundationModelsServer/Types.swift@@ -0,0 +1,98 @@+import Foundation++// MARK: - OpenAI Request Types++struct ChatCompletionRequest: Codable, Sendable {+ let model: String+ let messages: [ChatMessage]+ var temperature: Double?+ var top_p: Double?+ var max_tokens: Int?+ var n_predict: Int?+ var stream: Bool?+ var stop: [String]?+}++struct ChatMessage: Codable, Sendable {+ let role: String+ let content: String?+}++// MARK: - OpenAI Response Types++struct ChatCompletionResponse: Codable, Sendable {+ let id: String+ let object: String+ let created: Int+ let model: String+ let choices: [ChatCompletionChoice]+ let usage: UsageInfo+}++struct ChatCompletionChoice: Codable, Sendable {+ let index: Int+ let message: ChatResponseMessage+ let finish_reason: String+}++struct ChatResponseMessage: Codable, Sendable {+ let role: String+ let content: String+}++struct UsageInfo: Codable, Sendable {+ let prompt_tokens: Int+ let completion_tokens: Int+ let total_tokens: Int+}++// MARK: - Streaming Types++struct ChatCompletionChunk: Codable, Sendable {+ let id: String+ let object: String+ let created: Int+ let model: String+ let choices: [ChunkChoice]+}++struct ChunkChoice: Codable, Sendable {+ let index: Int+ let delta: DeltaContent+ let finish_reason: String?+}++struct DeltaContent: Codable, Sendable {+ let role: String?+ let content: String?+}++// MARK: - Model List Types++struct ModelsListResponse: Codable, Sendable {+ let object: String+ let data: [ModelData]+}++struct ModelData: Codable, Sendable {+ let id: String+ let object: String+ let created: Int+ let owned_by: String+}++// MARK: - Health / Error Types++struct HealthResponse: Codable, Sendable {+ let status: String+}++struct ErrorDetail: Codable, Sendable {+ let message: String+ let type: String+ let code: String?+}++struct ErrorResponse: Codable, Sendable {+ let error: ErrorDetail+}diff --git a/package.json b/package.jsonindex 1774e4d7e..842da4b7c 100644--- a/package.json+++ b/package.json@@ -31,10 +31,11 @@"download:lib": "node ./scripts/download-lib.mjs","download:bin": "node ./scripts/download-bin.mjs","build:mlx-server": "make build-mlx-server",+ "build:foundation-models-server": "make build-foundation-models-server","build:cli": "make build-cli","build:tauri:win32": "yarn download:bin && yarn build:cli && yarn tauri build","build:tauri:linux": "yarn download:bin && yarn build:cli && NO_STRIP=1 ./src-tauri/build-utils/shim-linuxdeploy.sh yarn tauri build && ./src-tauri/build-utils/buildAppImage.sh",- "build:tauri:darwin": "yarn download:bin && yarn build:mlx-server && yarn build:cli && yarn tauri build --target universal-apple-darwin",+ "build:tauri:darwin": "yarn download:bin && yarn build:mlx-server && yarn build:foundation-models-server && yarn build:cli && yarn tauri build --target universal-apple-darwin","build:tauri": "yarn build:icon && yarn copy:assets:tauri && run-script-os","build:tauri:plugin:api": "cd src-tauri/plugins && yarn install && yarn workspaces foreach -Apt run build","build:icon": "tauri icon ./src-tauri/icons/icon.png",@@ -42,8 +43,8 @@"build:web": "yarn workspace @janhq/web-app build","build:extensions": "rimraf ./pre-install/*.tgz || true && yarn workspace @janhq/core build && cd extensions && yarn install && cd .. && run-script-os","build:extensions:darwin": "cd extensions && yarn workspaces foreach -Apt run build:publish",- "build:extensions:win32": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension run build:publish",- "build:extensions:linux": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension run build:publish",+ "build:extensions:win32": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension --exclude @janhq/foundation-models-extension run build:publish",+ "build:extensions:linux": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension --exclude @janhq/foundation-models-extension run build:publish","prepare": "husky"},"devDependencies": {diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex ae0b090f0..7dab7692c 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -47,6 +47,7 @@ dependencies = ["tauri-build","tauri-plugin-deep-link","tauri-plugin-dialog",+ "tauri-plugin-foundation-models","tauri-plugin-hardware","tauri-plugin-http","tauri-plugin-llamacpp",@@ -6583,6 +6584,21 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-foundation-models"+version = "0.6.599"+dependencies = [+ "jan-utils",+ "log",+ "nix",+ "serde",+ "sysinfo",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.17",+ "tokio",+]+[[package]]name = "tauri-plugin-fs"version = "2.4.2"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 2e0aed686..ab3ad573c 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -34,11 +34,13 @@ default = [hardware = ["dep:tauri-plugin-hardware"]deep-link = ["dep:tauri-plugin-deep-link"]mlx = ["dep:tauri-plugin-mlx"]+foundation-models = ["dep:tauri-plugin-foundation-models"]docker = ["dep:bollard"]desktop = ["deep-link","hardware","mlx",+ "foundation-models","docker"]mobile = [@@ -95,6 +97,7 @@ tauri-plugin-deep-link = { version = "2", optional = true }tauri-plugin-hardware = { path = "./plugins/tauri-plugin-hardware", optional = true }tauri-plugin-llamacpp = { path = "./plugins/tauri-plugin-llamacpp" }tauri-plugin-mlx = { path = "./plugins/tauri-plugin-mlx", optional = true }+tauri-plugin-foundation-models = { path = "./plugins/tauri-plugin-foundation-models", optional = true }tauri-plugin-vector-db = { path = "./plugins/tauri-plugin-vector-db" }tauri-plugin-rag = { path = "./plugins/tauri-plugin-rag" }tauri-plugin-http = { version = "2", features = ["unsafe-headers"] }diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex b6a4eba7f..fbfb3bde6 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -30,6 +30,7 @@"deep-link:default","llamacpp:default","mlx:default",+ "foundation-models:default","updater:default","updater:allow-check",{diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.jsonindex cc49c6687..a4df1696d 100644--- a/src-tauri/capabilities/desktop.json+++ b/src-tauri/capabilities/desktop.json@@ -28,6 +28,7 @@"rag:default","llamacpp:default","mlx:default",+ "foundation-models:default","deep-link:default","hardware:default",{diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/.gitignore b/src-tauri/plugins/tauri-plugin-foundation-models/.gitignorenew file mode 100644index 000000000..5d3934a86--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/.gitignore@@ -0,0 +1,12 @@+/.vs+.DS_Store+package-lock.json+yarn.lock++/.tauri+/target+Cargo.lock+node_modules/++dist-js+distdiff --git a/src-tauri/plugins/tauri-plugin-foundation-models/Cargo.toml b/src-tauri/plugins/tauri-plugin-foundation-models/Cargo.tomlnew file mode 100644index 000000000..fc53de1ef--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/Cargo.toml@@ -0,0 +1,27 @@+[package]+name = "tauri-plugin-foundation-models"+version = "0.6.599"+authors = ["Jan <[email protected]>"]+description = "Tauri plugin for managing Apple Foundation Models server processes on macOS 26+"+license = "MIT"+repository = "https://github.com/janhq/jan"+edition = "2021"+rust-version = "1.77.2"+exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]+links = "tauri-plugin-foundation-models"++[dependencies]+log = "0.4"+serde = { version = "1.0", features = ["derive"] }+sysinfo = "0.34.2"+tauri = { version = "2.5.0", default-features = false, features = [] }+thiserror = "2.0.12"+tokio = { version = "1", features = ["full"] }+jan-utils = { path = "../../utils" }++# Unix-specific dependencies (macOS)+[target.'cfg(unix)'.dependencies]+nix = { version = "=0.30.1", features = ["signal", "process"] }++[build-dependencies]+tauri-plugin = { version = "2.3.1", features = ["build"] }diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/build.rs b/src-tauri/plugins/tauri-plugin-foundation-models/build.rsnew file mode 100644index 000000000..0667d6b3d--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/build.rs@@ -0,0 +1,15 @@+const COMMANDS: &[&str] = &[+ "cleanup_foundation_models_processes",+ "load_foundation_models_server",+ "unload_foundation_models_server",+ "is_foundation_models_process_running",+ "get_foundation_models_random_port",+ "find_foundation_models_session",+ "get_foundation_models_loaded",+ "get_foundation_models_all_sessions",+ "check_foundation_models_availability",+];++fn main() {+ tauri_plugin::Builder::new(COMMANDS).build();+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/index.tsnew file mode 100644index 000000000..014b019de--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/index.ts@@ -0,0 +1,64 @@+import { invoke } from '@tauri-apps/api/core'+import { SessionInfo, UnloadResult } from './types'++export { SessionInfo, UnloadResult } from './types'++export async function loadFoundationModelsServer(+ modelId: string,+ port: number,+ apiKey: string,+ timeout: number = 60+): Promise<SessionInfo> {+ return await invoke('plugin:foundation-models|load_foundation_models_server', {+ modelId,+ port,+ apiKey,+ timeout,+ })+}++export async function unloadFoundationModelsServer(+ pid: number+): Promise<UnloadResult> {+ return await invoke('plugin:foundation-models|unload_foundation_models_server', { pid })+}++export async function isFoundationModelsProcessRunning(+ pid: number+): Promise<boolean> {+ return await invoke('plugin:foundation-models|is_foundation_models_process_running', { pid })+}++export async function getFoundationModelsRandomPort(): Promise<number> {+ return await invoke('plugin:foundation-models|get_foundation_models_random_port')+}++export async function findFoundationModelsSession(): Promise<SessionInfo | null> {+ return await invoke('plugin:foundation-models|find_foundation_models_session')+}++export async function isFoundationModelsLoaded(): Promise<boolean> {+ return await invoke('plugin:foundation-models|get_foundation_models_loaded')+}++export async function getAllFoundationModelsSessions(): Promise<SessionInfo[]> {+ return await invoke('plugin:foundation-models|get_foundation_models_all_sessions')+}++export async function cleanupFoundationModelsProcesses(): Promise<void> {+ return await invoke('plugin:foundation-models|cleanup_foundation_models_processes')+}++/**+ * Run `foundation-models-server --check` and return a machine-readable+ * availability token. Possible values:+ * - `"available"` — device is eligible and ready+ * - `"notEligible"` — device does not support Apple Intelligence+ * - `"appleIntelligenceNotEnabled"` — Apple Intelligence disabled in Settings+ * - `"modelNotReady"` — model is still downloading+ * - `"unavailable"` — other unavailability reason+ * - `"binaryNotFound"` — server binary was not bundled (non-macOS build)+ */+export async function checkFoundationModelsAvailability(): Promise<string> {+ return await invoke('plugin:foundation-models|check_foundation_models_availability')+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/types.tsnew file mode 100644index 000000000..2d290125d--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/types.ts@@ -0,0 +1,11 @@+export interface SessionInfo {+ pid: number+ port: number+ model_id: string+ api_key: string+}++export interface UnloadResult {+ success: boolean+ error?: string+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/package.json b/src-tauri/plugins/tauri-plugin-foundation-models/package.jsonnew file mode 100644index 000000000..0fe5e7fc6--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/package.json@@ -0,0 +1,33 @@+{+ "name": "@janhq/tauri-plugin-foundation-models-api",+ "version": "0.6.599",+ "private": true,+ "description": "Tauri plugin API for Apple Foundation Models inference on macOS 26+",+ "type": "module",+ "types": "./dist-js/index.d.ts",+ "main": "./dist-js/index.cjs",+ "module": "./dist-js/index.js",+ "exports": {+ "types": "./dist-js/index.d.ts",+ "import": "./dist-js/index.js",+ "require": "./dist-js/index.cjs"+ },+ "files": [+ "dist-js",+ "README.md"+ ],+ "scripts": {+ "build": "rollup -c",+ "prepublishOnly": "yarn build",+ "pretest": "yarn build"+ },+ "dependencies": {+ "@tauri-apps/api": ">=2.0.0-beta.6"+ },+ "devDependencies": {+ "@rollup/plugin-typescript": "^12.0.0",+ "rollup": "^4.9.6",+ "tslib": "^2.6.2",+ "typescript": "^5.3.3"+ }+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/check_foundation_models_availability.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/check_foundation_models_availability.tomlnew file mode 100644index 000000000..7782714ac--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/check_foundation_models_availability.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-check-foundation-models-availability"+description = "Enables the check_foundation_models_availability command without any pre-configured scope."+commands.allow = ["check_foundation_models_availability"]++[[permission]]+identifier = "deny-check-foundation-models-availability"+description = "Denies the check_foundation_models_availability command without any pre-configured scope."+commands.deny = ["check_foundation_models_availability"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/cleanup_foundation_models_processes.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/cleanup_foundation_models_processes.tomlnew file mode 100644index 000000000..e8b16dcca--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/cleanup_foundation_models_processes.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-cleanup-foundation-models-processes"+description = "Enables the cleanup_foundation_models_processes command without any pre-configured scope."+commands.allow = ["cleanup_foundation_models_processes"]++[[permission]]+identifier = "deny-cleanup-foundation-models-processes"+description = "Denies the cleanup_foundation_models_processes command without any pre-configured scope."+commands.deny = ["cleanup_foundation_models_processes"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/find_foundation_models_session.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/find_foundation_models_session.tomlnew file mode 100644index 000000000..5f5da8609--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/find_foundation_models_session.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-find-foundation-models-session"+description = "Enables the find_foundation_models_session command without any pre-configured scope."+commands.allow = ["find_foundation_models_session"]++[[permission]]+identifier = "deny-find-foundation-models-session"+description = "Denies the find_foundation_models_session command without any pre-configured scope."+commands.deny = ["find_foundation_models_session"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_all_sessions.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_all_sessions.tomlnew file mode 100644index 000000000..276159846--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_all_sessions.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-foundation-models-all-sessions"+description = "Enables the get_foundation_models_all_sessions command without any pre-configured scope."+commands.allow = ["get_foundation_models_all_sessions"]++[[permission]]+identifier = "deny-get-foundation-models-all-sessions"+description = "Denies the get_foundation_models_all_sessions command without any pre-configured scope."+commands.deny = ["get_foundation_models_all_sessions"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_loaded.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_loaded.tomlnew file mode 100644index 000000000..99d2c0b96--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_loaded.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-foundation-models-loaded"+description = "Enables the get_foundation_models_loaded command without any pre-configured scope."+commands.allow = ["get_foundation_models_loaded"]++[[permission]]+identifier = "deny-get-foundation-models-loaded"+description = "Denies the get_foundation_models_loaded command without any pre-configured scope."+commands.deny = ["get_foundation_models_loaded"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_random_port.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_random_port.tomlnew file mode 100644index 000000000..eb310b423--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/get_foundation_models_random_port.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-foundation-models-random-port"+description = "Enables the get_foundation_models_random_port command without any pre-configured scope."+commands.allow = ["get_foundation_models_random_port"]++[[permission]]+identifier = "deny-get-foundation-models-random-port"+description = "Denies the get_foundation_models_random_port command without any pre-configured scope."+commands.deny = ["get_foundation_models_random_port"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/is_foundation_models_process_running.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/is_foundation_models_process_running.tomlnew file mode 100644index 000000000..e6d4d98e1--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/is_foundation_models_process_running.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-is-foundation-models-process-running"+description = "Enables the is_foundation_models_process_running command without any pre-configured scope."+commands.allow = ["is_foundation_models_process_running"]++[[permission]]+identifier = "deny-is-foundation-models-process-running"+description = "Denies the is_foundation_models_process_running command without any pre-configured scope."+commands.deny = ["is_foundation_models_process_running"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/load_foundation_models_server.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/load_foundation_models_server.tomlnew file mode 100644index 000000000..83ebad058--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/load_foundation_models_server.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-load-foundation-models-server"+description = "Enables the load_foundation_models_server command without any pre-configured scope."+commands.allow = ["load_foundation_models_server"]++[[permission]]+identifier = "deny-load-foundation-models-server"+description = "Denies the load_foundation_models_server command without any pre-configured scope."+commands.deny = ["load_foundation_models_server"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/unload_foundation_models_server.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/unload_foundation_models_server.tomlnew file mode 100644index 000000000..ba2859681--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/commands/unload_foundation_models_server.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-unload-foundation-models-server"+description = "Enables the unload_foundation_models_server command without any pre-configured scope."+commands.allow = ["unload_foundation_models_server"]++[[permission]]+identifier = "deny-unload-foundation-models-server"+description = "Denies the unload_foundation_models_server command without any pre-configured scope."+commands.deny = ["unload_foundation_models_server"]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/reference.mdnew file mode 100644index 000000000..3d12ef964--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/autogenerated/reference.md@@ -0,0 +1,259 @@+## Default Permission++Default permissions for the Foundation Models plugin++#### This default permission set includes the following:++- `allow-cleanup-foundation-models-processes`+- `allow-load-foundation-models-server`+- `allow-unload-foundation-models-server`+- `allow-is-foundation-models-process-running`+- `allow-get-foundation-models-random-port`+- `allow-find-foundation-models-session`+- `allow-get-foundation-models-loaded`+- `allow-get-foundation-models-all-sessions`+- `allow-check-foundation-models-availability`++## Permission Table++<table>+<tr>+<th>Identifier</th>+<th>Description</th>+</tr>+++<tr>+<td>++`foundation-models:allow-check-foundation-models-availability`++</td>+<td>++Enables the check_foundation_models_availability command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-check-foundation-models-availability`++</td>+<td>++Denies the check_foundation_models_availability command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-cleanup-foundation-models-processes`++</td>+<td>++Enables the cleanup_foundation_models_processes command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-cleanup-foundation-models-processes`++</td>+<td>++Denies the cleanup_foundation_models_processes command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-find-foundation-models-session`++</td>+<td>++Enables the find_foundation_models_session command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-find-foundation-models-session`++</td>+<td>++Denies the find_foundation_models_session command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-get-foundation-models-all-sessions`++</td>+<td>++Enables the get_foundation_models_all_sessions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-get-foundation-models-all-sessions`++</td>+<td>++Denies the get_foundation_models_all_sessions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-get-foundation-models-loaded`++</td>+<td>++Enables the get_foundation_models_loaded command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-get-foundation-models-loaded`++</td>+<td>++Denies the get_foundation_models_loaded command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-get-foundation-models-random-port`++</td>+<td>++Enables the get_foundation_models_random_port command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-get-foundation-models-random-port`++</td>+<td>++Denies the get_foundation_models_random_port command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-is-foundation-models-process-running`++</td>+<td>++Enables the is_foundation_models_process_running command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-is-foundation-models-process-running`++</td>+<td>++Denies the is_foundation_models_process_running command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-load-foundation-models-server`++</td>+<td>++Enables the load_foundation_models_server command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-load-foundation-models-server`++</td>+<td>++Denies the load_foundation_models_server command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:allow-unload-foundation-models-server`++</td>+<td>++Enables the unload_foundation_models_server command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`foundation-models:deny-unload-foundation-models-server`++</td>+<td>++Denies the unload_foundation_models_server command without any pre-configured scope.++</td>+</tr>+</table>diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/default.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/default.tomlnew file mode 100644index 000000000..51bfddcb8--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/default.toml@@ -0,0 +1,13 @@+[default]+description = "Default permissions for the Foundation Models plugin"+permissions = [+ "allow-cleanup-foundation-models-processes",+ "allow-load-foundation-models-server",+ "allow-unload-foundation-models-server",+ "allow-is-foundation-models-process-running",+ "allow-get-foundation-models-random-port",+ "allow-find-foundation-models-session",+ "allow-get-foundation-models-loaded",+ "allow-get-foundation-models-all-sessions",+ "allow-check-foundation-models-availability",+]diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/schemas/schema.jsonnew file mode 100644index 000000000..858d8817e--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/schemas/schema.json@@ -0,0 +1,414 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "PermissionFile",+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",+ "type": "object",+ "properties": {+ "default": {+ "description": "The default permission set for the plugin",+ "anyOf": [+ {+ "$ref": "#/definitions/DefaultPermission"+ },+ {+ "type": "null"+ }+ ]+ },+ "set": {+ "description": "A list of permissions sets defined",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionSet"+ }+ },+ "permission": {+ "description": "A list of inlined permissions",+ "default": [],+ "type": "array",+ "items": {+ "$ref": "#/definitions/Permission"+ }+ }+ },+ "definitions": {+ "DefaultPermission": {+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",+ "type": "object",+ "required": [+ "permissions"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionSet": {+ "description": "A set of direct permissions grouped together under a new name.",+ "type": "object",+ "required": [+ "description",+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does.",+ "type": "string"+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionKind"+ }+ }+ }+ },+ "Permission": {+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",+ "type": "object",+ "required": [+ "identifier"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "commands": {+ "description": "Allowed or denied commands when using this permission.",+ "default": {+ "allow": [],+ "deny": []+ },+ "allOf": [+ {+ "$ref": "#/definitions/Commands"+ }+ ]+ },+ "scope": {+ "description": "Allowed or denied scoped when using this permission.",+ "allOf": [+ {+ "$ref": "#/definitions/Scopes"+ }+ ]+ },+ "platforms": {+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "Commands": {+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Allowed command.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "deny": {+ "description": "Denied command, which takes priority.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "Scopes": {+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ },+ "PermissionKind": {+ "type": "string",+ "oneOf": [+ {+ "description": "Enables the check_foundation_models_availability command without any pre-configured scope.",+ "type": "string",+ "const": "allow-check-foundation-models-availability",+ "markdownDescription": "Enables the check_foundation_models_availability command without any pre-configured scope."+ },+ {+ "description": "Denies the check_foundation_models_availability command without any pre-configured scope.",+ "type": "string",+ "const": "deny-check-foundation-models-availability",+ "markdownDescription": "Denies the check_foundation_models_availability command without any pre-configured scope."+ },+ {+ "description": "Enables the cleanup_foundation_models_processes command without any pre-configured scope.",+ "type": "string",+ "const": "allow-cleanup-foundation-models-processes",+ "markdownDescription": "Enables the cleanup_foundation_models_processes command without any pre-configured scope."+ },+ {+ "description": "Denies the cleanup_foundation_models_processes command without any pre-configured scope.",+ "type": "string",+ "const": "deny-cleanup-foundation-models-processes",+ "markdownDescription": "Denies the cleanup_foundation_models_processes command without any pre-configured scope."+ },+ {+ "description": "Enables the find_foundation_models_session command without any pre-configured scope.",+ "type": "string",+ "const": "allow-find-foundation-models-session",+ "markdownDescription": "Enables the find_foundation_models_session command without any pre-configured scope."+ },+ {+ "description": "Denies the find_foundation_models_session command without any pre-configured scope.",+ "type": "string",+ "const": "deny-find-foundation-models-session",+ "markdownDescription": "Denies the find_foundation_models_session command without any pre-configured scope."+ },+ {+ "description": "Enables the get_foundation_models_all_sessions command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-foundation-models-all-sessions",+ "markdownDescription": "Enables the get_foundation_models_all_sessions command without any pre-configured scope."+ },+ {+ "description": "Denies the get_foundation_models_all_sessions command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-foundation-models-all-sessions",+ "markdownDescription": "Denies the get_foundation_models_all_sessions command without any pre-configured scope."+ },+ {+ "description": "Enables the get_foundation_models_loaded command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-foundation-models-loaded",+ "markdownDescription": "Enables the get_foundation_models_loaded command without any pre-configured scope."+ },+ {+ "description": "Denies the get_foundation_models_loaded command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-foundation-models-loaded",+ "markdownDescription": "Denies the get_foundation_models_loaded command without any pre-configured scope."+ },+ {+ "description": "Enables the get_foundation_models_random_port command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-foundation-models-random-port",+ "markdownDescription": "Enables the get_foundation_models_random_port command without any pre-configured scope."+ },+ {+ "description": "Denies the get_foundation_models_random_port command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-foundation-models-random-port",+ "markdownDescription": "Denies the get_foundation_models_random_port command without any pre-configured scope."+ },+ {+ "description": "Enables the is_foundation_models_process_running command without any pre-configured scope.",+ "type": "string",+ "const": "allow-is-foundation-models-process-running",+ "markdownDescription": "Enables the is_foundation_models_process_running command without any pre-configured scope."+ },+ {+ "description": "Denies the is_foundation_models_process_running command without any pre-configured scope.",+ "type": "string",+ "const": "deny-is-foundation-models-process-running",+ "markdownDescription": "Denies the is_foundation_models_process_running command without any pre-configured scope."+ },+ {+ "description": "Enables the load_foundation_models_server command without any pre-configured scope.",+ "type": "string",+ "const": "allow-load-foundation-models-server",+ "markdownDescription": "Enables the load_foundation_models_server command without any pre-configured scope."+ },+ {+ "description": "Denies the load_foundation_models_server command without any pre-configured scope.",+ "type": "string",+ "const": "deny-load-foundation-models-server",+ "markdownDescription": "Denies the load_foundation_models_server command without any pre-configured scope."+ },+ {+ "description": "Enables the unload_foundation_models_server command without any pre-configured scope.",+ "type": "string",+ "const": "allow-unload-foundation-models-server",+ "markdownDescription": "Enables the unload_foundation_models_server command without any pre-configured scope."+ },+ {+ "description": "Denies the unload_foundation_models_server command without any pre-configured scope.",+ "type": "string",+ "const": "deny-unload-foundation-models-server",+ "markdownDescription": "Denies the unload_foundation_models_server command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the Foundation Models plugin\n#### This default permission set includes:\n\n- `allow-cleanup-foundation-models-processes`\n- `allow-load-foundation-models-server`\n- `allow-unload-foundation-models-server`\n- `allow-is-foundation-models-process-running`\n- `allow-get-foundation-models-random-port`\n- `allow-find-foundation-models-session`\n- `allow-get-foundation-models-loaded`\n- `allow-get-foundation-models-all-sessions`\n- `allow-check-foundation-models-availability`",+ "type": "string",+ "const": "default",+ "markdownDescription": "Default permissions for the Foundation Models plugin\n#### This default permission set includes:\n\n- `allow-cleanup-foundation-models-processes`\n- `allow-load-foundation-models-server`\n- `allow-unload-foundation-models-server`\n- `allow-is-foundation-models-process-running`\n- `allow-get-foundation-models-random-port`\n- `allow-find-foundation-models-session`\n- `allow-get-foundation-models-loaded`\n- `allow-get-foundation-models-all-sessions`\n- `allow-check-foundation-models-availability`"+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/src-tauri/plugins/tauri-plugin-foundation-models/rollup.config.js b/src-tauri/plugins/tauri-plugin-foundation-models/rollup.config.jsnew file mode 100644index 000000000..8b4768ff6--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/rollup.config.js@@ -0,0 +1,31 @@+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { cwd } from 'node:process'+import typescript from '@rollup/plugin-typescript'++const pkg = JSON.parse(readFileSync(join(cwd(), 'package.json'), 'utf8'))++export default {+ input: 'guest-js/index.ts',+ output: [+ {+ file: pkg.exports.import,+ format: 'esm'+ },+ {+ file: pkg.exports.require,+ format: 'cjs'+ }+ ],+ plugins: [+ typescript({+ declaration: true,+ declarationDir: dirname(pkg.exports.import)+ })+ ],+ external: [+ /^@tauri-apps\/api/,+ ...Object.keys(pkg.dependencies || {}),+ ...Object.keys(pkg.peerDependencies || {})+ ]+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/cleanup.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/cleanup.rsnew file mode 100644index 000000000..425dceca2--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/src/cleanup.rs@@ -0,0 +1,70 @@+use tauri::{Manager, Runtime};++pub async fn cleanup_processes<R: Runtime>(app_handle: &tauri::AppHandle<R>) {+ let app_state = match app_handle.try_state::<crate::state::FoundationModelsState>() {+ Some(state) => state,+ None => {+ log::warn!("FoundationModelsState not found in app_handle");+ return;+ }+ };++ let mut map = app_state.sessions.lock().await;+ let pids: Vec<i32> = map.keys().cloned().collect();++ for pid in pids {+ if let Some(session) = map.remove(&pid) {+ let mut child = session.child;++ #[cfg(unix)]+ {+ use nix::sys::signal::{kill, Signal};+ use nix::unistd::Pid;+ use tokio::time::{timeout, Duration};++ if let Some(raw_pid) = child.id() {+ let raw_pid = raw_pid as i32;+ log::info!(+ "Sending SIGTERM to Foundation Models PID {} during shutdown",+ raw_pid+ );+ let _ = kill(Pid::from_raw(raw_pid), Signal::SIGTERM);++ match timeout(Duration::from_secs(2), child.wait()).await {+ Ok(Ok(status)) => log::info!(+ "Foundation Models process {} exited gracefully: {}",+ raw_pid,+ status+ ),+ Ok(Err(e)) => log::error!(+ "Error waiting after SIGTERM for Foundation Models PID {}: {}",+ raw_pid,+ e+ ),+ Err(_) => {+ log::warn!(+ "SIGTERM timed out for Foundation Models PID {}; sending SIGKILL",+ raw_pid+ );+ let _ = kill(Pid::from_raw(raw_pid), Signal::SIGKILL);+ let _ = child.wait().await;+ }+ }+ }+ }++ #[cfg(not(unix))]+ {+ let _ = child.kill().await;+ }+ }+ }+}++#[tauri::command]+pub async fn cleanup_foundation_models_processes<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<(), String> {+ cleanup_processes(&app_handle).await;+ Ok(())+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/commands.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/commands.rsnew file mode 100644index 000000000..eb114a25e--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/src/commands.rs@@ -0,0 +1,298 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;+use tauri::{Manager, Runtime, State};+use tokio::io::{AsyncBufReadExt, BufReader};+use tokio::time::Instant;++use crate::error::{ErrorCode, FoundationModelsError, ServerError, ServerResult};+use crate::process::{+ find_active_session, get_random_available_port, is_process_running_by_pid,+};+use crate::state::{FoundationModelsBackendSession, FoundationModelsState, SessionInfo};++#[cfg(unix)]+use crate::process::graceful_terminate_process;++#[derive(serde::Serialize, serde::Deserialize)]+pub struct UnloadResult {+ pub success: bool,+ pub error: Option<String>,+}++/// Start the Foundation Models server binary.+///+/// The binary is located at `binary_path` and is started with+/// the given `port` and optional `api_key`. Success is detected+/// by watching stdout for the ready signal within `timeout` seconds.+pub async fn load_foundation_models_server_impl(+ sessions_arc: std::sync::Arc<tokio::sync::Mutex<HashMap<i32, FoundationModelsBackendSession>>>,+ binary_path: &Path,+ model_id: String,+ port: u16,+ api_key: String,+ timeout: u64,+) -> ServerResult<SessionInfo> {+ let bin_path = PathBuf::from(binary_path);+ if !bin_path.exists() {+ return Err(FoundationModelsError::new(+ ErrorCode::BinaryNotFound,+ format!(+ "foundation-models-server binary not found at: {}",+ binary_path.display()+ ),+ None,+ )+ .into());+ }++ let mut args = vec!["--port".to_string(), port.to_string()];+ if !api_key.is_empty() {+ args.push("--api-key".to_string());+ args.push(api_key.clone());+ }++ log::info!("Launching Foundation Models server: {:?} {:?}", bin_path, args);++ let mut child = tokio::process::Command::new(&bin_path)+ .args(&args)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| ServerError::Io(e))?;++ let pid = child.id().unwrap_or(0) as i32;+ let stdout = child.stdout.take().expect("stdout not captured");+ let stderr = child.stderr.take().expect("stderr not captured");++ // Watch stderr for error messages+ let (stderr_tx, mut stderr_rx) = tokio::sync::mpsc::channel::<String>(64);+ tokio::spawn(async move {+ let mut reader = BufReader::new(stderr).lines();+ while let Ok(Some(line)) = reader.next_line().await {+ log::error!("[foundation-models stderr] {}", line);+ let _ = stderr_tx.send(line).await;+ }+ });++ // Watch stdout for the readiness signal+ let (ready_tx, mut ready_rx) = tokio::sync::mpsc::channel::<bool>(1);+ tokio::spawn(async move {+ let mut reader = BufReader::new(stdout).lines();+ while let Ok(Some(line)) = reader.next_line().await {+ log::info!("[foundation-models] {}", line);+ if line.contains("server is listening on") || line.contains("http server listening") {+ let _ = ready_tx.send(true).await;+ }+ }+ });++ let deadline = Instant::now() + Duration::from_secs(timeout);++ loop {+ tokio::select! {+ _ = tokio::time::sleep_until(deadline) => {+ log::error!("Foundation Models server startup timed out after {}s", timeout);+ // Terminate the process+ #[cfg(unix)]+ graceful_terminate_process(&mut child).await;+ #[cfg(not(unix))]+ let _ = child.kill().await;++ return Err(FoundationModelsError::new(+ ErrorCode::ServerStartTimedOut,+ format!(+ "Foundation Models server did not become ready within {} seconds.",+ timeout+ ),+ None,+ )+ .into());+ }++ ready = ready_rx.recv() => {+ if ready == Some(true) {+ log::info!("Foundation Models server ready on port {}", port);+ let session_info = SessionInfo {+ pid,+ port: port as i32,+ model_id: model_id.clone(),+ api_key: api_key.clone(),+ };+ let backend_session = FoundationModelsBackendSession {+ child,+ info: session_info.clone(),+ };+ sessions_arc.lock().await.insert(pid, backend_session);+ return Ok(session_info);+ }+ }++ stderr_line = stderr_rx.recv() => {+ if let Some(line) = stderr_line {+ if line.contains("[foundation-models] ERROR:") {+ // The availability check failed; terminate immediately+ #[cfg(unix)]+ graceful_terminate_process(&mut child).await;+ #[cfg(not(unix))]+ let _ = child.kill().await;++ return Err(FoundationModelsError::from_stderr(&line).into());+ }+ }+ }++ status = child.wait() => {+ // Process exited prematurely+ let code = match status {+ Ok(s) => s.code().unwrap_or(-1),+ Err(_) => -1,+ };+ log::error!("Foundation Models server exited prematurely with code {}", code);+ return Err(FoundationModelsError::new(+ ErrorCode::ServerStartFailed,+ format!(+ "Foundation Models server exited with code {} before becoming ready. \+ Ensure Apple Intelligence is enabled in System Settings.",+ code+ ),+ None,+ )+ .into());+ }+ }+ }+}++// ─── Tauri commands ──────────────────────────────────────────────────────────++#[tauri::command]+pub async fn load_foundation_models_server<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ model_id: String,+ port: u16,+ api_key: String,+ timeout: u64,+) -> Result<SessionInfo, ServerError> {+ let state: State<FoundationModelsState> = app_handle.state();++ let resource_dir = app_handle+ .path()+ .resource_dir()+ .map_err(ServerError::Tauri)?;+ let binary_path = resource_dir.join("resources/bin/foundation-models-server");++ load_foundation_models_server_impl(+ state.sessions.clone(),+ &binary_path,+ model_id,+ port,+ api_key,+ timeout,+ )+ .await+}++#[tauri::command]+pub async fn unload_foundation_models_server<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ pid: i32,+) -> Result<UnloadResult, ServerError> {+ let state: State<FoundationModelsState> = app_handle.state();+ let mut map = state.sessions.lock().await;++ if let Some(session) = map.remove(&pid) {+ let mut child = session.child;+ #[cfg(unix)]+ graceful_terminate_process(&mut child).await;+ #[cfg(not(unix))]+ let _ = child.kill().await;++ log::info!("Successfully unloaded Foundation Models server PID {}", pid);+ Ok(UnloadResult {+ success: true,+ error: None,+ })+ } else {+ Ok(UnloadResult {+ success: false,+ error: Some(format!("No active Foundation Models session found for PID {}", pid)),+ })+ }+}++#[tauri::command]+pub async fn is_foundation_models_process_running<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ pid: i32,+) -> Result<bool, String> {+ is_process_running_by_pid(app_handle, pid).await+}++#[tauri::command]+pub async fn get_foundation_models_random_port<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<u16, String> {+ get_random_available_port(app_handle).await+}++#[tauri::command]+pub async fn find_foundation_models_session<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<Option<SessionInfo>, String> {+ Ok(find_active_session(app_handle).await)+}++#[tauri::command]+pub async fn get_foundation_models_loaded<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<bool, String> {+ Ok(find_active_session(app_handle).await.is_some())+}++#[tauri::command]+pub async fn get_foundation_models_all_sessions<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<Vec<SessionInfo>, String> {+ let state: State<FoundationModelsState> = app_handle.state();+ let map = state.sessions.lock().await;+ Ok(map.values().map(|s| s.info.clone()).collect())+}++/// Run the server binary with `--check` and return a machine-readable+/// availability token: `"available"`, `"notEligible"`,+/// `"appleIntelligenceNotEnabled"`, `"modelNotReady"`, `"unavailable"`,+/// or `"binaryNotFound"` if the binary is missing.+///+/// Always returns `Ok` — the caller decides what to do with the status.+#[tauri::command]+pub async fn check_foundation_models_availability<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<String, String> {+ let resource_dir = app_handle+ .path()+ .resource_dir()+ .map_err(|e| e.to_string())?;+ let binary_path = resource_dir.join("resources/bin/foundation-models-server");++ if !binary_path.exists() {+ return Ok("binaryNotFound".to_string());+ }++ let output = tokio::process::Command::new(&binary_path)+ .arg("--check")+ .output()+ .await+ .map_err(|e| e.to_string())?;++ let status = String::from_utf8_lossy(&output.stdout)+ .trim()+ .to_string();++ if status.is_empty() {+ Ok("unavailable".to_string())+ } else {+ Ok(status)+ }+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/error.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/error.rsnew file mode 100644index 000000000..651cc7251--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/src/error.rs@@ -0,0 +1,107 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum ErrorCode {+ BinaryNotFound,+ FoundationModelsUnavailable,+ ServerStartFailed,+ ServerStartTimedOut,+ ProcessError,+ IoError,+ InternalError,+}++#[derive(Debug, Clone, Serialize, thiserror::Error)]+#[error("FoundationModelsError {{ code: {code:?}, message: \"{message}\" }}")]+pub struct FoundationModelsError {+ pub code: ErrorCode,+ pub message: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub details: Option<String>,+}++impl FoundationModelsError {+ pub fn new(code: ErrorCode, message: String, details: Option<String>) -> Self {+ Self {+ code,+ message,+ details,+ }+ }++ /// Interpret stderr output from the server binary and produce a descriptive error.+ pub fn from_stderr(stderr: &str) -> Self {+ let lower = stderr.to_lowercase();++ if lower.contains("device is not eligible")+ || lower.contains("devicenoteligible")+ {+ return Self::new(+ ErrorCode::FoundationModelsUnavailable,+ "This device is not eligible for Apple Intelligence.".into(),+ Some(stderr.into()),+ );+ }++ if lower.contains("apple intelligence is not enabled")+ || lower.contains("appleintelligencenotenabled")+ {+ return Self::new(+ ErrorCode::FoundationModelsUnavailable,+ "Apple Intelligence is not enabled. Please enable it in System Settings → Apple Intelligence & Siri.".into(),+ Some(stderr.into()),+ );+ }++ if lower.contains("model not ready") || lower.contains("modelnotready") {+ return Self::new(+ ErrorCode::FoundationModelsUnavailable,+ "The Foundation Model is still downloading or not yet ready. Please wait and try again.".into(),+ Some(stderr.into()),+ );+ }++ Self::new(+ ErrorCode::ProcessError,+ "The Foundation Models server encountered an unexpected error.".into(),+ Some(stderr.into()),+ )+ }+}++#[derive(Debug, thiserror::Error)]+pub enum ServerError {+ #[error(transparent)]+ FoundationModels(#[from] FoundationModelsError),++ #[error("IO error: {0}")]+ Io(#[from] std::io::Error),++ #[error("Tauri error: {0}")]+ Tauri(#[from] tauri::Error),+}++impl serde::Serialize for ServerError {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ let err = match self {+ ServerError::FoundationModels(e) => e.clone(),+ ServerError::Io(e) => FoundationModelsError::new(+ ErrorCode::IoError,+ "An input/output error occurred.".into(),+ Some(e.to_string()),+ ),+ ServerError::Tauri(e) => FoundationModelsError::new(+ ErrorCode::InternalError,+ "A Tauri internal error occurred.".into(),+ Some(e.to_string()),+ ),+ };+ err.serialize(serializer)+ }+}++pub type ServerResult<T> = Result<T, ServerError>;diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/lib.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/lib.rsnew file mode 100644index 000000000..2a07185d9--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/src/lib.rs@@ -0,0 +1,34 @@+use tauri::{+ plugin::{Builder, TauriPlugin},+ Manager, Runtime,+};++pub mod cleanup;+mod commands;+mod error;+mod process;+pub mod state;++pub use cleanup::cleanup_processes;+pub use state::FoundationModelsState;++/// Initializes the Foundation Models plugin.+pub fn init<R: Runtime>() -> TauriPlugin<R> {+ Builder::new("foundation-models")+ .invoke_handler(tauri::generate_handler![+ cleanup::cleanup_foundation_models_processes,+ commands::load_foundation_models_server,+ commands::unload_foundation_models_server,+ commands::is_foundation_models_process_running,+ commands::get_foundation_models_random_port,+ commands::find_foundation_models_session,+ commands::get_foundation_models_loaded,+ commands::get_foundation_models_all_sessions,+ commands::check_foundation_models_availability,+ ])+ .setup(|app, _api| {+ app.manage(state::FoundationModelsState::new());+ Ok(())+ })+ .build()+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/process.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/process.rsnew file mode 100644index 000000000..7dab56f08--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/src/process.rs@@ -0,0 +1,102 @@+use std::collections::HashSet;+use sysinfo::{Pid, System};+use tauri::{Manager, Runtime, State};++use crate::state::{FoundationModelsState, SessionInfo};+use jan_utils::generate_random_port;++/// Returns true if the process with the given PID is still running.+/// Removes the session from state if the process has exited.+pub async fn is_process_running_by_pid<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ pid: i32,+) -> Result<bool, String> {+ let mut system = System::new();+ system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);+ let alive = system.process(Pid::from(pid as usize)).is_some();++ if !alive {+ let state: State<FoundationModelsState> = app_handle.state();+ let mut map = state.sessions.lock().await;+ map.remove(&pid);+ }++ Ok(alive)+}++/// Returns a random available port that is not used by any active session.+pub async fn get_random_available_port<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<u16, String> {+ let state: State<FoundationModelsState> = app_handle.state();+ let map = state.sessions.lock().await;++ let used_ports: HashSet<u16> = map+ .values()+ .filter_map(|s| {+ if s.info.port > 0 && s.info.port <= u16::MAX as i32 {+ Some(s.info.port as u16)+ } else {+ None+ }+ })+ .collect();++ drop(map);+ generate_random_port(&used_ports)+}++/// Returns the SessionInfo for the only expected active session (if any).+pub async fn find_active_session<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Option<SessionInfo> {+ let state: State<FoundationModelsState> = app_handle.state();+ let map = state.sessions.lock().await;+ map.values().next().map(|s| s.info.clone())+}++/// Gracefully terminate a process on Unix (macOS).+#[cfg(unix)]+pub async fn graceful_terminate_process(child: &mut tokio::process::Child) {+ use nix::sys::signal::{kill, Signal};+ use nix::unistd::Pid;+ use std::time::Duration;+ use tokio::time::timeout;++ if let Some(raw_pid) = child.id() {+ let raw_pid = raw_pid as i32;+ log::info!(+ "Sending SIGTERM to Foundation Models PID {}",+ raw_pid+ );+ let _ = kill(Pid::from_raw(raw_pid), Signal::SIGTERM);++ match timeout(Duration::from_secs(5), child.wait()).await {+ Ok(Ok(status)) => log::info!(+ "Foundation Models process {} exited gracefully: {}",+ raw_pid,+ status+ ),+ Ok(Err(e)) => log::error!(+ "Error waiting after SIGTERM for Foundation Models PID {}: {}",+ raw_pid,+ e+ ),+ Err(_) => {+ log::warn!(+ "SIGTERM timed out for Foundation Models PID {}; sending SIGKILL",+ raw_pid+ );+ let _ = kill(Pid::from_raw(raw_pid), Signal::SIGKILL);+ match child.wait().await {+ Ok(s) => log::info!("Force-killed Foundation Models process: {}", s),+ Err(e) => log::error!(+ "Error waiting after SIGKILL for Foundation Models PID {}: {}",+ raw_pid,+ e+ ),+ }+ }+ }+ }+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/state.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/state.rsnew file mode 100644index 000000000..216c02682--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/src/state.rs@@ -0,0 +1,38 @@+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::sync::Arc;+use tokio::process::Child;+use tokio::sync::Mutex;++/// Session information for a running Foundation Models server instance+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SessionInfo {+ pub pid: i32,+ pub port: i32,+ pub model_id: String,+ pub api_key: String,+}++pub struct FoundationModelsBackendSession {+ pub child: Child,+ pub info: SessionInfo,+}++/// Plugin state — tracks all active server processes keyed by PID+pub struct FoundationModelsState {+ pub sessions: Arc<Mutex<HashMap<i32, FoundationModelsBackendSession>>>,+}++impl Default for FoundationModelsState {+ fn default() -> Self {+ Self {+ sessions: Arc::new(Mutex::new(HashMap::new())),+ }+ }+}++impl FoundationModelsState {+ pub fn new() -> Self {+ Self::default()+ }+}diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/tsconfig.json b/src-tauri/plugins/tauri-plugin-foundation-models/tsconfig.jsonnew file mode 100644index 000000000..059112270--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-foundation-models/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "es2021",+ "module": "esnext",+ "moduleResolution": "bundler",+ "skipLibCheck": true,+ "strict": true,+ "noUnusedLocals": true,+ "noImplicitAny": true,+ "noEmit": true+ },+ "include": ["guest-js/*.ts"],+ "exclude": ["dist-js", "node_modules"]+}diff --git a/src-tauri/plugins/yarn.lock b/src-tauri/plugins/yarn.lockindex ec6cad55b..8a524ef9f 100644--- a/src-tauri/plugins/yarn.lock+++ b/src-tauri/plugins/yarn.lock@@ -28,6 +28,18 @@ __metadata:languageName: nodelinkType: hard+"@janhq/tauri-plugin-foundation-models-api@workspace:tauri-plugin-foundation-models":+ version: 0.0.0-use.local+ resolution: "@janhq/tauri-plugin-foundation-models-api@workspace:tauri-plugin-foundation-models"+ dependencies:+ "@rollup/plugin-typescript": "npm:^12.0.0"+ "@tauri-apps/api": "npm:>=2.0.0-beta.6"+ rollup: "npm:^4.9.6"+ tslib: "npm:^2.6.2"+ typescript: "npm:^5.3.3"+ languageName: unknown+ linkType: soft+"@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware"diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 94be650bc..786f3a6ab 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -57,6 +57,11 @@ pub fn run() {app_builder = app_builder.plugin(tauri_plugin_mlx::init());}+ #[cfg(feature = "foundation-models")]+ {+ app_builder = app_builder.plugin(tauri_plugin_foundation_models::init());+ }+#[cfg(not(any(target_os = "android", target_os = "ios")))]{app_builder = app_builder.plugin(tauri_plugin_hardware::init());@@ -457,6 +462,13 @@ pub fn run() {}}+ #[cfg(feature = "foundation-models")]+ {+ use tauri_plugin_foundation_models::cleanup_processes;+ cleanup_processes(&app_handle).await;+ log::info!("Foundation Models processes cleaned up successfully");+ }+// OpenClaw gateway cleanup{use crate::core::openclaw::sandbox::Sandbox;diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.jsonindex b9af1ca13..fc43f3f26 100644--- a/src-tauri/tauri.macos.conf.json+++ b/src-tauri/tauri.macos.conf.json@@ -30,7 +30,7 @@},"bundle": {"targets": ["app", "dmg"],- "resources": ["resources/pre-install/**/*", "resources/LICENSE", "resources/bin/mlx-server", "resources/bin/mlx-swift_Cmlx.bundle", "resources/bin/jan-cli"],+ "resources": ["resources/pre-install/**/*", "resources/LICENSE", "resources/bin/mlx-server", "resources/bin/mlx-swift_Cmlx.bundle", "resources/bin/foundation-models-server", "resources/bin/jan-cli"],"externalBin": ["resources/bin/bun", "resources/bin/uv"],"macOS": {"entitlements": "./Entitlements.plist"diff --git a/web-app/src/lib/__tests__/model-factory.test.ts b/web-app/src/lib/__tests__/model-factory.test.tsindex 7d6d939bf..fa2c0e617 100644--- a/web-app/src/lib/__tests__/model-factory.test.ts+++ b/web-app/src/lib/__tests__/model-factory.test.ts@@ -1,19 +1,33 @@import { describe, it, expect, vi, beforeEach } from 'vitest'import { ModelFactory } from '../model-factory'import type { ProviderObject } from '@janhq/core'+import { invoke } from '@tauri-apps/api/core'// Mock the Tauri invoke functionvi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn(),}))-// Mock the AI SDK providers-vi.mock('@ai-sdk/openai-compatible', () => ({- createOpenAICompatible: vi.fn(() => ({- languageModel: vi.fn(() => ({ type: 'openai-compatible' })),- })),+// Mock the Tauri HTTP plugin+vi.mock('@tauri-apps/plugin-http', () => ({+ fetch: vi.fn(),}))+// Mock the AI SDK providers+vi.mock('@ai-sdk/openai-compatible', () => {+ const MockChatModel = vi.fn().mockImplementation(() => ({+ type: 'foundation-models',+ modelId: 'apple/on-device',+ }))+ return {+ createOpenAICompatible: vi.fn(() => ({+ languageModel: vi.fn(() => ({ type: 'openai-compatible' })),+ })),+ OpenAICompatibleChatLanguageModel: MockChatModel,+ MetadataExtractor: vi.fn(),+ }+})+vi.mock('@ai-sdk/anthropic', () => ({createAnthropic: vi.fn(() => vi.fn(() => ({ type: 'anthropic' }))),}))@@ -22,9 +36,29 @@ vi.mock('@ai-sdk/google', () => ({createGoogleGenerativeAI: vi.fn(() => vi.fn(() => ({ type: 'google' }))),}))+vi.mock('ai', () => ({+ wrapLanguageModel: vi.fn(({ model }) => model),+ extractReasoningMiddleware: vi.fn(() => ({})),+}))++const mockStartModel = vi.fn().mockResolvedValue(undefined)++vi.mock('@/hooks/useServiceHub', () => ({+ useServiceStore: {+ getState: () => ({+ serviceHub: {+ models: () => ({ startModel: mockStartModel }),+ },+ }),+ },+}))++const mockedInvoke = vi.mocked(invoke)+describe('ModelFactory', () => {beforeEach(() => {vi.clearAllMocks()+ mockStartModel.mockResolvedValue(undefined)})describe('createModel', () => {@@ -123,4 +157,106 @@ describe('ModelFactory', () => {expect(model.type).toBe('openai-compatible')})})++ describe('foundation-models provider', () => {+ const foundationModelsProvider: ProviderObject = {+ provider: 'foundation-models',+ models: [],+ settings: [],+ active: true,+ }++ it('should throw with notEligible message when device is not eligible', async () => {+ mockedInvoke.mockResolvedValueOnce('notEligible')++ await expect(+ ModelFactory.createModel('apple/on-device', foundationModelsProvider)+ ).rejects.toThrow(+ 'Apple Intelligence is not supported on this device. An Apple Silicon Mac (M1 or later) with macOS 26+ is required.'+ )++ expect(mockedInvoke).toHaveBeenCalledWith(+ 'plugin:foundation-models|check_foundation_models_availability',+ {}+ )+ })++ it('should throw when Apple Intelligence is not enabled', async () => {+ mockedInvoke.mockResolvedValueOnce('appleIntelligenceNotEnabled')++ await expect(+ ModelFactory.createModel('apple/on-device', foundationModelsProvider)+ ).rejects.toThrow(+ 'Apple Intelligence is not enabled. Please enable it in System Settings > Apple Intelligence & Siri.'+ )+ })++ it('should throw when the model is not ready', async () => {+ mockedInvoke.mockResolvedValueOnce('modelNotReady')++ await expect(+ ModelFactory.createModel('apple/on-device', foundationModelsProvider)+ ).rejects.toThrow(+ 'The Apple on-device model is still preparing. Please wait and try again shortly.'+ )+ })++ it('should throw when the server binary is missing', async () => {+ mockedInvoke.mockResolvedValueOnce('binaryNotFound')++ await expect(+ ModelFactory.createModel('apple/on-device', foundationModelsProvider)+ ).rejects.toThrow(+ 'The Foundation Models server binary is missing. Please reinstall Jan.'+ )+ })++ it('should throw with generic unavailable message for unknown status', async () => {+ mockedInvoke.mockResolvedValueOnce('unavailable')++ await expect(+ ModelFactory.createModel('apple/on-device', foundationModelsProvider)+ ).rejects.toThrow(+ 'Apple Foundation Models are currently unavailable on this device.'+ )+ })++ it('should throw when available but no session is found after start', async () => {+ mockedInvoke+ .mockResolvedValueOnce('available') // check_foundation_models_availability+ .mockResolvedValueOnce(null) // find_foundation_models_session++ await expect(+ ModelFactory.createModel('apple/on-device', foundationModelsProvider)+ ).rejects.toThrow(+ 'No running Foundation Models session. The server may have failed to start'+ )+ })++ it('should create a model when available and session exists', async () => {+ mockedInvoke+ .mockResolvedValueOnce('available') // check_foundation_models_availability+ .mockResolvedValueOnce({ // find_foundation_models_session+ pid: 12345,+ port: 9876,+ model_id: 'apple/on-device',+ api_key: 'test-session-key',+ })++ const model = await ModelFactory.createModel(+ 'apple/on-device',+ foundationModelsProvider+ )++ expect(model).toBeDefined()+ expect(mockedInvoke).toHaveBeenCalledWith(+ 'plugin:foundation-models|check_foundation_models_availability',+ {}+ )+ expect(mockedInvoke).toHaveBeenCalledWith(+ 'plugin:foundation-models|find_foundation_models_session',+ {}+ )+ })+ })})diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsindex bb67f74d6..57705fc72 100644--- a/web-app/src/lib/model-factory.ts+++ b/web-app/src/lib/model-factory.ts@@ -164,6 +164,9 @@ export class ModelFactory {case 'mlx':return this.createMlxModel(modelId, provider, parameters)+ case 'foundation-models':+ return this.createFoundationModelsModel(modelId, provider, parameters)+case 'anthropic':return this.createAnthropicModel(modelId, provider)@@ -344,6 +347,88 @@ export class ModelFactory {})}+ /**+ * Create a Foundation Models model (Apple on-device) by starting the local+ * Swift server via the Tauri plugin and connecting over localhost.+ */+ private static async createFoundationModelsModel(+ modelId: string,+ provider?: ProviderObject,+ parameters: Record<string, unknown> = {}+ ): Promise<LanguageModel> {+ const availability = await invoke<string>(+ 'plugin:foundation-models|check_foundation_models_availability',+ {}+ )++ if (availability !== 'available') {+ const messages: Record<string, string> = {+ notEligible:+ 'Apple Intelligence is not supported on this device. An Apple Silicon Mac (M1 or later) with macOS 26+ is required.',+ appleIntelligenceNotEnabled:+ 'Apple Intelligence is not enabled. Please enable it in System Settings > Apple Intelligence & Siri.',+ modelNotReady:+ 'The Apple on-device model is still preparing. Please wait and try again shortly.',+ binaryNotFound:+ 'The Foundation Models server binary is missing. Please reinstall Jan.',+ unavailable:+ 'Apple Foundation Models are currently unavailable on this device.',+ }+ throw new Error(messages[availability] ?? messages.unavailable)+ }++ if (provider) {+ try {+ const { useServiceStore } = await import('@/hooks/useServiceHub')+ const serviceHub = useServiceStore.getState().serviceHub++ if (serviceHub) {+ await serviceHub.models().startModel(provider, modelId)+ }+ } catch (error) {+ console.error('Failed to start Foundation Models:', error)+ throw new Error(+ `Failed to start model: ${error instanceof Error ? error.message : JSON.stringify(error)}`+ )+ }+ }++ const sessionInfo = await invoke<SessionInfo | null>(+ 'plugin:foundation-models|find_foundation_models_session',+ {}+ )++ if (!sessionInfo) {+ throw new Error(+ 'No running Foundation Models session. The server may have failed to start — please check the logs.'+ )+ }++ const baseUrl = `http://localhost:${sessionInfo.port}`+ const authHeaders = {+ Authorization: `Bearer ${sessionInfo.api_key}`,+ Origin: 'tauri://localhost',+ }++ const customFetch = createCustomFetch(httpFetch, parameters)++ const model = new OpenAICompatibleChatLanguageModel(modelId, {+ provider: 'foundation-models',+ headers: () => authHeaders,+ url: ({ path }) => new URL(`${baseUrl}/v1${path}`).toString(),+ fetch: customFetch,+ metadataExtractor: providerMetadataExtractor,+ })++ return wrapLanguageModel({+ model,+ middleware: extractReasoningMiddleware({+ tagName: 'think',+ separator: '\n',+ }),+ })+ }+/*** Create an Anthropic model using the official AI SDK*/diff --git a/yarn.lock b/yarn.lockindex 1e8f60ef4..cc2ba1284 100644--- a/yarn.lock+++ b/yarn.lock@@ -2824,6 +2824,7 @@ __metadata:"@types/istanbul-reports": "npm:3.0.4""@types/lodash.clonedeep": "npm:4.5.9""@types/lodash.debounce": "npm:4.0.9"+ "@types/matter-js": "npm:^0""@types/mdast": "npm:^4.0.4""@types/node": "npm:22.14.1""@types/react": "npm:19.1.2"@@ -2856,7 +2857,8 @@ __metadata:lodash.clonedeep: "npm:4.5.0"lodash.debounce: "npm:4.0.8"lucide-react: "npm:^0.563.0"- motion: "npm:^12.29.2"+ matter-js: "npm:^0.20.0"+ motion: "npm:^12.35.0"next-themes: "npm:0.4.6"posthog-js: "npm:1.255.1"radix-ui: "npm:^1.4.3"@@ -6932,6 +6934,13 @@ __metadata:languageName: nodelinkType: hard+"@types/matter-js@npm:^0":+ version: 0.20.2+ resolution: "@types/matter-js@npm:0.20.2"+ checksum: 10c0/da953eb54e3c0595ee4d9c36a95568161d41bdc42ae6fca0d479c0f0855e84c92925059d4bdb64a03d16ee5b7eca55af645bd26d2dfc581d574a42519ff1d345+ languageName: node+ linkType: hard+"@types/mdast@npm:^4.0.0, @types/mdast@npm:^4.0.4":version: 4.0.4resolution: "@types/mdast@npm:4.0.4"@@ -11167,6 +11176,28 @@ __metadata:languageName: nodelinkType: hard+"framer-motion@npm:^12.36.0":+ version: 12.36.0+ resolution: "framer-motion@npm:12.36.0"+ dependencies:+ motion-dom: "npm:^12.36.0"+ motion-utils: "npm:^12.36.0"+ tslib: "npm:^2.4.0"+ peerDependencies:+ "@emotion/is-prop-valid": "*"+ react: ^18.0.0 || ^19.0.0+ react-dom: ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ "@emotion/is-prop-valid":+ optional: true+ react:+ optional: true+ react-dom:+ optional: true+ checksum: 10c0/3acbb210d374ab80f4b086bcb8e7f722271f5d8e5d3e9f643ee0b5e7641bf34e100aaead68c99a4d478e67ccdda4b3ff89779bc0c9e5fe9aab8a955a5a6cfaa4+ languageName: node+ linkType: hard+"fs-extra@npm:^11.2.0":version: 11.3.1resolution: "fs-extra@npm:11.3.1"@@ -13932,6 +13963,13 @@ __metadata:languageName: nodelinkType: hard+"matter-js@npm:^0.20.0":+ version: 0.20.0+ resolution: "matter-js@npm:0.20.0"+ checksum: 10c0/95d58f407205ad24c96422109c959999f474ef29af79b4c2ad7550bca97cdcdac99df31ebe35ab858d9863c8f6cd5205339fbbff70909b56a3e2a6a57200c51b+ languageName: node+ linkType: hard+"md5.js@npm:^1.3.4":version: 1.3.5resolution: "md5.js@npm:1.3.5"@@ -14988,6 +15026,15 @@ __metadata:languageName: nodelinkType: hard+"motion-dom@npm:^12.36.0":+ version: 12.36.0+ resolution: "motion-dom@npm:12.36.0"+ dependencies:+ motion-utils: "npm:^12.36.0"+ checksum: 10c0/7f97b1e310310b44e6144f7303604d7c3f37f1e278b41ac5b57dca2abe082213d40a9f59cf5a2cb3442d27b8fd82e29f17f31d7b24d4b240f9b908fc97b42d80+ languageName: node+ linkType: hard+"motion-utils@npm:^12.23.6":version: 12.23.6resolution: "motion-utils@npm:12.23.6"@@ -15002,7 +15049,14 @@ __metadata:languageName: nodelinkType: hard-"motion@npm:^12.23.26, motion@npm:^12.29.2":+"motion-utils@npm:^12.36.0":+ version: 12.36.0+ resolution: "motion-utils@npm:12.36.0"+ checksum: 10c0/fe08231759064eef5d351a869379246f1e1b2031bda357a6197d2a99ff6b472bce69f8250212713d8bff2ff46978f354ca8c3b8c8f0c5bd337d26a6793ba42fa+ languageName: node+ linkType: hard++"motion@npm:^12.23.26":version: 12.34.3resolution: "motion@npm:12.34.3"dependencies:@@ -15023,6 +15077,27 @@ __metadata:languageName: nodelinkType: hard+"motion@npm:^12.35.0":+ version: 12.36.0+ resolution: "motion@npm:12.36.0"+ dependencies:+ framer-motion: "npm:^12.36.0"+ tslib: "npm:^2.4.0"+ peerDependencies:+ "@emotion/is-prop-valid": "*"+ react: ^18.0.0 || ^19.0.0+ react-dom: ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ "@emotion/is-prop-valid":+ optional: true+ react:+ optional: true+ react-dom:+ optional: true+ checksum: 10c0/3ad56cbc4d7de107dc8e72c4e5738b885fa455224461ca1e68545e5e790b9d5e27f4b01a6d9129899ee7e214cff10247f7b9b6edff25d3ef5ed292b212ed95a6+ languageName: node+ linkType: hard+"mrmime@npm:^2.0.0":version: 2.0.1resolution: "mrmime@npm:2.0.1"