@abhishek944/pi-embeddings 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -4
- package/dist/execute.js +2 -1
- package/dist/extension.js +23 -5
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/provider-types.d.ts +4 -0
- package/dist/providers.d.ts +13 -4
- package/dist/providers.js +147 -4
- package/dist/response.d.ts +11 -0
- package/dist/response.js +64 -3
- package/dist/runtime.d.ts +6 -1
- package/dist/runtime.js +8 -3
- package/dist/schemas.d.ts +275 -22
- package/dist/schemas.js +65 -0
- package/dist/settings.js +3 -1
- package/dist/tool-contracts.d.ts +129 -9
- package/package.json +3 -2
- package/src/execute.ts +2 -1
- package/src/extension.ts +43 -5
- package/src/index.ts +6 -0
- package/src/provider-types.ts +7 -0
- package/src/providers.ts +200 -2
- package/src/response.ts +73 -3
- package/src/runtime.ts +25 -6
- package/src/schemas.ts +87 -0
- package/src/settings.ts +4 -0
package/src/providers.ts
CHANGED
|
@@ -10,6 +10,8 @@ import {
|
|
|
10
10
|
DEFAULT_GEMINI_TASK_FORMAT,
|
|
11
11
|
GEMINI_EMBEDDING_MODELS,
|
|
12
12
|
GEMINI_TASK_PREFIXES,
|
|
13
|
+
OPENCODE_EMBEDDING_MODELS,
|
|
14
|
+
OPENCODE_GO_EMBEDDING_MODELS,
|
|
13
15
|
OPENROUTER_EMBEDDING_MODELS,
|
|
14
16
|
type EmbeddingContext,
|
|
15
17
|
type EmbeddingRoute,
|
|
@@ -17,15 +19,24 @@ import {
|
|
|
17
19
|
type EmbeddingSpace,
|
|
18
20
|
type GeminiEmbeddingDimension,
|
|
19
21
|
type GeminiEmbeddingTaskFormat,
|
|
22
|
+
type OpenCodeEmbeddingModel,
|
|
23
|
+
type OpenCodeGoEmbeddingModel,
|
|
24
|
+
type OpenCodeRouteId,
|
|
20
25
|
} from './schemas.js';
|
|
21
26
|
import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
|
|
22
27
|
import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE, type AcquiredLocalRuntime } from './local-runtime.js';
|
|
23
|
-
import type {
|
|
28
|
+
import type {
|
|
29
|
+
EmbeddingCredentialResolver,
|
|
30
|
+
EmbeddingsProvider,
|
|
31
|
+
PreparedInput,
|
|
32
|
+
ProviderBatchResult,
|
|
33
|
+
} from './provider-types.js';
|
|
24
34
|
import {
|
|
25
35
|
parseBatchResponse,
|
|
26
36
|
parseCloudflareBatchResponse,
|
|
27
37
|
parseGeminiCountTokensResponse,
|
|
28
38
|
parseGeminiEmbeddingResponse,
|
|
39
|
+
parseOpenCodeBatchResponse,
|
|
29
40
|
} from './response.js';
|
|
30
41
|
|
|
31
42
|
export const OPENAI_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
|
|
@@ -85,6 +96,12 @@ export const geminiEmbeddingSpace = (config: {
|
|
|
85
96
|
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
86
97
|
});
|
|
87
98
|
|
|
99
|
+
export const OPENCODE_CONSOLE_EMBEDDINGS_URL =
|
|
100
|
+
'https://opencode.ai/inference/openai/v1/embeddings';
|
|
101
|
+
export const OPENCODE_GO_EMBEDDINGS_URL =
|
|
102
|
+
'https://opencode.ai/inference/go/openai/v1/embeddings';
|
|
103
|
+
const OPENCODE_USER_AGENT = 'pi-embeddings';
|
|
104
|
+
|
|
88
105
|
const OPENAI_MODEL = 'text-embedding-3-small';
|
|
89
106
|
const SARVAM_MODEL = 'embeddinggemma-2';
|
|
90
107
|
const SARVAM_ORIGIN = 'https://api.sarvam.ai';
|
|
@@ -97,6 +114,51 @@ const OPENAI_MAX_INPUT_TOKENS = 8192;
|
|
|
97
114
|
const OPENAI_MAX_REQUEST_INPUTS = 2048;
|
|
98
115
|
const OPENAI_MAX_REQUEST_TOKENS = 300000;
|
|
99
116
|
|
|
117
|
+
const isOneOf = <T extends string>(values: readonly T[], value: string): value is T =>
|
|
118
|
+
values.some((candidate) => candidate === value);
|
|
119
|
+
|
|
120
|
+
export const opencodeEmbeddingSpace = (args: {
|
|
121
|
+
provider: OpenCodeRouteId;
|
|
122
|
+
model: string;
|
|
123
|
+
dimensions: number | null;
|
|
124
|
+
}): EmbeddingSpace => {
|
|
125
|
+
const common: {
|
|
126
|
+
readonly revision: null;
|
|
127
|
+
readonly quantization: null;
|
|
128
|
+
readonly dimensions: number | null;
|
|
129
|
+
readonly format: typeof EMBEDDING_FORMAT_VERSION;
|
|
130
|
+
readonly prefix: typeof EMBEDDING_DOCUMENT_PREFIX;
|
|
131
|
+
readonly normalization: typeof EMBEDDING_NORMALIZATION_VERSION;
|
|
132
|
+
} = {
|
|
133
|
+
revision: null,
|
|
134
|
+
quantization: null,
|
|
135
|
+
dimensions: args.dimensions,
|
|
136
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
137
|
+
prefix: EMBEDDING_DOCUMENT_PREFIX,
|
|
138
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
139
|
+
};
|
|
140
|
+
if (args.provider === 'opencode') {
|
|
141
|
+
if (!isOneOf<OpenCodeEmbeddingModel>(OPENCODE_EMBEDDING_MODELS, args.model))
|
|
142
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
143
|
+
const space: EmbeddingSpace = {
|
|
144
|
+
...common,
|
|
145
|
+
provider: 'opencode',
|
|
146
|
+
model: args.model,
|
|
147
|
+
runtime: 'opencode-console-embeddings-v1',
|
|
148
|
+
};
|
|
149
|
+
return Object.freeze(space);
|
|
150
|
+
}
|
|
151
|
+
if (!isOneOf<OpenCodeGoEmbeddingModel>(OPENCODE_GO_EMBEDDING_MODELS, args.model))
|
|
152
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
153
|
+
const space: EmbeddingSpace = {
|
|
154
|
+
...common,
|
|
155
|
+
provider: 'opencode-go',
|
|
156
|
+
model: args.model,
|
|
157
|
+
runtime: 'opencode-go-embeddings-v1',
|
|
158
|
+
};
|
|
159
|
+
return Object.freeze(space);
|
|
160
|
+
};
|
|
161
|
+
|
|
100
162
|
const trim = (value: string | undefined): string | undefined => {
|
|
101
163
|
const trimmed = value?.trim();
|
|
102
164
|
return trimmed === undefined || trimmed === '' ? undefined : trimmed;
|
|
@@ -104,13 +166,19 @@ const trim = (value: string | undefined): string | undefined => {
|
|
|
104
166
|
|
|
105
167
|
export const routeKey = (route: EmbeddingRoute): string => `${route.provider}\u0000${route.model}`;
|
|
106
168
|
|
|
169
|
+
export type OpenCodeCredentialAvailability = Readonly<Partial<Record<OpenCodeRouteId, boolean>>>;
|
|
170
|
+
|
|
107
171
|
export type EmbeddingDiagnostic = Readonly<{
|
|
108
172
|
readonly code: string;
|
|
109
173
|
readonly severity: 'error' | 'warning' | 'info';
|
|
110
174
|
}>;
|
|
111
175
|
|
|
112
176
|
/** Diagnostics are provider-free and never contain keys, origins or model paths. */
|
|
113
|
-
export function routeDiagnostics(
|
|
177
|
+
export function routeDiagnostics(
|
|
178
|
+
settings: EmbeddingSettings,
|
|
179
|
+
route: EmbeddingRoute,
|
|
180
|
+
piCredentialAvailable: OpenCodeCredentialAvailability = {}
|
|
181
|
+
): EmbeddingDiagnostic[] {
|
|
114
182
|
const diagnostics: EmbeddingDiagnostic[] = [];
|
|
115
183
|
const add = (code: string, severity: EmbeddingDiagnostic['severity'] = 'error'): void => {
|
|
116
184
|
diagnostics.push({ code, severity });
|
|
@@ -156,6 +224,22 @@ export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRo
|
|
|
156
224
|
if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
|
|
157
225
|
add('gemini-key-unconfigured');
|
|
158
226
|
break;
|
|
227
|
+
case 'opencode':
|
|
228
|
+
if (
|
|
229
|
+
trim(settings.providers?.opencode?.apiKey) === undefined &&
|
|
230
|
+
trim(process.env.OPENCODE_API_KEY) === undefined &&
|
|
231
|
+
piCredentialAvailable.opencode !== true
|
|
232
|
+
)
|
|
233
|
+
add('opencode-key-unconfigured');
|
|
234
|
+
break;
|
|
235
|
+
case 'opencode-go':
|
|
236
|
+
if (
|
|
237
|
+
trim(settings.providers?.['opencode-go']?.apiKey) === undefined &&
|
|
238
|
+
trim(process.env.OPENCODE_API_KEY) === undefined &&
|
|
239
|
+
piCredentialAvailable['opencode-go'] !== true
|
|
240
|
+
)
|
|
241
|
+
add('opencode-go-key-unconfigured');
|
|
242
|
+
break;
|
|
159
243
|
case 'vertex':
|
|
160
244
|
if (settings.providers?.vertex === undefined) add('vertex-configuration-unconfigured');
|
|
161
245
|
// Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
|
|
@@ -176,6 +260,34 @@ const headerCredential = (configured: string | undefined, env: string | undefine
|
|
|
176
260
|
return value;
|
|
177
261
|
};
|
|
178
262
|
|
|
263
|
+
const safeHeaderValue = (value: string): string => {
|
|
264
|
+
if (!headerValueIsSafe(value)) throw new EmbeddingsError('configuration-invalid');
|
|
265
|
+
return value;
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
/** Host-provided provider keys are read only when a route is acquired; errors never carry a value. */
|
|
269
|
+
async function openCodeCredential(args: {
|
|
270
|
+
route: OpenCodeRouteId;
|
|
271
|
+
settings: EmbeddingSettings;
|
|
272
|
+
resolver: EmbeddingCredentialResolver | undefined;
|
|
273
|
+
}): Promise<string> {
|
|
274
|
+
const configured =
|
|
275
|
+
args.route === 'opencode'
|
|
276
|
+
? args.settings.providers?.opencode?.apiKey
|
|
277
|
+
: args.settings.providers?.['opencode-go']?.apiKey;
|
|
278
|
+
const explicit = trim(configured);
|
|
279
|
+
if (explicit !== undefined) return safeHeaderValue(explicit);
|
|
280
|
+
if (args.resolver !== undefined) {
|
|
281
|
+
try {
|
|
282
|
+
const resolved = trim(await args.resolver(args.route));
|
|
283
|
+
if (resolved !== undefined) return safeHeaderValue(resolved);
|
|
284
|
+
} catch {
|
|
285
|
+
// A host resolver that cannot supply a key leaves the trusted environment fallback intact.
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return headerCredential(undefined, process.env.OPENCODE_API_KEY);
|
|
289
|
+
}
|
|
290
|
+
|
|
179
291
|
/** The documented text-string path avoids the token-array schema contradiction without truncating. */
|
|
180
292
|
const openAIPrepare = (
|
|
181
293
|
encoding: ReturnType<typeof getEncoding>,
|
|
@@ -241,6 +353,72 @@ class OpenAiProvider implements EmbeddingsProvider {
|
|
|
241
353
|
}
|
|
242
354
|
}
|
|
243
355
|
|
|
356
|
+
class OpenCodeProvider implements EmbeddingsProvider {
|
|
357
|
+
readonly route: OpenCodeRouteId;
|
|
358
|
+
readonly model: string;
|
|
359
|
+
readonly space: EmbeddingSpace;
|
|
360
|
+
// OpenCode documents per-input context requirements but publishes no aggregate request ceiling.
|
|
361
|
+
readonly maxRequestInputs = Number.POSITIVE_INFINITY;
|
|
362
|
+
readonly maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
363
|
+
readonly #url: URL;
|
|
364
|
+
readonly #key: string;
|
|
365
|
+
|
|
366
|
+
constructor(args: {
|
|
367
|
+
route: OpenCodeRouteId;
|
|
368
|
+
model: string;
|
|
369
|
+
key: string;
|
|
370
|
+
url: URL;
|
|
371
|
+
}) {
|
|
372
|
+
this.route = args.route;
|
|
373
|
+
this.model = args.model;
|
|
374
|
+
this.space = opencodeEmbeddingSpace({
|
|
375
|
+
provider: args.route,
|
|
376
|
+
model: args.model,
|
|
377
|
+
dimensions: null,
|
|
378
|
+
});
|
|
379
|
+
this.#url = args.url;
|
|
380
|
+
this.#key = args.key;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
|
|
384
|
+
signal.throwIfAborted();
|
|
385
|
+
return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
|
|
389
|
+
const parsed = parseOpenCodeBatchResponse({
|
|
390
|
+
response: await requestJson({
|
|
391
|
+
url: this.#url,
|
|
392
|
+
signal,
|
|
393
|
+
headers: {
|
|
394
|
+
authorization: `Bearer ${this.#key}`,
|
|
395
|
+
'user-agent': OPENCODE_USER_AGENT,
|
|
396
|
+
},
|
|
397
|
+
body: {
|
|
398
|
+
model: this.model,
|
|
399
|
+
input: providerTexts(inputs),
|
|
400
|
+
encoding_format: 'float',
|
|
401
|
+
},
|
|
402
|
+
}),
|
|
403
|
+
expectedModels: [this.model],
|
|
404
|
+
expectedCount: inputs.length,
|
|
405
|
+
});
|
|
406
|
+
return {
|
|
407
|
+
vectors: parsed.vectors,
|
|
408
|
+
usage: parsed.usage,
|
|
409
|
+
space: opencodeEmbeddingSpace({
|
|
410
|
+
provider: this.route,
|
|
411
|
+
model: this.model,
|
|
412
|
+
dimensions: parsed.dimensions,
|
|
413
|
+
}),
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async close(): Promise<void> {
|
|
418
|
+
// Native fetch owns no long-lived resource.
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
244
422
|
class SarvamProvider implements EmbeddingsProvider {
|
|
245
423
|
readonly route = 'sarvam' as const;
|
|
246
424
|
readonly model = SARVAM_MODEL;
|
|
@@ -525,10 +703,12 @@ export async function acquireProvider({
|
|
|
525
703
|
settings,
|
|
526
704
|
route,
|
|
527
705
|
signal,
|
|
706
|
+
credentialResolver,
|
|
528
707
|
}: {
|
|
529
708
|
settings: EmbeddingSettings;
|
|
530
709
|
route: EmbeddingRoute;
|
|
531
710
|
signal: AbortSignal;
|
|
711
|
+
credentialResolver?: EmbeddingCredentialResolver | undefined;
|
|
532
712
|
}): Promise<AcquiredProvider> {
|
|
533
713
|
switch (route.provider) {
|
|
534
714
|
case 'local': {
|
|
@@ -604,6 +784,21 @@ export async function acquireProvider({
|
|
|
604
784
|
release: noRelease,
|
|
605
785
|
};
|
|
606
786
|
}
|
|
787
|
+
case 'opencode':
|
|
788
|
+
case 'opencode-go':
|
|
789
|
+
return {
|
|
790
|
+
provider: new OpenCodeProvider({
|
|
791
|
+
route: route.provider,
|
|
792
|
+
model: route.model,
|
|
793
|
+
key: await openCodeCredential({ route: route.provider, settings, resolver: credentialResolver }),
|
|
794
|
+
url: new URL(
|
|
795
|
+
route.provider === 'opencode'
|
|
796
|
+
? OPENCODE_CONSOLE_EMBEDDINGS_URL
|
|
797
|
+
: OPENCODE_GO_EMBEDDINGS_URL
|
|
798
|
+
),
|
|
799
|
+
}),
|
|
800
|
+
release: noRelease,
|
|
801
|
+
};
|
|
607
802
|
case 'vertex': {
|
|
608
803
|
const configured = settings.providers?.vertex;
|
|
609
804
|
if (configured === undefined) throw new EmbeddingsError('configuration-invalid');
|
|
@@ -650,5 +845,8 @@ export const spaceForRoute = (
|
|
|
650
845
|
dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
651
846
|
taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
652
847
|
});
|
|
848
|
+
case 'opencode':
|
|
849
|
+
case 'opencode-go':
|
|
850
|
+
return opencodeEmbeddingSpace({ provider: route.provider, model: route.model, dimensions: null });
|
|
653
851
|
}
|
|
654
852
|
};
|
package/src/response.ts
CHANGED
|
@@ -17,6 +17,21 @@ const responseSchema = Type.Object({
|
|
|
17
17
|
}),
|
|
18
18
|
});
|
|
19
19
|
|
|
20
|
+
const openCodeResponseSchema = Type.Object({
|
|
21
|
+
model: Type.Optional(Type.String({ minLength: 1 })),
|
|
22
|
+
data: Type.Array(
|
|
23
|
+
Type.Object({
|
|
24
|
+
index: Type.Integer({ minimum: 0 }),
|
|
25
|
+
embedding: Type.Array(Type.Number()),
|
|
26
|
+
})
|
|
27
|
+
),
|
|
28
|
+
usage: Type.Optional(
|
|
29
|
+
Type.Object({
|
|
30
|
+
prompt_tokens: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
31
|
+
})
|
|
32
|
+
),
|
|
33
|
+
});
|
|
34
|
+
|
|
20
35
|
const cloudflareResponseSchema = Type.Object({
|
|
21
36
|
shape: Type.Optional(Type.Array(Type.Integer({ minimum: 0 }))),
|
|
22
37
|
data: Type.Array(Type.Array(Type.Number())),
|
|
@@ -67,6 +82,11 @@ export function normalizeVector(vector: readonly number[], dimensions: number):
|
|
|
67
82
|
return vector.map((value) => value / scale / norm);
|
|
68
83
|
}
|
|
69
84
|
|
|
85
|
+
function dimensionsOf(space: EmbeddingSpace): number {
|
|
86
|
+
if (typeof space.dimensions !== 'number') throw new EmbeddingsError('vector-invalid');
|
|
87
|
+
return space.dimensions;
|
|
88
|
+
}
|
|
89
|
+
|
|
70
90
|
export function parseBatchResponse(args: {
|
|
71
91
|
response: unknown;
|
|
72
92
|
space: EmbeddingSpace;
|
|
@@ -97,7 +117,7 @@ export function parseBatchResponse(args: {
|
|
|
97
117
|
throw known('provider-response-mismatch');
|
|
98
118
|
let vectors: number[][];
|
|
99
119
|
try {
|
|
100
|
-
vectors = ordered.map((item) => normalizeVector(item.embedding, args.space
|
|
120
|
+
vectors = ordered.map((item) => normalizeVector(item.embedding, dimensionsOf(args.space)));
|
|
101
121
|
} catch (error) {
|
|
102
122
|
if (error instanceof EmbeddingsError)
|
|
103
123
|
throw known(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid');
|
|
@@ -113,6 +133,56 @@ export function parseBatchResponse(args: {
|
|
|
113
133
|
};
|
|
114
134
|
}
|
|
115
135
|
|
|
136
|
+
/**
|
|
137
|
+
* OpenCode's OpenAI-compatible embeddings response does not publish per-model dimensions, so the
|
|
138
|
+
* dimension is observed from the returned vectors and included in the actual generating space.
|
|
139
|
+
*/
|
|
140
|
+
export function parseOpenCodeBatchResponse(args: {
|
|
141
|
+
response: unknown;
|
|
142
|
+
expectedModels: readonly string[];
|
|
143
|
+
expectedCount: number;
|
|
144
|
+
}): ProviderBatchResult & { readonly dimensions: number } {
|
|
145
|
+
if (!Value.Check(openCodeResponseSchema, args.response))
|
|
146
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
147
|
+
const parsed = args.response;
|
|
148
|
+
const providerReportedInputTokens = parsed.usage?.prompt_tokens ?? null;
|
|
149
|
+
const knownUsage = {
|
|
150
|
+
providerReportedInputTokens,
|
|
151
|
+
preparedInputTokens: null,
|
|
152
|
+
};
|
|
153
|
+
const fail = (
|
|
154
|
+
code: 'provider-response-mismatch' | 'vector-invalid' | 'vector-zero'
|
|
155
|
+
): never => {
|
|
156
|
+
throw new EmbeddingsError(code, { knownUsage });
|
|
157
|
+
};
|
|
158
|
+
if (parsed.model !== undefined && !args.expectedModels.includes(parsed.model))
|
|
159
|
+
fail('provider-response-mismatch');
|
|
160
|
+
const ordered = [...parsed.data].sort((left, right) => left.index - right.index);
|
|
161
|
+
if (ordered.length !== args.expectedCount || ordered.some((item, index) => item.index !== index))
|
|
162
|
+
fail('provider-response-mismatch');
|
|
163
|
+
const first = ordered[0];
|
|
164
|
+
if (first === undefined) throw new EmbeddingsError('provider-response-mismatch', { knownUsage });
|
|
165
|
+
const dimensions = first.embedding.length;
|
|
166
|
+
if (dimensions === 0) fail('vector-invalid');
|
|
167
|
+
let vectors: number[][];
|
|
168
|
+
try {
|
|
169
|
+
vectors = ordered.map((item) => normalizeVector(item.embedding, dimensions));
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (error instanceof EmbeddingsError)
|
|
172
|
+
fail(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid');
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
vectors,
|
|
177
|
+
usage: {
|
|
178
|
+
providerReportedInputTokens,
|
|
179
|
+
preparedInputTokens: null,
|
|
180
|
+
billedTokens: null,
|
|
181
|
+
},
|
|
182
|
+
dimensions,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
116
186
|
/**
|
|
117
187
|
* Gemini `embedContent` returns one embedding and provider-counted prompt tokens. A vector is accepted
|
|
118
188
|
* only when that response count matches the exact prepared prompt counted before inference; a mismatch
|
|
@@ -140,7 +210,7 @@ export function parseGeminiEmbeddingResponse(args: {
|
|
|
140
210
|
throw new EmbeddingsError('input-too-long', { knownUsage });
|
|
141
211
|
let vector: number[];
|
|
142
212
|
try {
|
|
143
|
-
vector = normalizeVector(parsed.embedding.values, args.space
|
|
213
|
+
vector = normalizeVector(parsed.embedding.values, dimensionsOf(args.space));
|
|
144
214
|
} catch (error) {
|
|
145
215
|
if (error instanceof EmbeddingsError)
|
|
146
216
|
throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
|
|
@@ -190,7 +260,7 @@ export function parseCloudflareBatchResponse(args: {
|
|
|
190
260
|
throw new EmbeddingsError('provider-response-mismatch', { knownUsage: {} });
|
|
191
261
|
let vectors: number[][];
|
|
192
262
|
try {
|
|
193
|
-
vectors = parsed.data.map((vector) => normalizeVector(vector, args.space
|
|
263
|
+
vectors = parsed.data.map((vector) => normalizeVector(vector, dimensionsOf(args.space)));
|
|
194
264
|
} catch (error) {
|
|
195
265
|
if (error instanceof EmbeddingsError)
|
|
196
266
|
throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
|
package/src/runtime.ts
CHANGED
|
@@ -5,7 +5,9 @@ import {
|
|
|
5
5
|
spaceForRoute,
|
|
6
6
|
type AcquiredProvider,
|
|
7
7
|
type EmbeddingDiagnostic,
|
|
8
|
+
type OpenCodeCredentialAvailability,
|
|
8
9
|
} from './providers.js';
|
|
10
|
+
import type { EmbeddingCredentialResolver } from './provider-types.js';
|
|
9
11
|
import { configuredDefault, configuredRoutes, validateEmbeddingSettings } from './settings.js';
|
|
10
12
|
import { executeCompare, executeEmbeddings } from './execute.js';
|
|
11
13
|
import { EmbeddingsError } from './errors.js';
|
|
@@ -54,6 +56,8 @@ const noSignal = (signal: AbortSignal | undefined): AbortSignal => signal ?? new
|
|
|
54
56
|
function createRuntime(args: {
|
|
55
57
|
settings: EmbeddingSettings;
|
|
56
58
|
cwd?: string | undefined;
|
|
59
|
+
credentialResolver?: EmbeddingCredentialResolver | undefined;
|
|
60
|
+
piCredentialAvailable?: OpenCodeCredentialAvailability | undefined;
|
|
57
61
|
}): EmbeddingsRuntimeWithDiagnostics {
|
|
58
62
|
const settings = validateEmbeddingSettings(args.settings);
|
|
59
63
|
const defaultRoute = configuredDefault(settings);
|
|
@@ -76,7 +80,12 @@ function createRuntime(args: {
|
|
|
76
80
|
if (cached !== undefined) return Promise.resolve(cached);
|
|
77
81
|
const inFlight = pending.get(key);
|
|
78
82
|
if (inFlight !== undefined) return inFlight;
|
|
79
|
-
const promise = acquireProvider({
|
|
83
|
+
const promise = acquireProvider({
|
|
84
|
+
settings,
|
|
85
|
+
route,
|
|
86
|
+
signal: lifetime.signal,
|
|
87
|
+
credentialResolver: args.credentialResolver,
|
|
88
|
+
})
|
|
80
89
|
.then((entry) => {
|
|
81
90
|
pending.delete(key);
|
|
82
91
|
if (closed || closing !== undefined) {
|
|
@@ -131,13 +140,19 @@ function createRuntime(args: {
|
|
|
131
140
|
});
|
|
132
141
|
},
|
|
133
142
|
describe() {
|
|
134
|
-
const defaultDiagnostics = routeDiagnostics(
|
|
143
|
+
const defaultDiagnostics = routeDiagnostics(
|
|
144
|
+
settings,
|
|
145
|
+
defaultRoute,
|
|
146
|
+
args.piCredentialAvailable ?? {}
|
|
147
|
+
);
|
|
135
148
|
const diagnostics = [...defaultDiagnostics];
|
|
136
149
|
for (const route of fallbackRoutes)
|
|
137
|
-
diagnostics.push(
|
|
138
|
-
...entry
|
|
139
|
-
|
|
140
|
-
|
|
150
|
+
diagnostics.push(
|
|
151
|
+
...routeDiagnostics(settings, route, args.piCredentialAvailable ?? {}).map((entry) => ({
|
|
152
|
+
...entry,
|
|
153
|
+
severity: 'warning' as const,
|
|
154
|
+
}))
|
|
155
|
+
);
|
|
141
156
|
return {
|
|
142
157
|
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
143
158
|
ready: defaultDiagnostics.length === 0,
|
|
@@ -170,6 +185,8 @@ function createRuntime(args: {
|
|
|
170
185
|
export function createEmbeddingsRuntime(args: {
|
|
171
186
|
settings: EmbeddingSettings;
|
|
172
187
|
cwd?: string | undefined;
|
|
188
|
+
credentialResolver?: EmbeddingCredentialResolver | undefined;
|
|
189
|
+
piCredentialAvailable?: OpenCodeCredentialAvailability | undefined;
|
|
173
190
|
}): EmbeddingsRuntime {
|
|
174
191
|
const { start, embed, compare, close } = createRuntime(args);
|
|
175
192
|
return { start, embed, compare, close };
|
|
@@ -179,6 +196,8 @@ export function createEmbeddingsRuntime(args: {
|
|
|
179
196
|
export function createEmbeddingsRuntimeWithDiagnostics(args: {
|
|
180
197
|
settings: EmbeddingSettings;
|
|
181
198
|
cwd?: string | undefined;
|
|
199
|
+
credentialResolver?: EmbeddingCredentialResolver | undefined;
|
|
200
|
+
piCredentialAvailable?: OpenCodeCredentialAvailability | undefined;
|
|
182
201
|
}): EmbeddingsRuntimeWithDiagnostics {
|
|
183
202
|
return createRuntime(args);
|
|
184
203
|
}
|
package/src/schemas.ts
CHANGED
|
@@ -23,14 +23,42 @@ export const EMBEDDING_ROUTE_IDS = [
|
|
|
23
23
|
'cloudflare',
|
|
24
24
|
'gemini',
|
|
25
25
|
'vertex',
|
|
26
|
+
'opencode',
|
|
27
|
+
'opencode-go',
|
|
26
28
|
] as const;
|
|
27
29
|
export type EmbeddingRouteId = (typeof EMBEDDING_ROUTE_IDS)[number];
|
|
30
|
+
export type OpenCodeRouteId = Extract<EmbeddingRouteId, 'opencode' | 'opencode-go'>;
|
|
28
31
|
|
|
29
32
|
export const GATEWAY_EMBEDDING_MODELS = [
|
|
30
33
|
'text-embedding-3-small',
|
|
31
34
|
'openai/text-embedding-3-small',
|
|
32
35
|
] as const;
|
|
33
36
|
|
|
37
|
+
/** Console (pay-as-you-go) embedding model IDs documented by OpenCode. */
|
|
38
|
+
export const OPENCODE_EMBEDDING_MODELS = [
|
|
39
|
+
'text-embedding-3-small',
|
|
40
|
+
'text-embedding-3-large',
|
|
41
|
+
'gemini-embedding-2',
|
|
42
|
+
'gemini-embedding-001',
|
|
43
|
+
'codestral-embed',
|
|
44
|
+
'mistral-embed',
|
|
45
|
+
'cohere-embed-v5-pro',
|
|
46
|
+
'cohere-embed-v5-fast',
|
|
47
|
+
'voyage-4',
|
|
48
|
+
'voyage-code-4',
|
|
49
|
+
'qwen3-embedding-8b',
|
|
50
|
+
'bge-m3',
|
|
51
|
+
] as const;
|
|
52
|
+
export type OpenCodeEmbeddingModel = (typeof OPENCODE_EMBEDDING_MODELS)[number];
|
|
53
|
+
|
|
54
|
+
/** Go subscription embedding model IDs documented by OpenCode. */
|
|
55
|
+
export const OPENCODE_GO_EMBEDDING_MODELS = [
|
|
56
|
+
'text-embedding-3-small',
|
|
57
|
+
'qwen3-embedding-8b',
|
|
58
|
+
'gemini-embedding-2',
|
|
59
|
+
] as const;
|
|
60
|
+
export type OpenCodeGoEmbeddingModel = (typeof OPENCODE_GO_EMBEDDING_MODELS)[number];
|
|
61
|
+
|
|
34
62
|
export const OPENROUTER_EMBEDDING_MODELS = ['openai/text-embedding-3-small'] as const;
|
|
35
63
|
export const CLOUDFLARE_EMBEDDING_MODELS = ['@cf/baai/bge-base-en-v1.5'] as const;
|
|
36
64
|
export const GEMINI_EMBEDDING_MODELS = ['gemini-embedding-2'] as const;
|
|
@@ -72,6 +100,25 @@ const gatewayModelSchema = Type.Union([
|
|
|
72
100
|
const openRouterModelSchema = Type.Literal('openai/text-embedding-3-small');
|
|
73
101
|
const cloudflareModelSchema = Type.Literal('@cf/baai/bge-base-en-v1.5');
|
|
74
102
|
const geminiModelSchema = Type.Literal(GEMINI_EMBEDDING_MODELS[0]);
|
|
103
|
+
const openCodeModelSchema = Type.Union([
|
|
104
|
+
Type.Literal('text-embedding-3-small'),
|
|
105
|
+
Type.Literal('text-embedding-3-large'),
|
|
106
|
+
Type.Literal('gemini-embedding-2'),
|
|
107
|
+
Type.Literal('gemini-embedding-001'),
|
|
108
|
+
Type.Literal('codestral-embed'),
|
|
109
|
+
Type.Literal('mistral-embed'),
|
|
110
|
+
Type.Literal('cohere-embed-v5-pro'),
|
|
111
|
+
Type.Literal('cohere-embed-v5-fast'),
|
|
112
|
+
Type.Literal('voyage-4'),
|
|
113
|
+
Type.Literal('voyage-code-4'),
|
|
114
|
+
Type.Literal('qwen3-embedding-8b'),
|
|
115
|
+
Type.Literal('bge-m3'),
|
|
116
|
+
]);
|
|
117
|
+
const openCodeGoModelSchema = Type.Union([
|
|
118
|
+
Type.Literal('text-embedding-3-small'),
|
|
119
|
+
Type.Literal('qwen3-embedding-8b'),
|
|
120
|
+
Type.Literal('gemini-embedding-2'),
|
|
121
|
+
]);
|
|
75
122
|
export const VERTEX_EMBEDDING_LOCATIONS = ['us', 'eu', 'global'] as const;
|
|
76
123
|
const vertexLocationSchema = Type.Union([
|
|
77
124
|
Type.Literal('us'),
|
|
@@ -159,6 +206,8 @@ const embeddingProviderSchema = Type.Union([
|
|
|
159
206
|
Type.Literal('cloudflare'),
|
|
160
207
|
Type.Literal('gemini'),
|
|
161
208
|
Type.Literal('vertex'),
|
|
209
|
+
Type.Literal('opencode'),
|
|
210
|
+
Type.Literal('opencode-go'),
|
|
162
211
|
]);
|
|
163
212
|
|
|
164
213
|
export const embeddingRouteSchema = Type.Object(
|
|
@@ -175,6 +224,14 @@ const spaceCommon = {
|
|
|
175
224
|
normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
|
|
176
225
|
};
|
|
177
226
|
|
|
227
|
+
const openCodeSpaceCommon = {
|
|
228
|
+
...spaceCommon,
|
|
229
|
+
revision: Type.Null(),
|
|
230
|
+
quantization: Type.Null(),
|
|
231
|
+
// Observed only after a successful response; preflight descriptors never invent a dimension.
|
|
232
|
+
dimensions: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
|
|
233
|
+
};
|
|
234
|
+
|
|
178
235
|
const geminiSpaceCommon = {
|
|
179
236
|
format: Type.Literal(EMBEDDING_FORMAT_VERSION),
|
|
180
237
|
prefix: Type.Union([
|
|
@@ -265,6 +322,24 @@ export const embeddingSpaceSchema = Type.Union([
|
|
|
265
322
|
},
|
|
266
323
|
{ additionalProperties: false }
|
|
267
324
|
),
|
|
325
|
+
Type.Object(
|
|
326
|
+
{
|
|
327
|
+
...openCodeSpaceCommon,
|
|
328
|
+
provider: Type.Literal('opencode'),
|
|
329
|
+
model: openCodeModelSchema,
|
|
330
|
+
runtime: Type.Literal('opencode-console-embeddings-v1'),
|
|
331
|
+
},
|
|
332
|
+
{ additionalProperties: false }
|
|
333
|
+
),
|
|
334
|
+
Type.Object(
|
|
335
|
+
{
|
|
336
|
+
...openCodeSpaceCommon,
|
|
337
|
+
provider: Type.Literal('opencode-go'),
|
|
338
|
+
model: openCodeGoModelSchema,
|
|
339
|
+
runtime: Type.Literal('opencode-go-embeddings-v1'),
|
|
340
|
+
},
|
|
341
|
+
{ additionalProperties: false }
|
|
342
|
+
),
|
|
268
343
|
]);
|
|
269
344
|
|
|
270
345
|
export const embeddingSettingsSchema = Type.Object(
|
|
@@ -350,6 +425,18 @@ export const embeddingSettingsSchema = Type.Object(
|
|
|
350
425
|
{ additionalProperties: false }
|
|
351
426
|
)
|
|
352
427
|
),
|
|
428
|
+
opencode: Type.Optional(
|
|
429
|
+
Type.Object(
|
|
430
|
+
{ apiKey: Type.Optional(Type.String({ minLength: 1 })) },
|
|
431
|
+
{ additionalProperties: false }
|
|
432
|
+
)
|
|
433
|
+
),
|
|
434
|
+
'opencode-go': Type.Optional(
|
|
435
|
+
Type.Object(
|
|
436
|
+
{ apiKey: Type.Optional(Type.String({ minLength: 1 })) },
|
|
437
|
+
{ additionalProperties: false }
|
|
438
|
+
)
|
|
439
|
+
),
|
|
353
440
|
},
|
|
354
441
|
{ additionalProperties: false }
|
|
355
442
|
)
|
package/src/settings.ts
CHANGED
|
@@ -9,6 +9,8 @@ import {
|
|
|
9
9
|
EMBEDDINGS_SETTINGS_KEY,
|
|
10
10
|
GATEWAY_EMBEDDING_MODELS,
|
|
11
11
|
GEMINI_EMBEDDING_MODELS,
|
|
12
|
+
OPENCODE_EMBEDDING_MODELS,
|
|
13
|
+
OPENCODE_GO_EMBEDDING_MODELS,
|
|
12
14
|
OPENROUTER_EMBEDDING_MODELS,
|
|
13
15
|
embeddingSettingsSchema,
|
|
14
16
|
type EmbeddingRoute,
|
|
@@ -24,6 +26,8 @@ const MODELS_BY_PROVIDER: Readonly<Record<EmbeddingRoute['provider'], readonly s
|
|
|
24
26
|
cloudflare: CLOUDFLARE_EMBEDDING_MODELS,
|
|
25
27
|
gemini: GEMINI_EMBEDDING_MODELS,
|
|
26
28
|
vertex: GEMINI_EMBEDDING_MODELS,
|
|
29
|
+
opencode: OPENCODE_EMBEDDING_MODELS,
|
|
30
|
+
'opencode-go': OPENCODE_GO_EMBEDDING_MODELS,
|
|
27
31
|
};
|
|
28
32
|
|
|
29
33
|
export const isEmbeddingSettings = (value: unknown): value is EmbeddingSettings =>
|