@reactive-agents/llm-provider 0.6.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -10
- package/dist/index.d.ts +54 -4
- package/dist/index.js +248 -71
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/whatwg-fetch/fetch.js","../../../node_modules/ollama/dist/browser.mjs","../../../node_modules/ollama/dist/index.mjs","../src/types.ts","../src/errors.ts","../src/llm-service.ts","../src/llm-config.ts","../src/prompt-manager.ts","../src/token-counter.ts","../src/providers/anthropic.ts","../src/retry.ts","../src/providers/openai.ts","../src/providers/local.ts","../src/provider-defaults.ts","../src/providers/gemini.ts","../src/providers/litellm.ts","../src/testing.ts","../src/structured-output.ts","../src/runtime.ts"],"sourcesContent":["/* eslint-disable no-prototype-builtins */\nvar g =\n (typeof globalThis !== 'undefined' && globalThis) ||\n (typeof self !== 'undefined' && self) ||\n // eslint-disable-next-line no-undef\n (typeof global !== 'undefined' && global) ||\n {}\n\nvar support = {\n searchParams: 'URLSearchParams' in g,\n iterable: 'Symbol' in g && 'iterator' in Symbol,\n blob:\n 'FileReader' in g &&\n 'Blob' in g &&\n (function() {\n try {\n new Blob()\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in g,\n arrayBuffer: 'ArrayBuffer' in g\n}\n\nfunction isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n}\n\nif (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n}\n\nfunction normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {\n throw new TypeError('Invalid character in header field name: \"' + name + '\"')\n }\n return name.toLowerCase()\n}\n\nfunction normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n}\n\n// Build a destructive iterator for the value list\nfunction iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n}\n\nexport function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n if (header.length != 2) {\n throw new TypeError('Headers constructor: expected name/value pair to be length 2, found' + header.length)\n }\n this.append(header[0], header[1])\n }, this)\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n}\n\nHeaders.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue + ', ' + value : value\n}\n\nHeaders.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n}\n\nHeaders.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n}\n\nHeaders.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n}\n\nHeaders.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n}\n\nHeaders.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n}\n\nHeaders.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push(name)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.values = function() {\n var items = []\n this.forEach(function(value) {\n items.push(value)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push([name, value])\n })\n return iteratorFor(items)\n}\n\nif (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n}\n\nfunction consumed(body) {\n if (body._noBody) return\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n}\n\nfunction fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n}\n\nfunction readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n}\n\nfunction readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type)\n var encoding = match ? match[1] : 'utf-8'\n reader.readAsText(blob, encoding)\n return promise\n}\n\nfunction readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n}\n\nfunction bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n}\n\nfunction Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n /*\n fetch-mock wraps the Response object in an ES6 Proxy to\n provide useful test harness features such as flush. However, on\n ES5 browsers without fetch or Proxy support pollyfills must be used;\n the proxy-pollyfill is unable to proxy an attribute unless it exists\n on the object before the Proxy is created. This change ensures\n Response.bodyUsed exists on the instance, while maintaining the\n semantic of setting Request.bodyUsed in the constructor before\n _initBody is called.\n */\n // eslint-disable-next-line no-self-assign\n this.bodyUsed = this.bodyUsed\n this._bodyInit = body\n if (!body) {\n this._noBody = true;\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n this._bodyText = body = Object.prototype.toString.call(body)\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n var isConsumed = consumed(this)\n if (isConsumed) {\n return isConsumed\n } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {\n return Promise.resolve(\n this._bodyArrayBuffer.buffer.slice(\n this._bodyArrayBuffer.byteOffset,\n this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength\n )\n )\n } else {\n return Promise.resolve(this._bodyArrayBuffer)\n }\n } else if (support.blob) {\n return this.blob().then(readBlobAsArrayBuffer)\n } else {\n throw new Error('could not read as ArrayBuffer')\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n}\n\n// HTTP methods whose capitalization should be normalized\nvar methods = ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE']\n\nfunction normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return methods.indexOf(upcased) > -1 ? upcased : method\n}\n\nexport function Request(input, options) {\n if (!(this instanceof Request)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n\n options = options || {}\n var body = options.body\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n this.signal = input.signal\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n } else {\n this.url = String(input)\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.signal = options.signal || this.signal || (function () {\n if ('AbortController' in g) {\n var ctrl = new AbortController();\n return ctrl.signal;\n }\n }());\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n\n if (this.method === 'GET' || this.method === 'HEAD') {\n if (options.cache === 'no-store' || options.cache === 'no-cache') {\n // Search for a '_' parameter in the query string\n var reParamSearch = /([?&])_=[^&]*/\n if (reParamSearch.test(this.url)) {\n // If it already exists then set the value with the current time\n this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime())\n } else {\n // Otherwise add a new '_' parameter to the end with the current time\n var reQueryString = /\\?/\n this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime()\n }\n }\n }\n}\n\nRequest.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n}\n\nfunction decode(body) {\n var form = new FormData()\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n}\n\nfunction parseHeaders(rawHeaders) {\n var headers = new Headers()\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ')\n // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill\n // https://github.com/github/fetch/issues/748\n // https://github.com/zloirock/core-js/issues/751\n preProcessedHeaders\n .split('\\r')\n .map(function(header) {\n return header.indexOf('\\n') === 0 ? header.substr(1, header.length) : header\n })\n .forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n try {\n headers.append(key, value)\n } catch (error) {\n console.warn('Response ' + error.message)\n }\n }\n })\n return headers\n}\n\nBody.call(Request.prototype)\n\nexport function Response(bodyInit, options) {\n if (!(this instanceof Response)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = options.status === undefined ? 200 : options.status\n if (this.status < 200 || this.status > 599) {\n throw new RangeError(\"Failed to construct 'Response': The status provided (0) is outside the range [200, 599].\")\n }\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = options.statusText === undefined ? '' : '' + options.statusText\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n}\n\nBody.call(Response.prototype)\n\nResponse.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n}\n\nResponse.error = function() {\n var response = new Response(null, {status: 200, statusText: ''})\n response.ok = false\n response.status = 0\n response.type = 'error'\n return response\n}\n\nvar redirectStatuses = [301, 302, 303, 307, 308]\n\nResponse.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n}\n\nexport var DOMException = g.DOMException\ntry {\n new DOMException()\n} catch (err) {\n DOMException = function(message, name) {\n this.message = message\n this.name = name\n var error = Error(message)\n this.stack = error.stack\n }\n DOMException.prototype = Object.create(Error.prototype)\n DOMException.prototype.constructor = DOMException\n}\n\nexport function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n\n if (request.signal && request.signal.aborted) {\n return reject(new DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest()\n\n function abortXhr() {\n xhr.abort()\n }\n\n xhr.onload = function() {\n var options = {\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n // This check if specifically for when a user fetches a file locally from the file system\n // Only if the status is out of a normal range\n if (request.url.indexOf('file://') === 0 && (xhr.status < 200 || xhr.status > 599)) {\n options.status = 200;\n } else {\n options.status = xhr.status;\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n setTimeout(function() {\n resolve(new Response(body, options))\n }, 0)\n }\n\n xhr.onerror = function() {\n setTimeout(function() {\n reject(new TypeError('Network request failed'))\n }, 0)\n }\n\n xhr.ontimeout = function() {\n setTimeout(function() {\n reject(new TypeError('Network request timed out'))\n }, 0)\n }\n\n xhr.onabort = function() {\n setTimeout(function() {\n reject(new DOMException('Aborted', 'AbortError'))\n }, 0)\n }\n\n function fixUrl(url) {\n try {\n return url === '' && g.location.href ? g.location.href : url\n } catch (e) {\n return url\n }\n }\n\n xhr.open(request.method, fixUrl(request.url), true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false\n }\n\n if ('responseType' in xhr) {\n if (support.blob) {\n xhr.responseType = 'blob'\n } else if (\n support.arrayBuffer\n ) {\n xhr.responseType = 'arraybuffer'\n }\n }\n\n if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers || (g.Headers && init.headers instanceof g.Headers))) {\n var names = [];\n Object.getOwnPropertyNames(init.headers).forEach(function(name) {\n names.push(normalizeName(name))\n xhr.setRequestHeader(name, normalizeValue(init.headers[name]))\n })\n request.headers.forEach(function(value, name) {\n if (names.indexOf(name) === -1) {\n xhr.setRequestHeader(name, value)\n }\n })\n } else {\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n }\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr)\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr)\n }\n }\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n}\n\nfetch.polyfill = true\n\nif (!g.fetch) {\n g.fetch = fetch\n g.Headers = Headers\n g.Request = Request\n g.Response = Response\n}\n","import 'whatwg-fetch';\n\nconst defaultPort = \"11434\";\nconst defaultHost = `http://127.0.0.1:${defaultPort}`;\n\nconst version = \"0.6.3\";\n\nvar __defProp$1 = Object.defineProperty;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$1 = (obj, key, value) => {\n __defNormalProp$1(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass ResponseError extends Error {\n constructor(error, status_code) {\n super(error);\n this.error = error;\n this.status_code = status_code;\n this.name = \"ResponseError\";\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ResponseError);\n }\n }\n}\nclass AbortableAsyncIterator {\n constructor(abortController, itr, doneCallback) {\n __publicField$1(this, \"abortController\");\n __publicField$1(this, \"itr\");\n __publicField$1(this, \"doneCallback\");\n this.abortController = abortController;\n this.itr = itr;\n this.doneCallback = doneCallback;\n }\n abort() {\n this.abortController.abort();\n }\n async *[Symbol.asyncIterator]() {\n for await (const message of this.itr) {\n if (\"error\" in message) {\n throw new Error(message.error);\n }\n yield message;\n if (message.done || message.status === \"success\") {\n this.doneCallback();\n return;\n }\n }\n throw new Error(\"Did not receive done or success response in stream.\");\n }\n}\nconst checkOk = async (response) => {\n if (response.ok) {\n return;\n }\n let message = `Error ${response.status}: ${response.statusText}`;\n let errorData = null;\n if (response.headers.get(\"content-type\")?.includes(\"application/json\")) {\n try {\n errorData = await response.json();\n message = errorData.error || message;\n } catch (error) {\n console.log(\"Failed to parse error response as JSON\");\n }\n } else {\n try {\n console.log(\"Getting text from response\");\n const textResponse = await response.text();\n message = textResponse || message;\n } catch (error) {\n console.log(\"Failed to get text from error response\");\n }\n }\n throw new ResponseError(message, response.status);\n};\nfunction getPlatform() {\n if (typeof window !== \"undefined\" && window.navigator) {\n const nav = navigator;\n if (\"userAgentData\" in nav && nav.userAgentData?.platform) {\n return `${nav.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`;\n }\n if (navigator.platform) {\n return `${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`;\n }\n return `unknown Browser/${navigator.userAgent};`;\n } else if (typeof process !== \"undefined\") {\n return `${process.arch} ${process.platform} Node.js/${process.version}`;\n }\n return \"\";\n}\nfunction normalizeHeaders(headers) {\n if (headers instanceof Headers) {\n const obj = {};\n headers.forEach((value, key) => {\n obj[key] = value;\n });\n return obj;\n } else if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n } else {\n return headers || {};\n }\n}\nconst readEnvVar = (obj, key) => {\n return obj[key];\n};\nconst fetchWithHeaders = async (fetch, url, options = {}) => {\n const defaultHeaders = {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"User-Agent\": `ollama-js/${version} (${getPlatform()})`\n };\n options.headers = normalizeHeaders(options.headers);\n try {\n const parsed = new URL(url);\n if (parsed.protocol === \"https:\" && parsed.hostname === \"ollama.com\") {\n const apiKey = typeof process === \"object\" && process !== null && typeof process.env === \"object\" && process.env !== null ? readEnvVar(process.env, \"OLLAMA_API_KEY\") : void 0;\n const authorization = options.headers[\"authorization\"] || options.headers[\"Authorization\"];\n if (!authorization && apiKey) {\n options.headers[\"Authorization\"] = `Bearer ${apiKey}`;\n }\n }\n } catch (error) {\n console.error(\"error parsing url\", error);\n }\n const customHeaders = Object.fromEntries(\n Object.entries(options.headers).filter(\n ([key]) => !Object.keys(defaultHeaders).some(\n (defaultKey) => defaultKey.toLowerCase() === key.toLowerCase()\n )\n )\n );\n options.headers = {\n ...defaultHeaders,\n ...customHeaders\n };\n return fetch(url, options);\n};\nconst get = async (fetch, host, options) => {\n const response = await fetchWithHeaders(fetch, host, {\n headers: options?.headers\n });\n await checkOk(response);\n return response;\n};\nconst post = async (fetch, host, data, options) => {\n const isRecord = (input) => {\n return input !== null && typeof input === \"object\" && !Array.isArray(input);\n };\n const formattedData = isRecord(data) ? JSON.stringify(data) : data;\n const response = await fetchWithHeaders(fetch, host, {\n method: \"POST\",\n body: formattedData,\n signal: options?.signal,\n headers: options?.headers\n });\n await checkOk(response);\n return response;\n};\nconst del = async (fetch, host, data, options) => {\n const response = await fetchWithHeaders(fetch, host, {\n method: \"DELETE\",\n body: JSON.stringify(data),\n headers: options?.headers\n });\n await checkOk(response);\n return response;\n};\nconst parseJSON = async function* (itr) {\n const decoder = new TextDecoder(\"utf-8\");\n let buffer = \"\";\n const reader = itr.getReader();\n while (true) {\n const { done, value: chunk } = await reader.read();\n if (done) {\n break;\n }\n buffer += decoder.decode(chunk, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n for (const part of parts) {\n try {\n yield JSON.parse(part);\n } catch (error) {\n console.warn(\"invalid json: \", part);\n }\n }\n }\n buffer += decoder.decode();\n for (const part of buffer.split(\"\\n\").filter((p) => p !== \"\")) {\n try {\n yield JSON.parse(part);\n } catch (error) {\n console.warn(\"invalid json: \", part);\n }\n }\n};\nconst formatHost = (host) => {\n if (!host) {\n return defaultHost;\n }\n let isExplicitProtocol = host.includes(\"://\");\n if (host.startsWith(\":\")) {\n host = `http://127.0.0.1${host}`;\n isExplicitProtocol = true;\n }\n if (!isExplicitProtocol) {\n host = `http://${host}`;\n }\n const url = new URL(host);\n let port = url.port;\n if (!port) {\n if (!isExplicitProtocol) {\n port = defaultPort;\n } else {\n port = url.protocol === \"https:\" ? \"443\" : \"80\";\n }\n }\n let auth = \"\";\n if (url.username) {\n auth = url.username;\n if (url.password) {\n auth += `:${url.password}`;\n }\n auth += \"@\";\n }\n let formattedHost = `${url.protocol}//${auth}${url.hostname}:${port}${url.pathname}`;\n if (formattedHost.endsWith(\"/\")) {\n formattedHost = formattedHost.slice(0, -1);\n }\n return formattedHost;\n};\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nlet Ollama$1 = class Ollama {\n constructor(config) {\n __publicField(this, \"config\");\n __publicField(this, \"fetch\");\n __publicField(this, \"ongoingStreamedRequests\", []);\n this.config = {\n host: \"\",\n headers: config?.headers\n };\n if (!config?.proxy) {\n this.config.host = formatHost(config?.host ?? defaultHost);\n }\n this.fetch = config?.fetch ?? fetch;\n }\n // Abort any ongoing streamed requests to Ollama\n abort() {\n for (const request of this.ongoingStreamedRequests) {\n request.abort();\n }\n this.ongoingStreamedRequests.length = 0;\n }\n /**\n * Processes a request to the Ollama server. If the request is streamable, it will return a\n * AbortableAsyncIterator that yields the response messages. Otherwise, it will return the response\n * object.\n * @param endpoint {string} - The endpoint to send the request to.\n * @param request {object} - The request object to send to the endpoint.\n * @protected {T | AbortableAsyncIterator<T>} - The response object or a AbortableAsyncIterator that yields\n * response messages.\n * @throws {Error} - If the response body is missing or if the response is an error.\n * @returns {Promise<T | AbortableAsyncIterator<T>>} - The response object or a AbortableAsyncIterator that yields the streamed response.\n */\n async processStreamableRequest(endpoint, request) {\n request.stream = request.stream ?? false;\n const host = `${this.config.host}/api/${endpoint}`;\n if (request.stream) {\n const abortController = new AbortController();\n const response2 = await post(this.fetch, host, request, {\n signal: abortController.signal,\n headers: this.config.headers\n });\n if (!response2.body) {\n throw new Error(\"Missing body\");\n }\n const itr = parseJSON(response2.body);\n const abortableAsyncIterator = new AbortableAsyncIterator(\n abortController,\n itr,\n () => {\n const i = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator);\n if (i > -1) {\n this.ongoingStreamedRequests.splice(i, 1);\n }\n }\n );\n this.ongoingStreamedRequests.push(abortableAsyncIterator);\n return abortableAsyncIterator;\n }\n const response = await post(this.fetch, host, request, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Encodes an image to base64 if it is a Uint8Array.\n * @param image {Uint8Array | string} - The image to encode.\n * @returns {Promise<string>} - The base64 encoded image.\n */\n async encodeImage(image) {\n if (typeof image !== \"string\") {\n const uint8Array = new Uint8Array(image);\n let byteString = \"\";\n const len = uint8Array.byteLength;\n for (let i = 0; i < len; i++) {\n byteString += String.fromCharCode(uint8Array[i]);\n }\n return btoa(byteString);\n }\n return image;\n }\n /**\n * Generates a response from a text prompt.\n * @param request {GenerateRequest} - The request object.\n * @returns {Promise<GenerateResponse | AbortableAsyncIterator<GenerateResponse>>} - The response object or\n * an AbortableAsyncIterator that yields response messages.\n */\n async generate(request) {\n if (request.images) {\n request.images = await Promise.all(request.images.map(this.encodeImage.bind(this)));\n }\n return this.processStreamableRequest(\"generate\", request);\n }\n /**\n * Chats with the model. The request object can contain messages with images that are either\n * Uint8Arrays or base64 encoded strings. The images will be base64 encoded before sending the\n * request.\n * @param request {ChatRequest} - The request object.\n * @returns {Promise<ChatResponse | AbortableAsyncIterator<ChatResponse>>} - The response object or an\n * AbortableAsyncIterator that yields response messages.\n */\n async chat(request) {\n if (request.messages) {\n for (const message of request.messages) {\n if (message.images) {\n message.images = await Promise.all(\n message.images.map(this.encodeImage.bind(this))\n );\n }\n }\n }\n return this.processStreamableRequest(\"chat\", request);\n }\n /**\n * Creates a new model from a stream of data.\n * @param request {CreateRequest} - The request object.\n * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or a stream of progress responses.\n */\n async create(request) {\n return this.processStreamableRequest(\"create\", {\n ...request\n });\n }\n /**\n * Pulls a model from the Ollama registry. The request object can contain a stream flag to indicate if the\n * response should be streamed.\n * @param request {PullRequest} - The request object.\n * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or\n * an AbortableAsyncIterator that yields response messages.\n */\n async pull(request) {\n return this.processStreamableRequest(\"pull\", {\n name: request.model,\n stream: request.stream,\n insecure: request.insecure\n });\n }\n /**\n * Pushes a model to the Ollama registry. The request object can contain a stream flag to indicate if the\n * response should be streamed.\n * @param request {PushRequest} - The request object.\n * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or\n * an AbortableAsyncIterator that yields response messages.\n */\n async push(request) {\n return this.processStreamableRequest(\"push\", {\n name: request.model,\n stream: request.stream,\n insecure: request.insecure\n });\n }\n /**\n * Deletes a model from the server. The request object should contain the name of the model to\n * delete.\n * @param request {DeleteRequest} - The request object.\n * @returns {Promise<StatusResponse>} - The response object.\n */\n async delete(request) {\n await del(\n this.fetch,\n `${this.config.host}/api/delete`,\n { name: request.model },\n { headers: this.config.headers }\n );\n return { status: \"success\" };\n }\n /**\n * Copies a model from one name to another. The request object should contain the name of the\n * model to copy and the new name.\n * @param request {CopyRequest} - The request object.\n * @returns {Promise<StatusResponse>} - The response object.\n */\n async copy(request) {\n await post(this.fetch, `${this.config.host}/api/copy`, { ...request }, {\n headers: this.config.headers\n });\n return { status: \"success\" };\n }\n /**\n * Lists the models on the server.\n * @returns {Promise<ListResponse>} - The response object.\n * @throws {Error} - If the response body is missing.\n */\n async list() {\n const response = await get(this.fetch, `${this.config.host}/api/tags`, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Shows the metadata of a model. The request object should contain the name of the model.\n * @param request {ShowRequest} - The request object.\n * @returns {Promise<ShowResponse>} - The response object.\n */\n async show(request) {\n const response = await post(this.fetch, `${this.config.host}/api/show`, {\n ...request\n }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Embeds text input into vectors.\n * @param request {EmbedRequest} - The request object.\n * @returns {Promise<EmbedResponse>} - The response object.\n */\n async embed(request) {\n const response = await post(this.fetch, `${this.config.host}/api/embed`, {\n ...request\n }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Embeds a text prompt into a vector.\n * @param request {EmbeddingsRequest} - The request object.\n * @returns {Promise<EmbeddingsResponse>} - The response object.\n */\n async embeddings(request) {\n const response = await post(this.fetch, `${this.config.host}/api/embeddings`, {\n ...request\n }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Lists the running models on the server\n * @returns {Promise<ListResponse>} - The response object.\n * @throws {Error} - If the response body is missing.\n */\n async ps() {\n const response = await get(this.fetch, `${this.config.host}/api/ps`, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Returns the Ollama server version.\n * @returns {Promise<VersionResponse>} - The server version object.\n */\n async version() {\n const response = await get(this.fetch, `${this.config.host}/api/version`, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Performs web search using the Ollama web search API\n * @param request {WebSearchRequest} - The search request containing query and options\n * @returns {Promise<WebSearchResponse>} - The search results\n * @throws {Error} - If the request is invalid or the server returns an error\n */\n async webSearch(request) {\n if (!request.query || request.query.length === 0) {\n throw new Error(\"Query is required\");\n }\n const response = await post(this.fetch, `https://ollama.com/api/web_search`, { ...request }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Fetches a single page using the Ollama web fetch API\n * @param request {WebFetchRequest} - The fetch request containing a URL\n * @returns {Promise<WebFetchResponse>} - The fetch result\n * @throws {Error} - If the request is invalid or the server returns an error\n */\n async webFetch(request) {\n if (!request.url || request.url.length === 0) {\n throw new Error(\"URL is required\");\n }\n const response = await post(this.fetch, `https://ollama.com/api/web_fetch`, { ...request }, { headers: this.config.headers });\n return await response.json();\n }\n};\nconst browser = new Ollama$1();\n\nexport { Ollama$1 as Ollama, browser as default };\n","import fs, { promises } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Ollama as Ollama$1 } from './browser.mjs';\nimport 'whatwg-fetch';\n\nclass Ollama extends Ollama$1 {\n async encodeImage(image) {\n if (typeof image !== \"string\") {\n return Buffer.from(image).toString(\"base64\");\n }\n try {\n if (fs.existsSync(image)) {\n const fileBuffer = await promises.readFile(resolve(image));\n return Buffer.from(fileBuffer).toString(\"base64\");\n }\n } catch {\n }\n return image;\n }\n /**\n * checks if a file exists\n * @param path {string} - The path to the file\n * @private @internal\n * @returns {Promise<boolean>} - Whether the file exists or not\n */\n async fileExists(path) {\n try {\n await promises.access(path);\n return true;\n } catch {\n return false;\n }\n }\n async create(request) {\n if (request.from && await this.fileExists(resolve(request.from))) {\n throw Error(\"Creating with a local path is not currently supported from ollama-js\");\n }\n if (request.stream) {\n return super.create(request);\n } else {\n return super.create(request);\n }\n }\n}\nconst index = new Ollama();\n\nexport { Ollama, index as default };\n","import { Schema } from \"effect\";\n\n// ─── LLM Provider Type ───\n\n/**\n * Schema for LLM provider selection.\n * Supported providers: anthropic, openai, ollama, gemini, litellm, custom.\n *\n * @example\n * ```typescript\n * const provider: LLMProvider = \"anthropic\";\n * ```\n */\nexport const LLMProviderType = Schema.Literal(\n /** Claude models via Anthropic API. Requires ANTHROPIC_API_KEY. */\n \"anthropic\",\n /** GPT models via OpenAI API. Requires OPENAI_API_KEY. */\n \"openai\",\n /** Local models via Ollama. Requires a running Ollama server. */\n \"ollama\",\n /** Google Gemini models. Requires GOOGLE_API_KEY. */\n \"gemini\",\n /** LiteLLM proxy — unified gateway to 40+ model providers. */\n \"litellm\",\n /** User-defined provider adapter — implement the LLMService interface. */\n \"custom\",\n);\n\n/**\n * Union of supported LLM provider names.\n * - \"anthropic\": Claude models via Anthropic API\n * - \"openai\": GPT models via OpenAI API\n * - \"ollama\": Local models via Ollama\n * - \"gemini\": Google Gemini models\n * - \"litellm\": LiteLLM proxy (40+ model providers)\n * - \"custom\": User-defined provider adapter\n */\nexport type LLMProvider = Schema.Schema.Type<typeof LLMProviderType>;\n\n// ─── Embedding Configuration ───\n\n/**\n * Schema for embedding model configuration.\n * Embeddings are used for semantic caching, memory similarity search, and verification.\n * Anthropic provides no embeddings API; embeddings always route to OpenAI or Ollama.\n *\n * @example\n * ```typescript\n * const config: EmbeddingConfig = {\n * model: \"text-embedding-3-small\",\n * dimensions: 1536,\n * provider: \"openai\",\n * batchSize: 100\n * };\n * ```\n */\nexport const EmbeddingConfigSchema = Schema.Struct({\n /** Embedding model name (e.g., \"text-embedding-3-small\") */\n model: Schema.String,\n /** Output embedding vector dimensionality */\n dimensions: Schema.Number,\n /** Provider hosting the embedding model */\n provider: Schema.Literal(\"openai\", \"ollama\"),\n /** Maximum vectors to embed in a single API call (default: 100) */\n batchSize: Schema.optional(Schema.Number),\n});\n\n/**\n * Embedding configuration type.\n * Specifies the embedding model and provider for semantic operations.\n */\nexport type EmbeddingConfig = Schema.Schema.Type<typeof EmbeddingConfigSchema>;\n\n/**\n * Default embedding configuration.\n * Uses OpenAI's text-embedding-3-small with 1536 dimensions.\n *\n * @default { model: \"text-embedding-3-small\", dimensions: 1536, provider: \"openai\", batchSize: 100 }\n */\nexport const DefaultEmbeddingConfig: EmbeddingConfig = {\n model: \"text-embedding-3-small\",\n dimensions: 1536,\n provider: \"openai\",\n batchSize: 100,\n};\n\n// ─── Model Configuration ───\n\n/**\n * Schema for LLM model configuration options.\n * Includes provider, model name, and optional sampling/output parameters.\n *\n * @example\n * ```typescript\n * const config: ModelConfig = {\n * provider: \"anthropic\",\n * model: \"claude-opus-4-20250514\",\n * maxTokens: 4096,\n * temperature: 0.7\n * };\n * ```\n */\nexport const ModelConfigSchema = Schema.Struct({\n /** LLM provider identifier */\n provider: LLMProviderType,\n /** Model name/identifier for the provider */\n model: Schema.String,\n /** Maximum tokens in response (optional) */\n maxTokens: Schema.optional(Schema.Number),\n /** Sampling temperature 0.0-1.0 (optional) */\n temperature: Schema.optional(Schema.Number),\n /** Top-p (nucleus) sampling probability (optional) */\n topP: Schema.optional(Schema.Number),\n /** Stop sequences to halt generation (optional) */\n stopSequences: Schema.optional(Schema.Array(Schema.String)),\n});\n\n/**\n * LLM model configuration type.\n * Specifies which LLM to use and how to configure its behavior.\n */\nexport type ModelConfig = Schema.Schema.Type<typeof ModelConfigSchema>;\n\n// ─── Model Presets ───\n\n/**\n * Pre-configured model profiles for popular LLMs.\n * Each preset includes cost estimates, context window, and quality tiers.\n * Quality tier: 0.0 (low) to 1.0 (highest).\n * Cost: per 1 million input/output tokens in USD.\n *\n * @example\n * ```typescript\n * const preset = ModelPresets[\"claude-opus\"];\n * // { provider: \"anthropic\", model: \"claude-opus-4-20250514\", costPer1MInput: 15.0, ... }\n * ```\n */\nexport const ModelPresets = {\n /**\n * Claude 3.5 Haiku — fast, cost-effective Anthropic model.\n * Best for low-latency, simple reasoning tasks; not recommended for complex analysis.\n */\n \"claude-haiku\": {\n provider: \"anthropic\" as const,\n model: \"claude-3-5-haiku-20241022\",\n /** Cost per 1 million input tokens in USD */\n costPer1MInput: 1.0,\n /** Cost per 1 million output tokens in USD */\n costPer1MOutput: 5.0,\n /** Maximum context window in tokens */\n maxContext: 200_000,\n /** Quality tier (0.6 = reliable for simple tasks) */\n quality: 0.6,\n },\n /**\n * Claude Sonnet 4 — balanced Anthropic model.\n * Recommended for general-purpose reasoning, tool use, and production agents.\n */\n \"claude-sonnet\": {\n provider: \"anthropic\" as const,\n model: \"claude-sonnet-4-20250514\",\n costPer1MInput: 3.0,\n costPer1MOutput: 15.0,\n maxContext: 200_000,\n /** Quality tier (0.85 = excellent reasoning) */\n quality: 0.85,\n },\n /**\n * Claude Sonnet 4.5 — latest Anthropic model.\n * Superior reasoning over Sonnet 4; recommended for complex multi-step reasoning.\n */\n \"claude-sonnet-4-5\": {\n provider: \"anthropic\" as const,\n model: \"claude-sonnet-4-5-20250929\",\n costPer1MInput: 3.0,\n costPer1MOutput: 15.0,\n maxContext: 200_000,\n /** Quality tier (0.9 = very strong reasoning) */\n quality: 0.9,\n },\n /**\n * Claude Opus 4 — most capable Anthropic model.\n * Best for complex analysis, research, and high-accuracy multi-hop reasoning.\n * Largest context window (1M tokens); highest cost.\n */\n \"claude-opus\": {\n provider: \"anthropic\" as const,\n model: \"claude-opus-4-20250514\",\n costPer1MInput: 15.0,\n costPer1MOutput: 75.0,\n maxContext: 1_000_000,\n /** Quality tier (1.0 = frontier-class reasoning) */\n quality: 1.0,\n },\n /**\n * GPT-4o Mini — fast, low-cost OpenAI model.\n * Good for simple tasks and high-throughput scenarios.\n */\n \"gpt-4o-mini\": {\n provider: \"openai\" as const,\n model: \"gpt-4o-mini\",\n costPer1MInput: 0.15,\n costPer1MOutput: 0.6,\n maxContext: 128_000,\n /** Quality tier (0.55 = capable but less reliable for complex reasoning) */\n quality: 0.55,\n },\n /**\n * GPT-4o — latest OpenAI flagship model.\n * Strong reasoning, multimodal support; recommended for tool use and complex analysis.\n */\n \"gpt-4o\": {\n provider: \"openai\" as const,\n model: \"gpt-4o\",\n costPer1MInput: 2.5,\n costPer1MOutput: 10.0,\n maxContext: 128_000,\n /** Quality tier (0.8 = very good reasoning) */\n quality: 0.8,\n },\n /**\n * Gemini 2.0 Flash — fast Google model.\n * Excellent speed and cost efficiency; large 1M context window.\n */\n \"gemini-2.0-flash\": {\n provider: \"gemini\" as const,\n model: \"gemini-2.0-flash\",\n costPer1MInput: 0.1,\n costPer1MOutput: 0.4,\n maxContext: 1_000_000,\n /** Quality tier (0.75 = good reasoning) */\n quality: 0.75,\n },\n /**\n * Gemini 2.5 Pro Preview — advanced Google model.\n * Superior reasoning to Flash; large context window and competitive pricing.\n */\n \"gemini-2.5-pro\": {\n provider: \"gemini\" as const,\n model: \"gemini-2.5-pro-preview-03-25\",\n costPer1MInput: 1.25,\n costPer1MOutput: 10.0,\n maxContext: 1_000_000,\n /** Quality tier (0.95 = excellent reasoning) */\n quality: 0.95,\n },\n} as const;\n\n/**\n * Union of all model preset names.\n * Use to select a pre-configured model with cost/quality/context metadata.\n *\n * @example\n * ```typescript\n * const presetName: ModelPresetName = \"claude-opus\";\n * const preset = ModelPresets[presetName];\n * ```\n */\nexport type ModelPresetName = keyof typeof ModelPresets;\n\n// ─── Cache Control (Anthropic Prompt Caching) ───\n\n/**\n * Schema for Anthropic prompt caching control.\n * Currently only supports \"ephemeral\" type (cache for this request only).\n * Non-Anthropic providers silently ignore cache_control directives.\n *\n * @example\n * ```typescript\n * const cacheControl: CacheControl = { type: \"ephemeral\" };\n * ```\n */\nexport const CacheControlSchema = Schema.Struct({\n /** Cache type: \"ephemeral\" for request-scoped caching */\n type: Schema.Literal(\"ephemeral\"),\n});\n\n/**\n * Anthropic prompt caching configuration.\n * Wraps text content blocks to enable prompt caching optimization.\n * Reduces costs for repeated context; only supported on Anthropic provider.\n */\nexport type CacheControl = Schema.Schema.Type<typeof CacheControlSchema>;\n\n// ─── Content Blocks ───\n\n/**\n * Schema for image source reference.\n * Supports base64-encoded or URL-referenced images in PNG, JPEG, GIF, or WebP format.\n *\n * @example\n * ```typescript\n * const source: ImageSource = {\n * type: \"base64\",\n * media_type: \"image/png\",\n * data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n * };\n * ```\n */\nexport const ImageSourceSchema = Schema.Struct({\n /** Image source type: \"base64\" for encoded data or \"url\" for HTTP(S) URL */\n type: Schema.Literal(\"base64\", \"url\"),\n /** MIME type of image: PNG, JPEG, GIF, or WebP */\n media_type: Schema.Literal(\n \"image/png\",\n \"image/jpeg\",\n \"image/gif\",\n \"image/webp\",\n ),\n /** Either base64-encoded data or HTTPS URL */\n data: Schema.String,\n});\n\n/**\n * Image source reference type.\n * Either a base64-encoded image or an HTTPS URL to an image resource.\n */\nexport type ImageSource = Schema.Schema.Type<typeof ImageSourceSchema>;\n\n/**\n * Schema for text content blocks.\n * Supports optional Anthropic prompt caching via cache_control.\n *\n * @example\n * ```typescript\n * const textBlock: TextContentBlock = {\n * type: \"text\",\n * text: \"This is a text message\"\n * };\n * ```\n */\nexport const TextContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"text\"),\n /** Text content */\n text: Schema.String,\n /** Optional Anthropic cache control directive */\n cache_control: Schema.optional(CacheControlSchema),\n});\n\n/**\n * Schema for image content blocks.\n *\n * @example\n * ```typescript\n * const imageBlock: ImageContentBlock = {\n * type: \"image\",\n * source: { type: \"url\", media_type: \"image/png\", data: \"https://...\" }\n * };\n * ```\n */\nexport const ImageContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"image\"),\n /** Image source reference */\n source: ImageSourceSchema,\n});\n\n/**\n * Schema for tool use content blocks (model invoking a tool).\n *\n * @example\n * ```typescript\n * const toolBlock: ToolUseContentBlock = {\n * type: \"tool_use\",\n * id: \"toolu_123\",\n * name: \"file-read\",\n * input: { path: \"./output.txt\" }\n * };\n * ```\n */\nexport const ToolUseContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"tool_use\"),\n /** Unique tool call identifier */\n id: Schema.String,\n /** Tool name being invoked */\n name: Schema.String,\n /** Tool parameters (JSON-compatible object) */\n input: Schema.Unknown,\n});\n\n/**\n * Schema for tool result content blocks (system returning tool output).\n *\n * @example\n * ```typescript\n * const resultBlock: ToolResultContentBlock = {\n * type: \"tool_result\",\n * tool_use_id: \"toolu_123\",\n * content: \"File contents...\"\n * };\n * ```\n */\nexport const ToolResultContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"tool_result\"),\n /** ID of tool call this result corresponds to */\n tool_use_id: Schema.String,\n /** Tool result/output content */\n content: Schema.String,\n});\n\n/**\n * Union of all content block types used in LLM messages.\n * Content blocks allow mixing text, images, tool invocations, and tool results.\n *\n * @example\n * ```typescript\n * const blocks: readonly ContentBlock[] = [\n * { type: \"text\", text: \"Analyze this image:\" },\n * { type: \"image\", source: { type: \"url\", media_type: \"image/png\", data: \"https://...\" } }\n * ];\n * ```\n */\nexport type ContentBlock =\n | {\n /** Text content (optionally cached with Anthropic) */\n readonly type: \"text\";\n readonly text: string;\n readonly cache_control?: CacheControl;\n }\n | {\n /** Image content */\n readonly type: \"image\";\n readonly source: ImageSource;\n }\n | {\n /** Model invoking a tool */\n readonly type: \"tool_use\";\n readonly id: string;\n readonly name: string;\n readonly input: unknown;\n }\n | {\n /** System returning tool output */\n readonly type: \"tool_result\";\n readonly tool_use_id: string;\n readonly content: string;\n };\n\n// ─── Cacheable Content Block ───\n\n/**\n * Text content block with cache control enabled.\n * Used when text context should be cached for cost reduction (Anthropic only).\n * Non-Anthropic providers silently ignore the cache_control directive.\n *\n * @example\n * ```typescript\n * const cached: CacheableContentBlock = {\n * type: \"text\",\n * text: \"Expensive context (system prompt, instructions, etc)\",\n * cache_control: { type: \"ephemeral\" }\n * };\n * ```\n */\nexport type CacheableContentBlock = {\n /** Always \"text\" */\n readonly type: \"text\";\n /** Cached text content */\n readonly text: string;\n /** Cache control directive (always ephemeral) */\n readonly cache_control: CacheControl;\n};\n\n/**\n * Wrap plain text in a cacheable content block.\n * Enables Anthropic prompt caching for the given text (no-op for other providers).\n * Useful for repeated context like system prompts, instructions, or reference documents.\n *\n * @param text — The text to cache\n * @returns A content block with ephemeral cache control enabled\n *\n * @example\n * ```typescript\n * const cached = makeCacheable(\"You are a helpful assistant...\");\n * // Returns: { type: \"text\", text: \"...\", cache_control: { type: \"ephemeral\" } }\n * ```\n */\nexport const makeCacheable = (text: string): CacheableContentBlock => ({\n type: \"text\",\n text,\n cache_control: { type: \"ephemeral\" },\n});\n\n// ─── Message Types ───\n\n/**\n * Union of LLM message roles.\n * Each message has a role (system, user, assistant, tool) and content.\n *\n * - **system**: Instructions/context set by the agent developer. Content is always a string.\n * - **user**: User query or context provided by caller. Content is string or content blocks.\n * - **assistant**: Model response or thoughts. Content is string or content blocks (including tool_use).\n * - **tool**: Tool execution result returned to model. Content is always string.\n *\n * @example\n * ```typescript\n * const messages: readonly LLMMessage[] = [\n * { role: \"system\", content: \"You are a helpful assistant.\" },\n * { role: \"user\", content: \"What is 2+2?\" },\n * { role: \"assistant\", content: \"2+2 equals 4.\" }\n * ];\n *\n * const withTools: readonly LLMMessage[] = [\n * { role: \"user\", content: \"Read the file.\" },\n * {\n * role: \"assistant\",\n * content: [\n * { type: \"text\", text: \"I'll read that file for you.\" },\n * { type: \"tool_use\", id: \"toolu_1\", name: \"file-read\", input: { path: \"./data.txt\" } }\n * ]\n * },\n * { role: \"tool\", toolCallId: \"toolu_1\", content: \"File contents here...\" }\n * ];\n * ```\n */\nexport type LLMMessage =\n | {\n /** System prompt/instructions — context set by developer */\n readonly role: \"system\";\n /** Plain text string only (no content blocks) */\n readonly content: string;\n }\n | {\n /** User input/query */\n readonly role: \"user\";\n /** Plain text or multimodal content blocks */\n readonly content: string | readonly ContentBlock[];\n }\n | {\n /** Model response or reasoning */\n readonly role: \"assistant\";\n /** Plain text or multimodal content blocks (including tool_use) */\n readonly content: string | readonly ContentBlock[];\n }\n | {\n /** Tool execution result */\n readonly role: \"tool\";\n /** Tool call ID this result corresponds to */\n readonly toolCallId: string;\n /** Plain text result/output */\n readonly content: string;\n };\n\n// ─── Token Usage ───\n\n/**\n * Schema for token usage statistics from an LLM response.\n * Used for cost tracking, budget enforcement, and observability.\n *\n * @example\n * ```typescript\n * const usage: TokenUsage = {\n * inputTokens: 1200,\n * outputTokens: 450,\n * totalTokens: 1650,\n * estimatedCost: 0.0045\n * };\n * ```\n */\nexport const TokenUsageSchema = Schema.Struct({\n /** Tokens consumed by the input (messages + system prompt) */\n inputTokens: Schema.Number,\n /** Tokens generated in the response */\n outputTokens: Schema.Number,\n /** Sum of input and output tokens */\n totalTokens: Schema.Number,\n /** Estimated cost in USD based on provider pricing */\n estimatedCost: Schema.Number,\n});\n\n/**\n * Token usage from an LLM response.\n * Tracks input/output tokens separately for cost calculation.\n */\nexport type TokenUsage = Schema.Schema.Type<typeof TokenUsageSchema>;\n\n// ─── Stop Reason ───\n\n/**\n * Schema for LLM response termination reason.\n * Indicates why the model stopped generating tokens.\n *\n * @example\n * ```typescript\n * const reason: StopReason = \"end_turn\"; // Model concluded naturally\n * const reason2: StopReason = \"max_tokens\"; // Hit output limit\n * ```\n */\nexport const StopReasonSchema = Schema.Literal(\n /** Model concluded naturally — full response present. */\n \"end_turn\",\n /** Hit `maxTokens` limit — response may be truncated. */\n \"max_tokens\",\n /** Hit a configured stop sequence — generation halted by design. */\n \"stop_sequence\",\n /** Model is invoking a tool — `toolCalls` array is populated. */\n \"tool_use\",\n);\n\n/**\n * Reason the LLM stopped generating.\n *\n * - **end_turn**: Model concluded naturally — response is complete.\n * - **max_tokens**: Hit configured output token limit — response may be truncated.\n * - **stop_sequence**: Hit a configured stop sequence — generation halted by design.\n * - **tool_use**: Model is invoking a tool — `toolCalls` array is populated.\n */\nexport type StopReason = Schema.Schema.Type<typeof StopReasonSchema>;\n\n// ─── Tool Definition ───\n\n/**\n * Schema for tool definitions.\n * Describes tools available to the LLM, including name, description, and input schema.\n * Tools are passed to the LLM for function calling / tool use.\n *\n * @example\n * ```typescript\n * const tool: ToolDefinition = {\n * name: \"file-read\",\n * description: \"Read a file from disk\",\n * inputSchema: {\n * path: { type: \"string\", description: \"File path\", required: true }\n * }\n * };\n * ```\n */\nexport const ToolDefinitionSchema = Schema.Struct({\n /** Tool identifier (used by model to invoke the tool) */\n name: Schema.String,\n /** Human-readable tool description for the model */\n description: Schema.String,\n /** Input schema describing expected parameters (JSON Schema format) */\n inputSchema: Schema.Record({ key: Schema.String, value: Schema.Unknown }),\n});\n\n/**\n * Tool definition.\n * Used to register available functions that the LLM can call.\n * Input schema is a JSON Schema object defining parameters.\n */\nexport type ToolDefinition = Schema.Schema.Type<typeof ToolDefinitionSchema>;\n\n// ─── Tool Call ───\n\n/**\n * Schema for tool invocation.\n * Emitted by the model when it decides to call a tool.\n *\n * @example\n * ```typescript\n * const call: ToolCall = {\n * id: \"toolu_123\",\n * name: \"file-read\",\n * input: { path: \"./output.txt\" }\n * };\n * ```\n */\nexport const ToolCallSchema = Schema.Struct({\n /** Unique tool call identifier (generated by model) */\n id: Schema.String,\n /** Tool name to invoke */\n name: Schema.String,\n /** Tool input parameters (arbitrary JSON-compatible object) */\n input: Schema.Unknown,\n});\n\n/**\n * Tool invocation from the LLM.\n * When the model decides to call a tool, this describes which tool and with what inputs.\n */\nexport type ToolCall = Schema.Schema.Type<typeof ToolCallSchema>;\n\n// ─── Completion Request ───\n\n/**\n * Request to the LLM for a completion.\n * Includes messages, model configuration, tool definitions, and sampling parameters.\n * Passed to LLMService.complete() for synchronous LLM calls.\n *\n * @see CompletionResponse — the response type returned by LLMService.complete()\n * @see ToolDefinition — shape of entries in the `tools` array\n * @see ModelConfig — shape of the `model` field\n *\n * @example\n * ```typescript\n * const request: CompletionRequest = {\n * messages: [\n * { role: \"system\", content: \"You are a helpful assistant.\" },\n * { role: \"user\", content: \"What is the capital of France?\" }\n * ],\n * model: { provider: \"anthropic\", model: \"claude-opus-4-20250514\" },\n * maxTokens: 1024,\n * temperature: 0.7,\n * tools: [\n * { name: \"web-search\", description: \"Search the web\", inputSchema: { query: { type: \"string\" } } }\n * ]\n * };\n * ```\n */\nexport type CompletionRequest = {\n /** Conversation history (at least 1 message required) */\n readonly messages: readonly LLMMessage[];\n /** Model config (provider + model name + optional sampling params) */\n readonly model?: ModelConfig;\n /** Maximum response tokens (optional, uses config default if omitted) */\n readonly maxTokens?: number;\n /** Sampling temperature 0.0-1.0 (optional, uses config default if omitted) */\n readonly temperature?: number;\n /** Stop sequences to halt generation (optional) */\n readonly stopSequences?: readonly string[];\n /** Tools available for the model to call (optional) */\n readonly tools?: readonly ToolDefinition[];\n /** System prompt (optional, prepended to user messages) */\n readonly systemPrompt?: string;\n};\n\n// ─── Completion Response ───\n\n/**\n * Schema for LLM response.\n * Contains the generated content, stop reason, token usage, and any tool calls.\n *\n * @example\n * ```typescript\n * const response: CompletionResponse = {\n * content: \"The capital of France is Paris.\",\n * stopReason: \"end_turn\",\n * usage: { inputTokens: 120, outputTokens: 15, totalTokens: 135, estimatedCost: 0.00041 },\n * model: \"claude-opus-4-20250514\",\n * toolCalls: undefined\n * };\n * ```\n */\nexport const CompletionResponseSchema = Schema.Struct({\n /** Generated response content (text only, no content blocks) */\n content: Schema.String,\n /** Why the model stopped generating */\n stopReason: StopReasonSchema,\n /** Token usage statistics */\n usage: TokenUsageSchema,\n /** Actual model identifier used (may differ from request) */\n model: Schema.String,\n /** Tool calls emitted by the model (if any) */\n toolCalls: Schema.optional(Schema.Array(ToolCallSchema)),\n /** Internal reasoning from thinking models (e.g. <think> blocks from qwen3, DeepSeek-R1) */\n thinking: Schema.optional(Schema.String),\n});\n\n/**\n * LLM response to a completion request.\n * Contains generated text, stop reason, usage metrics, and optional tool calls.\n *\n * @see CompletionRequest — the request type passed to LLMService.complete()\n * @see StopReason — possible values for the `stopReason` field\n * @see TokenUsage — shape of the `usage` field\n * @see ToolCall — shape of entries in the optional `toolCalls` array\n */\nexport type CompletionResponse = Schema.Schema.Type<\n typeof CompletionResponseSchema\n>;\n\n// ─── Stream Events ───\n\n/**\n * Events streamed during an LLM response.\n * Used when streaming responses rather than waiting for full completion.\n * Events arrive in sequence: text_delta(s), then tool_use_start/delta(s) if applicable, then content_complete, then usage.\n *\n * @example\n * ```typescript\n * const events: StreamEvent[] = [\n * { type: \"text_delta\", text: \"The \" },\n * { type: \"text_delta\", text: \"capital \" },\n * { type: \"text_delta\", text: \"is Paris.\" },\n * { type: \"content_complete\", content: \"The capital is Paris.\" },\n * { type: \"usage\", usage: { inputTokens: 50, outputTokens: 10, totalTokens: 60, estimatedCost: 0.00018 } }\n * ];\n * ```\n */\nexport type StreamEvent =\n | {\n /** Text chunk arriving */\n readonly type: \"text_delta\";\n /** Text chunk content */\n readonly text: string;\n }\n | {\n /** Tool invocation starting */\n readonly type: \"tool_use_start\";\n /** Unique tool call ID */\n readonly id: string;\n /** Tool name being invoked */\n readonly name: string;\n }\n | {\n /** Tool input parameter chunk arriving */\n readonly type: \"tool_use_delta\";\n /** JSON parameter chunk (accumulated to form full input) */\n readonly input: string;\n }\n | {\n /** Content generation completed */\n readonly type: \"content_complete\";\n /** Full accumulated response content */\n readonly content: string;\n }\n | {\n /** Token usage reported */\n readonly type: \"usage\";\n /** Final token usage for the request */\n readonly usage: TokenUsage;\n }\n | {\n /** Error occurred during streaming */\n readonly type: \"error\";\n /** Error message */\n readonly error: string;\n };\n\n// ─── Structured Output Config ───\n\n/**\n * Completion request with structured output validation.\n * Extends CompletionRequest to require the model output conform to a schema.\n * Used when the agent needs guaranteed JSON schema output from the LLM.\n *\n * @see CompletionRequest — base request type this extends\n *\n * @typeParam A — The type that the LLM output must conform to\n *\n * @example\n * ```typescript\n * interface Decision {\n * readonly choice: \"yes\" | \"no\";\n * readonly confidence: number;\n * }\n *\n * const request: StructuredCompletionRequest<Decision> = {\n * messages: [{ role: \"user\", content: \"Should I approve this?\" }],\n * outputSchema: Schema.Struct({\n * choice: Schema.Literal(\"yes\", \"no\"),\n * confidence: Schema.Number\n * }),\n * maxParseRetries: 2\n * };\n * ```\n */\nexport type StructuredCompletionRequest<A> = CompletionRequest & {\n /** Schema that the LLM response must conform to */\n readonly outputSchema: Schema.Schema<A>;\n /** If true, retry with corrected prompt if parse fails (default: false) */\n readonly retryOnParseFail?: boolean;\n /** Maximum parse retry attempts before giving up (default: 1) */\n readonly maxParseRetries?: number;\n};\n\n// ─── Truncation Strategy ───\n\n/**\n * Strategy for truncating context when it exceeds token budget.\n * Used by ContextWindowManager when compacting message history for token limits.\n *\n * @example\n * ```typescript\n * const strategy: TruncationStrategy = \"summarize-middle\";\n * ```\n */\nexport type TruncationStrategy =\n /** Remove oldest messages first (FIFO). Fastest; may lose early context. */\n | \"drop-oldest\"\n /** Summarize middle messages, preserving system prompt and most recent turns. */\n | \"summarize-middle\"\n /** Keep only the most recent N messages; drops all prior history. */\n | \"sliding-window\"\n /** Use heuristics to score and drop least-important messages first. */\n | \"importance-based\";\n\n// ─── LLM Request Event ───\n\n/**\n * Observability event emitted after every LLM request completes.\n * Captures request/response metadata for metrics, tracing, and cost tracking.\n * Published to EventBus and collected by MetricsCollector.\n *\n * Full request/response payloads included only when LLMConfig.observabilityVerbosity = \"full\".\n *\n * @see ObservabilityVerbosity — controls whether `fullRequest`/`fullResponse` are populated\n * @see TokenUsage — nested token usage shape in `response.usage`\n *\n * @example\n * ```typescript\n * const event: LLMRequestEvent = {\n * requestId: \"req-123\",\n * provider: \"anthropic\",\n * model: \"claude-opus-4-20250514\",\n * timestamp: new Date(),\n * durationMs: 1250,\n * systemPromptLength: 340,\n * messageCount: 3,\n * toolCount: 2,\n * response: {\n * contentLength: 156,\n * stopReason: \"end_turn\",\n * toolCallCount: 0,\n * usage: {\n * inputTokens: 420,\n * outputTokens: 45,\n * totalTokens: 465,\n * estimatedCost: 0.00195\n * }\n * }\n * };\n * ```\n */\nexport type LLMRequestEvent = {\n /** Unique request identifier for correlating request/response pairs */\n readonly requestId: string;\n /** LLM provider (e.g., \"anthropic\", \"openai\") */\n readonly provider: string;\n /** Model name used for the request */\n readonly model: string;\n /** When the request completed */\n readonly timestamp: Date;\n /** Request round-trip time in milliseconds */\n readonly durationMs: number;\n /** Length of system prompt in characters */\n readonly systemPromptLength: number;\n /** Number of messages in the request */\n readonly messageCount: number;\n /** Number of tool definitions passed to the model */\n readonly toolCount: number;\n /** Response details */\n readonly response: {\n /** Length of response content in characters */\n readonly contentLength: number;\n /** Why the model stopped (end_turn, max_tokens, etc.) */\n readonly stopReason: string;\n /** Number of tool calls in response */\n readonly toolCallCount: number;\n /** Token usage metrics */\n readonly usage: {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly totalTokens: number;\n readonly estimatedCost: number;\n };\n };\n /** Complete request payload (only if LLMConfig.observabilityVerbosity = \"full\") */\n readonly fullRequest?: CompletionRequest;\n /** Complete response payload (only if LLMConfig.observabilityVerbosity = \"full\") */\n readonly fullResponse?: CompletionResponse;\n};\n\n// ─── Observability Verbosity ───\n\n/**\n * Observability verbosity level for LLM request events.\n * Controls what is captured in each `LLMRequestEvent` published to the EventBus.\n *\n * @default \"full\"\n *\n * @example\n * ```typescript\n * const config = LLMConfig.of({\n * // ... other fields\n * observabilityVerbosity: process.env.NODE_ENV === \"production\" ? \"metadata\" : \"full\"\n * });\n * ```\n */\nexport type ObservabilityVerbosity =\n /** Capture timing, token counts, and cost only — lightweight, production-safe. */\n | \"metadata\"\n /** Capture complete request/response payloads — higher overhead, useful for debugging. */\n | \"full\";\n\n// ── Structured Output Capabilities ──\n\n/**\n * Provider-reported capabilities for structured JSON output.\n * Used by the structured output pipeline to select the optimal extraction strategy.\n */\nexport type StructuredOutputCapabilities = {\n /** Provider supports forcing JSON-only output (OpenAI, Gemini, Ollama) */\n readonly nativeJsonMode: boolean;\n /** Provider can enforce a JSON Schema on the output (OpenAI structured outputs) */\n readonly jsonSchemaEnforcement: boolean;\n /** Provider supports assistant message prefill to start response with \"{\" (Anthropic) */\n readonly prefillSupport: boolean;\n /** Provider supports GBNF grammar constraints for exact schema matching (Ollama/llama.cpp) */\n readonly grammarConstraints: boolean;\n};\n","import { Data } from \"effect\";\nimport type { LLMProvider } from \"./types.js\";\n\n/**\n * General LLM error — catch-all for unexpected provider failures.\n */\nexport class LLMError extends Data.TaggedError(\"LLMError\")<{\n readonly message: string;\n readonly provider: LLMProvider;\n readonly cause?: unknown;\n}> {}\n\n/**\n * Rate limit exceeded — includes retry-after hint.\n */\nexport class LLMRateLimitError extends Data.TaggedError(\"LLMRateLimitError\")<{\n readonly message: string;\n readonly provider: LLMProvider;\n readonly retryAfterMs: number;\n}> {}\n\n/**\n * Request timeout.\n */\nexport class LLMTimeoutError extends Data.TaggedError(\"LLMTimeoutError\")<{\n readonly message: string;\n readonly provider: LLMProvider;\n readonly timeoutMs: number;\n}> {}\n\n/**\n * Structured output parse failure.\n */\nexport class LLMParseError extends Data.TaggedError(\"LLMParseError\")<{\n readonly message: string;\n readonly rawOutput: string;\n readonly expectedSchema: string;\n}> {}\n\n/**\n * Context window overflow — too many tokens for the model.\n */\nexport class LLMContextOverflowError extends Data.TaggedError(\n \"LLMContextOverflowError\",\n)<{\n readonly message: string;\n readonly tokenCount: number;\n readonly maxTokens: number;\n}> {}\n\n/**\n * Union of all LLM error types.\n */\nexport type LLMErrors =\n | LLMError\n | LLMRateLimitError\n | LLMTimeoutError\n | LLMParseError\n | LLMContextOverflowError;\n","import { Effect, Context, type Stream } from \"effect\";\nimport type {\n CompletionRequest,\n CompletionResponse,\n StreamEvent,\n StructuredCompletionRequest,\n LLMMessage,\n ModelConfig,\n StructuredOutputCapabilities,\n} from \"./types.js\";\nimport type { LLMErrors } from \"./errors.js\";\n\n/**\n * Core LLM service — all LLM interactions go through this.\n * Layers 3, 4, 5, and 10 depend on this.\n */\nexport class LLMService extends Context.Tag(\"LLMService\")<\n LLMService,\n {\n /**\n * Complete a prompt (non-streaming).\n * Returns full response after generation completes.\n */\n readonly complete: (\n request: CompletionRequest,\n ) => Effect.Effect<CompletionResponse, LLMErrors>;\n\n /**\n * Stream a completion. Returns an Effect that yields a Stream of events.\n * Use for real-time UI updates (collaborative mode).\n */\n readonly stream: (\n request: CompletionRequest,\n ) => Effect.Effect<Stream.Stream<StreamEvent, LLMErrors>, LLMErrors>;\n\n /**\n * Complete with structured output.\n * Parses LLM response into a typed object using Effect Schema.\n * Retries with parse error feedback if parsing fails.\n */\n readonly completeStructured: <A>(\n request: StructuredCompletionRequest<A>,\n ) => Effect.Effect<A, LLMErrors>;\n\n /**\n * Generate embeddings for text.\n *\n * This is the SOLE embedding source for the entire framework.\n * Anthropic has no embeddings API — routes to OpenAI or Ollama\n * per LLMConfig.embeddingConfig.\n */\n readonly embed: (\n texts: readonly string[],\n model?: string,\n ) => Effect.Effect<readonly number[][], LLMErrors>;\n\n /**\n * Count tokens for a set of messages.\n * Used for context window management.\n */\n readonly countTokens: (\n messages: readonly LLMMessage[],\n ) => Effect.Effect<number, LLMErrors>;\n\n /**\n * Get current model configuration.\n */\n readonly getModelConfig: () => Effect.Effect<ModelConfig, never>;\n\n /**\n * Report structured output capabilities for this provider.\n * Used by the structured output pipeline to select optimal JSON extraction strategy.\n */\n readonly getStructuredOutputCapabilities: () => Effect.Effect<StructuredOutputCapabilities, never>;\n }\n>() {}\n","import { Context, Layer } from \"effect\";\nimport type { LLMProvider, EmbeddingConfig, ObservabilityVerbosity } from \"./types.js\";\n\n/**\n * LLM service configuration.\n * Provides API keys, default model settings, timeouts, and observability verbosity.\n * Typically constructed from environment variables via llmConfigFromEnv.\n *\n * @example\n * ```typescript\n * const config = LLMConfig.of({\n * defaultProvider: \"anthropic\",\n * defaultModel: \"claude-opus-4-20250514\",\n * anthropicApiKey: process.env.ANTHROPIC_API_KEY,\n * maxRetries: 3,\n * timeoutMs: 30000\n * });\n * ```\n */\nexport class LLMConfig extends Context.Tag(\"LLMConfig\")<\n LLMConfig,\n {\n /**\n * Default LLM provider.\n * Used as fallback when a request does not specify a provider.\n *\n * @default \"anthropic\"\n */\n readonly defaultProvider: LLMProvider;\n\n /**\n * Default LLM model identifier.\n * Used as fallback when a request does not specify a model.\n *\n * @default From LLM_DEFAULT_MODEL env var, falls back to \"claude-sonnet-4-20250514\"\n */\n readonly defaultModel: string;\n\n /**\n * Anthropic API key.\n * Retrieved from ANTHROPIC_API_KEY environment variable.\n * Required if provider is \"anthropic\".\n *\n * @default From ANTHROPIC_API_KEY env var (undefined if not set)\n */\n readonly anthropicApiKey?: string;\n\n /**\n * OpenAI API key.\n * Retrieved from OPENAI_API_KEY environment variable.\n * Required if provider is \"openai\".\n *\n * @default From OPENAI_API_KEY env var (undefined if not set)\n */\n readonly openaiApiKey?: string;\n\n /**\n * Google API key.\n * Retrieved from GOOGLE_API_KEY environment variable.\n * Required if provider is \"gemini\".\n *\n * @default From GOOGLE_API_KEY env var (undefined if not set)\n */\n readonly googleApiKey?: string;\n\n /**\n * Ollama server endpoint.\n * Retrieved from OLLAMA_ENDPOINT environment variable.\n * Used for local model serving.\n *\n * @default \"http://localhost:11434\"\n */\n readonly ollamaEndpoint?: string;\n\n /**\n * Embedding configuration — model, provider, dimensions.\n * Anthropic has no embeddings API; embeddings always route to OpenAI or Ollama.\n * This is the sole embedding config for the entire framework.\n * Used by semantic cache, memory similarity search, and verification layers.\n *\n * @default { model: \"text-embedding-3-small\", dimensions: 1536, provider: \"openai\", batchSize: 100 }\n */\n readonly embeddingConfig: EmbeddingConfig;\n\n /**\n * Enable Anthropic prompt caching.\n * When true, memory context injections and system prompts are wrapped in\n * `cache_control: { type: \"ephemeral\" }` blocks to reduce costs.\n * Non-Anthropic providers silently ignore cache control directives.\n * Automatically set to true if defaultModel starts with \"claude\".\n *\n * @default true if defaultModel starts with \"claude\", false otherwise\n */\n readonly supportsPromptCaching: boolean;\n\n /**\n * Maximum number of retries for transient LLM request failures.\n * Applied with exponential backoff (2^n seconds between attempts).\n *\n * @default 3\n */\n readonly maxRetries: number;\n\n /**\n * Request timeout in milliseconds.\n * LLM requests exceeding this duration are aborted.\n *\n * @default 30000 (30 seconds)\n */\n readonly timeoutMs: number;\n\n /**\n * Enable/disable thinking mode for thinking-capable models.\n * - `true` — Always enable thinking (e.g., qwen3.5, DeepSeek-R1)\n * - `false` — Always disable thinking (e.g., cogito:14b that crashes with think:true)\n * - `undefined` — Auto-detect based on model capabilities (Ollama only)\n *\n * @default undefined (auto-detect)\n */\n readonly thinking?: boolean;\n\n /**\n * Default maximum output tokens for LLM responses.\n * Used if a CompletionRequest does not specify maxTokens.\n * Set lower for faster responses; higher for longer outputs.\n *\n * @default 4096\n */\n readonly defaultMaxTokens: number;\n\n /**\n * Default sampling temperature (0.0-1.0).\n * Used if a CompletionRequest does not specify temperature.\n * 0.0 = deterministic; 1.0 = maximum randomness.\n *\n * @default 0.7 (good balance of creativity and coherence)\n */\n readonly defaultTemperature: number;\n\n /**\n * LLM request/response observability verbosity.\n * Determines what data is captured in LLMRequestEvent for observability.\n *\n * - **\"full\"**: Capture complete request/response payloads (useful for debugging, higher overhead)\n * - **\"metadata\"**: Capture only timing, token counts, and cost (lightweight, production-safe)\n *\n * @default \"full\" (capture everything)\n *\n * @example\n * ```typescript\n * // Development: full details\n * observabilityVerbosity: process.env.NODE_ENV === \"production\" ? \"metadata\" : \"full\"\n * ```\n */\n readonly observabilityVerbosity: ObservabilityVerbosity;\n }\n>() {}\n\n/**\n * Raw LLMConfig object constructed from environment variables.\n * Reads all config from process.env with sensible defaults.\n * Exported so callers can spread overrides (e.g. change model) on top.\n *\n * Environment variables:\n * - LLM_DEFAULT_MODEL: Model identifier (default: claude-sonnet-4-20250514)\n * - ANTHROPIC_API_KEY: Anthropic API key\n * - OPENAI_API_KEY: OpenAI API key\n * - GOOGLE_API_KEY: Google API key\n * - OLLAMA_ENDPOINT: Ollama server URL (default: http://localhost:11434)\n * - EMBEDDING_MODEL: Embedding model name (default: text-embedding-3-small)\n * - EMBEDDING_DIMENSIONS: Embedding vector dimensions (default: 1536)\n * - EMBEDDING_PROVIDER: Embedding provider (default: openai)\n * - LLM_MAX_RETRIES: Retry attempts (default: 3)\n * - LLM_TIMEOUT_MS: Request timeout in ms (default: 30000)\n * - LLM_DEFAULT_TEMPERATURE: Sampling temperature (default: 0.7)\n * - LLM_OBSERVABILITY_VERBOSITY: \"full\" or \"metadata\" (default: full)\n *\n * @example\n * ```typescript\n * // Use defaults from environment\n * const config = llmConfigFromEnv;\n *\n * // Override specific fields\n * const customConfig = LLMConfig.of({\n * ...llmConfigFromEnv,\n * defaultModel: \"gpt-4o\",\n * defaultProvider: \"openai\"\n * });\n * ```\n */\nexport const llmConfigFromEnv = LLMConfig.of({\n defaultProvider: \"anthropic\",\n defaultModel:\n process.env.LLM_DEFAULT_MODEL || \"claude-sonnet-4-20250514\",\n anthropicApiKey: process.env.ANTHROPIC_API_KEY,\n openaiApiKey: process.env.OPENAI_API_KEY,\n googleApiKey: process.env.GOOGLE_API_KEY,\n ollamaEndpoint:\n process.env.OLLAMA_ENDPOINT ?? \"http://localhost:11434\",\n embeddingConfig: {\n model: process.env.EMBEDDING_MODEL ?? \"text-embedding-3-small\",\n dimensions: Number(process.env.EMBEDDING_DIMENSIONS ?? 1536),\n provider:\n (process.env.EMBEDDING_PROVIDER as \"openai\" | \"ollama\") ?? \"openai\",\n batchSize: 100,\n },\n supportsPromptCaching: (\n process.env.LLM_DEFAULT_MODEL || \"claude-sonnet-4-20250514\"\n ).startsWith(\"claude\"),\n maxRetries: Number(process.env.LLM_MAX_RETRIES ?? 3),\n timeoutMs: Number(process.env.LLM_TIMEOUT_MS ?? 30_000),\n defaultMaxTokens: 4096,\n defaultTemperature: Number(process.env.LLM_DEFAULT_TEMPERATURE ?? 0.7),\n observabilityVerbosity: (process.env.LLM_OBSERVABILITY_VERBOSITY as ObservabilityVerbosity | undefined) ?? \"full\",\n});\n\n/**\n * Effect-TS Layer that provides LLMConfig from environment variables.\n * Use this layer to automatically populate LLMConfig from process.env.\n * Can be overridden with a custom layer for testing or custom configuration.\n *\n * @example\n * ```typescript\n * const effect = Effect.gen(function* () {\n * const config = yield* LLMConfig;\n * console.log(config.defaultModel);\n * }).pipe(Effect.provide(LLMConfigFromEnv));\n *\n * Effect.runPromise(effect);\n * ```\n *\n * @see llmConfigFromEnv\n */\nexport const LLMConfigFromEnv = Layer.succeed(LLMConfig, llmConfigFromEnv);\n","import { Effect, Context, Layer } from \"effect\";\nimport type { LLMMessage, TruncationStrategy } from \"./types.js\";\nimport type { LLMErrors } from \"./errors.js\";\nimport { estimateTokenCount } from \"./token-counter.js\";\n\n/**\n * Manages context window budgets.\n * Ensures prompts don't exceed model limits.\n * Implements truncation strategies.\n */\nexport class PromptManager extends Context.Tag(\"PromptManager\")<\n PromptManager,\n {\n /**\n * Build a prompt within token budget.\n * Automatically truncates conversation history if needed.\n */\n readonly buildPrompt: (options: {\n readonly systemPrompt: string;\n readonly messages: readonly LLMMessage[];\n readonly reserveOutputTokens: number;\n readonly maxContextTokens: number;\n readonly truncationStrategy: TruncationStrategy;\n }) => Effect.Effect<readonly LLMMessage[], LLMErrors>;\n\n /**\n * Check if messages fit within context window.\n */\n readonly fitsInContext: (\n messages: readonly LLMMessage[],\n maxTokens: number,\n ) => Effect.Effect<boolean, LLMErrors>;\n }\n>() {}\n\n/**\n * Live PromptManager that uses heuristic token counting\n * and applies truncation strategies.\n */\nexport const PromptManagerLive = Layer.succeed(\n PromptManager,\n PromptManager.of({\n buildPrompt: (options) =>\n Effect.gen(function* () {\n const {\n systemPrompt,\n messages,\n reserveOutputTokens,\n maxContextTokens,\n truncationStrategy,\n } = options;\n\n const budget = maxContextTokens - reserveOutputTokens;\n\n // Always keep the system prompt\n const systemMessage: LLMMessage = {\n role: \"system\",\n content: systemPrompt,\n };\n const systemTokens = yield* estimateTokenCount([systemMessage]);\n\n if (systemTokens >= budget) {\n // System prompt alone exceeds budget — return just it (truncated scenario)\n return [systemMessage];\n }\n\n const remainingBudget = budget - systemTokens;\n\n // Apply truncation strategy\n const truncated = yield* applyTruncation(\n messages,\n remainingBudget,\n truncationStrategy,\n );\n\n return [systemMessage, ...truncated];\n }),\n\n fitsInContext: (messages, maxTokens) =>\n Effect.gen(function* () {\n const count = yield* estimateTokenCount(messages);\n return count <= maxTokens;\n }),\n }),\n);\n\n/**\n * Apply truncation strategy to fit messages within token budget.\n */\nconst applyTruncation = (\n messages: readonly LLMMessage[],\n budget: number,\n strategy: TruncationStrategy,\n): Effect.Effect<readonly LLMMessage[], never> =>\n Effect.gen(function* () {\n const totalTokens = yield* estimateTokenCount(messages);\n\n if (totalTokens <= budget) {\n return messages;\n }\n\n switch (strategy) {\n case \"drop-oldest\": {\n // Remove messages from the beginning until we fit\n const result: LLMMessage[] = [];\n let usedTokens = 0;\n\n // Work backwards — keep most recent messages\n for (let i = messages.length - 1; i >= 0; i--) {\n const msgTokens = yield* estimateTokenCount([messages[i]!]);\n if (usedTokens + msgTokens <= budget) {\n result.unshift(messages[i]!);\n usedTokens += msgTokens;\n } else {\n break;\n }\n }\n return result;\n }\n\n case \"sliding-window\": {\n // Keep last N messages that fit\n const result: LLMMessage[] = [];\n let usedTokens = 0;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msgTokens = yield* estimateTokenCount([messages[i]!]);\n if (usedTokens + msgTokens <= budget) {\n result.unshift(messages[i]!);\n usedTokens += msgTokens;\n } else {\n break;\n }\n }\n return result;\n }\n\n case \"summarize-middle\":\n case \"importance-based\":\n // For Phase 1: fall back to sliding-window behavior\n // Full implementation requires LLM calls (circular dependency)\n {\n const result: LLMMessage[] = [];\n let usedTokens = 0;\n\n // Keep first message (often has important context)\n if (messages.length > 0) {\n const firstTokens = yield* estimateTokenCount([messages[0]!]);\n if (firstTokens <= budget) {\n result.push(messages[0]!);\n usedTokens += firstTokens;\n }\n }\n\n // Fill from the end\n const tail: LLMMessage[] = [];\n for (let i = messages.length - 1; i >= 1; i--) {\n const msgTokens = yield* estimateTokenCount([messages[i]!]);\n if (usedTokens + msgTokens <= budget) {\n tail.unshift(messages[i]!);\n usedTokens += msgTokens;\n } else {\n break;\n }\n }\n\n return [...result, ...tail];\n }\n }\n });\n","import { Effect } from \"effect\";\nimport type { LLMMessage } from \"./types.js\";\n\n/**\n * Estimate token count for messages.\n * Uses a simple heuristic: ~4 characters per token for English text.\n * This is used as a fallback when the provider's token counting API is unavailable.\n */\nexport const estimateTokenCount = (\n messages: readonly LLMMessage[],\n): Effect.Effect<number, never> =>\n Effect.sync(() => {\n let totalChars = 0;\n\n for (const msg of messages) {\n if (typeof msg.content === \"string\") {\n totalChars += msg.content.length;\n } else {\n // Content blocks\n for (const block of msg.content) {\n if (block.type === \"text\") {\n totalChars += block.text.length;\n } else if (block.type === \"tool_result\") {\n totalChars += block.content.length;\n } else if (block.type === \"tool_use\") {\n totalChars += JSON.stringify(block.input).length;\n }\n // Images not counted in token estimation\n }\n }\n // Add overhead for role/message framing (~4 tokens per message)\n totalChars += 16;\n }\n\n return Math.ceil(totalChars / 4);\n });\n\n/**\n * Calculate cost in USD given token counts and model name.\n */\nexport const calculateCost = (\n inputTokens: number,\n outputTokens: number,\n model: string,\n): number => {\n // Cost per 1M tokens lookup\n const costMap: Record<string, { input: number; output: number }> = {\n \"claude-3-5-haiku-20241022\": { input: 1.0, output: 5.0 },\n \"claude-sonnet-4-20250514\": { input: 3.0, output: 15.0 },\n \"claude-sonnet-4-5-20250929\": { input: 3.0, output: 15.0 },\n \"claude-opus-4-20250514\": { input: 15.0, output: 75.0 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4o\": { input: 2.5, output: 10.0 },\n \"gemini-2.0-flash\": { input: 0.1, output: 0.4 },\n \"gemini-2.5-pro-preview-03-25\": { input: 1.25, output: 10.0 },\n \"gemini-embedding-001\": { input: 0.0, output: 0.0 },\n };\n\n const costs = costMap[model] ?? { input: 3.0, output: 15.0 };\n return (\n (inputTokens / 1_000_000) * costs.input +\n (outputTokens / 1_000_000) * costs.output\n );\n};\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type {\n LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ContentBlock,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n// ─── Anthropic Message Conversion Helpers ───\n\ntype AnthropicRole = \"user\" | \"assistant\";\n\ntype AnthropicContentBlock =\n | { type: \"text\"; text: string; cache_control?: { type: \"ephemeral\" } }\n | { type: \"image\"; source: { type: string; media_type: string; data: string } }\n | { type: \"tool_use\"; id: string; name: string; input: unknown }\n | { type: \"tool_result\"; tool_use_id: string; content: string };\n\ntype AnthropicMessage = {\n role: AnthropicRole;\n content: string | AnthropicContentBlock[];\n};\n\nconst toAnthropicMessages = (\n messages: readonly LLMMessage[],\n): AnthropicMessage[] =>\n messages\n .filter((m) => m.role !== \"system\")\n .map((m) => {\n if (m.role === \"tool\") {\n // Convert tool result to Anthropic's tool_result content block format\n return {\n role: \"user\" as AnthropicRole,\n content: [{\n type: \"tool_result\" as const,\n tool_use_id: m.toolCallId,\n content: m.content,\n }] as unknown as AnthropicContentBlock[],\n };\n }\n return {\n role: m.role as AnthropicRole,\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly ContentBlock[]).map(\n (b) => b as unknown as AnthropicContentBlock,\n ),\n };\n });\n\nconst toAnthropicTool = (tool: {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}) => ({\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: \"object\" as const,\n ...tool.inputSchema,\n },\n});\n\nconst toEffectError = (error: unknown, provider: \"anthropic\"): LLMErrors => {\n const err = error as { status?: number; message?: string; headers?: Record<string, string> };\n if (err.status === 429) {\n const retryAfter = err.headers?.[\"retry-after\"];\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider,\n retryAfterMs: retryAfter ? Number(retryAfter) * 1000 : 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider,\n cause: error,\n });\n};\n\n// ─── Anthropic Provider Layer ───\n\nexport const AnthropicProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n // Lazy-load the SDK to avoid hard dependency if not using Anthropic\n const createClient = () => {\n // Dynamic import is handled in Effect.tryPromise\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const Anthropic = require(\"@anthropic-ai/sdk\").default;\n return new Anthropic({ apiKey: config.anthropicApiKey });\n };\n\n let _client: ReturnType<typeof createClient> | null = null;\n const getClient = () => {\n if (!_client) _client = createClient();\n return _client;\n };\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n\n const response = yield* Effect.tryPromise({\n try: () =>\n (client as { messages: { create: (opts: unknown) => Promise<unknown> } }).messages.create({\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n system: request.systemPrompt,\n messages: toAnthropicMessages(request.messages),\n stop_sequences: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n tools: request.tools?.map(toAnthropicTool),\n }),\n catch: (error) => toEffectError(error, \"anthropic\"),\n });\n\n return mapAnthropicResponse(response as AnthropicRawResponse, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"anthropic\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const stream = (client as { messages: { stream: (opts: unknown) => { on: (event: string, cb: (...args: unknown[]) => void) => void } } }).messages.stream({\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n system: request.systemPrompt,\n messages: toAnthropicMessages(request.messages),\n });\n\n stream.on(\"text\", (text: unknown) => {\n emit.single({ type: \"text_delta\", text: text as string });\n });\n\n stream.on(\"finalMessage\", (message: unknown) => {\n const msg = message as AnthropicRawResponse;\n const content = msg.content\n .filter(\n (b: { type: string }): b is { type: \"text\"; text: string } =>\n b.type === \"text\",\n )\n .map((b: { text: string }) => b.text)\n .join(\"\");\n\n emit.single({ type: \"content_complete\", content });\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens: msg.usage.input_tokens,\n outputTokens: msg.usage.output_tokens,\n totalTokens:\n msg.usage.input_tokens + msg.usage.output_tokens,\n estimatedCost: calculateCost(\n msg.usage.input_tokens,\n msg.usage.output_tokens,\n model,\n ),\n },\n });\n emit.end();\n });\n\n stream.on(\"error\", (error: unknown) => {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"anthropic\",\n cause: error,\n }),\n );\n });\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const schemaStr = JSON.stringify(\n Schema.encodedSchema(request.outputSchema),\n null,\n 2,\n );\n\n const messagesWithFormat: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ];\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messagesWithFormat\n : [\n ...messagesWithFormat,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response was not valid JSON. The parse error was: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ];\n\n const completeResult = yield* Effect.tryPromise({\n try: () => {\n const client = getClient();\n return (client as { messages: { create: (opts: unknown) => Promise<unknown> } }).messages.create({\n model: typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n system: request.systemPrompt,\n messages: toAnthropicMessages(msgs),\n });\n },\n catch: (error) => toEffectError(error, \"anthropic\"),\n });\n\n const response = mapAnthropicResponse(\n completeResult as AnthropicRawResponse,\n typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel,\n );\n\n try {\n const parsed = JSON.parse(response.content);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const embeddingModel = model ?? config.embeddingConfig.model;\n const embProvider = config.embeddingConfig.provider;\n\n if (embProvider === \"openai\") {\n const { default: OpenAI } = await import(\"openai\");\n const openaiClient = new OpenAI({\n apiKey: config.openaiApiKey,\n });\n const batchSize = config.embeddingConfig.batchSize ?? 100;\n const results: number[][] = [];\n\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize);\n const response = await openaiClient.embeddings.create({\n model: embeddingModel,\n input: [...batch],\n dimensions: config.embeddingConfig.dimensions,\n });\n results.push(\n ...response.data.map(\n (d: { embedding: number[] }) => d.embedding,\n ),\n );\n }\n\n return results;\n }\n\n // Ollama embeddings\n const endpoint =\n config.ollamaEndpoint ?? \"http://localhost:11434\";\n return Promise.all(\n [...texts].map(async (text) => {\n const res = await fetch(`${endpoint}/api/embed`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: embeddingModel,\n input: text,\n }),\n });\n const data = (await res.json()) as {\n embeddings: number[][];\n };\n return data.embeddings[0]!;\n }),\n );\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"anthropic\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"anthropic\" as const,\n model: config.defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: false,\n jsonSchemaEnforcement: false,\n prefillSupport: true,\n grammarConstraints: false,\n }),\n });\n }),\n);\n\n// ─── Anthropic Response Mapping ───\n\ntype AnthropicRawResponse = {\n content: Array<\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input: unknown }\n >;\n stop_reason: string;\n usage: { input_tokens: number; output_tokens: number };\n model: string;\n};\n\nconst mapAnthropicResponse = (\n response: AnthropicRawResponse,\n model: string,\n): CompletionResponse => {\n const textContent = response.content\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\");\n\n const toolCalls = response.content\n .filter(\n (\n b,\n ): b is {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n } => b.type === \"tool_use\",\n )\n .map((b) => ({\n id: b.id,\n name: b.name,\n input: b.input,\n }));\n\n const stopReason =\n response.stop_reason === \"end_turn\"\n ? (\"end_turn\" as const)\n : response.stop_reason === \"max_tokens\"\n ? (\"max_tokens\" as const)\n : response.stop_reason === \"stop_sequence\"\n ? (\"stop_sequence\" as const)\n : response.stop_reason === \"tool_use\"\n ? (\"tool_use\" as const)\n : (\"end_turn\" as const);\n\n return {\n content: textContent,\n stopReason,\n usage: {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n totalTokens:\n response.usage.input_tokens + response.usage.output_tokens,\n estimatedCost: calculateCost(\n response.usage.input_tokens,\n response.usage.output_tokens,\n model,\n ),\n },\n model: response.model ?? model,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n };\n};\n","import { Schedule } from \"effect\";\nimport type { LLMErrors } from \"./errors.js\";\n\n/**\n * Retry policy for LLM calls.\n * Handles rate limits with exponential backoff.\n * Only retries on rate limit and timeout errors.\n */\nexport const retryPolicy = Schedule.intersect(\n Schedule.recurs(3),\n Schedule.exponential(\"1 second\", 2.0),\n).pipe(\n Schedule.whileInput<LLMErrors>(\n (error) =>\n error._tag === \"LLMRateLimitError\" || error._tag === \"LLMTimeoutError\",\n ),\n);\n\n// ─── Circuit Breaker ───\n\nexport type CircuitBreakerConfig = {\n readonly failureThreshold: number;\n readonly cooldownMs: number;\n readonly halfOpenRequests: number;\n};\n\nexport const defaultCircuitBreakerConfig: CircuitBreakerConfig = {\n failureThreshold: 5,\n cooldownMs: 30_000,\n halfOpenRequests: 1,\n};\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ToolDefinition,\n ToolCall,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n// ─── OpenAI Message Conversion ───\n\ntype OpenAIMessage =\n | { role: \"system\" | \"user\" | \"assistant\"; content: string }\n | { role: \"tool\"; tool_call_id: string; content: string };\n\nconst toOpenAIMessages = (\n messages: readonly LLMMessage[],\n): OpenAIMessage[] =>\n messages.map((m) => {\n if (m.role === \"tool\") {\n return {\n role: \"tool\" as const,\n tool_call_id: m.toolCallId,\n content: m.content,\n };\n }\n return {\n role: m.role as \"system\" | \"user\" | \"assistant\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\"),\n };\n });\n\nconst toEffectError = (error: unknown, provider: \"openai\"): LLMErrors => {\n const err = error as { status?: number; message?: string };\n if (err.status === 429) {\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider,\n retryAfterMs: 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider,\n cause: error,\n });\n};\n\n// ─── OpenAI Tool Conversion ───\n\nconst toOpenAITool = (tool: ToolDefinition) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n});\n\n// ─── OpenAI Provider Layer ───\n\nexport const OpenAIProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n const createClient = () => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const OpenAI = require(\"openai\").default;\n return new OpenAI({ apiKey: config.openaiApiKey });\n };\n\n let _client: ReturnType<typeof createClient> | null = null;\n const getClient = () => {\n if (!_client) _client = createClient();\n return _client;\n };\n\n const defaultModel = config.defaultModel.startsWith(\"claude\")\n ? \"gpt-4o\"\n : config.defaultModel;\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? defaultModel;\n\n const messages = toOpenAIMessages(request.messages);\n if (request.systemPrompt) {\n messages.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const requestBody: Record<string, unknown> = {\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n messages,\n stop: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n };\n\n if (request.tools && request.tools.length > 0) {\n requestBody.tools = request.tools.map(toOpenAITool);\n }\n\n const response = yield* Effect.tryPromise({\n try: () =>\n (client as { chat: { completions: { create: (opts: unknown) => Promise<unknown> } } }).chat.completions.create(requestBody),\n catch: (error) => toEffectError(error, \"openai\"),\n });\n\n return mapOpenAIResponse(response as OpenAIRawResponse, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"openai\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? defaultModel;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const doStream = async () => {\n try {\n const stream = await (client as { chat: { completions: { create: (opts: unknown) => Promise<AsyncIterable<unknown>> } } }).chat.completions.create({\n model,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature:\n request.temperature ?? config.defaultTemperature,\n messages: (() => {\n const msgs = toOpenAIMessages(request.messages);\n if (request.systemPrompt) {\n msgs.unshift({ role: \"system\", content: request.systemPrompt });\n }\n return msgs;\n })(),\n stream: true,\n });\n\n let fullContent = \"\";\n\n for await (const chunk of stream as AsyncIterable<{\n choices: Array<{\n delta: { content?: string };\n finish_reason?: string;\n }>;\n usage?: { prompt_tokens: number; completion_tokens: number };\n }>) {\n const delta = chunk.choices[0]?.delta?.content;\n if (delta) {\n fullContent += delta;\n emit.single({ type: \"text_delta\", text: delta });\n }\n\n if (chunk.choices[0]?.finish_reason) {\n emit.single({\n type: \"content_complete\",\n content: fullContent,\n });\n\n const inputTokens = chunk.usage?.prompt_tokens ?? 0;\n const outputTokens =\n chunk.usage?.completion_tokens ?? 0;\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(\n inputTokens,\n outputTokens,\n model,\n ),\n },\n });\n emit.end();\n }\n }\n } catch (error) {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"openai\",\n cause: error,\n }),\n );\n }\n };\n void doStream();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const schemaStr = JSON.stringify(\n Schema.encodedSchema(request.outputSchema),\n null,\n 2,\n );\n\n const messagesWithFormat: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ];\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messagesWithFormat\n : [\n ...messagesWithFormat,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response was not valid JSON. The parse error was: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ];\n\n const client = getClient();\n const completeResult = yield* Effect.tryPromise({\n try: () =>\n (client as { chat: { completions: { create: (opts: unknown) => Promise<unknown> } } }).chat.completions.create({\n model: typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? defaultModel,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature:\n request.temperature ?? config.defaultTemperature,\n messages: toOpenAIMessages(msgs),\n }),\n catch: (error) => toEffectError(error, \"openai\"),\n });\n\n const response = mapOpenAIResponse(\n completeResult as OpenAIRawResponse,\n typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? defaultModel,\n );\n\n try {\n const parsed = JSON.parse(response.content);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const client = getClient();\n const embeddingModel =\n model ?? config.embeddingConfig.model;\n const batchSize = config.embeddingConfig.batchSize ?? 100;\n const results: number[][] = [];\n\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize);\n const response = await (client as { embeddings: { create: (opts: unknown) => Promise<{ data: Array<{ embedding: number[] }> }> } }).embeddings.create({\n model: embeddingModel,\n input: [...batch],\n dimensions: config.embeddingConfig.dimensions,\n });\n results.push(\n ...response.data.map(\n (d: { embedding: number[] }) => d.embedding,\n ),\n );\n }\n\n return results;\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"openai\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"openai\" as const,\n model: defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: true,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n });\n }),\n);\n\n// ─── OpenAI Response Mapping ───\n\ntype OpenAIToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\ntype OpenAIRawResponse = {\n choices: Array<{\n message: {\n content: string | null;\n role: string;\n tool_calls?: OpenAIToolCall[];\n };\n finish_reason: string;\n }>;\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n model: string;\n};\n\nconst mapOpenAIResponse = (\n response: OpenAIRawResponse,\n model: string,\n): CompletionResponse => {\n const message = response.choices[0]?.message;\n const content = message?.content ?? \"\";\n const rawToolCalls = message?.tool_calls;\n\n const hasToolCalls = rawToolCalls && rawToolCalls.length > 0;\n\n const stopReason =\n response.choices[0]?.finish_reason === \"tool_calls\" || hasToolCalls\n ? (\"tool_use\" as const)\n : response.choices[0]?.finish_reason === \"stop\"\n ? (\"end_turn\" as const)\n : response.choices[0]?.finish_reason === \"length\"\n ? (\"max_tokens\" as const)\n : (\"end_turn\" as const);\n\n const toolCalls: ToolCall[] | undefined = hasToolCalls\n ? rawToolCalls.map((tc) => {\n let input: unknown;\n try {\n input = JSON.parse(tc.function.arguments);\n } catch {\n input = { raw: tc.function.arguments };\n }\n return {\n id: tc.id,\n name: tc.function.name,\n input,\n };\n })\n : undefined;\n\n return {\n content,\n stopReason,\n usage: {\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n totalTokens: response.usage?.total_tokens ?? 0,\n estimatedCost: calculateCost(\n response.usage?.prompt_tokens ?? 0,\n response.usage?.completion_tokens ?? 0,\n model,\n ),\n },\n model: response.model ?? model,\n toolCalls,\n };\n};\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport { LLMError, LLMTimeoutError, LLMParseError } from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ToolDefinition,\n ToolCall,\n} from \"../types.js\";\nimport { estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\nimport { getProviderDefaultModel } from \"../provider-defaults.js\";\n\n// ─── Ollama SDK types (from the `ollama` npm package) ───\n\ntype OllamaTool = {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n};\n\ntype OllamaMessage = {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tool_calls?: Array<{\n function: { name: string; arguments: Record<string, any> };\n }>;\n};\n\n// ─── Conversion Helpers ───\n\nconst toOllamaMessages = (messages: readonly LLMMessage[]): OllamaMessage[] =>\n messages.map((m) => {\n // Tool result messages — pass through directly (Ollama supports role:\"tool\")\n if (m.role === \"tool\") {\n return { role: \"tool\" as const, content: m.content };\n }\n // Assistant messages — extract text and convert tool_use blocks to tool_calls\n if (m.role === \"assistant\") {\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\");\n const toolUseBlocks =\n typeof m.content !== \"string\"\n ? (\n m.content as readonly {\n type: string;\n name?: string;\n input?: unknown;\n }[]\n ).filter(\n (b): b is { type: \"tool_use\"; name: string; input: unknown } =>\n b.type === \"tool_use\",\n )\n : [];\n return {\n role: \"assistant\" as const,\n content: textContent,\n ...(toolUseBlocks.length > 0\n ? {\n tool_calls: toolUseBlocks.map((tc) => ({\n function: {\n name: tc.name,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arguments: (tc.input ?? {}) as Record<string, any>,\n },\n })),\n }\n : {}),\n };\n }\n // system, user\n return {\n role: m.role as \"system\" | \"user\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\"),\n };\n });\n\nconst toOllamaTools = (\n tools?: readonly ToolDefinition[],\n): OllamaTool[] | undefined => {\n if (!tools || tools.length === 0) return undefined;\n return tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema as Record<string, unknown>,\n },\n }));\n};\n\nconst parseToolCalls = (\n toolCalls?: Array<{\n function: { name: string; arguments: unknown };\n }>,\n): ToolCall[] | undefined => {\n if (!toolCalls || toolCalls.length === 0) return undefined;\n return toolCalls.map((tc, i) => ({\n id: `ollama-tc-${Date.now()}-${i}`,\n name: tc.function.name,\n input: tc.function.arguments,\n }));\n};\n\n// ─── Thinking Auto-Detect ───\n\n/** Cache for model thinking capability checks (avoids repeated /api/show calls) */\nconst thinkingCapabilityCache = new Map<string, boolean>();\n\n/**\n * Check if an Ollama model supports thinking mode via /api/show.\n * Results are cached per model name.\n */\nasync function supportsThinking(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client: { show: (opts: { model: string }) => Promise<any> },\n model: string,\n): Promise<boolean> {\n const cached = thinkingCapabilityCache.get(model);\n if (cached !== undefined) return cached;\n\n try {\n const info = await client.show({ model });\n const template = (info.template ?? \"\") as string;\n const result =\n template.includes(\"think\") || template.includes(\"<|thinking|>\");\n thinkingCapabilityCache.set(model, result);\n return result;\n } catch {\n thinkingCapabilityCache.set(model, false);\n return false;\n }\n}\n\n/**\n * Resolve the `think` parameter for Ollama chat calls.\n * - config.thinking === true → always enable\n * - config.thinking === false → always disable (omit param)\n * - config.thinking === undefined → auto-detect via /api/show\n */\nasync function resolveThinking(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client: { show: (opts: { model: string }) => Promise<any> },\n model: string,\n configThinking: boolean | undefined,\n): Promise<boolean | undefined> {\n if (configThinking === false) return undefined; // omit think param entirely\n if (configThinking === true) return true;\n // Auto-detect\n const capable = await supportsThinking(client, model);\n return capable ? true : undefined;\n}\n\n// ─── Error Helpers ───\n\n/**\n * Detect Ollama \"model not found\" errors and produce an actionable message.\n * Ollama returns ResponseError with status 404 and message \"model 'X' not found\".\n */\nfunction ollamaError(error: unknown, model?: string): LLMError {\n const msg = (error as { message?: string })?.message ?? String(error);\n const status =\n (error as { status_code?: number; statusCode?: number })?.status_code ??\n (error as { status_code?: number; statusCode?: number })?.statusCode;\n\n // Model not found — give the user a clear fix command\n if (status === 404 || /model\\s+['\"]?\\S+['\"]?\\s+not found/i.test(msg)) {\n const modelName =\n model ??\n msg.match(/model\\s+['\"]?(\\S+?)['\"]?\\s+not found/i)?.[1] ??\n \"unknown\";\n return new LLMError({\n message: `Model \"${modelName}\" not found locally. Run: ollama pull ${modelName}`,\n provider: \"ollama\",\n cause: error,\n });\n }\n\n return new LLMError({\n message: `Ollama request failed: ${msg}`,\n provider: \"ollama\",\n cause: error,\n });\n}\n// ─── Ollama / Local Provider Layer ───\n\nexport const LocalProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n const endpoint = config.ollamaEndpoint ?? \"http://localhost:11434\";\n const defaultModel =\n config.defaultModel.startsWith(\"claude\") ||\n config.defaultModel.startsWith(\"gpt\")\n ? (getProviderDefaultModel(\"ollama\") ?? \"cogito:14b\")\n : config.defaultModel;\n\n // Lazy-import the ollama SDK (same pattern as Gemini provider)\n const getClient = async () => {\n const { Ollama } = await import(\"ollama\");\n return new Ollama({ host: endpoint });\n };\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : (request.model?.model ?? defaultModel);\n\n const response = yield* Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n\n const msgs = toOllamaMessages(request.messages);\n if (request.systemPrompt) {\n msgs.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const think = await resolveThinking(\n client,\n model,\n config.thinking,\n );\n\n return client.chat({\n model,\n messages: msgs,\n tools: toOllamaTools(request.tools),\n stream: false,\n ...(think !== undefined ? { think } : {}),\n keep_alive: \"5m\",\n options: {\n temperature: request.temperature ?? config.defaultTemperature,\n num_predict: request.maxTokens ?? config.defaultMaxTokens,\n stop: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n },\n });\n },\n catch: (error) => ollamaError(error, model),\n });\n\n const content = response.message?.content ?? \"\";\n // Extract thinking from Ollama response (available in SDK v0.6+ for thinking models)\n const thinkingContent =\n (response.message as { thinking?: string } | undefined)?.thinking ||\n undefined;\n const inputTokens = response.prompt_eval_count ?? 0;\n const outputTokens = response.eval_count ?? 0;\n const toolCalls = parseToolCalls(\n response.message?.tool_calls as\n | Array<{\n function: { name: string; arguments: unknown };\n }>\n | undefined,\n );\n\n const hasToolCalls = toolCalls && toolCalls.length > 0;\n\n return {\n content,\n stopReason: hasToolCalls\n ? (\"tool_use\" as const)\n : response.done_reason === \"stop\"\n ? (\"end_turn\" as const)\n : response.done_reason === \"length\"\n ? (\"max_tokens\" as const)\n : (\"end_turn\" as const),\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: 0, // Local models are free\n },\n model: response.model ?? model,\n toolCalls,\n ...(thinkingContent ? { thinking: thinkingContent } : {}),\n } satisfies CompletionResponse;\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"120 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"Local LLM request timed out\",\n provider: \"ollama\",\n timeoutMs: 120_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : (request.model?.model ?? defaultModel);\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const doStream = async () => {\n try {\n const client = await getClient();\n\n const msgs = toOllamaMessages(request.messages);\n if (request.systemPrompt) {\n msgs.unshift({\n role: \"system\",\n content: request.systemPrompt,\n });\n }\n\n const think = await resolveThinking(\n client,\n model,\n config.thinking,\n );\n\n const stream = await client.chat({\n model,\n messages: msgs,\n tools: toOllamaTools(request.tools),\n stream: true,\n ...(think !== undefined ? { think } : {}),\n keep_alive: \"5m\",\n options: {\n temperature:\n request.temperature ?? config.defaultTemperature,\n num_predict: request.maxTokens ?? config.defaultMaxTokens,\n },\n });\n\n let fullContent = \"\";\n\n for await (const chunk of stream) {\n if (chunk.message?.content) {\n fullContent += chunk.message.content;\n emit.single({\n type: \"text_delta\",\n text: chunk.message.content,\n });\n }\n\n if (chunk.done) {\n emit.single({\n type: \"content_complete\",\n content: fullContent,\n });\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens: chunk.prompt_eval_count ?? 0,\n outputTokens: chunk.eval_count ?? 0,\n totalTokens:\n (chunk.prompt_eval_count ?? 0) +\n (chunk.eval_count ?? 0),\n estimatedCost: 0,\n },\n });\n emit.end();\n }\n }\n } catch (error) {\n emit.fail(ollamaError(error, model));\n }\n };\n void doStream();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const schemaStr = JSON.stringify(\n Schema.encodedSchema(request.outputSchema),\n null,\n 2,\n );\n\n const model =\n typeof request.model === \"string\"\n ? request.model\n : (request.model?.model ?? defaultModel);\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs = toOllamaMessages(\n attempt === 0\n ? [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ]\n : [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response was not valid JSON. The parse error was: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ],\n );\n\n if (request.systemPrompt) {\n msgs.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const response = yield* Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n return client.chat({\n model,\n messages: msgs,\n stream: false,\n format: \"json\",\n keep_alive: \"5m\",\n options: {\n temperature:\n request.temperature ?? config.defaultTemperature,\n num_predict: request.maxTokens ?? config.defaultMaxTokens,\n },\n });\n },\n catch: (error) => ollamaError(error, model),\n });\n\n const content = response.message?.content ?? \"\";\n\n try {\n const parsed = JSON.parse(content);\n const decoded = Schema.decodeUnknownEither(request.outputSchema)(\n parsed,\n );\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n const embeddingModel =\n model ?? config.embeddingConfig.model ?? \"nomic-embed-text\";\n\n const response = await client.embed({\n model: embeddingModel,\n input: [...texts],\n });\n\n return response.embeddings;\n },\n catch: (error) =>\n ollamaError(\n error,\n model ?? config.embeddingConfig.model ?? \"nomic-embed-text\",\n ),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"ollama\" as const,\n model: defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: false,\n prefillSupport: false,\n grammarConstraints: true,\n }),\n });\n }),\n);\n","/**\n * Default model constants for each LLM provider.\n * Single source of truth — used by providers at construction time\n * and by the runtime to resolve model names for display/metrics.\n */\n\nexport const PROVIDER_DEFAULT_MODELS: Record<string, string> = {\n anthropic: \"claude-sonnet-4-20250514\",\n openai: \"gpt-4o\",\n ollama: \"cogito:14b\",\n gemini: \"gemini-2.0-flash\",\n litellm: \"gpt-4o\",\n test: \"test-model\",\n};\n\n/**\n * Get the default model for a given provider.\n * Returns undefined if the provider is not recognized.\n */\nexport function getProviderDefaultModel(provider: string): string | undefined {\n return PROVIDER_DEFAULT_MODELS[provider];\n}\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ContentBlock,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n// ─── Gemini Message Conversion Helpers ───\n\ntype GeminiPart =\n | { text: string }\n | { functionCall: { name: string; args: unknown } }\n | { functionResponse: { name: string; response: unknown } };\n\ntype GeminiContent = {\n role: \"user\" | \"model\";\n parts: GeminiPart[];\n};\n\nconst toGeminiContents = (messages: readonly LLMMessage[]): GeminiContent[] => {\n const result: GeminiContent[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"system\") continue; // handled via config.systemInstruction\n\n // Handle tool result messages\n if (msg.role === \"tool\") {\n result.push({\n role: \"user\",\n parts: [{\n functionResponse: {\n name: \"tool\",\n response: { content: msg.content },\n },\n }],\n });\n continue;\n }\n\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n\n if (typeof msg.content === \"string\") {\n result.push({ role, parts: [{ text: msg.content }] });\n } else {\n const parts: GeminiPart[] = [];\n for (const block of msg.content as readonly ContentBlock[]) {\n if (block.type === \"text\") {\n parts.push({ text: block.text });\n } else if (block.type === \"tool_use\") {\n parts.push({\n functionCall: { name: block.name, args: block.input },\n });\n } else if (block.type === \"tool_result\") {\n parts.push({\n functionResponse: {\n name: \"tool\",\n response: { content: block.content },\n },\n });\n }\n // images not converted — Gemini multimodal requires separate file URIs\n }\n if (parts.length > 0) {\n result.push({ role, parts });\n }\n }\n }\n\n return result;\n};\n\nconst extractSystemPrompt = (\n messages: readonly LLMMessage[],\n): string | undefined => {\n const sys = messages.find((m) => m.role === \"system\");\n if (!sys) return undefined;\n return typeof sys.content === \"string\" ? sys.content : undefined;\n};\n\nconst toGeminiTools = (\n tools: { name: string; description: string; inputSchema: Record<string, unknown> }[],\n) =>\n tools.length === 0\n ? undefined\n : [\n {\n functionDeclarations: tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: { type: \"object\", ...t.inputSchema },\n })),\n },\n ];\n\nconst toEffectError = (error: unknown): LLMErrors => {\n const err = error as { status?: number; code?: number; message?: string };\n if (err.status === 429 || err.code === 429) {\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider: \"gemini\",\n retryAfterMs: 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider: \"gemini\",\n cause: error,\n });\n};\n\n// ─── Gemini Response Types ───\n\ntype GeminiUsage = {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n totalTokenCount?: number;\n};\n\ntype GeminiFunctionCall = { name: string; args: unknown };\n\ntype GeminiRawResponse = {\n text: string;\n functionCalls?: GeminiFunctionCall[];\n usageMetadata?: GeminiUsage;\n};\n\n// ─── Response Mapper ───\n\nconst mapGeminiResponse = (\n response: GeminiRawResponse,\n model: string,\n): CompletionResponse => {\n const toolCalls = response.functionCalls?.map((fc, i) => ({\n id: `call_${i}`,\n name: fc.name,\n input: fc.args,\n }));\n\n const inputTokens = response.usageMetadata?.promptTokenCount ?? 0;\n const outputTokens = response.usageMetadata?.candidatesTokenCount ?? 0;\n\n return {\n content: response.text ?? \"\",\n stopReason: toolCalls?.length ? \"tool_use\" : \"end_turn\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(inputTokens, outputTokens, model),\n },\n model,\n toolCalls: toolCalls?.length ? toolCalls : undefined,\n };\n};\n\n// ─── Gemini Provider Layer ───\n\nconst GEMINI_DEFAULT_MODEL = \"gemini-2.5-flash\";\n\nexport const GeminiProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n // ─── Lazy-load the SDK via dynamic import (interceptable by mock.module) ───\n\n type GoogleGenAIClient = {\n models: {\n generateContent: (opts: unknown) => Promise<GeminiRawResponse>;\n generateContentStream: (opts: unknown) => Promise<\n AsyncIterable<{\n text: string;\n usageMetadata?: GeminiUsage;\n }>\n >;\n embedContent: (opts: unknown) => Promise<{\n embeddings: Array<{ values: number[] }>;\n }>;\n };\n };\n\n type GoogleGenAIModule = {\n GoogleGenAI: new (opts: { apiKey?: string }) => GoogleGenAIClient;\n };\n\n let _clientPromise: Promise<GoogleGenAIClient> | null = null;\n const getClient = (): Promise<GoogleGenAIClient> => {\n if (!_clientPromise) {\n _clientPromise = (\n import(\"@google/genai\") as Promise<GoogleGenAIModule>\n ).then(({ GoogleGenAI }) => new GoogleGenAI({ apiKey: config.googleApiKey }));\n }\n return _clientPromise;\n };\n\n const buildGeminiConfig = (opts: {\n maxTokens?: number;\n temperature?: number;\n systemPrompt?: string;\n stopSequences?: readonly string[];\n tools?: readonly { name: string; description: string; inputSchema: Record<string, unknown> }[];\n }) => {\n const cfg: Record<string, unknown> = {\n maxOutputTokens: opts.maxTokens ?? config.defaultMaxTokens,\n temperature: opts.temperature ?? config.defaultTemperature,\n };\n const sys = opts.systemPrompt;\n if (sys) cfg.systemInstruction = sys;\n if (opts.stopSequences?.length) cfg.stopSequences = [...opts.stopSequences];\n if (opts.tools?.length) {\n cfg.tools = toGeminiTools([...opts.tools]);\n }\n return cfg;\n };\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const client = yield* Effect.promise(() => getClient());\n let model = typeof request.model === 'string' \n ? request.model \n : request.model?.model ?? config.defaultModel;\n // If using non-Gemini default (e.g., Anthropic), fall back to Gemini default\n if (!model || model.startsWith(\"claude\") || model.startsWith(\"gpt-\")) {\n model = GEMINI_DEFAULT_MODEL;\n }\n const contents = toGeminiContents(request.messages);\n const systemPrompt =\n extractSystemPrompt(request.messages) ?? request.systemPrompt;\n\n const response = yield* Effect.tryPromise({\n try: () =>\n client.models.generateContent({\n model,\n contents,\n config: buildGeminiConfig({\n maxTokens: request.maxTokens,\n temperature: request.temperature,\n systemPrompt,\n stopSequences: request.stopSequences,\n tools: request.tools,\n }),\n }),\n catch: toEffectError,\n });\n\n return mapGeminiResponse(response, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"gemini\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n let model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n // If using non-Gemini default (e.g., Anthropic), fall back to Gemini default\n if (!model || model.startsWith(\"claude\") || model.startsWith(\"gpt-\")) {\n model = GEMINI_DEFAULT_MODEL;\n }\n const contents = toGeminiContents(request.messages);\n const systemPrompt =\n extractSystemPrompt(request.messages) ?? request.systemPrompt;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n void (async () => {\n try {\n const client = await getClient();\n const stream = await client.models.generateContentStream({\n model,\n contents,\n config: buildGeminiConfig({\n maxTokens: request.maxTokens,\n temperature: request.temperature,\n systemPrompt,\n }),\n });\n\n let fullContent = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n\n for await (const chunk of stream) {\n if (chunk.text) {\n emit.single({ type: \"text_delta\", text: chunk.text });\n fullContent += chunk.text;\n }\n if (chunk.usageMetadata) {\n inputTokens = chunk.usageMetadata.promptTokenCount ?? 0;\n outputTokens =\n chunk.usageMetadata.candidatesTokenCount ?? 0;\n }\n }\n\n emit.single({ type: \"content_complete\", content: fullContent });\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(inputTokens, outputTokens, model),\n },\n });\n emit.end();\n } catch (error) {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"gemini\",\n cause: error,\n }),\n );\n }\n })();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const schemaStr = JSON.stringify(\n Schema.encodedSchema(request.outputSchema),\n null,\n 2,\n );\n\n const messagesWithFormat: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ];\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messagesWithFormat\n : [\n ...messagesWithFormat,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response was not valid JSON. The parse error was: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ];\n\n const client = yield* Effect.promise(() => getClient());\n let model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n // If using non-Gemini default (e.g., Anthropic), fall back to Gemini default\n if (!model || model.startsWith(\"claude\") || model.startsWith(\"gpt-\")) {\n model = GEMINI_DEFAULT_MODEL;\n }\n\n const response = yield* Effect.tryPromise({\n try: () =>\n client.models.generateContent({\n model,\n contents: toGeminiContents(msgs),\n config: buildGeminiConfig({\n maxTokens: request.maxTokens,\n temperature: request.temperature,\n systemPrompt: request.systemPrompt,\n }),\n }),\n catch: toEffectError,\n });\n\n const mapped = mapGeminiResponse(response, model);\n\n try {\n const parsed = JSON.parse(mapped.content);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n const embeddingModel = model ?? \"gemini-embedding-001\";\n\n const result = await client.models.embedContent({\n model: embeddingModel,\n contents: [...texts],\n config: {\n outputDimensionality: config.embeddingConfig.dimensions,\n },\n });\n\n return result.embeddings.map((e) => e.values);\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"gemini\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"gemini\" as const,\n model: config.defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: false,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n });\n }),\n);\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ToolDefinition,\n ToolCall,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n/**\n * LiteLLM Provider — OpenAI-compatible adapter for LiteLLM proxy.\n *\n * LiteLLM is an enterprise model gateway that exposes 100+ LLM providers\n * (Anthropic, OpenAI, Azure, Bedrock, Vertex, etc.) via a single OpenAI-\n * compatible API endpoint.\n *\n * Configuration:\n * LITELLM_BASE_URL=http://localhost:4000 (default)\n * LITELLM_API_KEY=sk-... (optional, for auth)\n *\n * Model names use LiteLLM format: \"provider/model\"\n * e.g. \"anthropic/claude-3-5-sonnet-20241022\", \"openai/gpt-4o\"\n */\n\n// ─── Message Conversion (reuses OpenAI format) ───\n\ntype LiteLLMMessage =\n | { role: \"system\" | \"user\" | \"assistant\"; content: string }\n | { role: \"tool\"; tool_call_id: string; content: string };\n\nconst toLiteLLMMessages = (\n messages: readonly LLMMessage[],\n): LiteLLMMessage[] =>\n messages.map((m) => {\n if (m.role === \"tool\") {\n return {\n role: \"tool\" as const,\n tool_call_id: m.toolCallId,\n content: m.content,\n };\n }\n return {\n role: m.role as \"system\" | \"user\" | \"assistant\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\"),\n };\n });\n\nconst toEffectError = (error: unknown): LLMErrors => {\n const err = error as { status?: number; message?: string };\n if (err.status === 429) {\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider: \"litellm\",\n retryAfterMs: 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider: \"litellm\",\n cause: error,\n });\n};\n\nconst toLiteLLMTool = (tool: ToolDefinition) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n});\n\n// ─── Response Types ───\n\ntype LiteLLMToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\ntype LiteLLMRawResponse = {\n choices: Array<{\n message: {\n content: string | null;\n role: string;\n tool_calls?: LiteLLMToolCall[];\n };\n finish_reason: string;\n }>;\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n model: string;\n};\n\nconst mapLiteLLMResponse = (\n response: LiteLLMRawResponse,\n model: string,\n): CompletionResponse => {\n const message = response.choices[0]?.message;\n const content = message?.content ?? \"\";\n const rawToolCalls = message?.tool_calls;\n const hasToolCalls = rawToolCalls && rawToolCalls.length > 0;\n\n const stopReason =\n response.choices[0]?.finish_reason === \"tool_calls\" || hasToolCalls\n ? (\"tool_use\" as const)\n : response.choices[0]?.finish_reason === \"stop\"\n ? (\"end_turn\" as const)\n : response.choices[0]?.finish_reason === \"length\"\n ? (\"max_tokens\" as const)\n : (\"end_turn\" as const);\n\n const toolCalls: ToolCall[] | undefined = hasToolCalls\n ? rawToolCalls.map((tc) => {\n let input: unknown;\n try {\n input = JSON.parse(tc.function.arguments);\n } catch {\n input = { raw: tc.function.arguments };\n }\n return { id: tc.id, name: tc.function.name, input };\n })\n : undefined;\n\n return {\n content,\n stopReason,\n usage: {\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n totalTokens: response.usage?.total_tokens ?? 0,\n estimatedCost: calculateCost(\n response.usage?.prompt_tokens ?? 0,\n response.usage?.completion_tokens ?? 0,\n model,\n ),\n },\n model: response.model ?? model,\n toolCalls,\n };\n};\n\n// ─── Fetch helper ───\n\nconst liteLLMFetch = async (\n baseURL: string,\n path: string,\n body: unknown,\n apiKey?: string,\n): Promise<unknown> => {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`;\n\n const res = await fetch(`${baseURL}${path}`, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n });\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n throw Object.assign(\n new Error(`LiteLLM ${res.status}: ${text || res.statusText}`),\n { status: res.status },\n );\n }\n\n return res.json();\n};\n\n// ─── LiteLLM Provider Layer ───\n\nexport const LiteLLMProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n const baseURL =\n (config as unknown as { litellmBaseUrl?: string }).litellmBaseUrl ??\n process.env.LITELLM_BASE_URL ??\n \"http://localhost:4000\";\n const apiKey =\n (config as unknown as { litellmApiKey?: string }).litellmApiKey ??\n process.env.LITELLM_API_KEY ??\n undefined;\n\n const defaultModel = config.defaultModel;\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : request.model?.model ?? defaultModel;\n\n const messages = toLiteLLMMessages(request.messages);\n if (request.systemPrompt) {\n messages.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const requestBody: Record<string, unknown> = {\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n messages,\n stop: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n };\n\n if (request.tools && request.tools.length > 0) {\n requestBody.tools = request.tools.map(toLiteLLMTool);\n }\n\n const response = yield* Effect.tryPromise({\n try: () =>\n liteLLMFetch(baseURL, \"/chat/completions\", requestBody, apiKey),\n catch: (error) => toEffectError(error),\n });\n\n return mapLiteLLMResponse(response as LiteLLMRawResponse, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"litellm\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : request.model?.model ?? defaultModel;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const doStream = async () => {\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`;\n\n const messages = toLiteLLMMessages(request.messages);\n if (request.systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: request.systemPrompt,\n });\n }\n\n const res = await fetch(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature:\n request.temperature ?? config.defaultTemperature,\n messages,\n stream: true,\n }),\n });\n\n if (!res.ok || !res.body) {\n throw new Error(`LiteLLM stream error: ${res.status}`);\n }\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let fullContent = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n const data = trimmed.slice(5).trim();\n if (data === \"[DONE]\") {\n emit.single({\n type: \"content_complete\",\n content: fullContent,\n });\n emit.end();\n return;\n }\n\n try {\n const chunk = JSON.parse(data) as {\n choices: Array<{\n delta: { content?: string };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n };\n };\n\n const delta = chunk.choices[0]?.delta?.content;\n if (delta) {\n fullContent += delta;\n emit.single({ type: \"text_delta\", text: delta });\n }\n\n if (chunk.choices[0]?.finish_reason) {\n const inputTokens =\n chunk.usage?.prompt_tokens ?? 0;\n const outputTokens =\n chunk.usage?.completion_tokens ?? 0;\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(\n inputTokens,\n outputTokens,\n model,\n ),\n },\n });\n }\n } catch {\n // Skip invalid JSON chunks\n }\n }\n }\n } catch (error) {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"litellm\",\n cause: error,\n }),\n );\n }\n };\n void doStream();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const schemaStr = JSON.stringify(\n Schema.encodedSchema(request.outputSchema),\n null,\n 2,\n );\n\n const messagesWithFormat: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ];\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messagesWithFormat\n : [\n ...messagesWithFormat,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response was not valid JSON. The parse error was: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ];\n\n const model =\n typeof request.model === \"string\"\n ? request.model\n : request.model?.model ?? defaultModel;\n\n const completeResult = yield* Effect.tryPromise({\n try: () =>\n liteLLMFetch(\n baseURL,\n \"/chat/completions\",\n {\n model,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature:\n request.temperature ?? config.defaultTemperature,\n messages: toLiteLLMMessages(msgs),\n },\n apiKey,\n ),\n catch: (error) => toEffectError(error),\n });\n\n const response = mapLiteLLMResponse(\n completeResult as LiteLLMRawResponse,\n model,\n );\n\n try {\n const parsed = JSON.parse(response.content);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const embeddingModel =\n model ?? config.embeddingConfig.model;\n const batchSize = config.embeddingConfig.batchSize ?? 100;\n const results: number[][] = [];\n\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize);\n const response = (await liteLLMFetch(\n baseURL,\n \"/embeddings\",\n {\n model: embeddingModel,\n input: [...batch],\n dimensions: config.embeddingConfig.dimensions,\n },\n apiKey,\n )) as { data: Array<{ embedding: number[] }> };\n\n results.push(\n ...response.data.map((d) => d.embedding),\n );\n }\n\n return results;\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"litellm\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"litellm\" as const,\n model: defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: false,\n jsonSchemaEnforcement: false,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n });\n }),\n);\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"./llm-service.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n} from \"./types.js\";\nimport type { LLMErrors } from \"./errors.js\";\n\n/**\n * Create a deterministic test LLM service.\n * Returns responses based on pattern matching against prompt content.\n *\n * Usage:\n * ```ts\n * const layer = TestLLMServiceLayer({\n * \"capital of France\": \"Paris\",\n * \"plan\": '{\"goal\":\"test\",\"steps\":[]}',\n * });\n * ```\n */\nexport const TestLLMService = (\n responses: Record<string, string>,\n): typeof LLMService.Service => ({\n complete: (request) =>\n Effect.gen(function* () {\n const lastMessage = request.messages[request.messages.length - 1];\n const content =\n lastMessage && typeof lastMessage.content === \"string\"\n ? lastMessage.content\n : \"\";\n\n // Also check systemPrompt for pattern matching\n const systemPrompt =\n typeof (request as any).systemPrompt === \"string\"\n ? (request as any).systemPrompt\n : \"\";\n const searchText = `${content} ${systemPrompt}`;\n\n // Match against registered patterns\n for (const [pattern, response] of Object.entries(responses)) {\n if (pattern.length > 0 && searchText.includes(pattern)) {\n return {\n content: response,\n stopReason: \"end_turn\" as const,\n usage: {\n inputTokens: Math.ceil(content.length / 4),\n outputTokens: Math.ceil(response.length / 4),\n totalTokens:\n Math.ceil(content.length / 4) +\n Math.ceil(response.length / 4),\n estimatedCost: 0,\n },\n model: \"test-model\",\n } satisfies CompletionResponse;\n }\n }\n\n // Default response\n return {\n content: \"Test response\",\n stopReason: \"end_turn\" as const,\n usage: {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n estimatedCost: 0,\n },\n model: \"test-model\",\n } satisfies CompletionResponse;\n }),\n\n stream: (request) => {\n const lastMessage = request.messages[request.messages.length - 1];\n const content =\n lastMessage && typeof lastMessage.content === \"string\"\n ? lastMessage.content\n : \"\";\n\n // Also check systemPrompt for pattern matching (mirrors complete() logic)\n const systemPrompt =\n typeof (request as any).systemPrompt === \"string\"\n ? (request as any).systemPrompt\n : \"\";\n const searchText = `${content} ${systemPrompt}`;\n\n // Match against registered patterns\n let matchedResponse = \"Test response\";\n for (const [pattern, response] of Object.entries(responses)) {\n if (pattern.length > 0 && searchText.includes(pattern)) {\n matchedResponse = response;\n break;\n }\n }\n\n const inputTokens = Math.ceil(content.length / 4);\n const outputTokens = Math.ceil(matchedResponse.length / 4);\n\n return Effect.succeed(\n Stream.make(\n {\n type: \"text_delta\" as const,\n text: matchedResponse,\n } satisfies StreamEvent,\n {\n type: \"content_complete\" as const,\n content: matchedResponse,\n } satisfies StreamEvent,\n {\n type: \"usage\" as const,\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: 0,\n },\n } satisfies StreamEvent,\n ) as Stream.Stream<StreamEvent, LLMErrors>,\n );\n },\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const lastMessage = request.messages[request.messages.length - 1];\n const content =\n lastMessage && typeof lastMessage.content === \"string\"\n ? lastMessage.content\n : \"\";\n\n // Try to find a matching response\n let responseContent = \"Test response\";\n for (const [pattern, response] of Object.entries(responses)) {\n if (content.includes(pattern)) {\n responseContent = response;\n break;\n }\n }\n\n const parsed = JSON.parse(responseContent);\n return Schema.decodeUnknownSync(request.outputSchema)(parsed);\n }),\n\n embed: (texts) =>\n Effect.succeed(\n texts.map(() => new Array(768).fill(0).map(() => Math.random())),\n ),\n\n countTokens: (messages) =>\n Effect.succeed(\n messages.reduce(\n (sum, m) =>\n sum +\n (typeof m.content === \"string\"\n ? Math.ceil(m.content.length / 4)\n : 100),\n 0,\n ),\n ),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"anthropic\" as const,\n model: \"test-model\",\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: false,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n});\n\n/**\n * Create a test Layer for LLMService with optional pattern-matched responses.\n */\nexport const TestLLMServiceLayer = (\n responses: Record<string, string> = {},\n) => Layer.succeed(LLMService, LLMService.of(TestLLMService(responses)));\n","import { Schema } from \"effect\";\n\n// ─── Common Schemas for Reasoning Strategies ───\n\n/**\n * Schema for ReAct action parsing.\n */\nexport const ReActActionSchema = Schema.Struct({\n thought: Schema.String,\n action: Schema.optional(\n Schema.Struct({\n tool: Schema.String,\n input: Schema.Unknown,\n }),\n ),\n finalAnswer: Schema.optional(Schema.String),\n isComplete: Schema.Boolean,\n});\n\nexport type ReActAction = Schema.Schema.Type<typeof ReActActionSchema>;\n\n/**\n * Schema for plan generation.\n */\nexport const PlanSchema = Schema.Struct({\n goal: Schema.String,\n steps: Schema.Array(\n Schema.Struct({\n id: Schema.Number,\n description: Schema.String,\n tool: Schema.optional(Schema.String),\n dependsOn: Schema.optional(Schema.Array(Schema.Number)),\n estimatedDuration: Schema.optional(Schema.String),\n }),\n ),\n});\n\nexport type Plan = Schema.Schema.Type<typeof PlanSchema>;\n\n/**\n * Schema for reflection output.\n */\nexport const ReflectionSchema = Schema.Struct({\n taskAccomplished: Schema.Boolean,\n confidence: Schema.Number,\n strengths: Schema.Array(Schema.String),\n weaknesses: Schema.Array(Schema.String),\n needsRefinement: Schema.Boolean,\n refinementSuggestions: Schema.optional(Schema.Array(Schema.String)),\n});\n\nexport type Reflection = Schema.Schema.Type<typeof ReflectionSchema>;\n\n/**\n * Schema for strategy selection.\n */\nexport const StrategySelectionSchema = Schema.Struct({\n selectedStrategy: Schema.String,\n reasoning: Schema.String,\n confidence: Schema.Number,\n alternativeStrategies: Schema.Array(\n Schema.Struct({\n strategy: Schema.String,\n whyNot: Schema.String,\n }),\n ),\n});\n\nexport type StrategySelection = Schema.Schema.Type<\n typeof StrategySelectionSchema\n>;\n\n/**\n * Schema for thought evaluation (Tree-of-Thought).\n */\nexport const ThoughtEvaluationSchema = Schema.Struct({\n score: Schema.Number,\n reasoning: Schema.String,\n strengths: Schema.Array(Schema.String),\n weaknesses: Schema.Array(Schema.String),\n shouldExpand: Schema.Boolean,\n});\n\nexport type ThoughtEvaluation = Schema.Schema.Type<\n typeof ThoughtEvaluationSchema\n>;\n\n/**\n * Schema for task complexity analysis.\n */\nexport const ComplexityAnalysisSchema = Schema.Struct({\n score: Schema.Number,\n factors: Schema.Array(\n Schema.Struct({\n factor: Schema.String,\n weight: Schema.Number,\n reasoning: Schema.String,\n }),\n ),\n recommendedStrategy: Schema.String,\n recommendedModel: Schema.String,\n});\n\nexport type ComplexityAnalysis = Schema.Schema.Type<\n typeof ComplexityAnalysisSchema\n>;\n","import { Layer } from \"effect\";\nimport { LLMConfig, LLMConfigFromEnv, llmConfigFromEnv } from \"./llm-config.js\";\nimport { AnthropicProviderLive } from \"./providers/anthropic.js\";\nimport { OpenAIProviderLive } from \"./providers/openai.js\";\nimport { LocalProviderLive } from \"./providers/local.js\";\nimport { GeminiProviderLive } from \"./providers/gemini.js\";\nimport { LiteLLMProviderLive } from \"./providers/litellm.js\";\nimport { PromptManagerLive } from \"./prompt-manager.js\";\nimport { TestLLMServiceLayer } from \"./testing.js\";\n\n/**\n * Create the LLM provider layer for a specific provider.\n * Uses env vars for configuration by default.\n */\nexport const createLLMProviderLayer = (\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"gemini\" | \"litellm\" | \"test\" = \"anthropic\",\n testResponses?: Record<string, string>,\n model?: string,\n modelParams?: { thinking?: boolean; temperature?: number; maxTokens?: number },\n) => {\n if (provider === \"test\") {\n return Layer.mergeAll(\n TestLLMServiceLayer(testResponses ?? {}),\n PromptManagerLive,\n );\n }\n\n const configOverrides: Record<string, unknown> = {};\n if (model) configOverrides.defaultModel = model;\n if (modelParams?.thinking !== undefined) configOverrides.thinking = modelParams.thinking;\n if (modelParams?.temperature !== undefined) configOverrides.defaultTemperature = modelParams.temperature;\n if (modelParams?.maxTokens !== undefined) configOverrides.defaultMaxTokens = modelParams.maxTokens;\n\n const configLayer = Object.keys(configOverrides).length > 0\n ? Layer.succeed(LLMConfig, LLMConfig.of({ ...llmConfigFromEnv, ...configOverrides }))\n : LLMConfigFromEnv;\n\n const providerLayer =\n provider === \"anthropic\"\n ? AnthropicProviderLive\n : provider === \"openai\"\n ? OpenAIProviderLive\n : provider === \"gemini\"\n ? GeminiProviderLive\n : provider === \"litellm\"\n ? LiteLLMProviderLive\n : LocalProviderLive;\n\n return Layer.mergeAll(\n providerLayer.pipe(Layer.provide(configLayer)),\n PromptManagerLive,\n );\n};\n\n/**\n * LLM layer with custom config (for programmatic use).\n */\nexport const createLLMProviderLayerWithConfig = (\n config: typeof LLMConfig.Service,\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"gemini\" | \"litellm\" = \"anthropic\",\n) => {\n const configLayer = Layer.succeed(LLMConfig, config);\n\n const providerLayer =\n provider === \"anthropic\"\n ? AnthropicProviderLive\n : provider === \"openai\"\n ? OpenAIProviderLive\n : provider === \"gemini\"\n ? GeminiProviderLive\n : provider === \"litellm\"\n ? LiteLLMProviderLive\n : LocalProviderLive;\n\n return Layer.mergeAll(\n providerLayer.pipe(Layer.provide(configLayer)),\n PromptManagerLive,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,SAAS,WAAW,KAAK;AACvB,SAAO,OAAO,SAAS,UAAU,cAAc,GAAG;AACpD;AAsBA,SAAS,cAAc,MAAM;AAC3B,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO,OAAO,IAAI;AAAA,EACpB;AACA,MAAI,6BAA6B,KAAK,IAAI,KAAK,SAAS,IAAI;AAC1D,UAAM,IAAI,UAAU,8CAA8C,OAAO,GAAG;AAAA,EAC9E;AACA,SAAO,KAAK,YAAY;AAC1B;AAEA,SAAS,eAAe,OAAO;AAC7B,MAAI,OAAO,UAAU,UAAU;AAC7B,YAAQ,OAAO,KAAK;AAAA,EACtB;AACA,SAAO;AACT;AAGA,SAAS,YAAY,OAAO;AAC1B,MAAI,WAAW;AAAA,IACb,MAAM,WAAW;AACf,UAAI,QAAQ,MAAM,MAAM;AACxB,aAAO,EAAC,MAAM,UAAU,QAAW,MAAY;AAAA,IACjD;AAAA,EACF;AAEA,MAAI,QAAQ,UAAU;AACpB,aAAS,OAAO,QAAQ,IAAI,WAAW;AACrC,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAASA,SAAQ,SAAS;AAC/B,OAAK,MAAM,CAAC;AAEZ,MAAI,mBAAmBA,UAAS;AAC9B,YAAQ,QAAQ,SAAS,OAAO,MAAM;AACpC,WAAK,OAAO,MAAM,KAAK;AAAA,IACzB,GAAG,IAAI;AAAA,EACT,WAA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SAAOA,OAAM;AAAA,IACX,cAAc,KAAKA,OAAM,QAAQ,WAAW,CAAC;AAAA,IAC7C;AAAA,EACF;AACF;AAKO,IAAM,mCAAmC,CAC9C,QACA,WAAqE,gBAClE;AACH,QAAM,cAAcA,OAAM,QAAQ,WAAW,MAAM;AAEnD,QAAM,gBACJ,aAAa,cACT,wBACA,aAAa,WACX,qBACA,aAAa,WACX,qBACA,aAAa,YACX,sBACA;AAEZ,SAAOA,OAAM;AAAA,IACX,cAAc,KAAKA,OAAM,QAAQ,WAAW,CAAC;AAAA,IAC7C;AAAA,EACF;AACF;","names":["Headers","resolve","fetch","__defProp","fetch","Ollama","Context","Effect","Context","Layer","Effect","Context","Layer","Effect","Effect","Layer","Schema","Layer","Effect","Schema","Effect","Layer","Stream","Schema","toEffectError","Layer","Effect","Stream","Schema","Effect","Layer","Stream","Schema","Layer","Effect","Ollama","Stream","Schema","Effect","Layer","Stream","Schema","toEffectError","Layer","Effect","Stream","Schema","Effect","Layer","Stream","Schema","toEffectError","Layer","Effect","Stream","Schema","Effect","Layer","Stream","Schema","Effect","Stream","Schema","Layer","Schema","Layer","Layer"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/whatwg-fetch/fetch.js","../../../node_modules/ollama/dist/browser.mjs","../../../node_modules/ollama/dist/index.mjs","../src/types.ts","../src/errors.ts","../src/llm-service.ts","../src/llm-config.ts","../src/prompt-manager.ts","../src/token-counter.ts","../src/providers/anthropic.ts","../src/retry.ts","../src/providers/openai.ts","../src/providers/local.ts","../src/provider-defaults.ts","../src/providers/gemini.ts","../src/providers/litellm.ts","../src/testing.ts","../src/structured-output.ts","../src/runtime.ts","../src/embedding-cache.ts","../src/circuit-breaker.ts"],"sourcesContent":["/* eslint-disable no-prototype-builtins */\nvar g =\n (typeof globalThis !== 'undefined' && globalThis) ||\n (typeof self !== 'undefined' && self) ||\n // eslint-disable-next-line no-undef\n (typeof global !== 'undefined' && global) ||\n {}\n\nvar support = {\n searchParams: 'URLSearchParams' in g,\n iterable: 'Symbol' in g && 'iterator' in Symbol,\n blob:\n 'FileReader' in g &&\n 'Blob' in g &&\n (function() {\n try {\n new Blob()\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in g,\n arrayBuffer: 'ArrayBuffer' in g\n}\n\nfunction isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n}\n\nif (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n}\n\nfunction normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {\n throw new TypeError('Invalid character in header field name: \"' + name + '\"')\n }\n return name.toLowerCase()\n}\n\nfunction normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n}\n\n// Build a destructive iterator for the value list\nfunction iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n}\n\nexport function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n if (header.length != 2) {\n throw new TypeError('Headers constructor: expected name/value pair to be length 2, found' + header.length)\n }\n this.append(header[0], header[1])\n }, this)\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n}\n\nHeaders.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue + ', ' + value : value\n}\n\nHeaders.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n}\n\nHeaders.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n}\n\nHeaders.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n}\n\nHeaders.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n}\n\nHeaders.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n}\n\nHeaders.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push(name)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.values = function() {\n var items = []\n this.forEach(function(value) {\n items.push(value)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push([name, value])\n })\n return iteratorFor(items)\n}\n\nif (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n}\n\nfunction consumed(body) {\n if (body._noBody) return\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n}\n\nfunction fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n}\n\nfunction readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n}\n\nfunction readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type)\n var encoding = match ? match[1] : 'utf-8'\n reader.readAsText(blob, encoding)\n return promise\n}\n\nfunction readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n}\n\nfunction bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n}\n\nfunction Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n /*\n fetch-mock wraps the Response object in an ES6 Proxy to\n provide useful test harness features such as flush. However, on\n ES5 browsers without fetch or Proxy support pollyfills must be used;\n the proxy-pollyfill is unable to proxy an attribute unless it exists\n on the object before the Proxy is created. This change ensures\n Response.bodyUsed exists on the instance, while maintaining the\n semantic of setting Request.bodyUsed in the constructor before\n _initBody is called.\n */\n // eslint-disable-next-line no-self-assign\n this.bodyUsed = this.bodyUsed\n this._bodyInit = body\n if (!body) {\n this._noBody = true;\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n this._bodyText = body = Object.prototype.toString.call(body)\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n var isConsumed = consumed(this)\n if (isConsumed) {\n return isConsumed\n } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {\n return Promise.resolve(\n this._bodyArrayBuffer.buffer.slice(\n this._bodyArrayBuffer.byteOffset,\n this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength\n )\n )\n } else {\n return Promise.resolve(this._bodyArrayBuffer)\n }\n } else if (support.blob) {\n return this.blob().then(readBlobAsArrayBuffer)\n } else {\n throw new Error('could not read as ArrayBuffer')\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n}\n\n// HTTP methods whose capitalization should be normalized\nvar methods = ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE']\n\nfunction normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return methods.indexOf(upcased) > -1 ? upcased : method\n}\n\nexport function Request(input, options) {\n if (!(this instanceof Request)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n\n options = options || {}\n var body = options.body\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n this.signal = input.signal\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n } else {\n this.url = String(input)\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.signal = options.signal || this.signal || (function () {\n if ('AbortController' in g) {\n var ctrl = new AbortController();\n return ctrl.signal;\n }\n }());\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n\n if (this.method === 'GET' || this.method === 'HEAD') {\n if (options.cache === 'no-store' || options.cache === 'no-cache') {\n // Search for a '_' parameter in the query string\n var reParamSearch = /([?&])_=[^&]*/\n if (reParamSearch.test(this.url)) {\n // If it already exists then set the value with the current time\n this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime())\n } else {\n // Otherwise add a new '_' parameter to the end with the current time\n var reQueryString = /\\?/\n this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime()\n }\n }\n }\n}\n\nRequest.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n}\n\nfunction decode(body) {\n var form = new FormData()\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n}\n\nfunction parseHeaders(rawHeaders) {\n var headers = new Headers()\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ')\n // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill\n // https://github.com/github/fetch/issues/748\n // https://github.com/zloirock/core-js/issues/751\n preProcessedHeaders\n .split('\\r')\n .map(function(header) {\n return header.indexOf('\\n') === 0 ? header.substr(1, header.length) : header\n })\n .forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n try {\n headers.append(key, value)\n } catch (error) {\n console.warn('Response ' + error.message)\n }\n }\n })\n return headers\n}\n\nBody.call(Request.prototype)\n\nexport function Response(bodyInit, options) {\n if (!(this instanceof Response)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = options.status === undefined ? 200 : options.status\n if (this.status < 200 || this.status > 599) {\n throw new RangeError(\"Failed to construct 'Response': The status provided (0) is outside the range [200, 599].\")\n }\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = options.statusText === undefined ? '' : '' + options.statusText\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n}\n\nBody.call(Response.prototype)\n\nResponse.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n}\n\nResponse.error = function() {\n var response = new Response(null, {status: 200, statusText: ''})\n response.ok = false\n response.status = 0\n response.type = 'error'\n return response\n}\n\nvar redirectStatuses = [301, 302, 303, 307, 308]\n\nResponse.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n}\n\nexport var DOMException = g.DOMException\ntry {\n new DOMException()\n} catch (err) {\n DOMException = function(message, name) {\n this.message = message\n this.name = name\n var error = Error(message)\n this.stack = error.stack\n }\n DOMException.prototype = Object.create(Error.prototype)\n DOMException.prototype.constructor = DOMException\n}\n\nexport function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n\n if (request.signal && request.signal.aborted) {\n return reject(new DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest()\n\n function abortXhr() {\n xhr.abort()\n }\n\n xhr.onload = function() {\n var options = {\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n // This check if specifically for when a user fetches a file locally from the file system\n // Only if the status is out of a normal range\n if (request.url.indexOf('file://') === 0 && (xhr.status < 200 || xhr.status > 599)) {\n options.status = 200;\n } else {\n options.status = xhr.status;\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n setTimeout(function() {\n resolve(new Response(body, options))\n }, 0)\n }\n\n xhr.onerror = function() {\n setTimeout(function() {\n reject(new TypeError('Network request failed'))\n }, 0)\n }\n\n xhr.ontimeout = function() {\n setTimeout(function() {\n reject(new TypeError('Network request timed out'))\n }, 0)\n }\n\n xhr.onabort = function() {\n setTimeout(function() {\n reject(new DOMException('Aborted', 'AbortError'))\n }, 0)\n }\n\n function fixUrl(url) {\n try {\n return url === '' && g.location.href ? g.location.href : url\n } catch (e) {\n return url\n }\n }\n\n xhr.open(request.method, fixUrl(request.url), true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false\n }\n\n if ('responseType' in xhr) {\n if (support.blob) {\n xhr.responseType = 'blob'\n } else if (\n support.arrayBuffer\n ) {\n xhr.responseType = 'arraybuffer'\n }\n }\n\n if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers || (g.Headers && init.headers instanceof g.Headers))) {\n var names = [];\n Object.getOwnPropertyNames(init.headers).forEach(function(name) {\n names.push(normalizeName(name))\n xhr.setRequestHeader(name, normalizeValue(init.headers[name]))\n })\n request.headers.forEach(function(value, name) {\n if (names.indexOf(name) === -1) {\n xhr.setRequestHeader(name, value)\n }\n })\n } else {\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n }\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr)\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr)\n }\n }\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n}\n\nfetch.polyfill = true\n\nif (!g.fetch) {\n g.fetch = fetch\n g.Headers = Headers\n g.Request = Request\n g.Response = Response\n}\n","import 'whatwg-fetch';\n\nconst defaultPort = \"11434\";\nconst defaultHost = `http://127.0.0.1:${defaultPort}`;\n\nconst version = \"0.6.3\";\n\nvar __defProp$1 = Object.defineProperty;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$1 = (obj, key, value) => {\n __defNormalProp$1(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass ResponseError extends Error {\n constructor(error, status_code) {\n super(error);\n this.error = error;\n this.status_code = status_code;\n this.name = \"ResponseError\";\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ResponseError);\n }\n }\n}\nclass AbortableAsyncIterator {\n constructor(abortController, itr, doneCallback) {\n __publicField$1(this, \"abortController\");\n __publicField$1(this, \"itr\");\n __publicField$1(this, \"doneCallback\");\n this.abortController = abortController;\n this.itr = itr;\n this.doneCallback = doneCallback;\n }\n abort() {\n this.abortController.abort();\n }\n async *[Symbol.asyncIterator]() {\n for await (const message of this.itr) {\n if (\"error\" in message) {\n throw new Error(message.error);\n }\n yield message;\n if (message.done || message.status === \"success\") {\n this.doneCallback();\n return;\n }\n }\n throw new Error(\"Did not receive done or success response in stream.\");\n }\n}\nconst checkOk = async (response) => {\n if (response.ok) {\n return;\n }\n let message = `Error ${response.status}: ${response.statusText}`;\n let errorData = null;\n if (response.headers.get(\"content-type\")?.includes(\"application/json\")) {\n try {\n errorData = await response.json();\n message = errorData.error || message;\n } catch (error) {\n console.log(\"Failed to parse error response as JSON\");\n }\n } else {\n try {\n console.log(\"Getting text from response\");\n const textResponse = await response.text();\n message = textResponse || message;\n } catch (error) {\n console.log(\"Failed to get text from error response\");\n }\n }\n throw new ResponseError(message, response.status);\n};\nfunction getPlatform() {\n if (typeof window !== \"undefined\" && window.navigator) {\n const nav = navigator;\n if (\"userAgentData\" in nav && nav.userAgentData?.platform) {\n return `${nav.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`;\n }\n if (navigator.platform) {\n return `${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`;\n }\n return `unknown Browser/${navigator.userAgent};`;\n } else if (typeof process !== \"undefined\") {\n return `${process.arch} ${process.platform} Node.js/${process.version}`;\n }\n return \"\";\n}\nfunction normalizeHeaders(headers) {\n if (headers instanceof Headers) {\n const obj = {};\n headers.forEach((value, key) => {\n obj[key] = value;\n });\n return obj;\n } else if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n } else {\n return headers || {};\n }\n}\nconst readEnvVar = (obj, key) => {\n return obj[key];\n};\nconst fetchWithHeaders = async (fetch, url, options = {}) => {\n const defaultHeaders = {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"User-Agent\": `ollama-js/${version} (${getPlatform()})`\n };\n options.headers = normalizeHeaders(options.headers);\n try {\n const parsed = new URL(url);\n if (parsed.protocol === \"https:\" && parsed.hostname === \"ollama.com\") {\n const apiKey = typeof process === \"object\" && process !== null && typeof process.env === \"object\" && process.env !== null ? readEnvVar(process.env, \"OLLAMA_API_KEY\") : void 0;\n const authorization = options.headers[\"authorization\"] || options.headers[\"Authorization\"];\n if (!authorization && apiKey) {\n options.headers[\"Authorization\"] = `Bearer ${apiKey}`;\n }\n }\n } catch (error) {\n console.error(\"error parsing url\", error);\n }\n const customHeaders = Object.fromEntries(\n Object.entries(options.headers).filter(\n ([key]) => !Object.keys(defaultHeaders).some(\n (defaultKey) => defaultKey.toLowerCase() === key.toLowerCase()\n )\n )\n );\n options.headers = {\n ...defaultHeaders,\n ...customHeaders\n };\n return fetch(url, options);\n};\nconst get = async (fetch, host, options) => {\n const response = await fetchWithHeaders(fetch, host, {\n headers: options?.headers\n });\n await checkOk(response);\n return response;\n};\nconst post = async (fetch, host, data, options) => {\n const isRecord = (input) => {\n return input !== null && typeof input === \"object\" && !Array.isArray(input);\n };\n const formattedData = isRecord(data) ? JSON.stringify(data) : data;\n const response = await fetchWithHeaders(fetch, host, {\n method: \"POST\",\n body: formattedData,\n signal: options?.signal,\n headers: options?.headers\n });\n await checkOk(response);\n return response;\n};\nconst del = async (fetch, host, data, options) => {\n const response = await fetchWithHeaders(fetch, host, {\n method: \"DELETE\",\n body: JSON.stringify(data),\n headers: options?.headers\n });\n await checkOk(response);\n return response;\n};\nconst parseJSON = async function* (itr) {\n const decoder = new TextDecoder(\"utf-8\");\n let buffer = \"\";\n const reader = itr.getReader();\n while (true) {\n const { done, value: chunk } = await reader.read();\n if (done) {\n break;\n }\n buffer += decoder.decode(chunk, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n for (const part of parts) {\n try {\n yield JSON.parse(part);\n } catch (error) {\n console.warn(\"invalid json: \", part);\n }\n }\n }\n buffer += decoder.decode();\n for (const part of buffer.split(\"\\n\").filter((p) => p !== \"\")) {\n try {\n yield JSON.parse(part);\n } catch (error) {\n console.warn(\"invalid json: \", part);\n }\n }\n};\nconst formatHost = (host) => {\n if (!host) {\n return defaultHost;\n }\n let isExplicitProtocol = host.includes(\"://\");\n if (host.startsWith(\":\")) {\n host = `http://127.0.0.1${host}`;\n isExplicitProtocol = true;\n }\n if (!isExplicitProtocol) {\n host = `http://${host}`;\n }\n const url = new URL(host);\n let port = url.port;\n if (!port) {\n if (!isExplicitProtocol) {\n port = defaultPort;\n } else {\n port = url.protocol === \"https:\" ? \"443\" : \"80\";\n }\n }\n let auth = \"\";\n if (url.username) {\n auth = url.username;\n if (url.password) {\n auth += `:${url.password}`;\n }\n auth += \"@\";\n }\n let formattedHost = `${url.protocol}//${auth}${url.hostname}:${port}${url.pathname}`;\n if (formattedHost.endsWith(\"/\")) {\n formattedHost = formattedHost.slice(0, -1);\n }\n return formattedHost;\n};\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nlet Ollama$1 = class Ollama {\n constructor(config) {\n __publicField(this, \"config\");\n __publicField(this, \"fetch\");\n __publicField(this, \"ongoingStreamedRequests\", []);\n this.config = {\n host: \"\",\n headers: config?.headers\n };\n if (!config?.proxy) {\n this.config.host = formatHost(config?.host ?? defaultHost);\n }\n this.fetch = config?.fetch ?? fetch;\n }\n // Abort any ongoing streamed requests to Ollama\n abort() {\n for (const request of this.ongoingStreamedRequests) {\n request.abort();\n }\n this.ongoingStreamedRequests.length = 0;\n }\n /**\n * Processes a request to the Ollama server. If the request is streamable, it will return a\n * AbortableAsyncIterator that yields the response messages. Otherwise, it will return the response\n * object.\n * @param endpoint {string} - The endpoint to send the request to.\n * @param request {object} - The request object to send to the endpoint.\n * @protected {T | AbortableAsyncIterator<T>} - The response object or a AbortableAsyncIterator that yields\n * response messages.\n * @throws {Error} - If the response body is missing or if the response is an error.\n * @returns {Promise<T | AbortableAsyncIterator<T>>} - The response object or a AbortableAsyncIterator that yields the streamed response.\n */\n async processStreamableRequest(endpoint, request) {\n request.stream = request.stream ?? false;\n const host = `${this.config.host}/api/${endpoint}`;\n if (request.stream) {\n const abortController = new AbortController();\n const response2 = await post(this.fetch, host, request, {\n signal: abortController.signal,\n headers: this.config.headers\n });\n if (!response2.body) {\n throw new Error(\"Missing body\");\n }\n const itr = parseJSON(response2.body);\n const abortableAsyncIterator = new AbortableAsyncIterator(\n abortController,\n itr,\n () => {\n const i = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator);\n if (i > -1) {\n this.ongoingStreamedRequests.splice(i, 1);\n }\n }\n );\n this.ongoingStreamedRequests.push(abortableAsyncIterator);\n return abortableAsyncIterator;\n }\n const response = await post(this.fetch, host, request, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Encodes an image to base64 if it is a Uint8Array.\n * @param image {Uint8Array | string} - The image to encode.\n * @returns {Promise<string>} - The base64 encoded image.\n */\n async encodeImage(image) {\n if (typeof image !== \"string\") {\n const uint8Array = new Uint8Array(image);\n let byteString = \"\";\n const len = uint8Array.byteLength;\n for (let i = 0; i < len; i++) {\n byteString += String.fromCharCode(uint8Array[i]);\n }\n return btoa(byteString);\n }\n return image;\n }\n /**\n * Generates a response from a text prompt.\n * @param request {GenerateRequest} - The request object.\n * @returns {Promise<GenerateResponse | AbortableAsyncIterator<GenerateResponse>>} - The response object or\n * an AbortableAsyncIterator that yields response messages.\n */\n async generate(request) {\n if (request.images) {\n request.images = await Promise.all(request.images.map(this.encodeImage.bind(this)));\n }\n return this.processStreamableRequest(\"generate\", request);\n }\n /**\n * Chats with the model. The request object can contain messages with images that are either\n * Uint8Arrays or base64 encoded strings. The images will be base64 encoded before sending the\n * request.\n * @param request {ChatRequest} - The request object.\n * @returns {Promise<ChatResponse | AbortableAsyncIterator<ChatResponse>>} - The response object or an\n * AbortableAsyncIterator that yields response messages.\n */\n async chat(request) {\n if (request.messages) {\n for (const message of request.messages) {\n if (message.images) {\n message.images = await Promise.all(\n message.images.map(this.encodeImage.bind(this))\n );\n }\n }\n }\n return this.processStreamableRequest(\"chat\", request);\n }\n /**\n * Creates a new model from a stream of data.\n * @param request {CreateRequest} - The request object.\n * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or a stream of progress responses.\n */\n async create(request) {\n return this.processStreamableRequest(\"create\", {\n ...request\n });\n }\n /**\n * Pulls a model from the Ollama registry. The request object can contain a stream flag to indicate if the\n * response should be streamed.\n * @param request {PullRequest} - The request object.\n * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or\n * an AbortableAsyncIterator that yields response messages.\n */\n async pull(request) {\n return this.processStreamableRequest(\"pull\", {\n name: request.model,\n stream: request.stream,\n insecure: request.insecure\n });\n }\n /**\n * Pushes a model to the Ollama registry. The request object can contain a stream flag to indicate if the\n * response should be streamed.\n * @param request {PushRequest} - The request object.\n * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or\n * an AbortableAsyncIterator that yields response messages.\n */\n async push(request) {\n return this.processStreamableRequest(\"push\", {\n name: request.model,\n stream: request.stream,\n insecure: request.insecure\n });\n }\n /**\n * Deletes a model from the server. The request object should contain the name of the model to\n * delete.\n * @param request {DeleteRequest} - The request object.\n * @returns {Promise<StatusResponse>} - The response object.\n */\n async delete(request) {\n await del(\n this.fetch,\n `${this.config.host}/api/delete`,\n { name: request.model },\n { headers: this.config.headers }\n );\n return { status: \"success\" };\n }\n /**\n * Copies a model from one name to another. The request object should contain the name of the\n * model to copy and the new name.\n * @param request {CopyRequest} - The request object.\n * @returns {Promise<StatusResponse>} - The response object.\n */\n async copy(request) {\n await post(this.fetch, `${this.config.host}/api/copy`, { ...request }, {\n headers: this.config.headers\n });\n return { status: \"success\" };\n }\n /**\n * Lists the models on the server.\n * @returns {Promise<ListResponse>} - The response object.\n * @throws {Error} - If the response body is missing.\n */\n async list() {\n const response = await get(this.fetch, `${this.config.host}/api/tags`, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Shows the metadata of a model. The request object should contain the name of the model.\n * @param request {ShowRequest} - The request object.\n * @returns {Promise<ShowResponse>} - The response object.\n */\n async show(request) {\n const response = await post(this.fetch, `${this.config.host}/api/show`, {\n ...request\n }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Embeds text input into vectors.\n * @param request {EmbedRequest} - The request object.\n * @returns {Promise<EmbedResponse>} - The response object.\n */\n async embed(request) {\n const response = await post(this.fetch, `${this.config.host}/api/embed`, {\n ...request\n }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Embeds a text prompt into a vector.\n * @param request {EmbeddingsRequest} - The request object.\n * @returns {Promise<EmbeddingsResponse>} - The response object.\n */\n async embeddings(request) {\n const response = await post(this.fetch, `${this.config.host}/api/embeddings`, {\n ...request\n }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Lists the running models on the server\n * @returns {Promise<ListResponse>} - The response object.\n * @throws {Error} - If the response body is missing.\n */\n async ps() {\n const response = await get(this.fetch, `${this.config.host}/api/ps`, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Returns the Ollama server version.\n * @returns {Promise<VersionResponse>} - The server version object.\n */\n async version() {\n const response = await get(this.fetch, `${this.config.host}/api/version`, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Performs web search using the Ollama web search API\n * @param request {WebSearchRequest} - The search request containing query and options\n * @returns {Promise<WebSearchResponse>} - The search results\n * @throws {Error} - If the request is invalid or the server returns an error\n */\n async webSearch(request) {\n if (!request.query || request.query.length === 0) {\n throw new Error(\"Query is required\");\n }\n const response = await post(this.fetch, `https://ollama.com/api/web_search`, { ...request }, {\n headers: this.config.headers\n });\n return await response.json();\n }\n /**\n * Fetches a single page using the Ollama web fetch API\n * @param request {WebFetchRequest} - The fetch request containing a URL\n * @returns {Promise<WebFetchResponse>} - The fetch result\n * @throws {Error} - If the request is invalid or the server returns an error\n */\n async webFetch(request) {\n if (!request.url || request.url.length === 0) {\n throw new Error(\"URL is required\");\n }\n const response = await post(this.fetch, `https://ollama.com/api/web_fetch`, { ...request }, { headers: this.config.headers });\n return await response.json();\n }\n};\nconst browser = new Ollama$1();\n\nexport { Ollama$1 as Ollama, browser as default };\n","import fs, { promises } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Ollama as Ollama$1 } from './browser.mjs';\nimport 'whatwg-fetch';\n\nclass Ollama extends Ollama$1 {\n async encodeImage(image) {\n if (typeof image !== \"string\") {\n return Buffer.from(image).toString(\"base64\");\n }\n try {\n if (fs.existsSync(image)) {\n const fileBuffer = await promises.readFile(resolve(image));\n return Buffer.from(fileBuffer).toString(\"base64\");\n }\n } catch {\n }\n return image;\n }\n /**\n * checks if a file exists\n * @param path {string} - The path to the file\n * @private @internal\n * @returns {Promise<boolean>} - Whether the file exists or not\n */\n async fileExists(path) {\n try {\n await promises.access(path);\n return true;\n } catch {\n return false;\n }\n }\n async create(request) {\n if (request.from && await this.fileExists(resolve(request.from))) {\n throw Error(\"Creating with a local path is not currently supported from ollama-js\");\n }\n if (request.stream) {\n return super.create(request);\n } else {\n return super.create(request);\n }\n }\n}\nconst index = new Ollama();\n\nexport { Ollama, index as default };\n","import { Schema } from \"effect\";\n\n// ─── LLM Provider Type ───\n\n/**\n * Schema for LLM provider selection.\n * Supported providers: anthropic, openai, ollama, gemini, litellm, custom.\n *\n * @example\n * ```typescript\n * const provider: LLMProvider = \"anthropic\";\n * ```\n */\nexport const LLMProviderType = Schema.Literal(\n /** Claude models via Anthropic API. Requires ANTHROPIC_API_KEY. */\n \"anthropic\",\n /** GPT models via OpenAI API. Requires OPENAI_API_KEY. */\n \"openai\",\n /** Local models via Ollama. Requires a running Ollama server. */\n \"ollama\",\n /** Google Gemini models. Requires GOOGLE_API_KEY. */\n \"gemini\",\n /** LiteLLM proxy — unified gateway to 40+ model providers. */\n \"litellm\",\n /** User-defined provider adapter — implement the LLMService interface. */\n \"custom\",\n);\n\n/**\n * Union of supported LLM provider names.\n * - \"anthropic\": Claude models via Anthropic API\n * - \"openai\": GPT models via OpenAI API\n * - \"ollama\": Local models via Ollama\n * - \"gemini\": Google Gemini models\n * - \"litellm\": LiteLLM proxy (40+ model providers)\n * - \"custom\": User-defined provider adapter\n */\nexport type LLMProvider = Schema.Schema.Type<typeof LLMProviderType>;\n\n// ─── Embedding Configuration ───\n\n/**\n * Schema for embedding model configuration.\n * Embeddings are used for semantic caching, memory similarity search, and verification.\n * Anthropic provides no embeddings API; embeddings always route to OpenAI or Ollama.\n *\n * @example\n * ```typescript\n * const config: EmbeddingConfig = {\n * model: \"text-embedding-3-small\",\n * dimensions: 1536,\n * provider: \"openai\",\n * batchSize: 100\n * };\n * ```\n */\nexport const EmbeddingConfigSchema = Schema.Struct({\n /** Embedding model name (e.g., \"text-embedding-3-small\") */\n model: Schema.String,\n /** Output embedding vector dimensionality */\n dimensions: Schema.Number,\n /** Provider hosting the embedding model */\n provider: Schema.Literal(\"openai\", \"ollama\"),\n /** Maximum vectors to embed in a single API call (default: 100) */\n batchSize: Schema.optional(Schema.Number),\n});\n\n/**\n * Embedding configuration type.\n * Specifies the embedding model and provider for semantic operations.\n */\nexport type EmbeddingConfig = Schema.Schema.Type<typeof EmbeddingConfigSchema>;\n\n/**\n * Default embedding configuration.\n * Uses OpenAI's text-embedding-3-small with 1536 dimensions.\n *\n * @default { model: \"text-embedding-3-small\", dimensions: 1536, provider: \"openai\", batchSize: 100 }\n */\nexport const DefaultEmbeddingConfig: EmbeddingConfig = {\n model: \"text-embedding-3-small\",\n dimensions: 1536,\n provider: \"openai\",\n batchSize: 100,\n};\n\n// ─── Model Configuration ───\n\n/**\n * Schema for LLM model configuration options.\n * Includes provider, model name, and optional sampling/output parameters.\n *\n * @example\n * ```typescript\n * const config: ModelConfig = {\n * provider: \"anthropic\",\n * model: \"claude-opus-4-20250514\",\n * maxTokens: 4096,\n * temperature: 0.7\n * };\n * ```\n */\nexport const ModelConfigSchema = Schema.Struct({\n /** LLM provider identifier */\n provider: LLMProviderType,\n /** Model name/identifier for the provider */\n model: Schema.String,\n /** Maximum tokens in response (optional) */\n maxTokens: Schema.optional(Schema.Number),\n /** Sampling temperature 0.0-1.0 (optional) */\n temperature: Schema.optional(Schema.Number),\n /** Top-p (nucleus) sampling probability (optional) */\n topP: Schema.optional(Schema.Number),\n /** Stop sequences to halt generation (optional) */\n stopSequences: Schema.optional(Schema.Array(Schema.String)),\n});\n\n/**\n * LLM model configuration type.\n * Specifies which LLM to use and how to configure its behavior.\n */\nexport type ModelConfig = Schema.Schema.Type<typeof ModelConfigSchema>;\n\n// ─── Model Presets ───\n\n/**\n * Pre-configured model profiles for popular LLMs.\n * Each preset includes cost estimates, context window, and quality tiers.\n * Quality tier: 0.0 (low) to 1.0 (highest).\n * Cost: per 1 million input/output tokens in USD.\n *\n * @example\n * ```typescript\n * const preset = ModelPresets[\"claude-opus\"];\n * // { provider: \"anthropic\", model: \"claude-opus-4-20250514\", costPer1MInput: 15.0, ... }\n * ```\n */\nexport const ModelPresets = {\n /**\n * Claude 3.5 Haiku — fast, cost-effective Anthropic model.\n * Best for low-latency, simple reasoning tasks; not recommended for complex analysis.\n */\n \"claude-haiku\": {\n provider: \"anthropic\" as const,\n model: \"claude-3-5-haiku-20241022\",\n /** Cost per 1 million input tokens in USD */\n costPer1MInput: 1.0,\n /** Cost per 1 million output tokens in USD */\n costPer1MOutput: 5.0,\n /** Maximum context window in tokens */\n maxContext: 200_000,\n /** Quality tier (0.6 = reliable for simple tasks) */\n quality: 0.6,\n },\n /**\n * Claude Sonnet 4 — balanced Anthropic model.\n * Recommended for general-purpose reasoning, tool use, and production agents.\n */\n \"claude-sonnet\": {\n provider: \"anthropic\" as const,\n model: \"claude-sonnet-4-20250514\",\n costPer1MInput: 3.0,\n costPer1MOutput: 15.0,\n maxContext: 200_000,\n /** Quality tier (0.85 = excellent reasoning) */\n quality: 0.85,\n },\n /**\n * Claude Sonnet 4.5 — latest Anthropic model.\n * Superior reasoning over Sonnet 4; recommended for complex multi-step reasoning.\n */\n \"claude-sonnet-4-5\": {\n provider: \"anthropic\" as const,\n model: \"claude-sonnet-4-5-20250929\",\n costPer1MInput: 3.0,\n costPer1MOutput: 15.0,\n maxContext: 200_000,\n /** Quality tier (0.9 = very strong reasoning) */\n quality: 0.9,\n },\n /**\n * Claude Opus 4 — most capable Anthropic model.\n * Best for complex analysis, research, and high-accuracy multi-hop reasoning.\n * Largest context window (1M tokens); highest cost.\n */\n \"claude-opus\": {\n provider: \"anthropic\" as const,\n model: \"claude-opus-4-20250514\",\n costPer1MInput: 15.0,\n costPer1MOutput: 75.0,\n maxContext: 1_000_000,\n /** Quality tier (1.0 = frontier-class reasoning) */\n quality: 1.0,\n },\n /**\n * GPT-4o Mini — fast, low-cost OpenAI model.\n * Good for simple tasks and high-throughput scenarios.\n */\n \"gpt-4o-mini\": {\n provider: \"openai\" as const,\n model: \"gpt-4o-mini\",\n costPer1MInput: 0.15,\n costPer1MOutput: 0.6,\n maxContext: 128_000,\n /** Quality tier (0.55 = capable but less reliable for complex reasoning) */\n quality: 0.55,\n },\n /**\n * GPT-4o — latest OpenAI flagship model.\n * Strong reasoning, multimodal support; recommended for tool use and complex analysis.\n */\n \"gpt-4o\": {\n provider: \"openai\" as const,\n model: \"gpt-4o\",\n costPer1MInput: 2.5,\n costPer1MOutput: 10.0,\n maxContext: 128_000,\n /** Quality tier (0.8 = very good reasoning) */\n quality: 0.8,\n },\n /**\n * Gemini 2.0 Flash — fast Google model.\n * Excellent speed and cost efficiency; large 1M context window.\n */\n \"gemini-2.0-flash\": {\n provider: \"gemini\" as const,\n model: \"gemini-2.0-flash\",\n costPer1MInput: 0.1,\n costPer1MOutput: 0.4,\n maxContext: 1_000_000,\n /** Quality tier (0.75 = good reasoning) */\n quality: 0.75,\n },\n /**\n * Gemini 2.5 Pro Preview — advanced Google model.\n * Superior reasoning to Flash; large context window and competitive pricing.\n */\n \"gemini-2.5-pro\": {\n provider: \"gemini\" as const,\n model: \"gemini-2.5-pro-preview-03-25\",\n costPer1MInput: 1.25,\n costPer1MOutput: 10.0,\n maxContext: 1_000_000,\n /** Quality tier (0.95 = excellent reasoning) */\n quality: 0.95,\n },\n} as const;\n\n/**\n * Union of all model preset names.\n * Use to select a pre-configured model with cost/quality/context metadata.\n *\n * @example\n * ```typescript\n * const presetName: ModelPresetName = \"claude-opus\";\n * const preset = ModelPresets[presetName];\n * ```\n */\nexport type ModelPresetName = keyof typeof ModelPresets;\n\n// ─── Cache Control (Anthropic Prompt Caching) ───\n\n/**\n * Schema for Anthropic prompt caching control.\n * Currently only supports \"ephemeral\" type (cache for this request only).\n * Non-Anthropic providers silently ignore cache_control directives.\n *\n * @example\n * ```typescript\n * const cacheControl: CacheControl = { type: \"ephemeral\" };\n * ```\n */\nexport const CacheControlSchema = Schema.Struct({\n /** Cache type: \"ephemeral\" for request-scoped caching */\n type: Schema.Literal(\"ephemeral\"),\n});\n\n/**\n * Anthropic prompt caching configuration.\n * Wraps text content blocks to enable prompt caching optimization.\n * Reduces costs for repeated context; only supported on Anthropic provider.\n */\nexport type CacheControl = Schema.Schema.Type<typeof CacheControlSchema>;\n\n// ─── Content Blocks ───\n\n/**\n * Schema for image source reference.\n * Supports base64-encoded or URL-referenced images in PNG, JPEG, GIF, or WebP format.\n *\n * @example\n * ```typescript\n * const source: ImageSource = {\n * type: \"base64\",\n * media_type: \"image/png\",\n * data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n * };\n * ```\n */\nexport const ImageSourceSchema = Schema.Struct({\n /** Image source type: \"base64\" for encoded data or \"url\" for HTTP(S) URL */\n type: Schema.Literal(\"base64\", \"url\"),\n /** MIME type of image: PNG, JPEG, GIF, or WebP */\n media_type: Schema.Literal(\n \"image/png\",\n \"image/jpeg\",\n \"image/gif\",\n \"image/webp\",\n ),\n /** Either base64-encoded data or HTTPS URL */\n data: Schema.String,\n});\n\n/**\n * Image source reference type.\n * Either a base64-encoded image or an HTTPS URL to an image resource.\n */\nexport type ImageSource = Schema.Schema.Type<typeof ImageSourceSchema>;\n\n/**\n * Schema for text content blocks.\n * Supports optional Anthropic prompt caching via cache_control.\n *\n * @example\n * ```typescript\n * const textBlock: TextContentBlock = {\n * type: \"text\",\n * text: \"This is a text message\"\n * };\n * ```\n */\nexport const TextContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"text\"),\n /** Text content */\n text: Schema.String,\n /** Optional Anthropic cache control directive */\n cache_control: Schema.optional(CacheControlSchema),\n});\n\n/**\n * Schema for image content blocks.\n *\n * @example\n * ```typescript\n * const imageBlock: ImageContentBlock = {\n * type: \"image\",\n * source: { type: \"url\", media_type: \"image/png\", data: \"https://...\" }\n * };\n * ```\n */\nexport const ImageContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"image\"),\n /** Image source reference */\n source: ImageSourceSchema,\n});\n\n/**\n * Schema for tool use content blocks (model invoking a tool).\n *\n * @example\n * ```typescript\n * const toolBlock: ToolUseContentBlock = {\n * type: \"tool_use\",\n * id: \"toolu_123\",\n * name: \"file-read\",\n * input: { path: \"./output.txt\" }\n * };\n * ```\n */\nexport const ToolUseContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"tool_use\"),\n /** Unique tool call identifier */\n id: Schema.String,\n /** Tool name being invoked */\n name: Schema.String,\n /** Tool parameters (JSON-compatible object) */\n input: Schema.Unknown,\n});\n\n/**\n * Schema for tool result content blocks (system returning tool output).\n *\n * @example\n * ```typescript\n * const resultBlock: ToolResultContentBlock = {\n * type: \"tool_result\",\n * tool_use_id: \"toolu_123\",\n * content: \"File contents...\"\n * };\n * ```\n */\nexport const ToolResultContentBlockSchema = Schema.Struct({\n /** Content type identifier */\n type: Schema.Literal(\"tool_result\"),\n /** ID of tool call this result corresponds to */\n tool_use_id: Schema.String,\n /** Tool result/output content */\n content: Schema.String,\n});\n\n/**\n * Union of all content block types used in LLM messages.\n * Content blocks allow mixing text, images, tool invocations, and tool results.\n *\n * @example\n * ```typescript\n * const blocks: readonly ContentBlock[] = [\n * { type: \"text\", text: \"Analyze this image:\" },\n * { type: \"image\", source: { type: \"url\", media_type: \"image/png\", data: \"https://...\" } }\n * ];\n * ```\n */\nexport type ContentBlock =\n | {\n /** Text content (optionally cached with Anthropic) */\n readonly type: \"text\";\n readonly text: string;\n readonly cache_control?: CacheControl;\n }\n | {\n /** Image content */\n readonly type: \"image\";\n readonly source: ImageSource;\n }\n | {\n /** Model invoking a tool */\n readonly type: \"tool_use\";\n readonly id: string;\n readonly name: string;\n readonly input: unknown;\n }\n | {\n /** System returning tool output */\n readonly type: \"tool_result\";\n readonly tool_use_id: string;\n readonly content: string;\n };\n\n// ─── Cacheable Content Block ───\n\n/**\n * Text content block with cache control enabled.\n * Used when text context should be cached for cost reduction (Anthropic only).\n * Non-Anthropic providers silently ignore the cache_control directive.\n *\n * @example\n * ```typescript\n * const cached: CacheableContentBlock = {\n * type: \"text\",\n * text: \"Expensive context (system prompt, instructions, etc)\",\n * cache_control: { type: \"ephemeral\" }\n * };\n * ```\n */\nexport type CacheableContentBlock = {\n /** Always \"text\" */\n readonly type: \"text\";\n /** Cached text content */\n readonly text: string;\n /** Cache control directive (always ephemeral) */\n readonly cache_control: CacheControl;\n};\n\n/**\n * Wrap plain text in a cacheable content block.\n * Enables Anthropic prompt caching for the given text (no-op for other providers).\n * Useful for repeated context like system prompts, instructions, or reference documents.\n *\n * @param text — The text to cache\n * @returns A content block with ephemeral cache control enabled\n *\n * @example\n * ```typescript\n * const cached = makeCacheable(\"You are a helpful assistant...\");\n * // Returns: { type: \"text\", text: \"...\", cache_control: { type: \"ephemeral\" } }\n * ```\n */\nexport const makeCacheable = (text: string): CacheableContentBlock => ({\n type: \"text\",\n text,\n cache_control: { type: \"ephemeral\" },\n});\n\n// ─── Message Types ───\n\n/**\n * Union of LLM message roles.\n * Each message has a role (system, user, assistant, tool) and content.\n *\n * - **system**: Instructions/context set by the agent developer. Content is always a string.\n * - **user**: User query or context provided by caller. Content is string or content blocks.\n * - **assistant**: Model response or thoughts. Content is string or content blocks (including tool_use).\n * - **tool**: Tool execution result returned to model. Content is always string.\n *\n * @example\n * ```typescript\n * const messages: readonly LLMMessage[] = [\n * { role: \"system\", content: \"You are a helpful assistant.\" },\n * { role: \"user\", content: \"What is 2+2?\" },\n * { role: \"assistant\", content: \"2+2 equals 4.\" }\n * ];\n *\n * const withTools: readonly LLMMessage[] = [\n * { role: \"user\", content: \"Read the file.\" },\n * {\n * role: \"assistant\",\n * content: [\n * { type: \"text\", text: \"I'll read that file for you.\" },\n * { type: \"tool_use\", id: \"toolu_1\", name: \"file-read\", input: { path: \"./data.txt\" } }\n * ]\n * },\n * { role: \"tool\", toolCallId: \"toolu_1\", content: \"File contents here...\" }\n * ];\n * ```\n */\nexport type LLMMessage =\n | {\n /** System prompt/instructions — context set by developer */\n readonly role: \"system\";\n /** Plain text string only (no content blocks) */\n readonly content: string;\n }\n | {\n /** User input/query */\n readonly role: \"user\";\n /** Plain text or multimodal content blocks */\n readonly content: string | readonly ContentBlock[];\n }\n | {\n /** Model response or reasoning */\n readonly role: \"assistant\";\n /** Plain text or multimodal content blocks (including tool_use) */\n readonly content: string | readonly ContentBlock[];\n }\n | {\n /** Tool execution result */\n readonly role: \"tool\";\n /** Tool call ID this result corresponds to */\n readonly toolCallId: string;\n /** Plain text result/output */\n readonly content: string;\n };\n\n// ─── Token Usage ───\n\n/**\n * Schema for token usage statistics from an LLM response.\n * Used for cost tracking, budget enforcement, and observability.\n *\n * @example\n * ```typescript\n * const usage: TokenUsage = {\n * inputTokens: 1200,\n * outputTokens: 450,\n * totalTokens: 1650,\n * estimatedCost: 0.0045\n * };\n * ```\n */\nexport const TokenUsageSchema = Schema.Struct({\n /** Tokens consumed by the input (messages + system prompt) */\n inputTokens: Schema.Number,\n /** Tokens generated in the response */\n outputTokens: Schema.Number,\n /** Sum of input and output tokens */\n totalTokens: Schema.Number,\n /** Estimated cost in USD based on provider pricing */\n estimatedCost: Schema.Number,\n});\n\n/**\n * Token usage from an LLM response.\n * Tracks input/output tokens separately for cost calculation.\n */\nexport type TokenUsage = Schema.Schema.Type<typeof TokenUsageSchema>;\n\n// ─── Stop Reason ───\n\n/**\n * Schema for LLM response termination reason.\n * Indicates why the model stopped generating tokens.\n *\n * @example\n * ```typescript\n * const reason: StopReason = \"end_turn\"; // Model concluded naturally\n * const reason2: StopReason = \"max_tokens\"; // Hit output limit\n * ```\n */\nexport const StopReasonSchema = Schema.Literal(\n /** Model concluded naturally — full response present. */\n \"end_turn\",\n /** Hit `maxTokens` limit — response may be truncated. */\n \"max_tokens\",\n /** Hit a configured stop sequence — generation halted by design. */\n \"stop_sequence\",\n /** Model is invoking a tool — `toolCalls` array is populated. */\n \"tool_use\",\n);\n\n/**\n * Reason the LLM stopped generating.\n *\n * - **end_turn**: Model concluded naturally — response is complete.\n * - **max_tokens**: Hit configured output token limit — response may be truncated.\n * - **stop_sequence**: Hit a configured stop sequence — generation halted by design.\n * - **tool_use**: Model is invoking a tool — `toolCalls` array is populated.\n */\nexport type StopReason = Schema.Schema.Type<typeof StopReasonSchema>;\n\n// ─── Tool Definition ───\n\n/**\n * Schema for tool definitions.\n * Describes tools available to the LLM, including name, description, and input schema.\n * Tools are passed to the LLM for function calling / tool use.\n *\n * @example\n * ```typescript\n * const tool: ToolDefinition = {\n * name: \"file-read\",\n * description: \"Read a file from disk\",\n * inputSchema: {\n * path: { type: \"string\", description: \"File path\", required: true }\n * }\n * };\n * ```\n */\nexport const ToolDefinitionSchema = Schema.Struct({\n /** Tool identifier (used by model to invoke the tool) */\n name: Schema.String,\n /** Human-readable tool description for the model */\n description: Schema.String,\n /** Input schema describing expected parameters (JSON Schema format) */\n inputSchema: Schema.Record({ key: Schema.String, value: Schema.Unknown }),\n});\n\n/**\n * Tool definition.\n * Used to register available functions that the LLM can call.\n * Input schema is a JSON Schema object defining parameters.\n */\nexport type ToolDefinition = Schema.Schema.Type<typeof ToolDefinitionSchema>;\n\n// ─── Tool Call ───\n\n/**\n * Schema for tool invocation.\n * Emitted by the model when it decides to call a tool.\n *\n * @example\n * ```typescript\n * const call: ToolCall = {\n * id: \"toolu_123\",\n * name: \"file-read\",\n * input: { path: \"./output.txt\" }\n * };\n * ```\n */\nexport const ToolCallSchema = Schema.Struct({\n /** Unique tool call identifier (generated by model) */\n id: Schema.String,\n /** Tool name to invoke */\n name: Schema.String,\n /** Tool input parameters (arbitrary JSON-compatible object) */\n input: Schema.Unknown,\n});\n\n/**\n * Tool invocation from the LLM.\n * When the model decides to call a tool, this describes which tool and with what inputs.\n */\nexport type ToolCall = Schema.Schema.Type<typeof ToolCallSchema>;\n\n// ─── Completion Request ───\n\n/**\n * Request to the LLM for a completion.\n * Includes messages, model configuration, tool definitions, and sampling parameters.\n * Passed to LLMService.complete() for synchronous LLM calls.\n *\n * @see CompletionResponse — the response type returned by LLMService.complete()\n * @see ToolDefinition — shape of entries in the `tools` array\n * @see ModelConfig — shape of the `model` field\n *\n * @example\n * ```typescript\n * const request: CompletionRequest = {\n * messages: [\n * { role: \"system\", content: \"You are a helpful assistant.\" },\n * { role: \"user\", content: \"What is the capital of France?\" }\n * ],\n * model: { provider: \"anthropic\", model: \"claude-opus-4-20250514\" },\n * maxTokens: 1024,\n * temperature: 0.7,\n * tools: [\n * { name: \"web-search\", description: \"Search the web\", inputSchema: { query: { type: \"string\" } } }\n * ]\n * };\n * ```\n */\nexport type CompletionRequest = {\n /** Conversation history (at least 1 message required) */\n readonly messages: readonly LLMMessage[];\n /** Model config (provider + model name + optional sampling params) */\n readonly model?: ModelConfig;\n /** Maximum response tokens (optional, uses config default if omitted) */\n readonly maxTokens?: number;\n /** Sampling temperature 0.0-1.0 (optional, uses config default if omitted) */\n readonly temperature?: number;\n /** Stop sequences to halt generation (optional) */\n readonly stopSequences?: readonly string[];\n /** Tools available for the model to call (optional) */\n readonly tools?: readonly ToolDefinition[];\n /** System prompt (optional, prepended to user messages) */\n readonly systemPrompt?: string;\n};\n\n// ─── Completion Response ───\n\n/**\n * Schema for LLM response.\n * Contains the generated content, stop reason, token usage, and any tool calls.\n *\n * @example\n * ```typescript\n * const response: CompletionResponse = {\n * content: \"The capital of France is Paris.\",\n * stopReason: \"end_turn\",\n * usage: { inputTokens: 120, outputTokens: 15, totalTokens: 135, estimatedCost: 0.00041 },\n * model: \"claude-opus-4-20250514\",\n * toolCalls: undefined\n * };\n * ```\n */\nexport const CompletionResponseSchema = Schema.Struct({\n /** Generated response content (text only, no content blocks) */\n content: Schema.String,\n /** Why the model stopped generating */\n stopReason: StopReasonSchema,\n /** Token usage statistics */\n usage: TokenUsageSchema,\n /** Actual model identifier used (may differ from request) */\n model: Schema.String,\n /** Tool calls emitted by the model (if any) */\n toolCalls: Schema.optional(Schema.Array(ToolCallSchema)),\n /** Internal reasoning from thinking models (e.g. <think> blocks from qwen3, DeepSeek-R1) */\n thinking: Schema.optional(Schema.String),\n});\n\n/**\n * LLM response to a completion request.\n * Contains generated text, stop reason, usage metrics, and optional tool calls.\n *\n * @see CompletionRequest — the request type passed to LLMService.complete()\n * @see StopReason — possible values for the `stopReason` field\n * @see TokenUsage — shape of the `usage` field\n * @see ToolCall — shape of entries in the optional `toolCalls` array\n */\nexport type CompletionResponse = Schema.Schema.Type<\n typeof CompletionResponseSchema\n>;\n\n// ─── Stream Events ───\n\n/**\n * Events streamed during an LLM response.\n * Used when streaming responses rather than waiting for full completion.\n * Events arrive in sequence: text_delta(s), then tool_use_start/delta(s) if applicable, then content_complete, then usage.\n *\n * @example\n * ```typescript\n * const events: StreamEvent[] = [\n * { type: \"text_delta\", text: \"The \" },\n * { type: \"text_delta\", text: \"capital \" },\n * { type: \"text_delta\", text: \"is Paris.\" },\n * { type: \"content_complete\", content: \"The capital is Paris.\" },\n * { type: \"usage\", usage: { inputTokens: 50, outputTokens: 10, totalTokens: 60, estimatedCost: 0.00018 } }\n * ];\n * ```\n */\nexport type StreamEvent =\n | {\n /** Text chunk arriving */\n readonly type: \"text_delta\";\n /** Text chunk content */\n readonly text: string;\n }\n | {\n /** Tool invocation starting */\n readonly type: \"tool_use_start\";\n /** Unique tool call ID */\n readonly id: string;\n /** Tool name being invoked */\n readonly name: string;\n }\n | {\n /** Tool input parameter chunk arriving */\n readonly type: \"tool_use_delta\";\n /** JSON parameter chunk (accumulated to form full input) */\n readonly input: string;\n }\n | {\n /** Content generation completed */\n readonly type: \"content_complete\";\n /** Full accumulated response content */\n readonly content: string;\n }\n | {\n /** Token usage reported */\n readonly type: \"usage\";\n /** Final token usage for the request */\n readonly usage: TokenUsage;\n }\n | {\n /** Error occurred during streaming */\n readonly type: \"error\";\n /** Error message */\n readonly error: string;\n };\n\n// ─── Structured Output Config ───\n\n/**\n * Completion request with structured output validation.\n * Extends CompletionRequest to require the model output conform to a schema.\n * Used when the agent needs guaranteed JSON schema output from the LLM.\n *\n * @see CompletionRequest — base request type this extends\n *\n * @typeParam A — The type that the LLM output must conform to\n *\n * @example\n * ```typescript\n * interface Decision {\n * readonly choice: \"yes\" | \"no\";\n * readonly confidence: number;\n * }\n *\n * const request: StructuredCompletionRequest<Decision> = {\n * messages: [{ role: \"user\", content: \"Should I approve this?\" }],\n * outputSchema: Schema.Struct({\n * choice: Schema.Literal(\"yes\", \"no\"),\n * confidence: Schema.Number\n * }),\n * maxParseRetries: 2\n * };\n * ```\n */\nexport type StructuredCompletionRequest<A> = CompletionRequest & {\n /** Schema that the LLM response must conform to */\n readonly outputSchema: Schema.Schema<A>;\n /** If true, retry with corrected prompt if parse fails (default: false) */\n readonly retryOnParseFail?: boolean;\n /** Maximum parse retry attempts before giving up (default: 1) */\n readonly maxParseRetries?: number;\n};\n\n// ─── Truncation Strategy ───\n\n/**\n * Strategy for truncating context when it exceeds token budget.\n * Used by ContextWindowManager when compacting message history for token limits.\n *\n * @example\n * ```typescript\n * const strategy: TruncationStrategy = \"summarize-middle\";\n * ```\n */\nexport type TruncationStrategy =\n /** Remove oldest messages first (FIFO). Fastest; may lose early context. */\n | \"drop-oldest\"\n /** Summarize middle messages, preserving system prompt and most recent turns. */\n | \"summarize-middle\"\n /** Keep only the most recent N messages; drops all prior history. */\n | \"sliding-window\"\n /** Use heuristics to score and drop least-important messages first. */\n | \"importance-based\";\n\n// ─── LLM Request Event ───\n\n/**\n * Observability event emitted after every LLM request completes.\n * Captures request/response metadata for metrics, tracing, and cost tracking.\n * Published to EventBus and collected by MetricsCollector.\n *\n * Full request/response payloads included only when LLMConfig.observabilityVerbosity = \"full\".\n *\n * @see ObservabilityVerbosity — controls whether `fullRequest`/`fullResponse` are populated\n * @see TokenUsage — nested token usage shape in `response.usage`\n *\n * @example\n * ```typescript\n * const event: LLMRequestEvent = {\n * requestId: \"req-123\",\n * provider: \"anthropic\",\n * model: \"claude-opus-4-20250514\",\n * timestamp: new Date(),\n * durationMs: 1250,\n * systemPromptLength: 340,\n * messageCount: 3,\n * toolCount: 2,\n * response: {\n * contentLength: 156,\n * stopReason: \"end_turn\",\n * toolCallCount: 0,\n * usage: {\n * inputTokens: 420,\n * outputTokens: 45,\n * totalTokens: 465,\n * estimatedCost: 0.00195\n * }\n * }\n * };\n * ```\n */\nexport type LLMRequestEvent = {\n /** Unique request identifier for correlating request/response pairs */\n readonly requestId: string;\n /** LLM provider (e.g., \"anthropic\", \"openai\") */\n readonly provider: string;\n /** Model name used for the request */\n readonly model: string;\n /** When the request completed */\n readonly timestamp: Date;\n /** Request round-trip time in milliseconds */\n readonly durationMs: number;\n /** Length of system prompt in characters */\n readonly systemPromptLength: number;\n /** Number of messages in the request */\n readonly messageCount: number;\n /** Number of tool definitions passed to the model */\n readonly toolCount: number;\n /** Response details */\n readonly response: {\n /** Length of response content in characters */\n readonly contentLength: number;\n /** Why the model stopped (end_turn, max_tokens, etc.) */\n readonly stopReason: string;\n /** Number of tool calls in response */\n readonly toolCallCount: number;\n /** Token usage metrics */\n readonly usage: {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly totalTokens: number;\n readonly estimatedCost: number;\n };\n };\n /** Complete request payload (only if LLMConfig.observabilityVerbosity = \"full\") */\n readonly fullRequest?: CompletionRequest;\n /** Complete response payload (only if LLMConfig.observabilityVerbosity = \"full\") */\n readonly fullResponse?: CompletionResponse;\n};\n\n// ─── Observability Verbosity ───\n\n/**\n * Observability verbosity level for LLM request events.\n * Controls what is captured in each `LLMRequestEvent` published to the EventBus.\n *\n * @default \"full\"\n *\n * @example\n * ```typescript\n * const config = LLMConfig.of({\n * // ... other fields\n * observabilityVerbosity: process.env.NODE_ENV === \"production\" ? \"metadata\" : \"full\"\n * });\n * ```\n */\nexport type ObservabilityVerbosity =\n /** Capture timing, token counts, and cost only — lightweight, production-safe. */\n | \"metadata\"\n /** Capture complete request/response payloads — higher overhead, useful for debugging. */\n | \"full\";\n\n// ── Structured Output Capabilities ──\n\n/**\n * Provider-reported capabilities for structured JSON output.\n * Used by the structured output pipeline to select the optimal extraction strategy.\n */\nexport type StructuredOutputCapabilities = {\n /** Provider supports forcing JSON-only output (OpenAI, Gemini, Ollama) */\n readonly nativeJsonMode: boolean;\n /** Provider can enforce a JSON Schema on the output (OpenAI structured outputs) */\n readonly jsonSchemaEnforcement: boolean;\n /** Provider supports assistant message prefill to start response with \"{\" (Anthropic) */\n readonly prefillSupport: boolean;\n /** Provider supports GBNF grammar constraints for exact schema matching (Ollama/llama.cpp) */\n readonly grammarConstraints: boolean;\n};\n","import { Data } from \"effect\";\nimport type { LLMProvider } from \"./types.js\";\n\n/**\n * General LLM error — catch-all for unexpected provider failures.\n */\nexport class LLMError extends Data.TaggedError(\"LLMError\")<{\n readonly message: string;\n readonly provider: LLMProvider;\n readonly cause?: unknown;\n}> {}\n\n/**\n * Rate limit exceeded — includes retry-after hint.\n */\nexport class LLMRateLimitError extends Data.TaggedError(\"LLMRateLimitError\")<{\n readonly message: string;\n readonly provider: LLMProvider;\n readonly retryAfterMs: number;\n}> {}\n\n/**\n * Request timeout.\n */\nexport class LLMTimeoutError extends Data.TaggedError(\"LLMTimeoutError\")<{\n readonly message: string;\n readonly provider: LLMProvider;\n readonly timeoutMs: number;\n}> {}\n\n/**\n * Structured output parse failure.\n */\nexport class LLMParseError extends Data.TaggedError(\"LLMParseError\")<{\n readonly message: string;\n readonly rawOutput: string;\n readonly expectedSchema: string;\n}> {}\n\n/**\n * Context window overflow — too many tokens for the model.\n */\nexport class LLMContextOverflowError extends Data.TaggedError(\n \"LLMContextOverflowError\",\n)<{\n readonly message: string;\n readonly tokenCount: number;\n readonly maxTokens: number;\n}> {}\n\n/**\n * Union of all LLM error types.\n */\nexport type LLMErrors =\n | LLMError\n | LLMRateLimitError\n | LLMTimeoutError\n | LLMParseError\n | LLMContextOverflowError;\n","import { Effect, Context, type Stream } from \"effect\";\nimport type {\n CompletionRequest,\n CompletionResponse,\n StreamEvent,\n StructuredCompletionRequest,\n LLMMessage,\n ModelConfig,\n StructuredOutputCapabilities,\n} from \"./types.js\";\nimport type { LLMErrors } from \"./errors.js\";\n\n/**\n * Core LLM service — all LLM interactions go through this.\n * Layers 3, 4, 5, and 10 depend on this.\n */\nexport class LLMService extends Context.Tag(\"LLMService\")<\n LLMService,\n {\n /**\n * Complete a prompt (non-streaming).\n * Returns full response after generation completes.\n */\n readonly complete: (\n request: CompletionRequest,\n ) => Effect.Effect<CompletionResponse, LLMErrors>;\n\n /**\n * Stream a completion. Returns an Effect that yields a Stream of events.\n * Use for real-time UI updates (collaborative mode).\n */\n readonly stream: (\n request: CompletionRequest,\n ) => Effect.Effect<Stream.Stream<StreamEvent, LLMErrors>, LLMErrors>;\n\n /**\n * Complete with structured output.\n * Parses LLM response into a typed object using Effect Schema.\n * Retries with parse error feedback if parsing fails.\n */\n readonly completeStructured: <A>(\n request: StructuredCompletionRequest<A>,\n ) => Effect.Effect<A, LLMErrors>;\n\n /**\n * Generate embeddings for text.\n *\n * This is the SOLE embedding source for the entire framework.\n * Anthropic has no embeddings API — routes to OpenAI or Ollama\n * per LLMConfig.embeddingConfig.\n */\n readonly embed: (\n texts: readonly string[],\n model?: string,\n ) => Effect.Effect<readonly (readonly number[])[], LLMErrors>;\n\n /**\n * Count tokens for a set of messages.\n * Used for context window management.\n */\n readonly countTokens: (\n messages: readonly LLMMessage[],\n ) => Effect.Effect<number, LLMErrors>;\n\n /**\n * Get current model configuration.\n */\n readonly getModelConfig: () => Effect.Effect<ModelConfig, never>;\n\n /**\n * Report structured output capabilities for this provider.\n * Used by the structured output pipeline to select optimal JSON extraction strategy.\n */\n readonly getStructuredOutputCapabilities: () => Effect.Effect<StructuredOutputCapabilities, never>;\n }\n>() {}\n","import { Context, Layer } from \"effect\";\nimport type { LLMProvider, EmbeddingConfig, ObservabilityVerbosity } from \"./types.js\";\n\n/**\n * LLM service configuration.\n * Provides API keys, default model settings, timeouts, and observability verbosity.\n * Typically constructed from environment variables via llmConfigFromEnv.\n *\n * @example\n * ```typescript\n * const config = LLMConfig.of({\n * defaultProvider: \"anthropic\",\n * defaultModel: \"claude-opus-4-20250514\",\n * anthropicApiKey: process.env.ANTHROPIC_API_KEY,\n * maxRetries: 3,\n * timeoutMs: 30000\n * });\n * ```\n */\nexport class LLMConfig extends Context.Tag(\"LLMConfig\")<\n LLMConfig,\n {\n /**\n * Default LLM provider.\n * Used as fallback when a request does not specify a provider.\n *\n * @default \"anthropic\"\n */\n readonly defaultProvider: LLMProvider;\n\n /**\n * Default LLM model identifier.\n * Used as fallback when a request does not specify a model.\n *\n * @default From LLM_DEFAULT_MODEL env var, falls back to \"claude-sonnet-4-20250514\"\n */\n readonly defaultModel: string;\n\n /**\n * Anthropic API key.\n * Retrieved from ANTHROPIC_API_KEY environment variable.\n * Required if provider is \"anthropic\".\n *\n * @default From ANTHROPIC_API_KEY env var (undefined if not set)\n */\n readonly anthropicApiKey?: string;\n\n /**\n * OpenAI API key.\n * Retrieved from OPENAI_API_KEY environment variable.\n * Required if provider is \"openai\".\n *\n * @default From OPENAI_API_KEY env var (undefined if not set)\n */\n readonly openaiApiKey?: string;\n\n /**\n * Google API key.\n * Retrieved from GOOGLE_API_KEY environment variable.\n * Required if provider is \"gemini\".\n *\n * @default From GOOGLE_API_KEY env var (undefined if not set)\n */\n readonly googleApiKey?: string;\n\n /**\n * Ollama server endpoint.\n * Retrieved from OLLAMA_ENDPOINT environment variable.\n * Used for local model serving.\n *\n * @default \"http://localhost:11434\"\n */\n readonly ollamaEndpoint?: string;\n\n /**\n * Embedding configuration — model, provider, dimensions.\n * Anthropic has no embeddings API; embeddings always route to OpenAI or Ollama.\n * This is the sole embedding config for the entire framework.\n * Used by semantic cache, memory similarity search, and verification layers.\n *\n * @default { model: \"text-embedding-3-small\", dimensions: 1536, provider: \"openai\", batchSize: 100 }\n */\n readonly embeddingConfig: EmbeddingConfig;\n\n /**\n * Enable Anthropic prompt caching.\n * When true, memory context injections and system prompts are wrapped in\n * `cache_control: { type: \"ephemeral\" }` blocks to reduce costs.\n * Non-Anthropic providers silently ignore cache control directives.\n * Automatically set to true if defaultModel starts with \"claude\".\n *\n * @default true if defaultModel starts with \"claude\", false otherwise\n */\n readonly supportsPromptCaching: boolean;\n\n /**\n * Maximum number of retries for transient LLM request failures.\n * Applied with exponential backoff (2^n seconds between attempts).\n *\n * @default 3\n */\n readonly maxRetries: number;\n\n /**\n * Request timeout in milliseconds.\n * LLM requests exceeding this duration are aborted.\n *\n * @default 30000 (30 seconds)\n */\n readonly timeoutMs: number;\n\n /**\n * Enable/disable thinking mode for thinking-capable models.\n * - `true` — Always enable thinking (e.g., qwen3.5, DeepSeek-R1)\n * - `false` — Always disable thinking (e.g., cogito:14b that crashes with think:true)\n * - `undefined` — Auto-detect based on model capabilities (Ollama only)\n *\n * @default undefined (auto-detect)\n */\n readonly thinking?: boolean;\n\n /**\n * Default maximum output tokens for LLM responses.\n * Used if a CompletionRequest does not specify maxTokens.\n * Set lower for faster responses; higher for longer outputs.\n *\n * @default 4096\n */\n readonly defaultMaxTokens: number;\n\n /**\n * Default sampling temperature (0.0-1.0).\n * Used if a CompletionRequest does not specify temperature.\n * 0.0 = deterministic; 1.0 = maximum randomness.\n *\n * @default 0.7 (good balance of creativity and coherence)\n */\n readonly defaultTemperature: number;\n\n /**\n * LLM request/response observability verbosity.\n * Determines what data is captured in LLMRequestEvent for observability.\n *\n * - **\"full\"**: Capture complete request/response payloads (useful for debugging, higher overhead)\n * - **\"metadata\"**: Capture only timing, token counts, and cost (lightweight, production-safe)\n *\n * @default \"full\" (capture everything)\n *\n * @example\n * ```typescript\n * // Development: full details\n * observabilityVerbosity: process.env.NODE_ENV === \"production\" ? \"metadata\" : \"full\"\n * ```\n */\n readonly observabilityVerbosity: ObservabilityVerbosity;\n }\n>() {}\n\n/**\n * Raw LLMConfig object constructed from environment variables.\n * Reads all config from process.env with sensible defaults.\n * Exported so callers can spread overrides (e.g. change model) on top.\n *\n * Environment variables:\n * - LLM_DEFAULT_MODEL: Model identifier (default: claude-sonnet-4-20250514)\n * - ANTHROPIC_API_KEY: Anthropic API key\n * - OPENAI_API_KEY: OpenAI API key\n * - GOOGLE_API_KEY: Google API key\n * - OLLAMA_ENDPOINT: Ollama server URL (default: http://localhost:11434)\n * - EMBEDDING_MODEL: Embedding model name (default: text-embedding-3-small)\n * - EMBEDDING_DIMENSIONS: Embedding vector dimensions (default: 1536)\n * - EMBEDDING_PROVIDER: Embedding provider (default: openai)\n * - LLM_MAX_RETRIES: Retry attempts (default: 3)\n * - LLM_TIMEOUT_MS: Request timeout in ms (default: 30000)\n * - LLM_DEFAULT_TEMPERATURE: Sampling temperature (default: 0.7)\n * - LLM_OBSERVABILITY_VERBOSITY: \"full\" or \"metadata\" (default: full)\n *\n * @example\n * ```typescript\n * // Use defaults from environment\n * const config = llmConfigFromEnv;\n *\n * // Override specific fields\n * const customConfig = LLMConfig.of({\n * ...llmConfigFromEnv,\n * defaultModel: \"gpt-4o\",\n * defaultProvider: \"openai\"\n * });\n * ```\n */\nexport const llmConfigFromEnv = LLMConfig.of({\n defaultProvider: \"anthropic\",\n defaultModel:\n process.env.LLM_DEFAULT_MODEL || \"claude-sonnet-4-20250514\",\n anthropicApiKey: process.env.ANTHROPIC_API_KEY,\n openaiApiKey: process.env.OPENAI_API_KEY,\n googleApiKey: process.env.GOOGLE_API_KEY,\n ollamaEndpoint:\n process.env.OLLAMA_ENDPOINT ?? \"http://localhost:11434\",\n embeddingConfig: {\n model: process.env.EMBEDDING_MODEL ?? \"text-embedding-3-small\",\n dimensions: Number(process.env.EMBEDDING_DIMENSIONS ?? 1536),\n provider:\n (process.env.EMBEDDING_PROVIDER as \"openai\" | \"ollama\") ?? \"openai\",\n batchSize: 100,\n },\n supportsPromptCaching: (\n process.env.LLM_DEFAULT_MODEL || \"claude-sonnet-4-20250514\"\n ).startsWith(\"claude\"),\n maxRetries: Number(process.env.LLM_MAX_RETRIES ?? 3),\n timeoutMs: Number(process.env.LLM_TIMEOUT_MS ?? 30_000),\n defaultMaxTokens: 4096,\n defaultTemperature: Number(process.env.LLM_DEFAULT_TEMPERATURE ?? 0.7),\n observabilityVerbosity: (process.env.LLM_OBSERVABILITY_VERBOSITY as ObservabilityVerbosity | undefined) ?? \"full\",\n});\n\n/**\n * Effect-TS Layer that provides LLMConfig from environment variables.\n * Use this layer to automatically populate LLMConfig from process.env.\n * Can be overridden with a custom layer for testing or custom configuration.\n *\n * @example\n * ```typescript\n * const effect = Effect.gen(function* () {\n * const config = yield* LLMConfig;\n * console.log(config.defaultModel);\n * }).pipe(Effect.provide(LLMConfigFromEnv));\n *\n * Effect.runPromise(effect);\n * ```\n *\n * @see llmConfigFromEnv\n */\nexport const LLMConfigFromEnv = Layer.succeed(LLMConfig, llmConfigFromEnv);\n","import { Effect, Context, Layer } from \"effect\";\nimport type { LLMMessage, TruncationStrategy } from \"./types.js\";\nimport type { LLMErrors } from \"./errors.js\";\nimport { estimateTokenCount } from \"./token-counter.js\";\n\n/**\n * Manages context window budgets.\n * Ensures prompts don't exceed model limits.\n * Implements truncation strategies.\n */\nexport class PromptManager extends Context.Tag(\"PromptManager\")<\n PromptManager,\n {\n /**\n * Build a prompt within token budget.\n * Automatically truncates conversation history if needed.\n */\n readonly buildPrompt: (options: {\n readonly systemPrompt: string;\n readonly messages: readonly LLMMessage[];\n readonly reserveOutputTokens: number;\n readonly maxContextTokens: number;\n readonly truncationStrategy: TruncationStrategy;\n }) => Effect.Effect<readonly LLMMessage[], LLMErrors>;\n\n /**\n * Check if messages fit within context window.\n */\n readonly fitsInContext: (\n messages: readonly LLMMessage[],\n maxTokens: number,\n ) => Effect.Effect<boolean, LLMErrors>;\n }\n>() {}\n\n/**\n * Live PromptManager that uses heuristic token counting\n * and applies truncation strategies.\n */\nexport const PromptManagerLive = Layer.succeed(\n PromptManager,\n PromptManager.of({\n buildPrompt: (options) =>\n Effect.gen(function* () {\n const {\n systemPrompt,\n messages,\n reserveOutputTokens,\n maxContextTokens,\n truncationStrategy,\n } = options;\n\n const budget = maxContextTokens - reserveOutputTokens;\n\n // Always keep the system prompt\n const systemMessage: LLMMessage = {\n role: \"system\",\n content: systemPrompt,\n };\n const systemTokens = yield* estimateTokenCount([systemMessage]);\n\n if (systemTokens >= budget) {\n // System prompt alone exceeds budget — return just it (truncated scenario)\n return [systemMessage];\n }\n\n const remainingBudget = budget - systemTokens;\n\n // Apply truncation strategy\n const truncated = yield* applyTruncation(\n messages,\n remainingBudget,\n truncationStrategy,\n );\n\n return [systemMessage, ...truncated];\n }),\n\n fitsInContext: (messages, maxTokens) =>\n Effect.gen(function* () {\n const count = yield* estimateTokenCount(messages);\n return count <= maxTokens;\n }),\n }),\n);\n\n/**\n * Apply truncation strategy to fit messages within token budget.\n */\nconst applyTruncation = (\n messages: readonly LLMMessage[],\n budget: number,\n strategy: TruncationStrategy,\n): Effect.Effect<readonly LLMMessage[], never> =>\n Effect.gen(function* () {\n const totalTokens = yield* estimateTokenCount(messages);\n\n if (totalTokens <= budget) {\n return messages;\n }\n\n switch (strategy) {\n case \"drop-oldest\": {\n // Remove messages from the beginning until we fit\n const result: LLMMessage[] = [];\n let usedTokens = 0;\n\n // Work backwards — keep most recent messages\n for (let i = messages.length - 1; i >= 0; i--) {\n const msgTokens = yield* estimateTokenCount([messages[i]!]);\n if (usedTokens + msgTokens <= budget) {\n result.unshift(messages[i]!);\n usedTokens += msgTokens;\n } else {\n break;\n }\n }\n return result;\n }\n\n case \"sliding-window\": {\n // Keep last N messages that fit\n const result: LLMMessage[] = [];\n let usedTokens = 0;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msgTokens = yield* estimateTokenCount([messages[i]!]);\n if (usedTokens + msgTokens <= budget) {\n result.unshift(messages[i]!);\n usedTokens += msgTokens;\n } else {\n break;\n }\n }\n return result;\n }\n\n case \"summarize-middle\":\n case \"importance-based\":\n // For Phase 1: fall back to sliding-window behavior\n // Full implementation requires LLM calls (circular dependency)\n {\n const result: LLMMessage[] = [];\n let usedTokens = 0;\n\n // Keep first message (often has important context)\n if (messages.length > 0) {\n const firstTokens = yield* estimateTokenCount([messages[0]!]);\n if (firstTokens <= budget) {\n result.push(messages[0]!);\n usedTokens += firstTokens;\n }\n }\n\n // Fill from the end\n const tail: LLMMessage[] = [];\n for (let i = messages.length - 1; i >= 1; i--) {\n const msgTokens = yield* estimateTokenCount([messages[i]!]);\n if (usedTokens + msgTokens <= budget) {\n tail.unshift(messages[i]!);\n usedTokens += msgTokens;\n } else {\n break;\n }\n }\n\n return [...result, ...tail];\n }\n }\n });\n","import { Effect } from \"effect\";\nimport type { LLMMessage } from \"./types.js\";\n\n/**\n * Estimate the chars-per-token ratio based on content characteristics.\n * Code and JSON are denser (~3 chars/token) while natural language is ~4.\n */\nfunction charsPerToken(text: string): number {\n if (text.length === 0) return 4;\n // Sample first 2000 chars for classification\n const sample = text.slice(0, 2000);\n const codeSignals = (sample.match(/[{}();=<>\\[\\]]/g) ?? []).length;\n const jsonSignals = (sample.match(/\"\\w+\"\\s*:/g) ?? []).length;\n const ratio = (codeSignals + jsonSignals) / sample.length;\n // High density of code/JSON markers → lower chars-per-token\n if (ratio > 0.08) return 3; // Mostly code/JSON\n if (ratio > 0.04) return 3.5; // Mixed\n return 4; // Natural language\n}\n\n/**\n * Estimate token count for messages.\n * Uses content-aware heuristics: ~3 chars/token for code/JSON, ~4 for English text.\n * This is used as a fallback when the provider's token counting API is unavailable.\n */\nexport const estimateTokenCount = (\n messages: readonly LLMMessage[],\n): Effect.Effect<number, never> =>\n Effect.sync(() => {\n let totalTokens = 0;\n\n for (const msg of messages) {\n if (typeof msg.content === \"string\") {\n totalTokens += Math.ceil(msg.content.length / charsPerToken(msg.content));\n } else {\n // Content blocks\n for (const block of msg.content) {\n if (block.type === \"text\") {\n totalTokens += Math.ceil(block.text.length / charsPerToken(block.text));\n } else if (block.type === \"tool_result\") {\n totalTokens += Math.ceil(block.content.length / charsPerToken(block.content));\n } else if (block.type === \"tool_use\") {\n const json = JSON.stringify(block.input);\n totalTokens += Math.ceil(json.length / 3); // Tool input is always JSON\n }\n // Images not counted in token estimation\n }\n }\n // Add overhead for role/message framing (~4 tokens per message)\n totalTokens += 4;\n }\n\n return totalTokens;\n });\n\n/**\n * Calculate cost in USD given token counts and model name.\n */\nexport const calculateCost = (\n inputTokens: number,\n outputTokens: number,\n model: string,\n): number => {\n // Cost per 1M tokens lookup\n const costMap: Record<string, { input: number; output: number }> = {\n \"claude-3-5-haiku-20241022\": { input: 1.0, output: 5.0 },\n \"claude-sonnet-4-20250514\": { input: 3.0, output: 15.0 },\n \"claude-sonnet-4-5-20250929\": { input: 3.0, output: 15.0 },\n \"claude-opus-4-20250514\": { input: 15.0, output: 75.0 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4o\": { input: 2.5, output: 10.0 },\n \"gemini-2.0-flash\": { input: 0.1, output: 0.4 },\n \"gemini-2.5-pro-preview-03-25\": { input: 1.25, output: 10.0 },\n \"gemini-embedding-001\": { input: 0.0, output: 0.0 },\n };\n\n const costs = costMap[model] ?? { input: 3.0, output: 15.0 };\n return (\n (inputTokens / 1_000_000) * costs.input +\n (outputTokens / 1_000_000) * costs.output\n );\n};\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type {\n LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ContentBlock,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n// ─── Anthropic Message Conversion Helpers ───\n\ntype AnthropicRole = \"user\" | \"assistant\";\n\ntype AnthropicContentBlock =\n | { type: \"text\"; text: string; cache_control?: { type: \"ephemeral\" } }\n | { type: \"image\"; source: { type: string; media_type: string; data: string } }\n | { type: \"tool_use\"; id: string; name: string; input: unknown }\n | { type: \"tool_result\"; tool_use_id: string; content: string };\n\ntype AnthropicMessage = {\n role: AnthropicRole;\n content: string | AnthropicContentBlock[];\n};\n\nconst toAnthropicMessages = (\n messages: readonly LLMMessage[],\n): AnthropicMessage[] =>\n messages\n .filter((m) => m.role !== \"system\")\n .map((m) => {\n if (m.role === \"tool\") {\n // Convert tool result to Anthropic's tool_result content block format\n return {\n role: \"user\" as AnthropicRole,\n content: [{\n type: \"tool_result\" as const,\n tool_use_id: m.toolCallId,\n content: m.content,\n }] as unknown as AnthropicContentBlock[],\n };\n }\n return {\n role: m.role as AnthropicRole,\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly ContentBlock[]).map(\n (b) => b as unknown as AnthropicContentBlock,\n ),\n };\n });\n\nconst toAnthropicTool = (tool: {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}) => ({\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: \"object\" as const,\n ...tool.inputSchema,\n },\n});\n\nconst toEffectError = (error: unknown, provider: \"anthropic\"): LLMErrors => {\n const err = error as { status?: number; message?: string; headers?: Record<string, string> };\n if (err.status === 429) {\n const retryAfter = err.headers?.[\"retry-after\"];\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider,\n retryAfterMs: retryAfter ? Number(retryAfter) * 1000 : 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider,\n cause: error,\n });\n};\n\n// ── System prompt caching ────────────────────────────────────────────────────\n// Anthropic's prompt caching uses cache_control on content blocks.\n// System prompts >= ~1024 tokens benefit from ephemeral caching; the 5-min\n// cache window avoids re-processing the same system prompt across turns.\n\nconst MIN_SYSTEM_CACHE_CHARS = 4096; // ~1024 tokens at ~4 chars/token\n\ntype SystemParam =\n | string\n | Array<{ type: \"text\"; text: string; cache_control?: { type: \"ephemeral\" } }>;\n\n/**\n * Build the Anthropic `system` parameter. For long system prompts, wrap in\n * a content block with `cache_control: { type: \"ephemeral\" }`.\n */\nconst buildSystemParam = (systemPrompt: string | undefined): SystemParam | undefined => {\n if (!systemPrompt) return undefined;\n if (systemPrompt.length < MIN_SYSTEM_CACHE_CHARS) return systemPrompt;\n return [{\n type: \"text\",\n text: systemPrompt,\n cache_control: { type: \"ephemeral\" },\n }];\n};\n\n// ─── Anthropic Provider Layer ───\n\nexport const AnthropicProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n // Lazy-load the SDK to avoid hard dependency if not using Anthropic\n const createClient = () => {\n // Dynamic import is handled in Effect.tryPromise\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const Anthropic = require(\"@anthropic-ai/sdk\").default;\n return new Anthropic({ apiKey: config.anthropicApiKey });\n };\n\n let _client: ReturnType<typeof createClient> | null = null;\n const getClient = () => {\n if (!_client) _client = createClient();\n return _client;\n };\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n\n const response = yield* Effect.tryPromise({\n try: () =>\n (client as { messages: { create: (opts: unknown) => Promise<unknown> } }).messages.create({\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n system: buildSystemParam(request.systemPrompt),\n messages: toAnthropicMessages(request.messages),\n stop_sequences: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n tools: request.tools?.map(toAnthropicTool),\n }),\n catch: (error) => toEffectError(error, \"anthropic\"),\n });\n\n return mapAnthropicResponse(response as AnthropicRawResponse, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"anthropic\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const stream = (client as { messages: { stream: (opts: unknown) => { on: (event: string, cb: (...args: unknown[]) => void) => void } } }).messages.stream({\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n system: buildSystemParam(request.systemPrompt),\n messages: toAnthropicMessages(request.messages),\n });\n\n stream.on(\"text\", (text: unknown) => {\n emit.single({ type: \"text_delta\", text: text as string });\n });\n\n stream.on(\"finalMessage\", (message: unknown) => {\n const msg = message as AnthropicRawResponse;\n const content = msg.content\n .filter(\n (b: { type: string }): b is { type: \"text\"; text: string } =>\n b.type === \"text\",\n )\n .map((b: { text: string }) => b.text)\n .join(\"\");\n\n emit.single({ type: \"content_complete\", content });\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens: msg.usage.input_tokens,\n outputTokens: msg.usage.output_tokens,\n totalTokens:\n msg.usage.input_tokens + msg.usage.output_tokens,\n estimatedCost: calculateCost(\n msg.usage.input_tokens,\n msg.usage.output_tokens,\n model,\n ),\n },\n });\n emit.end();\n });\n\n stream.on(\"error\", (error: unknown) => {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"anthropic\",\n cause: error,\n }),\n );\n });\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const jsonSchema = Schema.encodedSchema(request.outputSchema);\n const schemaStr = JSON.stringify(jsonSchema, null, 2);\n\n const messagesWithFormat: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `Respond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ];\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messagesWithFormat\n : [\n ...messagesWithFormat,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response did not match the schema. Error: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ];\n\n // Convert + inject assistant prefill to bias toward JSON output\n const anthropicMsgs = toAnthropicMessages(msgs);\n anthropicMsgs.push({ role: \"assistant\", content: \"{\" });\n\n const completeResult = yield* Effect.tryPromise({\n try: () => {\n const client = getClient();\n return (client as { messages: { create: (opts: unknown) => Promise<unknown> } }).messages.create({\n model: typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n system: buildSystemParam(request.systemPrompt),\n messages: anthropicMsgs,\n });\n },\n catch: (error) => toEffectError(error, \"anthropic\"),\n });\n\n const response = mapAnthropicResponse(\n completeResult as AnthropicRawResponse,\n typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel,\n );\n\n // Prepend the \"{\" prefill back to the response content\n const fullContent = \"{\" + response.content;\n\n try {\n const parsed = JSON.parse(fullContent);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const embeddingModel = model ?? config.embeddingConfig.model;\n const embProvider = config.embeddingConfig.provider;\n\n if (embProvider === \"openai\") {\n const { default: OpenAI } = await import(\"openai\");\n const openaiClient = new OpenAI({\n apiKey: config.openaiApiKey,\n });\n const batchSize = config.embeddingConfig.batchSize ?? 100;\n const results: number[][] = [];\n\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize);\n const response = await openaiClient.embeddings.create({\n model: embeddingModel,\n input: [...batch],\n dimensions: config.embeddingConfig.dimensions,\n });\n results.push(\n ...response.data.map(\n (d: { embedding: number[] }) => d.embedding,\n ),\n );\n }\n\n return results;\n }\n\n // Ollama embeddings\n const endpoint =\n config.ollamaEndpoint ?? \"http://localhost:11434\";\n return Promise.all(\n [...texts].map(async (text) => {\n const res = await fetch(`${endpoint}/api/embed`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: embeddingModel,\n input: text,\n }),\n });\n const data = (await res.json()) as {\n embeddings: number[][];\n };\n return data.embeddings[0]!;\n }),\n );\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"anthropic\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"anthropic\" as const,\n model: config.defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: false,\n jsonSchemaEnforcement: false,\n prefillSupport: true,\n grammarConstraints: false,\n }),\n });\n }),\n);\n\n// ─── Anthropic Response Mapping ───\n\ntype AnthropicRawResponse = {\n content: Array<\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input: unknown }\n >;\n stop_reason: string;\n usage: { input_tokens: number; output_tokens: number };\n model: string;\n};\n\nconst mapAnthropicResponse = (\n response: AnthropicRawResponse,\n model: string,\n): CompletionResponse => {\n const textContent = response.content\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\");\n\n const toolCalls = response.content\n .filter(\n (\n b,\n ): b is {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n } => b.type === \"tool_use\",\n )\n .map((b) => ({\n id: b.id,\n name: b.name,\n input: b.input,\n }));\n\n const stopReason =\n response.stop_reason === \"end_turn\"\n ? (\"end_turn\" as const)\n : response.stop_reason === \"max_tokens\"\n ? (\"max_tokens\" as const)\n : response.stop_reason === \"stop_sequence\"\n ? (\"stop_sequence\" as const)\n : response.stop_reason === \"tool_use\"\n ? (\"tool_use\" as const)\n : (\"end_turn\" as const);\n\n return {\n content: textContent,\n stopReason,\n usage: {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n totalTokens:\n response.usage.input_tokens + response.usage.output_tokens,\n estimatedCost: calculateCost(\n response.usage.input_tokens,\n response.usage.output_tokens,\n model,\n ),\n },\n model: response.model ?? model,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n };\n};\n","import { Schedule } from \"effect\";\nimport type { LLMErrors } from \"./errors.js\";\n\n/**\n * Retry policy for LLM calls.\n * Handles rate limits with exponential backoff.\n * Only retries on rate limit and timeout errors.\n */\nexport const retryPolicy = Schedule.intersect(\n Schedule.recurs(3),\n Schedule.exponential(\"1 second\", 2.0),\n).pipe(\n Schedule.whileInput<LLMErrors>(\n (error) =>\n error._tag === \"LLMRateLimitError\" || error._tag === \"LLMTimeoutError\",\n ),\n);\n\n// ─── Circuit Breaker ───\n\nexport type CircuitBreakerConfig = {\n readonly failureThreshold: number;\n readonly cooldownMs: number;\n readonly halfOpenRequests: number;\n};\n\nexport const defaultCircuitBreakerConfig: CircuitBreakerConfig = {\n failureThreshold: 5,\n cooldownMs: 30_000,\n halfOpenRequests: 1,\n};\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ToolDefinition,\n ToolCall,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n// ─── OpenAI Message Conversion ───\n\ntype OpenAIMessage =\n | { role: \"system\" | \"user\" | \"assistant\"; content: string }\n | { role: \"tool\"; tool_call_id: string; content: string };\n\nconst toOpenAIMessages = (\n messages: readonly LLMMessage[],\n): OpenAIMessage[] =>\n messages.map((m) => {\n if (m.role === \"tool\") {\n return {\n role: \"tool\" as const,\n tool_call_id: m.toolCallId,\n content: m.content,\n };\n }\n return {\n role: m.role as \"system\" | \"user\" | \"assistant\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\"),\n };\n });\n\nconst toEffectError = (error: unknown, provider: \"openai\"): LLMErrors => {\n const err = error as { status?: number; message?: string };\n if (err.status === 429) {\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider,\n retryAfterMs: 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider,\n cause: error,\n });\n};\n\n// ─── OpenAI Tool Conversion ───\n\nconst toOpenAITool = (tool: ToolDefinition) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n});\n\n// ─── OpenAI Provider Layer ───\n\nexport const OpenAIProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n const createClient = () => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const OpenAI = require(\"openai\").default;\n return new OpenAI({ apiKey: config.openaiApiKey });\n };\n\n let _client: ReturnType<typeof createClient> | null = null;\n const getClient = () => {\n if (!_client) _client = createClient();\n return _client;\n };\n\n const defaultModel = config.defaultModel.startsWith(\"claude\")\n ? \"gpt-4o\"\n : config.defaultModel;\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? defaultModel;\n\n const messages = toOpenAIMessages(request.messages);\n if (request.systemPrompt) {\n messages.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const requestBody: Record<string, unknown> = {\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n messages,\n stop: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n };\n\n if (request.tools && request.tools.length > 0) {\n requestBody.tools = request.tools.map(toOpenAITool);\n }\n\n const response = yield* Effect.tryPromise({\n try: () =>\n (client as { chat: { completions: { create: (opts: unknown) => Promise<unknown> } } }).chat.completions.create(requestBody),\n catch: (error) => toEffectError(error, \"openai\"),\n });\n\n return mapOpenAIResponse(response as OpenAIRawResponse, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"openai\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const client = getClient();\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? defaultModel;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const doStream = async () => {\n try {\n const stream = await (client as { chat: { completions: { create: (opts: unknown) => Promise<AsyncIterable<unknown>> } } }).chat.completions.create({\n model,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature:\n request.temperature ?? config.defaultTemperature,\n messages: (() => {\n const msgs = toOpenAIMessages(request.messages);\n if (request.systemPrompt) {\n msgs.unshift({ role: \"system\", content: request.systemPrompt });\n }\n return msgs;\n })(),\n stream: true,\n });\n\n let fullContent = \"\";\n\n for await (const chunk of stream as AsyncIterable<{\n choices: Array<{\n delta: { content?: string };\n finish_reason?: string;\n }>;\n usage?: { prompt_tokens: number; completion_tokens: number };\n }>) {\n const delta = chunk.choices[0]?.delta?.content;\n if (delta) {\n fullContent += delta;\n emit.single({ type: \"text_delta\", text: delta });\n }\n\n if (chunk.choices[0]?.finish_reason) {\n emit.single({\n type: \"content_complete\",\n content: fullContent,\n });\n\n const inputTokens = chunk.usage?.prompt_tokens ?? 0;\n const outputTokens =\n chunk.usage?.completion_tokens ?? 0;\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(\n inputTokens,\n outputTokens,\n model,\n ),\n },\n });\n emit.end();\n }\n }\n } catch (error) {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"openai\",\n cause: error,\n }),\n );\n }\n };\n void doStream();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const jsonSchema = Schema.encodedSchema(request.outputSchema);\n const schemaObj = JSON.parse(JSON.stringify(jsonSchema));\n const schemaStr = JSON.stringify(schemaObj, null, 2);\n const model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? defaultModel;\n const client = getClient();\n const maxRetries = request.maxParseRetries ?? 2;\n\n // ── Native JSON Schema mode (gpt-4o-2024-08-06+, o-series, gpt-4.1) ──\n // Use response_format with json_schema for strict enforcement.\n const requestBody: Record<string, unknown> = {\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n response_format: {\n type: \"json_schema\",\n json_schema: {\n name: \"structured_output\",\n strict: true,\n schema: schemaObj,\n },\n },\n };\n\n const messages: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `Respond with JSON matching this schema:\\n${schemaStr}`,\n },\n ];\n\n let lastError: unknown = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messages\n : [\n ...messages,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response did not match the schema. Error: ${String(lastError)}. Please try again.`,\n },\n ];\n\n const completeResult = yield* Effect.tryPromise({\n try: () =>\n (client as { chat: { completions: { create: (opts: unknown) => Promise<unknown> } } }).chat.completions.create({\n ...requestBody,\n messages: toOpenAIMessages(msgs),\n }),\n catch: (error) => toEffectError(error, \"openai\"),\n });\n\n const response = mapOpenAIResponse(\n completeResult as OpenAIRawResponse,\n model,\n );\n\n try {\n const parsed = JSON.parse(response.content);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const client = getClient();\n const embeddingModel =\n model ?? config.embeddingConfig.model;\n const batchSize = config.embeddingConfig.batchSize ?? 100;\n const results: number[][] = [];\n\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize);\n const response = await (client as { embeddings: { create: (opts: unknown) => Promise<{ data: Array<{ embedding: number[] }> }> } }).embeddings.create({\n model: embeddingModel,\n input: [...batch],\n dimensions: config.embeddingConfig.dimensions,\n });\n results.push(\n ...response.data.map(\n (d: { embedding: number[] }) => d.embedding,\n ),\n );\n }\n\n return results;\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"openai\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"openai\" as const,\n model: defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: true,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n });\n }),\n);\n\n// ─── OpenAI Response Mapping ───\n\ntype OpenAIToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\ntype OpenAIRawResponse = {\n choices: Array<{\n message: {\n content: string | null;\n role: string;\n tool_calls?: OpenAIToolCall[];\n };\n finish_reason: string;\n }>;\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n model: string;\n};\n\nconst mapOpenAIResponse = (\n response: OpenAIRawResponse,\n model: string,\n): CompletionResponse => {\n const message = response.choices[0]?.message;\n const content = message?.content ?? \"\";\n const rawToolCalls = message?.tool_calls;\n\n const hasToolCalls = rawToolCalls && rawToolCalls.length > 0;\n\n const stopReason =\n response.choices[0]?.finish_reason === \"tool_calls\" || hasToolCalls\n ? (\"tool_use\" as const)\n : response.choices[0]?.finish_reason === \"stop\"\n ? (\"end_turn\" as const)\n : response.choices[0]?.finish_reason === \"length\"\n ? (\"max_tokens\" as const)\n : (\"end_turn\" as const);\n\n const toolCalls: ToolCall[] | undefined = hasToolCalls\n ? rawToolCalls.map((tc) => {\n let input: unknown;\n try {\n input = JSON.parse(tc.function.arguments);\n } catch {\n input = { raw: tc.function.arguments };\n }\n return {\n id: tc.id,\n name: tc.function.name,\n input,\n };\n })\n : undefined;\n\n return {\n content,\n stopReason,\n usage: {\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n totalTokens: response.usage?.total_tokens ?? 0,\n estimatedCost: calculateCost(\n response.usage?.prompt_tokens ?? 0,\n response.usage?.completion_tokens ?? 0,\n model,\n ),\n },\n model: response.model ?? model,\n toolCalls,\n };\n};\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport { LLMError, LLMTimeoutError, LLMParseError } from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ToolDefinition,\n ToolCall,\n} from \"../types.js\";\nimport { estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\nimport { getProviderDefaultModel } from \"../provider-defaults.js\";\n\n// ─── Ollama SDK types (from the `ollama` npm package) ───\n\ntype OllamaTool = {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n};\n\ntype OllamaMessage = {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tool_calls?: Array<{\n function: { name: string; arguments: Record<string, any> };\n }>;\n};\n\n// ─── Conversion Helpers ───\n\nconst toOllamaMessages = (messages: readonly LLMMessage[]): OllamaMessage[] =>\n messages.map((m) => {\n // Tool result messages — pass through directly (Ollama supports role:\"tool\")\n if (m.role === \"tool\") {\n return { role: \"tool\" as const, content: m.content };\n }\n // Assistant messages — extract text and convert tool_use blocks to tool_calls\n if (m.role === \"assistant\") {\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\");\n const toolUseBlocks =\n typeof m.content !== \"string\"\n ? (\n m.content as readonly {\n type: string;\n name?: string;\n input?: unknown;\n }[]\n ).filter(\n (b): b is { type: \"tool_use\"; name: string; input: unknown } =>\n b.type === \"tool_use\",\n )\n : [];\n return {\n role: \"assistant\" as const,\n content: textContent,\n ...(toolUseBlocks.length > 0\n ? {\n tool_calls: toolUseBlocks.map((tc) => ({\n function: {\n name: tc.name,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arguments: (tc.input ?? {}) as Record<string, any>,\n },\n })),\n }\n : {}),\n };\n }\n // system, user\n return {\n role: m.role as \"system\" | \"user\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\"),\n };\n });\n\nconst toOllamaTools = (\n tools?: readonly ToolDefinition[],\n): OllamaTool[] | undefined => {\n if (!tools || tools.length === 0) return undefined;\n return tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema as Record<string, unknown>,\n },\n }));\n};\n\nconst parseToolCalls = (\n toolCalls?: Array<{\n function: { name: string; arguments: unknown };\n }>,\n): ToolCall[] | undefined => {\n if (!toolCalls || toolCalls.length === 0) return undefined;\n return toolCalls.map((tc, i) => ({\n id: `ollama-tc-${Date.now()}-${i}`,\n name: tc.function.name,\n input: tc.function.arguments,\n }));\n};\n\n// ─── Thinking Auto-Detect ───\n\n/** Cache for model thinking capability checks (avoids repeated /api/show calls) */\nconst thinkingCapabilityCache = new Map<string, boolean>();\n\n/**\n * Check if an Ollama model supports thinking mode via /api/show.\n * Results are cached per model name.\n */\nasync function supportsThinking(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client: { show: (opts: { model: string }) => Promise<any> },\n model: string,\n): Promise<boolean> {\n const cached = thinkingCapabilityCache.get(model);\n if (cached !== undefined) return cached;\n\n try {\n const info = await client.show({ model });\n const template = (info.template ?? \"\") as string;\n const result =\n template.includes(\"think\") || template.includes(\"<|thinking|>\");\n thinkingCapabilityCache.set(model, result);\n return result;\n } catch {\n thinkingCapabilityCache.set(model, false);\n return false;\n }\n}\n\n/**\n * Resolve the `think` parameter for Ollama chat calls.\n * - config.thinking === true → always enable\n * - config.thinking === false → always disable (omit param)\n * - config.thinking === undefined → auto-detect via /api/show\n */\nasync function resolveThinking(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client: { show: (opts: { model: string }) => Promise<any> },\n model: string,\n configThinking: boolean | undefined,\n): Promise<boolean | undefined> {\n if (configThinking === false) return undefined; // omit think param entirely\n if (configThinking === true) return true;\n // Auto-detect\n const capable = await supportsThinking(client, model);\n return capable ? true : undefined;\n}\n\n// ─── Error Helpers ───\n\n/**\n * Detect Ollama \"model not found\" errors and produce an actionable message.\n * Ollama returns ResponseError with status 404 and message \"model 'X' not found\".\n */\nfunction ollamaError(error: unknown, model?: string): LLMError {\n const msg = (error as { message?: string })?.message ?? String(error);\n const status =\n (error as { status_code?: number; statusCode?: number })?.status_code ??\n (error as { status_code?: number; statusCode?: number })?.statusCode;\n\n // Model not found — give the user a clear fix command\n if (status === 404 || /model\\s+['\"]?\\S+['\"]?\\s+not found/i.test(msg)) {\n const modelName =\n model ??\n msg.match(/model\\s+['\"]?(\\S+?)['\"]?\\s+not found/i)?.[1] ??\n \"unknown\";\n return new LLMError({\n message: `Model \"${modelName}\" not found locally. Run: ollama pull ${modelName}`,\n provider: \"ollama\",\n cause: error,\n });\n }\n\n return new LLMError({\n message: `Ollama request failed: ${msg}`,\n provider: \"ollama\",\n cause: error,\n });\n}\n// ─── Ollama / Local Provider Layer ───\n\nexport const LocalProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n const endpoint = config.ollamaEndpoint ?? \"http://localhost:11434\";\n const defaultModel =\n config.defaultModel.startsWith(\"claude\") ||\n config.defaultModel.startsWith(\"gpt\")\n ? (getProviderDefaultModel(\"ollama\") ?? \"cogito:14b\")\n : config.defaultModel;\n\n // Lazy-import the ollama SDK (same pattern as Gemini provider)\n const getClient = async () => {\n const { Ollama } = await import(\"ollama\");\n return new Ollama({ host: endpoint });\n };\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : (request.model?.model ?? defaultModel);\n\n const response = yield* Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n\n const msgs = toOllamaMessages(request.messages);\n if (request.systemPrompt) {\n msgs.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const think = await resolveThinking(\n client,\n model,\n config.thinking,\n );\n\n return client.chat({\n model,\n messages: msgs,\n tools: toOllamaTools(request.tools),\n stream: false,\n ...(think !== undefined ? { think } : {}),\n keep_alive: \"5m\",\n options: {\n temperature: request.temperature ?? config.defaultTemperature,\n num_predict: request.maxTokens ?? config.defaultMaxTokens,\n stop: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n },\n });\n },\n catch: (error) => ollamaError(error, model),\n });\n\n const content = response.message?.content ?? \"\";\n // Extract thinking from Ollama response (available in SDK v0.6+ for thinking models)\n const thinkingContent =\n (response.message as { thinking?: string } | undefined)?.thinking ||\n undefined;\n const inputTokens = response.prompt_eval_count ?? 0;\n const outputTokens = response.eval_count ?? 0;\n const toolCalls = parseToolCalls(\n response.message?.tool_calls as\n | Array<{\n function: { name: string; arguments: unknown };\n }>\n | undefined,\n );\n\n const hasToolCalls = toolCalls && toolCalls.length > 0;\n\n return {\n content,\n stopReason: hasToolCalls\n ? (\"tool_use\" as const)\n : response.done_reason === \"stop\"\n ? (\"end_turn\" as const)\n : response.done_reason === \"length\"\n ? (\"max_tokens\" as const)\n : (\"end_turn\" as const),\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: 0, // Local models are free\n },\n model: response.model ?? model,\n toolCalls,\n ...(thinkingContent ? { thinking: thinkingContent } : {}),\n } satisfies CompletionResponse;\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"120 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"Local LLM request timed out\",\n provider: \"ollama\",\n timeoutMs: 120_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : (request.model?.model ?? defaultModel);\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const doStream = async () => {\n try {\n const client = await getClient();\n\n const msgs = toOllamaMessages(request.messages);\n if (request.systemPrompt) {\n msgs.unshift({\n role: \"system\",\n content: request.systemPrompt,\n });\n }\n\n const think = await resolveThinking(\n client,\n model,\n config.thinking,\n );\n\n const stream = await client.chat({\n model,\n messages: msgs,\n tools: toOllamaTools(request.tools),\n stream: true,\n ...(think !== undefined ? { think } : {}),\n keep_alive: \"5m\",\n options: {\n temperature:\n request.temperature ?? config.defaultTemperature,\n num_predict: request.maxTokens ?? config.defaultMaxTokens,\n },\n });\n\n let fullContent = \"\";\n\n for await (const chunk of stream) {\n if (chunk.message?.content) {\n fullContent += chunk.message.content;\n emit.single({\n type: \"text_delta\",\n text: chunk.message.content,\n });\n }\n\n if (chunk.done) {\n emit.single({\n type: \"content_complete\",\n content: fullContent,\n });\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens: chunk.prompt_eval_count ?? 0,\n outputTokens: chunk.eval_count ?? 0,\n totalTokens:\n (chunk.prompt_eval_count ?? 0) +\n (chunk.eval_count ?? 0),\n estimatedCost: 0,\n },\n });\n emit.end();\n }\n }\n } catch (error) {\n emit.fail(ollamaError(error, model));\n }\n };\n void doStream();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const encodedSchema = Schema.encodedSchema(request.outputSchema);\n const schemaObj = JSON.parse(JSON.stringify(encodedSchema));\n const schemaStr = JSON.stringify(schemaObj, null, 2);\n\n // Build Ollama-native format constraint.\n // Ollama SDK ≥0.5 supports format: { type: \"object\", properties: ... }\n // for schema-enforced JSON output (GBNF grammar under the hood).\n // Fall back to format: \"json\" if the schema doesn't have properties.\n const ollamaFormat: \"json\" | Record<string, unknown> =\n schemaObj && typeof schemaObj === \"object\" && schemaObj.properties\n ? (schemaObj as Record<string, unknown>)\n : \"json\";\n\n const model =\n typeof request.model === \"string\"\n ? request.model\n : (request.model?.model ?? defaultModel);\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs = toOllamaMessages(\n attempt === 0\n ? [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ]\n : [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response was not valid JSON. The parse error was: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ],\n );\n\n if (request.systemPrompt) {\n msgs.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const response = yield* Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n return client.chat({\n model,\n messages: msgs,\n stream: false,\n format: ollamaFormat,\n keep_alive: \"5m\",\n options: {\n temperature:\n request.temperature ?? config.defaultTemperature,\n num_predict: request.maxTokens ?? config.defaultMaxTokens,\n },\n });\n },\n catch: (error) => ollamaError(error, model),\n });\n\n const content = response.message?.content ?? \"\";\n\n try {\n const parsed = JSON.parse(content);\n const decoded = Schema.decodeUnknownEither(request.outputSchema)(\n parsed,\n );\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n const embeddingModel =\n model ?? config.embeddingConfig.model ?? \"nomic-embed-text\";\n\n const response = await client.embed({\n model: embeddingModel,\n input: [...texts],\n });\n\n return response.embeddings;\n },\n catch: (error) =>\n ollamaError(\n error,\n model ?? config.embeddingConfig.model ?? \"nomic-embed-text\",\n ),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"ollama\" as const,\n model: defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: true,\n prefillSupport: false,\n grammarConstraints: true,\n }),\n });\n }),\n);\n","/**\n * Default model constants for each LLM provider.\n * Single source of truth — used by providers at construction time\n * and by the runtime to resolve model names for display/metrics.\n */\n\nexport const PROVIDER_DEFAULT_MODELS: Record<string, string> = {\n anthropic: \"claude-sonnet-4-20250514\",\n openai: \"gpt-4o\",\n ollama: \"cogito:14b\",\n gemini: \"gemini-2.0-flash\",\n litellm: \"gpt-4o\",\n test: \"test-model\",\n};\n\n/**\n * Get the default model for a given provider.\n * Returns undefined if the provider is not recognized.\n */\nexport function getProviderDefaultModel(provider: string): string | undefined {\n return PROVIDER_DEFAULT_MODELS[provider];\n}\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ContentBlock,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n// ─── Gemini Message Conversion Helpers ───\n\ntype GeminiPart =\n | { text: string }\n | { functionCall: { name: string; args: unknown } }\n | { functionResponse: { name: string; response: unknown } };\n\ntype GeminiContent = {\n role: \"user\" | \"model\";\n parts: GeminiPart[];\n};\n\nconst toGeminiContents = (messages: readonly LLMMessage[]): GeminiContent[] => {\n const result: GeminiContent[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"system\") continue; // handled via config.systemInstruction\n\n // Handle tool result messages\n if (msg.role === \"tool\") {\n result.push({\n role: \"user\",\n parts: [{\n functionResponse: {\n name: \"tool\",\n response: { content: msg.content },\n },\n }],\n });\n continue;\n }\n\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n\n if (typeof msg.content === \"string\") {\n result.push({ role, parts: [{ text: msg.content }] });\n } else {\n const parts: GeminiPart[] = [];\n for (const block of msg.content as readonly ContentBlock[]) {\n if (block.type === \"text\") {\n parts.push({ text: block.text });\n } else if (block.type === \"tool_use\") {\n parts.push({\n functionCall: { name: block.name, args: block.input },\n });\n } else if (block.type === \"tool_result\") {\n parts.push({\n functionResponse: {\n name: \"tool\",\n response: { content: block.content },\n },\n });\n }\n // images not converted — Gemini multimodal requires separate file URIs\n }\n if (parts.length > 0) {\n result.push({ role, parts });\n }\n }\n }\n\n return result;\n};\n\nconst extractSystemPrompt = (\n messages: readonly LLMMessage[],\n): string | undefined => {\n const sys = messages.find((m) => m.role === \"system\");\n if (!sys) return undefined;\n return typeof sys.content === \"string\" ? sys.content : undefined;\n};\n\nconst toGeminiTools = (\n tools: { name: string; description: string; inputSchema: Record<string, unknown> }[],\n) =>\n tools.length === 0\n ? undefined\n : [\n {\n functionDeclarations: tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: { type: \"object\", ...t.inputSchema },\n })),\n },\n ];\n\nconst toEffectError = (error: unknown): LLMErrors => {\n const err = error as { status?: number; code?: number; message?: string };\n if (err.status === 429 || err.code === 429) {\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider: \"gemini\",\n retryAfterMs: 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider: \"gemini\",\n cause: error,\n });\n};\n\n// ─── Gemini Response Types ───\n\ntype GeminiUsage = {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n totalTokenCount?: number;\n};\n\ntype GeminiFunctionCall = { name: string; args: unknown };\n\ntype GeminiRawResponse = {\n text: string;\n functionCalls?: GeminiFunctionCall[];\n usageMetadata?: GeminiUsage;\n};\n\n// ─── Response Mapper ───\n\nconst mapGeminiResponse = (\n response: GeminiRawResponse,\n model: string,\n): CompletionResponse => {\n const toolCalls = response.functionCalls?.map((fc, i) => ({\n id: `call_${i}`,\n name: fc.name,\n input: fc.args,\n }));\n\n const inputTokens = response.usageMetadata?.promptTokenCount ?? 0;\n const outputTokens = response.usageMetadata?.candidatesTokenCount ?? 0;\n\n return {\n content: response.text ?? \"\",\n stopReason: toolCalls?.length ? \"tool_use\" : \"end_turn\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(inputTokens, outputTokens, model),\n },\n model,\n toolCalls: toolCalls?.length ? toolCalls : undefined,\n };\n};\n\n// ─── Gemini Provider Layer ───\n\nconst GEMINI_DEFAULT_MODEL = \"gemini-2.5-flash\";\n\nexport const GeminiProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n // ─── Lazy-load the SDK via dynamic import (interceptable by mock.module) ───\n\n type GoogleGenAIClient = {\n models: {\n generateContent: (opts: unknown) => Promise<GeminiRawResponse>;\n generateContentStream: (opts: unknown) => Promise<\n AsyncIterable<{\n text: string;\n usageMetadata?: GeminiUsage;\n }>\n >;\n embedContent: (opts: unknown) => Promise<{\n embeddings: Array<{ values: number[] }>;\n }>;\n };\n };\n\n type GoogleGenAIModule = {\n GoogleGenAI: new (opts: { apiKey?: string }) => GoogleGenAIClient;\n };\n\n let _clientPromise: Promise<GoogleGenAIClient> | null = null;\n const getClient = (): Promise<GoogleGenAIClient> => {\n if (!_clientPromise) {\n _clientPromise = (\n import(\"@google/genai\") as Promise<GoogleGenAIModule>\n ).then(({ GoogleGenAI }) => new GoogleGenAI({ apiKey: config.googleApiKey }));\n }\n return _clientPromise;\n };\n\n const buildGeminiConfig = (opts: {\n maxTokens?: number;\n temperature?: number;\n systemPrompt?: string;\n stopSequences?: readonly string[];\n tools?: readonly { name: string; description: string; inputSchema: Record<string, unknown> }[];\n responseMimeType?: string;\n responseSchema?: Record<string, unknown>;\n }) => {\n const cfg: Record<string, unknown> = {\n maxOutputTokens: opts.maxTokens ?? config.defaultMaxTokens,\n temperature: opts.temperature ?? config.defaultTemperature,\n };\n const sys = opts.systemPrompt;\n if (sys) cfg.systemInstruction = sys;\n if (opts.stopSequences?.length) cfg.stopSequences = [...opts.stopSequences];\n if (opts.tools?.length) {\n cfg.tools = toGeminiTools([...opts.tools]);\n }\n if (opts.responseMimeType) cfg.responseMimeType = opts.responseMimeType;\n if (opts.responseSchema) cfg.responseSchema = opts.responseSchema;\n return cfg;\n };\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const client = yield* Effect.promise(() => getClient());\n let model = typeof request.model === 'string' \n ? request.model \n : request.model?.model ?? config.defaultModel;\n // If using non-Gemini default (e.g., Anthropic), fall back to Gemini default\n if (!model || model.startsWith(\"claude\") || model.startsWith(\"gpt-\")) {\n model = GEMINI_DEFAULT_MODEL;\n }\n const contents = toGeminiContents(request.messages);\n const systemPrompt =\n extractSystemPrompt(request.messages) ?? request.systemPrompt;\n\n const response = yield* Effect.tryPromise({\n try: () =>\n client.models.generateContent({\n model,\n contents,\n config: buildGeminiConfig({\n maxTokens: request.maxTokens,\n temperature: request.temperature,\n systemPrompt,\n stopSequences: request.stopSequences,\n tools: request.tools,\n }),\n }),\n catch: toEffectError,\n });\n\n return mapGeminiResponse(response, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"gemini\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n let model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n // If using non-Gemini default (e.g., Anthropic), fall back to Gemini default\n if (!model || model.startsWith(\"claude\") || model.startsWith(\"gpt-\")) {\n model = GEMINI_DEFAULT_MODEL;\n }\n const contents = toGeminiContents(request.messages);\n const systemPrompt =\n extractSystemPrompt(request.messages) ?? request.systemPrompt;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n void (async () => {\n try {\n const client = await getClient();\n const stream = await client.models.generateContentStream({\n model,\n contents,\n config: buildGeminiConfig({\n maxTokens: request.maxTokens,\n temperature: request.temperature,\n systemPrompt,\n }),\n });\n\n let fullContent = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n\n for await (const chunk of stream) {\n if (chunk.text) {\n emit.single({ type: \"text_delta\", text: chunk.text });\n fullContent += chunk.text;\n }\n if (chunk.usageMetadata) {\n inputTokens = chunk.usageMetadata.promptTokenCount ?? 0;\n outputTokens =\n chunk.usageMetadata.candidatesTokenCount ?? 0;\n }\n }\n\n emit.single({ type: \"content_complete\", content: fullContent });\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(inputTokens, outputTokens, model),\n },\n });\n emit.end();\n } catch (error) {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"gemini\",\n cause: error,\n }),\n );\n }\n })();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const jsonSchema = Schema.encodedSchema(request.outputSchema);\n const schemaObj = JSON.parse(JSON.stringify(jsonSchema));\n const schemaStr = JSON.stringify(schemaObj, null, 2);\n\n const client = yield* Effect.promise(() => getClient());\n let model = typeof request.model === 'string'\n ? request.model\n : request.model?.model ?? config.defaultModel;\n if (!model || model.startsWith(\"claude\") || model.startsWith(\"gpt-\")) {\n model = GEMINI_DEFAULT_MODEL;\n }\n\n const messagesWithFormat: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `Respond with JSON matching this schema:\\n${schemaStr}`,\n },\n ];\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messagesWithFormat\n : [\n ...messagesWithFormat,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response did not match the schema. Error: ${String(lastError)}. Please try again.`,\n },\n ];\n\n const response = yield* Effect.tryPromise({\n try: () =>\n client.models.generateContent({\n model,\n contents: toGeminiContents(msgs),\n config: buildGeminiConfig({\n maxTokens: request.maxTokens,\n temperature: request.temperature,\n systemPrompt: request.systemPrompt,\n responseMimeType: \"application/json\",\n responseSchema: schemaObj,\n }),\n }),\n catch: toEffectError,\n });\n\n const mapped = mapGeminiResponse(response, model);\n\n try {\n const parsed = JSON.parse(mapped.content);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const client = await getClient();\n const embeddingModel = model ?? \"gemini-embedding-001\";\n\n const result = await client.models.embedContent({\n model: embeddingModel,\n contents: [...texts],\n config: {\n outputDimensionality: config.embeddingConfig.dimensions,\n },\n });\n\n return result.embeddings.map((e) => e.values);\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"gemini\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"gemini\" as const,\n model: config.defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: false,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n });\n }),\n);\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"../llm-service.js\";\nimport { LLMConfig } from \"../llm-config.js\";\nimport {\n LLMError,\n LLMTimeoutError,\n LLMParseError,\n LLMRateLimitError,\n} from \"../errors.js\";\nimport type { LLMErrors } from \"../errors.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n ToolDefinition,\n ToolCall,\n} from \"../types.js\";\nimport { calculateCost, estimateTokenCount } from \"../token-counter.js\";\nimport { retryPolicy } from \"../retry.js\";\n\n/**\n * LiteLLM Provider — OpenAI-compatible adapter for LiteLLM proxy.\n *\n * LiteLLM is an enterprise model gateway that exposes 100+ LLM providers\n * (Anthropic, OpenAI, Azure, Bedrock, Vertex, etc.) via a single OpenAI-\n * compatible API endpoint.\n *\n * Configuration:\n * LITELLM_BASE_URL=http://localhost:4000 (default)\n * LITELLM_API_KEY=sk-... (optional, for auth)\n *\n * Model names use LiteLLM format: \"provider/model\"\n * e.g. \"anthropic/claude-3-5-sonnet-20241022\", \"openai/gpt-4o\"\n */\n\n// ─── Message Conversion (reuses OpenAI format) ───\n\ntype LiteLLMMessage =\n | { role: \"system\" | \"user\" | \"assistant\"; content: string }\n | { role: \"tool\"; tool_call_id: string; content: string };\n\nconst toLiteLLMMessages = (\n messages: readonly LLMMessage[],\n): LiteLLMMessage[] =>\n messages.map((m) => {\n if (m.role === \"tool\") {\n return {\n role: \"tool\" as const,\n tool_call_id: m.toolCallId,\n content: m.content,\n };\n }\n return {\n role: m.role as \"system\" | \"user\" | \"assistant\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : (m.content as readonly { type: string; text?: string }[])\n .filter(\n (b): b is { type: \"text\"; text: string } => b.type === \"text\",\n )\n .map((b) => b.text)\n .join(\"\"),\n };\n });\n\nconst toEffectError = (error: unknown): LLMErrors => {\n const err = error as { status?: number; message?: string };\n if (err.status === 429) {\n return new LLMRateLimitError({\n message: err.message ?? \"Rate limit exceeded\",\n provider: \"litellm\",\n retryAfterMs: 60_000,\n });\n }\n return new LLMError({\n message: err.message ?? String(error),\n provider: \"litellm\",\n cause: error,\n });\n};\n\nconst toLiteLLMTool = (tool: ToolDefinition) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n});\n\n// ─── Response Types ───\n\ntype LiteLLMToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\ntype LiteLLMRawResponse = {\n choices: Array<{\n message: {\n content: string | null;\n role: string;\n tool_calls?: LiteLLMToolCall[];\n };\n finish_reason: string;\n }>;\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n model: string;\n};\n\nconst mapLiteLLMResponse = (\n response: LiteLLMRawResponse,\n model: string,\n): CompletionResponse => {\n const message = response.choices[0]?.message;\n const content = message?.content ?? \"\";\n const rawToolCalls = message?.tool_calls;\n const hasToolCalls = rawToolCalls && rawToolCalls.length > 0;\n\n const stopReason =\n response.choices[0]?.finish_reason === \"tool_calls\" || hasToolCalls\n ? (\"tool_use\" as const)\n : response.choices[0]?.finish_reason === \"stop\"\n ? (\"end_turn\" as const)\n : response.choices[0]?.finish_reason === \"length\"\n ? (\"max_tokens\" as const)\n : (\"end_turn\" as const);\n\n const toolCalls: ToolCall[] | undefined = hasToolCalls\n ? rawToolCalls.map((tc) => {\n let input: unknown;\n try {\n input = JSON.parse(tc.function.arguments);\n } catch {\n input = { raw: tc.function.arguments };\n }\n return { id: tc.id, name: tc.function.name, input };\n })\n : undefined;\n\n return {\n content,\n stopReason,\n usage: {\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n totalTokens: response.usage?.total_tokens ?? 0,\n estimatedCost: calculateCost(\n response.usage?.prompt_tokens ?? 0,\n response.usage?.completion_tokens ?? 0,\n model,\n ),\n },\n model: response.model ?? model,\n toolCalls,\n };\n};\n\n// ─── Fetch helper ───\n\nconst liteLLMFetch = async (\n baseURL: string,\n path: string,\n body: unknown,\n apiKey?: string,\n): Promise<unknown> => {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`;\n\n const res = await fetch(`${baseURL}${path}`, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n });\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n throw Object.assign(\n new Error(`LiteLLM ${res.status}: ${text || res.statusText}`),\n { status: res.status },\n );\n }\n\n return res.json();\n};\n\n// ─── LiteLLM Provider Layer ───\n\nexport const LiteLLMProviderLive = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const config = yield* LLMConfig;\n\n const baseURL =\n (config as unknown as { litellmBaseUrl?: string }).litellmBaseUrl ??\n process.env.LITELLM_BASE_URL ??\n \"http://localhost:4000\";\n const apiKey =\n (config as unknown as { litellmApiKey?: string }).litellmApiKey ??\n process.env.LITELLM_API_KEY ??\n undefined;\n\n const defaultModel = config.defaultModel;\n\n return LLMService.of({\n complete: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : request.model?.model ?? defaultModel;\n\n const messages = toLiteLLMMessages(request.messages);\n if (request.systemPrompt) {\n messages.unshift({ role: \"system\", content: request.systemPrompt });\n }\n\n const requestBody: Record<string, unknown> = {\n model,\n max_tokens: request.maxTokens ?? config.defaultMaxTokens,\n temperature: request.temperature ?? config.defaultTemperature,\n messages,\n stop: request.stopSequences\n ? [...request.stopSequences]\n : undefined,\n };\n\n if (request.tools && request.tools.length > 0) {\n requestBody.tools = request.tools.map(toLiteLLMTool);\n }\n\n const response = yield* Effect.tryPromise({\n try: () =>\n liteLLMFetch(baseURL, \"/chat/completions\", requestBody, apiKey),\n catch: (error) => toEffectError(error),\n });\n\n return mapLiteLLMResponse(response as LiteLLMRawResponse, model);\n }).pipe(\n Effect.retry(retryPolicy),\n Effect.timeout(\"30 seconds\"),\n Effect.catchTag(\"TimeoutException\", () =>\n Effect.fail(\n new LLMTimeoutError({\n message: \"LLM request timed out\",\n provider: \"litellm\",\n timeoutMs: 30_000,\n }),\n ),\n ),\n ),\n\n stream: (request) =>\n Effect.gen(function* () {\n const model =\n typeof request.model === \"string\"\n ? request.model\n : request.model?.model ?? defaultModel;\n\n return Stream.async<StreamEvent, LLMErrors>((emit) => {\n const doStream = async () => {\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`;\n\n const messages = toLiteLLMMessages(request.messages);\n if (request.systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: request.systemPrompt,\n });\n }\n\n const res = await fetch(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n model,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature:\n request.temperature ?? config.defaultTemperature,\n messages,\n stream: true,\n }),\n });\n\n if (!res.ok || !res.body) {\n throw new Error(`LiteLLM stream error: ${res.status}`);\n }\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let fullContent = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n const data = trimmed.slice(5).trim();\n if (data === \"[DONE]\") {\n emit.single({\n type: \"content_complete\",\n content: fullContent,\n });\n emit.end();\n return;\n }\n\n try {\n const chunk = JSON.parse(data) as {\n choices: Array<{\n delta: { content?: string };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n };\n };\n\n const delta = chunk.choices[0]?.delta?.content;\n if (delta) {\n fullContent += delta;\n emit.single({ type: \"text_delta\", text: delta });\n }\n\n if (chunk.choices[0]?.finish_reason) {\n const inputTokens =\n chunk.usage?.prompt_tokens ?? 0;\n const outputTokens =\n chunk.usage?.completion_tokens ?? 0;\n emit.single({\n type: \"usage\",\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: calculateCost(\n inputTokens,\n outputTokens,\n model,\n ),\n },\n });\n }\n } catch {\n // Skip invalid JSON chunks\n }\n }\n }\n } catch (error) {\n const err = error as { message?: string };\n emit.fail(\n new LLMError({\n message: err.message ?? String(error),\n provider: \"litellm\",\n cause: error,\n }),\n );\n }\n };\n void doStream();\n });\n }),\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const schemaStr = JSON.stringify(\n Schema.encodedSchema(request.outputSchema),\n null,\n 2,\n );\n\n const messagesWithFormat: LLMMessage[] = [\n ...request.messages,\n {\n role: \"user\" as const,\n content: `\\nRespond with ONLY valid JSON matching this schema:\\n${schemaStr}\\n\\nNo markdown, no code fences, just raw JSON.`,\n },\n ];\n\n let lastError: unknown = null;\n const maxRetries = request.maxParseRetries ?? 2;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const msgs =\n attempt === 0\n ? messagesWithFormat\n : [\n ...messagesWithFormat,\n {\n role: \"assistant\" as const,\n content: String(lastError),\n },\n {\n role: \"user\" as const,\n content: `That response was not valid JSON. The parse error was: ${String(lastError)}. Please try again with valid JSON only.`,\n },\n ];\n\n const model =\n typeof request.model === \"string\"\n ? request.model\n : request.model?.model ?? defaultModel;\n\n const completeResult = yield* Effect.tryPromise({\n try: () =>\n liteLLMFetch(\n baseURL,\n \"/chat/completions\",\n {\n model,\n max_tokens:\n request.maxTokens ?? config.defaultMaxTokens,\n temperature:\n request.temperature ?? config.defaultTemperature,\n messages: toLiteLLMMessages(msgs),\n },\n apiKey,\n ),\n catch: (error) => toEffectError(error),\n });\n\n const response = mapLiteLLMResponse(\n completeResult as LiteLLMRawResponse,\n model,\n );\n\n try {\n const parsed = JSON.parse(response.content);\n const decoded = Schema.decodeUnknownEither(\n request.outputSchema,\n )(parsed);\n\n if (decoded._tag === \"Right\") {\n return decoded.right;\n }\n lastError = decoded.left;\n } catch (e) {\n lastError = e;\n }\n }\n\n return yield* Effect.fail(\n new LLMParseError({\n message: `Failed to parse structured output after ${maxRetries + 1} attempts`,\n rawOutput: String(lastError),\n expectedSchema: schemaStr,\n }),\n );\n }),\n\n embed: (texts, model) =>\n Effect.tryPromise({\n try: async () => {\n const embeddingModel =\n model ?? config.embeddingConfig.model;\n const batchSize = config.embeddingConfig.batchSize ?? 100;\n const results: number[][] = [];\n\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize);\n const response = (await liteLLMFetch(\n baseURL,\n \"/embeddings\",\n {\n model: embeddingModel,\n input: [...batch],\n dimensions: config.embeddingConfig.dimensions,\n },\n apiKey,\n )) as { data: Array<{ embedding: number[] }> };\n\n results.push(\n ...response.data.map((d) => d.embedding),\n );\n }\n\n return results;\n },\n catch: (error) =>\n new LLMError({\n message: `Embedding failed: ${error}`,\n provider: \"litellm\",\n cause: error,\n }),\n }),\n\n countTokens: (messages) =>\n Effect.gen(function* () {\n return yield* estimateTokenCount(messages);\n }),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"litellm\" as const,\n model: defaultModel,\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: false,\n jsonSchemaEnforcement: false,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n });\n }),\n);\n","import { Effect, Layer, Stream, Schema } from \"effect\";\nimport { LLMService } from \"./llm-service.js\";\nimport type {\n CompletionResponse,\n StreamEvent,\n LLMMessage,\n} from \"./types.js\";\nimport type { LLMErrors } from \"./errors.js\";\n\n/**\n * Create a deterministic test LLM service.\n * Returns responses based on pattern matching against prompt content.\n *\n * Usage:\n * ```ts\n * const layer = TestLLMServiceLayer({\n * \"capital of France\": \"Paris\",\n * \"plan\": '{\"goal\":\"test\",\"steps\":[]}',\n * });\n * ```\n */\nexport const TestLLMService = (\n responses: Record<string, string>,\n): typeof LLMService.Service => ({\n complete: (request) =>\n Effect.gen(function* () {\n const lastMessage = request.messages[request.messages.length - 1];\n const content =\n lastMessage && typeof lastMessage.content === \"string\"\n ? lastMessage.content\n : \"\";\n\n // Also check systemPrompt for pattern matching\n const systemPrompt =\n typeof (request as any).systemPrompt === \"string\"\n ? (request as any).systemPrompt\n : \"\";\n const searchText = `${content} ${systemPrompt}`;\n\n // Match against registered patterns\n for (const [pattern, response] of Object.entries(responses)) {\n if (pattern.length > 0 && searchText.includes(pattern)) {\n return {\n content: response,\n stopReason: \"end_turn\" as const,\n usage: {\n inputTokens: Math.ceil(content.length / 4),\n outputTokens: Math.ceil(response.length / 4),\n totalTokens:\n Math.ceil(content.length / 4) +\n Math.ceil(response.length / 4),\n estimatedCost: 0,\n },\n model: \"test-model\",\n } satisfies CompletionResponse;\n }\n }\n\n // Default response\n return {\n content: \"Test response\",\n stopReason: \"end_turn\" as const,\n usage: {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n estimatedCost: 0,\n },\n model: \"test-model\",\n } satisfies CompletionResponse;\n }),\n\n stream: (request) => {\n const lastMessage = request.messages[request.messages.length - 1];\n const content =\n lastMessage && typeof lastMessage.content === \"string\"\n ? lastMessage.content\n : \"\";\n\n // Also check systemPrompt for pattern matching (mirrors complete() logic)\n const systemPrompt =\n typeof (request as any).systemPrompt === \"string\"\n ? (request as any).systemPrompt\n : \"\";\n const searchText = `${content} ${systemPrompt}`;\n\n // Match against registered patterns\n let matchedResponse = \"Test response\";\n for (const [pattern, response] of Object.entries(responses)) {\n if (pattern.length > 0 && searchText.includes(pattern)) {\n matchedResponse = response;\n break;\n }\n }\n\n const inputTokens = Math.ceil(content.length / 4);\n const outputTokens = Math.ceil(matchedResponse.length / 4);\n\n return Effect.succeed(\n Stream.make(\n {\n type: \"text_delta\" as const,\n text: matchedResponse,\n } satisfies StreamEvent,\n {\n type: \"content_complete\" as const,\n content: matchedResponse,\n } satisfies StreamEvent,\n {\n type: \"usage\" as const,\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n estimatedCost: 0,\n },\n } satisfies StreamEvent,\n ) as Stream.Stream<StreamEvent, LLMErrors>,\n );\n },\n\n completeStructured: (request) =>\n Effect.gen(function* () {\n const lastMessage = request.messages[request.messages.length - 1];\n const content =\n lastMessage && typeof lastMessage.content === \"string\"\n ? lastMessage.content\n : \"\";\n\n // Try to find a matching response\n let responseContent = \"Test response\";\n for (const [pattern, response] of Object.entries(responses)) {\n if (content.includes(pattern)) {\n responseContent = response;\n break;\n }\n }\n\n const parsed = JSON.parse(responseContent);\n return Schema.decodeUnknownSync(request.outputSchema)(parsed);\n }),\n\n embed: (texts) =>\n Effect.succeed(\n texts.map(() => new Array(768).fill(0).map(() => Math.random())),\n ),\n\n countTokens: (messages) =>\n Effect.succeed(\n messages.reduce(\n (sum, m) =>\n sum +\n (typeof m.content === \"string\"\n ? Math.ceil(m.content.length / 4)\n : 100),\n 0,\n ),\n ),\n\n getModelConfig: () =>\n Effect.succeed({\n provider: \"anthropic\" as const,\n model: \"test-model\",\n }),\n\n getStructuredOutputCapabilities: () =>\n Effect.succeed({\n nativeJsonMode: true,\n jsonSchemaEnforcement: false,\n prefillSupport: false,\n grammarConstraints: false,\n }),\n});\n\n/**\n * Create a test Layer for LLMService with optional pattern-matched responses.\n */\nexport const TestLLMServiceLayer = (\n responses: Record<string, string> = {},\n) => Layer.succeed(LLMService, LLMService.of(TestLLMService(responses)));\n","import { Schema } from \"effect\";\n\n// ─── Common Schemas for Reasoning Strategies ───\n\n/**\n * Schema for ReAct action parsing.\n */\nexport const ReActActionSchema = Schema.Struct({\n thought: Schema.String,\n action: Schema.optional(\n Schema.Struct({\n tool: Schema.String,\n input: Schema.Unknown,\n }),\n ),\n finalAnswer: Schema.optional(Schema.String),\n isComplete: Schema.Boolean,\n});\n\nexport type ReActAction = Schema.Schema.Type<typeof ReActActionSchema>;\n\n/**\n * Schema for plan generation.\n */\nexport const PlanSchema = Schema.Struct({\n goal: Schema.String,\n steps: Schema.Array(\n Schema.Struct({\n id: Schema.Number,\n description: Schema.String,\n tool: Schema.optional(Schema.String),\n dependsOn: Schema.optional(Schema.Array(Schema.Number)),\n estimatedDuration: Schema.optional(Schema.String),\n }),\n ),\n});\n\nexport type Plan = Schema.Schema.Type<typeof PlanSchema>;\n\n/**\n * Schema for reflection output.\n */\nexport const ReflectionSchema = Schema.Struct({\n taskAccomplished: Schema.Boolean,\n confidence: Schema.Number,\n strengths: Schema.Array(Schema.String),\n weaknesses: Schema.Array(Schema.String),\n needsRefinement: Schema.Boolean,\n refinementSuggestions: Schema.optional(Schema.Array(Schema.String)),\n});\n\nexport type Reflection = Schema.Schema.Type<typeof ReflectionSchema>;\n\n/**\n * Schema for strategy selection.\n */\nexport const StrategySelectionSchema = Schema.Struct({\n selectedStrategy: Schema.String,\n reasoning: Schema.String,\n confidence: Schema.Number,\n alternativeStrategies: Schema.Array(\n Schema.Struct({\n strategy: Schema.String,\n whyNot: Schema.String,\n }),\n ),\n});\n\nexport type StrategySelection = Schema.Schema.Type<\n typeof StrategySelectionSchema\n>;\n\n/**\n * Schema for thought evaluation (Tree-of-Thought).\n */\nexport const ThoughtEvaluationSchema = Schema.Struct({\n score: Schema.Number,\n reasoning: Schema.String,\n strengths: Schema.Array(Schema.String),\n weaknesses: Schema.Array(Schema.String),\n shouldExpand: Schema.Boolean,\n});\n\nexport type ThoughtEvaluation = Schema.Schema.Type<\n typeof ThoughtEvaluationSchema\n>;\n\n/**\n * Schema for task complexity analysis.\n */\nexport const ComplexityAnalysisSchema = Schema.Struct({\n score: Schema.Number,\n factors: Schema.Array(\n Schema.Struct({\n factor: Schema.String,\n weight: Schema.Number,\n reasoning: Schema.String,\n }),\n ),\n recommendedStrategy: Schema.String,\n recommendedModel: Schema.String,\n});\n\nexport type ComplexityAnalysis = Schema.Schema.Type<\n typeof ComplexityAnalysisSchema\n>;\n","import { Effect, Layer } from \"effect\";\nimport { LLMConfig, LLMConfigFromEnv, llmConfigFromEnv } from \"./llm-config.js\";\nimport { LLMService } from \"./llm-service.js\";\nimport { AnthropicProviderLive } from \"./providers/anthropic.js\";\nimport { OpenAIProviderLive } from \"./providers/openai.js\";\nimport { LocalProviderLive } from \"./providers/local.js\";\nimport { GeminiProviderLive } from \"./providers/gemini.js\";\nimport { LiteLLMProviderLive } from \"./providers/litellm.js\";\nimport { PromptManagerLive } from \"./prompt-manager.js\";\nimport { TestLLMServiceLayer } from \"./testing.js\";\nimport { makeEmbeddingCache } from \"./embedding-cache.js\";\nimport { makeCircuitBreaker } from \"./circuit-breaker.js\";\nimport type { CircuitBreakerConfig } from \"./retry.js\";\n\n/**\n * Layer that wraps the underlying LLMService.embed() with a content-hash\n * deduplication cache. Identical texts get cached embeddings without an API call.\n */\nconst EmbeddingCacheLayer = Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const llm = yield* LLMService;\n const cache = makeEmbeddingCache(llm.embed);\n return LLMService.of({ ...llm, embed: cache.embed });\n }),\n);\n\n/**\n * Layer that wraps LLMService.complete() and stream() with a circuit breaker.\n * After N consecutive failures, fast-fails without hitting the provider.\n */\nconst makeCircuitBreakerLayer = (config?: Partial<CircuitBreakerConfig>) =>\n Layer.effect(\n LLMService,\n Effect.gen(function* () {\n const llm = yield* LLMService;\n const breaker = makeCircuitBreaker(config);\n return LLMService.of({\n ...llm,\n complete: (req) => breaker.protect(llm.complete(req)),\n stream: (req) => breaker.protect(llm.stream(req)),\n });\n }),\n );\n/**\n * Create the LLM provider layer for a specific provider.\n * Uses env vars for configuration by default.\n */\nexport const createLLMProviderLayer = (\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"gemini\" | \"litellm\" | \"test\" = \"anthropic\",\n testResponses?: Record<string, string>,\n model?: string,\n modelParams?: { thinking?: boolean; temperature?: number; maxTokens?: number },\n circuitBreaker?: Partial<CircuitBreakerConfig>,\n) => {\n if (provider === \"test\") {\n return Layer.mergeAll(\n TestLLMServiceLayer(testResponses ?? {}),\n PromptManagerLive,\n );\n }\n\n const configOverrides: Record<string, unknown> = {};\n if (model) configOverrides.defaultModel = model;\n if (modelParams?.thinking !== undefined) configOverrides.thinking = modelParams.thinking;\n if (modelParams?.temperature !== undefined) configOverrides.defaultTemperature = modelParams.temperature;\n if (modelParams?.maxTokens !== undefined) configOverrides.defaultMaxTokens = modelParams.maxTokens;\n\n const configLayer = Object.keys(configOverrides).length > 0\n ? Layer.succeed(LLMConfig, LLMConfig.of({ ...llmConfigFromEnv, ...configOverrides }))\n : LLMConfigFromEnv;\n\n const providerLayer =\n provider === \"anthropic\"\n ? AnthropicProviderLive\n : provider === \"openai\"\n ? OpenAIProviderLive\n : provider === \"gemini\"\n ? GeminiProviderLive\n : provider === \"litellm\"\n ? LiteLLMProviderLive\n : LocalProviderLive;\n\n const baseProviderLayer = providerLayer.pipe(Layer.provide(configLayer));\n\n // Stack: provider → circuit breaker (optional) → embedding cache\n let llmLayer = EmbeddingCacheLayer.pipe(Layer.provide(baseProviderLayer));\n if (circuitBreaker) {\n llmLayer = EmbeddingCacheLayer.pipe(\n Layer.provide(makeCircuitBreakerLayer(circuitBreaker).pipe(Layer.provide(baseProviderLayer))),\n );\n }\n\n return Layer.mergeAll(llmLayer, PromptManagerLive);\n};\n\n/**\n * LLM layer with custom config (for programmatic use).\n */\nexport const createLLMProviderLayerWithConfig = (\n config: typeof LLMConfig.Service,\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"gemini\" | \"litellm\" = \"anthropic\",\n) => {\n const configLayer = Layer.succeed(LLMConfig, config);\n\n const providerLayer =\n provider === \"anthropic\"\n ? AnthropicProviderLive\n : provider === \"openai\"\n ? OpenAIProviderLive\n : provider === \"gemini\"\n ? GeminiProviderLive\n : provider === \"litellm\"\n ? LiteLLMProviderLive\n : LocalProviderLive;\n\n const baseProviderLayer = providerLayer.pipe(Layer.provide(configLayer));\n\n return Layer.mergeAll(\n EmbeddingCacheLayer.pipe(Layer.provide(baseProviderLayer)),\n PromptManagerLive,\n );\n};\n","// File: src/embedding-cache.ts\n/**\n * Content-hash embedding cache — deduplicates embed() calls per text.\n * Cache is keyed by Bun.hash(text) and avoids re-embedding identical strings.\n */\nimport { Effect } from \"effect\";\nimport type { LLMErrors } from \"./errors.js\";\n\nconst MAX_ENTRIES = 5_000;\n\nexport interface EmbeddingCache {\n /** Wrap an embed function with content-hash deduplication. */\n readonly embed: (\n texts: readonly string[],\n model?: string,\n ) => Effect.Effect<readonly (readonly number[])[], LLMErrors>;\n /** Number of cached embeddings. */\n readonly size: () => number;\n /** Clear all cached entries. */\n readonly clear: () => void;\n}\n\n/**\n * Create an embedding cache that wraps an underlying embed function.\n * Each text is hashed individually; only cache-misses are sent to the LLM.\n */\nexport const makeEmbeddingCache = (\n underlying: (\n texts: readonly string[],\n model?: string,\n ) => Effect.Effect<readonly (readonly number[])[], LLMErrors>,\n): EmbeddingCache => {\n // Per-model caches to avoid collisions between models with different dimensions\n const caches = new Map<string, Map<string, readonly number[]>>();\n\n const getModelCache = (model: string): Map<string, readonly number[]> => {\n let c = caches.get(model);\n if (!c) {\n c = new Map();\n caches.set(model, c);\n }\n return c;\n };\n\n const evictIfNeeded = (cache: Map<string, readonly number[]>) => {\n if (cache.size > MAX_ENTRIES) {\n // Evict oldest 20%\n const evictCount = Math.floor(MAX_ENTRIES * 0.2);\n const keys = cache.keys();\n for (let i = 0; i < evictCount; i++) {\n const next = keys.next();\n if (next.done) break;\n cache.delete(next.value);\n }\n }\n };\n\n return {\n embed: (texts, model) =>\n Effect.gen(function* () {\n const modelKey = model ?? \"__default__\";\n const cache = getModelCache(modelKey);\n\n // Partition into hits and misses\n const results: (readonly number[] | null)[] = new Array(texts.length);\n const misses: { index: number; text: string }[] = [];\n\n for (let i = 0; i < texts.length; i++) {\n const hash = Bun.hash(texts[i]!).toString(36);\n const cached = cache.get(hash);\n if (cached) {\n results[i] = cached;\n } else {\n results[i] = null;\n misses.push({ index: i, text: texts[i]! });\n }\n }\n\n // All cached — skip LLM call entirely\n if (misses.length === 0) {\n return results as readonly (readonly number[])[];\n }\n\n // Call underlying for misses only\n const missTexts = misses.map((m) => m.text);\n const embeddings = yield* underlying(missTexts, model);\n\n // Store in cache\n for (let j = 0; j < misses.length; j++) {\n const { index, text } = misses[j]!;\n const embedding = embeddings[j]!;\n const hash = Bun.hash(text).toString(36);\n cache.set(hash, embedding);\n results[index] = embedding;\n }\n\n evictIfNeeded(cache);\n return results as readonly (readonly number[])[];\n }),\n\n size: () => {\n let total = 0;\n for (const c of caches.values()) total += c.size;\n return total;\n },\n\n clear: () => caches.clear(),\n };\n};\n","// File: src/circuit-breaker.ts\n/**\n * Circuit Breaker — prevents cascading failures by fast-failing when\n * the underlying LLM provider is consistently erroring.\n *\n * States: CLOSED (normal) → OPEN (fast-fail) → HALF_OPEN (test one request)\n */\nimport { Effect } from \"effect\";\nimport type { LLMErrors } from \"./errors.js\";\nimport { LLMError } from \"./errors.js\";\nimport type { CircuitBreakerConfig } from \"./retry.js\";\nimport { defaultCircuitBreakerConfig } from \"./retry.js\";\n\ntype State = \"closed\" | \"open\" | \"half_open\";\n\nexport interface CircuitBreaker {\n /** Wrap an Effect with circuit breaker protection. */\n readonly protect: <A>(effect: Effect.Effect<A, LLMErrors>) => Effect.Effect<A, LLMErrors>;\n /** Current state. */\n readonly state: () => State;\n /** Reset to closed. */\n readonly reset: () => void;\n}\n\n/**\n * Create a circuit breaker with configurable thresholds.\n *\n * - After `failureThreshold` consecutive failures → OPEN (fast-fail).\n * - After `cooldownMs` → HALF_OPEN (allow one test request).\n * - If test request succeeds → CLOSED. If it fails → OPEN again.\n */\nexport const makeCircuitBreaker = (\n config: Partial<CircuitBreakerConfig> = {},\n): CircuitBreaker => {\n const { failureThreshold, cooldownMs } = {\n ...defaultCircuitBreakerConfig,\n ...config,\n };\n\n let currentState: State = \"closed\";\n let consecutiveFailures = 0;\n let openedAt = 0;\n\n const onSuccess = () => {\n consecutiveFailures = 0;\n currentState = \"closed\";\n };\n\n const onFailure = () => {\n consecutiveFailures++;\n if (consecutiveFailures >= failureThreshold) {\n currentState = \"open\";\n openedAt = Date.now();\n }\n };\n\n return {\n protect: <A>(effect: Effect.Effect<A, LLMErrors>) =>\n Effect.gen(function* () {\n if (currentState === \"open\") {\n if (Date.now() - openedAt >= cooldownMs) {\n currentState = \"half_open\";\n } else {\n return yield* Effect.fail(\n new LLMError({\n message: `Circuit breaker OPEN — ${consecutiveFailures} consecutive failures. Retry after ${Math.ceil((cooldownMs - (Date.now() - openedAt)) / 1000)}s cooldown.`,\n provider: \"custom\",\n cause: undefined,\n }),\n );\n }\n }\n\n const result = yield* Effect.exit(effect);\n if (result._tag === \"Success\") {\n onSuccess();\n return result.value;\n }\n\n onFailure();\n return yield* Effect.failCause(result.cause);\n }),\n\n state: () => currentState,\n\n reset: () => {\n currentState = \"closed\";\n consecutiveFailures = 0;\n openedAt = 0;\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,SAAS,WAAW,KAAK;AACvB,SAAO,OAAO,SAAS,UAAU,cAAc,GAAG;AACpD;AAsBA,SAAS,cAAc,MAAM;AAC3B,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO,OAAO,IAAI;AAAA,EACpB;AACA,MAAI,6BAA6B,KAAK,IAAI,KAAK,SAAS,IAAI;AAC1D,UAAM,IAAI,UAAU,8CAA8C,OAAO,GAAG;AAAA,EAC9E;AACA,SAAO,KAAK,YAAY;AAC1B;AAEA,SAAS,eAAe,OAAO;AAC7B,MAAI,OAAO,UAAU,UAAU;AAC7B,YAAQ,OAAO,KAAK;AAAA,EACtB;AACA,SAAO;AACT;AAGA,SAAS,YAAY,OAAO;AAC1B,MAAI,WAAW;AAAA,IACb,MAAM,WAAW;AACf,UAAI,QAAQ,MAAM,MAAM;AACxB,aAAO,EAAC,MAAM,UAAU,QAAW,MAAY;AAAA,IACjD;AAAA,EACF;AAEA,MAAI,QAAQ,UAAU;AACpB,aAAS,OAAO,QAAQ,IAAI,WAAW;AACrC,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAASA,SAAQ,SAAS;AAC/B,OAAK,MAAM,CAAC;AAEZ,MAAI,mBAAmBA,UAAS;AAC9B,YAAQ,QAAQ,SAAS,OAAO,MAAM;AACpC,WAAK,OAAO,MAAM,KAAK;AAAA,IACzB,GAAG,IAAI;AAAA,EAC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oBAAoB,KAAKA,OAAM,QAAQ,iBAAiB,CAAC;AACxE,MAAI,gBAAgB;AAClB,eAAW,oBAAoB;AAAA,MAC7BA,OAAM,QAAQ,wBAAwB,cAAc,EAAE,KAAKA,OAAM,QAAQ,iBAAiB,CAAC,CAAC;AAAA,IAC9F;AAAA,EACF;AAEA,SAAOA,OAAM,SAAS,UAAU,iBAAiB;AACnD;AAKO,IAAM,mCAAmC,CAC9C,QACA,WAAqE,gBAClE;AACH,QAAM,cAAcA,OAAM,QAAQ,WAAW,MAAM;AAEnD,QAAM,gBACJ,aAAa,cACT,wBACA,aAAa,WACX,qBACA,aAAa,WACX,qBACA,aAAa,YACX,sBACA;AAEZ,QAAM,oBAAoB,cAAc,KAAKA,OAAM,QAAQ,WAAW,CAAC;AAEvE,SAAOA,OAAM;AAAA,IACX,oBAAoB,KAAKA,OAAM,QAAQ,iBAAiB,CAAC;AAAA,IACzD;AAAA,EACF;AACF;","names":["Headers","resolve","fetch","__defProp","fetch","Ollama","Context","Effect","Context","Layer","Effect","Context","Layer","Effect","Effect","Layer","Schema","Layer","Effect","Schema","Effect","Layer","Stream","Schema","toEffectError","Layer","Effect","Stream","Schema","Effect","Layer","Stream","Schema","Layer","Effect","Ollama","Stream","Schema","Effect","Layer","Stream","Schema","toEffectError","Layer","Effect","Stream","Schema","Effect","Layer","Stream","Schema","toEffectError","Layer","Effect","Stream","Schema","Effect","Layer","Stream","Schema","Effect","Stream","Schema","Layer","Schema","Effect","Layer","Effect","index","Effect","Effect","Layer","Effect"]}
|