Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
chore: remove foundation-models-server implementation and related build configurations
dev-miro26c02ce61630b4
diff --git a/Makefile b/Makefileindex 893daa5d4..a2b91e282 100644--- a/Makefile+++ b/Makefile@@ -172,39 +172,6 @@ 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:diff --git a/foundation-models-server/Package.swift b/foundation-models-server/Package.swiftdeleted file mode 100644index d899a6925..000000000--- a/foundation-models-server/Package.swift+++ /dev/null@@ -1,30 +0,0 @@-// 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.mddeleted file mode 100644index 3d840b72c..000000000--- a/foundation-models-server/README.md+++ /dev/null@@ -1,40 +0,0 @@-# 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.swiftdeleted file mode 100644index 36d2d5ec8..000000000--- a/foundation-models-server/Sources/FoundationModelsServer/FoundationModelsServerCommand.swift+++ /dev/null@@ -1,78 +0,0 @@-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.swiftdeleted file mode 100644index 34bb17517..000000000--- a/foundation-models-server/Sources/FoundationModelsServer/Logger.swift+++ /dev/null@@ -1,6 +0,0 @@-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.swiftdeleted file mode 100644index b14eb3574..000000000--- a/foundation-models-server/Sources/FoundationModelsServer/Server.swift+++ /dev/null@@ -1,299 +0,0 @@-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.swiftdeleted file mode 100644index 86dc656f7..000000000--- a/foundation-models-server/Sources/FoundationModelsServer/Types.swift+++ /dev/null@@ -1,98 +0,0 @@-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-}