@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/README.md
CHANGED
|
@@ -5,23 +5,23 @@ Config-driven text embeddings for Pi and MCP. The package owns provider configur
|
|
|
5
5
|
## Public surfaces
|
|
6
6
|
|
|
7
7
|
- `@abhishek944/pi-embeddings` — typed library factory and derived public types. No Pi runtime imports.
|
|
8
|
-
- `@abhishek944/pi-embeddings/schemas` — authoritative TypeBox schemas for settings, requests, outcomes, attempts, results, context, descriptors and
|
|
8
|
+
- `@abhishek944/pi-embeddings/schemas` — authoritative TypeBox schemas for settings, requests, outcomes, attempts, results, context, descriptors and actual generation metadata.
|
|
9
9
|
- `@abhishek944/pi-embeddings/extension` — Pi extension registered in `pi.extensions`.
|
|
10
10
|
- `@abhishek944/pi-embeddings/mcp` — `createEmbeddingsMcpServer`; transport-neutral, no Pi runtime dependency.
|
|
11
11
|
- `pi-embeddings-mcp` — stdio binary. stdout carries JSON-RPC only; diagnostics go to stderr.
|
|
12
12
|
|
|
13
|
-
MCP tools are `embed
|
|
13
|
+
MCP tools are `embed` and `embed_compare`. Vectors and their actual generating metadata are returned in `structuredContent.result`; the text content is a short summary. Pi commands are `/embeddings list`, `doctor`, `reload`, `use <provider> <model>` and `compare <text>`. There is no describe tool.
|
|
14
14
|
|
|
15
15
|
```ts
|
|
16
16
|
import { createEmbeddingsRuntime } from '@abhishek944/pi-embeddings';
|
|
17
17
|
|
|
18
18
|
const runtime = createEmbeddingsRuntime({ settings, cwd });
|
|
19
|
-
const described = runtime.describe();
|
|
20
19
|
const result = await runtime.embed({ inputs: ['Attribute: value'] }, { signal, context });
|
|
20
|
+
console.log(result.provider, result.model, result.space, result.generations);
|
|
21
21
|
await runtime.close();
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
There are no per-call provider, model, endpoint, credential or expected-space parameters. `
|
|
24
|
+
There are no per-call provider, model, endpoint, credential or expected-space parameters. The result reports the provider, model and complete space that actually generated the vectors. `generations` lists every distinct actual generation in first-seen order; the singular fields are populated only when one generation produced every vector. Mixed fallback results are never collapsed into a guessed route or space.
|
|
25
25
|
|
|
26
26
|
## Settings
|
|
27
27
|
|
|
@@ -46,15 +46,58 @@ Settings live under the `pi-embeddings` namespace. Pi loading follows global < a
|
|
|
46
46
|
"apiKey": "${LITELLM_INFERENCE_KEY}",
|
|
47
47
|
"model": "openai/text-embedding-3-small",
|
|
48
48
|
"stage": "dev"
|
|
49
|
+
},
|
|
50
|
+
"openrouter": { "apiKey": "${OPENROUTER_API_KEY}" },
|
|
51
|
+
"cloudflare": {
|
|
52
|
+
"accountId": "${CLOUDFLARE_ACCOUNT_ID}",
|
|
53
|
+
"apiKey": "${CLOUDFLARE_API_TOKEN}",
|
|
54
|
+
"gatewayId": "${CLOUDFLARE_AI_GATEWAY_ID}",
|
|
55
|
+
"model": "@cf/baai/bge-base-en-v1.5",
|
|
56
|
+
"pooling": "cls"
|
|
57
|
+
},
|
|
58
|
+
"gemini": {
|
|
59
|
+
"apiKey": "${GEMINI_API_KEY}",
|
|
60
|
+
"dimensions": 3072,
|
|
61
|
+
"taskFormat": "retrieval-document"
|
|
49
62
|
}
|
|
50
63
|
}
|
|
51
64
|
}
|
|
52
65
|
}
|
|
53
66
|
```
|
|
54
67
|
|
|
55
|
-
Provider IDs are route identifiers: `local`, `openai`, `sarvam` and `
|
|
68
|
+
Provider IDs are route identifiers: `local`, `openai`, `sarvam`, `gateway`, `openrouter`, `cloudflare`, `gemini` and `vertex`. Only the declared model pairs are valid. Omitted or empty `fallback` and `compare` lists are inactive. No route is activated by a schema annotation, a present key or existing model files. Credentials and identifiers may also come from `OPENROUTER_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_AI_GATEWAY_ID` and `GEMINI_API_KEY` in the trusted host environment. An environment fallback works only when the MCP process itself receives that variable; a hosted settings file that is copied without environment forwarding must carry `providers.gemini.apiKey` directly.
|
|
69
|
+
|
|
70
|
+
### Google Cloud Vertex (keyless ADC)
|
|
56
71
|
|
|
57
|
-
|
|
72
|
+
Vertex is a separate route, not a Gemini Developer API endpoint override. All four configuration fields are explicit; no API key, credential JSON, token or custom URL is accepted in package settings:
|
|
73
|
+
|
|
74
|
+
```json
|
|
75
|
+
{
|
|
76
|
+
"pi-embeddings": {
|
|
77
|
+
"version": 1,
|
|
78
|
+
"default": { "provider": "vertex", "model": "gemini-embedding-2" },
|
|
79
|
+
"fallback": [],
|
|
80
|
+
"providers": {
|
|
81
|
+
"vertex": {
|
|
82
|
+
"project": "highsku",
|
|
83
|
+
"location": "us",
|
|
84
|
+
"dimensions": 768,
|
|
85
|
+
"taskFormat": "retrieval-document"
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`location` is `us`, `eu` or `global`, the documented Gemini Embedding 2 locations. The `us` multi-region is not Iowa-only. `dimensions` accepts 128–3072 and `taskFormat` uses the same instruction formats as Gemini below. Selecting a Vertex route without its provider configuration fails validation before inference.
|
|
93
|
+
|
|
94
|
+
The official `google-auth-library` discovers ADC in the trusted host environment: local user ADC, attached service account metadata, workload/workforce federation or impersonation. Private-key service-account/GDCH credentials, including an impersonation source, are rejected. The adapter never runs `gcloud`, reads the operator's gcloud token cache, accepts a Gemini API key or creates credentials. The runtime identity needs `aiplatform.endpoints.predict` on the target project/model for both operations; API enablement, IAM, quota and billing remain operator responsibilities. No IAM/API change happens automatically. Local ADC is distinct from `gcloud auth login`; configure it through Google's documented [ADC setup](https://docs.cloud.google.com/docs/authentication/provide-credentials-adc) outside this package.
|
|
95
|
+
|
|
96
|
+
Both `countTokens` and `embedContent` use the same Vertex host and full resource path. US uses `https://aiplatform.us.rep.googleapis.com/v1/projects/{project}/locations/us/publishers/google/models/gemini-embedding-2:{method}`; EU uses the corresponding `eu` host; global uses `https://aiplatform.googleapis.com` with `locations/global`. Only the SDK's bearer authorization and optional quota-project header are forwarded. Native model requests reject redirects and have no automatic retry. ADC discovery/refresh errors are sanitized to `configuration-invalid`, not guessed to be fallback-eligible HTTP errors. Cancellation stops waiting for ADC and prevents a subsequent model request; an already-running SDK credential refresh may finish in the background.
|
|
97
|
+
|
|
98
|
+
Provider-free diagnostics validate configuration only: they do not prove ADC, API activation, permissions or live model readiness. A real successful neutral call is required to establish endpoint/counting acceptance for the selected project/location. The generic Vertex countTokens contract is documented, but model-specific support must not be claimed from static schema validation alone.
|
|
99
|
+
|
|
100
|
+
Ordinary calls use the configured default, then configured fallback in order, advancing only for typed missing credentials or HTTP 401/404/429 from route acquisition, provider preparation or embedding. Gemini `countTokens` preflight errors therefore follow the same fallback rule. There is no fallback for 403, refusal, 400/422, invalid input or vector, malformed response, token-count mismatch, ambiguous network failure, timeout, 5xx or cancellation. Successful inputs are never replayed on another route. Explicit comparison runs exactly the configured compare list in order, without fallback, ranking or default mutation.
|
|
58
101
|
|
|
59
102
|
## Routes and batching
|
|
60
103
|
|
|
@@ -62,6 +105,11 @@ Ordinary calls use the configured default, then configured fallback in order, ad
|
|
|
62
105
|
- `openai`: `text-embedding-3-small`, 1536 dimensions. Complete prefixed strings are submitted; `cl100k_base` counts the exact prepared string and a local encode/decode round-trip is checked. Mandatory limits are 8192 tokens per input, 2048 inputs and 300000 tokens per request.
|
|
63
106
|
- `sarvam`: hosted `embeddinggemma-2`, 768 dimensions. Strings are submitted and the service enforces its documented per-string token estimate; no local count or borrowed aggregate cap is invented.
|
|
64
107
|
- `gateway`: the declared OpenAI recipe through LiteLLM. Only `text-embedding-3-small` and `openai/text-embedding-3-small` aliases are supported. One request carries generic host attribution as `x-litellm-customer-id` and `x-litellm-tags`; missing or unsafe attribution refuses before inference.
|
|
108
|
+
- `openrouter`: `openai/text-embedding-3-small` through `https://openrouter.ai/api/v1/embeddings` with bearer authentication and float output. It shares the OpenAI generating-space descriptor because the declared model, text preparation and normalization are identical.
|
|
109
|
+
- `cloudflare`: `@cf/baai/bge-base-en-v1.5` through Cloudflare's documented REST `POST /ai/run/{model}`. The Cloudflare API token goes in `Authorization`, and the gateway ID goes in `cf-aig-gateway-id` as Workers AI requires. `pooling` defaults to `mean`; `cls` produces a different generating space and is recorded in the result. The REST API wraps the model output in its standard `result` envelope; the parser also accepts the model's raw `{ shape, data, pooling }` form. Cloudflare reports no local token usage, so usage fields are null.
|
|
110
|
+
- `gemini`: `gemini-embedding-2` through the fixed Gemini API `POST /v1beta/models/gemini-embedding-2:embedContent` endpoint with the `x-goog-api-key` header. `dimensions` accepts the documented 128–3072 range (768, 1536 and 3072 are Google's recommended sizes) and defaults to `3072`. `taskFormat` selects the documented Gemini 2 text prefix (`retrieval-document` by default, plus query and single-input formats); the package does not send `task_type`, which applies only to `gemini-embedding-001`. Each exact prepared prompt is counted with the model's `countTokens` endpoint before a single-input `embedContent` request; inputs over the documented 8192-token boundary fail before inference, and the embed response token count must match the preflight count before a vector is accepted. `autoTruncate: false` is deliberately not sent because the official SDK marks it Enterprise/Vertex-only. The exact dimension, task format and prefix are recorded in the generating space.
|
|
111
|
+
|
|
112
|
+
- `vertex`: Google Cloud `gemini-embedding-2` through the fixed Vertex `v1` `embedContent` and `countTokens` resource methods with keyless ADC. Each exact instruction-prefixed text is counted before inference and must fit the documented 8192-token window; `role: user` is consistent in both operations. Dimensions use `embedContentConfig.outputDimensionality`. The model's `task_type` and `autoTruncate` options are not used. A true response `truncated` flag, mismatched prompt count, missing usage, invalid dimensions or invalid vector fails closed; no truncated vector is accepted. Its complete descriptor has `provider: vertex` and `runtime: vertex-ai-v1`, distinct from `gemini` even for identical model names and dimensions.
|
|
65
113
|
|
|
66
114
|
The package supplies the document prefix `title: none | text: ` exactly once and normalizes vectors with the recorded stable L2 identity. It never summarizes, trims, chunks or truncates input text.
|
|
67
115
|
|
|
@@ -77,12 +125,14 @@ This is attribution only. The authenticated server-to-server boundary supplies c
|
|
|
77
125
|
|
|
78
126
|
## Generating spaces
|
|
79
127
|
|
|
80
|
-
Descriptors record canonical provider, model, known revision or explicit null, quantization/runtime/pooling provenance, dimensions, preparation prefix and normalization identity. Local and
|
|
128
|
+
Descriptors record canonical provider, model, known revision or explicit null, quantization/runtime/pooling provenance, dimensions, preparation prefix and normalization identity. Local, Sarvam and Cloudflare remain distinct at 768 dimensions, and Cloudflare `mean` and `cls` are distinct spaces. Gemini and Vertex dimensions and task formats are distinct spaces, including 768-dimensional MRL output; Vertex is never relabeled as the Developer API or vice versa, because the provider, prompt format and normalization provenance differ. Direct OpenAI, the declared gateway alias and the declared OpenRouter alias share the OpenAI descriptor only when the effective text, preparation and normalization remain identical. API keys, service URLs, account IDs and gateway IDs are route metadata, not implicit new spaces. The ordinary embed result carries these descriptors for actual successful work; no separate metadata call is required.
|
|
81
129
|
|
|
82
130
|
Existing stored vector documents are preserved. Package outcome descriptors allow callers to compare complete identity before persistence; a successful inference from an incompatible space is still reported truthfully.
|
|
83
131
|
|
|
84
132
|
## Limits
|
|
85
133
|
|
|
86
|
-
No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam and
|
|
134
|
+
No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam, local and Cloudflare publish no aggregate request cap, so none is invented. Gemini publishes an 8192-token input boundary and no aggregate request cap; one exact prompt per request is pre-counted with `countTokens`, and a mismatched embed token count fails closed. Cloudflare documents a 512-token per-input ceiling for `bge-base-en-v1.5`; this package does not ship that model's tokenizer and does not approximate the ceiling locally, so Cloudflare may reject an oversized input. No cost estimator or pricing table is included; unknown provider accounting is reported as null.
|
|
135
|
+
|
|
136
|
+
Official Vertex contracts: [embedContent](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.publishers.models/embedContent), [countTokens](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.publishers.models/countTokens), [multimodal model constraints and task instructions](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings), and [ADC discovery order](https://docs.cloud.google.com/docs/authentication/application-default-credentials).
|
|
87
137
|
|
|
88
|
-
Live cloud or local inference, service deployment and shared database writes are not performed by this package.
|
|
138
|
+
The public result protocol is version 2; stored generating-space documents keep their existing descriptor format. Live cloud or local inference, service deployment and shared database writes are not performed by this package.
|
package/dist/execute.js
CHANGED
|
@@ -14,6 +14,35 @@ const unstarted = (index) => ({
|
|
|
14
14
|
attemptId: null,
|
|
15
15
|
});
|
|
16
16
|
const preparedTokenCount = (input) => input.kind === 'tokens' ? input.tokens.length : (input.tokenCount ?? 0);
|
|
17
|
+
const generationKey = (generation) => `${generation.provider}\u0000${generation.model}\u0000${JSON.stringify(generation.space)}`;
|
|
18
|
+
/**
|
|
19
|
+
* Record the complete set of actual generations. Singular metadata is set only when one generation
|
|
20
|
+
* produced every vector; a mixed fallback never collapses into a guessed route or space.
|
|
21
|
+
*/
|
|
22
|
+
const generationsOf = (outcomes) => {
|
|
23
|
+
const byKey = new Map();
|
|
24
|
+
for (const outcome of outcomes) {
|
|
25
|
+
if (outcome.status !== 'success')
|
|
26
|
+
continue;
|
|
27
|
+
const generation = {
|
|
28
|
+
provider: outcome.route,
|
|
29
|
+
model: outcome.model,
|
|
30
|
+
space: outcome.space,
|
|
31
|
+
};
|
|
32
|
+
byKey.set(generationKey(generation), generation);
|
|
33
|
+
}
|
|
34
|
+
return [...byKey.values()];
|
|
35
|
+
};
|
|
36
|
+
const resultMetadata = (outcomes) => {
|
|
37
|
+
const generations = generationsOf(outcomes);
|
|
38
|
+
const only = generations.length === 1 ? generations[0] : undefined;
|
|
39
|
+
return {
|
|
40
|
+
provider: only?.provider ?? null,
|
|
41
|
+
model: only?.model ?? null,
|
|
42
|
+
space: only?.space ?? null,
|
|
43
|
+
generations,
|
|
44
|
+
};
|
|
45
|
+
};
|
|
17
46
|
/**
|
|
18
47
|
* Runs one ordinary call or one explicit comparison entry. Successful inputs are never replayed on a
|
|
19
48
|
* fallback route; only unfinished inputs continue. Every input keeps its original zero-based index.
|
|
@@ -76,8 +105,26 @@ export async function executeEmbeddings(args) {
|
|
|
76
105
|
outcomes[index] = cancelled(index);
|
|
77
106
|
else {
|
|
78
107
|
const code = codeOf(error);
|
|
79
|
-
|
|
80
|
-
|
|
108
|
+
if (args.allowFallback && isFallbackError(error)) {
|
|
109
|
+
// Preflight HTTP and credential failures follow the same fallback rule as embed failures.
|
|
110
|
+
// The failed index stays pending; successful inputs are never replayed on the next route.
|
|
111
|
+
const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
|
|
112
|
+
attempts.push({
|
|
113
|
+
id: attemptId,
|
|
114
|
+
route: route.provider,
|
|
115
|
+
model: provider.model,
|
|
116
|
+
routeIndex,
|
|
117
|
+
status: 'error',
|
|
118
|
+
usage: null,
|
|
119
|
+
errorCode: code,
|
|
120
|
+
});
|
|
121
|
+
failureByIndex.set(index, { code, attemptId });
|
|
122
|
+
unfinished.push(index);
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
failureByIndex.set(index, { code, attemptId: null });
|
|
126
|
+
outcomes[index] = { status: 'error', index, code, attemptId: null };
|
|
127
|
+
}
|
|
81
128
|
}
|
|
82
129
|
}
|
|
83
130
|
}
|
|
@@ -182,9 +229,11 @@ export async function executeEmbeddings(args) {
|
|
|
182
229
|
attemptId: failureByIndex.get(index)?.attemptId ?? null,
|
|
183
230
|
};
|
|
184
231
|
}
|
|
232
|
+
const allOutcomes = outcomes.map((outcome, index) => outcome ?? unstarted(index));
|
|
185
233
|
return {
|
|
186
234
|
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
187
|
-
|
|
235
|
+
...resultMetadata(allOutcomes),
|
|
236
|
+
outcomes: allOutcomes,
|
|
188
237
|
attempts,
|
|
189
238
|
};
|
|
190
239
|
}
|
|
@@ -199,6 +248,10 @@ export async function executeCompare(args) {
|
|
|
199
248
|
status: 'cancelled',
|
|
200
249
|
result: {
|
|
201
250
|
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
251
|
+
provider: null,
|
|
252
|
+
model: null,
|
|
253
|
+
space: null,
|
|
254
|
+
generations: [],
|
|
202
255
|
outcomes: args.request.inputs.map((_input, offset) => cancelled(offset)),
|
|
203
256
|
attempts: [],
|
|
204
257
|
},
|
package/dist/extension.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { isProjectTrusted } from '@amaster.ai/pi-shared/settings';
|
|
2
2
|
import { defineTool, } from '@earendil-works/pi-coding-agent';
|
|
3
3
|
import { EmbeddingsError } from './errors.js';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { createEmbeddingsRuntimeWithDiagnostics, } from './runtime.js';
|
|
5
|
+
import { configuredDefault, loadEmbeddingSettings } from './settings.js';
|
|
6
6
|
import { updateProjectEmbeddingSettings } from './settings-write.js';
|
|
7
7
|
import { EMBEDDINGS_SETTINGS_KEY, } from './schemas.js';
|
|
8
|
-
import { EMBED_COMPARE_TOOL, EMBED_TOOL,
|
|
8
|
+
import { EMBED_COMPARE_TOOL, EMBED_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, embedCompareOutput, embedCompareParameters, embedOutput, embedParameters, } from './tool-contracts.js';
|
|
9
9
|
const summary = (result) => {
|
|
10
10
|
const successes = result.outcomes.filter((outcome) => outcome.status === 'success');
|
|
11
11
|
const routes = [...new Set(successes.map((outcome) => `${outcome.route}:${outcome.model}`))].join(', ');
|
|
@@ -21,7 +21,7 @@ export default function piEmbeddingsExtension(pi) {
|
|
|
21
21
|
await runtime?.close();
|
|
22
22
|
settings = next;
|
|
23
23
|
cwd = nextCwd;
|
|
24
|
-
runtime =
|
|
24
|
+
runtime = createEmbeddingsRuntimeWithDiagnostics({ settings: next, cwd: nextCwd });
|
|
25
25
|
};
|
|
26
26
|
const currentRuntime = (ctx) => {
|
|
27
27
|
if (runtime === undefined || cwd !== ctx.cwd)
|
|
@@ -43,7 +43,7 @@ export default function piEmbeddingsExtension(pi) {
|
|
|
43
43
|
promptGuidelines: [
|
|
44
44
|
'Provider, model, credentials and caller storage policy are fixed by trusted settings and cannot be overridden through this tool.',
|
|
45
45
|
'Use embed_compare only when the user explicitly asks to compare configured embedding routes.',
|
|
46
|
-
'
|
|
46
|
+
'The embed result reports the actual generating provider, model and space, including mixed fallback generations.',
|
|
47
47
|
],
|
|
48
48
|
parameters: embedParameters,
|
|
49
49
|
outputSchema: embedOutput,
|
|
@@ -90,45 +90,14 @@ export default function piEmbeddingsExtension(pi) {
|
|
|
90
90
|
}
|
|
91
91
|
},
|
|
92
92
|
}));
|
|
93
|
-
pi.registerTool(defineTool({
|
|
94
|
-
name: EMBEDDINGS_DESCRIBE_TOOL,
|
|
95
|
-
label: 'Describe embeddings',
|
|
96
|
-
description: EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
|
|
97
|
-
promptSnippet: 'Report the configured embedding route, complete generating space and redacted readiness diagnostics without inference.',
|
|
98
|
-
promptGuidelines: [
|
|
99
|
-
'Describe is information, not a reservation or a storage-compatibility decision.',
|
|
100
|
-
'Do not treat ready as proof that an inference call succeeded or that a caller can persist the returned vectors.',
|
|
101
|
-
],
|
|
102
|
-
parameters: embeddingsDescribeParameters,
|
|
103
|
-
outputSchema: embeddingsDescribeOutput,
|
|
104
|
-
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
105
|
-
async execute(_id, _params, _signal, _onUpdate, ctx) {
|
|
106
|
-
try {
|
|
107
|
-
const described = currentRuntime(ctx).describe();
|
|
108
|
-
return {
|
|
109
|
-
content: [
|
|
110
|
-
{
|
|
111
|
-
type: 'text',
|
|
112
|
-
text: `${described.selected.provider}/${described.selected.model}; ready: ${described.ready}.`,
|
|
113
|
-
},
|
|
114
|
-
],
|
|
115
|
-
details: described,
|
|
116
|
-
structuredContent: described,
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
catch (error) {
|
|
120
|
-
throw new Error(codeOf(error));
|
|
121
|
-
}
|
|
122
|
-
},
|
|
123
|
-
}));
|
|
124
93
|
pi.registerCommand('embeddings', {
|
|
125
|
-
description: 'Embeddings: /embeddings list | doctor | reload | use <provider> <model> | compare <text>. list
|
|
94
|
+
description: 'Embeddings: /embeddings list | doctor | reload | use <provider> <model> | compare <text>. list and doctor make no inference calls.',
|
|
126
95
|
handler: async (args, ctx) => {
|
|
127
96
|
const raw = (args ?? '').trim();
|
|
128
97
|
const parts = raw.split(/\s+/).filter(Boolean);
|
|
129
98
|
const command = parts[0] ?? 'list';
|
|
130
99
|
try {
|
|
131
|
-
if (command === 'list' || command === 'doctor' || command === '
|
|
100
|
+
if (command === 'list' || command === 'doctor' || command === 'status') {
|
|
132
101
|
if (parts.length !== 1)
|
|
133
102
|
throw new EmbeddingsError('configuration-invalid');
|
|
134
103
|
const active = currentRuntime(ctx);
|
|
@@ -161,7 +130,7 @@ export default function piEmbeddingsExtension(pi) {
|
|
|
161
130
|
if (parts.length !== 3)
|
|
162
131
|
throw new EmbeddingsError('configuration-invalid');
|
|
163
132
|
const route = { provider: parts[1], model: parts[2] ?? '' };
|
|
164
|
-
|
|
133
|
+
configuredDefault({ default: route });
|
|
165
134
|
await updateProjectEmbeddingSettings({
|
|
166
135
|
cwd: ctx.cwd,
|
|
167
136
|
projectTrusted: isProjectTrusted(ctx),
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { createEmbeddingsRuntime, type EmbeddingsRuntime } from './runtime.js';
|
|
2
2
|
export { loadEmbeddingSettings, validateEmbeddingSettings, configuredDefault, configuredRoutes, isEmbeddingSettings, } from './settings.js';
|
|
3
3
|
export { EmbeddingsError } from './errors.js';
|
|
4
|
-
export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, EMBEDDING_ERROR_CODES, } from './schemas.js';
|
|
5
|
-
export type { EmbeddingSettings, EmbeddingRoute, EmbeddingRouteId, EmbeddingSpace, EmbeddingRequest, EmbeddingContext, EmbeddingUsage, EmbeddingAttempt, EmbeddingOutcome, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult,
|
|
4
|
+
export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, GEMINI_EMBEDDING_MODELS, VERTEX_EMBEDDING_LOCATIONS, GEMINI_EMBEDDING_MIN_DIMENSIONS, GEMINI_EMBEDDING_MAX_DIMENSIONS, GEMINI_EMBEDDING_TASK_FORMATS, GEMINI_TASK_PREFIXES, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, EMBEDDING_ERROR_CODES, } from './schemas.js';
|
|
5
|
+
export type { EmbeddingSettings, EmbeddingRoute, EmbeddingRouteId, EmbeddingSpace, EmbeddingRequest, EmbeddingContext, EmbeddingUsage, EmbeddingAttempt, EmbeddingOutcome, EmbeddingGeneration, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult, EmbeddingErrorCode, GeminiEmbeddingDimension, GeminiEmbeddingTaskFormat, } from './schemas.js';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { createEmbeddingsRuntime } from './runtime.js';
|
|
2
2
|
export { loadEmbeddingSettings, validateEmbeddingSettings, configuredDefault, configuredRoutes, isEmbeddingSettings, } from './settings.js';
|
|
3
3
|
export { EmbeddingsError } from './errors.js';
|
|
4
|
-
export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, EMBEDDING_ERROR_CODES, } from './schemas.js';
|
|
4
|
+
export { EMBEDDINGS_SETTINGS_KEY, EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_FORMAT_VERSION, EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_NORMALIZATION_VERSION, EMBEDDING_CONTEXT_META_KEY, EMBEDDING_ROUTE_IDS, GATEWAY_EMBEDDING_MODELS, GEMINI_EMBEDDING_MODELS, VERTEX_EMBEDDING_LOCATIONS, GEMINI_EMBEDDING_MIN_DIMENSIONS, GEMINI_EMBEDDING_MAX_DIMENSIONS, GEMINI_EMBEDDING_TASK_FORMATS, GEMINI_TASK_PREFIXES, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, EMBEDDING_ERROR_CODES, } from './schemas.js';
|
package/dist/mcp-server.js
CHANGED
|
@@ -6,7 +6,7 @@ import { EmbeddingsError } from './errors.js';
|
|
|
6
6
|
import { createEmbeddingsRuntime } from './runtime.js';
|
|
7
7
|
import { loadEmbeddingSettings } from './settings.js';
|
|
8
8
|
import { EMBEDDING_CONTEXT_META_KEY, embeddingContextSchema, embeddingRequestSchema, } from './schemas.js';
|
|
9
|
-
import { EMBED_COMPARE_TOOL, EMBED_TOOL,
|
|
9
|
+
import { EMBED_COMPARE_TOOL, EMBED_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, embedCompareParameters, embedParameters, } from './tool-contracts.js';
|
|
10
10
|
const require = createRequire(import.meta.url);
|
|
11
11
|
const manifest = require('../package.json');
|
|
12
12
|
const version = typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
|
|
@@ -95,12 +95,6 @@ export async function createEmbeddingsMcpServer(options = {}) {
|
|
|
95
95
|
inputSchema: embedCompareParameters,
|
|
96
96
|
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
|
|
97
97
|
},
|
|
98
|
-
{
|
|
99
|
-
name: EMBEDDINGS_DESCRIBE_TOOL,
|
|
100
|
-
description: EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
|
|
101
|
-
inputSchema: embeddingsDescribeParameters,
|
|
102
|
-
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
103
|
-
},
|
|
104
98
|
],
|
|
105
99
|
}));
|
|
106
100
|
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
@@ -122,13 +116,6 @@ export async function createEmbeddingsMcpServer(options = {}) {
|
|
|
122
116
|
const compared = await runtime.compare(args, { signal: extra.signal, context });
|
|
123
117
|
return jsonResult(compared, `Compared ${compared.entries.length} configured embedding route(s).`);
|
|
124
118
|
}
|
|
125
|
-
case EMBEDDINGS_DESCRIBE_TOOL: {
|
|
126
|
-
const problems = validationProblems(embeddingsDescribeParameters, args);
|
|
127
|
-
if (problems.length > 0)
|
|
128
|
-
return errorResult(`Invalid arguments for ${request.params.name}:\n- ${problems.join('\n- ')}`);
|
|
129
|
-
const described = runtime.describe();
|
|
130
|
-
return jsonResult(described, `Embedding route ${described.selected.provider}/${described.selected.model}; ready: ${described.ready}.`);
|
|
131
|
-
}
|
|
132
119
|
default:
|
|
133
120
|
throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${request.params.name}`);
|
|
134
121
|
}
|
package/dist/providers.d.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace, type GeminiEmbeddingDimension, type GeminiEmbeddingTaskFormat } from './schemas.js';
|
|
2
2
|
import type { EmbeddingsProvider } from './provider-types.js';
|
|
3
3
|
export declare const OPENAI_EMBEDDING_SPACE: EmbeddingSpace;
|
|
4
4
|
export declare const SARVAM_EMBEDDING_SPACE: EmbeddingSpace;
|
|
5
|
+
type CloudflarePooling = 'mean' | 'cls';
|
|
6
|
+
export declare const cloudflareEmbeddingSpace: (pooling: CloudflarePooling) => EmbeddingSpace;
|
|
7
|
+
export declare const geminiEmbeddingSpace: (config: {
|
|
8
|
+
dimensions: GeminiEmbeddingDimension;
|
|
9
|
+
taskFormat: GeminiEmbeddingTaskFormat;
|
|
10
|
+
}) => EmbeddingSpace;
|
|
5
11
|
export declare const routeKey: (route: EmbeddingRoute) => string;
|
|
12
|
+
export type EmbeddingDiagnostic = Readonly<{
|
|
13
|
+
readonly code: string;
|
|
14
|
+
readonly severity: 'error' | 'warning' | 'info';
|
|
15
|
+
}>;
|
|
6
16
|
/** Diagnostics are provider-free and never contain keys, origins or model paths. */
|
|
7
17
|
export declare function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[];
|
|
8
18
|
export type AcquiredProvider = Readonly<{
|
|
@@ -15,4 +25,5 @@ export declare function acquireProvider({ settings, route, signal, }: {
|
|
|
15
25
|
route: EmbeddingRoute;
|
|
16
26
|
signal: AbortSignal;
|
|
17
27
|
}): Promise<AcquiredProvider>;
|
|
18
|
-
export declare const spaceForRoute: (route: EmbeddingRoute) => EmbeddingSpace;
|
|
28
|
+
export declare const spaceForRoute: (route: EmbeddingRoute, settings?: EmbeddingSettings | undefined) => EmbeddingSpace;
|
|
29
|
+
export {};
|