@abhishek944/pi-embeddings 0.4.0 → 0.6.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/src/providers.ts CHANGED
@@ -6,35 +6,174 @@ import {
6
6
  EMBEDDING_FORMAT_VERSION,
7
7
  EMBEDDING_NORMALIZATION_VERSION,
8
8
  CLOUDFLARE_EMBEDDING_MODELS,
9
+ COHERE_EMBEDDING_DIMENSIONS,
10
+ COHERE_EMBEDDING_MODELS,
11
+ DASHSCOPE_EMBEDDING_DIMENSIONS,
12
+ DASHSCOPE_EMBEDDING_MODELS,
13
+ DEFAULT_COHERE_DIMENSIONS,
14
+ DEFAULT_DASHSCOPE_DIMENSIONS,
9
15
  DEFAULT_GEMINI_DIMENSIONS,
10
16
  DEFAULT_GEMINI_TASK_FORMAT,
17
+ DEFAULT_VOYAGE_DIMENSIONS,
11
18
  GEMINI_EMBEDDING_MODELS,
12
19
  GEMINI_TASK_PREFIXES,
20
+ HETZNER_EMBEDDING_DIMENSIONS,
21
+ HETZNER_EMBEDDING_MODELS,
22
+ JINA_EMBEDDING_DIMENSIONS,
23
+ JINA_EMBEDDING_MODELS,
24
+ OPENAI_EMBEDDING_DIMENSIONS,
25
+ OPENAI_EMBEDDING_MODELS,
26
+ OPENCODE_EMBEDDING_MODELS,
27
+ OPENCODE_GO_EMBEDDING_MODELS,
13
28
  OPENROUTER_EMBEDDING_MODELS,
29
+ VOYAGE_EMBEDDING_DIMENSIONS,
30
+ VOYAGE_EMBEDDING_MODELS,
31
+ type CohereEmbeddingDimension,
32
+ type CohereEmbeddingModel,
33
+ type DashScopeEmbeddingDimension,
14
34
  type EmbeddingContext,
15
35
  type EmbeddingRoute,
16
36
  type EmbeddingSettings,
17
37
  type EmbeddingSpace,
18
38
  type GeminiEmbeddingDimension,
19
39
  type GeminiEmbeddingTaskFormat,
40
+ type JinaEmbeddingModel,
41
+ type OpenAiEmbeddingModel,
42
+ type OpenCodeEmbeddingModel,
43
+ type OpenCodeGoEmbeddingModel,
44
+ type OpenCodeRouteId,
45
+ type OpenRouterEmbeddingModel,
46
+ type VoyageEmbeddingDimension,
47
+ type VoyageEmbeddingModel,
20
48
  } from './schemas.js';
21
49
  import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
22
50
  import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE, type AcquiredLocalRuntime } from './local-runtime.js';
23
- import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
51
+ import type {
52
+ EmbeddingCredentialResolver,
53
+ EmbeddingsProvider,
54
+ PreparedInput,
55
+ ProviderBatchResult,
56
+ } from './provider-types.js';
24
57
  import {
25
58
  parseBatchResponse,
26
59
  parseCloudflareBatchResponse,
60
+ parseCohereBatchResponse,
27
61
  parseGeminiCountTokensResponse,
28
62
  parseGeminiEmbeddingResponse,
63
+ parseOpenCodeBatchResponse,
64
+ parseOptionalUsageBatchResponse,
65
+ parseVoyageBatchResponse,
29
66
  } from './response.js';
30
67
 
31
- export const OPENAI_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
32
- provider: 'openai',
33
- model: 'text-embedding-3-small',
68
+ export const openaiEmbeddingSpace = (model: OpenAiEmbeddingModel): EmbeddingSpace => {
69
+ const common = {
70
+ provider: 'openai' as const,
71
+ revision: null,
72
+ quantization: null,
73
+ runtime: null,
74
+ format: EMBEDDING_FORMAT_VERSION,
75
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
76
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
77
+ } as const;
78
+ // Dimension is bound to the model so the descriptor cannot record an impossible pair.
79
+ if (model === 'text-embedding-3-large')
80
+ return Object.freeze({
81
+ ...common,
82
+ model: 'text-embedding-3-large' as const,
83
+ dimensions: OPENAI_EMBEDDING_DIMENSIONS['text-embedding-3-large'],
84
+ });
85
+ return Object.freeze({
86
+ ...common,
87
+ model: 'text-embedding-3-small' as const,
88
+ dimensions: OPENAI_EMBEDDING_DIMENSIONS['text-embedding-3-small'],
89
+ });
90
+ };
91
+
92
+ export const OPENAI_EMBEDDING_SPACE: EmbeddingSpace = openaiEmbeddingSpace('text-embedding-3-small');
93
+
94
+ export const voyageEmbeddingSpace = (config: {
95
+ model: VoyageEmbeddingModel;
96
+ dimensions: VoyageEmbeddingDimension;
97
+ }): EmbeddingSpace =>
98
+ Object.freeze({
99
+ provider: 'voyage',
100
+ model: config.model,
101
+ revision: null,
102
+ quantization: null,
103
+ runtime: 'voyage-api-v1',
104
+ dimensions: config.dimensions,
105
+ inputType: 'document',
106
+ format: EMBEDDING_FORMAT_VERSION,
107
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
108
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
109
+ });
110
+
111
+ export const cohereEmbeddingSpace = (config: {
112
+ model: CohereEmbeddingModel;
113
+ dimensions: CohereEmbeddingDimension;
114
+ }): EmbeddingSpace =>
115
+ Object.freeze({
116
+ provider: 'cohere',
117
+ model: config.model,
118
+ revision: null,
119
+ quantization: null,
120
+ runtime: 'cohere-api-v2',
121
+ dimensions: config.dimensions,
122
+ inputType: 'search_document',
123
+ format: EMBEDDING_FORMAT_VERSION,
124
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
125
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
126
+ });
127
+
128
+ /** Jina's declared default is the largest documented Matryoshka size for that model. */
129
+ const jinaDefaultDimensions = (model: JinaEmbeddingModel): number => {
130
+ const documented = JINA_EMBEDDING_DIMENSIONS[model];
131
+ const largest = documented[documented.length - 1];
132
+ if (largest === undefined) throw new EmbeddingsError('configuration-invalid');
133
+ return largest;
134
+ };
135
+
136
+ /** Jina documents per-model Matryoshka sizes; an undeclared size is a configuration error. */
137
+ export const jinaEmbeddingSpace = (config: {
138
+ model: JinaEmbeddingModel;
139
+ dimensions: number;
140
+ }): EmbeddingSpace => {
141
+ if (!JINA_EMBEDDING_DIMENSIONS[config.model].includes(config.dimensions))
142
+ throw new EmbeddingsError('configuration-invalid');
143
+ return Object.freeze({
144
+ provider: 'jina',
145
+ model: config.model,
146
+ revision: null,
147
+ quantization: null,
148
+ runtime: 'jina-api-v1',
149
+ dimensions: config.dimensions,
150
+ task: 'retrieval.passage',
151
+ format: EMBEDDING_FORMAT_VERSION,
152
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
153
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
154
+ });
155
+ };
156
+
157
+ export const dashScopeEmbeddingSpace = (dimensions: DashScopeEmbeddingDimension): EmbeddingSpace =>
158
+ Object.freeze({
159
+ provider: 'dashscope',
160
+ model: DASHSCOPE_EMBEDDING_MODELS[0],
161
+ revision: null,
162
+ quantization: null,
163
+ runtime: 'dashscope-compatible-mode-v1',
164
+ dimensions,
165
+ format: EMBEDDING_FORMAT_VERSION,
166
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
167
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
168
+ });
169
+
170
+ export const HETZNER_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
171
+ provider: 'hetzner',
172
+ model: HETZNER_EMBEDDING_MODELS[0],
34
173
  revision: null,
35
174
  quantization: null,
36
- runtime: null,
37
- dimensions: 1536,
175
+ runtime: 'hetzner-inference-v1',
176
+ dimensions: HETZNER_EMBEDDING_DIMENSIONS,
38
177
  format: EMBEDDING_FORMAT_VERSION,
39
178
  prefix: EMBEDDING_DOCUMENT_PREFIX,
40
179
  normalization: EMBEDDING_NORMALIZATION_VERSION,
@@ -85,6 +224,12 @@ export const geminiEmbeddingSpace = (config: {
85
224
  normalization: EMBEDDING_NORMALIZATION_VERSION,
86
225
  });
87
226
 
227
+ export const OPENCODE_CONSOLE_EMBEDDINGS_URL =
228
+ 'https://opencode.ai/inference/openai/v1/embeddings';
229
+ export const OPENCODE_GO_EMBEDDINGS_URL =
230
+ 'https://opencode.ai/inference/go/openai/v1/embeddings';
231
+ const OPENCODE_USER_AGENT = 'pi-embeddings';
232
+
88
233
  const OPENAI_MODEL = 'text-embedding-3-small';
89
234
  const SARVAM_MODEL = 'embeddinggemma-2';
90
235
  const SARVAM_ORIGIN = 'https://api.sarvam.ai';
@@ -97,6 +242,69 @@ const OPENAI_MAX_INPUT_TOKENS = 8192;
97
242
  const OPENAI_MAX_REQUEST_INPUTS = 2048;
98
243
  const OPENAI_MAX_REQUEST_TOKENS = 300000;
99
244
 
245
+ /** Voyage documents a 1000-input list ceiling; aggregate caps are provider-enforced only. */
246
+ const VOYAGE_ORIGIN = 'https://api.voyageai.com';
247
+ const VOYAGE_MAX_REQUEST_INPUTS = 1000;
248
+ /** Cohere documents a maximum of 96 texts per call. */
249
+ const COHERE_ORIGIN = 'https://api.cohere.com';
250
+ const COHERE_MAX_REQUEST_INPUTS = 96;
251
+ /** Jina publishes RPM/TPM rate limits but no per-request input count ceiling. */
252
+ const JINA_EMBEDDINGS_URL = 'https://api.jina.ai/v1/embeddings';
253
+ /** Model Studio documents at most 20 rows per request for qwen3.7-text-embedding. */
254
+ const DASHSCOPE_EMBEDDINGS_PATH = '/compatible-mode/v1/embeddings';
255
+ const DASHSCOPE_MAX_REQUEST_INPUTS = 20;
256
+ /** Hetzner publishes a 32 MiB body ceiling and about 1M recommended tokens, no count cap. */
257
+ const HETZNER_EMBEDDINGS_URL = 'https://inference.hetzner.com/v1/embeddings';
258
+
259
+ const VOYAGE_INPUT_TYPE = 'document' as const;
260
+ const COHERE_INPUT_TYPE = 'search_document' as const;
261
+ const JINA_TASK = 'retrieval.passage' as const;
262
+
263
+ const isOneOf = <T extends string>(values: readonly T[], value: string): value is T =>
264
+ values.some((candidate) => candidate === value);
265
+
266
+ export const opencodeEmbeddingSpace = (args: {
267
+ provider: OpenCodeRouteId;
268
+ model: string;
269
+ dimensions: number | null;
270
+ }): EmbeddingSpace => {
271
+ const common: {
272
+ readonly revision: null;
273
+ readonly quantization: null;
274
+ readonly dimensions: number | null;
275
+ readonly format: typeof EMBEDDING_FORMAT_VERSION;
276
+ readonly prefix: typeof EMBEDDING_DOCUMENT_PREFIX;
277
+ readonly normalization: typeof EMBEDDING_NORMALIZATION_VERSION;
278
+ } = {
279
+ revision: null,
280
+ quantization: null,
281
+ dimensions: args.dimensions,
282
+ format: EMBEDDING_FORMAT_VERSION,
283
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
284
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
285
+ };
286
+ if (args.provider === 'opencode') {
287
+ if (!isOneOf<OpenCodeEmbeddingModel>(OPENCODE_EMBEDDING_MODELS, args.model))
288
+ throw new EmbeddingsError('configuration-invalid');
289
+ const space: EmbeddingSpace = {
290
+ ...common,
291
+ provider: 'opencode',
292
+ model: args.model,
293
+ runtime: 'opencode-console-embeddings-v1',
294
+ };
295
+ return Object.freeze(space);
296
+ }
297
+ if (!isOneOf<OpenCodeGoEmbeddingModel>(OPENCODE_GO_EMBEDDING_MODELS, args.model))
298
+ throw new EmbeddingsError('configuration-invalid');
299
+ const space: EmbeddingSpace = {
300
+ ...common,
301
+ provider: 'opencode-go',
302
+ model: args.model,
303
+ runtime: 'opencode-go-embeddings-v1',
304
+ };
305
+ return Object.freeze(space);
306
+ };
307
+
100
308
  const trim = (value: string | undefined): string | undefined => {
101
309
  const trimmed = value?.trim();
102
310
  return trimmed === undefined || trimmed === '' ? undefined : trimmed;
@@ -104,13 +312,19 @@ const trim = (value: string | undefined): string | undefined => {
104
312
 
105
313
  export const routeKey = (route: EmbeddingRoute): string => `${route.provider}\u0000${route.model}`;
106
314
 
315
+ export type OpenCodeCredentialAvailability = Readonly<Partial<Record<OpenCodeRouteId, boolean>>>;
316
+
107
317
  export type EmbeddingDiagnostic = Readonly<{
108
318
  readonly code: string;
109
319
  readonly severity: 'error' | 'warning' | 'info';
110
320
  }>;
111
321
 
112
322
  /** Diagnostics are provider-free and never contain keys, origins or model paths. */
113
- export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[] {
323
+ export function routeDiagnostics(
324
+ settings: EmbeddingSettings,
325
+ route: EmbeddingRoute,
326
+ piCredentialAvailable: OpenCodeCredentialAvailability = {}
327
+ ): EmbeddingDiagnostic[] {
114
328
  const diagnostics: EmbeddingDiagnostic[] = [];
115
329
  const add = (code: string, severity: EmbeddingDiagnostic['severity'] = 'error'): void => {
116
330
  diagnostics.push({ code, severity });
@@ -156,10 +370,53 @@ export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRo
156
370
  if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
157
371
  add('gemini-key-unconfigured');
158
372
  break;
373
+ case 'opencode':
374
+ if (
375
+ trim(settings.providers?.opencode?.apiKey) === undefined &&
376
+ trim(process.env.OPENCODE_API_KEY) === undefined &&
377
+ piCredentialAvailable.opencode !== true
378
+ )
379
+ add('opencode-key-unconfigured');
380
+ break;
381
+ case 'opencode-go':
382
+ if (
383
+ trim(settings.providers?.['opencode-go']?.apiKey) === undefined &&
384
+ trim(process.env.OPENCODE_API_KEY) === undefined &&
385
+ piCredentialAvailable['opencode-go'] !== true
386
+ )
387
+ add('opencode-go-key-unconfigured');
388
+ break;
159
389
  case 'vertex':
160
390
  if (settings.providers?.vertex === undefined) add('vertex-configuration-unconfigured');
161
391
  // Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
162
392
  break;
393
+ case 'voyage':
394
+ if (trim(settings.providers?.voyage?.apiKey) === undefined && trim(process.env.VOYAGE_API_KEY) === undefined)
395
+ add('voyage-key-unconfigured');
396
+ break;
397
+ case 'cohere':
398
+ if (trim(settings.providers?.cohere?.apiKey) === undefined && trim(process.env.COHERE_API_KEY) === undefined)
399
+ add('cohere-key-unconfigured');
400
+ break;
401
+ case 'jina':
402
+ if (trim(settings.providers?.jina?.apiKey) === undefined && trim(process.env.JINA_API_KEY) === undefined)
403
+ add('jina-key-unconfigured');
404
+ break;
405
+ case 'dashscope': {
406
+ const dashscope = settings.providers?.dashscope;
407
+ if (trim(dashscope?.baseUrl) === undefined && trim(process.env.DASHSCOPE_BASE_URL) === undefined)
408
+ add('dashscope-base-url-unconfigured');
409
+ if (trim(dashscope?.apiKey) === undefined && trim(process.env.DASHSCOPE_API_KEY) === undefined)
410
+ add('dashscope-key-unconfigured');
411
+ break;
412
+ }
413
+ case 'hetzner':
414
+ if (
415
+ trim(settings.providers?.hetzner?.apiKey) === undefined &&
416
+ trim(process.env.HETZNER_INFERENCE_TOKEN) === undefined
417
+ )
418
+ add('hetzner-key-unconfigured');
419
+ break;
163
420
  }
164
421
  return diagnostics;
165
422
  }
@@ -176,6 +433,34 @@ const headerCredential = (configured: string | undefined, env: string | undefine
176
433
  return value;
177
434
  };
178
435
 
436
+ const safeHeaderValue = (value: string): string => {
437
+ if (!headerValueIsSafe(value)) throw new EmbeddingsError('configuration-invalid');
438
+ return value;
439
+ };
440
+
441
+ /** Host-provided provider keys are read only when a route is acquired; errors never carry a value. */
442
+ async function openCodeCredential(args: {
443
+ route: OpenCodeRouteId;
444
+ settings: EmbeddingSettings;
445
+ resolver: EmbeddingCredentialResolver | undefined;
446
+ }): Promise<string> {
447
+ const configured =
448
+ args.route === 'opencode'
449
+ ? args.settings.providers?.opencode?.apiKey
450
+ : args.settings.providers?.['opencode-go']?.apiKey;
451
+ const explicit = trim(configured);
452
+ if (explicit !== undefined) return safeHeaderValue(explicit);
453
+ if (args.resolver !== undefined) {
454
+ try {
455
+ const resolved = trim(await args.resolver(args.route));
456
+ if (resolved !== undefined) return safeHeaderValue(resolved);
457
+ } catch {
458
+ // A host resolver that cannot supply a key leaves the trusted environment fallback intact.
459
+ }
460
+ }
461
+ return headerCredential(undefined, process.env.OPENCODE_API_KEY);
462
+ }
463
+
179
464
  /** The documented text-string path avoids the token-array schema contradiction without truncating. */
180
465
  const openAIPrepare = (
181
466
  encoding: ReturnType<typeof getEncoding>,
@@ -199,16 +484,21 @@ const providerTexts = (inputs: readonly PreparedInput[]): string[] =>
199
484
  return input.text;
200
485
  });
201
486
 
487
+ const openRouterCanonicalModel = (model: OpenRouterEmbeddingModel): OpenAiEmbeddingModel =>
488
+ model === 'openai/text-embedding-3-large' ? 'text-embedding-3-large' : 'text-embedding-3-small';
489
+
202
490
  class OpenAiProvider implements EmbeddingsProvider {
203
491
  readonly route = 'openai' as const;
204
- readonly model = OPENAI_MODEL;
205
- readonly space: EmbeddingSpace = OPENAI_EMBEDDING_SPACE;
492
+ readonly model: OpenAiEmbeddingModel;
493
+ readonly space: EmbeddingSpace;
206
494
  readonly maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
207
495
  readonly maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
208
496
  readonly #encoding = getEncoding('cl100k_base');
209
497
  readonly #key: string;
210
498
 
211
- constructor(key: string) {
499
+ constructor(model: OpenAiEmbeddingModel, key: string) {
500
+ this.model = model;
501
+ this.space = openaiEmbeddingSpace(model);
212
502
  this.#key = key;
213
503
  }
214
504
 
@@ -241,6 +531,72 @@ class OpenAiProvider implements EmbeddingsProvider {
241
531
  }
242
532
  }
243
533
 
534
+ class OpenCodeProvider implements EmbeddingsProvider {
535
+ readonly route: OpenCodeRouteId;
536
+ readonly model: string;
537
+ readonly space: EmbeddingSpace;
538
+ // OpenCode documents per-input context requirements but publishes no aggregate request ceiling.
539
+ readonly maxRequestInputs = Number.POSITIVE_INFINITY;
540
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
541
+ readonly #url: URL;
542
+ readonly #key: string;
543
+
544
+ constructor(args: {
545
+ route: OpenCodeRouteId;
546
+ model: string;
547
+ key: string;
548
+ url: URL;
549
+ }) {
550
+ this.route = args.route;
551
+ this.model = args.model;
552
+ this.space = opencodeEmbeddingSpace({
553
+ provider: args.route,
554
+ model: args.model,
555
+ dimensions: null,
556
+ });
557
+ this.#url = args.url;
558
+ this.#key = args.key;
559
+ }
560
+
561
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
562
+ signal.throwIfAborted();
563
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
564
+ }
565
+
566
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
567
+ const parsed = parseOpenCodeBatchResponse({
568
+ response: await requestJson({
569
+ url: this.#url,
570
+ signal,
571
+ headers: {
572
+ authorization: `Bearer ${this.#key}`,
573
+ 'user-agent': OPENCODE_USER_AGENT,
574
+ },
575
+ body: {
576
+ model: this.model,
577
+ input: providerTexts(inputs),
578
+ encoding_format: 'float',
579
+ },
580
+ }),
581
+ expectedModels: [this.model],
582
+ expectedCount: inputs.length,
583
+ });
584
+ return {
585
+ vectors: parsed.vectors,
586
+ usage: parsed.usage,
587
+ space: opencodeEmbeddingSpace({
588
+ provider: this.route,
589
+ model: this.model,
590
+ dimensions: parsed.dimensions,
591
+ }),
592
+ };
593
+ }
594
+
595
+ async close(): Promise<void> {
596
+ // Native fetch owns no long-lived resource.
597
+ }
598
+ }
599
+
244
600
  class SarvamProvider implements EmbeddingsProvider {
245
601
  readonly route = 'sarvam' as const;
246
602
  readonly model = SARVAM_MODEL;
@@ -342,14 +698,16 @@ class GatewayProvider implements EmbeddingsProvider {
342
698
 
343
699
  class OpenRouterProvider implements EmbeddingsProvider {
344
700
  readonly route = 'openrouter' as const;
345
- readonly model = OPENROUTER_EMBEDDING_MODELS[0];
346
- readonly space: EmbeddingSpace = OPENAI_EMBEDDING_SPACE;
701
+ readonly model: OpenRouterEmbeddingModel;
702
+ readonly space: EmbeddingSpace;
347
703
  readonly maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
348
704
  readonly maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
349
705
  readonly #encoding = getEncoding('cl100k_base');
350
706
  readonly #key: string;
351
707
 
352
- constructor(key: string) {
708
+ constructor(model: OpenRouterEmbeddingModel, key: string) {
709
+ this.model = model;
710
+ this.space = openaiEmbeddingSpace(openRouterCanonicalModel(model));
353
711
  this.#key = key;
354
712
  }
355
713
 
@@ -384,6 +742,228 @@ class OpenRouterProvider implements EmbeddingsProvider {
384
742
  }
385
743
  }
386
744
 
745
+ class VoyageProvider implements EmbeddingsProvider {
746
+ readonly route = 'voyage' as const;
747
+ readonly model: VoyageEmbeddingModel;
748
+ readonly space: EmbeddingSpace;
749
+ // Voyage documents a 1000-input list ceiling; aggregate token caps stay provider-enforced.
750
+ readonly maxRequestInputs = VOYAGE_MAX_REQUEST_INPUTS;
751
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
752
+ readonly #key: string;
753
+
754
+ constructor(config: {
755
+ model: VoyageEmbeddingModel;
756
+ dimensions: VoyageEmbeddingDimension;
757
+ key: string;
758
+ }) {
759
+ this.model = config.model;
760
+ this.space = voyageEmbeddingSpace({ model: config.model, dimensions: config.dimensions });
761
+ this.#key = config.key;
762
+ }
763
+
764
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
765
+ signal.throwIfAborted();
766
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
767
+ }
768
+
769
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
770
+ const response = await requestJson({
771
+ url: new URL('/v1/embeddings', VOYAGE_ORIGIN),
772
+ signal,
773
+ headers: { authorization: `Bearer ${this.#key}` },
774
+ body: {
775
+ model: this.model,
776
+ input: providerTexts(inputs),
777
+ input_type: VOYAGE_INPUT_TYPE,
778
+ output_dimension: this.space.dimensions,
779
+ // This package never truncates, so an over-length input must fail instead of being cut.
780
+ truncation: false,
781
+ },
782
+ });
783
+ return parseVoyageBatchResponse({
784
+ response,
785
+ space: this.space,
786
+ expectedModels: [this.model],
787
+ expectedCount: inputs.length,
788
+ });
789
+ }
790
+
791
+ async close(): Promise<void> {
792
+ // Native fetch owns no long-lived resource.
793
+ }
794
+ }
795
+
796
+ class CohereProvider implements EmbeddingsProvider {
797
+ readonly route = 'cohere' as const;
798
+ readonly model: CohereEmbeddingModel;
799
+ readonly space: EmbeddingSpace;
800
+ /** Cohere rejects more than 96 texts in one call. */
801
+ readonly maxRequestInputs = COHERE_MAX_REQUEST_INPUTS;
802
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
803
+ readonly #key: string;
804
+
805
+ constructor(config: {
806
+ model: CohereEmbeddingModel;
807
+ dimensions: CohereEmbeddingDimension;
808
+ key: string;
809
+ }) {
810
+ this.model = config.model;
811
+ this.space = cohereEmbeddingSpace({ model: config.model, dimensions: config.dimensions });
812
+ this.#key = config.key;
813
+ }
814
+
815
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
816
+ signal.throwIfAborted();
817
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
818
+ }
819
+
820
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
821
+ const response = await requestJson({
822
+ url: new URL('/v2/embed', COHERE_ORIGIN),
823
+ signal,
824
+ headers: { authorization: `Bearer ${this.#key}` },
825
+ body: {
826
+ model: this.model,
827
+ input_type: COHERE_INPUT_TYPE,
828
+ texts: providerTexts(inputs),
829
+ embedding_types: ['float'],
830
+ output_dimension: this.space.dimensions,
831
+ // Default is END; refuse instead of silently shortening an over-length input.
832
+ truncate: 'NONE',
833
+ },
834
+ });
835
+ return parseCohereBatchResponse({ response, space: this.space, expectedCount: inputs.length });
836
+ }
837
+
838
+ async close(): Promise<void> {
839
+ // Native fetch owns no long-lived resource.
840
+ }
841
+ }
842
+
843
+ class JinaProvider implements EmbeddingsProvider {
844
+ readonly route = 'jina' as const;
845
+ readonly model: JinaEmbeddingModel;
846
+ readonly space: EmbeddingSpace;
847
+ // Jina publishes RPM/TPM limits but no per-request input count ceiling.
848
+ readonly maxRequestInputs = Number.POSITIVE_INFINITY;
849
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
850
+ readonly #key: string;
851
+
852
+ constructor(config: { model: JinaEmbeddingModel; dimensions: number; key: string }) {
853
+ this.model = config.model;
854
+ this.space = jinaEmbeddingSpace({ model: config.model, dimensions: config.dimensions });
855
+ this.#key = config.key;
856
+ }
857
+
858
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
859
+ signal.throwIfAborted();
860
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
861
+ }
862
+
863
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
864
+ const response = await requestJson({
865
+ url: new URL(JINA_EMBEDDINGS_URL),
866
+ signal,
867
+ headers: { authorization: `Bearer ${this.#key}` },
868
+ body: {
869
+ model: this.model,
870
+ input: providerTexts(inputs),
871
+ task: JINA_TASK,
872
+ dimensions: this.space.dimensions,
873
+ embedding_type: 'float',
874
+ // The package owns normalization and never truncates, so both are disabled explicitly.
875
+ normalized: false,
876
+ truncate: false,
877
+ },
878
+ });
879
+ return parseBatchResponse({ response, space: this.space, expectedModels: [this.model] });
880
+ }
881
+
882
+ async close(): Promise<void> {
883
+ // Native fetch owns no long-lived resource.
884
+ }
885
+ }
886
+
887
+ class DashScopeProvider implements EmbeddingsProvider {
888
+ readonly route = 'dashscope' as const;
889
+ readonly model = DASHSCOPE_EMBEDDING_MODELS[0];
890
+ readonly space: EmbeddingSpace;
891
+ /** Model Studio documents at most 20 rows per request for this model. */
892
+ readonly maxRequestInputs = DASHSCOPE_MAX_REQUEST_INPUTS;
893
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
894
+ readonly #url: URL;
895
+ readonly #key: string;
896
+
897
+ constructor(config: { origin: URL; dimensions: DashScopeEmbeddingDimension; key: string }) {
898
+ this.#url = new URL(DASHSCOPE_EMBEDDINGS_PATH, config.origin);
899
+ this.#key = config.key;
900
+ this.space = dashScopeEmbeddingSpace(config.dimensions);
901
+ }
902
+
903
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
904
+ signal.throwIfAborted();
905
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
906
+ }
907
+
908
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
909
+ const response = await requestJson({
910
+ url: this.#url,
911
+ signal,
912
+ headers: { authorization: `Bearer ${this.#key}` },
913
+ body: {
914
+ model: this.model,
915
+ input: providerTexts(inputs),
916
+ dimensions: this.space.dimensions,
917
+ encoding_format: 'float',
918
+ },
919
+ });
920
+ return parseBatchResponse({ response, space: this.space, expectedModels: [this.model] });
921
+ }
922
+
923
+ async close(): Promise<void> {
924
+ // Native fetch owns no long-lived resource.
925
+ }
926
+ }
927
+
928
+ class HetznerProvider implements EmbeddingsProvider {
929
+ readonly route = 'hetzner' as const;
930
+ readonly model = HETZNER_EMBEDDING_MODELS[0];
931
+ readonly space: EmbeddingSpace = HETZNER_EMBEDDING_SPACE;
932
+ // Hetzner documents a 32 MiB body ceiling and no fixed input count.
933
+ readonly maxRequestInputs = Number.POSITIVE_INFINITY;
934
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
935
+ readonly #key: string;
936
+
937
+ constructor(key: string) {
938
+ this.#key = key;
939
+ }
940
+
941
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
942
+ signal.throwIfAborted();
943
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
944
+ }
945
+
946
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
947
+ const response = await requestJson({
948
+ url: new URL(HETZNER_EMBEDDINGS_URL),
949
+ signal,
950
+ headers: { authorization: `Bearer ${this.#key}` },
951
+ // Hetzner documents `float` and `base64` for this endpoint; float is the value this package records.
952
+ body: { model: this.model, input: providerTexts(inputs), encoding_format: 'float' },
953
+ });
954
+ return parseOptionalUsageBatchResponse({
955
+ response,
956
+ space: this.space,
957
+ expectedModels: [this.model],
958
+ expectedCount: inputs.length,
959
+ });
960
+ }
961
+
962
+ async close(): Promise<void> {
963
+ // Native fetch owns no long-lived resource.
964
+ }
965
+ }
966
+
387
967
  class CloudflareProvider implements EmbeddingsProvider {
388
968
  readonly route = 'cloudflare' as const;
389
969
  readonly model = CLOUDFLARE_EMBEDDING_MODELS[0];
@@ -525,10 +1105,12 @@ export async function acquireProvider({
525
1105
  settings,
526
1106
  route,
527
1107
  signal,
1108
+ credentialResolver,
528
1109
  }: {
529
1110
  settings: EmbeddingSettings;
530
1111
  route: EmbeddingRoute;
531
1112
  signal: AbortSignal;
1113
+ credentialResolver?: EmbeddingCredentialResolver | undefined;
532
1114
  }): Promise<AcquiredProvider> {
533
1115
  switch (route.provider) {
534
1116
  case 'local': {
@@ -543,13 +1125,17 @@ export async function acquireProvider({
543
1125
  );
544
1126
  return { provider: acquired.provider, release: acquired.release };
545
1127
  }
546
- case 'openai':
1128
+ case 'openai': {
1129
+ if (!isOneOf<OpenAiEmbeddingModel>(OPENAI_EMBEDDING_MODELS, route.model))
1130
+ throw new EmbeddingsError('configuration-invalid');
547
1131
  return {
548
1132
  provider: new OpenAiProvider(
1133
+ route.model,
549
1134
  credential(settings.providers?.openai?.apiKey, process.env.OPENAI_API_KEY)
550
1135
  ),
551
1136
  release: noRelease,
552
1137
  };
1138
+ }
553
1139
  case 'sarvam':
554
1140
  return {
555
1141
  provider: new SarvamProvider(
@@ -575,13 +1161,17 @@ export async function acquireProvider({
575
1161
  release: noRelease,
576
1162
  };
577
1163
  }
578
- case 'openrouter':
1164
+ case 'openrouter': {
1165
+ if (!isOneOf<OpenRouterEmbeddingModel>(OPENROUTER_EMBEDDING_MODELS, route.model))
1166
+ throw new EmbeddingsError('configuration-invalid');
579
1167
  return {
580
1168
  provider: new OpenRouterProvider(
1169
+ route.model,
581
1170
  headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)
582
1171
  ),
583
1172
  release: noRelease,
584
1173
  };
1174
+ }
585
1175
  case 'cloudflare': {
586
1176
  const configured = settings.providers?.cloudflare;
587
1177
  const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
@@ -604,6 +1194,21 @@ export async function acquireProvider({
604
1194
  release: noRelease,
605
1195
  };
606
1196
  }
1197
+ case 'opencode':
1198
+ case 'opencode-go':
1199
+ return {
1200
+ provider: new OpenCodeProvider({
1201
+ route: route.provider,
1202
+ model: route.model,
1203
+ key: await openCodeCredential({ route: route.provider, settings, resolver: credentialResolver }),
1204
+ url: new URL(
1205
+ route.provider === 'opencode'
1206
+ ? OPENCODE_CONSOLE_EMBEDDINGS_URL
1207
+ : OPENCODE_GO_EMBEDDINGS_URL
1208
+ ),
1209
+ }),
1210
+ release: noRelease,
1211
+ };
607
1212
  case 'vertex': {
608
1213
  const configured = settings.providers?.vertex;
609
1214
  if (configured === undefined) throw new EmbeddingsError('configuration-invalid');
@@ -622,6 +1227,66 @@ export async function acquireProvider({
622
1227
  release: noRelease,
623
1228
  };
624
1229
  }
1230
+ case 'voyage': {
1231
+ const configured = settings.providers?.voyage;
1232
+ if (!isOneOf<VoyageEmbeddingModel>(VOYAGE_EMBEDDING_MODELS, route.model))
1233
+ throw new EmbeddingsError('configuration-invalid');
1234
+ return {
1235
+ provider: new VoyageProvider({
1236
+ model: route.model,
1237
+ dimensions: configured?.dimensions ?? DEFAULT_VOYAGE_DIMENSIONS,
1238
+ key: headerCredential(configured?.apiKey, process.env.VOYAGE_API_KEY),
1239
+ }),
1240
+ release: noRelease,
1241
+ };
1242
+ }
1243
+ case 'cohere': {
1244
+ const configured = settings.providers?.cohere;
1245
+ if (!isOneOf<CohereEmbeddingModel>(COHERE_EMBEDDING_MODELS, route.model))
1246
+ throw new EmbeddingsError('configuration-invalid');
1247
+ return {
1248
+ provider: new CohereProvider({
1249
+ model: route.model,
1250
+ dimensions: configured?.dimensions ?? DEFAULT_COHERE_DIMENSIONS,
1251
+ key: headerCredential(configured?.apiKey, process.env.COHERE_API_KEY),
1252
+ }),
1253
+ release: noRelease,
1254
+ };
1255
+ }
1256
+ case 'jina': {
1257
+ const configured = settings.providers?.jina;
1258
+ if (!isOneOf<JinaEmbeddingModel>(JINA_EMBEDDING_MODELS, route.model))
1259
+ throw new EmbeddingsError('configuration-invalid');
1260
+ const model = route.model;
1261
+ return {
1262
+ provider: new JinaProvider({
1263
+ model,
1264
+ dimensions: configured?.dimensions ?? jinaDefaultDimensions(model),
1265
+ key: headerCredential(configured?.apiKey, process.env.JINA_API_KEY),
1266
+ }),
1267
+ release: noRelease,
1268
+ };
1269
+ }
1270
+ case 'dashscope': {
1271
+ const configured = settings.providers?.dashscope;
1272
+ const baseUrl = trim(configured?.baseUrl) ?? trim(process.env.DASHSCOPE_BASE_URL);
1273
+ if (baseUrl === undefined) throw new EmbeddingsError('configuration-invalid');
1274
+ return {
1275
+ provider: new DashScopeProvider({
1276
+ origin: fixedOrigin(baseUrl),
1277
+ dimensions: configured?.dimensions ?? DEFAULT_DASHSCOPE_DIMENSIONS,
1278
+ key: headerCredential(configured?.apiKey, process.env.DASHSCOPE_API_KEY),
1279
+ }),
1280
+ release: noRelease,
1281
+ };
1282
+ }
1283
+ case 'hetzner':
1284
+ return {
1285
+ provider: new HetznerProvider(
1286
+ headerCredential(settings.providers?.hetzner?.apiKey, process.env.HETZNER_INFERENCE_TOKEN)
1287
+ ),
1288
+ release: noRelease,
1289
+ };
625
1290
  }
626
1291
  }
627
1292
 
@@ -633,9 +1298,44 @@ export const spaceForRoute = (
633
1298
  case 'local':
634
1299
  return LOCAL_EMBEDDING_SPACE;
635
1300
  case 'openai':
1301
+ if (!isOneOf<OpenAiEmbeddingModel>(OPENAI_EMBEDDING_MODELS, route.model))
1302
+ throw new EmbeddingsError('configuration-invalid');
1303
+ return openaiEmbeddingSpace(route.model);
636
1304
  case 'gateway':
637
- case 'openrouter':
638
1305
  return OPENAI_EMBEDDING_SPACE;
1306
+ case 'openrouter':
1307
+ if (!isOneOf<OpenRouterEmbeddingModel>(OPENROUTER_EMBEDDING_MODELS, route.model))
1308
+ throw new EmbeddingsError('configuration-invalid');
1309
+ return openaiEmbeddingSpace(openRouterCanonicalModel(route.model));
1310
+ case 'voyage':
1311
+ if (!isOneOf<VoyageEmbeddingModel>(VOYAGE_EMBEDDING_MODELS, route.model))
1312
+ throw new EmbeddingsError('configuration-invalid');
1313
+ return voyageEmbeddingSpace({
1314
+ model: route.model,
1315
+ dimensions: settings?.providers?.voyage?.dimensions ?? DEFAULT_VOYAGE_DIMENSIONS,
1316
+ });
1317
+ case 'cohere':
1318
+ if (!isOneOf<CohereEmbeddingModel>(COHERE_EMBEDDING_MODELS, route.model))
1319
+ throw new EmbeddingsError('configuration-invalid');
1320
+ return cohereEmbeddingSpace({
1321
+ model: route.model,
1322
+ dimensions: settings?.providers?.cohere?.dimensions ?? DEFAULT_COHERE_DIMENSIONS,
1323
+ });
1324
+ case 'jina': {
1325
+ if (!isOneOf<JinaEmbeddingModel>(JINA_EMBEDDING_MODELS, route.model))
1326
+ throw new EmbeddingsError('configuration-invalid');
1327
+ const model = route.model;
1328
+ return jinaEmbeddingSpace({
1329
+ model,
1330
+ dimensions: settings?.providers?.jina?.dimensions ?? jinaDefaultDimensions(model),
1331
+ });
1332
+ }
1333
+ case 'dashscope':
1334
+ return dashScopeEmbeddingSpace(
1335
+ settings?.providers?.dashscope?.dimensions ?? DEFAULT_DASHSCOPE_DIMENSIONS
1336
+ );
1337
+ case 'hetzner':
1338
+ return HETZNER_EMBEDDING_SPACE;
639
1339
  case 'sarvam':
640
1340
  return SARVAM_EMBEDDING_SPACE;
641
1341
  case 'cloudflare':
@@ -650,5 +1350,8 @@ export const spaceForRoute = (
650
1350
  dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
651
1351
  taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
652
1352
  });
1353
+ case 'opencode':
1354
+ case 'opencode-go':
1355
+ return opencodeEmbeddingSpace({ provider: route.provider, model: route.model, dimensions: null });
653
1356
  }
654
1357
  };