@abhishek944/pi-embeddings 0.2.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 +50 -5
- package/dist/execute.js +22 -3
- package/dist/extension.js +25 -7
- 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 +17 -4
- package/dist/providers.js +257 -4
- package/dist/response.d.ts +26 -0
- package/dist/response.js +135 -2
- package/dist/runtime.d.ts +6 -1
- package/dist/runtime.js +8 -3
- package/dist/schemas.d.ts +570 -22
- package/dist/schemas.js +156 -0
- package/dist/settings-write.js +2 -2
- package/dist/settings.js +8 -1
- package/dist/tool-contracts.d.ts +261 -9
- package/dist/vertex-provider.d.ts +18 -0
- package/dist/vertex-provider.js +139 -0
- package/package.json +10 -2
- package/src/execute.ts +21 -3
- package/src/extension.ts +45 -7
- package/src/index.ts +16 -0
- package/src/provider-types.ts +7 -0
- package/src/providers.ts +338 -3
- package/src/response.ts +156 -2
- package/src/runtime.ts +25 -6
- package/src/schemas.ts +199 -0
- package/src/settings-write.ts +2 -2
- package/src/settings.ts +10 -0
- package/src/vertex-provider.ts +152 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abhishek944/pi-embeddings",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam and gateway routes, ordered fallback and explicit comparisons.",
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam, Gemini, Vertex ADC, OpenCode and gateway routes, ordered fallback and explicit comparisons.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
7
7
|
"pi",
|
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
"mcp",
|
|
10
10
|
"openai",
|
|
11
11
|
"sarvam",
|
|
12
|
+
"gemini",
|
|
12
13
|
"embeddinggemma",
|
|
14
|
+
"opencode",
|
|
13
15
|
"litellm"
|
|
14
16
|
],
|
|
15
17
|
"license": "Apache-2.0",
|
|
@@ -65,6 +67,7 @@
|
|
|
65
67
|
"dependencies": {
|
|
66
68
|
"@amaster.ai/pi-shared": "^0.1.10",
|
|
67
69
|
"@modelcontextprotocol/sdk": "1.32.1",
|
|
70
|
+
"google-auth-library": "10.9.1",
|
|
68
71
|
"js-tiktoken": "1.0.21"
|
|
69
72
|
},
|
|
70
73
|
"peerDependencies": {
|
|
@@ -81,5 +84,10 @@
|
|
|
81
84
|
"@types/node": "24.19.2",
|
|
82
85
|
"typebox": "1.3.27",
|
|
83
86
|
"typescript": "5.9.3"
|
|
87
|
+
},
|
|
88
|
+
"repository": {
|
|
89
|
+
"type": "git",
|
|
90
|
+
"url": "https://github.com/abhishek944/astack.git",
|
|
91
|
+
"directory": "packages/pi-embeddings"
|
|
84
92
|
}
|
|
85
93
|
}
|
package/src/execute.ts
CHANGED
|
@@ -135,8 +135,25 @@ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingRes
|
|
|
135
135
|
if (args.signal.aborted) outcomes[index] = cancelled(index);
|
|
136
136
|
else {
|
|
137
137
|
const code = codeOf(error);
|
|
138
|
-
|
|
139
|
-
|
|
138
|
+
if (args.allowFallback && isFallbackError(error)) {
|
|
139
|
+
// Preflight HTTP and credential failures follow the same fallback rule as embed failures.
|
|
140
|
+
// The failed index stays pending; successful inputs are never replayed on the next route.
|
|
141
|
+
const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
|
|
142
|
+
attempts.push({
|
|
143
|
+
id: attemptId,
|
|
144
|
+
route: route.provider,
|
|
145
|
+
model: provider.model,
|
|
146
|
+
routeIndex,
|
|
147
|
+
status: 'error',
|
|
148
|
+
usage: null,
|
|
149
|
+
errorCode: code,
|
|
150
|
+
});
|
|
151
|
+
failureByIndex.set(index, { code, attemptId });
|
|
152
|
+
unfinished.push(index);
|
|
153
|
+
} else {
|
|
154
|
+
failureByIndex.set(index, { code, attemptId: null });
|
|
155
|
+
outcomes[index] = { status: 'error', index, code, attemptId: null };
|
|
156
|
+
}
|
|
140
157
|
}
|
|
141
158
|
}
|
|
142
159
|
}
|
|
@@ -178,6 +195,7 @@ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingRes
|
|
|
178
195
|
attempt.usage = result.usage;
|
|
179
196
|
if (result.vectors.length !== captured.length)
|
|
180
197
|
throw new EmbeddingsError('provider-response-mismatch');
|
|
198
|
+
const actualSpace = result.space ?? provider.space;
|
|
181
199
|
for (const [offset, entry] of captured.entries()) {
|
|
182
200
|
const vector = result.vectors[offset];
|
|
183
201
|
if (vector === undefined) throw new EmbeddingsError('provider-response-mismatch');
|
|
@@ -187,7 +205,7 @@ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingRes
|
|
|
187
205
|
vector: [...vector],
|
|
188
206
|
route: route.provider,
|
|
189
207
|
model: provider.model,
|
|
190
|
-
space:
|
|
208
|
+
space: actualSpace,
|
|
191
209
|
attemptId,
|
|
192
210
|
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
193
211
|
};
|
package/src/extension.ts
CHANGED
|
@@ -5,11 +5,13 @@ import {
|
|
|
5
5
|
type ExtensionContext,
|
|
6
6
|
} from '@earendil-works/pi-coding-agent';
|
|
7
7
|
import { EmbeddingsError } from './errors.js';
|
|
8
|
+
import type { EmbeddingCredentialResolver } from './provider-types.js';
|
|
9
|
+
import type { OpenCodeCredentialAvailability } from './providers.js';
|
|
8
10
|
import {
|
|
9
11
|
createEmbeddingsRuntimeWithDiagnostics,
|
|
10
12
|
type EmbeddingsRuntimeWithDiagnostics,
|
|
11
13
|
} from './runtime.js';
|
|
12
|
-
import {
|
|
14
|
+
import { configuredDefault, loadEmbeddingSettings } from './settings.js';
|
|
13
15
|
import { updateProjectEmbeddingSettings } from './settings-write.js';
|
|
14
16
|
import {
|
|
15
17
|
EMBEDDINGS_SETTINGS_KEY,
|
|
@@ -41,16 +43,44 @@ const codeOf = (error: unknown): string =>
|
|
|
41
43
|
const signalOptions = (signal: AbortSignal | undefined) =>
|
|
42
44
|
signal === undefined ? {} : { signal };
|
|
43
45
|
|
|
46
|
+
type PiCredentials = Readonly<{
|
|
47
|
+
readonly resolver: EmbeddingCredentialResolver;
|
|
48
|
+
readonly available: OpenCodeCredentialAvailability;
|
|
49
|
+
}>;
|
|
50
|
+
|
|
51
|
+
/** Pi exposes provider keys through ModelRegistry; only nonsecret availability is retained. */
|
|
52
|
+
async function piCredentials(ctx: ExtensionContext): Promise<PiCredentials> {
|
|
53
|
+
const opencode = (await ctx.modelRegistry.getApiKeyForProvider('opencode')) !== undefined;
|
|
54
|
+
const go = (await ctx.modelRegistry.getApiKeyForProvider('opencode-go')) !== undefined;
|
|
55
|
+
return {
|
|
56
|
+
available: { opencode, 'opencode-go': go },
|
|
57
|
+
resolver: async (provider) => {
|
|
58
|
+
if (provider === 'opencode' || provider === 'opencode-go')
|
|
59
|
+
return ctx.modelRegistry.getApiKeyForProvider(provider);
|
|
60
|
+
return undefined;
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
44
65
|
export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
45
66
|
let settings: EmbeddingSettings | undefined;
|
|
46
67
|
let runtime: EmbeddingsRuntimeWithDiagnostics | undefined;
|
|
47
68
|
let cwd = process.cwd();
|
|
48
69
|
|
|
49
|
-
const refresh = async (
|
|
70
|
+
const refresh = async (
|
|
71
|
+
next: EmbeddingSettings,
|
|
72
|
+
nextCwd: string,
|
|
73
|
+
credentials: PiCredentials
|
|
74
|
+
): Promise<void> => {
|
|
50
75
|
await runtime?.close();
|
|
51
76
|
settings = next;
|
|
52
77
|
cwd = nextCwd;
|
|
53
|
-
runtime = createEmbeddingsRuntimeWithDiagnostics({
|
|
78
|
+
runtime = createEmbeddingsRuntimeWithDiagnostics({
|
|
79
|
+
settings: next,
|
|
80
|
+
cwd: nextCwd,
|
|
81
|
+
credentialResolver: credentials.resolver,
|
|
82
|
+
piCredentialAvailable: credentials.available,
|
|
83
|
+
});
|
|
54
84
|
};
|
|
55
85
|
|
|
56
86
|
const currentRuntime = (ctx: ExtensionContext): EmbeddingsRuntimeWithDiagnostics => {
|
|
@@ -60,7 +90,11 @@ export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
|
60
90
|
};
|
|
61
91
|
|
|
62
92
|
pi.on('session_start', async (_event: unknown, ctx: ExtensionContext) => {
|
|
63
|
-
await refresh(
|
|
93
|
+
await refresh(
|
|
94
|
+
loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
95
|
+
ctx.cwd,
|
|
96
|
+
await piCredentials(ctx)
|
|
97
|
+
);
|
|
64
98
|
});
|
|
65
99
|
|
|
66
100
|
pi.on('session_shutdown', async () => {
|
|
@@ -172,20 +206,24 @@ export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
|
172
206
|
if (command === 'reload') {
|
|
173
207
|
if (parts.length !== 1) throw new EmbeddingsError('configuration-invalid');
|
|
174
208
|
const next = loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx));
|
|
175
|
-
await refresh(next, ctx.cwd);
|
|
209
|
+
await refresh(next, ctx.cwd, await piCredentials(ctx));
|
|
176
210
|
reply(pi, ctx, `${EMBEDDINGS_SETTINGS_KEY} settings reloaded. No inference was run.`);
|
|
177
211
|
return;
|
|
178
212
|
}
|
|
179
213
|
if (command === 'use') {
|
|
180
214
|
if (parts.length !== 3) throw new EmbeddingsError('configuration-invalid');
|
|
181
215
|
const route: EmbeddingRoute = { provider: parts[1] as EmbeddingRoute['provider'], model: parts[2] ?? '' };
|
|
182
|
-
|
|
216
|
+
configuredDefault({ default: route });
|
|
183
217
|
await updateProjectEmbeddingSettings({
|
|
184
218
|
cwd: ctx.cwd,
|
|
185
219
|
projectTrusted: isProjectTrusted(ctx),
|
|
186
220
|
route,
|
|
187
221
|
});
|
|
188
|
-
await refresh(
|
|
222
|
+
await refresh(
|
|
223
|
+
loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
224
|
+
ctx.cwd,
|
|
225
|
+
await piCredentials(ctx)
|
|
226
|
+
);
|
|
189
227
|
reply(pi, ctx, `Selected ${route.provider}/${route.model} in trusted project settings.`);
|
|
190
228
|
return;
|
|
191
229
|
}
|
package/src/index.ts
CHANGED
|
@@ -7,6 +7,7 @@ export {
|
|
|
7
7
|
isEmbeddingSettings,
|
|
8
8
|
} from './settings.js';
|
|
9
9
|
export { EmbeddingsError } from './errors.js';
|
|
10
|
+
export type { EmbeddingCredentialResolver } from './provider-types.js';
|
|
10
11
|
export {
|
|
11
12
|
EMBEDDINGS_SETTINGS_KEY,
|
|
12
13
|
EMBEDDINGS_PROTOCOL_VERSION,
|
|
@@ -16,6 +17,16 @@ export {
|
|
|
16
17
|
EMBEDDING_CONTEXT_META_KEY,
|
|
17
18
|
EMBEDDING_ROUTE_IDS,
|
|
18
19
|
GATEWAY_EMBEDDING_MODELS,
|
|
20
|
+
GEMINI_EMBEDDING_MODELS,
|
|
21
|
+
VERTEX_EMBEDDING_LOCATIONS,
|
|
22
|
+
OPENCODE_EMBEDDING_MODELS,
|
|
23
|
+
OPENCODE_GO_EMBEDDING_MODELS,
|
|
24
|
+
GEMINI_EMBEDDING_MIN_DIMENSIONS,
|
|
25
|
+
GEMINI_EMBEDDING_MAX_DIMENSIONS,
|
|
26
|
+
GEMINI_EMBEDDING_TASK_FORMATS,
|
|
27
|
+
GEMINI_TASK_PREFIXES,
|
|
28
|
+
DEFAULT_GEMINI_DIMENSIONS,
|
|
29
|
+
DEFAULT_GEMINI_TASK_FORMAT,
|
|
19
30
|
EMBEDDING_ERROR_CODES,
|
|
20
31
|
} from './schemas.js';
|
|
21
32
|
export type {
|
|
@@ -33,4 +44,9 @@ export type {
|
|
|
33
44
|
EmbeddingCompareEntry,
|
|
34
45
|
EmbeddingCompareResult,
|
|
35
46
|
EmbeddingErrorCode,
|
|
47
|
+
GeminiEmbeddingDimension,
|
|
48
|
+
GeminiEmbeddingTaskFormat,
|
|
49
|
+
OpenCodeRouteId,
|
|
50
|
+
OpenCodeEmbeddingModel,
|
|
51
|
+
OpenCodeGoEmbeddingModel,
|
|
36
52
|
} from './schemas.js';
|
package/src/provider-types.ts
CHANGED
|
@@ -14,8 +14,15 @@ export type ProviderUsage = Readonly<{
|
|
|
14
14
|
export type ProviderBatchResult = Readonly<{
|
|
15
15
|
readonly vectors: readonly (readonly number[])[];
|
|
16
16
|
readonly usage: ProviderUsage;
|
|
17
|
+
/** Set only when the response establishes a more specific space than the preflight descriptor. */
|
|
18
|
+
readonly space?: EmbeddingSpace | undefined;
|
|
17
19
|
}>;
|
|
18
20
|
|
|
21
|
+
/** Supplied by hosts with a supported provider-key lookup; never invoked with a secret value. */
|
|
22
|
+
export type EmbeddingCredentialResolver = (
|
|
23
|
+
provider: EmbeddingRouteId
|
|
24
|
+
) => Promise<string | undefined>;
|
|
25
|
+
|
|
19
26
|
export interface EmbeddingsProvider {
|
|
20
27
|
readonly route: EmbeddingRouteId;
|
|
21
28
|
readonly model: string;
|
package/src/providers.ts
CHANGED
|
@@ -1,20 +1,43 @@
|
|
|
1
1
|
import { getEncoding } from 'js-tiktoken';
|
|
2
|
+
import { VertexProvider, vertexEmbeddingSpace } from './vertex-provider.js';
|
|
2
3
|
import { EmbeddingsError } from './errors.js';
|
|
3
4
|
import {
|
|
4
5
|
EMBEDDING_DOCUMENT_PREFIX,
|
|
5
6
|
EMBEDDING_FORMAT_VERSION,
|
|
6
7
|
EMBEDDING_NORMALIZATION_VERSION,
|
|
7
8
|
CLOUDFLARE_EMBEDDING_MODELS,
|
|
9
|
+
DEFAULT_GEMINI_DIMENSIONS,
|
|
10
|
+
DEFAULT_GEMINI_TASK_FORMAT,
|
|
11
|
+
GEMINI_EMBEDDING_MODELS,
|
|
12
|
+
GEMINI_TASK_PREFIXES,
|
|
13
|
+
OPENCODE_EMBEDDING_MODELS,
|
|
14
|
+
OPENCODE_GO_EMBEDDING_MODELS,
|
|
8
15
|
OPENROUTER_EMBEDDING_MODELS,
|
|
9
16
|
type EmbeddingContext,
|
|
10
17
|
type EmbeddingRoute,
|
|
11
18
|
type EmbeddingSettings,
|
|
12
19
|
type EmbeddingSpace,
|
|
20
|
+
type GeminiEmbeddingDimension,
|
|
21
|
+
type GeminiEmbeddingTaskFormat,
|
|
22
|
+
type OpenCodeEmbeddingModel,
|
|
23
|
+
type OpenCodeGoEmbeddingModel,
|
|
24
|
+
type OpenCodeRouteId,
|
|
13
25
|
} from './schemas.js';
|
|
14
26
|
import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
|
|
15
27
|
import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE, type AcquiredLocalRuntime } from './local-runtime.js';
|
|
16
|
-
import type {
|
|
17
|
-
|
|
28
|
+
import type {
|
|
29
|
+
EmbeddingCredentialResolver,
|
|
30
|
+
EmbeddingsProvider,
|
|
31
|
+
PreparedInput,
|
|
32
|
+
ProviderBatchResult,
|
|
33
|
+
} from './provider-types.js';
|
|
34
|
+
import {
|
|
35
|
+
parseBatchResponse,
|
|
36
|
+
parseCloudflareBatchResponse,
|
|
37
|
+
parseGeminiCountTokensResponse,
|
|
38
|
+
parseGeminiEmbeddingResponse,
|
|
39
|
+
parseOpenCodeBatchResponse,
|
|
40
|
+
} from './response.js';
|
|
18
41
|
|
|
19
42
|
export const OPENAI_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
|
|
20
43
|
provider: 'openai',
|
|
@@ -56,16 +79,86 @@ export const cloudflareEmbeddingSpace = (pooling: CloudflarePooling): EmbeddingS
|
|
|
56
79
|
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
57
80
|
});
|
|
58
81
|
|
|
82
|
+
export const geminiEmbeddingSpace = (config: {
|
|
83
|
+
dimensions: GeminiEmbeddingDimension;
|
|
84
|
+
taskFormat: GeminiEmbeddingTaskFormat;
|
|
85
|
+
}): EmbeddingSpace =>
|
|
86
|
+
Object.freeze({
|
|
87
|
+
provider: 'gemini',
|
|
88
|
+
model: GEMINI_EMBEDDING_MODELS[0],
|
|
89
|
+
revision: null,
|
|
90
|
+
quantization: null,
|
|
91
|
+
runtime: 'gemini-api-v1beta',
|
|
92
|
+
dimensions: config.dimensions,
|
|
93
|
+
taskFormat: config.taskFormat,
|
|
94
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
95
|
+
prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
|
|
96
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
97
|
+
});
|
|
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
|
+
|
|
59
105
|
const OPENAI_MODEL = 'text-embedding-3-small';
|
|
60
106
|
const SARVAM_MODEL = 'embeddinggemma-2';
|
|
61
107
|
const SARVAM_ORIGIN = 'https://api.sarvam.ai';
|
|
62
108
|
const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
|
|
63
109
|
const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
|
|
110
|
+
const GEMINI_ORIGIN = 'https://generativelanguage.googleapis.com';
|
|
111
|
+
const GEMINI_MAX_INPUT_TOKENS = 8192;
|
|
64
112
|
|
|
65
113
|
const OPENAI_MAX_INPUT_TOKENS = 8192;
|
|
66
114
|
const OPENAI_MAX_REQUEST_INPUTS = 2048;
|
|
67
115
|
const OPENAI_MAX_REQUEST_TOKENS = 300000;
|
|
68
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
|
+
|
|
69
162
|
const trim = (value: string | undefined): string | undefined => {
|
|
70
163
|
const trimmed = value?.trim();
|
|
71
164
|
return trimmed === undefined || trimmed === '' ? undefined : trimmed;
|
|
@@ -73,13 +166,19 @@ const trim = (value: string | undefined): string | undefined => {
|
|
|
73
166
|
|
|
74
167
|
export const routeKey = (route: EmbeddingRoute): string => `${route.provider}\u0000${route.model}`;
|
|
75
168
|
|
|
169
|
+
export type OpenCodeCredentialAvailability = Readonly<Partial<Record<OpenCodeRouteId, boolean>>>;
|
|
170
|
+
|
|
76
171
|
export type EmbeddingDiagnostic = Readonly<{
|
|
77
172
|
readonly code: string;
|
|
78
173
|
readonly severity: 'error' | 'warning' | 'info';
|
|
79
174
|
}>;
|
|
80
175
|
|
|
81
176
|
/** Diagnostics are provider-free and never contain keys, origins or model paths. */
|
|
82
|
-
export function routeDiagnostics(
|
|
177
|
+
export function routeDiagnostics(
|
|
178
|
+
settings: EmbeddingSettings,
|
|
179
|
+
route: EmbeddingRoute,
|
|
180
|
+
piCredentialAvailable: OpenCodeCredentialAvailability = {}
|
|
181
|
+
): EmbeddingDiagnostic[] {
|
|
83
182
|
const diagnostics: EmbeddingDiagnostic[] = [];
|
|
84
183
|
const add = (code: string, severity: EmbeddingDiagnostic['severity'] = 'error'): void => {
|
|
85
184
|
diagnostics.push({ code, severity });
|
|
@@ -121,6 +220,30 @@ export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRo
|
|
|
121
220
|
add('cloudflare-gateway-unconfigured');
|
|
122
221
|
break;
|
|
123
222
|
}
|
|
223
|
+
case 'gemini':
|
|
224
|
+
if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
|
|
225
|
+
add('gemini-key-unconfigured');
|
|
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;
|
|
243
|
+
case 'vertex':
|
|
244
|
+
if (settings.providers?.vertex === undefined) add('vertex-configuration-unconfigured');
|
|
245
|
+
// Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
|
|
246
|
+
break;
|
|
124
247
|
}
|
|
125
248
|
return diagnostics;
|
|
126
249
|
}
|
|
@@ -137,6 +260,34 @@ const headerCredential = (configured: string | undefined, env: string | undefine
|
|
|
137
260
|
return value;
|
|
138
261
|
};
|
|
139
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
|
+
|
|
140
291
|
/** The documented text-string path avoids the token-array schema contradiction without truncating. */
|
|
141
292
|
const openAIPrepare = (
|
|
142
293
|
encoding: ReturnType<typeof getEncoding>,
|
|
@@ -202,6 +353,72 @@ class OpenAiProvider implements EmbeddingsProvider {
|
|
|
202
353
|
}
|
|
203
354
|
}
|
|
204
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
|
+
|
|
205
422
|
class SarvamProvider implements EmbeddingsProvider {
|
|
206
423
|
readonly route = 'sarvam' as const;
|
|
207
424
|
readonly model = SARVAM_MODEL;
|
|
@@ -404,6 +621,76 @@ class CloudflareProvider implements EmbeddingsProvider {
|
|
|
404
621
|
}
|
|
405
622
|
}
|
|
406
623
|
|
|
624
|
+
class GeminiProvider implements EmbeddingsProvider {
|
|
625
|
+
readonly route = 'gemini' as const;
|
|
626
|
+
readonly model = GEMINI_EMBEDDING_MODELS[0];
|
|
627
|
+
readonly space: EmbeddingSpace;
|
|
628
|
+
// One exact prepared prompt is counted and embedded per request; no vector is accepted unless the
|
|
629
|
+
// embed response token count equals that preflight count.
|
|
630
|
+
readonly maxRequestInputs = 1;
|
|
631
|
+
readonly maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
632
|
+
readonly #url = new URL(`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:embedContent`, GEMINI_ORIGIN);
|
|
633
|
+
readonly #countUrl = new URL(
|
|
634
|
+
`/v1beta/models/${GEMINI_EMBEDDING_MODELS[0]}:countTokens`,
|
|
635
|
+
GEMINI_ORIGIN
|
|
636
|
+
);
|
|
637
|
+
readonly #key: string;
|
|
638
|
+
readonly #taskFormat: GeminiEmbeddingTaskFormat;
|
|
639
|
+
|
|
640
|
+
constructor(key: string, config: {
|
|
641
|
+
dimensions: GeminiEmbeddingDimension;
|
|
642
|
+
taskFormat: GeminiEmbeddingTaskFormat;
|
|
643
|
+
}) {
|
|
644
|
+
this.#key = key;
|
|
645
|
+
this.#taskFormat = config.taskFormat;
|
|
646
|
+
this.space = geminiEmbeddingSpace(config);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
|
|
650
|
+
signal.throwIfAborted();
|
|
651
|
+
const prepared = GEMINI_TASK_PREFIXES[this.#taskFormat] + text;
|
|
652
|
+
const response = await requestJson({
|
|
653
|
+
url: this.#countUrl,
|
|
654
|
+
signal,
|
|
655
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
656
|
+
body: { contents: [{ parts: [{ text: prepared }] }] },
|
|
657
|
+
});
|
|
658
|
+
const tokenCount = parseGeminiCountTokensResponse(response);
|
|
659
|
+
if (tokenCount > GEMINI_MAX_INPUT_TOKENS)
|
|
660
|
+
throw new EmbeddingsError('input-too-long', {
|
|
661
|
+
knownUsage: { preparedInputTokens: tokenCount },
|
|
662
|
+
});
|
|
663
|
+
return { kind: 'text', text: prepared, tokenCount };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
|
|
667
|
+
const text = providerTexts(inputs)[0];
|
|
668
|
+
if (inputs.length !== 1 || text === undefined)
|
|
669
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
670
|
+
const preparedInputTokens = preparedTokens(inputs);
|
|
671
|
+
const response = await requestJson({
|
|
672
|
+
url: this.#url,
|
|
673
|
+
signal,
|
|
674
|
+
headers: { 'x-goog-api-key': this.#key },
|
|
675
|
+
body: {
|
|
676
|
+
model: `models/${this.model}`,
|
|
677
|
+
content: { parts: [{ text }] },
|
|
678
|
+
output_dimensionality: this.space.dimensions,
|
|
679
|
+
},
|
|
680
|
+
});
|
|
681
|
+
return parseGeminiEmbeddingResponse({
|
|
682
|
+
response,
|
|
683
|
+
space: this.space,
|
|
684
|
+
maxInputTokens: GEMINI_MAX_INPUT_TOKENS,
|
|
685
|
+
preparedInputTokens,
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
async close(): Promise<void> {
|
|
690
|
+
// Native fetch owns no long-lived resource.
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
407
694
|
export type AcquiredProvider = Readonly<{
|
|
408
695
|
readonly provider: EmbeddingsProvider;
|
|
409
696
|
readonly release: () => Promise<void>;
|
|
@@ -416,10 +703,12 @@ export async function acquireProvider({
|
|
|
416
703
|
settings,
|
|
417
704
|
route,
|
|
418
705
|
signal,
|
|
706
|
+
credentialResolver,
|
|
419
707
|
}: {
|
|
420
708
|
settings: EmbeddingSettings;
|
|
421
709
|
route: EmbeddingRoute;
|
|
422
710
|
signal: AbortSignal;
|
|
711
|
+
credentialResolver?: EmbeddingCredentialResolver | undefined;
|
|
423
712
|
}): Promise<AcquiredProvider> {
|
|
424
713
|
switch (route.provider) {
|
|
425
714
|
case 'local': {
|
|
@@ -495,6 +784,39 @@ export async function acquireProvider({
|
|
|
495
784
|
release: noRelease,
|
|
496
785
|
};
|
|
497
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
|
+
};
|
|
802
|
+
case 'vertex': {
|
|
803
|
+
const configured = settings.providers?.vertex;
|
|
804
|
+
if (configured === undefined) throw new EmbeddingsError('configuration-invalid');
|
|
805
|
+
return { provider: new VertexProvider(configured), release: noRelease };
|
|
806
|
+
}
|
|
807
|
+
case 'gemini': {
|
|
808
|
+
const configured = settings.providers?.gemini;
|
|
809
|
+
return {
|
|
810
|
+
provider: new GeminiProvider(
|
|
811
|
+
headerCredential(configured?.apiKey, process.env.GEMINI_API_KEY),
|
|
812
|
+
{
|
|
813
|
+
dimensions: configured?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
814
|
+
taskFormat: configured?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
815
|
+
}
|
|
816
|
+
),
|
|
817
|
+
release: noRelease,
|
|
818
|
+
};
|
|
819
|
+
}
|
|
498
820
|
}
|
|
499
821
|
}
|
|
500
822
|
|
|
@@ -513,5 +835,18 @@ export const spaceForRoute = (
|
|
|
513
835
|
return SARVAM_EMBEDDING_SPACE;
|
|
514
836
|
case 'cloudflare':
|
|
515
837
|
return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
|
|
838
|
+
case 'vertex': {
|
|
839
|
+
const configured = settings?.providers?.vertex;
|
|
840
|
+
if (configured === undefined) throw new EmbeddingsError('configuration-invalid');
|
|
841
|
+
return vertexEmbeddingSpace(configured);
|
|
842
|
+
}
|
|
843
|
+
case 'gemini':
|
|
844
|
+
return geminiEmbeddingSpace({
|
|
845
|
+
dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
|
|
846
|
+
taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
|
|
847
|
+
});
|
|
848
|
+
case 'opencode':
|
|
849
|
+
case 'opencode-go':
|
|
850
|
+
return opencodeEmbeddingSpace({ provider: route.provider, model: route.model, dimensions: null });
|
|
516
851
|
}
|
|
517
852
|
};
|