@abhishek944/pi-embeddings 0.1.0 → 0.4.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 +59 -9
- package/dist/execute.js +56 -3
- package/dist/extension.js +8 -39
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/mcp-server.js +1 -14
- package/dist/providers.d.ts +13 -2
- package/dist/providers.js +263 -3
- package/dist/response.d.ts +21 -0
- package/dist/response.js +115 -0
- package/dist/runtime.d.ts +22 -2
- package/dist/runtime.js +12 -3
- package/dist/schemas.d.ts +703 -81
- package/dist/schemas.js +137 -16
- package/dist/settings-write.js +2 -2
- package/dist/settings.js +8 -1
- package/dist/tool-contracts.d.ts +459 -184
- package/dist/tool-contracts.js +2 -11
- package/dist/vertex-provider.d.ts +18 -0
- package/dist/vertex-provider.js +139 -0
- package/package.json +9 -2
- package/src/execute.ts +59 -3
- package/src/extension.ts +12 -47
- package/src/index.ts +11 -2
- package/src/mcp-server.ts +0 -19
- package/src/providers.ts +322 -3
- package/src/response.ts +135 -0
- package/src/runtime.ts +44 -6
- package/src/schemas.ts +180 -26
- package/src/settings-write.ts +2 -2
- package/src/settings.ts +10 -0
- package/src/tool-contracts.ts +1 -13
- package/src/vertex-provider.ts +152 -0
package/dist/tool-contracts.js
CHANGED
|
@@ -1,19 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { embeddingDescribeSchema, embeddingCompareResultSchema, embeddingRequestSchema, embeddingResultSchema, } from './schemas.js';
|
|
1
|
+
import { embeddingCompareResultSchema, embeddingRequestSchema, embeddingResultSchema, } from './schemas.js';
|
|
3
2
|
export const EMBED_TOOL = 'embed';
|
|
4
3
|
export const EMBED_COMPARE_TOOL = 'embed_compare';
|
|
5
|
-
export const EMBEDDINGS_DESCRIBE_TOOL = 'embeddings_describe';
|
|
6
4
|
export const EMBED_TOOL_DESCRIPTION = 'Embed one or more text inputs with the server-configured embedding route. Provider, model, fallback routes and credentials stay in trusted settings; this tool cannot override them. Returns vectors and their actual generating space as structured data. Full text is preserved; the package owns prefixing and provider batching. Use embed_compare only for an explicit comparison.';
|
|
7
5
|
export const EMBED_COMPARE_TOOL_DESCRIPTION = 'Explicitly compare the same text inputs using exactly the configured compare routes. Every entry is a separate request and may incur charges. No implicit default, fallback, ranking or settings mutation.';
|
|
8
|
-
export const EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION = 'Report the selected configured embedding route, generating space and provider-free readiness diagnostics without inference or credentials. Information is not a reservation or a caller storage policy.';
|
|
9
6
|
export const embedParameters = embeddingRequestSchema;
|
|
10
7
|
export const embedCompareParameters = embeddingRequestSchema;
|
|
11
|
-
export const embeddingsDescribeParameters = Type.Object({}, { additionalProperties: false });
|
|
12
8
|
export const embedOutput = embeddingResultSchema;
|
|
13
9
|
export const embedCompareOutput = embeddingCompareResultSchema;
|
|
14
|
-
export const
|
|
15
|
-
export const EMBEDDINGS_TOOL_NAMES = [
|
|
16
|
-
EMBED_TOOL,
|
|
17
|
-
EMBED_COMPARE_TOOL,
|
|
18
|
-
EMBEDDINGS_DESCRIBE_TOOL,
|
|
19
|
-
];
|
|
10
|
+
export const EMBEDDINGS_TOOL_NAMES = [EMBED_TOOL, EMBED_COMPARE_TOOL];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
|
|
2
|
+
import { type EmbeddingSettings, type EmbeddingSpace } from './schemas.js';
|
|
3
|
+
type VertexSettings = NonNullable<NonNullable<EmbeddingSettings['providers']>['vertex']>;
|
|
4
|
+
export declare const vertexEmbeddingSpace: (config: VertexSettings) => EmbeddingSpace;
|
|
5
|
+
/** Native Vertex transport: fixed Google hosts, explicit resource, keyless ADC, no gcloud or API keys. */
|
|
6
|
+
export declare class VertexProvider implements EmbeddingsProvider {
|
|
7
|
+
#private;
|
|
8
|
+
readonly route: "vertex";
|
|
9
|
+
readonly model: "gemini-embedding-2";
|
|
10
|
+
readonly space: EmbeddingSpace;
|
|
11
|
+
readonly maxRequestInputs = 1;
|
|
12
|
+
readonly maxRequestTokens: number;
|
|
13
|
+
constructor(config: VertexSettings);
|
|
14
|
+
prepare(text: string, signal: AbortSignal): Promise<PreparedInput>;
|
|
15
|
+
embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { GdchClient, GoogleAuth, JWT } from 'google-auth-library';
|
|
2
|
+
import { EmbeddingsError } from './errors.js';
|
|
3
|
+
import { headerValueIsSafe, requestJson } from './provider-http.js';
|
|
4
|
+
import { parseGeminiCountTokensResponse, parseVertexEmbeddingResponse } from './response.js';
|
|
5
|
+
import { EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, GEMINI_EMBEDDING_MODELS, GEMINI_TASK_PREFIXES, } from './schemas.js';
|
|
6
|
+
// Gemini Embedding 2 shares an 8192-token window across modalities; excess input is silently truncated.
|
|
7
|
+
// https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings
|
|
8
|
+
const MAX_INPUT_TOKENS = 8192;
|
|
9
|
+
export const vertexEmbeddingSpace = (config) => Object.freeze({
|
|
10
|
+
provider: 'vertex',
|
|
11
|
+
model: GEMINI_EMBEDDING_MODELS[0],
|
|
12
|
+
revision: null,
|
|
13
|
+
quantization: null,
|
|
14
|
+
runtime: 'vertex-ai-v1',
|
|
15
|
+
dimensions: config.dimensions,
|
|
16
|
+
taskFormat: config.taskFormat,
|
|
17
|
+
format: EMBEDDING_FORMAT_VERSION,
|
|
18
|
+
prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
|
|
19
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
20
|
+
});
|
|
21
|
+
/** Inspect only ADC type metadata, including an impersonation source; never expose credentials. */
|
|
22
|
+
const isKeylessCredentialMetadata = (metadata) => {
|
|
23
|
+
if (typeof metadata !== 'object' || metadata === null || !('type' in metadata))
|
|
24
|
+
return false;
|
|
25
|
+
switch (metadata.type) {
|
|
26
|
+
case 'authorized_user':
|
|
27
|
+
case 'external_account':
|
|
28
|
+
case 'external_account_authorized_user':
|
|
29
|
+
return true;
|
|
30
|
+
case 'impersonated_service_account':
|
|
31
|
+
return 'source_credentials' in metadata && isKeylessCredentialMetadata(metadata.source_credentials);
|
|
32
|
+
default:
|
|
33
|
+
// The SDK treats missing/unknown types as JWT credentials too; a denylist misses nested keys.
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** Native Vertex transport: fixed Google hosts, explicit resource, keyless ADC, no gcloud or API keys. */
|
|
38
|
+
export class VertexProvider {
|
|
39
|
+
route = 'vertex';
|
|
40
|
+
model = GEMINI_EMBEDDING_MODELS[0];
|
|
41
|
+
space;
|
|
42
|
+
maxRequestInputs = 1; // embedContent contains exactly one Content.
|
|
43
|
+
maxRequestTokens = Number.POSITIVE_INFINITY;
|
|
44
|
+
#config;
|
|
45
|
+
#auth;
|
|
46
|
+
#url;
|
|
47
|
+
#countUrl;
|
|
48
|
+
constructor(config) {
|
|
49
|
+
this.#config = config;
|
|
50
|
+
this.space = vertexEmbeddingSpace(config);
|
|
51
|
+
const origin = config.location === 'global'
|
|
52
|
+
? 'https://aiplatform.googleapis.com'
|
|
53
|
+
: `https://aiplatform.${config.location}.rep.googleapis.com`;
|
|
54
|
+
const resource = `/v1/projects/${encodeURIComponent(config.project)}/locations/${config.location}/publishers/google/models/${this.model}`;
|
|
55
|
+
this.#url = new URL(`${resource}:embedContent`, origin);
|
|
56
|
+
this.#countUrl = new URL(`${resource}:countTokens`, origin);
|
|
57
|
+
// An explicit project also prevents ADC discovery from invoking gcloud to infer one.
|
|
58
|
+
this.#auth = new GoogleAuth({
|
|
59
|
+
projectId: config.project,
|
|
60
|
+
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
async #headers(url, signal) {
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
let listener;
|
|
66
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
67
|
+
listener = () => reject(new EmbeddingsError('cancelled'));
|
|
68
|
+
signal.addEventListener('abort', listener, { once: true });
|
|
69
|
+
});
|
|
70
|
+
try {
|
|
71
|
+
// The SDK does not expose an AbortSignal for ADC discovery/refresh. Stop waiting on cancellation;
|
|
72
|
+
// any in-flight SDK refresh may finish, but cannot proceed to a model request after cancellation.
|
|
73
|
+
const headers = await Promise.race([(async () => {
|
|
74
|
+
const client = await this.#auth.getClient();
|
|
75
|
+
if (client instanceof JWT || client instanceof GdchClient ||
|
|
76
|
+
(this.#auth.jsonContent !== null && !isKeylessCredentialMetadata(this.#auth.jsonContent)))
|
|
77
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
78
|
+
signal.throwIfAborted();
|
|
79
|
+
return client.getRequestHeaders(url);
|
|
80
|
+
})(), cancelled]);
|
|
81
|
+
signal.throwIfAborted();
|
|
82
|
+
const authorization = headers.get('authorization');
|
|
83
|
+
if (authorization === null || !authorization.startsWith('Bearer ') || !headerValueIsSafe(authorization))
|
|
84
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
85
|
+
const result = { authorization };
|
|
86
|
+
const quotaProject = headers.get('x-goog-user-project');
|
|
87
|
+
if (quotaProject !== null) {
|
|
88
|
+
if (!headerValueIsSafe(quotaProject))
|
|
89
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
90
|
+
result['x-goog-user-project'] = quotaProject;
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// SDK errors may contain sensitive request metadata. Never propagate them or infer a retry/fallback.
|
|
96
|
+
throw new EmbeddingsError(signal.aborted ? 'cancelled' : 'configuration-invalid');
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
if (listener !== undefined)
|
|
100
|
+
signal.removeEventListener('abort', listener);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async prepare(text, signal) {
|
|
104
|
+
const prepared = GEMINI_TASK_PREFIXES[this.#config.taskFormat] + text;
|
|
105
|
+
const response = await requestJson({
|
|
106
|
+
url: this.#countUrl,
|
|
107
|
+
signal,
|
|
108
|
+
headers: await this.#headers(this.#countUrl, signal),
|
|
109
|
+
body: { contents: [{ role: 'user', parts: [{ text: prepared }] }] },
|
|
110
|
+
});
|
|
111
|
+
const tokenCount = parseGeminiCountTokensResponse(response);
|
|
112
|
+
if (tokenCount > MAX_INPUT_TOKENS)
|
|
113
|
+
throw new EmbeddingsError('input-too-long', { knownUsage: { preparedInputTokens: tokenCount } });
|
|
114
|
+
return { kind: 'text', text: prepared, tokenCount };
|
|
115
|
+
}
|
|
116
|
+
async embed(inputs, signal) {
|
|
117
|
+
const input = inputs[0];
|
|
118
|
+
if (inputs.length !== 1 || input?.kind !== 'text' || input.tokenCount === null)
|
|
119
|
+
throw new EmbeddingsError('provider-response-invalid');
|
|
120
|
+
const response = await requestJson({
|
|
121
|
+
url: this.#url,
|
|
122
|
+
signal,
|
|
123
|
+
headers: await this.#headers(this.#url, signal),
|
|
124
|
+
body: {
|
|
125
|
+
content: { role: 'user', parts: [{ text: input.text }] },
|
|
126
|
+
embedContentConfig: { outputDimensionality: this.space.dimensions },
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
return parseVertexEmbeddingResponse({
|
|
130
|
+
response,
|
|
131
|
+
space: this.space,
|
|
132
|
+
maxInputTokens: MAX_INPUT_TOKENS,
|
|
133
|
+
preparedInputTokens: input.tokenCount,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
async close() {
|
|
137
|
+
// ADC and native fetch own no adapter-created child, timer or listener.
|
|
138
|
+
}
|
|
139
|
+
}
|
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.4.0",
|
|
4
|
+
"description": "Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam, Gemini, Vertex ADC and gateway routes, ordered fallback and explicit comparisons.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
7
7
|
"pi",
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
"mcp",
|
|
10
10
|
"openai",
|
|
11
11
|
"sarvam",
|
|
12
|
+
"gemini",
|
|
12
13
|
"embeddinggemma",
|
|
13
14
|
"litellm"
|
|
14
15
|
],
|
|
@@ -65,6 +66,7 @@
|
|
|
65
66
|
"dependencies": {
|
|
66
67
|
"@amaster.ai/pi-shared": "^0.1.10",
|
|
67
68
|
"@modelcontextprotocol/sdk": "1.32.1",
|
|
69
|
+
"google-auth-library": "10.9.1",
|
|
68
70
|
"js-tiktoken": "1.0.21"
|
|
69
71
|
},
|
|
70
72
|
"peerDependencies": {
|
|
@@ -81,5 +83,10 @@
|
|
|
81
83
|
"@types/node": "24.19.2",
|
|
82
84
|
"typebox": "1.3.27",
|
|
83
85
|
"typescript": "5.9.3"
|
|
86
|
+
},
|
|
87
|
+
"repository": {
|
|
88
|
+
"type": "git",
|
|
89
|
+
"url": "https://github.com/abhishek944/astack.git",
|
|
90
|
+
"directory": "packages/pi-embeddings"
|
|
84
91
|
}
|
|
85
92
|
}
|
package/src/execute.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
type EmbeddingCompareResult,
|
|
11
11
|
type EmbeddingContext,
|
|
12
12
|
type EmbeddingErrorCode,
|
|
13
|
+
type EmbeddingGeneration,
|
|
13
14
|
type EmbeddingOutcome,
|
|
14
15
|
type EmbeddingRequest,
|
|
15
16
|
type EmbeddingResult,
|
|
@@ -45,6 +46,38 @@ const unstarted = (index: number): EmbeddingOutcome => ({
|
|
|
45
46
|
const preparedTokenCount = (input: PreparedInput): number =>
|
|
46
47
|
input.kind === 'tokens' ? input.tokens.length : (input.tokenCount ?? 0);
|
|
47
48
|
|
|
49
|
+
const generationKey = (generation: EmbeddingGeneration): string =>
|
|
50
|
+
`${generation.provider}\u0000${generation.model}\u0000${JSON.stringify(generation.space)}`;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Record the complete set of actual generations. Singular metadata is set only when one generation
|
|
54
|
+
* produced every vector; a mixed fallback never collapses into a guessed route or space.
|
|
55
|
+
*/
|
|
56
|
+
const generationsOf = (outcomes: readonly EmbeddingOutcome[]): EmbeddingGeneration[] => {
|
|
57
|
+
const byKey = new Map<string, EmbeddingGeneration>();
|
|
58
|
+
for (const outcome of outcomes) {
|
|
59
|
+
if (outcome.status !== 'success') continue;
|
|
60
|
+
const generation: EmbeddingGeneration = {
|
|
61
|
+
provider: outcome.route,
|
|
62
|
+
model: outcome.model,
|
|
63
|
+
space: outcome.space,
|
|
64
|
+
};
|
|
65
|
+
byKey.set(generationKey(generation), generation);
|
|
66
|
+
}
|
|
67
|
+
return [...byKey.values()];
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const resultMetadata = (outcomes: readonly EmbeddingOutcome[]) => {
|
|
71
|
+
const generations = generationsOf(outcomes);
|
|
72
|
+
const only = generations.length === 1 ? generations[0] : undefined;
|
|
73
|
+
return {
|
|
74
|
+
provider: only?.provider ?? null,
|
|
75
|
+
model: only?.model ?? null,
|
|
76
|
+
space: only?.space ?? null,
|
|
77
|
+
generations,
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
|
|
48
81
|
/**
|
|
49
82
|
* Runs one ordinary call or one explicit comparison entry. Successful inputs are never replayed on a
|
|
50
83
|
* fallback route; only unfinished inputs continue. Every input keeps its original zero-based index.
|
|
@@ -102,8 +135,25 @@ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingRes
|
|
|
102
135
|
if (args.signal.aborted) outcomes[index] = cancelled(index);
|
|
103
136
|
else {
|
|
104
137
|
const code = codeOf(error);
|
|
105
|
-
|
|
106
|
-
|
|
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
|
+
}
|
|
107
157
|
}
|
|
108
158
|
}
|
|
109
159
|
}
|
|
@@ -207,9 +257,11 @@ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingRes
|
|
|
207
257
|
attemptId: failureByIndex.get(index)?.attemptId ?? null,
|
|
208
258
|
};
|
|
209
259
|
}
|
|
260
|
+
const allOutcomes = outcomes.map((outcome, index) => outcome ?? unstarted(index));
|
|
210
261
|
return {
|
|
211
262
|
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
212
|
-
|
|
263
|
+
...resultMetadata(allOutcomes),
|
|
264
|
+
outcomes: allOutcomes,
|
|
213
265
|
attempts,
|
|
214
266
|
};
|
|
215
267
|
}
|
|
@@ -231,6 +283,10 @@ export async function executeCompare(args: {
|
|
|
231
283
|
status: 'cancelled',
|
|
232
284
|
result: {
|
|
233
285
|
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
286
|
+
provider: null,
|
|
287
|
+
model: null,
|
|
288
|
+
space: null,
|
|
289
|
+
generations: [],
|
|
234
290
|
outcomes: args.request.inputs.map((_input, offset) => cancelled(offset)),
|
|
235
291
|
attempts: [],
|
|
236
292
|
},
|
package/src/extension.ts
CHANGED
|
@@ -5,8 +5,11 @@ import {
|
|
|
5
5
|
type ExtensionContext,
|
|
6
6
|
} from '@earendil-works/pi-coding-agent';
|
|
7
7
|
import { EmbeddingsError } from './errors.js';
|
|
8
|
-
import {
|
|
9
|
-
|
|
8
|
+
import {
|
|
9
|
+
createEmbeddingsRuntimeWithDiagnostics,
|
|
10
|
+
type EmbeddingsRuntimeWithDiagnostics,
|
|
11
|
+
} from './runtime.js';
|
|
12
|
+
import { configuredDefault, loadEmbeddingSettings } from './settings.js';
|
|
10
13
|
import { updateProjectEmbeddingSettings } from './settings-write.js';
|
|
11
14
|
import {
|
|
12
15
|
EMBEDDINGS_SETTINGS_KEY,
|
|
@@ -16,16 +19,12 @@ import {
|
|
|
16
19
|
import {
|
|
17
20
|
EMBED_COMPARE_TOOL,
|
|
18
21
|
EMBED_TOOL,
|
|
19
|
-
EMBEDDINGS_DESCRIBE_TOOL,
|
|
20
22
|
EMBED_COMPARE_TOOL_DESCRIPTION,
|
|
21
23
|
EMBED_TOOL_DESCRIPTION,
|
|
22
|
-
EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
|
|
23
24
|
embedCompareOutput,
|
|
24
25
|
embedCompareParameters,
|
|
25
26
|
embedOutput,
|
|
26
27
|
embedParameters,
|
|
27
|
-
embeddingsDescribeOutput,
|
|
28
|
-
embeddingsDescribeParameters,
|
|
29
28
|
} from './tool-contracts.js';
|
|
30
29
|
|
|
31
30
|
const summary = (result: {
|
|
@@ -44,17 +43,17 @@ const signalOptions = (signal: AbortSignal | undefined) =>
|
|
|
44
43
|
|
|
45
44
|
export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
46
45
|
let settings: EmbeddingSettings | undefined;
|
|
47
|
-
let runtime:
|
|
46
|
+
let runtime: EmbeddingsRuntimeWithDiagnostics | undefined;
|
|
48
47
|
let cwd = process.cwd();
|
|
49
48
|
|
|
50
49
|
const refresh = async (next: EmbeddingSettings, nextCwd = cwd): Promise<void> => {
|
|
51
50
|
await runtime?.close();
|
|
52
51
|
settings = next;
|
|
53
52
|
cwd = nextCwd;
|
|
54
|
-
runtime =
|
|
53
|
+
runtime = createEmbeddingsRuntimeWithDiagnostics({ settings: next, cwd: nextCwd });
|
|
55
54
|
};
|
|
56
55
|
|
|
57
|
-
const currentRuntime = (ctx: ExtensionContext):
|
|
56
|
+
const currentRuntime = (ctx: ExtensionContext): EmbeddingsRuntimeWithDiagnostics => {
|
|
58
57
|
if (runtime === undefined || cwd !== ctx.cwd)
|
|
59
58
|
throw new EmbeddingsError('configuration-invalid');
|
|
60
59
|
return runtime;
|
|
@@ -79,7 +78,7 @@ export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
|
79
78
|
promptGuidelines: [
|
|
80
79
|
'Provider, model, credentials and caller storage policy are fixed by trusted settings and cannot be overridden through this tool.',
|
|
81
80
|
'Use embed_compare only when the user explicitly asks to compare configured embedding routes.',
|
|
82
|
-
'
|
|
81
|
+
'The embed result reports the actual generating provider, model and space, including mixed fallback generations.',
|
|
83
82
|
],
|
|
84
83
|
parameters: embedParameters,
|
|
85
84
|
outputSchema: embedOutput,
|
|
@@ -130,49 +129,15 @@ export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
|
130
129
|
})
|
|
131
130
|
);
|
|
132
131
|
|
|
133
|
-
pi.registerTool(
|
|
134
|
-
defineTool({
|
|
135
|
-
name: EMBEDDINGS_DESCRIBE_TOOL,
|
|
136
|
-
label: 'Describe embeddings',
|
|
137
|
-
description: EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
|
|
138
|
-
promptSnippet:
|
|
139
|
-
'Report the configured embedding route, complete generating space and redacted readiness diagnostics without inference.',
|
|
140
|
-
promptGuidelines: [
|
|
141
|
-
'Describe is information, not a reservation or a storage-compatibility decision.',
|
|
142
|
-
'Do not treat ready as proof that an inference call succeeded or that a caller can persist the returned vectors.',
|
|
143
|
-
],
|
|
144
|
-
parameters: embeddingsDescribeParameters,
|
|
145
|
-
outputSchema: embeddingsDescribeOutput,
|
|
146
|
-
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
147
|
-
async execute(_id, _params, _signal, _onUpdate, ctx) {
|
|
148
|
-
try {
|
|
149
|
-
const described = currentRuntime(ctx).describe();
|
|
150
|
-
return {
|
|
151
|
-
content: [
|
|
152
|
-
{
|
|
153
|
-
type: 'text',
|
|
154
|
-
text: `${described.selected.provider}/${described.selected.model}; ready: ${described.ready}.`,
|
|
155
|
-
},
|
|
156
|
-
],
|
|
157
|
-
details: described,
|
|
158
|
-
structuredContent: described,
|
|
159
|
-
};
|
|
160
|
-
} catch (error) {
|
|
161
|
-
throw new Error(codeOf(error));
|
|
162
|
-
}
|
|
163
|
-
},
|
|
164
|
-
})
|
|
165
|
-
);
|
|
166
|
-
|
|
167
132
|
pi.registerCommand('embeddings', {
|
|
168
133
|
description:
|
|
169
|
-
'Embeddings: /embeddings list | doctor | reload | use <provider> <model> | compare <text>. list
|
|
134
|
+
'Embeddings: /embeddings list | doctor | reload | use <provider> <model> | compare <text>. list and doctor make no inference calls.',
|
|
170
135
|
handler: async (args: string | undefined, ctx: ExtensionContext) => {
|
|
171
136
|
const raw = (args ?? '').trim();
|
|
172
137
|
const parts = raw.split(/\s+/).filter(Boolean);
|
|
173
138
|
const command = parts[0] ?? 'list';
|
|
174
139
|
try {
|
|
175
|
-
if (command === 'list' || command === 'doctor' || command === '
|
|
140
|
+
if (command === 'list' || command === 'doctor' || command === 'status') {
|
|
176
141
|
if (parts.length !== 1) throw new EmbeddingsError('configuration-invalid');
|
|
177
142
|
const active = currentRuntime(ctx);
|
|
178
143
|
const described = active.describe();
|
|
@@ -214,7 +179,7 @@ export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
|
|
|
214
179
|
if (command === 'use') {
|
|
215
180
|
if (parts.length !== 3) throw new EmbeddingsError('configuration-invalid');
|
|
216
181
|
const route: EmbeddingRoute = { provider: parts[1] as EmbeddingRoute['provider'], model: parts[2] ?? '' };
|
|
217
|
-
|
|
182
|
+
configuredDefault({ default: route });
|
|
218
183
|
await updateProjectEmbeddingSettings({
|
|
219
184
|
cwd: ctx.cwd,
|
|
220
185
|
projectTrusted: isProjectTrusted(ctx),
|
package/src/index.ts
CHANGED
|
@@ -16,6 +16,14 @@ export {
|
|
|
16
16
|
EMBEDDING_CONTEXT_META_KEY,
|
|
17
17
|
EMBEDDING_ROUTE_IDS,
|
|
18
18
|
GATEWAY_EMBEDDING_MODELS,
|
|
19
|
+
GEMINI_EMBEDDING_MODELS,
|
|
20
|
+
VERTEX_EMBEDDING_LOCATIONS,
|
|
21
|
+
GEMINI_EMBEDDING_MIN_DIMENSIONS,
|
|
22
|
+
GEMINI_EMBEDDING_MAX_DIMENSIONS,
|
|
23
|
+
GEMINI_EMBEDDING_TASK_FORMATS,
|
|
24
|
+
GEMINI_TASK_PREFIXES,
|
|
25
|
+
DEFAULT_GEMINI_DIMENSIONS,
|
|
26
|
+
DEFAULT_GEMINI_TASK_FORMAT,
|
|
19
27
|
EMBEDDING_ERROR_CODES,
|
|
20
28
|
} from './schemas.js';
|
|
21
29
|
export type {
|
|
@@ -28,10 +36,11 @@ export type {
|
|
|
28
36
|
EmbeddingUsage,
|
|
29
37
|
EmbeddingAttempt,
|
|
30
38
|
EmbeddingOutcome,
|
|
39
|
+
EmbeddingGeneration,
|
|
31
40
|
EmbeddingResult,
|
|
32
41
|
EmbeddingCompareEntry,
|
|
33
42
|
EmbeddingCompareResult,
|
|
34
|
-
EmbeddingDiagnostic,
|
|
35
|
-
EmbeddingDescribe,
|
|
36
43
|
EmbeddingErrorCode,
|
|
44
|
+
GeminiEmbeddingDimension,
|
|
45
|
+
GeminiEmbeddingTaskFormat,
|
|
37
46
|
} from './schemas.js';
|
package/src/mcp-server.ts
CHANGED
|
@@ -23,13 +23,10 @@ import {
|
|
|
23
23
|
import {
|
|
24
24
|
EMBED_COMPARE_TOOL,
|
|
25
25
|
EMBED_TOOL,
|
|
26
|
-
EMBEDDINGS_DESCRIBE_TOOL,
|
|
27
26
|
EMBED_COMPARE_TOOL_DESCRIPTION,
|
|
28
27
|
EMBED_TOOL_DESCRIPTION,
|
|
29
|
-
EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
|
|
30
28
|
embedCompareParameters,
|
|
31
29
|
embedParameters,
|
|
32
|
-
embeddingsDescribeParameters,
|
|
33
30
|
} from './tool-contracts.js';
|
|
34
31
|
|
|
35
32
|
const require = createRequire(import.meta.url);
|
|
@@ -145,12 +142,6 @@ export async function createEmbeddingsMcpServer(
|
|
|
145
142
|
inputSchema: embedCompareParameters,
|
|
146
143
|
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
|
|
147
144
|
},
|
|
148
|
-
{
|
|
149
|
-
name: EMBEDDINGS_DESCRIBE_TOOL,
|
|
150
|
-
description: EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
|
|
151
|
-
inputSchema: embeddingsDescribeParameters,
|
|
152
|
-
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
153
|
-
},
|
|
154
145
|
],
|
|
155
146
|
}));
|
|
156
147
|
|
|
@@ -172,16 +163,6 @@ export async function createEmbeddingsMcpServer(
|
|
|
172
163
|
const compared = await runtime.compare(args, { signal: extra.signal, context });
|
|
173
164
|
return jsonResult(compared, `Compared ${compared.entries.length} configured embedding route(s).`);
|
|
174
165
|
}
|
|
175
|
-
case EMBEDDINGS_DESCRIBE_TOOL: {
|
|
176
|
-
const problems = validationProblems(embeddingsDescribeParameters, args);
|
|
177
|
-
if (problems.length > 0)
|
|
178
|
-
return errorResult(`Invalid arguments for ${request.params.name}:\n- ${problems.join('\n- ')}`);
|
|
179
|
-
const described = runtime.describe();
|
|
180
|
-
return jsonResult(
|
|
181
|
-
described,
|
|
182
|
-
`Embedding route ${described.selected.provider}/${described.selected.model}; ready: ${described.ready}.`
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
166
|
default:
|
|
186
167
|
throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${request.params.name}`);
|
|
187
168
|
}
|