@abhishek944/pi-embeddings 0.1.0 → 0.2.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 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 describe output.
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`, `embed_compare` and `embeddings_describe`. Vectors 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>`.
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. `describe` is provider-free information, not a reservation or a caller storage policy.
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,13 +46,21 @@ 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"
49
57
  }
50
58
  }
51
59
  }
52
60
  }
53
61
  ```
54
62
 
55
- Provider IDs are route identifiers: `local`, `openai`, `sarvam` and `gateway`. 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.
63
+ Provider IDs are route identifiers: `local`, `openai`, `sarvam`, `gateway`, `openrouter` and `cloudflare`. 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` and `CLOUDFLARE_AI_GATEWAY_ID` in the trusted host environment.
56
64
 
57
65
  Ordinary calls use the configured default, then configured fallback in order, advancing only for typed missing credentials or HTTP 401/404/429. There is no fallback for 403, refusal, 400/422, invalid input or vector, malformed response, 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
66
 
@@ -62,6 +70,8 @@ Ordinary calls use the configured default, then configured fallback in order, ad
62
70
  - `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
71
  - `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
72
  - `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.
73
+ - `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.
74
+ - `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.
65
75
 
66
76
  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
77
 
@@ -77,12 +87,12 @@ This is attribution only. The authenticated server-to-server boundary supplies c
77
87
 
78
88
  ## Generating spaces
79
89
 
80
- Descriptors record canonical provider, model, known revision or explicit null, quantization/runtime/pooling provenance, dimensions, preparation prefix and normalization identity. Local and Sarvam remain distinct at 768 dimensions. Direct OpenAI and the declared gateway alias share the OpenAI descriptor only when the effective text, preparation and normalization remain identical. API keys, service URLs and gateway aliases are route metadata, not implicit new spaces.
90
+ 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. 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
91
 
82
92
  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
93
 
84
94
  ## Limits
85
95
 
86
- No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam and local publish no aggregate request cap, so none is invented. No cost estimator or pricing table is included; unknown provider accounting is reported as null.
96
+ 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. 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.
87
97
 
88
- Live cloud or local inference, service deployment and shared database writes are not performed by this package.
98
+ 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.
@@ -182,9 +211,11 @@ export async function executeEmbeddings(args) {
182
211
  attemptId: failureByIndex.get(index)?.attemptId ?? null,
183
212
  };
184
213
  }
214
+ const allOutcomes = outcomes.map((outcome, index) => outcome ?? unstarted(index));
185
215
  return {
186
216
  schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
187
- outcomes: outcomes.map((outcome, index) => outcome ?? unstarted(index)),
217
+ ...resultMetadata(allOutcomes),
218
+ outcomes: allOutcomes,
188
219
  attempts,
189
220
  };
190
221
  }
@@ -199,6 +230,10 @@ export async function executeCompare(args) {
199
230
  status: 'cancelled',
200
231
  result: {
201
232
  schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
233
+ provider: null,
234
+ model: null,
235
+ space: null,
236
+ generations: [],
202
237
  outcomes: args.request.inputs.map((_input, offset) => cancelled(offset)),
203
238
  attempts: [],
204
239
  },
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 { createEmbeddingsRuntime } from './runtime.js';
4
+ import { createEmbeddingsRuntimeWithDiagnostics, } from './runtime.js';
5
5
  import { loadEmbeddingSettings, validateEmbeddingSettings } 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, EMBEDDINGS_DESCRIBE_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION, embedCompareOutput, embedCompareParameters, embedOutput, embedParameters, embeddingsDescribeOutput, embeddingsDescribeParameters, } from './tool-contracts.js';
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 = createEmbeddingsRuntime({ settings: next, cwd: nextCwd });
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
- 'Describe reports configuration and readiness; it does not reserve a generating space or prove a caller can store the result.',
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, doctor and describe make no inference calls.',
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 === 'describe' || command === 'status') {
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);
package/dist/index.d.ts CHANGED
@@ -2,4 +2,4 @@ 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
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, EmbeddingDiagnostic, EmbeddingDescribe, EmbeddingErrorCode, } from './schemas.js';
5
+ export type { EmbeddingSettings, EmbeddingRoute, EmbeddingRouteId, EmbeddingSpace, EmbeddingRequest, EmbeddingContext, EmbeddingUsage, EmbeddingAttempt, EmbeddingOutcome, EmbeddingGeneration, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult, EmbeddingErrorCode, } from './schemas.js';
@@ -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, EMBEDDINGS_DESCRIBE_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION, embedCompareParameters, embedParameters, embeddingsDescribeParameters, } from './tool-contracts.js';
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
  }
@@ -1,8 +1,14 @@
1
- import { type EmbeddingDiagnostic, type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace } from './schemas.js';
1
+ import { type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace } 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;
5
7
  export declare const routeKey: (route: EmbeddingRoute) => string;
8
+ export type EmbeddingDiagnostic = Readonly<{
9
+ readonly code: string;
10
+ readonly severity: 'error' | 'warning' | 'info';
11
+ }>;
6
12
  /** Diagnostics are provider-free and never contain keys, origins or model paths. */
7
13
  export declare function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[];
8
14
  export type AcquiredProvider = Readonly<{
@@ -15,4 +21,5 @@ export declare function acquireProvider({ settings, route, signal, }: {
15
21
  route: EmbeddingRoute;
16
22
  signal: AbortSignal;
17
23
  }): Promise<AcquiredProvider>;
18
- export declare const spaceForRoute: (route: EmbeddingRoute) => EmbeddingSpace;
24
+ export declare const spaceForRoute: (route: EmbeddingRoute, settings?: EmbeddingSettings | undefined) => EmbeddingSpace;
25
+ export {};
package/dist/providers.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { getEncoding } from 'js-tiktoken';
2
2
  import { EmbeddingsError } from './errors.js';
3
- import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, } from './schemas.js';
3
+ import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, CLOUDFLARE_EMBEDDING_MODELS, OPENROUTER_EMBEDDING_MODELS, } from './schemas.js';
4
4
  import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
5
5
  import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE } from './local-runtime.js';
6
- import { parseBatchResponse } from './response.js';
6
+ import { parseBatchResponse, parseCloudflareBatchResponse } from './response.js';
7
7
  export const OPENAI_EMBEDDING_SPACE = Object.freeze({
8
8
  provider: 'openai',
9
9
  model: 'text-embedding-3-small',
@@ -26,9 +26,23 @@ export const SARVAM_EMBEDDING_SPACE = Object.freeze({
26
26
  prefix: EMBEDDING_DOCUMENT_PREFIX,
27
27
  normalization: EMBEDDING_NORMALIZATION_VERSION,
28
28
  });
29
+ export const cloudflareEmbeddingSpace = (pooling) => Object.freeze({
30
+ provider: 'cloudflare',
31
+ model: CLOUDFLARE_EMBEDDING_MODELS[0],
32
+ revision: null,
33
+ quantization: null,
34
+ runtime: 'cloudflare-workers-ai',
35
+ dimensions: 768,
36
+ pooling,
37
+ format: EMBEDDING_FORMAT_VERSION,
38
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
39
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
40
+ });
29
41
  const OPENAI_MODEL = 'text-embedding-3-small';
30
42
  const SARVAM_MODEL = 'embeddinggemma-2';
31
43
  const SARVAM_ORIGIN = 'https://api.sarvam.ai';
44
+ const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
45
+ const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
32
46
  const OPENAI_MAX_INPUT_TOKENS = 8192;
33
47
  const OPENAI_MAX_REQUEST_INPUTS = 2048;
34
48
  const OPENAI_MAX_REQUEST_TOKENS = 300000;
@@ -66,6 +80,20 @@ export function routeDiagnostics(settings, route) {
66
80
  add('gateway-key-unconfigured');
67
81
  break;
68
82
  }
83
+ case 'openrouter':
84
+ if (trim(settings.providers?.openrouter?.apiKey) === undefined && trim(process.env.OPENROUTER_API_KEY) === undefined)
85
+ add('openrouter-key-unconfigured');
86
+ break;
87
+ case 'cloudflare': {
88
+ const cloudflare = settings.providers?.cloudflare;
89
+ if (trim(cloudflare?.accountId) === undefined && trim(process.env.CLOUDFLARE_ACCOUNT_ID) === undefined)
90
+ add('cloudflare-account-unconfigured');
91
+ if (trim(cloudflare?.apiKey) === undefined && trim(process.env.CLOUDFLARE_API_TOKEN) === undefined)
92
+ add('cloudflare-key-unconfigured');
93
+ if (trim(cloudflare?.gatewayId) === undefined && trim(process.env.CLOUDFLARE_AI_GATEWAY_ID) === undefined)
94
+ add('cloudflare-gateway-unconfigured');
95
+ break;
96
+ }
69
97
  }
70
98
  return diagnostics;
71
99
  }
@@ -75,6 +103,12 @@ const credential = (configured, env) => {
75
103
  throw new EmbeddingsError('missing-credentials');
76
104
  return value;
77
105
  };
106
+ const headerCredential = (configured, env) => {
107
+ const value = credential(configured, env);
108
+ if (!headerValueIsSafe(value))
109
+ throw new EmbeddingsError('configuration-invalid');
110
+ return value;
111
+ };
78
112
  /** The documented text-string path avoids the token-array schema contradiction without truncating. */
79
113
  const openAIPrepare = (encoding, text, signal) => {
80
114
  signal.throwIfAborted();
@@ -210,6 +244,91 @@ class GatewayProvider {
210
244
  // js-tiktoken is pure JavaScript and owns no process or handle.
211
245
  }
212
246
  }
247
+ class OpenRouterProvider {
248
+ route = 'openrouter';
249
+ model = OPENROUTER_EMBEDDING_MODELS[0];
250
+ space = OPENAI_EMBEDDING_SPACE;
251
+ maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
252
+ maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
253
+ #encoding = getEncoding('cl100k_base');
254
+ #key;
255
+ constructor(key) {
256
+ this.#key = key;
257
+ }
258
+ async prepare(text, signal) {
259
+ return openAIPrepare(this.#encoding, text, signal);
260
+ }
261
+ async embed(inputs, signal) {
262
+ const response = await requestJson({
263
+ url: new URL(OPENROUTER_EMBEDDINGS_URL),
264
+ signal,
265
+ headers: { authorization: `Bearer ${this.#key}` },
266
+ body: {
267
+ model: this.model,
268
+ dimensions: this.space.dimensions,
269
+ input: providerTexts(inputs),
270
+ encoding_format: 'float',
271
+ },
272
+ });
273
+ const count = preparedTokens(inputs);
274
+ return parseBatchResponse({
275
+ response,
276
+ space: this.space,
277
+ expectedModels: [this.model],
278
+ expectedPreparedTokens: count,
279
+ preparedInputTokens: count,
280
+ });
281
+ }
282
+ async close() {
283
+ // js-tiktoken is pure JavaScript and owns no process or handle.
284
+ }
285
+ }
286
+ class CloudflareProvider {
287
+ route = 'cloudflare';
288
+ model = CLOUDFLARE_EMBEDDING_MODELS[0];
289
+ space;
290
+ // Workers AI documents a 512-token input ceiling for this model but no aggregate request cap.
291
+ // The model-owned tokenizer is not available here, so no approximate local cap is invented.
292
+ maxRequestInputs = Number.POSITIVE_INFINITY;
293
+ maxRequestTokens = Number.POSITIVE_INFINITY;
294
+ #url;
295
+ #key;
296
+ #gatewayId;
297
+ #pooling;
298
+ constructor(config) {
299
+ this.#url = new URL(`${CLOUDFLARE_ORIGIN}/${encodeURIComponent(config.accountId)}/ai/run/${config.model}`);
300
+ this.#key = config.apiKey;
301
+ this.#gatewayId = config.gatewayId;
302
+ this.#pooling = config.pooling;
303
+ this.space = cloudflareEmbeddingSpace(config.pooling);
304
+ // The model is pinned from settings; this guard keeps the fixed URL invariant explicit.
305
+ if (config.model !== CLOUDFLARE_EMBEDDING_MODELS[0])
306
+ throw new EmbeddingsError('configuration-invalid');
307
+ }
308
+ async prepare(text, signal) {
309
+ signal.throwIfAborted();
310
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
311
+ }
312
+ async embed(inputs, signal) {
313
+ const response = await requestJson({
314
+ url: this.#url,
315
+ signal,
316
+ headers: {
317
+ authorization: `Bearer ${this.#key}`,
318
+ 'cf-aig-gateway-id': this.#gatewayId,
319
+ },
320
+ body: { text: providerTexts(inputs), pooling: this.#pooling },
321
+ });
322
+ return parseCloudflareBatchResponse({
323
+ response,
324
+ space: this.space,
325
+ expectedCount: inputs.length,
326
+ });
327
+ }
328
+ async close() {
329
+ // Native fetch owns no long-lived resource.
330
+ }
331
+ }
213
332
  const noRelease = async () => undefined;
214
333
  /** Resolve a configured route only when that route is actually about to be used. */
215
334
  export async function acquireProvider({ settings, route, signal, }) {
@@ -250,16 +369,47 @@ export async function acquireProvider({ settings, route, signal, }) {
250
369
  release: noRelease,
251
370
  };
252
371
  }
372
+ case 'openrouter':
373
+ return {
374
+ provider: new OpenRouterProvider(headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)),
375
+ release: noRelease,
376
+ };
377
+ case 'cloudflare': {
378
+ const configured = settings.providers?.cloudflare;
379
+ const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
380
+ const gatewayId = trim(configured?.gatewayId) ?? trim(process.env.CLOUDFLARE_AI_GATEWAY_ID);
381
+ if (accountId === undefined || gatewayId === undefined)
382
+ throw new EmbeddingsError('configuration-invalid');
383
+ if (!headerValueIsSafe(accountId) || !headerValueIsSafe(gatewayId))
384
+ throw new EmbeddingsError('configuration-invalid');
385
+ const model = trim(configured?.model) ?? CLOUDFLARE_EMBEDDING_MODELS[0];
386
+ if (model !== CLOUDFLARE_EMBEDDING_MODELS[0])
387
+ throw new EmbeddingsError('configuration-invalid');
388
+ const pooling = configured?.pooling ?? 'mean';
389
+ return {
390
+ provider: new CloudflareProvider({
391
+ accountId,
392
+ apiKey: headerCredential(configured?.apiKey, process.env.CLOUDFLARE_API_TOKEN),
393
+ gatewayId,
394
+ model,
395
+ pooling,
396
+ }),
397
+ release: noRelease,
398
+ };
399
+ }
253
400
  }
254
401
  }
255
- export const spaceForRoute = (route) => {
402
+ export const spaceForRoute = (route, settings) => {
256
403
  switch (route.provider) {
257
404
  case 'local':
258
405
  return LOCAL_EMBEDDING_SPACE;
259
406
  case 'openai':
260
407
  case 'gateway':
408
+ case 'openrouter':
261
409
  return OPENAI_EMBEDDING_SPACE;
262
410
  case 'sarvam':
263
411
  return SARVAM_EMBEDDING_SPACE;
412
+ case 'cloudflare':
413
+ return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
264
414
  }
265
415
  };
@@ -9,3 +9,9 @@ export declare function parseBatchResponse(args: {
9
9
  expectedPreparedTokens?: number | null;
10
10
  preparedInputTokens?: number | null;
11
11
  }): ProviderBatchResult;
12
+ /** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
13
+ export declare function parseCloudflareBatchResponse(args: {
14
+ response: unknown;
15
+ space: EmbeddingSpace;
16
+ expectedCount: number;
17
+ }): ProviderBatchResult;
package/dist/response.js CHANGED
@@ -11,6 +11,21 @@ const responseSchema = Type.Object({
11
11
  prompt_tokens: Type.Integer({ minimum: 0 }),
12
12
  }),
13
13
  });
14
+ const cloudflareResponseSchema = Type.Object({
15
+ shape: Type.Optional(Type.Array(Type.Integer({ minimum: 0 }))),
16
+ data: Type.Array(Type.Array(Type.Number())),
17
+ pooling: Type.Optional(Type.Union([Type.Literal('mean'), Type.Literal('cls')])),
18
+ });
19
+ /** Cloudflare REST wraps model output in a standard API envelope; bindings return the raw model output. */
20
+ function unwrapCloudflareModelOutput(response) {
21
+ if (typeof response !== 'object' || response === null || Array.isArray(response))
22
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
23
+ const envelope = response;
24
+ if (envelope.success === false ||
25
+ (Array.isArray(envelope.errors) && envelope.errors.length > 0))
26
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
27
+ return Object.hasOwn(envelope, 'result') ? envelope.result : envelope;
28
+ }
14
29
  /** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
15
30
  export function normalizeVector(vector, dimensions) {
16
31
  if (vector.length !== dimensions || vector.some((value) => !Number.isFinite(value)))
@@ -60,3 +75,31 @@ export function parseBatchResponse(args) {
60
75
  },
61
76
  };
62
77
  }
78
+ /** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
79
+ export function parseCloudflareBatchResponse(args) {
80
+ const output = unwrapCloudflareModelOutput(args.response);
81
+ if (!Value.Check(cloudflareResponseSchema, output))
82
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
83
+ const parsed = output;
84
+ if (parsed.data.length !== args.expectedCount)
85
+ throw new EmbeddingsError('provider-response-mismatch', { knownUsage: {} });
86
+ let vectors;
87
+ try {
88
+ vectors = parsed.data.map((vector) => normalizeVector(vector, args.space.dimensions));
89
+ }
90
+ catch (error) {
91
+ if (error instanceof EmbeddingsError)
92
+ throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
93
+ knownUsage: {},
94
+ });
95
+ throw error;
96
+ }
97
+ return {
98
+ vectors,
99
+ usage: {
100
+ providerReportedInputTokens: null,
101
+ preparedInputTokens: null,
102
+ billedTokens: null,
103
+ },
104
+ };
105
+ }
package/dist/runtime.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { type EmbeddingCompareResult, type EmbeddingContext, type EmbeddingDescribe, type EmbeddingRequest, type EmbeddingResult, type EmbeddingSettings } from './schemas.js';
1
+ import { spaceForRoute, type EmbeddingDiagnostic } from './providers.js';
2
+ import { EMBEDDINGS_PROTOCOL_VERSION, type EmbeddingCompareResult, type EmbeddingContext, type EmbeddingRequest, type EmbeddingResult, type EmbeddingRoute, type EmbeddingSettings } from './schemas.js';
2
3
  export interface EmbeddingsRuntime {
3
4
  /** Acquire the selected local child at MCP startup; cloud selections start no local process. */
4
5
  start(): Promise<void>;
@@ -10,10 +11,29 @@ export interface EmbeddingsRuntime {
10
11
  signal?: AbortSignal | undefined;
11
12
  context?: EmbeddingContext | undefined;
12
13
  }): Promise<EmbeddingCompareResult>;
13
- describe(): EmbeddingDescribe;
14
14
  close(): Promise<void>;
15
15
  }
16
+ /** Internal diagnostics for Pi commands and host startup; never registered as a tool. */
17
+ export interface RuntimeDiagnostics {
18
+ readonly schemaVersion: typeof EMBEDDINGS_PROTOCOL_VERSION;
19
+ readonly ready: boolean;
20
+ readonly selected: EmbeddingRoute;
21
+ readonly space: ReturnType<typeof spaceForRoute> | null;
22
+ readonly default: EmbeddingRoute;
23
+ readonly fallback: readonly EmbeddingRoute[];
24
+ readonly compare: readonly EmbeddingRoute[];
25
+ readonly diagnostics: readonly EmbeddingDiagnostic[];
26
+ }
27
+ export interface EmbeddingsRuntimeWithDiagnostics extends EmbeddingsRuntime {
28
+ describe(): RuntimeDiagnostics;
29
+ }
30
+ /** Public factory: callers cannot obtain describe metadata from the runtime API. */
16
31
  export declare function createEmbeddingsRuntime(args: {
17
32
  settings: EmbeddingSettings;
18
33
  cwd?: string | undefined;
19
34
  }): EmbeddingsRuntime;
35
+ /** Package-internal factory for Pi command output and provider-free host startup checks. */
36
+ export declare function createEmbeddingsRuntimeWithDiagnostics(args: {
37
+ settings: EmbeddingSettings;
38
+ cwd?: string | undefined;
39
+ }): EmbeddingsRuntimeWithDiagnostics;
package/dist/runtime.js CHANGED
@@ -1,10 +1,10 @@
1
- import { acquireProvider, routeDiagnostics, routeKey, spaceForRoute } from './providers.js';
1
+ import { acquireProvider, routeDiagnostics, routeKey, spaceForRoute, } from './providers.js';
2
2
  import { configuredDefault, configuredRoutes, validateEmbeddingSettings } from './settings.js';
3
3
  import { executeCompare, executeEmbeddings } from './execute.js';
4
4
  import { EmbeddingsError } from './errors.js';
5
5
  import { EMBEDDINGS_PROTOCOL_VERSION, } from './schemas.js';
6
6
  const noSignal = (signal) => signal ?? new AbortController().signal;
7
- export function createEmbeddingsRuntime(args) {
7
+ function createRuntime(args) {
8
8
  const settings = validateEmbeddingSettings(args.settings);
9
9
  const defaultRoute = configuredDefault(settings);
10
10
  const fallbackRoutes = configuredRoutes(settings, 'fallback');
@@ -95,7 +95,7 @@ export function createEmbeddingsRuntime(args) {
95
95
  schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
96
96
  ready: defaultDiagnostics.length === 0,
97
97
  selected: defaultRoute,
98
- space: spaceForRoute(defaultRoute),
98
+ space: spaceForRoute(defaultRoute, settings),
99
99
  default: defaultRoute,
100
100
  fallback: [...fallbackRoutes],
101
101
  compare: [...compareRoutes],
@@ -119,3 +119,12 @@ export function createEmbeddingsRuntime(args) {
119
119
  },
120
120
  };
121
121
  }
122
+ /** Public factory: callers cannot obtain describe metadata from the runtime API. */
123
+ export function createEmbeddingsRuntime(args) {
124
+ const { start, embed, compare, close } = createRuntime(args);
125
+ return { start, embed, compare, close };
126
+ }
127
+ /** Package-internal factory for Pi command output and provider-free host startup checks. */
128
+ export function createEmbeddingsRuntimeWithDiagnostics(args) {
129
+ return createRuntime(args);
130
+ }