@nemesis-oss/ollama-sdk 1.23.0 → 1.24.1
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/CHANGELOG.md +36 -1
- package/dist/{anthropic-DjdkzlIn.d.ts → anthropic-Czz0OKH-.d.ts} +1 -1
- package/dist/{anthropic-D8qPCPIr.d.cts → anthropic-Dfa6TV9C.d.cts} +1 -1
- package/dist/{compose-BXXgHmrS.d.cts → compose-Bjpsu3Y1.d.cts} +1 -1
- package/dist/{compose-DaG83yId.d.ts → compose-DxAQ2z26.d.ts} +1 -1
- package/dist/generated-api.d.cts +5 -5
- package/dist/generated-api.d.ts +5 -5
- package/dist/generated-runtime.cjs.map +1 -1
- package/dist/generated-runtime.d.cts +2 -2
- package/dist/generated-runtime.d.ts +2 -2
- package/dist/generated-runtime.js.map +1 -1
- package/dist/index.cjs +456 -104
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -9
- package/dist/index.d.ts +25 -9
- package/dist/index.js +456 -104
- package/dist/index.js.map +1 -1
- package/dist/mcp-generated.d.cts +2 -2
- package/dist/mcp-generated.d.ts +2 -2
- package/dist/mcp-http.cjs.map +1 -1
- package/dist/mcp-http.js.map +1 -1
- package/dist/{runtime-CpO3H6yy.d.cts → runtime-CUzw4GAE.d.cts} +1 -1
- package/dist/{runtime-DPSrPwAa.d.ts → runtime-D_rMXIVT.d.ts} +1 -1
- package/dist/skills.d.cts +3 -3
- package/dist/skills.d.ts +3 -3
- package/dist/{types-CnsZ24tm.d.cts → types-CH3pdrak.d.cts} +124 -18
- package/dist/{types-CnsZ24tm.d.ts → types-CH3pdrak.d.ts} +124 -18
- package/package.json +11 -10
package/dist/mcp-generated.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as McpToolDescriptor } from './types-CI-gM2u5.cjs';
|
|
2
|
-
import { O as OllamaRuntime } from './runtime-
|
|
2
|
+
import { O as OllamaRuntime } from './runtime-CUzw4GAE.cjs';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import './types-
|
|
4
|
+
import './types-CH3pdrak.cjs';
|
|
5
5
|
|
|
6
6
|
interface GeneratedToolEntry extends McpToolDescriptor {
|
|
7
7
|
readonly _operationId: string;
|
package/dist/mcp-generated.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as McpToolDescriptor } from './types-CI-gM2u5.js';
|
|
2
|
-
import { O as OllamaRuntime } from './runtime-
|
|
2
|
+
import { O as OllamaRuntime } from './runtime-D_rMXIVT.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import './types-
|
|
4
|
+
import './types-CH3pdrak.js';
|
|
5
5
|
|
|
6
6
|
interface GeneratedToolEntry extends McpToolDescriptor {
|
|
7
7
|
readonly _operationId: string;
|
package/dist/mcp-http.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/client-options.ts","../src/mcp/http.ts"],"names":["request"],"mappings":";;;AA2BO,SAAS,2BAAA,CACd,QACA,QAAA,EACM;AACN,EAAA,IAAI,aAAa,MAAA,EAAW;AAE5B,EAAA,MAAM,YAAA,GAAe,SAAS,IAAA,KAAS,MAAA;AACvC,EAAA,MAAM,WAAA,GAAc,SAAS,GAAA,KAAQ,MAAA;AACrC,EAAA,IAAI,CAAC,YAAA,IAAgB,CAAC,WAAA,EAAa;AACjC,IAAA,MAAM,IAAI,UAAU,uDAAuD,CAAA;AAAA,EAC7E;AACA,EAAA,IAAI,MAAA,CAAO,oBAAA,KAAyB,MAAA,IAAa,MAAA,CAAO,sBAAsB,MAAA,EAAW;AACvF,IAAA,MAAM,IAAI,SAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,MAAA,CAAO,oBAAA,CAAqB;AAAA,IAC1B,WAAA,EAAa;AAAA,MACX,GAAI,YAAA,GAAe,EAAE,MAAM,EAAC,KAAM,EAAC;AAAA,MACnC,GAAI,WAAA,GAAc,EA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AM,IAAA,GAAO,QAAQ,SAAA,IAAa,iBAAA;AAClC,EAAA,IAAI,SAAS,MAAA,EAAQ;AACnB,IAAA,OAAO,qBAAqB,IAAA,EAAM,GAAA,EAAK,OAAA,EAAS,MAAM,kBAAkB,CAAA;AAAA,EAC1E;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,gBAAA,EAAiB;AACvC,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,oBAAA,CAAqB,iBAAA,EAAmB,GAAA,EAAK,SAAS,OAAO,CAAA;AAAA,EAC5E,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,CAAC,mBAAA,CAAoB,KAAK,CAAA,EAAG,MAAM,KAAA;AACvC,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,oBAAA,CAAqB,KAAA,EAAO,GAAA,EAAK,SAAS,OAAO,CAAA;AAAA,IAChE,SAAS,QAAA,EAAU;AACjB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,8EAAA;AAAA,QACA,EAAE,OAAO,QAAA;AAAS,OACpB;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,+BACpB,OAAA,EAC4B;AAC5B,EAAA,OAAO,qBAAqB,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,mBAAmB,CAAA;AAC1E;AAEA,eAAsB,oBACpB,OAAA,EAC4B;AAC5B,EAAA,OAAO,qBAAqB,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,OAAO,CAAA;AAC9D","file":"mcp-http.cjs","sourcesContent":["import type {\n McpElicitationFormRequest,\n McpElicitationHandlers,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationUrlRequest,\n} from './types.js';\n\nexport interface McpClientRequestHandler {\n registerCapabilities?:\n | ((capabilities: {\n readonly elicitation: {\n readonly form?: Record<string, never> | undefined;\n readonly url?: Record<string, never> | undefined;\n };\n }) => void)\n | undefined;\n setRequestHandler?:\n | ((\n method: 'elicitation/create',\n handler: (request: {\n readonly params: McpElicitationRequest;\n }) => Promise<McpElicitationResult>,\n ) => void)\n | undefined;\n}\n\nexport function registerElicitationHandlers(\n client: McpClientRequestHandler,\n handlers: McpElicitationHandlers | undefined,\n): void {\n if (handlers === undefined) return;\n\n const supportsForm = handlers.form !== undefined;\n const supportsUrl = handlers.url !== undefined;\n if (!supportsForm && !supportsUrl) {\n throw new TypeError('At least one MCP elicitation handler must be provided');\n }\n if (client.registerCapabilities === undefined || client.setRequestHandler === undefined) {\n throw new TypeError(\n 'The MCP client does not support elicitation capabilities and request handlers',\n );\n }\n\n client.registerCapabilities({\n elicitation: {\n ...(supportsForm ? { form: {} } : {}),\n ...(supportsUrl ? { url: {} } : {}),\n },\n });\n client.setRequestHandler('elicitation/create', async ({ params }) => {\n if (params.mode === 'url') {\n const request = params as McpElicitationUrlRequest;\n if (handlers.url === undefined) {\n throw new Error('MCP server requested URL elicitation, but no URL handler is configured');\n }\n return handlers.url(request);\n }\n\n const request = params as McpElicitationFormRequest;\n if (handlers.form === undefined) {\n throw new Error('MCP server requested form elicitation, but no form handler is configured');\n }\n return handlers.form(request);\n });\n}\n","/**\n * Optional remote MCP transport connectors.\n *\n * The root SDK stays transport-agnostic and Edge-compatible. This subpath dynamically\n * loads the official MCP TypeScript client so applications can connect to remote servers\n * over modern Streamable HTTP or legacy SSE.\n */\n\nimport { registerElicitationHandlers, type McpClientRequestHandler } from './client-options.js';\nimport type { McpClientLike, McpElicitationHandlers } from './types.js';\n\nconst MCP_CLIENT_PACKAGE = '@modelcontextprotocol/client';\n\nexport type McpHttpTransport = 'streamable-http' | 'sse' | 'auto';\n\nexport interface HttpMcpClientOptions {\n /** Absolute MCP server URL, for example https://example.com/mcp. */\n readonly url: string | URL;\n /**\n * Transport selection. Defaults to Streamable HTTP. In 'auto' mode, a compatible 4xx\n * from the modern transport triggers a retry with the legacy SSE transport.\n */\n readonly transport?: McpHttpTransport | undefined;\n readonly name?: string | undefined;\n readonly version?: string | undefined;\n /** Fetch RequestInit forwarded to the MCP transport for remote authentication/proxy headers. */\n readonly requestInit?: RequestInit | undefined;\n /** Optional fetch implementation forwarded to the MCP transport. */\n readonly fetch?: typeof globalThis.fetch | undefined;\n readonly elicitation?: McpElicitationHandlers | undefined;\n /** Defaults to manual so input_required responses are returned to the caller. */\n readonly inputRequiredMode?: 'manual' | 'automatic' | undefined;\n}\n\nexport interface HttpMcpConnection {\n readonly client: McpClientLike;\n readonly transport: 'streamable-http' | 'sse';\n readonly close: () => Promise<void>;\n /**\n * Streamable HTTP only: terminate the server-side MCP session when one exists.\n * Undefined for legacy SSE connections.\n */\n readonly terminateSession?: (() => Promise<void>) | undefined;\n}\n\ninterface DynamicMcpClient {\n readonly Client: new (\n metadata: { name: string; version: string },\n options?: { readonly inputRequired?: { readonly autoFulfill: boolean } },\n ) => {\n connect: (transport: unknown) => Promise<void>;\n close: () => Promise<void>;\n listTools: McpClientLike['listTools'];\n callTool: McpClientLike['callTool'];\n } & McpClientRequestHandler;\n readonly StreamableHTTPClientTransport: new (\n url: URL,\n options?: unknown,\n ) => unknown;\n readonly SSEClientTransport: new (url: URL, options?: unknown) => unknown;\n}\n\nasync function loadClientModule(): Promise<DynamicMcpClient> {\n try {\n return (await import(MCP_CLIENT_PACKAGE)) as unknown as DynamicMcpClient;\n } catch (error) {\n throw new Error(\n 'MCP HTTP support requires @modelcontextprotocol/client >= 2.0.0. ' +\n 'Install it with npm install @modelcontextprotocol/client.',\n { cause: error },\n );\n }\n}\n\nfunction parseServerUrl(value: string | URL): URL {\n let url: URL;\n try {\n url = value instanceof URL ? new URL(value.href) : new URL(value);\n } catch (error) {\n throw new TypeError('MCP HTTP server URL must be a valid absolute URL', { cause: error });\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new TypeError('MCP HTTP server URL must use http: or https:');\n }\n return url;\n}\n\nfunction transportOptions(options: HttpMcpClientOptions): Record<string, unknown> {\n return {\n ...(options.requestInit !== undefined ? { requestInit: options.requestInit } : {}),\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n };\n}\n\nfunction connectionFrom(\n client: DynamicMcpClient['Client'] extends new (...args: infer _Args) => infer C ? C : never,\n transport: unknown,\n kind: 'streamable-http' | 'sse',\n): HttpMcpConnection {\n const transportWithTermination = transport as {\n terminateSession?: (() => Promise<void>) | undefined;\n };\n\n return {\n client,\n transport: kind,\n close: () => client.close(),\n ...(kind === 'streamable-http' && typeof transportWithTermination.terminateSession === 'function'\n ? { terminateSession: () => transportWithTermination.terminateSession!() }\n : {}),\n };\n}\n\nasync function connectWithTransport(\n mode: Exclude<McpHttpTransport, 'auto'>,\n url: URL,\n options: HttpMcpClientOptions,\n modules: DynamicMcpClient,\n): Promise<HttpMcpConnection> {\n const client = new modules.Client(\n {\n name: options.name ?? '@nemesis-oss/ollama-sdk',\n version: options.version ?? '1.0.0',\n },\n { inputRequired: { autoFulfill: options.inputRequiredMode === 'automatic' } },\n );\n registerElicitationHandlers(client, options.elicitation);\n const transport =\n mode === 'streamable-http'\n ? new modules.StreamableHTTPClientTransport(url, transportOptions(options))\n : new modules.SSEClientTransport(url, transportOptions(options));\n\n await client.connect(transport);\n return connectionFrom(client, transport, mode);\n}\n\nfunction responseStatus(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const value = error as Record<string, unknown>;\n if (typeof value.status === 'number') return value.status;\n if (typeof value.statusCode === 'number') return value.statusCode;\n\n const response = value.response;\n if (typeof response === 'object' && response !== null && typeof (response as Record<string, unknown>).status === 'number') {\n return (response as Record<string, number>).status;\n }\n\n const cause = value.cause;\n if (cause !== error) return responseStatus(cause);\n return undefined;\n}\n\nfunction shouldFallbackToSse(error: unknown): boolean {\n const status = responseStatus(error);\n return status !== undefined && status >= 400 && status < 500 && status !== 401 && status !== 403 && status !== 429;\n}\n\n/**\n * Connect to a remote MCP server.\n *\n * Defaults to modern Streamable HTTP. Use 'sse' for an explicitly legacy server or\n * 'auto' to try Streamable HTTP and fall back to SSE only for a non-authentication 4xx\n * response, avoiding accidental downgrade on credentials, throttling, or server failures.\n */\nexport async function connectMcpHttpClient(\n options: HttpMcpClientOptions,\n): Promise<HttpMcpConnection> {\n const url = parseServerUrl(options.url);\n const mode = options.transport ?? 'streamable-http';\n if (mode !== 'auto') {\n return connectWithTransport(mode, url, options, await loadClientModule());\n }\n\n const modules = await loadClientModule();\n try {\n return await connectWithTransport('streamable-http', url, options, modules);\n } catch (error) {\n if (!shouldFallbackToSse(error)) throw error;\n try {\n return await connectWithTransport('sse', url, options, modules);\n } catch (sseError) {\n throw new Error(\n 'MCP Streamable HTTP was unavailable and the legacy SSE fallback also failed.',\n { cause: sseError },\n );\n }\n }\n}\n\nexport async function connectStreamableHttpMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'streamable-http' });\n}\n\nexport async function connectSseMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'sse' });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp/client-options.ts","../src/mcp/http.ts"],"names":["request"],"mappings":";;;AA2BO,SAAS,2BAAA,CACd,QACA,QAAA,EACM;AACN,EAAA,IAAI,aAAa,MAAA,EAAW;AAE5B,EAAA,MAAM,YAAA,GAAe,SAAS,IAAA,KAAS,MAAA;AACvC,EAAA,MAAM,WAAA,GAAc,SAAS,GAAA,KAAQ,MAAA;AACrC,EAAA,IAAI,CAAC,YAAA,IAAgB,CAAC,WAAA,EAAa;AACjC,IAAA,MAAM,IAAI,UAAU,uDAAuD,CAAA;AAAA,EAC7E;AACA,EAAA,IAAI,MAAA,CAAO,oBAAA,KAAyB,MAAA,IAAa,MAAA,CAAO,sBAAsB,MAAA,EAAW;AACvF,IAAA,MAAM,IAAI,SAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,MAAA,CAAO,oBAAA,CAAqB;AAAA,IAC1B,WAAA,EAAa;AAAA,MACX,GAAI,YA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GAAM,cAAA,CAAe,OAAA,CAAQ,GAAG,CAAA;AACtC,EAAA,MAAM,IAAA,GAAO,QAAQ,SAAA,IAAa,iBAAA;AAClC,EAAA,IAAI,SAAS,MAAA,EAAQ;AACnB,IAAA,OAAO,qBAAqB,IAAA,EAAM,GAAA,EAAK,OAAA,EAAS,MAAM,kBAAkB,CAAA;AAAA,EAC1E;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,gBAAA,EAAiB;AACvC,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,oBAAA,CAAqB,iBAAA,EAAmB,GAAA,EAAK,SAAS,OAAO,CAAA;AAAA,EAC5E,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,CAAC,mBAAA,CAAoB,KAAK,CAAA,EAAG,MAAM,KAAA;AACvC,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,oBAAA,CAAqB,KAAA,EAAO,GAAA,EAAK,SAAS,OAAO,CAAA;AAAA,IAChE,SAAS,QAAA,EAAU;AACjB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,8EAAA;AAAA,QACA,EAAE,OAAO,QAAA;AAAS,OACpB;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,+BACpB,OAAA,EAC4B;AAC5B,EAAA,OAAO,qBAAqB,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,mBAAmB,CAAA;AAC1E;AAEA,eAAsB,oBACpB,OAAA,EAC4B;AAC5B,EAAA,OAAO,qBAAqB,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,OAAO,CAAA;AAC9D","file":"mcp-http.cjs","sourcesContent":["import type {\n McpElicitationFormRequest,\n McpElicitationHandlers,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationUrlRequest,\n} from './types.js';\n\nexport interface McpClientRequestHandler {\n registerCapabilities?:\n | ((capabilities: {\n readonly elicitation: {\n readonly form?: Record<string, never> | undefined;\n readonly url?: Record<string, never> | undefined;\n };\n }) => void)\n | undefined;\n setRequestHandler?:\n | ((\n method: 'elicitation/create',\n handler: (request: {\n readonly params: McpElicitationRequest;\n }) => Promise<McpElicitationResult>,\n ) => void)\n | undefined;\n}\n\nexport function registerElicitationHandlers(\n client: McpClientRequestHandler,\n handlers: McpElicitationHandlers | undefined,\n): void {\n if (handlers === undefined) return;\n\n const supportsForm = handlers.form !== undefined;\n const supportsUrl = handlers.url !== undefined;\n if (!supportsForm && !supportsUrl) {\n throw new TypeError('At least one MCP elicitation handler must be provided');\n }\n if (client.registerCapabilities === undefined || client.setRequestHandler === undefined) {\n throw new TypeError(\n 'The MCP client does not support elicitation capabilities and request handlers',\n );\n }\n\n client.registerCapabilities({\n elicitation: {\n ...(supportsForm ? { form: {} } : {}),\n ...(supportsUrl ? { url: {} } : {}),\n },\n });\n client.setRequestHandler('elicitation/create', async ({ params }) => {\n if (params.mode === 'url') {\n const request = params as McpElicitationUrlRequest;\n if (handlers.url === undefined) {\n throw new Error('MCP server requested URL elicitation, but no URL handler is configured');\n }\n return handlers.url(request);\n }\n\n const request = params as McpElicitationFormRequest;\n if (handlers.form === undefined) {\n throw new Error('MCP server requested form elicitation, but no form handler is configured');\n }\n return handlers.form(request);\n });\n}\n","/**\n * Optional remote MCP transport connectors.\n *\n * The root SDK stays transport-agnostic and Edge-compatible. This subpath dynamically\n * loads the official MCP TypeScript client so applications can connect to remote servers\n * over modern Streamable HTTP or legacy SSE.\n */\n\nimport { registerElicitationHandlers, type McpClientRequestHandler } from './client-options.js';\nimport type { McpClientLike, McpElicitationHandlers } from './types.js';\n\nconst MCP_CLIENT_PACKAGE = '@modelcontextprotocol/client';\n\nexport type McpHttpTransport = 'streamable-http' | 'sse' | 'auto';\n\nexport interface HttpMcpClientOptions {\n /** Absolute MCP server URL, for example https://example.com/mcp. */\n readonly url: string | URL;\n /**\n * Transport selection. Defaults to Streamable HTTP. In 'auto' mode, a compatible 4xx\n * from the modern transport triggers a retry with the legacy SSE transport.\n */\n readonly transport?: McpHttpTransport | undefined;\n readonly name?: string | undefined;\n readonly version?: string | undefined;\n /** Fetch RequestInit forwarded to the MCP transport for remote authentication/proxy headers. */\n readonly requestInit?: RequestInit | undefined;\n /** Optional fetch implementation forwarded to the MCP transport. */\n readonly fetch?: typeof globalThis.fetch | undefined;\n readonly elicitation?: McpElicitationHandlers | undefined;\n /** Defaults to manual so input_required responses are returned to the caller. */\n readonly inputRequiredMode?: 'manual' | 'automatic' | undefined;\n}\n\nexport interface HttpMcpConnection {\n readonly client: McpClientLike;\n readonly transport: 'streamable-http' | 'sse';\n readonly close: () => Promise<void>;\n /**\n * Streamable HTTP only: terminate the server-side MCP session when one exists.\n * Undefined for legacy SSE connections.\n */\n readonly terminateSession?: (() => Promise<void>) | undefined;\n}\n\ninterface DynamicMcpClient {\n readonly Client: new (\n metadata: { name: string; version: string },\n options?: { readonly inputRequired?: { readonly autoFulfill: boolean } },\n ) => {\n connect: (transport: unknown) => Promise<void>;\n close: () => Promise<void>;\n listTools: McpClientLike['listTools'];\n callTool: McpClientLike['callTool'];\n } & McpClientRequestHandler;\n readonly StreamableHTTPClientTransport: new (url: URL, options?: unknown) => unknown;\n readonly SSEClientTransport: new (url: URL, options?: unknown) => unknown;\n}\n\nasync function loadClientModule(): Promise<DynamicMcpClient> {\n try {\n return (await import(MCP_CLIENT_PACKAGE)) as unknown as DynamicMcpClient;\n } catch (error) {\n throw new Error(\n 'MCP HTTP support requires @modelcontextprotocol/client >= 2.0.0. ' +\n 'Install it with npm install @modelcontextprotocol/client.',\n { cause: error },\n );\n }\n}\n\nfunction parseServerUrl(value: string | URL): URL {\n let url: URL;\n try {\n url = value instanceof URL ? new URL(value.href) : new URL(value);\n } catch (error) {\n throw new TypeError('MCP HTTP server URL must be a valid absolute URL', { cause: error });\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new TypeError('MCP HTTP server URL must use http: or https:');\n }\n return url;\n}\n\nfunction transportOptions(options: HttpMcpClientOptions): Record<string, unknown> {\n return {\n ...(options.requestInit !== undefined ? { requestInit: options.requestInit } : {}),\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n };\n}\n\nfunction connectionFrom(\n client: DynamicMcpClient['Client'] extends new (...args: infer _Args) => infer C ? C : never,\n transport: unknown,\n kind: 'streamable-http' | 'sse',\n): HttpMcpConnection {\n const transportWithTermination = transport as {\n terminateSession?: (() => Promise<void>) | undefined;\n };\n\n return {\n client,\n transport: kind,\n close: () => client.close(),\n ...(kind === 'streamable-http' &&\n typeof transportWithTermination.terminateSession === 'function'\n ? { terminateSession: () => transportWithTermination.terminateSession!() }\n : {}),\n };\n}\n\nasync function connectWithTransport(\n mode: Exclude<McpHttpTransport, 'auto'>,\n url: URL,\n options: HttpMcpClientOptions,\n modules: DynamicMcpClient,\n): Promise<HttpMcpConnection> {\n const client = new modules.Client(\n {\n name: options.name ?? '@nemesis-oss/ollama-sdk',\n version: options.version ?? '1.0.0',\n },\n { inputRequired: { autoFulfill: options.inputRequiredMode === 'automatic' } },\n );\n registerElicitationHandlers(client, options.elicitation);\n const transport =\n mode === 'streamable-http'\n ? new modules.StreamableHTTPClientTransport(url, transportOptions(options))\n : new modules.SSEClientTransport(url, transportOptions(options));\n\n await client.connect(transport);\n return connectionFrom(client, transport, mode);\n}\n\nfunction responseStatus(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const value = error as Record<string, unknown>;\n if (typeof value.status === 'number') return value.status;\n if (typeof value.statusCode === 'number') return value.statusCode;\n\n const response = value.response;\n if (\n typeof response === 'object' &&\n response !== null &&\n typeof (response as Record<string, unknown>).status === 'number'\n ) {\n return (response as Record<string, number>).status;\n }\n\n const cause = value.cause;\n if (cause !== error) return responseStatus(cause);\n return undefined;\n}\n\nfunction shouldFallbackToSse(error: unknown): boolean {\n const status = responseStatus(error);\n return (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401 &&\n status !== 403 &&\n status !== 429\n );\n}\n\n/**\n * Connect to a remote MCP server.\n *\n * Defaults to modern Streamable HTTP. Use 'sse' for an explicitly legacy server or\n * 'auto' to try Streamable HTTP and fall back to SSE only for a non-authentication 4xx\n * response, avoiding accidental downgrade on credentials, throttling, or server failures.\n */\nexport async function connectMcpHttpClient(\n options: HttpMcpClientOptions,\n): Promise<HttpMcpConnection> {\n const url = parseServerUrl(options.url);\n const mode = options.transport ?? 'streamable-http';\n if (mode !== 'auto') {\n return connectWithTransport(mode, url, options, await loadClientModule());\n }\n\n const modules = await loadClientModule();\n try {\n return await connectWithTransport('streamable-http', url, options, modules);\n } catch (error) {\n if (!shouldFallbackToSse(error)) throw error;\n try {\n return await connectWithTransport('sse', url, options, modules);\n } catch (sseError) {\n throw new Error(\n 'MCP Streamable HTTP was unavailable and the legacy SSE fallback also failed.',\n { cause: sseError },\n );\n }\n }\n}\n\nexport async function connectStreamableHttpMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'streamable-http' });\n}\n\nexport async function connectSseMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'sse' });\n}\n"]}
|
package/dist/mcp-http.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/client-options.ts","../src/mcp/http.ts"],"names":["request"],"mappings":";AA2BO,SAAS,2BAAA,CACd,QACA,QAAA,EACM;AACN,EAAA,IAAI,aAAa,MAAA,EAAW;AAE5B,EAAA,MAAM,YAAA,GAAe,SAAS,IAAA,KAAS,MAAA;AACvC,EAAA,MAAM,WAAA,GAAc,SAAS,GAAA,KAAQ,MAAA;AACrC,EAAA,IAAI,CAAC,YAAA,IAAgB,CAAC,WAAA,EAAa;AACjC,IAAA,MAAM,IAAI,UAAU,uDAAuD,CAAA;AAAA,EAC7E;AACA,EAAA,IAAI,MAAA,CAAO,oBAAA,KAAyB,MAAA,IAAa,MAAA,CAAO,sBAAsB,MAAA,EAAW;AACvF,IAAA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,MAAA,GAAS,OAAO,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA;AACjH;AASA,eAAsB,qBACpB,OAAA,EAC4B;AAC5B,EAAA,MAAM,GAAA,GAAM,cAAA,CAAe,OAAA,CAAQ,GAAG,CAAA;AACtC,EAAA,MAAM,IAAA,GAAO,QAAQ,SAAA,IAAa,iBAAA;AAClC,EAAA,IAAI,SAAS,MAAA,EAAQ;AACnB,IAAA,OAAO,qBAAqB,IAAA,EAAM,GAAA,EAAK,OAAA,EAAS,MAAM,kBAAkB,CAAA;AAAA,EAC1E;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,gBAAA,EAAiB;AACvC,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,oBAAA,CAAqB,iBAAA,EAAmB,GAAA,EAAK,SAAS,OAAO,CAAA;AAAA,EAC5E,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,CAAC,mBAAA,CAAoB,KAAK,CAAA,EAAG,MAAM,KAAA;AACvC,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,oBAAA,CAAqB,KAAA,EAAO,GAAA,EAAK,SAAS,OAAO,CAAA;AAAA,IAChE,SAAS,QAAA,EAAU;AACjB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,8EAAA;AAAA,QACA,EAAE,OAAO,QAAA;AAAS,OACpB;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,+BACpB,OAAA,EAC4B;AAC5B,EAAA,OAAO,qBAAqB,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,mBAAmB,CAAA;AAC1E;AAEA,eAAsB,oBACpB,OAAA,EAC4B;AAC5B,EAAA,OAAO,qBAAqB,EAAE,GAAG,OAAA,EAAS,SAAA,EAAW,OAAO,CAAA;AAC9D","file":"mcp-http.js","sourcesContent":["import type {\n McpElicitationFormRequest,\n McpElicitationHandlers,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationUrlRequest,\n} from './types.js';\n\nexport interface McpClientRequestHandler {\n registerCapabilities?:\n | ((capabilities: {\n readonly elicitation: {\n readonly form?: Record<string, never> | undefined;\n readonly url?: Record<string, never> | undefined;\n };\n }) => void)\n | undefined;\n setRequestHandler?:\n | ((\n method: 'elicitation/create',\n handler: (request: {\n readonly params: McpElicitationRequest;\n }) => Promise<McpElicitationResult>,\n ) => void)\n | undefined;\n}\n\nexport function registerElicitationHandlers(\n client: McpClientRequestHandler,\n handlers: McpElicitationHandlers | undefined,\n): void {\n if (handlers === undefined) return;\n\n const supportsForm = handlers.form !== undefined;\n const supportsUrl = handlers.url !== undefined;\n if (!supportsForm && !supportsUrl) {\n throw new TypeError('At least one MCP elicitation handler must be provided');\n }\n if (client.registerCapabilities === undefined || client.setRequestHandler === undefined) {\n throw new TypeError(\n 'The MCP client does not support elicitation capabilities and request handlers',\n );\n }\n\n client.registerCapabilities({\n elicitation: {\n ...(supportsForm ? { form: {} } : {}),\n ...(supportsUrl ? { url: {} } : {}),\n },\n });\n client.setRequestHandler('elicitation/create', async ({ params }) => {\n if (params.mode === 'url') {\n const request = params as McpElicitationUrlRequest;\n if (handlers.url === undefined) {\n throw new Error('MCP server requested URL elicitation, but no URL handler is configured');\n }\n return handlers.url(request);\n }\n\n const request = params as McpElicitationFormRequest;\n if (handlers.form === undefined) {\n throw new Error('MCP server requested form elicitation, but no form handler is configured');\n }\n return handlers.form(request);\n });\n}\n","/**\n * Optional remote MCP transport connectors.\n *\n * The root SDK stays transport-agnostic and Edge-compatible. This subpath dynamically\n * loads the official MCP TypeScript client so applications can connect to remote servers\n * over modern Streamable HTTP or legacy SSE.\n */\n\nimport { registerElicitationHandlers, type McpClientRequestHandler } from './client-options.js';\nimport type { McpClientLike, McpElicitationHandlers } from './types.js';\n\nconst MCP_CLIENT_PACKAGE = '@modelcontextprotocol/client';\n\nexport type McpHttpTransport = 'streamable-http' | 'sse' | 'auto';\n\nexport interface HttpMcpClientOptions {\n /** Absolute MCP server URL, for example https://example.com/mcp. */\n readonly url: string | URL;\n /**\n * Transport selection. Defaults to Streamable HTTP. In 'auto' mode, a compatible 4xx\n * from the modern transport triggers a retry with the legacy SSE transport.\n */\n readonly transport?: McpHttpTransport | undefined;\n readonly name?: string | undefined;\n readonly version?: string | undefined;\n /** Fetch RequestInit forwarded to the MCP transport for remote authentication/proxy headers. */\n readonly requestInit?: RequestInit | undefined;\n /** Optional fetch implementation forwarded to the MCP transport. */\n readonly fetch?: typeof globalThis.fetch | undefined;\n readonly elicitation?: McpElicitationHandlers | undefined;\n /** Defaults to manual so input_required responses are returned to the caller. */\n readonly inputRequiredMode?: 'manual' | 'automatic' | undefined;\n}\n\nexport interface HttpMcpConnection {\n readonly client: McpClientLike;\n readonly transport: 'streamable-http' | 'sse';\n readonly close: () => Promise<void>;\n /**\n * Streamable HTTP only: terminate the server-side MCP session when one exists.\n * Undefined for legacy SSE connections.\n */\n readonly terminateSession?: (() => Promise<void>) | undefined;\n}\n\ninterface DynamicMcpClient {\n readonly Client: new (\n metadata: { name: string; version: string },\n options?: { readonly inputRequired?: { readonly autoFulfill: boolean } },\n ) => {\n connect: (transport: unknown) => Promise<void>;\n close: () => Promise<void>;\n listTools: McpClientLike['listTools'];\n callTool: McpClientLike['callTool'];\n } & McpClientRequestHandler;\n readonly StreamableHTTPClientTransport: new (\n url: URL,\n options?: unknown,\n ) => unknown;\n readonly SSEClientTransport: new (url: URL, options?: unknown) => unknown;\n}\n\nasync function loadClientModule(): Promise<DynamicMcpClient> {\n try {\n return (await import(MCP_CLIENT_PACKAGE)) as unknown as DynamicMcpClient;\n } catch (error) {\n throw new Error(\n 'MCP HTTP support requires @modelcontextprotocol/client >= 2.0.0. ' +\n 'Install it with npm install @modelcontextprotocol/client.',\n { cause: error },\n );\n }\n}\n\nfunction parseServerUrl(value: string | URL): URL {\n let url: URL;\n try {\n url = value instanceof URL ? new URL(value.href) : new URL(value);\n } catch (error) {\n throw new TypeError('MCP HTTP server URL must be a valid absolute URL', { cause: error });\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new TypeError('MCP HTTP server URL must use http: or https:');\n }\n return url;\n}\n\nfunction transportOptions(options: HttpMcpClientOptions): Record<string, unknown> {\n return {\n ...(options.requestInit !== undefined ? { requestInit: options.requestInit } : {}),\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n };\n}\n\nfunction connectionFrom(\n client: DynamicMcpClient['Client'] extends new (...args: infer _Args) => infer C ? C : never,\n transport: unknown,\n kind: 'streamable-http' | 'sse',\n): HttpMcpConnection {\n const transportWithTermination = transport as {\n terminateSession?: (() => Promise<void>) | undefined;\n };\n\n return {\n client,\n transport: kind,\n close: () => client.close(),\n ...(kind === 'streamable-http' && typeof transportWithTermination.terminateSession === 'function'\n ? { terminateSession: () => transportWithTermination.terminateSession!() }\n : {}),\n };\n}\n\nasync function connectWithTransport(\n mode: Exclude<McpHttpTransport, 'auto'>,\n url: URL,\n options: HttpMcpClientOptions,\n modules: DynamicMcpClient,\n): Promise<HttpMcpConnection> {\n const client = new modules.Client(\n {\n name: options.name ?? '@nemesis-oss/ollama-sdk',\n version: options.version ?? '1.0.0',\n },\n { inputRequired: { autoFulfill: options.inputRequiredMode === 'automatic' } },\n );\n registerElicitationHandlers(client, options.elicitation);\n const transport =\n mode === 'streamable-http'\n ? new modules.StreamableHTTPClientTransport(url, transportOptions(options))\n : new modules.SSEClientTransport(url, transportOptions(options));\n\n await client.connect(transport);\n return connectionFrom(client, transport, mode);\n}\n\nfunction responseStatus(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const value = error as Record<string, unknown>;\n if (typeof value.status === 'number') return value.status;\n if (typeof value.statusCode === 'number') return value.statusCode;\n\n const response = value.response;\n if (typeof response === 'object' && response !== null && typeof (response as Record<string, unknown>).status === 'number') {\n return (response as Record<string, number>).status;\n }\n\n const cause = value.cause;\n if (cause !== error) return responseStatus(cause);\n return undefined;\n}\n\nfunction shouldFallbackToSse(error: unknown): boolean {\n const status = responseStatus(error);\n return status !== undefined && status >= 400 && status < 500 && status !== 401 && status !== 403 && status !== 429;\n}\n\n/**\n * Connect to a remote MCP server.\n *\n * Defaults to modern Streamable HTTP. Use 'sse' for an explicitly legacy server or\n * 'auto' to try Streamable HTTP and fall back to SSE only for a non-authentication 4xx\n * response, avoiding accidental downgrade on credentials, throttling, or server failures.\n */\nexport async function connectMcpHttpClient(\n options: HttpMcpClientOptions,\n): Promise<HttpMcpConnection> {\n const url = parseServerUrl(options.url);\n const mode = options.transport ?? 'streamable-http';\n if (mode !== 'auto') {\n return connectWithTransport(mode, url, options, await loadClientModule());\n }\n\n const modules = await loadClientModule();\n try {\n return await connectWithTransport('streamable-http', url, options, modules);\n } catch (error) {\n if (!shouldFallbackToSse(error)) throw error;\n try {\n return await connectWithTransport('sse', url, options, modules);\n } catch (sseError) {\n throw new Error(\n 'MCP Streamable HTTP was unavailable and the legacy SSE fallback also failed.',\n { cause: sseError },\n );\n }\n }\n}\n\nexport async function connectStreamableHttpMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'streamable-http' });\n}\n\nexport async function connectSseMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'sse' });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp/client-options.ts","../src/mcp/http.ts"],"names":["request"],"mappings":";AA2BO,SAAS,2BAAA,CACd,QACA,QAAA,EACM;AACN,EAAA,IAAI,aAAa,MAAA,EAAW;AAE5B,EAAA,MAAM,YAAA,GAAe,SAAS,IAAA,KAAS,MAAA;AACvC,EAAA,MAAM,WAAA,GAAc,SAAS,GAAA,KAAQ,MAAA;AACrC,EAAA,IAAI,CAAC,YAAA,IAAgB,CAAC,WAAA,EAAa;AACjC,IAAA,MAAM,IAAI,UAAU,uDAAuD,CAAA;AAAA,EAC7E;AACA,EAAA,IAAI,MAAA,CAAO,oB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Request,\n McpElicitationResult,\n McpElicitationUrlRequest,\n} from './types.js';\n\nexport interface McpClientRequestHandler {\n registerCapabilities?:\n | ((capabilities: {\n readonly elicitation: {\n readonly form?: Record<string, never> | undefined;\n readonly url?: Record<string, never> | undefined;\n };\n }) => void)\n | undefined;\n setRequestHandler?:\n | ((\n method: 'elicitation/create',\n handler: (request: {\n readonly params: McpElicitationRequest;\n }) => Promise<McpElicitationResult>,\n ) => void)\n | undefined;\n}\n\nexport function registerElicitationHandlers(\n client: McpClientRequestHandler,\n handlers: McpElicitationHandlers | undefined,\n): void {\n if (handlers === undefined) return;\n\n const supportsForm = handlers.form !== undefined;\n const supportsUrl = handlers.url !== undefined;\n if (!supportsForm && !supportsUrl) {\n throw new TypeError('At least one MCP elicitation handler must be provided');\n }\n if (client.registerCapabilities === undefined || client.setRequestHandler === undefined) {\n throw new TypeError(\n 'The MCP client does not support elicitation capabilities and request handlers',\n );\n }\n\n client.registerCapabilities({\n elicitation: {\n ...(supportsForm ? { form: {} } : {}),\n ...(supportsUrl ? { url: {} } : {}),\n },\n });\n client.setRequestHandler('elicitation/create', async ({ params }) => {\n if (params.mode === 'url') {\n const request = params as McpElicitationUrlRequest;\n if (handlers.url === undefined) {\n throw new Error('MCP server requested URL elicitation, but no URL handler is configured');\n }\n return handlers.url(request);\n }\n\n const request = params as McpElicitationFormRequest;\n if (handlers.form === undefined) {\n throw new Error('MCP server requested form elicitation, but no form handler is configured');\n }\n return handlers.form(request);\n });\n}\n","/**\n * Optional remote MCP transport connectors.\n *\n * The root SDK stays transport-agnostic and Edge-compatible. This subpath dynamically\n * loads the official MCP TypeScript client so applications can connect to remote servers\n * over modern Streamable HTTP or legacy SSE.\n */\n\nimport { registerElicitationHandlers, type McpClientRequestHandler } from './client-options.js';\nimport type { McpClientLike, McpElicitationHandlers } from './types.js';\n\nconst MCP_CLIENT_PACKAGE = '@modelcontextprotocol/client';\n\nexport type McpHttpTransport = 'streamable-http' | 'sse' | 'auto';\n\nexport interface HttpMcpClientOptions {\n /** Absolute MCP server URL, for example https://example.com/mcp. */\n readonly url: string | URL;\n /**\n * Transport selection. Defaults to Streamable HTTP. In 'auto' mode, a compatible 4xx\n * from the modern transport triggers a retry with the legacy SSE transport.\n */\n readonly transport?: McpHttpTransport | undefined;\n readonly name?: string | undefined;\n readonly version?: string | undefined;\n /** Fetch RequestInit forwarded to the MCP transport for remote authentication/proxy headers. */\n readonly requestInit?: RequestInit | undefined;\n /** Optional fetch implementation forwarded to the MCP transport. */\n readonly fetch?: typeof globalThis.fetch | undefined;\n readonly elicitation?: McpElicitationHandlers | undefined;\n /** Defaults to manual so input_required responses are returned to the caller. */\n readonly inputRequiredMode?: 'manual' | 'automatic' | undefined;\n}\n\nexport interface HttpMcpConnection {\n readonly client: McpClientLike;\n readonly transport: 'streamable-http' | 'sse';\n readonly close: () => Promise<void>;\n /**\n * Streamable HTTP only: terminate the server-side MCP session when one exists.\n * Undefined for legacy SSE connections.\n */\n readonly terminateSession?: (() => Promise<void>) | undefined;\n}\n\ninterface DynamicMcpClient {\n readonly Client: new (\n metadata: { name: string; version: string },\n options?: { readonly inputRequired?: { readonly autoFulfill: boolean } },\n ) => {\n connect: (transport: unknown) => Promise<void>;\n close: () => Promise<void>;\n listTools: McpClientLike['listTools'];\n callTool: McpClientLike['callTool'];\n } & McpClientRequestHandler;\n readonly StreamableHTTPClientTransport: new (url: URL, options?: unknown) => unknown;\n readonly SSEClientTransport: new (url: URL, options?: unknown) => unknown;\n}\n\nasync function loadClientModule(): Promise<DynamicMcpClient> {\n try {\n return (await import(MCP_CLIENT_PACKAGE)) as unknown as DynamicMcpClient;\n } catch (error) {\n throw new Error(\n 'MCP HTTP support requires @modelcontextprotocol/client >= 2.0.0. ' +\n 'Install it with npm install @modelcontextprotocol/client.',\n { cause: error },\n );\n }\n}\n\nfunction parseServerUrl(value: string | URL): URL {\n let url: URL;\n try {\n url = value instanceof URL ? new URL(value.href) : new URL(value);\n } catch (error) {\n throw new TypeError('MCP HTTP server URL must be a valid absolute URL', { cause: error });\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new TypeError('MCP HTTP server URL must use http: or https:');\n }\n return url;\n}\n\nfunction transportOptions(options: HttpMcpClientOptions): Record<string, unknown> {\n return {\n ...(options.requestInit !== undefined ? { requestInit: options.requestInit } : {}),\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n };\n}\n\nfunction connectionFrom(\n client: DynamicMcpClient['Client'] extends new (...args: infer _Args) => infer C ? C : never,\n transport: unknown,\n kind: 'streamable-http' | 'sse',\n): HttpMcpConnection {\n const transportWithTermination = transport as {\n terminateSession?: (() => Promise<void>) | undefined;\n };\n\n return {\n client,\n transport: kind,\n close: () => client.close(),\n ...(kind === 'streamable-http' &&\n typeof transportWithTermination.terminateSession === 'function'\n ? { terminateSession: () => transportWithTermination.terminateSession!() }\n : {}),\n };\n}\n\nasync function connectWithTransport(\n mode: Exclude<McpHttpTransport, 'auto'>,\n url: URL,\n options: HttpMcpClientOptions,\n modules: DynamicMcpClient,\n): Promise<HttpMcpConnection> {\n const client = new modules.Client(\n {\n name: options.name ?? '@nemesis-oss/ollama-sdk',\n version: options.version ?? '1.0.0',\n },\n { inputRequired: { autoFulfill: options.inputRequiredMode === 'automatic' } },\n );\n registerElicitationHandlers(client, options.elicitation);\n const transport =\n mode === 'streamable-http'\n ? new modules.StreamableHTTPClientTransport(url, transportOptions(options))\n : new modules.SSEClientTransport(url, transportOptions(options));\n\n await client.connect(transport);\n return connectionFrom(client, transport, mode);\n}\n\nfunction responseStatus(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const value = error as Record<string, unknown>;\n if (typeof value.status === 'number') return value.status;\n if (typeof value.statusCode === 'number') return value.statusCode;\n\n const response = value.response;\n if (\n typeof response === 'object' &&\n response !== null &&\n typeof (response as Record<string, unknown>).status === 'number'\n ) {\n return (response as Record<string, number>).status;\n }\n\n const cause = value.cause;\n if (cause !== error) return responseStatus(cause);\n return undefined;\n}\n\nfunction shouldFallbackToSse(error: unknown): boolean {\n const status = responseStatus(error);\n return (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401 &&\n status !== 403 &&\n status !== 429\n );\n}\n\n/**\n * Connect to a remote MCP server.\n *\n * Defaults to modern Streamable HTTP. Use 'sse' for an explicitly legacy server or\n * 'auto' to try Streamable HTTP and fall back to SSE only for a non-authentication 4xx\n * response, avoiding accidental downgrade on credentials, throttling, or server failures.\n */\nexport async function connectMcpHttpClient(\n options: HttpMcpClientOptions,\n): Promise<HttpMcpConnection> {\n const url = parseServerUrl(options.url);\n const mode = options.transport ?? 'streamable-http';\n if (mode !== 'auto') {\n return connectWithTransport(mode, url, options, await loadClientModule());\n }\n\n const modules = await loadClientModule();\n try {\n return await connectWithTransport('streamable-http', url, options, modules);\n } catch (error) {\n if (!shouldFallbackToSse(error)) throw error;\n try {\n return await connectWithTransport('sse', url, options, modules);\n } catch (sseError) {\n throw new Error(\n 'MCP Streamable HTTP was unavailable and the legacy SSE fallback also failed.',\n { cause: sseError },\n );\n }\n }\n}\n\nexport async function connectStreamableHttpMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'streamable-http' });\n}\n\nexport async function connectSseMcpClient(\n options: Omit<HttpMcpClientOptions, 'transport'>,\n): Promise<HttpMcpConnection> {\n return connectMcpHttpClient({ ...options, transport: 'sse' });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-
|
|
1
|
+
import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-CH3pdrak.cjs';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-
|
|
1
|
+
import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-CH3pdrak.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
package/dist/skills.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { g as SkillSummary, S as Skill } from './compose-
|
|
2
|
-
export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-
|
|
3
|
-
import './types-
|
|
1
|
+
import { g as SkillSummary, S as Skill } from './compose-Bjpsu3Y1.cjs';
|
|
2
|
+
export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-Bjpsu3Y1.cjs';
|
|
3
|
+
import './types-CH3pdrak.cjs';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/**
|
package/dist/skills.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { g as SkillSummary, S as Skill } from './compose-
|
|
2
|
-
export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-
|
|
3
|
-
import './types-
|
|
1
|
+
import { g as SkillSummary, S as Skill } from './compose-DxAQ2z26.js';
|
|
2
|
+
export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-DxAQ2z26.js';
|
|
3
|
+
import './types-CH3pdrak.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -12,26 +12,36 @@
|
|
|
12
12
|
* Resolution order for `string` inputs:
|
|
13
13
|
*
|
|
14
14
|
* 1. `data:image/...;base64,` data URIs — the header is stripped, the
|
|
15
|
-
* payload passed through.
|
|
16
|
-
* 2. `http://` / `https://` URLs — fetched with the
|
|
17
|
-
* `fetch
|
|
15
|
+
* payload passed through (decoded size capped by `maxImageBytes`).
|
|
16
|
+
* 2. `http://` / `https://` URLs — fetched with the configured fetch
|
|
17
|
+
* implementation (the client's own `fetch` by default, see
|
|
18
|
+
* {@link ImageResolutionPolicy.fetchImpl}), then base64-encoded. Remote
|
|
19
|
+
* resolution is governed by {@link ImageResolutionPolicy}: the response
|
|
20
|
+
* body is size-capped *while streaming*, every fetch has a timeout, and
|
|
21
|
+
* an SSRF guard rejects private/loopback/link-local targets — hostname
|
|
22
|
+
* allowlists and redirect hops included (redirects are followed manually
|
|
23
|
+
* on Node so each hop is re-validated; see ADR 0041 for the
|
|
24
|
+
* browser/edge caveat).
|
|
18
25
|
* 3. Strings with a known image file extension (`.png`, `.jpg`, `.webp`,
|
|
19
26
|
* ...) — treated as a local file path and read via a *dynamically
|
|
20
|
-
* imported* `node:fs` (Node.js only)
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* a path-shaped string throws a descriptive error instead of
|
|
25
|
-
* shipping garbage to the server.
|
|
27
|
+
* imported* `node:fs` (Node.js only), size-capped via `maxImageBytes`.
|
|
28
|
+
* A failed read throws `vision_path_read_failed` instead of silently
|
|
29
|
+
* shipping the raw path string to the server (which could only reject
|
|
30
|
+
* it — see ADR 0041). In browsers/edge runtimes, where `node:fs` does
|
|
31
|
+
* not exist, a path-shaped string throws a descriptive error instead of
|
|
32
|
+
* silently shipping garbage to the server.
|
|
26
33
|
* 4. Anything else — assumed to already be raw base64 and passed through.
|
|
27
34
|
*
|
|
28
35
|
* `Buffer` and `Uint8Array` inputs are base64-encoded via the runtime's
|
|
29
36
|
* universal base64 primitive (`Buffer` on Node, `btoa` on the web), matching
|
|
30
|
-
* {@link encodeImage}.
|
|
37
|
+
* {@link encodeImage}. Direct byte inputs are *not* size-capped: the caller
|
|
38
|
+
* already holds those bytes in memory, and the resolution cost is already
|
|
39
|
+
* paid (see ADR 0041 for the threat model).
|
|
31
40
|
*
|
|
32
41
|
* Everything here is dependency-free and safe to import from the core client
|
|
33
|
-
* bundle: the `node:fs`
|
|
34
|
-
* never pull
|
|
42
|
+
* bundle: the `node:fs` and `node:dns/promises` imports are dynamic and
|
|
43
|
+
* guarded, so browser/edge builds never pull them in (see ADR 0006 — Edge
|
|
44
|
+
* Runtime CI).
|
|
35
45
|
*/
|
|
36
46
|
/**
|
|
37
47
|
* Polymorphic vision input accepted anywhere this SDK takes an `images` entry.
|
|
@@ -44,6 +54,89 @@
|
|
|
44
54
|
* published declarations stay free of `@types/node` globals (audit TYP-03).
|
|
45
55
|
*/
|
|
46
56
|
type VisionInput = string | Uint8Array;
|
|
57
|
+
/**
|
|
58
|
+
* Fetch signature accepted for remote image resolution. Deliberately a
|
|
59
|
+
* structural subset of the global `fetch` (and of the client's configured
|
|
60
|
+
* `fetch`), so either can be passed without adaptation.
|
|
61
|
+
*/
|
|
62
|
+
type ImageFetchLike = (url: string, init?: {
|
|
63
|
+
redirect?: 'manual' | 'follow';
|
|
64
|
+
signal?: AbortSignal;
|
|
65
|
+
} | undefined) => Promise<Response>;
|
|
66
|
+
/** One address-resolution result, mirroring `node:dns`' `LookupAddress` shape. */
|
|
67
|
+
interface ImageAddress {
|
|
68
|
+
readonly address: string;
|
|
69
|
+
readonly family: number;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Policy applied whenever a vision input needs resolution — URL fetches,
|
|
73
|
+
* data-URI decoding, and local file reads. Set it once per client via
|
|
74
|
+
* `OllamaClientConfig.imageResolution`, or per call through the lower-level
|
|
75
|
+
* {@link resolveImages} / {@link resolveImageInput} signatures.
|
|
76
|
+
*
|
|
77
|
+
* Defaults are chosen so the common cases keep working while the failure
|
|
78
|
+
* modes an untrusted input can trigger (oversized bodies, slow or looping
|
|
79
|
+
* fetches, requests into private networks) fail closed with a clear error.
|
|
80
|
+
* See ADR 0041 for the full rationale.
|
|
81
|
+
*/
|
|
82
|
+
interface ImageResolutionPolicy {
|
|
83
|
+
/**
|
|
84
|
+
* Hard cap on the *decoded* image size, in bytes. Applies to remote fetch
|
|
85
|
+
* bodies (enforced while streaming, before the body is buffered), to local
|
|
86
|
+
* file reads (enforced via `stat` before the read), and to data-URI
|
|
87
|
+
* payloads. Direct `Uint8Array`/`Buffer` inputs are not capped. Default:
|
|
88
|
+
* 50 MiB.
|
|
89
|
+
*/
|
|
90
|
+
readonly maxImageBytes?: number | undefined;
|
|
91
|
+
/**
|
|
92
|
+
* Timeout for the whole remote fetch — connection, redirects, and body
|
|
93
|
+
* read combined. Default: 30 000 ms.
|
|
94
|
+
*/
|
|
95
|
+
readonly fetchTimeoutMs?: number | undefined;
|
|
96
|
+
/**
|
|
97
|
+
* Maximum redirect hops followed for a remote image. Every hop is
|
|
98
|
+
* re-validated against the host policy and the private-address guard (on
|
|
99
|
+
* Node, where redirects are followed manually). Default: 5.
|
|
100
|
+
*/
|
|
101
|
+
readonly maxRedirects?: number | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Allowlist of hosts remote images may be fetched from. Exact hostnames
|
|
104
|
+
* (case-insensitive), `*.example.com` wildcards for subdomains, or `'*'`
|
|
105
|
+
* for any host. `undefined` (default) allows any host — the
|
|
106
|
+
* private-address guard still applies.
|
|
107
|
+
*/
|
|
108
|
+
readonly allowedImageHosts?: readonly string[] | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* Permit fetching remote images from private, loopback, link-local, or
|
|
111
|
+
* otherwise reserved addresses (and from hostnames that resolve to them).
|
|
112
|
+
* Default: `false` — the SSRF guard. Flip it to `true` only for clients
|
|
113
|
+
* whose image URLs are trusted and genuinely live on a private network
|
|
114
|
+
* (e.g. an internal image service in the same subnet as the app).
|
|
115
|
+
*/
|
|
116
|
+
readonly allowPrivateNetworkAccess?: boolean | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* Permit resolving local file paths (`/path/to.png`). Default: `true`
|
|
119
|
+
* (the historical behavior). Set to `false` when image input is untrusted
|
|
120
|
+
* and filesystem reads must not happen at all.
|
|
121
|
+
*/
|
|
122
|
+
readonly allowLocalFileReads?: boolean | undefined;
|
|
123
|
+
/**
|
|
124
|
+
* Fetch implementation used for URL resolution. Defaults to the client's
|
|
125
|
+
* configured `fetch` (and to the platform's global `fetch` when called
|
|
126
|
+
* outside a client), so image fetches flow through whatever proxy, agent,
|
|
127
|
+
* or mock the caller already installed. Bypassed never — the resolver
|
|
128
|
+
* always uses this path, not a bare global, when resolving URLs.
|
|
129
|
+
*/
|
|
130
|
+
readonly fetchImpl?: ImageFetchLike | undefined;
|
|
131
|
+
/**
|
|
132
|
+
* Address resolver used by the private-network guard for non-literal
|
|
133
|
+
* hostnames. Defaults to `node:dns/promises` `lookup` on Node-like
|
|
134
|
+
* runtimes and to a hostname-heuristics-only check elsewhere (browsers and
|
|
135
|
+
* edge runtimes have no DNS API — see ADR 0041). Injectable so callers can
|
|
136
|
+
* resolve through DoH, a cache, or a test double.
|
|
137
|
+
*/
|
|
138
|
+
readonly addressLookup?: ((hostname: string) => Promise<readonly ImageAddress[]>) | undefined | undefined;
|
|
139
|
+
}
|
|
47
140
|
/**
|
|
48
141
|
* Cheap synchronous check: does this string input require async resolution
|
|
49
142
|
* (data-URI stripping, URL fetch, or file read), or is it already wire-ready
|
|
@@ -54,13 +147,18 @@ declare function imageStringNeedsResolution(input: string): boolean;
|
|
|
54
147
|
/**
|
|
55
148
|
* Resolves any supported vision input into the raw base64 string Ollama's
|
|
56
149
|
* REST API expects — no data-URI headers, no URL/path indirection left
|
|
57
|
-
* behind. See the module doc for the full resolution order
|
|
150
|
+
* behind. See the module doc for the full resolution order and
|
|
151
|
+
* {@link ImageResolutionPolicy} for the trust-boundary and resource-limit
|
|
152
|
+
* knobs.
|
|
58
153
|
*
|
|
59
|
-
* @throws {OllamaClientError} if a URL fetch fails (non-2xx
|
|
60
|
-
*
|
|
61
|
-
*
|
|
154
|
+
* @throws {OllamaClientError} if a URL fetch fails (non-2xx, timeout,
|
|
155
|
+
* oversize, redirect limit, host not allowed, private address blocked, or
|
|
156
|
+
* unsupported protocol), if a local file read fails, is disabled, or is
|
|
157
|
+
* oversize, or if a path-shaped string is passed in a runtime without
|
|
158
|
+
* `node:fs` (browser/edge) — in that environment, read the file yourself and
|
|
159
|
+
* pass the bytes.
|
|
62
160
|
*/
|
|
63
|
-
declare function resolveImageInput(input: VisionInput, signal?: AbortSignal | undefined): Promise<string>;
|
|
161
|
+
declare function resolveImageInput(input: VisionInput, signal?: AbortSignal | undefined, policy?: ImageResolutionPolicy | undefined): Promise<string>;
|
|
64
162
|
|
|
65
163
|
/**
|
|
66
164
|
* Core protocol and message types for the Ollama REST API.
|
|
@@ -105,6 +203,10 @@ interface Message {
|
|
|
105
203
|
* URLs are fetched and encoded; local file paths (`.png`/`.jpg`/`.webp`/...) are
|
|
106
204
|
* read via `node:fs` on Node.js; and `Buffer`/`Uint8Array` bytes are base64-encoded.
|
|
107
205
|
* Ollama's REST API only ever receives raw base64 strings.
|
|
206
|
+
*
|
|
207
|
+
* URL fetches, data-URI payloads, and file reads are governed by the
|
|
208
|
+
* client's `imageResolution` policy (byte caps, timeouts, redirect limits,
|
|
209
|
+
* host allowlist, SSRF guard — see `ImageResolutionPolicy`, ADR 0041).
|
|
108
210
|
*/
|
|
109
211
|
readonly images?: readonly VisionInput[] | undefined;
|
|
110
212
|
readonly tool_calls?: readonly ToolCall[] | undefined;
|
|
@@ -281,6 +383,10 @@ interface GenerateRequestOptions extends RequestCancellationOptions {
|
|
|
281
383
|
* URLs are fetched and encoded; local file paths (`.png`/`.jpg`/`.webp`/...) are
|
|
282
384
|
* read via `node:fs` on Node.js; and `Buffer`/`Uint8Array` bytes are base64-encoded.
|
|
283
385
|
* Ollama's REST API only ever receives raw base64 strings.
|
|
386
|
+
*
|
|
387
|
+
* URL fetches, data-URI payloads, and file reads are governed by the
|
|
388
|
+
* client's `imageResolution` policy (byte caps, timeouts, redirect limits,
|
|
389
|
+
* host allowlist, SSRF guard — see `ImageResolutionPolicy`, ADR 0041).
|
|
284
390
|
*/
|
|
285
391
|
readonly images?: readonly VisionInput[] | undefined;
|
|
286
392
|
readonly options?: ModelOptions | undefined;
|
|
@@ -560,4 +666,4 @@ type UsageGroupBy = 'model';
|
|
|
560
666
|
*/
|
|
561
667
|
type BalanceRequestOptions = RequestCancellationOptions;
|
|
562
668
|
|
|
563
|
-
export { type
|
|
669
|
+
export { resolveImageInput as $, type LogprobToken as A, type BalanceRequestOptions as B, type CreateRequestOptions as C, type DeleteRequestOptions as D, type EmbedRequestOptions as E, type FormatOption as F, type GenerateRequestOptions as G, type ModelDetails as H, type ImageResolutionPolicy as I, type Role as J, type ToolCallFunction as K, type ListResponse as L, type ModelResponse as M, type ToolFunctionDefinition as N, type ToolProperty as O, type PullRequestOptions as P, type UsageGroupBy as Q, type RequestCancellationOptions as R, type ShowRequestOptions as S, type ThinkingMetadata as T, type UsageRequestOptions as U, type VersionResponse as V, type WebSearchRequestOptions as W, type UsageRange as X, type UsageScope as Y, type WebSearchResult as Z, imageStringNeedsResolution as _, type ShowResponse as a, type ProgressResponse as b, type PushRequestOptions as c, type StatusResponse as d, type CopyRequestOptions as e, type PsResponse as f, type ToolParameters as g, type ThinkValue as h, type ToolCall as i, type ChatRequestOptions as j, type ModelOptions as k, type ToolDefinition as l, type ChatResponse as m, type Message as n, type GenerateResponse as o, type EmbedResponse as p, type EmbeddingsRequestOptions as q, type EmbeddingsResponse as r, type WebSearchResponse as s, type WebFetchRequestOptions as t, type WebFetchResponse as u, type PingResult as v, type VisionInput as w, type ImageAddress as x, type ImageFetchLike as y, type Logprob as z };
|
|
@@ -12,26 +12,36 @@
|
|
|
12
12
|
* Resolution order for `string` inputs:
|
|
13
13
|
*
|
|
14
14
|
* 1. `data:image/...;base64,` data URIs — the header is stripped, the
|
|
15
|
-
* payload passed through.
|
|
16
|
-
* 2. `http://` / `https://` URLs — fetched with the
|
|
17
|
-
* `fetch
|
|
15
|
+
* payload passed through (decoded size capped by `maxImageBytes`).
|
|
16
|
+
* 2. `http://` / `https://` URLs — fetched with the configured fetch
|
|
17
|
+
* implementation (the client's own `fetch` by default, see
|
|
18
|
+
* {@link ImageResolutionPolicy.fetchImpl}), then base64-encoded. Remote
|
|
19
|
+
* resolution is governed by {@link ImageResolutionPolicy}: the response
|
|
20
|
+
* body is size-capped *while streaming*, every fetch has a timeout, and
|
|
21
|
+
* an SSRF guard rejects private/loopback/link-local targets — hostname
|
|
22
|
+
* allowlists and redirect hops included (redirects are followed manually
|
|
23
|
+
* on Node so each hop is re-validated; see ADR 0041 for the
|
|
24
|
+
* browser/edge caveat).
|
|
18
25
|
* 3. Strings with a known image file extension (`.png`, `.jpg`, `.webp`,
|
|
19
26
|
* ...) — treated as a local file path and read via a *dynamically
|
|
20
|
-
* imported* `node:fs` (Node.js only)
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* a path-shaped string throws a descriptive error instead of
|
|
25
|
-
* shipping garbage to the server.
|
|
27
|
+
* imported* `node:fs` (Node.js only), size-capped via `maxImageBytes`.
|
|
28
|
+
* A failed read throws `vision_path_read_failed` instead of silently
|
|
29
|
+
* shipping the raw path string to the server (which could only reject
|
|
30
|
+
* it — see ADR 0041). In browsers/edge runtimes, where `node:fs` does
|
|
31
|
+
* not exist, a path-shaped string throws a descriptive error instead of
|
|
32
|
+
* silently shipping garbage to the server.
|
|
26
33
|
* 4. Anything else — assumed to already be raw base64 and passed through.
|
|
27
34
|
*
|
|
28
35
|
* `Buffer` and `Uint8Array` inputs are base64-encoded via the runtime's
|
|
29
36
|
* universal base64 primitive (`Buffer` on Node, `btoa` on the web), matching
|
|
30
|
-
* {@link encodeImage}.
|
|
37
|
+
* {@link encodeImage}. Direct byte inputs are *not* size-capped: the caller
|
|
38
|
+
* already holds those bytes in memory, and the resolution cost is already
|
|
39
|
+
* paid (see ADR 0041 for the threat model).
|
|
31
40
|
*
|
|
32
41
|
* Everything here is dependency-free and safe to import from the core client
|
|
33
|
-
* bundle: the `node:fs`
|
|
34
|
-
* never pull
|
|
42
|
+
* bundle: the `node:fs` and `node:dns/promises` imports are dynamic and
|
|
43
|
+
* guarded, so browser/edge builds never pull them in (see ADR 0006 — Edge
|
|
44
|
+
* Runtime CI).
|
|
35
45
|
*/
|
|
36
46
|
/**
|
|
37
47
|
* Polymorphic vision input accepted anywhere this SDK takes an `images` entry.
|
|
@@ -44,6 +54,89 @@
|
|
|
44
54
|
* published declarations stay free of `@types/node` globals (audit TYP-03).
|
|
45
55
|
*/
|
|
46
56
|
type VisionInput = string | Uint8Array;
|
|
57
|
+
/**
|
|
58
|
+
* Fetch signature accepted for remote image resolution. Deliberately a
|
|
59
|
+
* structural subset of the global `fetch` (and of the client's configured
|
|
60
|
+
* `fetch`), so either can be passed without adaptation.
|
|
61
|
+
*/
|
|
62
|
+
type ImageFetchLike = (url: string, init?: {
|
|
63
|
+
redirect?: 'manual' | 'follow';
|
|
64
|
+
signal?: AbortSignal;
|
|
65
|
+
} | undefined) => Promise<Response>;
|
|
66
|
+
/** One address-resolution result, mirroring `node:dns`' `LookupAddress` shape. */
|
|
67
|
+
interface ImageAddress {
|
|
68
|
+
readonly address: string;
|
|
69
|
+
readonly family: number;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Policy applied whenever a vision input needs resolution — URL fetches,
|
|
73
|
+
* data-URI decoding, and local file reads. Set it once per client via
|
|
74
|
+
* `OllamaClientConfig.imageResolution`, or per call through the lower-level
|
|
75
|
+
* {@link resolveImages} / {@link resolveImageInput} signatures.
|
|
76
|
+
*
|
|
77
|
+
* Defaults are chosen so the common cases keep working while the failure
|
|
78
|
+
* modes an untrusted input can trigger (oversized bodies, slow or looping
|
|
79
|
+
* fetches, requests into private networks) fail closed with a clear error.
|
|
80
|
+
* See ADR 0041 for the full rationale.
|
|
81
|
+
*/
|
|
82
|
+
interface ImageResolutionPolicy {
|
|
83
|
+
/**
|
|
84
|
+
* Hard cap on the *decoded* image size, in bytes. Applies to remote fetch
|
|
85
|
+
* bodies (enforced while streaming, before the body is buffered), to local
|
|
86
|
+
* file reads (enforced via `stat` before the read), and to data-URI
|
|
87
|
+
* payloads. Direct `Uint8Array`/`Buffer` inputs are not capped. Default:
|
|
88
|
+
* 50 MiB.
|
|
89
|
+
*/
|
|
90
|
+
readonly maxImageBytes?: number | undefined;
|
|
91
|
+
/**
|
|
92
|
+
* Timeout for the whole remote fetch — connection, redirects, and body
|
|
93
|
+
* read combined. Default: 30 000 ms.
|
|
94
|
+
*/
|
|
95
|
+
readonly fetchTimeoutMs?: number | undefined;
|
|
96
|
+
/**
|
|
97
|
+
* Maximum redirect hops followed for a remote image. Every hop is
|
|
98
|
+
* re-validated against the host policy and the private-address guard (on
|
|
99
|
+
* Node, where redirects are followed manually). Default: 5.
|
|
100
|
+
*/
|
|
101
|
+
readonly maxRedirects?: number | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Allowlist of hosts remote images may be fetched from. Exact hostnames
|
|
104
|
+
* (case-insensitive), `*.example.com` wildcards for subdomains, or `'*'`
|
|
105
|
+
* for any host. `undefined` (default) allows any host — the
|
|
106
|
+
* private-address guard still applies.
|
|
107
|
+
*/
|
|
108
|
+
readonly allowedImageHosts?: readonly string[] | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* Permit fetching remote images from private, loopback, link-local, or
|
|
111
|
+
* otherwise reserved addresses (and from hostnames that resolve to them).
|
|
112
|
+
* Default: `false` — the SSRF guard. Flip it to `true` only for clients
|
|
113
|
+
* whose image URLs are trusted and genuinely live on a private network
|
|
114
|
+
* (e.g. an internal image service in the same subnet as the app).
|
|
115
|
+
*/
|
|
116
|
+
readonly allowPrivateNetworkAccess?: boolean | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* Permit resolving local file paths (`/path/to.png`). Default: `true`
|
|
119
|
+
* (the historical behavior). Set to `false` when image input is untrusted
|
|
120
|
+
* and filesystem reads must not happen at all.
|
|
121
|
+
*/
|
|
122
|
+
readonly allowLocalFileReads?: boolean | undefined;
|
|
123
|
+
/**
|
|
124
|
+
* Fetch implementation used for URL resolution. Defaults to the client's
|
|
125
|
+
* configured `fetch` (and to the platform's global `fetch` when called
|
|
126
|
+
* outside a client), so image fetches flow through whatever proxy, agent,
|
|
127
|
+
* or mock the caller already installed. Bypassed never — the resolver
|
|
128
|
+
* always uses this path, not a bare global, when resolving URLs.
|
|
129
|
+
*/
|
|
130
|
+
readonly fetchImpl?: ImageFetchLike | undefined;
|
|
131
|
+
/**
|
|
132
|
+
* Address resolver used by the private-network guard for non-literal
|
|
133
|
+
* hostnames. Defaults to `node:dns/promises` `lookup` on Node-like
|
|
134
|
+
* runtimes and to a hostname-heuristics-only check elsewhere (browsers and
|
|
135
|
+
* edge runtimes have no DNS API — see ADR 0041). Injectable so callers can
|
|
136
|
+
* resolve through DoH, a cache, or a test double.
|
|
137
|
+
*/
|
|
138
|
+
readonly addressLookup?: ((hostname: string) => Promise<readonly ImageAddress[]>) | undefined | undefined;
|
|
139
|
+
}
|
|
47
140
|
/**
|
|
48
141
|
* Cheap synchronous check: does this string input require async resolution
|
|
49
142
|
* (data-URI stripping, URL fetch, or file read), or is it already wire-ready
|
|
@@ -54,13 +147,18 @@ declare function imageStringNeedsResolution(input: string): boolean;
|
|
|
54
147
|
/**
|
|
55
148
|
* Resolves any supported vision input into the raw base64 string Ollama's
|
|
56
149
|
* REST API expects — no data-URI headers, no URL/path indirection left
|
|
57
|
-
* behind. See the module doc for the full resolution order
|
|
150
|
+
* behind. See the module doc for the full resolution order and
|
|
151
|
+
* {@link ImageResolutionPolicy} for the trust-boundary and resource-limit
|
|
152
|
+
* knobs.
|
|
58
153
|
*
|
|
59
|
-
* @throws {OllamaClientError} if a URL fetch fails (non-2xx
|
|
60
|
-
*
|
|
61
|
-
*
|
|
154
|
+
* @throws {OllamaClientError} if a URL fetch fails (non-2xx, timeout,
|
|
155
|
+
* oversize, redirect limit, host not allowed, private address blocked, or
|
|
156
|
+
* unsupported protocol), if a local file read fails, is disabled, or is
|
|
157
|
+
* oversize, or if a path-shaped string is passed in a runtime without
|
|
158
|
+
* `node:fs` (browser/edge) — in that environment, read the file yourself and
|
|
159
|
+
* pass the bytes.
|
|
62
160
|
*/
|
|
63
|
-
declare function resolveImageInput(input: VisionInput, signal?: AbortSignal | undefined): Promise<string>;
|
|
161
|
+
declare function resolveImageInput(input: VisionInput, signal?: AbortSignal | undefined, policy?: ImageResolutionPolicy | undefined): Promise<string>;
|
|
64
162
|
|
|
65
163
|
/**
|
|
66
164
|
* Core protocol and message types for the Ollama REST API.
|
|
@@ -105,6 +203,10 @@ interface Message {
|
|
|
105
203
|
* URLs are fetched and encoded; local file paths (`.png`/`.jpg`/`.webp`/...) are
|
|
106
204
|
* read via `node:fs` on Node.js; and `Buffer`/`Uint8Array` bytes are base64-encoded.
|
|
107
205
|
* Ollama's REST API only ever receives raw base64 strings.
|
|
206
|
+
*
|
|
207
|
+
* URL fetches, data-URI payloads, and file reads are governed by the
|
|
208
|
+
* client's `imageResolution` policy (byte caps, timeouts, redirect limits,
|
|
209
|
+
* host allowlist, SSRF guard — see `ImageResolutionPolicy`, ADR 0041).
|
|
108
210
|
*/
|
|
109
211
|
readonly images?: readonly VisionInput[] | undefined;
|
|
110
212
|
readonly tool_calls?: readonly ToolCall[] | undefined;
|
|
@@ -281,6 +383,10 @@ interface GenerateRequestOptions extends RequestCancellationOptions {
|
|
|
281
383
|
* URLs are fetched and encoded; local file paths (`.png`/`.jpg`/`.webp`/...) are
|
|
282
384
|
* read via `node:fs` on Node.js; and `Buffer`/`Uint8Array` bytes are base64-encoded.
|
|
283
385
|
* Ollama's REST API only ever receives raw base64 strings.
|
|
386
|
+
*
|
|
387
|
+
* URL fetches, data-URI payloads, and file reads are governed by the
|
|
388
|
+
* client's `imageResolution` policy (byte caps, timeouts, redirect limits,
|
|
389
|
+
* host allowlist, SSRF guard — see `ImageResolutionPolicy`, ADR 0041).
|
|
284
390
|
*/
|
|
285
391
|
readonly images?: readonly VisionInput[] | undefined;
|
|
286
392
|
readonly options?: ModelOptions | undefined;
|
|
@@ -560,4 +666,4 @@ type UsageGroupBy = 'model';
|
|
|
560
666
|
*/
|
|
561
667
|
type BalanceRequestOptions = RequestCancellationOptions;
|
|
562
668
|
|
|
563
|
-
export { type
|
|
669
|
+
export { resolveImageInput as $, type LogprobToken as A, type BalanceRequestOptions as B, type CreateRequestOptions as C, type DeleteRequestOptions as D, type EmbedRequestOptions as E, type FormatOption as F, type GenerateRequestOptions as G, type ModelDetails as H, type ImageResolutionPolicy as I, type Role as J, type ToolCallFunction as K, type ListResponse as L, type ModelResponse as M, type ToolFunctionDefinition as N, type ToolProperty as O, type PullRequestOptions as P, type UsageGroupBy as Q, type RequestCancellationOptions as R, type ShowRequestOptions as S, type ThinkingMetadata as T, type UsageRequestOptions as U, type VersionResponse as V, type WebSearchRequestOptions as W, type UsageRange as X, type UsageScope as Y, type WebSearchResult as Z, imageStringNeedsResolution as _, type ShowResponse as a, type ProgressResponse as b, type PushRequestOptions as c, type StatusResponse as d, type CopyRequestOptions as e, type PsResponse as f, type ToolParameters as g, type ThinkValue as h, type ToolCall as i, type ChatRequestOptions as j, type ModelOptions as k, type ToolDefinition as l, type ChatResponse as m, type Message as n, type GenerateResponse as o, type EmbedResponse as p, type EmbeddingsRequestOptions as q, type EmbeddingsResponse as r, type WebSearchResponse as s, type WebFetchRequestOptions as t, type WebFetchResponse as u, type PingResult as v, type VisionInput as w, type ImageAddress as x, type ImageFetchLike as y, type Logprob as z };
|