summaryrefslogtreecommitdiff
path: root/src/background/ollama-client.js
blob: e53d997e1d921f413d0fadbbf05bd8c8a721335e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
 * Ollama REST API client (background only).
 *
 * Uses the browser Fetch API directly against the Ollama REST API.
 * - GET  {host}/api/tags  : list installed models
 * - POST {host}/api/chat  : streaming chat completion (NDJSON)
 *
 * Security rules implemented here (Security.md §4):
 * - the host is re-validated immediately before each request;
 * - NDJSON is parsed with a buffering line reader that tolerates chunk
 *   boundaries falling inside a JSON object;
 * - requests can be aborted via AbortController.
 */

import { isValidOllamaHost } from '../shared/settings-schema.js';
import { ERROR_CODES } from '../shared/constants.js';

/**
 * Extract a short error message from an Ollama JSON error body.
 * @param {string} raw
 * @returns {string} message or '' when not parseable
 */
function extractOllamaError(raw) {
  if (!raw) return '';
  try {
    const parsed = JSON.parse(raw);
    if (parsed && typeof parsed.error === 'string') {
      return parsed.error.slice(0, 200);
    }
  } catch {
    // not JSON
  }
  return '';
}

/**
 * Translate a fetch/HTTP failure into a stable error code.
 * @param {Response|undefined} response
 * @returns {string} error code
 */
function statusCodeToError(status) {
  if (status === 404) return ERROR_CODES.MODEL_NOT_FOUND;
  if (status === 400 || status === 403) return ERROR_CODES.INVALID_SETTINGS;
  if (status >= 500) return ERROR_CODES.STREAM_ERROR;
  return ERROR_CODES.STREAM_ERROR;
}

/**
 * Assert that the host is allowed. Throws Error with code attached.
 * @param {string} host
 */
function assertAllowedHost(host) {
  if (!isValidOllamaHost(host)) {
    const error = new Error('Invalid Ollama host');
    error.code = ERROR_CODES.INVALID_SETTINGS;
    throw error;
  }
}

/**
 * Normalize an error thrown by fetch into an extension error code.
 * @param {*} error
 * @param {{aborted?: boolean, code?: string}} [options]
 * @returns {Error}
 */
export function toExtensionError(error, { aborted = false, code = ERROR_CODES.OLLAMA_UNAVAILABLE } = {}) {
  if (error && error.name === 'AbortError') {
    const e = new Error('Request aborted');
    e.code = ERROR_CODES.REQUEST_ABORTED;
    return e;
  }
  if (error && error.code) return error;
  // fetch() rejects on network failures (Ollama not running etc.)
  const e = new Error(error instanceof Error ? error.message : 'Unknown Ollama error');
  e.code = aborted ? ERROR_CODES.REQUEST_ABORTED : code;
  return e;
}

/**
 * List models installed in Ollama.
 * @param {string} host validated host
 * @param {AbortSignal} [signal]
 * @returns {Promise<string[]>} model names
 */
export async function listModels(host, signal) {
  assertAllowedHost(host);
  let response;
  try {
    response = await fetch(`${host}/api/tags`, { method: 'GET', signal });
  } catch (error) {
    throw toExtensionError(error);
  }
  if (!response.ok) {
    const detail = await response.text().catch(() => '');
    const serverMessage = extractOllamaError(detail);
    const e = new Error(`Ollama /api/tags failed: ${response.status}${serverMessage ? ` - ${serverMessage}` : ''}`);
    e.code = response.status === 404 ? ERROR_CODES.MODEL_NOT_FOUND : ERROR_CODES.STREAM_ERROR;
    throw e;
  }
  const data = await response.json();
  if (!data || !Array.isArray(data.models)) return [];
  return data.models.map((m) => (m && typeof m.name === 'string' ? m.name : '')).filter((name) => name.length > 0);
}

/**
 * Stream a chat completion. Calls handlers for each incremental text chunk.
 *
 * @param {object} params
 * @param {string} params.host validated Ollama host
 * @param {string} params.model
 * @param {Array<{role: string, content: string}>} params.messages
 * @param {boolean|string} [params.think] true | 'low' | 'medium' | 'high'; omit when off
 * @param {object} params.options Ollama options object
 * @param {(text: string, thinking: string) => void} params.onChunk
 * @param {AbortSignal} [params.signal]
 * @returns {Promise<void>} resolves when the stream completes
 */
export async function chatStream({ host, model, messages, think, options, onChunk, signal }) {
  assertAllowedHost(host);

  const body = { model, messages, stream: true };
  if (think !== undefined) {
    body.think = think;
  }
  if (options && Object.keys(options).length > 0) {
    body.options = options;
  }

  let response;
  try {
    response = await fetch(`${host}/api/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
      signal
    });
  } catch (error) {
    throw toExtensionError(error, { aborted: isAbortError(error) });
  }

  if (!response.ok) {
    const detail = await response.text().catch(() => '');
    const serverMessage = extractOllamaError(detail);
    const e = new Error(`Ollama /api/chat failed: ${response.status}${serverMessage ? ` - ${serverMessage}` : ''}`);
    e.code =
      response.status === 404
        ? ERROR_CODES.MODEL_NOT_FOUND
        : response.status === 400 || response.status === 403
          ? ERROR_CODES.INVALID_SETTINGS
          : ERROR_CODES.STREAM_ERROR;
    throw e;
  }
  if (!response.body) {
    const e = new Error('Ollama response has no body');
    e.code = ERROR_CODES.STREAM_ERROR;
    throw e;
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  const processLine = (line) => {
    if (!line) return;
    let parsed;
    try {
      parsed = JSON.parse(line);
    } catch {
      // Malformed line: skip it rather than crashing the stream.
      return;
    }
    if (parsed === null || typeof parsed !== 'object') return;
    if (parsed.error) {
      const e = new Error(String(parsed.error));
      e.code = typeof parsed.error === 'string' && /not found/i.test(parsed.error) ? ERROR_CODES.MODEL_NOT_FOUND : ERROR_CODES.STREAM_ERROR;
      throw e;
    }
    const content = parsed.message && typeof parsed.message.content === 'string' ? parsed.message.content : '';
    const thinking = parsed.message && typeof parsed.message.thinking === 'string' ? parsed.message.thinking : '';
    if (content || thinking) {
      onChunk(content, thinking);
    }
  };

  try {
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      let newlineIndex;
      while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
        const line = buffer.slice(0, newlineIndex).replace(/\r$/, '');
        buffer = buffer.slice(newlineIndex + 1);
        processLine(line);
      }
    }
    // Flush any remaining buffered line.
    const tail = buffer.replace(/\r$/, '');
    if (tail) processLine(tail);
  } catch (error) {
    if (isAbortError(error)) {
      const e = new Error('Request aborted');
      e.code = ERROR_CODES.REQUEST_ABORTED;
      throw e;
    }
    throw error && error.code ? error : toExtensionError(error, { code: ERROR_CODES.STREAM_ERROR });
  }
}

/**
 * @param {*} error
 * @returns {boolean}
 */
function isAbortError(error) {
  return Boolean(error && (error.name === 'AbortError' || error.code === ERROR_CODES.REQUEST_ABORTED));
}