Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
Add OpenAI-compatible local server and tool calling (#13)
Andrey Mikhaylove65da9e2f8f7
diff --git a/AGENTS.md b/AGENTS.mdindex aebebbfd..8fb2187a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -8,7 +8,10 @@ This checkout is for running and reporting existing behavior. Do not edit source## Layout and commands-`Sources/TurboFieldfare/` is the runtime; `Sources/TurboFieldfareRepack/`, `Sources/TurboFieldfareCLI/`, and `Sources/TurboFieldfareApp/` contain the installer, CLI, and Mac app.+`Sources/TurboFieldfare/` is the runtime; `Sources/TurboFieldfareRepack/`,+`Sources/TurboFieldfareCLI/`, `Sources/TurboFieldfareServer/`, and+`Sources/TurboFieldfareApp/` contain the installer, CLI, loopback server, and+Mac app.`Tests/` contains focused public tests; `docs/` contains design, benchmark, and experiment notes.```bash@@ -23,9 +26,21 @@ swift run -c release TurboFieldfareCLI \The installer streams the pinned model without staging the full source checkpoint. Set `HF_TOKEN` only if requested. The download is about 15 GB.+## Local server++Follow the [server guide](docs/OPENAI_SERVER.md) for launch commands, health+checks, client setup, prompt reuse, tool loops, and supported API behavior.+Apply the model-process checks below first; never start a second model process+or terminate an existing one.++Keep the server on `127.0.0.1`; it has no remote authentication or TLS, so do+not proxy, tunnel, or expose it. A tool call from the local model never bypasses+the client's normal permission policy. Keep the execution session alive while+the server is needed, and stop only a server you launched.+## Test rules-Before a model run, require macOS 26+, Swift 6.2+, enough disk, acceptable `memory_pressure -Q`, a completed `scratch/gemma4.gturbo`, and no process from `pgrep -fl 'TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'`. If a check fails, inform the user and stop; do not terminate apps or delete or reinstall the model.+Before a model run, require macOS 26+, Swift 6.2+, enough disk, acceptable `memory_pressure -Q`, a completed `scratch/gemma4.gturbo`, and no process from `pgrep -fl 'TurboFieldfareServer|TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'`. If a check fails, inform the user and stop; do not terminate apps or delete or reinstall the model.Run package tests through `Scripts/test.sh`. Run only one app, CLI, or model-using test at a time.diff --git a/Package.swift b/Package.swiftindex 6faf007e..f3ee04aa 100644--- a/Package.swift+++ b/Package.swift@@ -13,9 +13,11 @@ let package = Package(.executable(name: "TurboFieldfareCLI", targets: ["TurboFieldfareCLI"]),.executable(name: "TurboFieldfareMac", targets: ["TurboFieldfareMac"]),.executable(name: "TurboFieldfareDecodeService", targets: ["TurboFieldfareDecodeService"]),+ .executable(name: "TurboFieldfareServer", targets: ["TurboFieldfareServer"]),],dependencies: [.package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),+ .package(url: "https://github.com/apple/swift-nio.git", exact: "2.99.0"),],targets: [.target(@@ -70,6 +72,21 @@ let package = Package(dependencies: ["TurboFieldfareAppCore", "TurboFieldfareDecodeProtocol"],path: "Sources/TurboFieldfareDecodeService"),+ .target(+ name: "TurboFieldfareServerCore",+ dependencies: [+ "TurboFieldfare",+ .product(name: "NIOCore", package: "swift-nio"),+ .product(name: "NIOPosix", package: "swift-nio"),+ .product(name: "NIOHTTP1", package: "swift-nio"),+ ],+ path: "Sources/TurboFieldfareServer/Core"+ ),+ .executableTarget(+ name: "TurboFieldfareServer",+ dependencies: ["TurboFieldfareServerCore"],+ path: "Sources/TurboFieldfareServer/Command"+ ),.executableTarget(name: "TurboFieldfareMac",dependencies: ["TurboFieldfareAppCore", "TurboFieldfareMacPresentation"],@@ -103,5 +120,14 @@ let package = Package(dependencies: ["TurboFieldfareMacPresentation"],path: "Tests/TurboFieldfareApp/MacPresentation"),+ .testTarget(+ name: "TurboFieldfareServerTests",+ dependencies: [+ "TurboFieldfareServerCore",+ .product(name: "NIOEmbedded", package: "swift-nio"),+ ],+ path: "Tests/TurboFieldfareServer",+ resources: [.copy("Fixtures")]+ ),])diff --git a/README.md b/README.mdindex 2e1ea195..aba3277b 100644--- a/README.md+++ b/README.md@@ -18,6 +18,7 @@<p align="center"><a href="#try-it">Quick start</a> ·+ <a href="docs/OPENAI_SERVER.md">Local server</a> ·<a href="docs/BENCHMARKS.md">Benchmarks</a> ·<a href="docs/COMMUNITY_BENCHMARKS.md">Contribute results</a> ·<a href="docs/SYSTEM_DESIGN.md">How it works</a> ·@@ -79,11 +80,11 @@ To help measure another Apple Silicon Mac, follow the## Using TurboFieldfare-TurboFieldfare provides a native Mac app and a command-line interface. Both-use the same `.gturbo` model directory. Start with the Mac app; use the CLI for-scripts, reproducible runs, and direct control over generation settings.+TurboFieldfare provides a native Mac app, a command-line interface, and an+experimental loopback OpenAI-compatible server. They use the same `.gturbo`+model directory, but only one model-owning product should run at a time.-The Swift package exposes five products:+The Swift package exposes six products:| Product | Purpose || --- | --- |@@ -91,6 +92,7 @@ The Swift package exposes five products:| `TurboFieldfareMac` | Native Mac app for installation and generation || `TurboFieldfareDecodeService` | One-shot local model and Metal owner used by the Mac app || `TurboFieldfareCLI` | Command-line instruction chat and raw completion |+| `TurboFieldfareServer` | Loopback OpenAI-compatible Chat Completions server || `TurboFieldfareRepack` | Streaming model installer and install verifier |### Requirements@@ -113,9 +115,11 @@ Generation defaults to temperature `0.2`, Top-K `64`, and Top-P `0.95`. Settemperature to `0` for deterministic greedy output. The model can still repeatitself or give incorrect answers, so check important results.-TurboFieldfare is text-only. It supports user and model messages, plus an-optional system message at the start of a conversation. Tool calling and image-input are not supported.+TurboFieldfare is text-only. The app and CLI support user and model messages+plus optional system guidance; they do not expose or execute tools. The+loopback server accepts function-tool declarations and returns+model-produced tool calls for the client to authorize and execute. Images,+audio, and video are not supported.### Mac app@@ -231,6 +235,24 @@ swift run -c release TurboFieldfareCLI --helpGenerated text goes to standard output. Timing statistics go to standard error;add `--quiet` to suppress that footer in scripts.+### Local OpenAI-compatible server++Build the server and point it at an installed model:++```bash+swift build -c release --product TurboFieldfareServer+.build/release/TurboFieldfareServer \+ --model scratch/gemma4.gturbo+```++It listens on `http://127.0.0.1:8080/v1` and supports Chat Completions,+streaming, function tools, and single-prefix prompt reuse. The client must+authorize and run every tool call. Keep the server on loopback; it has no+remote authentication or TLS.++See [Local server](docs/OPENAI_SERVER.md) for a test request, Python and+OpenCode setup, prompt reuse, tool handling, and the supported API subset.+## Test and contributeRun the public test suite serially:@@ -241,7 +263,8 @@ Scripts/test.shBefore starting a model run, close memory-heavy apps and check`memory_pressure -Q`. If it reports little free memory, postpone the run. Run-only one TurboFieldfare or local-model process at a time.+only one TurboFieldfare app, decode service, CLI, server, test, or other+local-model process at a time.To contribute a comparable performance result, follow the[community benchmark guide](docs/COMMUNITY_BENCHMARKS.md).@@ -281,8 +304,9 @@ TurboFieldfare currently includes:- FP16 KV storage with bounded circular storage for 25 sliding-window layersand linear storage for 5 full-attention layers- Exact split-K/V decode attention with distinct normalized K and V paths-- A Swift library, streaming installer, command-line interface, and native- SwiftUI/AppKit Mac app with a one-shot local decode service+- A Swift library, streaming installer, command-line interface, loopback+ OpenAI-compatible server, and native SwiftUI/AppKit Mac app with a one-shot+ local decode serviceCurrent scope is text-only inference from the pinned Gemma 4 26B-A4Binstruction checkpoint on Apple Silicon Macs with at least 8 GB of RAM.@@ -304,6 +328,7 @@ audited entries as optional evidence.Useful entry points:+- [Local OpenAI-compatible server](docs/OPENAI_SERVER.md)- [System design](docs/SYSTEM_DESIGN.md)- [Benchmarks](docs/BENCHMARKS.md)- [The experiments that shaped TurboFieldfare](docs/OPTIMIZATION_JOURNEY.md)diff --git a/Sources/TurboFieldfare/Runtime/Generation/Generator.swift b/Sources/TurboFieldfare/Runtime/Generation/Generator.swiftindex d5e16e22..52a218b2 100644--- a/Sources/TurboFieldfare/Runtime/Generation/Generator.swift+++ b/Sources/TurboFieldfare/Runtime/Generation/Generator.swift@@ -5,11 +5,13 @@ public enum StopReason: Sendable, Equatable {case endOfTurncase maxTokenscase stopString+ case toolCalls}enum GeneratorError: Error, CustomStringConvertible, Equatable {case contextOverflow(prompt: Int, maxNew: Int, maxContext: Int)case invalidGenerationConfig(String)+ case invalidContinuation(String)case emptyPromptpublic var description: String {@@ -18,6 +20,8 @@ enum GeneratorError: Error, CustomStringConvertible, Equatable {return "context overflow: prompt \(prompt) + maxNew \(maxNew) exceeds maxContext \(maxContext)"case .invalidGenerationConfig(let reason):return reason+ case .invalidContinuation(let reason):+ return reasoncase .emptyPrompt:return "empty prompt"}diff --git a/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift b/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swiftindex a36d91fd..41881393 100644--- a/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift+++ b/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift@@ -10,6 +10,11 @@ public protocol LogitProducer: AnyObject, Sendable {func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws}+public protocol ContinuableLogitProducer: LogitProducer {+ var continuationPosition: Int { get }+ func prepareForContinuation(expectedPosition: Int) throws+}+protocol ContextWindowReporting: Sendable {var maxContext: Int { get }}diff --git a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swiftindex 74745a53..1086a86c 100644--- a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift+++ b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift@@ -12,12 +12,22 @@ public enum RawDecodeProgress: Sendable {case tail(String)}+public enum RawCompletionStart: Sendable, Equatable {+ case reset+ case resume(cachedPromptTokens: Int)+}+public struct RawDecodeResult: Sendable {public let prefillTokens: Int+ public let cachedPromptTokens: Int+ public let computedPrefillTokens: Intpublic let prefillSeconds: Doublepublic let newTokens: Intpublic let decodeSeconds: Doublepublic let reason: StopReason+ public let kvPosition: Int+ public let kvBackedTokenIDs: [Int32]+ public let uncommittedBoundaryTokenIDs: [Int32]}/// Preallocated per-generation buffers (two 512 KiB vocab buffers plus a token@@ -75,6 +85,8 @@ public func runRawCompletion(producer: any LogitProducer,context: MetalContext,scratch: RawCompletionScratch,prefillConfig: PrefillRuntimeConfig = .defaultChunked,+ start: RawCompletionStart = .reset,+ shouldStop: () -> Bool = { false },onProgress: (RawDecodeProgress) -> Void) async throws -> RawDecodeResult {try config.validate()guard !promptIds.isEmpty else {@@ -87,8 +99,25 @@ public func runRawCompletion(producer: any LogitProducer,"the fused-head producer cannot serve this sampling configuration; use a logits head")}+ let cachedPromptTokens: Int+ switch start {+ case .reset:+ cachedPromptTokens = 0+ case .resume(let count):+ guard count > 0, count < promptIds.count else {+ throw GeneratorError.invalidContinuation(+ "cached prompt token count must be greater than zero and less than the effective prompt")+ }+ guard producer is any ContinuableLogitProducer else {+ throw GeneratorError.invalidContinuation(+ "producer does not support continuation")+ }+ cachedPromptTokens = count+ }+ let computedPrefillTokens = promptIds.count - cachedPromptTokens+var detok = GFDetokenizer(tokenizer: tokenizer)- var history: [Int32] = []+ var history = Array(promptIds.prefix(cachedPromptTokens))history.reserveCapacity(promptIds.count + config.maxNewTokens)if let context = producer as? any ContextWindowReporting,@@ -97,20 +126,27 @@ public func runRawCompletion(producer: any LogitProducer,maxNew: config.maxNewTokens,maxContext: context.maxContext)}- producer.reset()+ switch start {+ case .reset:+ producer.reset()+ case .resume:+ let continuable = producer as! any ContinuableLogitProducer+ try continuable.prepareForContinuation(expectedPosition: cachedPromptTokens)+ }let prefillStart = Date()- var position = 0+ var position = cachedPromptTokensvar prefillSeed: PrefillSeed?+ let prefillTokens = promptIds[cachedPromptTokens...]switch prefillConfig.mode {case .chunked where producer is any ChunkedPrefillRunner:let chunked = producer as! any ChunkedPrefillRunnerlet mode: PrefillOutputMode = fusedGreedy ? .greedyIfAvailable : .logits- let result = try await chunked.prefillChunked(tokens: promptIds[...],+ let result = try await chunked.prefillChunked(tokens: prefillTokens,startPosition: position,outputMode: mode,config: prefillConfig,into: scratch.logits) { done in- onProgress(.prefill(done: done, total: promptIds.count))+ onProgress(.prefill(done: cachedPromptTokens + done, total: promptIds.count))}if mode == .logits, result.seed != .logitsWritten {throw PrefillError.unsupportedPrefillSeed(@@ -122,12 +158,12 @@ public func runRawCompletion(producer: any LogitProducer,}position = result.newPositionprefillSeed = result.seed- history.append(contentsOf: promptIds)+ history.append(contentsOf: prefillTokens)case .chunked:throw PrefillError.chunkedUnsupported(PrefillError.chunkedRequiresChunkedRunnerReason)case .off:- for t in promptIds {+ for t in prefillTokens {try Task.checkCancellation()try await producer.produce(token: t, position: position, into: scratch.logits)position += 1@@ -138,9 +174,10 @@ public func runRawCompletion(producer: any LogitProducer,let decodeStart = Date()let prefillSeconds = decodeStart.timeIntervalSince(prefillStart)- var accumulated = ""+ var stopMatcher = StreamingStopMatcher(stops: config.stopStrings)var generated = 0var reason: StopReason = .maxTokens+ var uncommittedBoundaryTokenIDs: [Int32] = []while true {try Task.checkCancellation()@@ -161,22 +198,29 @@ public func runRawCompletion(producer: any LogitProducer,history: history, config: config, position: generated)}generated += 1+ uncommittedBoundaryTokenIDs = [tokenID]if tokenizer.stopTokenIDs.contains(tokenID) || config.extraStopTokens.contains(tokenID) {- reason = tokenID == tokenizer.endOfTurnID ? .endOfTurn : .eos- let tail = detok.flush()+ if tokenID == tokenizer.endOfTurnID {+ reason = .endOfTurn+ } else if tokenID == tokenizer.toolResponseID {+ reason = .toolCalls+ } else {+ reason = .eos+ }+ let tail = stopMatcher.push(detok.flush()) + stopMatcher.finish()if !tail.isEmpty { onProgress(.tail(tail)) }break}let delta = detok.push(tokenID)- onProgress(.token(index: generated - 1, id: tokenID, delta: delta))- accumulated += delta+ let visible = stopMatcher.push(delta)+ onProgress(.token(index: generated - 1, id: tokenID, delta: visible))- let hitStopString = config.stopStrings.contains { !$0.isEmpty && accumulated.contains($0) }+ let hitStopString = stopMatcher.isStopped || shouldStop()let hitMax = generated >= config.maxNewTokensif hitStopString || hitMax {- let tail = detok.flush()+ let tail = stopMatcher.push(detok.flush()) + stopMatcher.finish()if !tail.isEmpty { onProgress(.tail(tail)) }reason = hitStopString ? .stopString : .maxTokensbreak@@ -185,13 +229,19 @@ public func runRawCompletion(producer: any LogitProducer,history.append(tokenID)try await producer.produce(token: tokenID, position: position, into: scratch.logits)position += 1+ uncommittedBoundaryTokenIDs.removeAll(keepingCapacity: true)}return RawDecodeResult(prefillTokens: promptIds.count,+ cachedPromptTokens: cachedPromptTokens,+ computedPrefillTokens: computedPrefillTokens,prefillSeconds: prefillSeconds,newTokens: generated,decodeSeconds: Date().timeIntervalSince(decodeStart),- reason: reason)+ reason: reason,+ kvPosition: position,+ kvBackedTokenIDs: history,+ uncommittedBoundaryTokenIDs: uncommittedBoundaryTokenIDs)}private func sampleOnce(scratch: RawCompletionScratch, context: MetalContext,diff --git a/Sources/TurboFieldfare/Runtime/Generation/StreamingStopMatcher.swift b/Sources/TurboFieldfare/Runtime/Generation/StreamingStopMatcher.swiftnew file mode 100644index 00000000..2924a70a--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Generation/StreamingStopMatcher.swift@@ -0,0 +1,51 @@+import Foundation++public struct StreamingStopMatcher: Sendable {+ private let stops: [String]+ private var pending = ""+ public private(set) var isStopped = false++ public init(stops: [String]) {+ self.stops = stops.filter { !$0.isEmpty }+ }++ public mutating func push(_ text: String) -> String {+ guard !isStopped else { return "" }+ pending += text+ if let match = earliestMatch(in: pending) {+ let output = String(pending[..<match])+ pending = ""+ isStopped = true+ return output+ }+ let retained = longestPossibleSuffix(in: pending)+ let boundary = pending.index(pending.endIndex, offsetBy: -retained)+ let output = String(pending[..<boundary])+ pending = String(pending[boundary...])+ return output+ }++ public mutating func finish() -> String {+ guard !isStopped else { return "" }+ defer { pending = "" }+ return pending+ }++ private func earliestMatch(in text: String) -> String.Index? {+ stops.compactMap { text.range(of: $0)?.lowerBound }.min()+ }++ private func longestPossibleSuffix(in text: String) -> Int {+ var best = 0+ for stop in stops {+ let maximum = min(text.count, max(stop.count - 1, 0))+ for length in stride(from: maximum, through: 1, by: -1) {+ if text.suffix(length) == stop.prefix(length) {+ best = max(best, length)+ break+ }+ }+ }+ return best+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swiftindex 81c949db..16706f5d 100644--- a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift+++ b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift@@ -130,7 +130,7 @@ internal enum PrefillProjectionDispatchPolicy {}}-public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporting, @unchecked Sendable {+public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporting, ContinuableLogitProducer, @unchecked Sendable {private struct LayerSharedExpertProjections {let gate: SharedExpertInt8Projlet up: SharedExpertInt8Proj@@ -376,6 +376,26 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportipublic func reset() {kv?.reset()+ resetTransientState()+ }++ public var continuationPosition: Int {+ kv?.position ?? 0+ }++ public func prepareForContinuation(expectedPosition: Int) throws {+ guard let kv else {+ throw PrefillError.prefillCursorMismatch(+ "continuation requires an initialized KV cache")+ }+ guard expectedPosition > 0, kv.position == expectedPosition else {+ throw PrefillError.prefillCursorMismatch(+ "continuation expected KV position \(expectedPosition), current \(kv.position)")+ }+ resetTransientState()+ }++ private func resetTransientState() {prefillChunkState.reset()rdadviseSkipUntilPosition = -1rdadviseAdaptiveState.reset()diff --git a/Sources/TurboFieldfare/Tokenization/GemmaToolCallParser.swift b/Sources/TurboFieldfare/Tokenization/GemmaToolCallParser.swiftnew file mode 100644index 00000000..cd95e28d--- /dev/null+++ b/Sources/TurboFieldfare/Tokenization/GemmaToolCallParser.swift@@ -0,0 +1,290 @@+import Foundation++public struct ParsedToolCall: Equatable, Sendable {+ public let id: String+ public let name: String+ public let arguments: JSONValue+ public let argumentsJSON: String++ public init(id: String,+ name: String,+ arguments: JSONValue,+ argumentsJSON: String) {+ self.id = id+ self.name = name+ self.arguments = arguments+ self.argumentsJSON = argumentsJSON+ }+}++public enum GemmaToolCallParserError: Error, Equatable {+ case malformed+ case unknownTool(String)+ case oversized+}++public struct GemmaToolCallParser: Sendable {+ public static let maximumBytes = 256 * 1024++ public init() {}++ public static func isRepresentableObjectKey(_ key: String) -> Bool {+ !key.isEmpty && key.allSatisfy {+ $0.isLetter || $0.isNumber || "_-.$".contains($0)+ }+ }++ public func parse(_ text: String,+ allowedTools: Set<String>,+ id: String) throws -> ParsedToolCall {+ guard text.utf8.count <= Self.maximumBytes else {+ throw GemmaToolCallParserError.oversized+ }+ var parser = Parser(text)+ try parser.consume("call:")+ let name = try parser.identifier()+ guard allowedTools.contains(name) else {+ throw GemmaToolCallParserError.unknownTool(name)+ }+ let arguments = try parser.object()+ parser.skipWhitespace()+ guard parser.isAtEnd else { throw GemmaToolCallParserError.malformed }+ return ParsedToolCall(id: id,+ name: name,+ arguments: arguments,+ argumentsJSON: try arguments.encoded())+ }+}++private struct Parser {+ private let characters: [Character]+ private var index = 0++ init(_ text: String) {+ characters = Array(text)+ }++ var isAtEnd: Bool { index == characters.count }++ mutating func skipWhitespace() {+ while index < characters.count, characters[index].isWhitespace { index += 1 }+ }++ mutating func consume(_ literal: String) throws {+ skipWhitespace()+ let value = Array(literal)+ guard index + value.count <= characters.count,+ Array(characters[index..<(index + value.count)]) == value else {+ throw GemmaToolCallParserError.malformed+ }+ index += value.count+ }++ mutating func identifier() throws -> String {+ skipWhitespace()+ let start = index+ while index < characters.count {+ let character = characters[index]+ guard character.isLetter || character.isNumber || character == "_" else { break }+ index += 1+ }+ guard index > start else { throw GemmaToolCallParserError.malformed }+ return String(characters[start..<index])+ }++ mutating func object() throws -> JSONValue {+ try consume("{")+ var result: [String: JSONValue] = [:]+ skipWhitespace()+ if take("}") { return .object(result) }+ while true {+ let key = try objectKey()+ try consume(":")+ result[key] = try value()+ skipWhitespace()+ if take("}") { return .object(result) }+ try consume(",")+ }+ }++ mutating func value() throws -> JSONValue {+ skipWhitespace()+ if starts(with: "<|\"|>") { return .string(try gemmaString()) }+ if starts(with: "\"") { return .string(try jsonString()) }+ if starts(with: "{") { return try object() }+ if starts(with: "[") { return try array() }+ if takeWord("true") { return .bool(true) }+ if takeWord("false") { return .bool(false) }+ if takeWord("null") { return .null }+ return try number()+ }++ mutating func objectKey() throws -> String {+ skipWhitespace()+ let start = index+ while index < characters.count {+ let character = characters[index]+ guard character.isLetter+ || character.isNumber+ || "_-.$".contains(character) else {+ break+ }+ index += 1+ }+ guard index > start else { throw GemmaToolCallParserError.malformed }+ return String(characters[start..<index])+ }++ mutating func array() throws -> JSONValue {+ try consume("[")+ var result: [JSONValue] = []+ skipWhitespace()+ if take("]") { return .array(result) }+ while true {+ result.append(try value())+ skipWhitespace()+ if take("]") { return .array(result) }+ try consume(",")+ }+ }++ mutating func gemmaString() throws -> String {+ try consume("<|\"|>")+ var result = ""+ while !isAtEnd {+ if starts(with: "<|\"|>") {+ try consume("<|\"|>")+ return result+ }+ if characters[index] == "\\", index + 1 < characters.count {+ index += 1+ result += try escapedFragment()+ } else {+ result.append(characters[index])+ index += 1+ }+ }+ throw GemmaToolCallParserError.malformed+ }++ mutating func jsonString() throws -> String {+ try consume("\"")+ var result = ""+ while !isAtEnd {+ if take("\"") { return result }+ if take("\\") {+ result += try escapedFragment()+ } else {+ result.append(characters[index])+ index += 1+ }+ }+ throw GemmaToolCallParserError.malformed+ }++ mutating func escapedFragment() throws -> String {+ guard index < characters.count else { throw GemmaToolCallParserError.malformed }+ let escape = characters[index]+ index += 1+ switch escape {+ case "\"": return "\""+ case "\\": return "\\"+ case "/": return "/"+ case "b": return "\u{8}"+ case "f": return "\u{c}"+ case "n": return "\n"+ case "r": return "\r"+ case "t": return "\t"+ case "u":+ let first = try unicodeCodeUnit()+ let scalar: UInt32+ if (0xD800...0xDBFF).contains(first) {+ guard index + 2 <= characters.count,+ characters[index] == "\\",+ characters[index + 1] == "u" else {+ throw GemmaToolCallParserError.malformed+ }+ index += 2+ let second = try unicodeCodeUnit()+ guard (0xDC00...0xDFFF).contains(second) else {+ throw GemmaToolCallParserError.malformed+ }+ scalar = 0x10000+ + (UInt32(first - 0xD800) << 10)+ + UInt32(second - 0xDC00)+ } else {+ guard !(0xDC00...0xDFFF).contains(first) else {+ throw GemmaToolCallParserError.malformed+ }+ scalar = UInt32(first)+ }+ guard let unicode = UnicodeScalar(scalar) else {+ throw GemmaToolCallParserError.malformed+ }+ return String(unicode)+ default: throw GemmaToolCallParserError.malformed+ }+ }++ mutating func unicodeCodeUnit() throws -> UInt16 {+ guard index + 4 <= characters.count else {+ throw GemmaToolCallParserError.malformed+ }+ var value: UInt16 = 0+ for _ in 0..<4 {+ guard let digit = characters[index].hexDigitValue else {+ throw GemmaToolCallParserError.malformed+ }+ value = value * 16 + UInt16(digit)+ index += 1+ }+ return value+ }++ mutating func number() throws -> JSONValue {+ let start = index+ while index < characters.count,+ "-+0123456789.eE".contains(characters[index]) {+ index += 1+ }+ guard index > start else {+ throw GemmaToolCallParserError.malformed+ }+ let literal = String(characters[start..<index])+ guard literal.range(+ of: #"^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$"#,+ options: .regularExpression) != nil else {+ throw GemmaToolCallParserError.malformed+ }+ if !literal.contains(where: { ".eE".contains($0) }) {+ if let value = Int64(literal) { return .integer(value) }+ if let value = UInt64(literal) { return .unsignedInteger(value) }+ }+ guard let value = Decimal(+ string: literal,+ locale: Locale(identifier: "en_US_POSIX")),+ !value.isNaN else {+ throw GemmaToolCallParserError.malformed+ }+ return .decimal(value)+ }++ func starts(with literal: String) -> Bool {+ let value = Array(literal)+ return index + value.count <= characters.count+ && Array(characters[index..<(index + value.count)]) == value+ }++ mutating func take(_ literal: Character) -> Bool {+ skipWhitespace()+ guard index < characters.count, characters[index] == literal else { return false }+ index += 1+ return true+ }++ mutating func takeWord(_ literal: String) -> Bool {+ guard starts(with: literal) else { return false }+ index += literal.count+ return true+ }+}diff --git a/Sources/TurboFieldfare/Tokenization/JSONValue.swift b/Sources/TurboFieldfare/Tokenization/JSONValue.swiftnew file mode 100644index 00000000..2a788d54--- /dev/null+++ b/Sources/TurboFieldfare/Tokenization/JSONValue.swift@@ -0,0 +1,138 @@+import Foundation++public indirect enum JSONValue: Codable, Equatable, Sendable {+ case object([String: JSONValue])+ case array([JSONValue])+ case string(String)+ case integer(Int64)+ case unsignedInteger(UInt64)+ case decimal(Decimal)+ case number(Double)+ case bool(Bool)+ case null++ public init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if container.decodeNil() {+ self = .null+ } else if let value = try? container.decode(Bool.self) {+ self = .bool(value)+ } else if let value = try? container.decode(Int64.self) {+ self = .integer(value)+ } else if let value = try? container.decode(UInt64.self) {+ self = .unsignedInteger(value)+ } else if let value = try? container.decode(Decimal.self) {+ self = .decimal(value)+ } else if let value = try? container.decode(String.self) {+ self = .string(value)+ } else if let value = try? container.decode([JSONValue].self) {+ self = .array(value)+ } else {+ self = .object(try container.decode([String: JSONValue].self))+ }+ }++ public func encode(to encoder: Encoder) throws {+ var container = encoder.singleValueContainer()+ switch self {+ case .object(let value): try container.encode(value)+ case .array(let value): try container.encode(value)+ case .string(let value): try container.encode(value)+ case .integer(let value): try container.encode(value)+ case .unsignedInteger(let value): try container.encode(value)+ case .decimal(let value): try container.encode(value)+ case .number(let value): try container.encode(value)+ case .bool(let value): try container.encode(value)+ case .null: try container.encodeNil()+ }+ }++ public func jinjaSendableValue() throws -> any Sendable {+ switch self {+ case .object(let value):+ return try value.mapValues { try $0.jinjaSendableValue() }+ case .array(let value):+ return try value.map { try $0.jinjaSendableValue() }+ case .string(let value):+ return value+ case .integer(let value):+ guard let value = Int(exactly: value) else {+ throw GemmaToolCallParserError.malformed+ }+ return value+ case .unsignedInteger(let value):+ guard let value = Int(exactly: value) else {+ throw GemmaToolCallParserError.malformed+ }+ return value+ case .decimal(let value):+ let text = NSDecimalNumber(decimal: value).stringValue+ guard let double = Double(text),+ double.isFinite,+ let roundTrip = Decimal(+ string: String(double),+ locale: Locale(identifier: "en_US_POSIX")),+ roundTrip == value else {+ throw GemmaToolCallParserError.malformed+ }+ return double+ case .number(let value):+ return value+ case .bool(let value):+ return value+ case .null:+ return Optional<String>.none as String?+ }+ }++ public var objectValue: [String: JSONValue]? {+ guard case .object(let value) = self else { return nil }+ return value+ }++ public func encoded(sortedKeys: Bool = true) throws -> String {+ let encoder = JSONEncoder()+ if sortedKeys { encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] }+ return String(decoding: try encoder.encode(self), as: UTF8.self)+ }++ public func gemmaToolArgumentBody() throws -> String {+ guard case .object(let value) = self else {+ throw GemmaToolCallParserError.malformed+ }+ return try value.keys.sorted().map { key in+ guard GemmaToolCallParser.isRepresentableObjectKey(key) else {+ throw GemmaToolCallParserError.malformed+ }+ return "\(key):\(try value[key]!.gemmaToolValue())"+ }.joined(separator: ",")+ }++ private func gemmaToolValue() throws -> String {+ switch self {+ case .object:+ return "{\(try gemmaToolArgumentBody())}"+ case .array(let value):+ return "[\(try value.map { try $0.gemmaToolValue() }.joined(separator: ","))]"+ case .string(let value):+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.withoutEscapingSlashes]+ return String(decoding: try encoder.encode(value), as: UTF8.self)+ case .integer(let value):+ return String(value)+ case .unsignedInteger(let value):+ return String(value)+ case .decimal(let value):+ return NSDecimalNumber(decimal: value).stringValue+ case .number(let value):+ guard value.isFinite else {+ throw GemmaToolCallParserError.malformed+ }+ return String(value)+ case .bool(let value):+ return value ? "true" : "false"+ case .null:+ return "null"+ }+ }+}diff --git a/Sources/TurboFieldfare/Tokenization/StructuredAssistantDecoder.swift b/Sources/TurboFieldfare/Tokenization/StructuredAssistantDecoder.swiftnew file mode 100644index 00000000..6c17d6c6--- /dev/null+++ b/Sources/TurboFieldfare/Tokenization/StructuredAssistantDecoder.swift@@ -0,0 +1,113 @@+import Foundation++public enum StructuredAssistantEvent: Equatable, Sendable {+ case content(String)+ case toolCall(ParsedToolCall)+}++public final class StructuredAssistantDecoder: @unchecked Sendable {+ private enum Channel {+ case thought+ case visible+ case label+ }++ private let tokenizer: GFTokenizer+ private let allowedTools: Set<String>+ private let idGenerator: @Sendable () -> String+ private var channel: Channel = .visible+ private var label = ""+ private var toolTokens: [Int32]?+ private var emittedCalls = 0+ private var failed = false++ public init(tokenizer: GFTokenizer,+ allowedTools: Set<String>,+ idGenerator: @escaping @Sendable () -> String = {+ "call_" + (0..<24).map { _ in String(format: "%x", UInt8.random(in: 0...15)) }.joined()+ }) {+ self.tokenizer = tokenizer+ self.allowedTools = allowedTools+ self.idGenerator = idGenerator+ }++ public func consume(tokenID: Int32, delta: String) throws -> [StructuredAssistantEvent] {+ guard !failed else { throw GemmaToolCallParserError.malformed }+ if tokenID == tokenizer.channelStartID {+ label = ""+ channel = .label+ return []+ }+ if tokenID == tokenizer.channelEndID {+ channel = .visible+ return []+ }+ if tokenID == tokenizer.toolCallStartID {+ guard toolTokens == nil else {+ failed = true+ throw GemmaToolCallParserError.malformed+ }+ toolTokens = []+ return []+ }+ if tokenID == tokenizer.toolCallEndID {+ guard let tokens = toolTokens else {+ failed = true+ throw GemmaToolCallParserError.malformed+ }+ toolTokens = nil+ let text = tokenizer.decode(tokens, skipSpecialTokens: false)+ do {+ let call = try GemmaToolCallParser().parse(+ text, allowedTools: allowedTools, id: idGenerator())+ emittedCalls += 1+ return [.toolCall(call)]+ } catch {+ failed = true+ throw error+ }+ }+ if tokenID == tokenizer.toolResponseID || tokenID == tokenizer.toolResponseEndID {+ guard emittedCalls > 0, toolTokens == nil else {+ failed = true+ throw GemmaToolCallParserError.malformed+ }+ return []+ }+ if var tokens = toolTokens {+ tokens.append(tokenID)+ guard tokens.count * MemoryLayout<Int32>.size <= GemmaToolCallParser.maximumBytes else {+ failed = true+ throw GemmaToolCallParserError.oversized+ }+ toolTokens = tokens+ return []+ }+ switch channel {+ case .thought:+ return []+ case .visible:+ return delta.isEmpty ? [] : [.content(delta)]+ case .label:+ label += delta+ guard let newline = label.firstIndex(of: "\n") else { return [] }+ let name = label[..<newline].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ let contentStart = label.index(after: newline)+ let content = String(label[contentStart...])+ channel = name == "final" || name == "answer" ? .visible : .thought+ label = ""+ if channel == .visible, !content.isEmpty {+ return [.content(content)]+ }+ return []+ }+ }++ public func finish() throws {+ guard !failed, toolTokens == nil else {+ throw GemmaToolCallParserError.malformed+ }+ }++ public var hasToolCalls: Bool { emittedCalls > 0 }+}diff --git a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift b/Sources/TurboFieldfare/Tokenization/Tokenizer.swiftindex 2efdcda9..045d3064 100644--- a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift+++ b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift@@ -4,11 +4,14 @@ import Tokenizerspublic enum GFTokenizerError: Error, CustomStringConvertible {case missingSpecialToken(String)case invalidChatTemplate(String)+ case missingToolTemplatepublic var description: String {switch self {case .missingSpecialToken(let t): return "tokenizer missing required special token: \(t)"case .invalidChatTemplate(let detail): return "invalid chat messages: \(detail)"+ case .missingToolTemplate:+ return "installed tokenizer is missing chat_template.jinja; reinstall the model"}}}@@ -27,12 +30,18 @@ public enum GFTokenizerError: Error, CustomStringConvertible {public struct GFTokenizer: @unchecked Sendable {public static let modelID = "google/gemma-4-26B-A4B-it"public static let chatTemplateIdentity = "gemma4-it-text-no-tools-v1"+ public static let toolChatTemplateIdentity = "gemma4-it-tools-jinja-v1"public let bosID: Int32public let eosID: Int32public let padID: Int32public let endOfTurnID: Int32+ public let toolCallStartID: Int32+ public let toolCallEndID: Int32public let toolResponseID: Int32+ public let toolResponseEndID: Int32+ public let channelStartID: Int32+ public let channelEndID: Int32public let stopTokenIDs: Set<Int32>public let vocabSize: Int@@ -104,12 +113,24 @@ public struct GFTokenizer: @unchecked Sendable {guard let toolResponse = tokenizer.convertTokenToId("<|tool_response>") else {throw GFTokenizerError.missingSpecialToken("<|tool_response>")}+ guard let toolCallStart = tokenizer.convertTokenToId("<|tool_call>"),+ let toolCallEnd = tokenizer.convertTokenToId("<tool_call|>"),+ let toolResponseEnd = tokenizer.convertTokenToId("<tool_response|>"),+ let channelStart = tokenizer.convertTokenToId("<|channel>"),+ let channelEnd = tokenizer.convertTokenToId("<channel|>") else {+ throw GFTokenizerError.missingSpecialToken("Gemma tool/channel markers")+ }self.bosID = Int32(bos)self.eosID = Int32(eos)self.padID = Int32(pad)self.endOfTurnID = Int32(eot)+ self.toolCallStartID = Int32(toolCallStart)+ self.toolCallEndID = Int32(toolCallEnd)self.toolResponseID = Int32(toolResponse)+ self.toolResponseEndID = Int32(toolResponseEnd)+ self.channelStartID = Int32(channelStart)+ self.channelEndID = Int32(channelEnd)self.stopTokenIDs = [self.eosID, self.endOfTurnID, self.toolResponseID]self.vocabSize = 262_144}@@ -132,13 +153,56 @@ public struct GFTokenizer: @unchecked Sendable {// MARK: - Chat template- public enum Role: String, Sendable { case system, user, assistant }- public struct Message: Sendable {+ public enum Role: String, Sendable { case system, developer, user, assistant, tool }+ public struct HistoricalToolCall: Sendable, Equatable {+ public let id: String+ public let name: String+ public let arguments: JSONValue++ public init(id: String, name: String, arguments: JSONValue) {+ self.id = id+ self.name = name+ self.arguments = arguments+ }+ }++ public struct FunctionDefinition: Sendable, Equatable {+ public let name: String+ public let description: String+ public let parameters: JSONValue++ public init(name: String, description: String, parameters: JSONValue) {+ self.name = name+ self.description = description+ self.parameters = parameters+ }+ }++ public struct Message: Sendable, Equatable {public let role: Role- public let content: String+ public let content: String?+ public let toolCalls: [HistoricalToolCall]+ public let toolCallID: String?+ public let name: String?+public init(role: Role, content: String) {self.role = roleself.content = content+ self.toolCalls = []+ self.toolCallID = nil+ self.name = nil+ }++ public init(role: Role,+ content: String?,+ toolCalls: [HistoricalToolCall] = [],+ toolCallID: String? = nil,+ name: String? = nil) {+ self.role = role+ self.content = content+ self.toolCalls = toolCalls+ self.toolCallID = toolCallID+ self.name = name}}@@ -152,7 +216,10 @@ public struct GFTokenizer: @unchecked Sendable {public func applyChatTemplate(_ messages: [Message]) throws -> String {var s = Self.bosMarkfor (index, message) in messages.enumerated() {- let content = message.content.trimmingCharacters(in: .whitespacesAndNewlines)+ guard let rawContent = message.content else {+ throw GFTokenizerError.invalidChatTemplate("text-only messages require content")+ }+ let content = rawContent.trimmingCharacters(in: .whitespacesAndNewlines)if message.role == .system && index != 0 {throw GFTokenizerError.invalidChatTemplate("system message must be first")}@@ -162,6 +229,103 @@ public struct GFTokenizer: @unchecked Sendable {s += Self.turnOpen + "model\n<|channel>thought\n<channel|>"return s}++ public func encodeToolChat(messages: [Message],+ tools: [FunctionDefinition]) throws -> [Int32] {+ guard tokenizer.hasChatTemplate else {+ throw GFTokenizerError.missingToolTemplate+ }+ let upstreamMessages: [Tokenizers.Message] = try messages.map { message in+ var value: Tokenizers.Message = [+ "role": message.role.rawValue,+ "content": message.content,+ ]+ if !message.toolCalls.isEmpty {+ value["tool_calls"] = try message.toolCalls.map { call -> [String: any Sendable] in+ [+ "id": call.id,+ "type": "function",+ "function": [+ "name": call.name,+ "arguments": try call.arguments.jinjaSendableValue(),+ ] as [String: any Sendable],+ ]+ }+ }+ if let toolCallID = message.toolCallID { value["tool_call_id"] = toolCallID }+ if let name = message.name { value["name"] = name }+ return value+ }+ let upstreamTools: [ToolSpec] = try tools.map { tool in+ [+ "type": "function",+ "function": [+ "name": tool.name,+ "description": tool.description,+ "parameters": try tool.parameters.jinjaSendableValue(),+ ] as [String: any Sendable],+ ]+ }+ return try tokenizer.applyChatTemplate(+ messages: upstreamMessages,+ chatTemplate: nil,+ addGenerationPrompt: true,+ truncation: false,+ maxLength: nil,+ tools: upstreamTools,+ additionalContext: ["enable_thinking": false]+ ).map(Int32.init)+ }++ public func encodeTextContinuation(userContent: String) -> [Int32] {+ let content = userContent.trimmingCharacters(in: .whitespacesAndNewlines)+ return [endOfTurnID] + encode(+ "\n\(Self.turnOpen)user\n\(content)\(Self.turnClose)\n"+ + "\(Self.turnOpen)model\n<|channel>thought\n<channel|>",+ addBOS: false)+ }++ public func encodeToolResultContinuation(+ cachedMessages: [Message],+ assistant: Message,+ incomingMessages: [Message],+ tools: [FunctionDefinition]+ ) throws -> [Int32] {+ let prefix = try encodeToolChat(+ messages: cachedMessages + [assistant],+ tools: tools)+ let full = try encodeToolChat(messages: incomingMessages, tools: tools)+ let callCount = assistant.toolCalls.count+ let starts = prefix.indices.filter { prefix[$0] == toolCallStartID }+ guard callCount > 0, starts.count >= callCount,+ let callEnd = prefix.lastIndex(of: toolCallEndID) else {+ throw GFTokenizerError.invalidChatTemplate(+ "cached assistant tool-call boundary is missing")+ }+ let callStart = starts[starts.count - callCount]+ let callSequence = Array(prefix[callStart...callEnd])+ let matches = full.subsequenceStartIndices(matching: callSequence)+ guard matches.count == 1 else {+ throw GFTokenizerError.invalidChatTemplate(+ "cached assistant tool-call boundary is ambiguous")+ }+ let suffixStart = matches[0] + callSequence.count+ let suffix = Array(full[suffixStart...])+ guard suffix.first == toolResponseID else {+ throw GFTokenizerError.invalidChatTemplate(+ "tool-result continuation does not begin at the KV boundary")+ }+ return suffix+ }+}++private extension Array where Element: Equatable {+ func subsequenceStartIndices(matching needle: [Element]) -> [Int] {+ guard !needle.isEmpty, needle.count <= count else { return [] }+ return indices.dropLast(needle.count - 1).filter { start in+ self[start..<(start + needle.count)].elementsEqual(needle)+ }+ }}private enum GFTokenizerLoadSource: Hashable {diff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swiftindex 302b68eb..b6040277 100644--- a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift@@ -8,6 +8,7 @@ public enum AppStopReason: String, Equatable, Sendable {case eoscase endOfTurncase stopString+ case toolCalls}public struct AppRunnerDiagnostics: Equatable, Sendable {diff --git a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swiftindex 2b2cdeb9..851a8eba 100644--- a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift@@ -452,6 +452,7 @@ actor RealInferenceSession {case .endOfTurn: return .endOfTurncase .maxTokens: return .maxTokenscase .stopString: return .stopString+ case .toolCalls: return .toolCalls}}diff --git a/Sources/TurboFieldfareServer/Command/main.swift b/Sources/TurboFieldfareServer/Command/main.swiftnew file mode 100644index 00000000..ba6aae71--- /dev/null+++ b/Sources/TurboFieldfareServer/Command/main.swift@@ -0,0 +1,36 @@+import Darwin+import Foundation+import TurboFieldfareServerCore++let arguments: ServerArguments+do {+ arguments = try ServerArguments.parse(Array(CommandLine.arguments.dropFirst()))+} catch ServerArgumentError.help {+ print(ServerArguments.usage)+ exit(0)+} catch {+ FileHandle.standardError.write(Data("error: \(error)\n\n\(ServerArguments.usage)\n".utf8))+ exit(2)+}++do {+ let signals = ServerTerminationSignals()+ let modelURL = URL(fileURLWithPath: arguments.model).standardizedFileURL+ let backend = try await ServerModelSession.load(+ modelDirectory: modelURL,+ maxContext: arguments.maxContext,+ promptCacheMode: arguments.promptCacheMode)+ let server = TurboFieldfareHTTPServer(+ modelID: arguments.modelID,+ queueLimit: arguments.queueLimit,+ backend: backend)+ _ = try await server.start(port: arguments.port)+ print("TurboFieldfareServer ready at http://127.0.0.1:\(arguments.port) model=\(arguments.modelID) context=\(arguments.maxContext) prompt_cache=\(arguments.promptCacheMode.rawValue)")++ _ = await signals.wait()+ try await server.shutdown()+ await signals.cancel()+} catch {+ FileHandle.standardError.write(Data("error: \(error)\n".utf8))+ exit(1)+}diff --git a/Sources/TurboFieldfareServer/Core/HTTPServer.swift b/Sources/TurboFieldfareServer/Core/HTTPServer.swiftnew file mode 100644index 00000000..998a3009--- /dev/null+++ b/Sources/TurboFieldfareServer/Core/HTTPServer.swift@@ -0,0 +1,637 @@+import Foundation+import NIOCore+import NIOHTTP1+import NIOPosix+import Synchronization+import TurboFieldfare++public actor TurboFieldfareHTTPServer {+ public static let maximumBodyBytes = 1_048_576++ private let group: MultiThreadedEventLoopGroup+ private let modelID: String+ private let backend: any ServerInferenceBackend+ private let coordinator: ServerCoordinator+ private let heartbeatInterval: TimeAmount+ private let childChannels = ChildChannelRegistry()+ private var channel: Channel?+ private var shutdownTask: Task<Void, any Error>?++ public init(modelID: String,+ queueLimit: Int,+ backend: any ServerInferenceBackend,+ heartbeatInterval: TimeAmount = .seconds(5),+ group: MultiThreadedEventLoopGroup = .init(numberOfThreads: 1)) {+ self.group = group+ self.modelID = modelID+ self.backend = backend+ self.coordinator = ServerCoordinator(queueLimit: queueLimit)+ self.heartbeatInterval = heartbeatInterval+ }++ public func start(port: Int) async throws -> Channel {+ let modelID = self.modelID+ let backend = self.backend+ let coordinator = self.coordinator+ let heartbeatInterval = self.heartbeatInterval+ let childChannels = self.childChannels+ let bootstrap = ServerBootstrap(group: group)+ .serverChannelOption(ChannelOptions.backlog, value: 16)+ .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)+ .childChannelInitializer { channel in+ childChannels.insert(channel)+ return channel.pipeline.configureHTTPServerPipeline(+ withPipeliningAssistance: true,+ withErrorHandling: true+ ).flatMap {+ channel.pipeline.addHandler(ServerHTTPHandler(+ modelID: modelID,+ backend: backend,+ coordinator: coordinator,+ heartbeatInterval: heartbeatInterval,+ childChannels: childChannels))+ }+ }+ .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)+ let channel = try await bootstrap.bind(host: "127.0.0.1", port: port).get()+ self.channel = channel+ return channel+ }++ public func shutdown() async throws {+ if let shutdownTask {+ try await shutdownTask.value+ return+ }++ let listeningChannel = channel+ channel = nil+ let childChannels = self.childChannels+ let coordinator = self.coordinator+ let group = self.group+ let task = Task { @Sendable in+ var firstError: (any Error)?+ await coordinator.shutdown()+ if let listeningChannel {+ do {+ try await listeningChannel.close().get()+ } catch ChannelError.alreadyClosed {+ } catch {+ firstError = error+ }+ }+ await childChannels.closeAll()+ do {+ try await group.shutdownGracefully()+ } catch {+ if firstError == nil {+ firstError = error+ }+ }+ if let firstError {+ throw firstError+ }+ }+ shutdownTask = task+ try await task.value+ }++ var queuedRequestCount: Int {+ get async { await coordinator.queuedCount }+ }++ var hasActiveRequest: Bool {+ get async { await coordinator.isActive }+ }++ var acceptedConnectionCount: Int {+ childChannels.count+ }+}++private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendable {+ typealias InboundIn = HTTPServerRequestPart+ typealias OutboundOut = HTTPServerResponsePart++ private let modelID: String+ private let backend: any ServerInferenceBackend+ private let coordinator: ServerCoordinator+ private let heartbeatInterval: TimeAmount+ private let childChannels: ChildChannelRegistry+ private var head: HTTPRequestHead?+ private var body = ByteBuffer()+ private var oversized = false+ private var activeTask: Task<Void, Never>?++ init(modelID: String,+ backend: any ServerInferenceBackend,+ coordinator: ServerCoordinator,+ heartbeatInterval: TimeAmount,+ childChannels: ChildChannelRegistry) {+ self.modelID = modelID+ self.backend = backend+ self.coordinator = coordinator+ self.heartbeatInterval = heartbeatInterval+ self.childChannels = childChannels+ }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ switch unwrapInboundIn(data) {+ case .head(let head):+ self.head = head+ body.clear()+ oversized = false+ case .body(var part):+ if body.readableBytes + part.readableBytes > TurboFieldfareHTTPServer.maximumBodyBytes {+ oversized = true+ } else {+ body.writeBuffer(&part)+ }+ case .end:+ guard let head else { return }+ self.head = nil+ if oversized {+ writeError(context, status: .payloadTooLarge,+ OpenAIErrorEnvelope(message: "request body is too large",+ code: "request_too_large"))+ return+ }+ route(head: head, body: body, context: context)+ }+ }++ func channelInactive(context: ChannelHandlerContext) {+ activeTask?.cancel()+ activeTask = nil+ childChannels.remove(context.channel)+ context.fireChannelInactive()+ }++ private func route(head: HTTPRequestHead,+ body: ByteBuffer,+ context: ChannelHandlerContext) {+ switch (head.method, head.uri) {+ case (.GET, "/health"):+ writeJSON(context, status: .ok, object: ["status": "ok"])+ case (.GET, "/v1/models"):+ let response = OpenAIModelList(+ object: "list",+ data: [.init(id: modelID,+ object: "model",+ created: 0,+ ownedBy: "turbofieldfare")])+ writeCodable(context, status: .ok, response)+ case (.POST, "/v1/chat/completions"):+ guard head.headers.first(name: "content-type")?+ .lowercased().hasPrefix("application/json") == true else {+ writeError(context, status: .unsupportedMediaType,+ OpenAIErrorEnvelope(message: "content-type must be application/json",+ code: "unsupported_media_type"))+ return+ }+ handleCompletion(body: body, context: context)+ case (_, "/health"), (_, "/v1/models"), (_, "/v1/chat/completions"):+ writeError(context, status: .methodNotAllowed,+ OpenAIErrorEnvelope(message: "method not allowed",+ code: "method_not_allowed"))+ default:+ writeError(context, status: .notFound,+ OpenAIErrorEnvelope(message: "route not found",+ code: "not_found"))+ }+ }++ private func handleCompletion(body: ByteBuffer,+ context: ChannelHandlerContext) {+ do {+ let bytes = body.getBytes(at: body.readerIndex, length: body.readableBytes) ?? []+ let decoded = try JSONDecoder().decode(OpenAIChatRequest.self, from: Data(bytes))+ let request = try OpenAIRequestValidator.validate(decoded, modelID: modelID)+ let responseID = "chatcmpl-" + UUID().uuidString.lowercased().replacingOccurrences(of: "-", with: "")+ let created = Int(Date().timeIntervalSince1970)+ let contextBox = SendableContext(context)+ let streamState = StreamState()+ let startStream: @Sendable () -> Void = {+ guard request.stream,+ streamState.start(eventLoop: contextBox.value.eventLoop,+ interval: self.heartbeatInterval,+ ping: {+ self.writeHeartbeat(contextBox.value)+ }) else { return }+ self.beginStream(contextBox.value)+ self.writeStreamChunk(+ contextBox.value,+ self.chunk(id: responseID, created: created,+ delta: ["role": "assistant"],+ finishReason: nil))+ }+ activeTask = childChannels.startTask {+ defer { streamState.stop() }+ do {+ let completion = try await self.coordinator.run(onQueued: startStream) {+ startStream()+ return try await self.backend.generate(request) { event in+ guard request.stream else { return }+ switch event {+ case .content(let text):+ self.writeStreamChunk(+ contextBox.value,+ self.chunk(id: responseID, created: created,+ delta: ["content": text],+ finishReason: nil))+ case .toolCall(let call):+ self.writeToolCall(contextBox.value,+ id: responseID,+ created: created,+ toolIndex: streamState.nextToolIndex(),+ call: call)+ }+ }+ }+ if request.stream {+ self.finishStream(contextBox.value,+ id: responseID,+ created: created,+ completion: completion,+ includeUsage: request.includeUsage)+ } else {+ self.writeCompletion(contextBox.value,+ id: responseID,+ created: created,+ completion: completion)+ }+ } catch {+ self.handleAsyncError(error,+ context: contextBox.value,+ stream: streamState.isStarted)+ }+ }+ } catch let error as ServerRequestError {+ writeError(context,+ status: error == .unknownModel ? .notFound : .badRequest,+ error.envelope)+ } catch {+ writeError(context, status: .badRequest,+ OpenAIErrorEnvelope(message: "malformed JSON request",+ code: "invalid_json"))+ }+ }++ private func writeCompletion(_ context: ChannelHandlerContext,+ id: String,+ created: Int,+ completion: ServerCompletion) {+ let encodedContent: Any =+ completion.content.isEmpty && !completion.toolCalls.isEmpty+ ? NSNull()+ : completion.content+ var message: [String: Any] = [+ "role": "assistant",+ "content": encodedContent,+ ]+ if !completion.toolCalls.isEmpty {+ message["tool_calls"] = completion.toolCalls.map(toolCallObject)+ }+ let object: [String: Any] = [+ "id": id,+ "object": "chat.completion",+ "created": created,+ "model": modelID,+ "choices": [[+ "index": 0,+ "message": message,+ "finish_reason": completion.finishReason,+ ]],+ "usage": usageObject(completion.usage),+ ]+ writeJSON(context, status: .ok, object: object)+ }++ private func beginStream(_ context: ChannelHandlerContext) {+ var headers = HTTPHeaders()+ headers.add(name: "content-type", value: "text/event-stream")+ headers.add(name: "cache-control", value: "no-cache")+ headers.add(name: "connection", value: "keep-alive")+ let head = HTTPResponseHead(version: .http1_1, status: .ok, headers: headers)+ let contextBox = SendableContext(context)+ context.eventLoop.execute {+ contextBox.value.write(self.wrapOutboundOut(.head(head)),+ promise: nil)+ contextBox.value.flush()+ }+ }++ private func writeToolCall(_ context: ChannelHandlerContext,+ id: String,+ created: Int,+ toolIndex: Int,+ call: ParsedToolCall) {+ let fragments = utf8Fragments(call.argumentsJSON, maximumBytes: 1024)+ for (index, fragment) in fragments.enumerated() {+ var function: [String: Any] = ["arguments": fragment]+ var tool: [String: Any] = ["index": toolIndex, "function": function]+ if index == 0 {+ function["name"] = call.name+ tool["id"] = call.id+ tool["type"] = "function"+ tool["function"] = function+ }+ writeStreamChunk(+ context,+ chunk(id: id, created: created,+ delta: ["tool_calls": [tool]],+ finishReason: nil))+ }+ }++ private func finishStream(_ context: ChannelHandlerContext,+ id: String,+ created: Int,+ completion: ServerCompletion,+ includeUsage: Bool) {+ writeStreamChunk(+ context,+ chunk(id: id, created: created,+ delta: [:],+ finishReason: completion.finishReason))+ if includeUsage {+ writeStreamChunk(context, [+ "id": id,+ "object": "chat.completion.chunk",+ "created": created,+ "model": modelID,+ "choices": [],+ "usage": usageObject(completion.usage),+ ])+ }+ let contextBox = SendableContext(context)+ context.eventLoop.execute {+ let buffer = contextBox.value.channel.allocator.buffer(string: "data: [DONE]\n\n")+ contextBox.value.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil)+ contextBox.value.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)+ }+ }++ private func chunk(id: String,+ created: Int,+ delta: [String: Any],+ finishReason: String?) -> [String: Any] {+ let encodedReason: Any = finishReason.map { $0 as Any } ?? NSNull()+ return [+ "id": id,+ "object": "chat.completion.chunk",+ "created": created,+ "model": modelID,+ "choices": [[+ "index": 0,+ "delta": delta,+ "finish_reason": encodedReason,+ ]],+ ]+ }++ private func writeStreamChunk(_ context: ChannelHandlerContext,+ _ object: [String: Any]) {+ guard let data = try? JSONSerialization.data(withJSONObject: object) else { return }+ let contextBox = SendableContext(context)+ context.eventLoop.execute {+ var buffer = contextBox.value.channel.allocator.buffer(capacity: data.count + 8)+ buffer.writeString("data: ")+ buffer.writeBytes(data)+ buffer.writeString("\n\n")+ contextBox.value.writeAndFlush(+ self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil)+ }+ }++ private func writeHeartbeat(_ context: ChannelHandlerContext) {+ let buffer = context.channel.allocator.buffer(string: ": ping\n\n")+ context.writeAndFlush(+ wrapOutboundOut(.body(.byteBuffer(buffer))),+ promise: nil)+ }++ private func handleAsyncError(_ error: Error,+ context: ChannelHandlerContext,+ stream: Bool) {+ if stream {+ let contextBox = SendableContext(context)+ context.eventLoop.execute {+ contextBox.value.close(promise: nil)+ }+ return+ }+ if let requestError = error as? ServerRequestError {+ let status: HTTPResponseStatus = requestError == .queueFull ? .tooManyRequests : .badRequest+ writeError(context, status: status, requestError.envelope)+ } else {+ writeError(context, status: .internalServerError,+ OpenAIErrorEnvelope(message: "generation failed",+ code: "internal_error"))+ }+ }++ private func writeCodable<T: Encodable>(_ context: ChannelHandlerContext,+ status: HTTPResponseStatus,+ _ value: T) {+ guard let data = try? JSONEncoder().encode(value) else { return }+ writeData(context, status: status, data: data)+ }++ private func writeError(_ context: ChannelHandlerContext,+ status: HTTPResponseStatus,+ _ error: OpenAIErrorEnvelope) {+ writeCodable(context, status: status, error)+ }++ private func writeJSON(_ context: ChannelHandlerContext,+ status: HTTPResponseStatus,+ object: Any) {+ guard let data = try? JSONSerialization.data(withJSONObject: object) else { return }+ writeData(context, status: status, data: data)+ }++ private func writeData(_ context: ChannelHandlerContext,+ status: HTTPResponseStatus,+ data: Data) {+ let contextBox = SendableContext(context)+ context.eventLoop.execute {+ var headers = HTTPHeaders()+ headers.add(name: "content-type", value: "application/json")+ headers.add(name: "content-length", value: "\(data.count)")+ contextBox.value.write(self.wrapOutboundOut(.head(+ HTTPResponseHead(version: .http1_1, status: status, headers: headers))),+ promise: nil)+ var buffer = contextBox.value.channel.allocator.buffer(capacity: data.count)+ buffer.writeBytes(data)+ contextBox.value.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil)+ contextBox.value.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)+ }+ }++ private func usageObject(_ usage: OpenAIUsage) -> [String: Any] {+ [+ "prompt_tokens": usage.promptTokens,+ "completion_tokens": usage.completionTokens,+ "total_tokens": usage.totalTokens,+ "prompt_tokens_details": [+ "cached_tokens": usage.promptTokensDetails.cachedTokens,+ ],+ ]+ }++ private func toolCallObject(_ call: ParsedToolCall) -> [String: Any] {+ [+ "id": call.id,+ "type": "function",+ "function": [+ "name": call.name,+ "arguments": call.argumentsJSON,+ ],+ ]+ }++ private func utf8Fragments(_ text: String, maximumBytes: Int) -> [String] {+ guard !text.isEmpty else { return [""] }+ var result: [String] = []+ var current = ""+ var bytes = 0+ for character in text {+ let size = String(character).utf8.count+ if bytes + size > maximumBytes, !current.isEmpty {+ result.append(current)+ current = ""+ bytes = 0+ }+ current.append(character)+ bytes += size+ }+ if !current.isEmpty { result.append(current) }+ return result+ }+}++private final class ChildChannelRegistry: Sendable {+ private struct State {+ var channels: [ObjectIdentifier: Channel] = [:]+ var tasks: [UUID: Task<Void, Never>] = [:]+ var shuttingDown = false+ }++ private let state = Mutex(State())++ func insert(_ channel: Channel) {+ let shouldClose = state.withLock {+ guard !$0.shuttingDown else { return true }+ $0.channels[ObjectIdentifier(channel)] = channel+ return false+ }+ if shouldClose {+ channel.close(promise: nil)+ }+ }++ func remove(_ channel: Channel) {+ _ = state.withLock {+ $0.channels.removeValue(forKey: ObjectIdentifier(channel))+ }+ }++ func startTask(+ _ operation: @escaping @Sendable () async -> Void+ ) -> Task<Void, Never> {+ state.withLock { state in+ let id = UUID()+ let task = Task { [self] in+ defer {+ _ = self.state.withLock {+ $0.tasks.removeValue(forKey: id)+ }+ }+ await operation()+ }+ state.tasks[id] = task+ if state.shuttingDown {+ task.cancel()+ }+ return task+ }+ }++ func closeAll() async {+ let channels = state.withLock {+ $0.shuttingDown = true+ return Array($0.channels.values)+ }+ for channel in channels {+ try? await channel.close().get()+ }+ let tasks = state.withLock { Array($0.tasks.values) }+ for task in tasks {+ task.cancel()+ }+ for task in tasks {+ await task.value+ }+ }++ var count: Int {+ state.withLock { $0.channels.count }+ }+}++private final class SendableContext: @unchecked Sendable {+ let value: ChannelHandlerContext++ init(_ value: ChannelHandlerContext) {+ self.value = value+ }+}++private final class StreamState: @unchecked Sendable {+ private let lock = NSLock()+ private var started = false+ private var stopped = false+ private var heartbeat: RepeatedTask?+ private var toolIndex = 0++ var isStarted: Bool {+ lock.withLock { started }+ }++ func start(eventLoop: EventLoop,+ interval: TimeAmount,+ ping: @escaping @Sendable () -> Void) -> Bool {+ lock.withLock {+ guard !started else { return false }+ started = true+ stopped = false+ heartbeat = eventLoop.scheduleRepeatedTask(+ initialDelay: interval,+ delay: interval) { [weak self] _ in+ guard self?.shouldPing == true else { return }+ ping()+ }+ return true+ }+ }++ private var shouldPing: Bool {+ lock.withLock { started && !stopped }+ }++ func stop() {+ lock.withLock {+ stopped = true+ heartbeat?.cancel()+ heartbeat = nil+ }+ }++ func nextToolIndex() -> Int {+ lock.withLock {+ defer { toolIndex += 1 }+ return toolIndex+ }+ }+}diff --git a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift b/Sources/TurboFieldfareServer/Core/OpenAIModels.swiftnew file mode 100644index 00000000..f2c33ac2--- /dev/null+++ b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift@@ -0,0 +1,462 @@+import Foundation+import TurboFieldfare++public struct OpenAIErrorEnvelope: Codable, Equatable, Sendable {+ public struct Detail: Codable, Equatable, Sendable {+ public let message: String+ public let type: String+ public let param: String?+ public let code: String+ }++ public let error: Detail++ public init(message: String, param: String? = nil, code: String) {+ error = Detail(message: message,+ type: "invalid_request_error",+ param: param,+ code: code)+ }+}++public struct OpenAITextPart: Codable, Equatable, Sendable {+ public let type: String+ public let text: String?+}++public enum OpenAIMessageContent: Codable, Equatable, Sendable {+ case text(String)+ case parts([OpenAITextPart])++ public init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if let text = try? container.decode(String.self) {+ self = .text(text)+ } else {+ self = .parts(try container.decode([OpenAITextPart].self))+ }+ }++ public func encode(to encoder: Encoder) throws {+ var container = encoder.singleValueContainer()+ switch self {+ case .text(let text): try container.encode(text)+ case .parts(let parts): try container.encode(parts)+ }+ }++ func textValue() throws -> String {+ switch self {+ case .text(let text):+ return text+ case .parts(let parts):+ guard parts.allSatisfy({ $0.type == "text" && $0.text != nil }) else {+ throw ServerRequestError.invalid(+ message: "only text content parts are supported",+ param: "messages",+ code: "unsupported_content")+ }+ return parts.compactMap(\.text).joined()+ }+ }+}++public struct OpenAIFunctionCall: Codable, Equatable, Sendable {+ public let name: String+ public let arguments: String+}++public struct OpenAIToolCall: Codable, Equatable, Sendable {+ public let id: String+ public let type: String+ public let function: OpenAIFunctionCall+}++public struct OpenAIChatMessage: Codable, Equatable, Sendable {+ public let role: String+ public let content: OpenAIMessageContent?+ public let toolCalls: [OpenAIToolCall]?+ public let toolCallID: String?+ public let name: String?++ enum CodingKeys: String, CodingKey {+ case role, content, name+ case toolCalls = "tool_calls"+ case toolCallID = "tool_call_id"+ }+}++public struct OpenAIFunctionDefinition: Codable, Equatable, Sendable {+ public let name: String+ public let description: String?+ public let parameters: JSONValue+}++public struct OpenAITool: Codable, Equatable, Sendable {+ public let type: String+ public let function: OpenAIFunctionDefinition+}++public enum OpenAIStop: Codable, Equatable, Sendable {+ case one(String)+ case many([String])++ public init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if let one = try? container.decode(String.self) {+ self = .one(one)+ } else {+ self = .many(try container.decode([String].self))+ }+ }++ public func encode(to encoder: Encoder) throws {+ var container = encoder.singleValueContainer()+ switch self {+ case .one(let value): try container.encode(value)+ case .many(let value): try container.encode(value)+ }+ }++ var values: [String] {+ switch self {+ case .one(let value): [value]+ case .many(let value): value+ }+ }+}++public struct OpenAIStreamOptions: Codable, Equatable, Sendable {+ public let includeUsage: Bool?++ enum CodingKeys: String, CodingKey {+ case includeUsage = "include_usage"+ }+}++public struct OpenAIChatRequest: Codable, Equatable, Sendable {+ public let model: String+ public let messages: [OpenAIChatMessage]+ public let stream: Bool?+ public let streamOptions: OpenAIStreamOptions?+ public let temperature: Float?+ public let topP: Float?+ public let maxTokens: Int?+ public let maxCompletionTokens: Int?+ public let stop: OpenAIStop?+ public let seed: UInt64?+ public let tools: [OpenAITool]?+ public let toolChoice: JSONValue?+ public let parallelToolCalls: Bool?+ public let topK: Int?+ public let repetitionPenalty: Float?+ public let n: Int?+ public let logprobs: Bool?+ public let presencePenalty: Float?+ public let frequencyPenalty: Float?++ enum CodingKeys: String, CodingKey {+ case model, messages, stream, temperature, stop, seed, tools, n, logprobs+ case streamOptions = "stream_options"+ case topP = "top_p"+ case maxTokens = "max_tokens"+ case maxCompletionTokens = "max_completion_tokens"+ case toolChoice = "tool_choice"+ case parallelToolCalls = "parallel_tool_calls"+ case topK = "top_k"+ case repetitionPenalty = "repetition_penalty"+ case presencePenalty = "presence_penalty"+ case frequencyPenalty = "frequency_penalty"+ }+}++public struct OpenAIUsage: Codable, Equatable, Sendable {+ public struct PromptTokensDetails: Codable, Equatable, Sendable {+ public let cachedTokens: Int++ enum CodingKeys: String, CodingKey {+ case cachedTokens = "cached_tokens"+ }++ public init(cachedTokens: Int) {+ self.cachedTokens = cachedTokens+ }+ }++ public let promptTokens: Int+ public let completionTokens: Int+ public let totalTokens: Int+ public let promptTokensDetails: PromptTokensDetails++ enum CodingKeys: String, CodingKey {+ case promptTokens = "prompt_tokens"+ case completionTokens = "completion_tokens"+ case totalTokens = "total_tokens"+ case promptTokensDetails = "prompt_tokens_details"+ }++ public init(promptTokens: Int,+ completionTokens: Int,+ totalTokens: Int,+ cachedTokens: Int = 0) {+ self.promptTokens = promptTokens+ self.completionTokens = completionTokens+ self.totalTokens = totalTokens+ self.promptTokensDetails = PromptTokensDetails(cachedTokens: cachedTokens)+ }+}++public struct OpenAIModelList: Codable, Equatable, Sendable {+ public struct Model: Codable, Equatable, Sendable {+ public let id: String+ public let object: String+ public let created: Int+ public let ownedBy: String++ enum CodingKeys: String, CodingKey {+ case id, object, created+ case ownedBy = "owned_by"+ }+ }++ public let object: String+ public let data: [Model]+}++public enum ServerRequestError: Error, Equatable, Sendable {+ case invalid(message: String, param: String?, code: String)+ case unknownModel+ case queueFull++ public var envelope: OpenAIErrorEnvelope {+ switch self {+ case .invalid(let message, let param, let code):+ OpenAIErrorEnvelope(message: message, param: param, code: code)+ case .unknownModel:+ OpenAIErrorEnvelope(message: "requested model is not available",+ param: "model", code: "model_not_found")+ case .queueFull:+ OpenAIErrorEnvelope(message: "generation queue is full",+ code: "queue_full")+ }+ }+}++public struct ValidatedChatRequest: Sendable {+ public let messages: [GFTokenizer.Message]+ public let tools: [GFTokenizer.FunctionDefinition]+ public let stream: Bool+ public let includeUsage: Bool+ public let generationConfig: GenerationConfig+ public let maximumCompletionTokens: Int+}++public enum OpenAIRequestValidator {+ public static func validate(_ request: OpenAIChatRequest,+ modelID: String) throws -> ValidatedChatRequest {+ guard request.model == modelID else { throw ServerRequestError.unknownModel }+ guard request.n == nil || request.n == 1 else {+ throw invalid("only n=1 is supported", "n", "unsupported_value")+ }+ guard request.logprobs != true else {+ throw invalid("logprobs are not supported", "logprobs", "unsupported_value")+ }+ guard request.presencePenalty == nil || request.presencePenalty == 0 else {+ throw invalid("presence_penalty must be zero", "presence_penalty", "unsupported_value")+ }+ guard request.frequencyPenalty == nil || request.frequencyPenalty == 0 else {+ throw invalid("frequency_penalty must be zero", "frequency_penalty", "unsupported_value")+ }+ guard request.parallelToolCalls != false else {+ throw invalid("parallel_tool_calls=false is not supported",+ "parallel_tool_calls", "unsupported_value")+ }++ let temperature = request.temperature ?? 0.2+ guard temperature >= 0, temperature <= 2 else {+ throw invalid("temperature must be between 0 and 2",+ "temperature", "invalid_value")+ }+ let topP = request.topP ?? 0.95+ guard topP > 0, topP <= 1 else {+ throw invalid("top_p must be greater than 0 and at most 1",+ "top_p", "invalid_value")+ }+ let topK = request.topK ?? 64+ guard (1...256).contains(topK) else {+ throw invalid("top_k must be between 1 and 256", "top_k", "invalid_value")+ }+ let repetitionPenalty = request.repetitionPenalty ?? 1+ guard repetitionPenalty > 0 else {+ throw invalid("repetition_penalty must be positive",+ "repetition_penalty", "invalid_value")+ }+ let maximum = request.maxCompletionTokens ?? request.maxTokens ?? 4096+ guard maximum > 0 else {+ throw invalid("maximum completion tokens must be positive",+ request.maxCompletionTokens != nil ? "max_completion_tokens" : "max_tokens",+ "invalid_value")+ }++ let includeTools: Bool+ switch request.toolChoice {+ case nil, .some(.string("auto")):+ includeTools = true+ case .some(.string("none")):+ includeTools = false+ case .some(.string("required")):+ throw invalid("tool_choice=required is not supported",+ "tool_choice", "unsupported_value")+ default:+ throw invalid("named tool choices are not supported",+ "tool_choice", "unsupported_value")+ }++ let tools = try (includeTools ? request.tools ?? [] : []).map(validateTool)+ let messages = try validateMessages(request.messages)+ let config = GenerationConfig(maxNewTokens: maximum,+ temperature: temperature,+ topK: topK,+ topP: topP,+ repetitionPenalty: repetitionPenalty,+ seed: request.seed,+ stopStrings: request.stop?.values ?? [])+ return ValidatedChatRequest(messages: messages,+ tools: tools,+ stream: request.stream ?? false,+ includeUsage: request.streamOptions?.includeUsage ?? false,+ generationConfig: config,+ maximumCompletionTokens: maximum)+ }++ private static func validateTool(_ tool: OpenAITool) throws -> GFTokenizer.FunctionDefinition {+ guard tool.type == "function" else {+ throw invalid("only function tools are supported", "tools", "unsupported_tool")+ }+ let name = tool.function.name+ guard name.range(of: #"^[A-Za-z0-9_]{1,64}$"#, options: .regularExpression) != nil else {+ throw invalid("tool name must match [A-Za-z0-9_]{1,64}",+ "tools", "invalid_tool_name")+ }+ guard tool.function.parameters.objectValue != nil else {+ throw invalid("tool parameters must be an object schema",+ "tools", "invalid_tool_schema")+ }+ try validateSchemaKeys(tool.function.parameters)+ guard (try? tool.function.parameters.jinjaSendableValue()) != nil else {+ throw invalid("tool schema contains a number that cannot be represented exactly",+ "tools", "invalid_tool_schema")+ }+ return GFTokenizer.FunctionDefinition(name: name,+ description: tool.function.description ?? "",+ parameters: tool.function.parameters)+ }++ private static func validateSchemaKeys(_ schema: JSONValue) throws {+ switch schema {+ case .object(let object):+ for (schemaKey, value) in object {+ if schemaKey == "properties" {+ guard case .object(let definitions) = value else {+ throw invalid("tool schema properties must be an object",+ "tools", "invalid_tool_schema")+ }+ for (key, definition) in definitions {+ guard GemmaToolCallParser.isRepresentableObjectKey(key) else {+ throw invalid(+ "tool parameter names may contain only letters, numbers, _, -, ., and $",+ "tools",+ "invalid_tool_schema")+ }+ try validateSchemaKeys(definition)+ }+ } else {+ try validateSchemaKeys(value)+ }+ }+ case .array(let values):+ for value in values {+ try validateSchemaKeys(value)+ }+ default:+ break+ }+ }++ private static func validateMessages(_ input: [OpenAIChatMessage]) throws -> [GFTokenizer.Message] {+ guard !input.isEmpty else {+ throw invalid("messages must not be empty", "messages", "invalid_message")+ }+ var knownCalls: [String: (name: String, resolved: Bool)] = [:]+ var result: [GFTokenizer.Message] = []+ var sawConversationMessage = false+ for message in input {+ guard let role = GFTokenizer.Role(rawValue: message.role) else {+ throw invalid("unsupported message role \(message.role)",+ "messages", "invalid_message")+ }+ if role == .system || role == .developer {+ guard !sawConversationMessage else {+ throw invalid("system or developer guidance must precede the conversation",+ "messages", "invalid_message")+ }+ } else {+ sawConversationMessage = true+ }+ let content = try message.content?.textValue()+ let calls: [GFTokenizer.HistoricalToolCall] = try (message.toolCalls ?? []).map { call in+ guard role == .assistant, call.type == "function",+ !call.id.isEmpty, knownCalls[call.id] == nil,+ call.function.name.range(+ of: #"^[A-Za-z0-9_]{1,64}$"#,+ options: .regularExpression) != nil else {+ throw invalid("invalid or duplicate historical tool call",+ "messages", "invalid_tool_call")+ }+ let data = Data(call.function.arguments.utf8)+ let arguments = try JSONDecoder().decode(JSONValue.self, from: data)+ guard arguments.objectValue != nil else {+ throw invalid("historical tool arguments must be a JSON object",+ "messages", "invalid_tool_arguments")+ }+ guard (try? arguments.gemmaToolArgumentBody()) != nil,+ (try? arguments.jinjaSendableValue()) != nil else {+ throw invalid(+ "historical tool arguments cannot be represented exactly",+ "messages",+ "invalid_tool_arguments")+ }+ knownCalls[call.id] = (call.function.name, false)+ return GFTokenizer.HistoricalToolCall(+ id: call.id, name: call.function.name, arguments: arguments)+ }+ if role == .tool {+ guard let id = message.toolCallID,+ let call = knownCalls[id], !call.resolved else {+ throw invalid("tool result must reference one unresolved call",+ "messages", "invalid_tool_result")+ }+ knownCalls[id] = (call.name, true)+ guard content != nil else {+ throw invalid("tool result content is required",+ "messages", "invalid_tool_result")+ }+ } else if content == nil && calls.isEmpty {+ throw invalid("message content is required",+ "messages", "invalid_message")+ }+ result.append(GFTokenizer.Message(role: role,+ content: content,+ toolCalls: calls,+ toolCallID: message.toolCallID,+ name: message.name))+ }+ return result+ }++ private static func invalid(_ message: String,+ _ param: String?,+ _ code: String) -> ServerRequestError {+ .invalid(message: message, param: param, code: code)+ }+}diff --git a/Sources/TurboFieldfareServer/Core/ServerArguments.swift b/Sources/TurboFieldfareServer/Core/ServerArguments.swiftnew file mode 100644index 00000000..632b1a00--- /dev/null+++ b/Sources/TurboFieldfareServer/Core/ServerArguments.swift@@ -0,0 +1,94 @@+import Foundation++public struct ServerArguments: Equatable, Sendable {+ public let model: String+ public let port: Int+ public let modelID: String+ public let maxContext: Int+ public let queueLimit: Int+ public let promptCacheMode: ServerPromptCacheMode++ public static let usage = """+ usage: TurboFieldfareServer --model <completed .gturbo directory> [options]++ --model <dir> Required model directory.+ --port <1...65535> Loopback port (default 8080).+ --model-id <id> API model identifier (default gemma-4-26b-a4b-it).+ --max-context <tokens> 4096, 8192, 16384, 32768, or 65536 (default 16384).+ --queue-limit <count> Maximum queued requests (default 4).+ --prompt-cache-mode <off|single-prefix>+ Prompt KV reuse mode (default single-prefix).+ --help Show this help.+ """++ public static func parse(_ input: [String]) throws -> ServerArguments {+ var model: String?+ var port = 8080+ var modelID = "gemma-4-26b-a4b-it"+ var maxContext = 16_384+ var queueLimit = 4+ var promptCacheMode: ServerPromptCacheMode = .singlePrefix+ var index = 0+ while index < input.count {+ let flag = input[index]+ if flag == "--help" || flag == "-h" { throw ServerArgumentError.help }+ guard index + 1 < input.count else {+ throw ServerArgumentError.invalid("\(flag) requires a value")+ }+ let value = input[index + 1]+ index += 2+ switch flag {+ case "--model":+ model = value+ case "--port":+ guard let parsed = Int(value), (1...65_535).contains(parsed) else {+ throw ServerArgumentError.invalid("--port must be between 1 and 65535")+ }+ port = parsed+ case "--model-id":+ guard !value.isEmpty else {+ throw ServerArgumentError.invalid("--model-id must not be empty")+ }+ modelID = value+ case "--max-context":+ guard let parsed = Int(value),+ [4_096, 8_192, 16_384, 32_768, 65_536].contains(parsed) else {+ throw ServerArgumentError.invalid("--max-context is not supported")+ }+ maxContext = parsed+ case "--queue-limit":+ guard let parsed = Int(value), parsed > 0 else {+ throw ServerArgumentError.invalid("--queue-limit must be positive")+ }+ queueLimit = parsed+ case "--prompt-cache-mode":+ guard let parsed = ServerPromptCacheMode(rawValue: value) else {+ throw ServerArgumentError.invalid(+ "--prompt-cache-mode must be off or single-prefix")+ }+ promptCacheMode = parsed+ default:+ throw ServerArgumentError.invalid("unknown flag: \(flag)")+ }+ }+ guard let model else { throw ServerArgumentError.invalid("--model is required") }+ return ServerArguments(model: model,+ port: port,+ modelID: modelID,+ maxContext: maxContext,+ queueLimit: queueLimit,+ promptCacheMode: promptCacheMode)+ }+}++public enum ServerArgumentError: Error, Equatable, CustomStringConvertible {+ case help+ case invalid(String)++ public var description: String {+ switch self {+ case .help: "help"+ case .invalid(let message): message+ }+ }+}diff --git a/Sources/TurboFieldfareServer/Core/ServerInference.swift b/Sources/TurboFieldfareServer/Core/ServerInference.swiftnew file mode 100644index 00000000..da852bb8--- /dev/null+++ b/Sources/TurboFieldfareServer/Core/ServerInference.swift@@ -0,0 +1,354 @@+import CryptoKit+import Foundation+import TurboFieldfare++public enum ServerInferenceEvent: Equatable, Sendable {+ case content(String)+ case toolCall(ParsedToolCall)+}++public struct ServerCompletion: Equatable, Sendable {+ public let content: String+ public let toolCalls: [ParsedToolCall]+ public let finishReason: String+ public let usage: OpenAIUsage++ public init(content: String,+ toolCalls: [ParsedToolCall],+ finishReason: String,+ usage: OpenAIUsage) {+ self.content = content+ self.toolCalls = toolCalls+ self.finishReason = finishReason+ self.usage = usage+ }+}++public protocol ServerInferenceBackend: Sendable {+ func generate(_ request: ValidatedChatRequest,+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void) async throws -> ServerCompletion+}++public actor ServerCoordinator {+ private struct Waiter {+ let id: UUID+ let continuation: CheckedContinuation<Void, Error>+ }++ private let queueLimit: Int+ private var active = false+ private var waiters: [Waiter] = []+ private var shuttingDown = false++ public init(queueLimit: Int) {+ self.queueLimit = queueLimit+ }++ public func run<T: Sendable>(+ onQueued: @escaping @Sendable () -> Void = {},+ _ operation: @escaping @Sendable () async throws -> T+ ) async throws -> T {+ try await acquire(onQueued: onQueued)+ defer { release() }+ return try await operation()+ }++ private func acquire(onQueued: @escaping @Sendable () -> Void) async throws {+ try Task.checkCancellation()+ guard !shuttingDown else { throw CancellationError() }+ if !active {+ active = true+ return+ }+ guard waiters.count < queueLimit else { throw ServerRequestError.queueFull }+ onQueued()+ let id = UUID()+ try await withTaskCancellationHandler {+ try await withCheckedThrowingContinuation { continuation in+ waiters.append(Waiter(id: id, continuation: continuation))+ }+ } onCancel: {+ Task { await self.cancelWaiter(id) }+ }+ if Task.isCancelled {+ release()+ throw CancellationError()+ }+ }++ private func cancelWaiter(_ id: UUID) {+ guard let index = waiters.firstIndex(where: { $0.id == id }) else { return }+ let waiter = waiters.remove(at: index)+ waiter.continuation.resume(throwing: CancellationError())+ }++ private func release() {+ if waiters.isEmpty {+ active = false+ } else {+ waiters.removeFirst().continuation.resume()+ }+ }++ public func shutdown() {+ shuttingDown = true+ let queued = waiters+ waiters.removeAll()+ for waiter in queued {+ waiter.continuation.resume(throwing: CancellationError())+ }+ }++ public var queuedCount: Int { waiters.count }+ public var isActive: Bool { active }+}++public actor ServerModelSession: ServerInferenceBackend {+ private let context: MetalContext+ private let model: Model+ private let tokenizer: GFTokenizer+ private let runner: RealForwardRunner+ private let scratch: RawCompletionScratch+ private let prefillConfig: PrefillRuntimeConfig+ private let maxContext: Int+ private let promptCacheMode: ServerPromptCacheMode+ private let promptCacheDomain: ServerPromptCacheDomain+ private var promptCache = ServerPromptCache()++ public static func load(modelDirectory: URL,+ maxContext: Int,+ promptCacheMode: ServerPromptCacheMode = .singlePrefix) async throws -> ServerModelSession {+ let tokenizerFolder = GFTokenizer.tokenizerFolder(forModelDirectory: modelDirectory)+ guard let tokenizerFolder else {+ throw GFTokenizerError.missingToolTemplate+ }+ let templateURL = tokenizerFolder.appendingPathComponent("chat_template.jinja")+ guard FileManager.default.fileExists(atPath: templateURL.path) else {+ throw GFTokenizerError.missingToolTemplate+ }+ let tokenizer = try await GFTokenizer.load(from: tokenizerFolder)+ let context = try MetalContext()+ let runtime = RuntimeConfiguration(forceLogitsHead: true)+ let model = try Model.load(+ directoryURL: modelDirectory,+ device: context.device,+ streamingMode: .pread(slotCount: runtime.expertCacheSlots),+ expertCachePolicy: runtime.modelExpertCachePolicy,+ integrityPolicy: .fullSha256)+ let runner = try RealForwardRunner(model: model,+ context: context,+ maxContext: maxContext,+ runtimeConfiguration: runtime)+ let scratch = try RawCompletionScratch(context: context, vocab: model.config.vocabSize)+ let templateDigest = SHA256.hash(data: try Data(contentsOf: templateURL))+ .map { String(format: "%02x", $0) }+ .joined()+ let runtimeIdentity = [+ String(runtime.expertCacheSlots),+ runtime.expertCachePolicy.rawValue,+ runtime.rdadvisePolicy.rawValue,+ runtime.prefillPolicy.rawValue,+ String(runtime.prefillChunkTokens),+ runtime.headPath.rawValue,+ ].joined(separator: ":")+ let runtimeDigest = SHA256.hash(data: Data(runtimeIdentity.utf8))+ .map { String(format: "%02x", $0) }+ .joined()+ let promptCacheDomain = ServerPromptCacheDomain(+ modelID: model.modelID,+ sourceSnapshotHash: model.sourceSnapshotHash,+ runtimeProfileHash: runtimeDigest,+ maximumContext: maxContext,+ kvStorage: PrefillKVStorageMode.fp16.rawValue,+ fp16RingEnabled: runtime.fp16RingEnabled,+ templateSHA256: templateDigest)+ return ServerModelSession(context: context,+ model: model,+ tokenizer: tokenizer,+ runner: runner,+ scratch: scratch,+ prefillConfig: runtime.prefillConfig,+ maxContext: maxContext,+ promptCacheMode: promptCacheMode,+ promptCacheDomain: promptCacheDomain)+ }++ private init(context: MetalContext,+ model: Model,+ tokenizer: GFTokenizer,+ runner: RealForwardRunner,+ scratch: RawCompletionScratch,+ prefillConfig: PrefillRuntimeConfig,+ maxContext: Int,+ promptCacheMode: ServerPromptCacheMode,+ promptCacheDomain: ServerPromptCacheDomain) {+ self.context = context+ self.model = model+ self.tokenizer = tokenizer+ self.runner = runner+ self.scratch = scratch+ self.prefillConfig = prefillConfig+ self.maxContext = maxContext+ self.promptCacheMode = promptCacheMode+ self.promptCacheDomain = promptCacheDomain+ }++ public func generate(+ _ request: ValidatedChatRequest,+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void+ ) async throws -> ServerCompletion {+ var completed = false+ defer {+ if !completed {+ promptCache.invalidate()+ runner.reset()+ }+ }+ let needsToolTemplate = !request.tools.isEmpty+ || request.messages.contains {+ $0.role == .developer || $0.role == .tool || !$0.toolCalls.isEmpty+ }+ let promptIDs: [Int32]+ if needsToolTemplate {+ promptIDs = try tokenizer.encodeToolChat(messages: request.messages, tools: request.tools)+ } else {+ let rendered = try tokenizer.applyChatTemplate(request.messages)+ promptIDs = tokenizer.encode(rendered, addBOS: false)+ }+ guard promptIDs.count < maxContext else {+ throw ServerRequestError.invalid(+ message: "prompt exceeds the configured context",+ param: "messages",+ code: "context_length_exceeded")+ }++ let effectivePromptIDs: [Int32]+ let completionStart: RawCompletionStart+ if promptCacheMode == .singlePrefix {+ switch promptCache.match(+ domain: promptCacheDomain,+ request: request,+ renderedPromptIDs: promptIDs,+ tokenizer: tokenizer) {+ case .miss:+ promptCache.invalidate()+ effectivePromptIDs = promptIDs+ completionStart = .reset+ case .hit(let effective, let cached):+ effectivePromptIDs = effective+ completionStart = .resume(cachedPromptTokens: cached)+ }+ } else {+ promptCache.invalidate()+ effectivePromptIDs = promptIDs+ completionStart = .reset+ }+ guard effectivePromptIDs.count < maxContext else {+ throw ServerRequestError.invalid(+ message: "effective prompt exceeds the configured context",+ param: "messages",+ code: "context_length_exceeded")+ }++ var config = request.generationConfig+ config.maxNewTokens = min(+ request.maximumCompletionTokens,+ maxContext - effectivePromptIDs.count)+ config.stopStrings = []++ let decoder = needsToolTemplate+ ? StructuredAssistantDecoder(+ tokenizer: tokenizer,+ allowedTools: Set(request.tools.map(\.name)))+ : nil+ var stopMatcher = StreamingStopMatcher(stops: request.generationConfig.stopStrings)+ var content = ""+ var calls: [ParsedToolCall] = []+ var decodingError: Error?+ var shouldStop = false++ let result = try await runRawCompletion(+ producer: runner,+ tokenizer: tokenizer,+ promptIds: effectivePromptIDs,+ config: config,+ context: context,+ scratch: scratch,+ prefillConfig: prefillConfig,+ start: completionStart,+ shouldStop: { shouldStop }) { progress in+ guard decodingError == nil else { return }+ do {+ switch progress {+ case .prefill:+ break+ case .token(_, let tokenID, let delta):+ let events = if let decoder {+ try decoder.consume(tokenID: tokenID, delta: delta)+ } else {+ delta.isEmpty ? [] : [StructuredAssistantEvent.content(delta)]+ }+ for event in events {+ switch event {+ case .content(let text):+ let visible = stopMatcher.push(text)+ if !visible.isEmpty {+ content += visible+ onEvent(.content(visible))+ }+ if stopMatcher.isStopped { shouldStop = true }+ case .toolCall(let call):+ calls.append(call)+ onEvent(.toolCall(call))+ }+ }+ case .tail(let text):+ let visible = stopMatcher.push(text)+ if !visible.isEmpty {+ content += visible+ onEvent(.content(visible))+ }+ }+ } catch {+ decodingError = error+ shouldStop = true+ }+ }+ if let decodingError { throw decodingError }+ try decoder?.finish()+ if needsToolTemplate, result.reason == .toolCalls, calls.isEmpty {+ throw GemmaToolCallParserError.malformed+ }+ let tail = stopMatcher.finish()+ if !tail.isEmpty {+ content += tail+ onEvent(.content(tail))+ }+ let reason: String+ if !calls.isEmpty {+ reason = "tool_calls"+ } else if result.reason == .maxTokens {+ reason = "length"+ } else {+ reason = "stop"+ }+ if promptCacheMode == .singlePrefix {+ promptCache.publish(+ domain: promptCacheDomain,+ request: request,+ content: content,+ calls: calls,+ result: result,+ stopStringFiltered: stopMatcher.isStopped)+ }+ completed = true+ return ServerCompletion(+ content: content,+ toolCalls: calls,+ finishReason: reason,+ usage: OpenAIUsage(promptTokens: result.prefillTokens,+ completionTokens: result.newTokens,+ totalTokens: result.prefillTokens + result.newTokens,+ cachedTokens: result.cachedPromptTokens))+ }+}diff --git a/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift b/Sources/TurboFieldfareServer/Core/ServerPromptCache.swiftnew file mode 100644index 00000000..70af208d--- /dev/null+++ b/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift@@ -0,0 +1,206 @@+import Foundation+import TurboFieldfare++public enum ServerPromptCacheMode: String, Sendable, Equatable {+ case off+ case singlePrefix = "single-prefix"+}++struct ServerPromptCacheDomain: Sendable, Equatable {+ let modelID: String+ let sourceSnapshotHash: String?+ let runtimeProfileHash: String+ let maximumContext: Int+ let kvStorage: String+ let fp16RingEnabled: Bool+ let templateSHA256: String+}++struct CachedAssistantTurn: Sendable, Equatable {+ let message: GFTokenizer.Message+ let rawStopReason: StopReason+}++struct ServerPromptCacheEntry: Sendable, Equatable {+ let domain: ServerPromptCacheDomain+ let inputMessages: [GFTokenizer.Message]+ let tools: [GFTokenizer.FunctionDefinition]+ let assistantTurn: CachedAssistantTurn+ let kvBackedTokenIDs: [Int32]+ let uncommittedBoundaryTokenIDs: [Int32]+ let kvPosition: Int+}++enum ServerPromptCacheMatch: Sendable, Equatable {+ case miss+ case hit(effectivePromptIDs: [Int32], cachedPromptTokens: Int)+}++struct ServerPromptCache: Sendable {+ private(set) var entry: ServerPromptCacheEntry?++ mutating func invalidate() {+ entry = nil+ }++ mutating func publish(+ domain: ServerPromptCacheDomain,+ request: ValidatedChatRequest,+ content: String,+ calls: [ParsedToolCall],+ result: RawDecodeResult,+ stopStringFiltered: Bool = false+ ) {+ guard result.kvPosition == result.kvBackedTokenIDs.count,+ !result.kvBackedTokenIDs.isEmpty,+ result.uncommittedBoundaryTokenIDs.count == 1,+ !stopStringFiltered,+ result.reason == .endOfTurn+ || result.reason == .toolCalls+ || result.reason == .maxTokens else {+ entry = nil+ return+ }+ let historicalCalls = calls.map {+ GFTokenizer.HistoricalToolCall(+ id: $0.id,+ name: $0.name,+ arguments: $0.arguments)+ }+ let assistant = GFTokenizer.Message(+ role: .assistant,+ content: calls.isEmpty ? content : nil,+ toolCalls: historicalCalls)+ entry = ServerPromptCacheEntry(+ domain: domain,+ inputMessages: request.messages,+ tools: request.tools,+ assistantTurn: CachedAssistantTurn(+ message: assistant,+ rawStopReason: result.reason),+ kvBackedTokenIDs: result.kvBackedTokenIDs,+ uncommittedBoundaryTokenIDs: result.uncommittedBoundaryTokenIDs,+ kvPosition: result.kvPosition)+ }++ func match(+ domain: ServerPromptCacheDomain,+ request: ValidatedChatRequest,+ renderedPromptIDs: [Int32],+ tokenizer: GFTokenizer+ ) -> ServerPromptCacheMatch {+ guard let entry,+ entry.domain == domain,+ entry.tools == request.tools,+ entry.kvPosition == entry.kvBackedTokenIDs.count,+ entry.kvPosition > 0,+ entry.uncommittedBoundaryTokenIDs.count == 1 else {+ return .miss+ }++ if renderedPromptIDs.count > entry.kvPosition,+ renderedPromptIDs.prefix(entry.kvPosition)+ .elementsEqual(entry.kvBackedTokenIDs) {+ return .hit(+ effectivePromptIDs: renderedPromptIDs,+ cachedPromptTokens: entry.kvPosition)+ }++ let inputCount = entry.inputMessages.count+ guard request.messages.count > inputCount + 1,+ request.messages.prefix(inputCount)+ .elementsEqual(entry.inputMessages),+ assistantMatches(+ request.messages[inputCount],+ entry.assistantTurn.message) else {+ return .miss+ }+ let continuation = Array(request.messages.dropFirst(inputCount + 1))++ if entry.assistantTurn.message.toolCalls.isEmpty {+ return matchTextContinuation(+ entry: entry,+ continuation: continuation,+ tokenizer: tokenizer)+ }+ return matchToolContinuation(+ entry: entry,+ request: request,+ continuation: continuation,+ tokenizer: tokenizer)+ }++ private func assistantMatches(+ _ incoming: GFTokenizer.Message,+ _ cached: GFTokenizer.Message+ ) -> Bool {+ guard incoming.role == .assistant,+ cached.role == .assistant,+ incoming.toolCalls == cached.toolCalls,+ incoming.toolCallID == cached.toolCallID,+ incoming.name == cached.name else {+ return false+ }+ if !cached.toolCalls.isEmpty {+ return (incoming.content ?? "").isEmpty+ && (cached.content ?? "").isEmpty+ }+ return incoming.content == cached.content+ }++ private func matchTextContinuation(+ entry: ServerPromptCacheEntry,+ continuation: [GFTokenizer.Message],+ tokenizer: GFTokenizer+ ) -> ServerPromptCacheMatch {+ guard continuation.count == 1,+ continuation[0].role == .user,+ let content = continuation[0].content,+ continuation[0].toolCalls.isEmpty,+ continuation[0].toolCallID == nil,+ entry.assistantTurn.rawStopReason == .endOfTurn+ || entry.assistantTurn.rawStopReason == .maxTokens else {+ return .miss+ }+ var bridge = tokenizer.encodeTextContinuation(userContent: content)+ if entry.assistantTurn.rawStopReason == .maxTokens {+ bridge = entry.uncommittedBoundaryTokenIDs + bridge+ } else if bridge.first != entry.uncommittedBoundaryTokenIDs.first {+ return .miss+ }+ return .hit(+ effectivePromptIDs: entry.kvBackedTokenIDs + bridge,+ cachedPromptTokens: entry.kvPosition)+ }++ private func matchToolContinuation(+ entry: ServerPromptCacheEntry,+ request: ValidatedChatRequest,+ continuation: [GFTokenizer.Message],+ tokenizer: GFTokenizer+ ) -> ServerPromptCacheMatch {+ let calls = entry.assistantTurn.message.toolCalls+ guard entry.assistantTurn.rawStopReason == .toolCalls,+ continuation.count == calls.count,+ zip(continuation, calls).allSatisfy({ message, call in+ message.role == .tool+ && message.toolCallID == call.id+ && (message.name == nil || message.name == call.name)+ && message.content != nil+ && message.toolCalls.isEmpty+ }) else {+ return .miss+ }+ guard let bridge = try? tokenizer.encodeToolResultContinuation(+ cachedMessages: entry.inputMessages,+ assistant: entry.assistantTurn.message,+ incomingMessages: request.messages,+ tools: request.tools),+ bridge.first == entry.uncommittedBoundaryTokenIDs.first else {+ return .miss+ }+ return .hit(+ effectivePromptIDs: entry.kvBackedTokenIDs + bridge,+ cachedPromptTokens: entry.kvPosition)+ }+}diff --git a/Sources/TurboFieldfareServer/Core/ServerTerminationSignals.swift b/Sources/TurboFieldfareServer/Core/ServerTerminationSignals.swiftnew file mode 100644index 00000000..72c83253--- /dev/null+++ b/Sources/TurboFieldfareServer/Core/ServerTerminationSignals.swift@@ -0,0 +1,51 @@+import Darwin+import Dispatch++public actor ServerTerminationSignals {+ private let stream: AsyncStream<Int32>+ private let continuation: AsyncStream<Int32>.Continuation+ private let sources: [any DispatchSourceSignal]++ public init(_ signals: [Int32] = [SIGINT, SIGTERM]) {+ var capturedContinuation: AsyncStream<Int32>.Continuation?+ let stream = AsyncStream<Int32>(bufferingPolicy: .bufferingOldest(1)) {+ capturedContinuation = $0+ }+ let continuation = capturedContinuation!++ self.stream = stream+ self.continuation = continuation+ self.sources = signals.map {+ Darwin.signal($0, SIG_IGN)+ return Self.makeSource(signal: $0, continuation: continuation)+ }+ for source in sources {+ source.resume()+ }+ }++ public func wait() async -> Int32 {+ for await signal in stream {+ return signal+ }+ preconditionFailure("termination signal stream ended without a signal")+ }++ public func cancel() {+ for source in sources {+ source.cancel()+ }+ continuation.finish()+ }++ private nonisolated static func makeSource(+ signal: Int32,+ continuation: AsyncStream<Int32>.Continuation+ ) -> any DispatchSourceSignal {+ let source = DispatchSource.makeSignalSource(signal: signal, queue: .global())+ source.setEventHandler { @Sendable [continuation] in+ continuation.yield(signal)+ }+ return source+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Continuation.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Continuation.swiftnew file mode 100644index 00000000..82faf895--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Continuation.swift@@ -0,0 +1,136 @@+import Metal+import Testing++@testable import TurboFieldfare++extension RawCompletionLoopTests {+ final class ContinuationProducer: ChunkedPrefillRunner, ContinuableLogitProducer,+ @unchecked Sendable+ {+ let vocabSize: Int+ private let terminalToken: Int32+ private(set) var continuationPosition: Int+ private(set) var resetCalls = 0+ private(set) var prepareCalls: [Int] = []+ private(set) var prefillRanges: [Range<Int>] = []++ init(vocabSize: Int, terminalToken: Int32, position: Int) {+ self.vocabSize = vocabSize+ self.terminalToken = terminalToken+ self.continuationPosition = position+ }++ func reset() {+ resetCalls += 1+ continuationPosition = 0+ }++ func prepareForContinuation(expectedPosition: Int) throws {+ guard continuationPosition == expectedPosition else {+ throw PrefillError.prefillCursorMismatch("test cursor mismatch")+ }+ prepareCalls.append(expectedPosition)+ }++ func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws {+ guard continuationPosition == position else {+ throw PrefillError.prefillCursorMismatch("test scalar cursor mismatch")+ }+ continuationPosition += 1+ writeTerminal(to: logits)+ }++ func prefillChunked(tokens: ArraySlice<Int32>,+ startPosition: Int,+ outputMode: PrefillOutputMode,+ config: PrefillRuntimeConfig,+ into logits: MTLBuffer,+ onProgress: (Int) -> Void) async throws -> PrefillResult {+ guard continuationPosition == startPosition else {+ throw PrefillError.prefillCursorMismatch("test prefill cursor mismatch")+ }+ prefillRanges.append(startPosition..<(startPosition + tokens.count))+ continuationPosition += tokens.count+ onProgress(tokens.count)+ writeTerminal(to: logits)+ return PrefillResult(newPosition: continuationPosition,+ seed: .logitsWritten)+ }++ private func writeTerminal(to logits: MTLBuffer) {+ let pointer = logits.contents().bindMemory(to: Float16.self, capacity: vocabSize)+ for index in 0..<vocabSize { pointer[index] = -30 }+ pointer[Int(terminalToken)] = 30+ }+ }++ @Test func resumedChunkedPrefillUsesNonzeroStart() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let prompt = tokenizer.encode("one two three four", addBOS: true)+ let cached = prompt.count - 1+ let producer = ContinuationProducer(+ vocabSize: tokenizer.vocabSize,+ terminalToken: tokenizer.eosID,+ position: cached)+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)+ var progress: [(Int, Int)] = []++ let result = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: prompt,+ config: GenerationConfig(maxNewTokens: 1, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .defaultChunked,+ start: .resume(cachedPromptTokens: cached)+ ) { event in+ if case .prefill(let done, let total) = event {+ progress.append((done, total))+ }+ }++ #expect(producer.resetCalls == 0)+ #expect(producer.prepareCalls == [cached])+ #expect(producer.prefillRanges == [cached..<prompt.count])+ #expect(progress.last?.0 == prompt.count)+ #expect(progress.last?.1 == prompt.count)+ #expect(result.prefillTokens == prompt.count)+ #expect(result.cachedPromptTokens == cached)+ #expect(result.computedPrefillTokens == 1)+ #expect(result.kvPosition == prompt.count)+ #expect(result.kvBackedTokenIDs == prompt)+ #expect(result.uncommittedBoundaryTokenIDs == [tokenizer.eosID])+ }++ @Test func resumeRejectsInvalidCachedCountsBeforeMutatingProducer() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let prompt = tokenizer.encode("one two", addBOS: true)+ let producer = ContinuationProducer(+ vocabSize: tokenizer.vocabSize,+ terminalToken: tokenizer.eosID,+ position: 0)+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)++ for count in [0, prompt.count, prompt.count + 1] {+ await #expect(throws: GeneratorError.self) {+ _ = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: prompt,+ config: GenerationConfig(maxNewTokens: 1, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .off,+ start: .resume(cachedPromptTokens: count)+ ) { _ in }+ }+ }++ #expect(producer.resetCalls == 0)+ #expect(producer.prepareCalls.isEmpty)+ #expect(producer.prefillRanges.isEmpty)+ }+}diff --git a/Tests/TurboFieldfareServer/Fixtures/README.md b/Tests/TurboFieldfareServer/Fixtures/README.mdnew file mode 100644index 00000000..40b34c2b--- /dev/null+++ b/Tests/TurboFieldfareServer/Fixtures/README.md@@ -0,0 +1,12 @@+# OpenCode request fixtures++Sanitized request bodies captured on 2026-07-23 from `[email protected]`.+That source release pins `ai` 6.0.168,+`@ai-sdk/openai-compatible` 2.0.41, and `@ai-sdk/provider` 3.0.8.++- `opencode-1.15.11-initial.json`: 11,521-byte initial streamed request.+- `opencode-1.15.11-tool-result.json`: 12,153-byte follow-up containing the+ fake server's assistant `read` call and OpenCode's tool result.++Temporary paths and call IDs are deterministic and sanitized. The fixtures+contain no credentials or user repository content.diff --git a/Tests/TurboFieldfareServer/Fixtures/opencode-1.15.11-initial.json b/Tests/TurboFieldfareServer/Fixtures/opencode-1.15.11-initial.jsonnew file mode 100644index 00000000..b204e95a--- /dev/null+++ b/Tests/TurboFieldfareServer/Fixtures/opencode-1.15.11-initial.json@@ -0,0 +1,53 @@+{+ "model": "gemma-4-26b-a4b-it",+ "max_tokens": 4096,+ "messages": [+ {+ "role": "system",+ "content": "You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.\n\nIf the user asks for help or wants to give feedback inform them of the following:\n- /help: Get help with using opencode\n- To give feedback, users should report the issue at https://github.com/anomalyco/opencode/issues\n\nWhen the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nOnly use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is <answer>.\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\". Here are some examples to demonstrate appropriate verbosity:\n<example>\nuser: what is 2+2?\nassistant: 4\n</example>\n\n<example>\nuser: is 11 a prime number?\nassistant: Yes\n</example>\n\n<example>\nuser: what command should I run to list files in the current directory?\nassistant: ls\n</example>\n\n<example>\nuser: what command should I run to watch files in the current directory?\nassistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]\nnpm run dev\n</example>\n\n<example>\nuser: what files are in the directory src/?\nassistant: [runs ls and sees foo.c, bar.c, baz.c]\nuser: which file contains the implementation of foo?\nassistant: src/foo.c\n</example>\n\n<example>\nuser: write tests for new feature\nassistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]\n</example>\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n- Implement the solution using all tools available to you\n- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.\n\n# Tool usage policy\n- When doing file search, prefer to use the Task tool in order to reduce context usage.\n- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run \"git status\" and \"git diff\", send a single message with two tool calls to run the calls in parallel.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.\n\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.\n\n# Code References\n\nWhen referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.\n\n<example>\nuser: Where are errors from the client handled?\nassistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.\n</example>\n\nYou are powered by the model named gemma-4-26b-a4b-it. The exact model ID is turbofieldfare/gemma-4-26b-a4b-it\nHere is some useful information about the environment you are running in:\n<env>\n Working directory: /private/tmp/turbo-opencode-capture\n Workspace root folder: /\n Is directory a git repo: no\n Platform: darwin\n Today's date: Thu Jul 23 2026\n</env>"+ },+ {+ "role": "user",+ "content": "\"Read /tmp/turbo-opencode-capture/sentinel.txt and report its exact contents.\""+ }+ ],+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "read",+ "description": "Read a file or directory from the local filesystem. If the path does not exist, an error is returned.\n\nUsage:\n- The filePath parameter should be an absolute path.\n- By default, this tool returns up to 2000 lines from the start of the file.\n- The offset parameter is the line number to start from (1-indexed).\n- To read later sections, call this tool again with a larger offset.\n- Use the grep tool to find specific content in large files or files with long lines.\n- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.\n- Contents are returned with each line prefixed by its line number as `<line>: <content>`. For example, if a file has contents \"foo\\n\", you will receive \"1: foo\\n\". For directories, entries are returned one per line (without line numbers) with a trailing `/` for subdirectories.\n- Any line longer than 2000 characters is truncated.\n- Call this tool in parallel when you know there are multiple files you want to read.\n- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.\n- This tool can read image files and PDFs and return them as file attachments.\n",+ "parameters": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "filePath": {+ "type": "string",+ "description": "The absolute path to the file or directory to read"+ },+ "offset": {+ "minimum": 0,+ "type": "integer",+ "maximum": 9007199254740991,+ "description": "The line number to start reading from (1-indexed)"+ },+ "limit": {+ "minimum": 0,+ "type": "integer",+ "maximum": 9007199254740991,+ "description": "The maximum number of lines to read (defaults to 2000)"+ }+ },+ "required": [+ "filePath"+ ]+ }+ }+ }+ ],+ "tool_choice": "auto",+ "stream": true,+ "stream_options": {+ "include_usage": true+ }+}diff --git a/Tests/TurboFieldfareServer/Fixtures/opencode-1.15.11-tool-result.json b/Tests/TurboFieldfareServer/Fixtures/opencode-1.15.11-tool-result.jsonnew file mode 100644index 00000000..56a2234e--- /dev/null+++ b/Tests/TurboFieldfareServer/Fixtures/opencode-1.15.11-tool-result.json@@ -0,0 +1,72 @@+{+ "model": "gemma-4-26b-a4b-it",+ "max_tokens": 4096,+ "messages": [+ {+ "role": "system",+ "content": "You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.\n\nIf the user asks for help or wants to give feedback inform them of the following:\n- /help: Get help with using opencode\n- To give feedback, users should report the issue at https://github.com/anomalyco/opencode/issues\n\nWhen the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nOnly use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is <answer>.\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\". Here are some examples to demonstrate appropriate verbosity:\n<example>\nuser: what is 2+2?\nassistant: 4\n</example>\n\n<example>\nuser: is 11 a prime number?\nassistant: Yes\n</example>\n\n<example>\nuser: what command should I run to list files in the current directory?\nassistant: ls\n</example>\n\n<example>\nuser: what command should I run to watch files in the current directory?\nassistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]\nnpm run dev\n</example>\n\n<example>\nuser: what files are in the directory src/?\nassistant: [runs ls and sees foo.c, bar.c, baz.c]\nuser: which file contains the implementation of foo?\nassistant: src/foo.c\n</example>\n\n<example>\nuser: write tests for new feature\nassistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]\n</example>\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n- Implement the solution using all tools available to you\n- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.\n\n# Tool usage policy\n- When doing file search, prefer to use the Task tool in order to reduce context usage.\n- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run \"git status\" and \"git diff\", send a single message with two tool calls to run the calls in parallel.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.\n\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.\n\n# Code References\n\nWhen referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.\n\n<example>\nuser: Where are errors from the client handled?\nassistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.\n</example>\n\nYou are powered by the model named gemma-4-26b-a4b-it. The exact model ID is turbofieldfare/gemma-4-26b-a4b-it\nHere is some useful information about the environment you are running in:\n<env>\n Working directory: /private/tmp/turbo-opencode-capture\n Workspace root folder: /\n Is directory a git repo: no\n Platform: darwin\n Today's date: Thu Jul 23 2026\n</env>"+ },+ {+ "role": "user",+ "content": "\"Read /tmp/turbo-opencode-capture/sentinel.txt and report its exact contents.\""+ },+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_0123456789abcdef01234567",+ "type": "function",+ "function": {+ "name": "read",+ "arguments": "{\"filePath\":\"/private/tmp/turbo-opencode-capture/sentinel.txt\"}"+ }+ }+ ]+ },+ {+ "role": "tool",+ "tool_call_id": "call_0123456789abcdef01234567",+ "content": "<path>/private/tmp/turbo-opencode-capture/sentinel.txt</path>\n<type>file</type>\n<content>\n1: TURBO_FIELDFARE_CAPTURE_SENTINEL\n\n(End of file - total 1 lines)\n</content>"+ }+ ],+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "read",+ "description": "Read a file or directory from the local filesystem. If the path does not exist, an error is returned.\n\nUsage:\n- The filePath parameter should be an absolute path.\n- By default, this tool returns up to 2000 lines from the start of the file.\n- The offset parameter is the line number to start from (1-indexed).\n- To read later sections, call this tool again with a larger offset.\n- Use the grep tool to find specific content in large files or files with long lines.\n- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.\n- Contents are returned with each line prefixed by its line number as `<line>: <content>`. For example, if a file has contents \"foo\\n\", you will receive \"1: foo\\n\". For directories, entries are returned one per line (without line numbers) with a trailing `/` for subdirectories.\n- Any line longer than 2000 characters is truncated.\n- Call this tool in parallel when you know there are multiple files you want to read.\n- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.\n- This tool can read image files and PDFs and return them as file attachments.\n",+ "parameters": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "filePath": {+ "type": "string",+ "description": "The absolute path to the file or directory to read"+ },+ "offset": {+ "minimum": 0,+ "type": "integer",+ "maximum": 9007199254740991,+ "description": "The line number to start reading from (1-indexed)"+ },+ "limit": {+ "minimum": 0,+ "type": "integer",+ "maximum": 9007199254740991,+ "description": "The maximum number of lines to read (defaults to 2000)"+ }+ },+ "required": [+ "filePath"+ ]+ }+ }+ }+ ],+ "tool_choice": "auto",+ "stream": true,+ "stream_options": {+ "include_usage": true+ }+}diff --git a/Tests/TurboFieldfareServer/HTTPServerTests.swift b/Tests/TurboFieldfareServer/HTTPServerTests.swiftnew file mode 100644index 00000000..bea9ff91--- /dev/null+++ b/Tests/TurboFieldfareServer/HTTPServerTests.swift@@ -0,0 +1,493 @@+import Darwin+import Foundation+import NIOCore+import Testing+@testable import TurboFieldfare+@testable import TurboFieldfareServerCore++private actor ScriptedServerBackend: ServerInferenceBackend {+ let delayNanoseconds: UInt64++ init(delayNanoseconds: UInt64 = 0) {+ self.delayNanoseconds = delayNanoseconds+ }++ func generate(+ _ request: ValidatedChatRequest,+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void+ ) async throws -> ServerCompletion {+ if delayNanoseconds > 0 {+ try await Task.sleep(nanoseconds: delayNanoseconds)+ }+ onEvent(.content("hello"))+ return ServerCompletion(+ content: "hello",+ toolCalls: [],+ finishReason: "stop",+ usage: OpenAIUsage(promptTokens: 3, completionTokens: 1, totalTokens: 4))+ }+}++private actor MultipleToolBackend: ServerInferenceBackend {+ func generate(+ _ request: ValidatedChatRequest,+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void+ ) async throws -> ServerCompletion {+ let first = ParsedToolCall(+ id: "call_000000000000000000000001",+ name: "read",+ arguments: .object(["path": .string("/tmp/a")]),+ argumentsJSON: #"{"path":"/tmp/a"}"#)+ let second = ParsedToolCall(+ id: "call_000000000000000000000002",+ name: "read",+ arguments: .object(["path": .string("/tmp/b")]),+ argumentsJSON: #"{"path":"/tmp/b"}"#)+ onEvent(.toolCall(first))+ onEvent(.toolCall(second))+ return ServerCompletion(+ content: "",+ toolCalls: [first, second],+ finishReason: "tool_calls",+ usage: OpenAIUsage(promptTokens: 3, completionTokens: 8, totalTokens: 11))+ }+}++private actor ContentAndToolBackend: ServerInferenceBackend {+ func generate(+ _ request: ValidatedChatRequest,+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void+ ) async throws -> ServerCompletion {+ let content = "I will read it."+ let call = ParsedToolCall(+ id: "call_000000000000000000000003",+ name: "read",+ arguments: .object(["path": .string("/tmp/mixed")]),+ argumentsJSON: #"{"path":"/tmp/mixed"}"#)+ onEvent(.content(content))+ onEvent(.toolCall(call))+ return ServerCompletion(+ content: content,+ toolCalls: [call],+ finishReason: "tool_calls",+ usage: OpenAIUsage(promptTokens: 3, completionTokens: 8, totalTokens: 11))+ }+}++private actor PipelinedRequestBackend: ServerInferenceBackend {+ private var continuation: CheckedContinuation<Void, Never>?+ private(set) var generationCount = 0++ var isWaiting: Bool { continuation != nil }++ func release() {+ continuation?.resume()+ continuation = nil+ }++ func generate(+ _ request: ValidatedChatRequest,+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void+ ) async throws -> ServerCompletion {+ generationCount += 1+ await withCheckedContinuation { continuation = $0 }+ onEvent(.content("first"))+ return ServerCompletion(+ content: "first",+ toolCalls: [],+ finishReason: "stop",+ usage: OpenAIUsage(promptTokens: 3, completionTokens: 1, totalTokens: 4))+ }+}++private actor CancellableServerBackend: ServerInferenceBackend {+ private(set) var startedCount = 0+ private(set) var cancellationCount = 0++ func generate(+ _ request: ValidatedChatRequest,+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void+ ) async throws -> ServerCompletion {+ startedCount += 1+ do {+ try await Task.sleep(for: .seconds(30))+ } catch is CancellationError {+ cancellationCount += 1+ throw CancellationError()+ }+ return ServerCompletion(+ content: "unexpected",+ toolCalls: [],+ finishReason: "stop",+ usage: OpenAIUsage(promptTokens: 1, completionTokens: 1, totalTokens: 2))+ }+}++@Suite("OpenAI HTTP server", .serialized)+struct HTTPServerTests {+ @Test func healthModelsAndNonStreamingCompletion() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)++ let health = try await URLSession.shared.data(+ from: URL(string: "http://127.0.0.1:\(port)/health")!).0+ #expect(String(decoding: health, as: UTF8.self).contains(#""status":"ok""#))++ let models = try await URLSession.shared.data(+ from: URL(string: "http://127.0.0.1:\(port)/v1/models")!).0+ #expect(String(decoding: models, as: UTF8.self).contains("test-model"))++ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"hi"}]}+ """#.utf8)+ let (data, response) = try await URLSession.shared.data(for: request)+ #expect((response as? HTTPURLResponse)?.statusCode == 200)+ let object = try #require(+ JSONSerialization.jsonObject(with: data) as? [String: Any])+ let choices = try #require(object["choices"] as? [[String: Any]])+ let message = try #require(choices[0]["message"] as? [String: Any])+ #expect(message["content"] as? String == "hello")+ let usage = try #require(object["usage"] as? [String: Any])+ let details = try #require(usage["prompt_tokens_details"] as? [String: Any])+ #expect(details["cached_tokens"] as? Int == 0)++ try await server.shutdown()+ }++ @Test func streamingUsesStableShapeAndDoneMarker() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"hi"}],+ "stream":true,"stream_options":{"include_usage":true}}+ """#.utf8)+ let (data, response) = try await URLSession.shared.data(for: request)+ #expect((response as? HTTPURLResponse)?.statusCode == 200)+ let text = String(decoding: data, as: UTF8.self)+ #expect(text.contains(#""role":"assistant""#))+ #expect(text.contains(#""content":"hello""#))+ #expect(text.contains(#""finish_reason":"stop""#))+ #expect(text.contains(#""prompt_tokens":3"#))+ #expect(text.contains(#""cached_tokens":0"#))+ #expect(text.hasSuffix("data: [DONE]\n\n"))++ try await server.shutdown()+ }++ @Test func wrongModelUsesOpenAIErrorEnvelope() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"wrong","messages":[{"role":"user","content":"hi"}]}+ """#.utf8)+ let (data, response) = try await URLSession.shared.data(for: request)+ #expect((response as? HTTPURLResponse)?.statusCode == 404)+ #expect(String(decoding: data, as: UTF8.self).contains("model_not_found"))++ try await server.shutdown()+ }++ @Test func streamingHeartbeatKeepsSlowFirstEventAlive() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend(delayNanoseconds: 50_000_000),+ heartbeatInterval: .milliseconds(10))+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"hi"}],"stream":true}+ """#.utf8)+ let data = try await URLSession.shared.data(for: request).0+ #expect(String(decoding: data, as: UTF8.self).contains(": ping\n\n"))++ try await server.shutdown()+ }++ @Test func streamingMultipleToolsUseDistinctIndexes() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: MultipleToolBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"read both"}],+ "stream":true}+ """#.utf8)+ let text = String(decoding: try await URLSession.shared.data(for: request).0,+ as: UTF8.self)+ #expect(text.contains(#""index":0"#))+ #expect(text.contains(#""index":1"#))+ #expect(text.contains(#""finish_reason":"tool_calls""#))++ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"read both"}]}+ """#.utf8)+ let data = try await URLSession.shared.data(for: request).0+ let object = try #require(+ JSONSerialization.jsonObject(with: data) as? [String: Any])+ let choices = try #require(object["choices"] as? [[String: Any]])+ let message = try #require(choices[0]["message"] as? [String: Any])+ #expect(message["content"] is NSNull)+ #expect((message["tool_calls"] as? [[String: Any]])?.count == 2)++ try await server.shutdown()+ }++ @Test func nonStreamingToolCallRetainsVisibleContent() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ContentAndToolBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"read"}]}+ """#.utf8)++ let data = try await URLSession.shared.data(for: request).0+ let object = try #require(+ JSONSerialization.jsonObject(with: data) as? [String: Any])+ let choices = try #require(object["choices"] as? [[String: Any]])+ let message = try #require(choices[0]["message"] as? [String: Any])+ #expect(message["content"] as? String == "I will read it.")+ #expect((message["tool_calls"] as? [[String: Any]])?.count == 1)+ #expect(choices[0]["finish_reason"] as? String == "tool_calls")++ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"read"}],"stream":true}+ """#.utf8)+ let stream = String(+ decoding: try await URLSession.shared.data(for: request).0,+ as: UTF8.self)+ #expect(stream.contains(#""content":"I will read it.""#))+ #expect(stream.contains(#""tool_calls""#))+ #expect(stream.contains(#""finish_reason":"tool_calls""#))++ try await server.shutdown()+ }++ @Test func pipelinedStreamingThenHealthResponsesRemainOrdered() async throws {+ let backend = PipelinedRequestBackend()+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: backend,+ heartbeatInterval: .seconds(10))+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ let socket = try connectedSocket(port: port)++ let body = #"{"model":"test-model","messages":[{"role":"user","content":"hi"}],"stream":true}"#+ let firstRequest =+ "POST /v1/chat/completions HTTP/1.1\r\n"+ + "Host: 127.0.0.1:\(port)\r\n"+ + "Content-Type: application/json\r\n"+ + "Content-Length: \(body.utf8.count)\r\n"+ + "Connection: keep-alive\r\n"+ + "\r\n"+ + body+ let secondRequest =+ "GET /health HTTP/1.1\r\n"+ + "Host: 127.0.0.1:\(port)\r\n"+ + "Connection: close\r\n"+ + "\r\n"+ try writeAll(socket: socket, text: firstRequest + secondRequest)+ let waitDeadline = ContinuousClock.now + .seconds(2)+ while await !backend.isWaiting, ContinuousClock.now < waitDeadline {+ try await Task.sleep(for: .milliseconds(1))+ }+ #expect(await backend.isWaiting)++ var response = try readAvailable(socket: socket, timeoutMilliseconds: 200)+ #expect(response.contains("text/event-stream"))+ #expect(response.components(separatedBy: "HTTP/1.1 200").count - 1 == 1)+ #expect(!response.contains(#""status":"ok""#))++ await backend.release()+ response += try readUntil(+ socket: socket,+ timeoutMilliseconds: 2_000,+ condition: { $0.contains(#""status":"ok""#) })+ #expect(response.components(separatedBy: "HTTP/1.1 200").count - 1 == 2)+ let done = try #require(response.range(of: "data: [DONE]"))+ let health = try #require(response.range(of: #""status":"ok""#))+ #expect(done.lowerBound < health.lowerBound)+ #expect(await backend.generationCount == 1)++ Darwin.close(socket)+ try await server.shutdown()+ }++ @Test func shutdownAfterListenerClosesIsIdempotent() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)++ try await channel.close().get()+ try await server.shutdown()+ try await server.shutdown()+ }++ @Test func shutdownCancelsActiveAndQueuedRequestsBeforeReturning() async throws {+ let backend = CancellableServerBackend()+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: backend)+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ let firstSocket = try connectedSocket(port: port)+ let secondSocket = try connectedSocket(port: port)+ defer {+ Darwin.close(firstSocket)+ Darwin.close(secondSocket)+ }+ let body =+ #"{"model":"test-model","messages":[{"role":"user","content":"wait"}]}"#+ let request =+ "POST /v1/chat/completions HTTP/1.1\r\n"+ + "Host: 127.0.0.1:\(port)\r\n"+ + "Content-Type: application/json\r\n"+ + "Content-Length: \(body.utf8.count)\r\n"+ + "Connection: keep-alive\r\n"+ + "\r\n"+ + body++ try writeAll(socket: firstSocket, text: request)+ let activeDeadline = ContinuousClock.now + .seconds(2)+ while await backend.startedCount != 1, ContinuousClock.now < activeDeadline {+ await Task.yield()+ }+ #expect(await backend.startedCount == 1)++ try writeAll(socket: secondSocket, text: request)+ let queuedDeadline = ContinuousClock.now + .seconds(2)+ while await server.queuedRequestCount != 1, ContinuousClock.now < queuedDeadline {+ await Task.yield()+ }+ #expect(await server.queuedRequestCount == 1)+ #expect(await server.acceptedConnectionCount == 2)++ try await server.shutdown()++ #expect(await backend.cancellationCount == 1)+ #expect(await backend.startedCount == 1)+ #expect(await server.queuedRequestCount == 0)+ #expect(await !server.hasActiveRequest)+ #expect(await server.acceptedConnectionCount == 0)+ try await server.shutdown()+ }+}++private enum RawSocketError: Error {+ case systemCall(String, Int32)+ case timeout+}++private func connectedSocket(port: Int) throws -> Int32 {+ let descriptor = Darwin.socket(AF_INET, SOCK_STREAM, 0)+ guard descriptor >= 0 else {+ throw RawSocketError.systemCall("socket", errno)+ }+ var address = sockaddr_in()+ address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)+ address.sin_family = sa_family_t(AF_INET)+ address.sin_port = in_port_t(port).bigEndian+ address.sin_addr = in_addr(s_addr: inet_addr("127.0.0.1"))+ let result = withUnsafePointer(to: &address) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ Darwin.connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))+ }+ }+ guard result == 0 else {+ let code = errno+ Darwin.close(descriptor)+ throw RawSocketError.systemCall("connect", code)+ }+ return descriptor+}++private func writeAll(socket: Int32, text: String) throws {+ let bytes = Array(text.utf8)+ var written = 0+ while written < bytes.count {+ let count = bytes.withUnsafeBytes {+ Darwin.send(socket, $0.baseAddress!.advanced(by: written),+ bytes.count - written, 0)+ }+ guard count > 0 else {+ throw RawSocketError.systemCall("send", errno)+ }+ written += count+ }+}++private func readAvailable(socket: Int32, timeoutMilliseconds: Int32) throws -> String {+ var result: [UInt8] = []+ var descriptor = pollfd(fd: socket, events: Int16(POLLIN), revents: 0)+ while Darwin.poll(&descriptor, 1, timeoutMilliseconds) > 0 {+ var buffer = [UInt8](repeating: 0, count: 4_096)+ let count = Darwin.recv(socket, &buffer, buffer.count, 0)+ guard count >= 0 else {+ throw RawSocketError.systemCall("recv", errno)+ }+ if count == 0 { break }+ result.append(contentsOf: buffer.prefix(count))+ descriptor.revents = 0+ }+ return String(decoding: result, as: UTF8.self)+}++private func readUntil(+ socket: Int32,+ timeoutMilliseconds: Int32,+ condition: (String) -> Bool+) throws -> String {+ let deadline = Date().addingTimeInterval(Double(timeoutMilliseconds) / 1_000)+ var result = ""+ while Date() < deadline {+ result += try readAvailable(socket: socket, timeoutMilliseconds: 50)+ if condition(result) { return result }+ }+ throw RawSocketError.timeout+}diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swiftnew file mode 100644index 00000000..f4e7b4d1--- /dev/null+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift@@ -0,0 +1,323 @@+import Foundation+import Testing+@testable import TurboFieldfare+@testable import TurboFieldfareServerCore++@Suite("OpenAI request validation")+struct OpenAIValidationTests {+ @Test func capturedOpenCodeInitialRequestValidates() throws {+ let request = try fixture("opencode-1.15.11-initial.json")+ let validated = try OpenAIRequestValidator.validate(+ request, modelID: "gemma-4-26b-a4b-it")+ #expect(validated.stream)+ #expect(validated.includeUsage)+ #expect(validated.tools.count == 1)+ #expect(validated.maximumCompletionTokens == 4096)+ }++ @Test func capturedOpenCodeToolResultValidates() throws {+ let request = try fixture("opencode-1.15.11-tool-result.json")+ let validated = try OpenAIRequestValidator.validate(+ request, modelID: "gemma-4-26b-a4b-it")+ #expect(validated.messages.count == 4)+ #expect(validated.messages[2].toolCalls.count == 1)+ #expect(validated.messages[3].toolCallID == "call_0123456789abcdef01234567")+ }++ @Test func capturedOpenCodePromptFits16KWith4096Completion() async throws {+ let request = try fixture("opencode-1.15.11-tool-result.json")+ let validated = try OpenAIRequestValidator.validate(+ request, modelID: "gemma-4-26b-a4b-it")+ let tokenizer = try await GFTokenizer.load()+ let ids = try tokenizer.encodeToolChat(+ messages: validated.messages, tools: validated.tools)+ #expect(ids.count <= 16_384 - 4_096)+ }++ @Test func requiredToolChoiceIsRejected() throws {+ let data = Data(#"""+ {"model":"m","messages":[{"role":"user","content":"x"}],"tool_choice":"required"}+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ #expect(throws: ServerRequestError.self) {+ try OpenAIRequestValidator.validate(request, modelID: "m")+ }+ }++ @Test func acceptsLeadingSystemAndDeveloperGuidance() throws {+ let data = Data(#"""+ {"model":"m","messages":[+ {"role":"system","content":"system"},+ {"role":"developer","content":"developer"},+ {"role":"user","content":"hello"}+ ]}+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")+ #expect(validated.messages.map(\.role) == [.system, .developer, .user])+ }++ @Test func rejectsLateDeveloperGuidance() throws {+ let data = Data(#"""+ {"model":"m","messages":[+ {"role":"user","content":"hello"},+ {"role":"developer","content":"late"}+ ]}+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ #expect(throws: ServerRequestError.self) {+ try OpenAIRequestValidator.validate(request, modelID: "m")+ }+ }++ @Test func wideIntegerToolArgumentsRoundTripExactly() async throws {+ let expected = "9007199254740993"+ let parsed = try GemmaToolCallParser().parse(+ "call:lookup{id:\(expected)}",+ allowedTools: ["lookup"],+ id: "call_0123456789abcdef01234567")+ #expect(parsed.argumentsJSON.contains(#""id":\#(expected)"#))+ let signedMinimum = String(Int64.min)+ let signedMaximum = String(Int64.max)+ let unsignedMaximum = String(UInt64.max)+ let edges = try GemmaToolCallParser().parse(+ "call:lookup{minimum:\(signedMinimum),maximum:\(signedMaximum),unsigned:\(unsignedMaximum)}",+ allowedTools: ["lookup"],+ id: "call_0123456789abcdef01234568")+ #expect(edges.arguments.objectValue?["minimum"] == .integer(.min))+ #expect(edges.arguments.objectValue?["maximum"] == .integer(.max))+ #expect(edges.arguments.objectValue?["unsigned"] == .unsignedInteger(.max))+ let encodedEdges = try edges.arguments.encoded()+ #expect(encodedEdges.contains(signedMinimum))+ #expect(encodedEdges.contains(signedMaximum))+ #expect(encodedEdges.contains(unsignedMaximum))+ #expect(try JSONDecoder().decode(+ JSONValue.self,+ from: Data(encodedEdges.utf8)) == edges.arguments)+ for malformed in ["+1", "01", "1.", ".1", "1e", "--1"] {+ #expect(throws: GemmaToolCallParserError.self) {+ try GemmaToolCallParser().parse(+ "call:lookup{id:\(malformed)}",+ allowedTools: ["lookup"],+ id: "call_0123456789abcdef01234570")+ }+ }++ let data = Data(#"""+ {+ "model":"m",+ "messages":[+ {"role":"user","content":"lookup"},+ {"role":"assistant","tool_calls":[{+ "id":"call_0123456789abcdef01234567",+ "type":"function",+ "function":{"name":"lookup","arguments":"{\"id\":9007199254740993}"}+ }]}+ ],+ "tools":[{+ "type":"function",+ "function":{+ "name":"lookup",+ "parameters":{"type":"object","properties":{"id":{"type":"integer"}}}+ }+ }]+ }+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")+ let call = try #require(validated.messages[1].toolCalls.first)+ #expect(try call.arguments.encoded().contains(#""id":\#(expected)"#))+ let tokenizer = try await GFTokenizer.load()+ let rendered = tokenizer.decode(+ try tokenizer.encodeToolChat(+ messages: validated.messages,+ tools: validated.tools),+ skipSpecialTokens: false)+ #expect(rendered.contains(expected))++ let unrepresentableHistory = Data(#"""+ {+ "model":"m",+ "messages":[+ {"role":"user","content":"lookup"},+ {"role":"assistant","tool_calls":[{+ "id":"call_0123456789abcdef01234569",+ "type":"function",+ "function":{"name":"lookup","arguments":"{\"id\":18446744073709551615}"}+ }]}+ ],+ "tools":[{+ "type":"function",+ "function":{+ "name":"lookup",+ "parameters":{"type":"object","properties":{"id":{"type":"integer"}}}+ }+ }]+ }+ """#.utf8)+ let rejected = try JSONDecoder().decode(+ OpenAIChatRequest.self,+ from: unrepresentableHistory)+ #expect(throws: ServerRequestError.self) {+ try OpenAIRequestValidator.validate(rejected, modelID: "m")+ }+ }++ @Test func acceptedNonIdentifierParameterKeysParseAndRender() async throws {+ let data = Data(#"""+ {+ "model":"m",+ "messages":[{"role":"user","content":"lookup"}],+ "tools":[{+ "type":"function",+ "function":{+ "name":"lookup",+ "parameters":{+ "type":"object",+ "properties":{+ "$id":{"type":"string"},+ "file-path":{"type":"string"},+ "nested":{"type":"object","properties":{"child-key":{"type":"integer"}}}+ }+ }+ }+ }]+ }+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")+ let tokenizer = try await GFTokenizer.load()+ _ = try tokenizer.encodeToolChat(+ messages: validated.messages,+ tools: validated.tools)+ let parsed = try GemmaToolCallParser().parse(+ #"call:lookup{$id:<|"|>item<|"|>,file-path:<|"|>/tmp/x<|"|>,nested:{child-key:7}}"#,+ allowedTools: ["lookup"],+ id: "call_0123456789abcdef01234567")+ #expect(parsed.arguments.objectValue?["$id"] == .string("item"))+ #expect(parsed.arguments.objectValue?["file-path"] == .string("/tmp/x"))+ }++ @Test func ambiguousParameterKeysFailValidation() throws {+ let data = Data(#"""+ {+ "model":"m",+ "messages":[{"role":"user","content":"lookup"}],+ "tools":[{+ "type":"function",+ "function":{+ "name":"lookup",+ "parameters":{+ "type":"object",+ "allOf":[{+ "type":"object",+ "properties":{"bad:key":{"type":"string"}}+ }]+ }+ }+ }]+ }+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ #expect(throws: ServerRequestError.self) {+ try OpenAIRequestValidator.validate(request, modelID: "m")+ }+ }++ private func fixture(_ name: String) throws -> OpenAIChatRequest {+ let url = try #require(Bundle.module.url(+ forResource: name, withExtension: nil, subdirectory: "Fixtures"))+ return try JSONDecoder().decode(OpenAIChatRequest.self, from: Data(contentsOf: url))+ }+}++@Suite("Gemma tool calls")+struct GemmaToolCallTests {+ @Test func parsesNestedArgumentsAndGemmaQuotes() throws {+ let parsed = try GemmaToolCallParser().parse(+ #"call:read{path:<|"|>/tmp/ü"<|"|>,options:{lines:[1,2],exact:true}}"#,+ allowedTools: ["read"],+ id: "call_0123456789abcdef01234567")+ #expect(parsed.name == "read")+ #expect(parsed.argumentsJSON.contains(#""path":"/tmp/ü\"""#))+ #expect(parsed.argumentsJSON.contains(#""exact":true"#))+ }++ @Test func unknownToolFailsClosed() {+ #expect(throws: GemmaToolCallParserError.unknownTool("write")) {+ try GemmaToolCallParser().parse(+ "call:write{path:<|\"|>/tmp/x<|\"|>}",+ allowedTools: ["read"],+ id: "call_0123456789abcdef01234567")+ }+ }++ @Test func parsesJSONUnicodeEscapesAndSurrogatePairs() throws {+ let parsed = try GemmaToolCallParser().parse(+ #"call:read{path:"\u00fc-\ud83c\udf33",note:"a\b\f"}"#,+ allowedTools: ["read"],+ id: "call_0123456789abcdef01234567")+ #expect(parsed.argumentsJSON.contains(#""path":"ü-🌳""#))+ #expect(parsed.argumentsJSON.contains(#""note":"a\b\f""#))+ }++ @Test func suppressesThoughtBlockAndExposesTextAfterChannelClose() async throws {+ let tokenizer = try await GFTokenizer.load()+ let decoder = StructuredAssistantDecoder(tokenizer: tokenizer, allowedTools: [])+ #expect(try decoder.consume(tokenID: tokenizer.channelStartID, delta: "").isEmpty)+ #expect(try decoder.consume(tokenID: tokenizer.bosID, delta: "thought").isEmpty)+ #expect(try decoder.consume(tokenID: tokenizer.bosID, delta: "\n").isEmpty)+ #expect(try decoder.consume(tokenID: tokenizer.bosID, delta: "private").isEmpty)+ #expect(try decoder.consume(tokenID: tokenizer.channelEndID, delta: "").isEmpty)+ #expect(try decoder.consume(tokenID: tokenizer.bosID, delta: "visible") == [+ .content("visible"),+ ])+ }+}++@Suite("Streaming stop matcher")+struct StreamingStopMatcherTests {+ @Test func withholdsCrossChunkStop() {+ var matcher = StreamingStopMatcher(stops: ["END"])+ #expect(matcher.push("hello E") == "hello ")+ #expect(matcher.push("N") == "")+ #expect(matcher.push("D ignored") == "")+ #expect(matcher.isStopped)+ }++ @Test func flushesUnicodeTail() {+ var matcher = StreamingStopMatcher(stops: ["🌳stop"])+ #expect(matcher.push("hello 🌳") == "hello ")+ #expect(matcher.finish() == "🌳")+ }+}++@Suite("Server arguments")+struct ServerArgumentTests {+ @Test func defaults() throws {+ let arguments = try ServerArguments.parse(["--model", "model.gturbo"])+ #expect(arguments.port == 8080)+ #expect(arguments.maxContext == 16_384)+ #expect(arguments.queueLimit == 4)+ #expect(arguments.promptCacheMode == .singlePrefix)+ }++ @Test func parsesSinglePrefixModeAndRejectsUnknownMode() throws {+ let arguments = try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prompt-cache-mode", "single-prefix",+ ])+ #expect(arguments.promptCacheMode == .singlePrefix)+ let rollback = try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prompt-cache-mode", "off",+ ])+ #expect(rollback.promptCacheMode == .off)+ #expect(throws: ServerArgumentError.self) {+ try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prompt-cache-mode", "many",+ ])+ }+ }+}diff --git a/Tests/TurboFieldfareServer/ServerCoordinatorTests.swift b/Tests/TurboFieldfareServer/ServerCoordinatorTests.swiftnew file mode 100644index 00000000..bd26ea31--- /dev/null+++ b/Tests/TurboFieldfareServer/ServerCoordinatorTests.swift@@ -0,0 +1,46 @@+import Testing+@testable import TurboFieldfareServerCore++private actor TestGate {+ private var continuation: CheckedContinuation<Void, Never>?++ func wait() async {+ await withCheckedContinuation { continuation = $0 }+ }++ func open() {+ continuation?.resume()+ continuation = nil+ }+}++@Suite("Server coordinator")+struct ServerCoordinatorTests {+ @Test func boundsFIFOAndRecoversAfterCancellation() async throws {+ let coordinator = ServerCoordinator(queueLimit: 1)+ let gate = TestGate()+ let active = Task {+ try await coordinator.run {+ await gate.wait()+ return 1+ }+ }+ while await !coordinator.isActive {+ await Task.yield()+ }+ let queued = Task {+ try await coordinator.run { 2 }+ }+ while await coordinator.queuedCount != 1 {+ await Task.yield()+ }+ await #expect(throws: ServerRequestError.queueFull) {+ try await coordinator.run { 3 }+ }+ queued.cancel()+ _ = try? await queued.value+ await gate.open()+ #expect(try await active.value == 1)+ #expect(await coordinator.queuedCount == 0)+ }+}diff --git a/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swiftnew file mode 100644index 00000000..4731faaf--- /dev/null+++ b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift@@ -0,0 +1,242 @@+import Foundation+import Testing++@testable import TurboFieldfare+@testable import TurboFieldfareServerCore++@Suite("Server prompt cache")+struct ServerPromptCacheTests {+ private let domain = ServerPromptCacheDomain(+ modelID: "model",+ sourceSnapshotHash: "snapshot",+ runtimeProfileHash: "profile",+ maximumContext: 16_384,+ kvStorage: "fp16",+ fp16RingEnabled: true,+ templateSHA256: "template")++ @Test func textContinuationUsesActualGeneratedHistoryAndOnlyPrefillsSuffix() async throws {+ let tokenizer = try await GFTokenizer.load()+ let initial = request(messages: [+ GFTokenizer.Message(role: .user, content: "first"),+ ])+ let initialPrompt = tokenizer.encode(+ try tokenizer.applyChatTemplate(initial.messages),+ addBOS: false)+ let generated = tokenizer.encode("answer", addBOS: false)+ let kvBacked = initialPrompt + generated+ var cache = ServerPromptCache()+ cache.publish(+ domain: domain,+ request: initial,+ content: "answer",+ calls: [],+ result: rawResult(+ prompt: initialPrompt,+ kvBacked: kvBacked,+ boundary: tokenizer.endOfTurnID,+ reason: .endOfTurn))++ let continuation = request(messages: initial.messages + [+ GFTokenizer.Message(role: .assistant, content: "answer"),+ GFTokenizer.Message(role: .user, content: "second"),+ ])+ let rendered = tokenizer.encode(+ try tokenizer.applyChatTemplate(continuation.messages),+ addBOS: false)+ let match = cache.match(+ domain: domain,+ request: continuation,+ renderedPromptIDs: rendered,+ tokenizer: tokenizer)++ guard case .hit(let effective, let cached) = match else {+ Issue.record("expected text continuation hit")+ return+ }+ let bridge = tokenizer.encodeTextContinuation(userContent: "second")+ #expect(cached == kvBacked.count)+ #expect(effective == kvBacked + bridge)+ #expect(!rendered.prefix(kvBacked.count).elementsEqual(kvBacked))+ #expect(effective[cached] == tokenizer.endOfTurnID)+ }++ @Test func capturedOpenCodeToolResultUsesFrozenToolBoundary() async throws {+ let tokenizer = try await GFTokenizer.load()+ let initial = try validatedFixture("opencode-1.15.11-initial.json")+ let continuation = try validatedFixture("opencode-1.15.11-tool-result.json")+ let initialPrompt = try tokenizer.encodeToolChat(+ messages: initial.messages,+ tools: initial.tools)+ let assistant = continuation.messages[initial.messages.count]+ let prefix = try tokenizer.encodeToolChat(+ messages: initial.messages + [assistant],+ tools: initial.tools)+ let callStart = try #require(prefix.lastIndex(of: tokenizer.toolCallStartID))+ let callEnd = try #require(prefix.lastIndex(of: tokenizer.toolCallEndID))+ let generatedCall = Array(prefix[callStart...callEnd])+ let kvBacked = initialPrompt + generatedCall+ let historicalCall = try #require(assistant.toolCalls.first)+ let parsedCall = ParsedToolCall(+ id: historicalCall.id,+ name: historicalCall.name,+ arguments: historicalCall.arguments,+ argumentsJSON: try historicalCall.arguments.encoded())+ var cache = ServerPromptCache()+ cache.publish(+ domain: domain,+ request: initial,+ content: "",+ calls: [parsedCall],+ result: rawResult(+ prompt: initialPrompt,+ kvBacked: kvBacked,+ boundary: tokenizer.toolResponseID,+ reason: .toolCalls))+ let rendered = try tokenizer.encodeToolChat(+ messages: continuation.messages,+ tools: continuation.tools)++ let match = cache.match(+ domain: domain,+ request: continuation,+ renderedPromptIDs: rendered,+ tokenizer: tokenizer)++ guard case .hit(let effective, let cached) = match else {+ Issue.record("expected captured OpenCode tool-result hit")+ return+ }+ let bridge = try tokenizer.encodeToolResultContinuation(+ cachedMessages: initial.messages,+ assistant: assistant,+ incomingMessages: continuation.messages,+ tools: continuation.tools)+ #expect(cached == kvBacked.count)+ #expect(effective == kvBacked + bridge)+ #expect(bridge.first == tokenizer.toolResponseID)+ #expect(!rendered.prefix(kvBacked.count).elementsEqual(kvBacked))+ }++ @Test func mismatchedLineageDomainAndUnsafeStopsMiss() async throws {+ let tokenizer = try await GFTokenizer.load()+ let initial = request(messages: [+ GFTokenizer.Message(role: .user, content: "first"),+ ])+ let prompt = tokenizer.encode(+ try tokenizer.applyChatTemplate(initial.messages),+ addBOS: false)+ var cache = ServerPromptCache()++ for reason in [StopReason.stopString, .eos] {+ cache.publish(+ domain: domain,+ request: initial,+ content: "answer",+ calls: [],+ result: rawResult(+ prompt: prompt,+ kvBacked: prompt,+ boundary: tokenizer.eosID,+ reason: reason))+ #expect(cache.entry == nil)+ }++ cache.publish(+ domain: domain,+ request: initial,+ content: "answer",+ calls: [],+ result: rawResult(+ prompt: prompt,+ kvBacked: prompt + tokenizer.encode("answer", addBOS: false),+ boundary: tokenizer.endOfTurnID,+ reason: .endOfTurn))+ let changed = request(messages: [+ GFTokenizer.Message(role: .user, content: "changed"),+ GFTokenizer.Message(role: .assistant, content: "answer"),+ GFTokenizer.Message(role: .user, content: "second"),+ ])+ let rendered = tokenizer.encode(+ try tokenizer.applyChatTemplate(changed.messages),+ addBOS: false)+ #expect(cache.match(+ domain: domain,+ request: changed,+ renderedPromptIDs: rendered,+ tokenizer: tokenizer) == .miss)+ }++ @Test func tailCompletedStopStringDoesNotPublishPrefix() async throws {+ let tokenizer = try await GFTokenizer.load()+ let initial = request(messages: [+ GFTokenizer.Message(role: .user, content: "first"),+ ])+ let prompt = tokenizer.encode(+ try tokenizer.applyChatTemplate(initial.messages),+ addBOS: false)+ var matcher = StreamingStopMatcher(stops: ["🌳stop"])+ #expect(matcher.push("answer 🌳") == "answer ")+ #expect(matcher.push("stop") == "")+ #expect(matcher.isStopped)++ var cache = ServerPromptCache()+ cache.publish(+ domain: domain,+ request: initial,+ content: "answer ",+ calls: [],+ result: rawResult(+ prompt: prompt,+ kvBacked: prompt,+ boundary: tokenizer.endOfTurnID,+ reason: .endOfTurn),+ stopStringFiltered: matcher.isStopped)+ #expect(cache.entry == nil)+ }++ private func request(+ messages: [GFTokenizer.Message],+ tools: [GFTokenizer.FunctionDefinition] = []+ ) -> ValidatedChatRequest {+ ValidatedChatRequest(+ messages: messages,+ tools: tools,+ stream: false,+ includeUsage: false,+ generationConfig: GenerationConfig(maxNewTokens: 16, temperature: 0),+ maximumCompletionTokens: 16)+ }++ private func rawResult(+ prompt: [Int32],+ kvBacked: [Int32],+ boundary: Int32,+ reason: StopReason+ ) -> RawDecodeResult {+ RawDecodeResult(+ prefillTokens: prompt.count,+ cachedPromptTokens: 0,+ computedPrefillTokens: prompt.count,+ prefillSeconds: 0,+ newTokens: 1,+ decodeSeconds: 0,+ reason: reason,+ kvPosition: kvBacked.count,+ kvBackedTokenIDs: kvBacked,+ uncommittedBoundaryTokenIDs: [boundary])+ }++ private func validatedFixture(_ name: String) throws -> ValidatedChatRequest {+ let url = try #require(Bundle.module.url(+ forResource: name,+ withExtension: nil,+ subdirectory: "Fixtures"))+ let request = try JSONDecoder().decode(+ OpenAIChatRequest.self,+ from: Data(contentsOf: url))+ return try OpenAIRequestValidator.validate(+ request,+ modelID: "gemma-4-26b-a4b-it")+ }+}diff --git a/Tests/TurboFieldfareServer/ServerTerminationSignalTests.swift b/Tests/TurboFieldfareServer/ServerTerminationSignalTests.swiftnew file mode 100644index 00000000..2d614ef9--- /dev/null+++ b/Tests/TurboFieldfareServer/ServerTerminationSignalTests.swift@@ -0,0 +1,31 @@+import Darwin+import Testing+@testable import TurboFieldfareServerCore++@Suite("Server termination signals", .serialized)+struct ServerTerminationSignalTests {+ @Test func dispatchSignalCrossesIntoAsyncCodeWithoutExecutorTrap() async {+ let signals = ServerTerminationSignals([SIGUSR1])+ let waiter = Task {+ await signals.wait()+ }++ kill(getpid(), SIGUSR1)++ #expect(await waiter.value == SIGUSR1)+ await signals.cancel()+ }++ @Test func repeatedSignalDeliveryKeepsTheFirstSignal() async {+ let signals = ServerTerminationSignals([SIGUSR1])+ let waiter = Task {+ await signals.wait()+ }++ kill(getpid(), SIGUSR1)+ kill(getpid(), SIGUSR1)++ #expect(await waiter.value == SIGUSR1)+ await signals.cancel()+ }+}diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.mdindex ab60368b..54d14934 100644--- a/docs/COMMUNITY_BENCHMARKS.md+++ b/docs/COMMUNITY_BENCHMARKS.md@@ -24,7 +24,7 @@ swift build -c release --product TurboFieldfareCLIConfirm that no other model process is running:```bash-pgrep -fl 'TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'+pgrep -fl 'TurboFieldfareServer|TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'```Continue only when that command prints nothing.diff --git a/docs/OPENAI_SERVER.md b/docs/OPENAI_SERVER.mdnew file mode 100644index 00000000..3633c3b3--- /dev/null+++ b/docs/OPENAI_SERVER.md@@ -0,0 +1,145 @@+# Local OpenAI-compatible server++`TurboFieldfareServer` exposes a local Chat Completions API for one Gemma+model. It binds to `127.0.0.1` without authentication or TLS. Do not expose it+through a proxy or tunnel.++## Start the server++First, install the model with the Mac app or `TurboFieldfareRepack`. Then check+that no other TurboFieldfare model process is running:++```bash+pgrep -fl 'TurboFieldfareServer|TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'+```++If the command prints a match, do not start the server.++```bash+swift build -c release --product TurboFieldfareServer+.build/release/TurboFieldfareServer \+ --model scratch/gemma4.gturbo \+ --port 8080 \+ --max-context 16384+```++The server loads the model before opening the port. Wait for+`TurboFieldfareServer ready`, then keep the process running while clients use+it.++Check the server from another terminal:++```bash+curl --silent --show-error http://127.0.0.1:8080/health+curl --silent --show-error http://127.0.0.1:8080/v1/models+curl --silent --show-error http://127.0.0.1:8080/v1/chat/completions \+ -H 'Content-Type: application/json' \+ -d '{+ "model": "gemma-4-26b-a4b-it",+ "messages": [{"role": "user", "content": "Reply with exactly READY."}],+ "temperature": 0,+ "max_completion_tokens": 16+ }'+```++By default, the server runs one generation and queues up to four requests. Use+`--queue-limit` to change the queue size. Press Control-C to stop the server.++## Connect a client++The base URL is `http://127.0.0.1:8080/v1`. Some client libraries require an+API key, but the server ignores it.++Python:++```python+from openai import OpenAI++client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="local")+response = client.chat.completions.create(+ model="gemma-4-26b-a4b-it",+ messages=[{"role": "user", "content": "Say hello in one sentence."}],+)+print(response.choices[0].message.content)+```++OpenCode:++```json+{+ "$schema": "https://opencode.ai/config.json",+ "provider": {+ "turbofieldfare": {+ "npm": "@ai-sdk/openai-compatible",+ "name": "TurboFieldfare",+ "options": {+ "baseURL": "http://127.0.0.1:8080/v1",+ "apiKey": "local"+ },+ "models": {+ "gemma-4-26b-a4b-it": {+ "name": "Gemma 4 26B-A4B IT"+ }+ }+ }+ }+}+```++Select `turbofieldfare/gemma-4-26b-a4b-it` in OpenCode.++## Prompt reuse++Single-prefix KV reuse is on by default. Send the complete message history with+every request. When a request continues the retained conversation exactly, the+server reuses the verified KV prefix and reports the number of reused tokens in:++```text+usage.prompt_tokens_details.cached_tokens+```++The server retains one prefix. A different or incompatible history replaces+it. Use `--prompt-cache-mode off` to disable reuse.++## Tool calls++The server can return OpenAI-style function calls, but it cannot authorize or+execute them. The client runs the tool loop:++1. Send function schemas in `tools`.+2. When `finish_reason` is `"tool_calls"`, inspect each function name and JSON+ argument object. Apply the client's normal permission checks before running+ the function.+3. Append the assistant message, including its unchanged `tool_calls`.+4. Append each result as a `role: "tool"` message. Its `tool_call_id` must+ match the call it resolves.+5. Send the complete history and tool schemas again.++The server accepts only function tools. Omit `tool_choice` or set it to `auto`+to allow calls. Set it to `none` to disable them. The server does not support+`required`, named tool selection, or `parallel_tool_calls: false`.++## Supported API++Endpoints:++- `GET /health`+- `GET /v1/models`+- `POST /v1/chat/completions`++Chat Completions supports JSON and Server-Sent Events responses. Set+`"stream": true` for streaming. Set+`"stream_options": {"include_usage": true}` to receive a final usage chunk.++Requests may contain system, developer, user, assistant, and tool messages.+Supported options include `temperature`, `top_p`, `top_k`,+`repetition_penalty`, `seed`, `stop`, `max_tokens`,+`max_completion_tokens`, and function-tool fields.++The server supports one model and one choice. It does not support the Responses+API, legacy Completions, embeddings, multimodal input, structured output,+batching, log probabilities, or remote model switching.++Context length can be 4K, 8K, 16K, 32K, or 64K. The default is 16K. Larger FP16+KV contexts use more memory. On an 8 GB Mac, run one model process at a time and+watch memory pressure.diff --git a/docs/SYSTEM_DESIGN.md b/docs/SYSTEM_DESIGN.mdindex c5b69fcd..3f81b86d 100644--- a/docs/SYSTEM_DESIGN.md+++ b/docs/SYSTEM_DESIGN.md@@ -227,13 +227,17 @@ flowchart LRThe Mac app and CLI `--messages-file` mode use the pinned text-only Gemma 4 chatformat. The app wraps one user prompt. `--messages-file` accepts user and-assistant messages plus an optional leading system message. Assistant messages-render with Gemma's `model` role.+assistant messages plus optional leading system guidance. Assistant messages+render with Gemma's `model` role. The separate loopback server uses the pinned+upstream Jinja template for developer messages, function declarations,+assistant tool calls, and tool results.The runtime stops generation on `<eos>` (token 1), `<turn|>` (token 106), or-`<|tool_response>` (token 50). The third token is a defensive boundary; tool-calling itself is not supported. CLI `--prompt` bypasses chat framing for raw-completion and reproducible comparisons.+`<|tool_response>` (token 50). The app and CLI treat the third token as a+defensive boundary. The server instead parses complete native+`<|tool_call>` blocks before returning OpenAI function calls and fails closed+on malformed output. CLI `--prompt` bypasses chat framing for raw completion+and reproducible comparisons.## Prefill@@ -421,10 +425,13 @@ The current runtime supports text-only generation with the pinned Gemma 426B-A4B instruction checkpoint. The source model supports image input, butTurboFieldfare omits its vision tower.-The Mac app offers 4K, 8K, 16K, 32K, and 64K context lengths. Current-acceptance evidence covers up to 4K; memory, correctness, and speed beyond 4K-have not been characterized. Vision input, training, fine-tuning, server-batching, and general model support are outside the current scope.+The Mac app offers 4K, 8K, 16K, 32K, and 64K context lengths. Published app+and CLI acceptance evidence covers up to 4K. Vision input, training,+fine-tuning, server batching, remote serving, and general model support are+outside the current scope. The optional HTTP server is loopback-only, owns one+warm model, serializes generation, and retains one verified conversational KV+prefix by default. It retains only that prefix. See the+[local server guide](OPENAI_SERVER.md).TurboFieldfare is a research system. The Mac app exposes a small set of typedruntime controls. The production path uses FP16 KV, exact split-K/V@@ -434,6 +441,7 @@ default.## Read next+- [Local OpenAI-compatible server](OPENAI_SERVER.md)- [Benchmarks](BENCHMARKS.md)- [The experiments that shaped TurboFieldfare](OPTIMIZATION_JOURNEY.md)- [Complete experiment inventory](experiments/EXPERIMENT_INVENTORY.md)