//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
	if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
		key = keys[i];
		if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
			get: ((k) => from[k]).bind(null, key),
			enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
		});
	}
	return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
	value: mod,
	enumerable: true
}) : target, mod));

//#endregion
let child_process = require("child_process");
child_process = __toESM(child_process);
let path = require("path");
path = __toESM(path);
let url = require("url");
url = __toESM(url);
let fs = require("fs");
fs = __toESM(fs);
let net = require("net");
net = __toESM(net);
let crypto = require("crypto");
crypto = __toESM(crypto);
let readline = require("readline");
readline = __toESM(readline);

//#region src/executor.ts
const __dirname$1 = (0, path.dirname)((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
/**
* Get the path to the Swift executable
*/
function getSwiftExecutablePath() {
	const productionPath = (0, path.join)(__dirname$1, "..", "swift", ".build", "release", "AppleFoundationModelsWrapper");
	const debugPath = (0, path.join)(__dirname$1, "..", "swift", ".build", "debug", "AppleFoundationModelsWrapper");
	try {
		(0, fs.accessSync)(productionPath, fs.constants.X_OK);
		return productionPath;
	} catch {
		return debugPath;
	}
}
/**
* Execute a command via the Swift wrapper
*/
async function executeSwiftCommand(action, parameters) {
	const executablePath = getSwiftExecutablePath();
	const command = {
		action,
		parameters: parameters || {}
	};
	const commandJson = JSON.stringify(command);
	return new Promise((resolve, reject) => {
		const child = (0, child_process.spawn)(executablePath, [], { stdio: [
			"pipe",
			"pipe",
			"pipe"
		] });
		let stdout = "";
		let stderr = "";
		child.stdout.on("data", (data) => {
			stdout += data.toString();
		});
		child.stderr.on("data", (data) => {
			stderr += data.toString();
		});
		child.on("error", (error) => {
			reject(/* @__PURE__ */ new Error(`Failed to spawn Swift process: ${error.message}`));
		});
		child.on("close", (code) => {
			if (stderr) console.error("Swift stderr:", stderr);
			if (code !== 0) {
				reject(/* @__PURE__ */ new Error(`Swift process exited with code ${code}`));
				return;
			}
			try {
				const response = JSON.parse(stdout);
				if (!response.success) {
					reject(new Error(response.error || "Unknown error from Swift wrapper"));
					return;
				}
				resolve(response.data);
			} catch (error) {
				reject(/* @__PURE__ */ new Error(`Failed to parse Swift response: ${error instanceof Error ? error.message : "Unknown error"}`));
			}
		});
		child.stdin.write(commandJson + "\n");
		child.stdin.end();
	});
}
/**
* Execute a streaming command via the Swift wrapper
* Yields chunks as they arrive
*
* IMPLEMENTATION NOTE: This function reads stdout line-by-line, parsing each line
* as a separate JSON response. The Swift wrapper outputs single-line JSON for each
* chunk (using printCompactResponse) to enable this streaming architecture.
* Protocol: {"success":true,"data":{"chunk":"text","done":false}}
*/
async function* executeSwiftStreamCommand(action, parameters) {
	const executablePath = getSwiftExecutablePath();
	const command = {
		action,
		parameters: parameters || {}
	};
	const commandJson = JSON.stringify(command);
	const child = (0, child_process.spawn)(executablePath, [], { stdio: [
		"pipe",
		"pipe",
		"pipe"
	] });
	let stderr = "";
	let buffer = "";
	child.stderr.on("data", (data) => {
		stderr += data.toString();
	});
	child.stdin.write(commandJson + "\n");
	child.stdin.end();
	for await (const data of child.stdout) {
		buffer += data.toString();
		const lines = buffer.split("\n");
		buffer = lines.pop() || "";
		for (const line of lines) {
			if (!line.trim()) continue;
			try {
				const response = JSON.parse(line);
				if (!response.success) throw new Error(response.error || "Unknown error from Swift wrapper");
				if (response.data?.done) return;
				if (response.data?.chunk) yield response.data.chunk;
			} catch (error) {
				throw new Error(`Failed to parse streaming response: ${error instanceof Error ? error.message : "Unknown error"}`);
			}
		}
	}
	if (buffer.trim()) try {
		const response = JSON.parse(buffer);
		if (!response.success) throw new Error(response.error || "Unknown error from Swift wrapper");
	} catch (error) {}
	const exitCode = await new Promise((resolve) => {
		child.on("close", resolve);
	});
	if (stderr) console.error("Swift stderr:", stderr);
	if (exitCode !== 0) throw new Error(`Swift process exited with code ${exitCode}`);
}

//#endregion
//#region src/executors/process-per-call.ts
var ProcessPerCallExecutor = class {
	/**
	* Execute a command via process-per-call pattern
	* Spawns a new Swift process for each call
	*/
	async execute(action, parameters) {
		return executeSwiftCommand(action, parameters);
	}
	/**
	* Execute a streaming command via process-per-call pattern
	* Spawns a new Swift process that streams results
	*/
	async *executeStream(action, parameters) {
		yield* executeSwiftStreamCommand(action, parameters);
	}
	/**
	* Close the executor
	* No-op for process-per-call since there's no persistent state
	*/
	async close() {}
};

//#endregion
//#region src/executors/persistent-server.ts
let socketCounter = 0;
var PersistentServerExecutor = class {
	socket;
	serverProcess;
	tools;
	socketPath;
	messageHandlers = /* @__PURE__ */ new Map();
	connected = false;
	connecting = null;
	constructor(tools) {
		this.tools = new Map(tools.map((t) => [t.name, t]));
		this.socketPath = `/tmp/afm-${process.pid}-${Date.now()}-${socketCounter++}.sock`;
	}
	/**
	* Ensure connection to Swift server
	* Starts server if not running and connects socket
	*/
	async ensureConnected() {
		if (this.connected && this.socket?.writable) return;
		if (this.connecting) return this.connecting;
		this.connecting = (async () => {
			try {
				if (!this.serverProcess || this.serverProcess.exitCode !== null) await this.startServer();
				if (!this.socket || !this.socket.writable) await this.connectSocket();
				this.connected = true;
			} finally {
				this.connecting = null;
			}
		})();
		return this.connecting;
	}
	/**
	* Start the Swift server process
	*/
	async startServer() {
		const serverPath = getSwiftExecutablePath();
		if ((0, fs.existsSync)(this.socketPath)) (0, fs.unlinkSync)(this.socketPath);
		this.serverProcess = (0, child_process.spawn)(serverPath, [
			"--persistent-server",
			"--socket",
			this.socketPath
		], { stdio: [
			"ignore",
			"pipe",
			"pipe"
		] });
		if (this.serverProcess.stderr) readline.default.createInterface({ input: this.serverProcess.stderr }).on("line", (line) => {
			console.error("[Swift Server]:", line);
		});
		this.serverProcess.on("exit", (code) => {
			console.error(`[Swift Server] Exited with code ${code}`);
			this.connected = false;
			this.socket?.destroy();
			this.socket = void 0;
		});
		await this.waitForSocket(5e3);
	}
	/**
	* Wait for Unix socket file to exist
	*/
	async waitForSocket(timeoutMs) {
		const startTime = Date.now();
		while (!(0, fs.existsSync)(this.socketPath)) {
			if (Date.now() - startTime > timeoutMs) throw new Error(`Timeout waiting for server socket: ${this.socketPath}`);
			await new Promise((resolve) => setTimeout(resolve, 50));
		}
		await new Promise((resolve) => setTimeout(resolve, 100));
	}
	/**
	* Connect to the Unix socket
	*/
	async connectSocket() {
		this.socket = net.default.createConnection(this.socketPath);
		let buffer = "";
		this.socket.on("data", (data) => {
			buffer += data.toString();
			const lines = buffer.split("\n");
			buffer = lines.pop() || "";
			for (const line of lines) {
				if (!line.trim()) continue;
				try {
					const message = JSON.parse(line);
					this.handleMessage(message);
				} catch (error) {
					console.error("[Socket] Failed to parse message:", error);
				}
			}
		});
		this.socket.on("error", (error) => {
			console.error("[Socket] Error:", error);
			this.connected = false;
		});
		this.socket.on("close", () => {
			this.connected = false;
		});
		await new Promise((resolve, reject) => {
			this.socket.once("connect", () => resolve());
			this.socket.once("error", (err) => reject(err));
		});
		await this.sendToolDefinitions();
	}
	/**
	* Send tool definitions to Swift server
	*/
	async sendToolDefinitions() {
		const toolDefs = Array.from(this.tools.values()).map((tool) => ({
			name: tool.name,
			description: tool.description
		}));
		await this.sendRequest("registerTools", { tools: toolDefs });
	}
	/**
	* Handle incoming message from Swift server
	*/
	async handleMessage(message) {
		if (message.method === "executeTool") {
			await this.handleToolCall(message);
			return;
		}
		if (message.id) {
			const handler = this.messageHandlers.get(message.id);
			if (handler) {
				if (message.error) handler({ error: message.error.message });
				else handler({ result: message.result });
				this.messageHandlers.delete(message.id);
			}
		}
	}
	/**
	* Handle tool execution request from Swift
	*/
	async handleToolCall(message) {
		const { name, arguments: args } = message.params;
		const tool = this.tools.get(name);
		if (!tool) {
			this.sendResponse(message.id, { error: {
				code: -32601,
				message: `Tool not found: ${name}`
			} });
			return;
		}
		try {
			const result = await tool.call(args);
			this.sendResponse(message.id, { result: result.value });
		} catch (error) {
			this.sendResponse(message.id, { error: {
				code: -32603,
				message: error instanceof Error ? error.message : "Tool execution failed"
			} });
		}
	}
	/**
	* Send JSON-RPC request to Swift server
	*/
	async sendRequest(method, params) {
		const id = (0, crypto.randomUUID)();
		return new Promise((resolve, reject) => {
			this.messageHandlers.set(id, (data) => {
				if (data.error) reject(new Error(data.error));
				else resolve(data.result);
			});
			const message = {
				jsonrpc: "2.0",
				id,
				method,
				params
			};
			this.socket.write(JSON.stringify(message) + "\n");
			setTimeout(() => {
				if (this.messageHandlers.has(id)) {
					this.messageHandlers.delete(id);
					reject(/* @__PURE__ */ new Error("Request timeout"));
				}
			}, 3e4);
		});
	}
	/**
	* Send JSON-RPC response to Swift server
	*/
	sendResponse(id, response) {
		const message = {
			jsonrpc: "2.0",
			id,
			...response
		};
		this.socket.write(JSON.stringify(message) + "\n");
	}
	/**
	* Execute a command via persistent server
	*/
	async execute(action, parameters) {
		await this.ensureConnected();
		return this.sendRequest(action, parameters);
	}
	/**
	* Execute a streaming command via persistent server
	*/
	async *executeStream(action, parameters) {
		await this.ensureConnected();
		const id = (0, crypto.randomUUID)();
		const chunks = [];
		let done = false;
		let error = null;
		this.messageHandlers.set(id, (data) => {
			if (data.error) {
				error = new Error(data.error);
				done = true;
			} else if (data.result?.done) done = true;
			else if (data.result?.chunk) chunks.push(data.result.chunk);
		});
		const message = {
			jsonrpc: "2.0",
			id,
			method: `${action}Stream`,
			params: parameters
		};
		this.socket.write(JSON.stringify(message) + "\n");
		while (!done) {
			if (error) throw error;
			if (chunks.length > 0) yield chunks.shift();
			else await new Promise((resolve) => setTimeout(resolve, 10));
		}
		while (chunks.length > 0) yield chunks.shift();
		this.messageHandlers.delete(id);
	}
	/**
	* Close the executor and clean up resources
	* Shuts down Swift server and removes socket file
	*/
	async close() {
		if (this.socket) {
			this.socket.destroy();
			this.socket = void 0;
		}
		if (this.serverProcess && this.serverProcess.exitCode === null) {
			this.serverProcess.kill("SIGTERM");
			await Promise.race([new Promise((resolve) => {
				this.serverProcess.once("exit", () => resolve());
			}), new Promise((resolve) => setTimeout(resolve, 2e3))]);
			if (this.serverProcess.exitCode === null) this.serverProcess.kill("SIGKILL");
			this.serverProcess = void 0;
		}
		try {
			if ((0, fs.existsSync)(this.socketPath)) (0, fs.unlinkSync)(this.socketPath);
		} catch (error) {}
		this.connected = false;
	}
};

//#endregion
//#region src/types.ts
/**
* Type definitions matching Apple's FoundationModels API
*/
/**
* Availability status of the system language model
*/
let Availability = /* @__PURE__ */ function(Availability$1) {
	/** Model is available and ready to use */
	Availability$1["Available"] = "available";
	/** Model is unavailable - device not eligible */
	Availability$1["DeviceNotEligible"] = "deviceNotEligible";
	/** Model is unavailable - Apple Intelligence not enabled */
	Availability$1["AppleIntelligenceNotEnabled"] = "appleIntelligenceNotEnabled";
	/** Model is unavailable - model not ready (downloading or initializing) */
	Availability$1["ModelNotReady"] = "modelNotReady";
	return Availability$1;
}({});
/**
* Use case for specialized language models
*/
let UseCase = /* @__PURE__ */ function(UseCase$1) {
	/** Specialized for content tagging, entity extraction, and topic detection */
	UseCase$1["ContentTagging"] = "contentTagging";
	return UseCase$1;
}({});
/**
* Sampling mode for text generation
*/
let SamplingMode = /* @__PURE__ */ function(SamplingMode$1) {
	/** Deterministic - always picks highest probability token */
	SamplingMode$1["Greedy"] = "greedy";
	/** Random sampling from the probability distribution */
	SamplingMode$1["Random"] = "random";
	return SamplingMode$1;
}({});
/**
* Instructions provide context, role, and preferences for model responses
*/
var Instructions = class {
	text;
	constructor(text) {
		Object.defineProperty(this, "text", {
			value: text,
			writable: false,
			enumerable: true,
			configurable: false
		});
	}
};
/**
* Guardrails for safety filtering
*/
var Guardrails = class Guardrails {
	static _default;
	static get default() {
		if (!this._default) this._default = new Guardrails();
		return this._default;
	}
	constructor() {}
};
/**
* Tool output wrapper
*/
var ToolOutput = class {
	value;
	constructor(value) {
		Object.defineProperty(this, "value", {
			value,
			writable: false,
			enumerable: true,
			configurable: false
		});
	}
};
/**
* Finish reason for generation (legacy)
*/
let FinishReason = /* @__PURE__ */ function(FinishReason$1) {
	/** Generation completed naturally */
	FinishReason$1["Stop"] = "stop";
	/** Hit maximum token limit */
	FinishReason$1["Length"] = "length";
	/** Content filtered */
	FinishReason$1["ContentFilter"] = "contentFilter";
	/** Unknown or other reason */
	FinishReason$1["Unknown"] = "unknown";
	return FinishReason$1;
}({});
/**
* Role of a message in a conversation (legacy)
*/
let MessageRole = /* @__PURE__ */ function(MessageRole$1) {
	/** System message that sets the context */
	MessageRole$1["System"] = "system";
	/** Message from the user */
	MessageRole$1["User"] = "user";
	/** Message from the assistant */
	MessageRole$1["Assistant"] = "assistant";
	return MessageRole$1;
}({});

//#endregion
//#region src/foundation-models.ts
/**
* SystemLanguageModel - Apple's on-device language model
* This is a 1-to-1 mapping of the Swift SystemLanguageModel class
* 
* Usage:
* ```typescript
* // Access the default model
* const model = SystemLanguageModel.default;
* 
* // Check availability
* if (model.isAvailable) {
*   // Create a session and generate
*   const session = new LanguageModelSession(model);
*   const response = await session.respond('Hello!');
* }
* 
* // Or use a specialized model
* const taggingModel = new SystemLanguageModel(UseCase.ContentTagging);
* ```
*/
var SystemLanguageModel = class SystemLanguageModel {
	modelId;
	useCase;
	modelInfo;
	static _defaultInstance;
	/**
	* The default system language model
	* Maps to: SystemLanguageModel.default (static property in Swift)
	*/
	static get default() {
		if (!this._defaultInstance) this._defaultInstance = new SystemLanguageModel("default");
		return this._defaultInstance;
	}
	/**
	* Get a list of available language models (internal helper)
	* Note: The actual FoundationModels API only exposes SystemLanguageModel.default
	* This is kept for internal use only.
	* @internal
	*/
	static get availableModels() {
		return executeSwiftCommand("listAvailableModels");
	}
	constructor(idOrUseCase) {
		if (typeof idOrUseCase === "string") this.modelId = idOrUseCase;
		else {
			this.useCase = idOrUseCase;
			this.modelId = `useCase-${idOrUseCase}`;
		}
	}
	/**
	* Get the model ID
	*/
	get id() {
		return this.modelId;
	}
	/**
	* Get the availability status of the model
	* Maps to: SystemLanguageModel.availability (instance property in Swift)
	*/
	get availability() {
		return Availability.Available;
	}
	/**
	* Convenience getter to check if the system is entirely ready
	* Maps to: SystemLanguageModel.isAvailable (instance property in Swift)
	*/
	get isAvailable() {
		return this.availability === Availability.Available;
	}
	/**
	* Get the model name (lazy loaded, for internal use)
	* @internal
	*/
	async getName() {
		await this.ensureModelInfo();
		return this.modelInfo?.name ?? "Unknown";
	}
	/**
	* Get the maximum tokens for this model (lazy loaded, for internal use)
	* @internal
	*/
	async getMaxTokens() {
		await this.ensureModelInfo();
		return this.modelInfo?.maxTokens ?? 0;
	}
	/**
	* Generate text using this language model (internal use - prefer LanguageModelSession)
	* Maps to: SystemLanguageModel.generate(prompt:config:) in Swift
	* @internal
	*/
	async generate(prompt, config) {
		const result = await executeSwiftCommand("generateText", {
			prompt,
			modelId: this.modelId,
			...config
		});
		return {
			text: result.text,
			finishReason: result.finishReason || FinishReason.Unknown
		};
	}
	/**
	* Generate text with streaming (internal use - prefer LanguageModelSession)
	* Maps to: SystemLanguageModel streaming functionality in Swift
	* @internal
	*/
	async *generateStream(prompt, config) {
		for await (const chunk of executeSwiftStreamCommand("generateStream", {
			prompt,
			modelId: this.modelId,
			...config
		})) yield chunk;
	}
	/**
	* Ensure model info is loaded
	* @internal
	*/
	async ensureModelInfo() {
		if (this.modelInfo) return;
		this.modelInfo = (await SystemLanguageModel.availableModels).find((m) => m.id === this.modelId);
		if (!this.modelInfo) throw new Error(`Model with id '${this.modelId}' not found`);
	}
};
/**
* LanguageModelSession - Manages stateful interactions with the language model
* This is a 1-to-1 mapping of the Swift LanguageModelSession class
* 
* Usage:
* ```typescript
* // Create a session with the default model
* const session = new LanguageModelSession();
* 
* // With instructions
* const session = new LanguageModelSession(
*   SystemLanguageModel.default,
*   Guardrails.default,
*   [],
*   new Instructions('You are a helpful assistant.')
* );
* 
* // Send a prompt and get a response
* const response = await session.respond('Tell me a joke');
* console.log(response.content);
* 
* // Stream a response
* const stream = session.streamResponse('Write a story');
* for await (const chunk of stream) {
*   console.log(chunk);
* }
* 
* // Access conversation history
* const history = session.transcript;
* ```
*/
var LanguageModelSession = class {
	model;
	guardrails;
	tools;
	instructions;
	executor;
	transcriptHistory = [];
	_isResponding = false;
	/**
	* Create a new LanguageModelSession
	*
	* Maps to multiple Swift initializers:
	* - init()
	* - init(instructions:)
	* - init(model:)
	* - init(model:instructions:)
	* - init(model:guardrails:tools:instructions:)
	*
	* Note: The actual Swift API does NOT have a separate `guardrails` parameter.
	* Guardrails are managed internally by the framework.
	*
	* IMPORTANT: Tool execution is not yet fully implemented. Tools can be registered
	* but automatic execution during respond/streamResponse is pending architecture updates.
	* For now, you must manually handle tool calls from the response transcript.
	*
	* @param model - The language model to use (defaults to SystemLanguageModel.default)
	* @param guardrails - Kept for backwards compatibility, but ignored (guardrails are internal)
	* @param tools - Array of tools available for the model to call (defaults to [])
	* @param instructions - Context, role, and preferences for model responses (optional)
	*
	* @example
	* ```typescript
	* class WeatherTool implements Tool {
	*   name = 'getWeather';
	*   description = 'Gets current weather';
	*   async call(args: { city: string }) {
	*     return new ToolOutput(`Sunny in ${args.city}`);
	*   }
	* }
	*
	* const session = new LanguageModelSession(
	*   SystemLanguageModel.default,
	*   Guardrails.default,
	*   [new WeatherTool()],
	*   new Instructions('You can check weather')
	* );
	* ```
	*/
	constructor(model = SystemLanguageModel.default, guardrails = Guardrails.default, tools = [], instructions) {
		this.model = model;
		this.guardrails = guardrails;
		this.tools = tools;
		this.instructions = instructions;
		if (tools.length > 0) this.executor = new PersistentServerExecutor(tools);
		else this.executor = new ProcessPerCallExecutor();
		if (this.instructions) this.transcriptHistory.push({
			type: "instructions",
			instructions: this.instructions
		});
	}
	/**
	* Indicates whether the model is currently generating a response
	* Maps to: LanguageModelSession.isResponding (instance property in Swift)
	*/
	get isResponding() {
		return this._isResponding;
	}
	/**
	* Get the conversation transcript
	* Maps to: LanguageModelSession.transcript (instance property in Swift)
	*/
	get transcript() {
		return [...this.transcriptHistory];
	}
	async respond(prompt, options) {
		this._isResponding = true;
		try {
			this.transcriptHistory.push({
				type: "prompt",
				content: prompt
			});
			const contextPrompt = this.buildContextPrompt();
			const data = await this.executor.execute("generateText", {
				prompt: contextPrompt,
				maxTokens: options?.maximumResponseTokens,
				temperature: options?.temperature,
				sampling: options?.sampling
			});
			const responseText = data.text || data.content || "";
			this.transcriptHistory.push({
				type: "response",
				content: responseText
			});
			return {
				content: responseText,
				transcriptEntries: [...this.transcriptHistory]
			};
		} finally {
			this._isResponding = false;
		}
	}
	/**
	* Stream the model's response incrementally
	* Maps to: LanguageModelSession.streamResponse(to:) in Swift
	*
	* @param prompt - The text prompt to send
	* @returns AsyncIterable that yields text chunks
	*/
	async *streamResponse(prompt) {
		this._isResponding = true;
		try {
			this.transcriptHistory.push({
				type: "prompt",
				content: prompt
			});
			const contextPrompt = this.buildContextPrompt();
			let fullResponse = "";
			for await (const chunk of this.executor.executeStream("generateStream", { prompt: contextPrompt })) {
				fullResponse += chunk;
				yield chunk;
			}
			this.transcriptHistory.push({
				type: "response",
				content: fullResponse
			});
		} finally {
			this._isResponding = false;
		}
	}
	/**
	* Preload session resources for faster initial responses
	* Maps to: LanguageModelSession.prewarm() in Swift
	*
	* Prewarming initializes the model and allocates resources ahead of time,
	* reducing latency for the first generation request. This is especially useful
	* when you know you'll need the model soon but want to minimize wait time.
	*
	* @example
	* ```typescript
	* const session = new LanguageModelSession();
	* await session.prewarm(); // Initialize resources
	* // First generation will be faster
	* const response = await session.respond('Hello');
	* ```
	*/
	async prewarm() {
		await executeSwiftCommand("prewarm", {});
	}
	/**
	* Preload session with a prompt prefix for optimized generation
	* Maps to: LanguageModelSession.prewarm(promptPrefix:) in Swift
	*
	* Prewarming with a prefix allows the model to process and cache the prefix,
	* which can significantly speed up generation when using that prefix. This is
	* particularly useful for system prompts that will be reused or template-based generation.
	*
	* @param promptPrefix - The prompt prefix to preload
	* @example
	* ```typescript
	* const session = new LanguageModelSession();
	* await session.prewarmWithPrefix('You are a helpful coding assistant.');
	* // Subsequent generations with this prefix will be faster
	* const response = await session.respond('that specializes in TypeScript...');
	* ```
	*/
	async prewarmWithPrefix(promptPrefix) {
		await executeSwiftCommand("prewarmWithPrefix", { prefix: promptPrefix });
	}
	/**
	* Close the session and clean up resources
	*
	* **API DEVIATION**: This method does not exist in the Swift FoundationModels API,
	* where resource cleanup is automatic via ARC (Automatic Reference Counting).
	* In JavaScript, we need explicit cleanup for:
	* - Persistent server processes (when using tools)
	* - Unix socket connections
	* - Background threads
	*
	* **When to call**:
	* - Required: When session has tools (uses persistent server)
	* - Optional: When session has no tools (process-per-call, no cleanup needed)
	*
	* **Best Practice**: Always call close() in a finally block or use try-finally pattern.
	*
	* @example
	* ```typescript
	* // With tools (persistent server - cleanup required)
	* const session = new LanguageModelSession(model, undefined, [weatherTool]);
	* try {
	*   await session.respond('What\'s the weather?');
	* } finally {
	*   await session.close();  // Shuts down server, removes socket
	* }
	*
	* // Without tools (process-per-call - cleanup optional but harmless)
	* const simpleSession = new LanguageModelSession();
	* try {
	*   await simpleSession.respond('Hello');
	* } finally {
	*   await simpleSession.close();  // No-op, but good practice
	* }
	* ```
	*/
	async close() {
		await this.executor.close();
	}
	/**
	* Build a context prompt from transcript history
	* @internal
	*/
	buildContextPrompt() {
		return this.transcriptHistory.map((entry) => {
			switch (entry.type) {
				case "instructions": return `Instructions: ${entry.instructions.text}`;
				case "prompt": return `User: ${entry.content}`;
				case "response": return `Assistant: ${entry.content}`;
				case "toolCalls": return `Tools called: ${entry.calls.length}`;
				case "toolOutput": return `Tool output: ${JSON.stringify(entry.output)}`;
				default: return "";
			}
		}).filter(Boolean).join("\n\n");
	}
};

//#endregion
exports.Availability = Availability;
exports.FinishReason = FinishReason;
exports.Guardrails = Guardrails;
exports.Instructions = Instructions;
exports.LanguageModelSession = LanguageModelSession;
exports.MessageRole = MessageRole;
exports.SamplingMode = SamplingMode;
exports.SystemLanguageModel = SystemLanguageModel;
exports.ToolOutput = ToolOutput;
exports.UseCase = UseCase;
//# sourceMappingURL=index.cjs.map