@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-embeddings",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam and gateway routes, ordered fallback and explicit comparisons.",
5
5
  "keywords": [
6
6
  "pi-package",
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.
@@ -207,9 +240,11 @@ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingRes
207
240
  attemptId: failureByIndex.get(index)?.attemptId ?? null,
208
241
  };
209
242
  }
243
+ const allOutcomes = outcomes.map((outcome, index) => outcome ?? unstarted(index));
210
244
  return {
211
245
  schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
212
- outcomes: outcomes.map((outcome, index) => outcome ?? unstarted(index)),
246
+ ...resultMetadata(allOutcomes),
247
+ outcomes: allOutcomes,
213
248
  attempts,
214
249
  };
215
250
  }
@@ -231,6 +266,10 @@ export async function executeCompare(args: {
231
266
  status: 'cancelled',
232
267
  result: {
233
268
  schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
269
+ provider: null,
270
+ model: null,
271
+ space: null,
272
+ generations: [],
234
273
  outcomes: args.request.inputs.map((_input, offset) => cancelled(offset)),
235
274
  attempts: [],
236
275
  },
package/src/extension.ts CHANGED
@@ -5,7 +5,10 @@ import {
5
5
  type ExtensionContext,
6
6
  } from '@earendil-works/pi-coding-agent';
7
7
  import { EmbeddingsError } from './errors.js';
8
- import { createEmbeddingsRuntime, type EmbeddingsRuntime } from './runtime.js';
8
+ import {
9
+ createEmbeddingsRuntimeWithDiagnostics,
10
+ type EmbeddingsRuntimeWithDiagnostics,
11
+ } from './runtime.js';
9
12
  import { loadEmbeddingSettings, validateEmbeddingSettings } from './settings.js';
10
13
  import { updateProjectEmbeddingSettings } from './settings-write.js';
11
14
  import {
@@ -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: EmbeddingsRuntime | undefined;
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 = createEmbeddingsRuntime({ settings: next, cwd: nextCwd });
53
+ runtime = createEmbeddingsRuntimeWithDiagnostics({ settings: next, cwd: nextCwd });
55
54
  };
56
55
 
57
- const currentRuntime = (ctx: ExtensionContext): EmbeddingsRuntime => {
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
- 'Describe reports configuration and readiness; it does not reserve a generating space or prove a caller can store the result.',
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, doctor and describe make no inference calls.',
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 === 'describe' || command === 'status') {
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();
package/src/index.ts CHANGED
@@ -28,10 +28,9 @@ export type {
28
28
  EmbeddingUsage,
29
29
  EmbeddingAttempt,
30
30
  EmbeddingOutcome,
31
+ EmbeddingGeneration,
31
32
  EmbeddingResult,
32
33
  EmbeddingCompareEntry,
33
34
  EmbeddingCompareResult,
34
- EmbeddingDiagnostic,
35
- EmbeddingDescribe,
36
35
  EmbeddingErrorCode,
37
36
  } 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
  }
package/src/providers.ts CHANGED
@@ -4,8 +4,9 @@ import {
4
4
  EMBEDDING_DOCUMENT_PREFIX,
5
5
  EMBEDDING_FORMAT_VERSION,
6
6
  EMBEDDING_NORMALIZATION_VERSION,
7
+ CLOUDFLARE_EMBEDDING_MODELS,
8
+ OPENROUTER_EMBEDDING_MODELS,
7
9
  type EmbeddingContext,
8
- type EmbeddingDiagnostic,
9
10
  type EmbeddingRoute,
10
11
  type EmbeddingSettings,
11
12
  type EmbeddingSpace,
@@ -13,7 +14,7 @@ import {
13
14
  import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
14
15
  import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE, type AcquiredLocalRuntime } from './local-runtime.js';
15
16
  import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
16
- import { parseBatchResponse } from './response.js';
17
+ import { parseBatchResponse, parseCloudflareBatchResponse } from './response.js';
17
18
 
18
19
  export const OPENAI_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
19
20
  provider: 'openai',
@@ -39,9 +40,27 @@ export const SARVAM_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
39
40
  normalization: EMBEDDING_NORMALIZATION_VERSION,
40
41
  });
41
42
 
43
+ type CloudflarePooling = 'mean' | 'cls';
44
+
45
+ export const cloudflareEmbeddingSpace = (pooling: CloudflarePooling): EmbeddingSpace =>
46
+ Object.freeze({
47
+ provider: 'cloudflare',
48
+ model: CLOUDFLARE_EMBEDDING_MODELS[0],
49
+ revision: null,
50
+ quantization: null,
51
+ runtime: 'cloudflare-workers-ai',
52
+ dimensions: 768,
53
+ pooling,
54
+ format: EMBEDDING_FORMAT_VERSION,
55
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
56
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
57
+ });
58
+
42
59
  const OPENAI_MODEL = 'text-embedding-3-small';
43
60
  const SARVAM_MODEL = 'embeddinggemma-2';
44
61
  const SARVAM_ORIGIN = 'https://api.sarvam.ai';
62
+ const OPENROUTER_EMBEDDINGS_URL = 'https://openrouter.ai/api/v1/embeddings';
63
+ const CLOUDFLARE_ORIGIN = 'https://api.cloudflare.com/client/v4/accounts';
45
64
 
46
65
  const OPENAI_MAX_INPUT_TOKENS = 8192;
47
66
  const OPENAI_MAX_REQUEST_INPUTS = 2048;
@@ -54,6 +73,11 @@ const trim = (value: string | undefined): string | undefined => {
54
73
 
55
74
  export const routeKey = (route: EmbeddingRoute): string => `${route.provider}\u0000${route.model}`;
56
75
 
76
+ export type EmbeddingDiagnostic = Readonly<{
77
+ readonly code: string;
78
+ readonly severity: 'error' | 'warning' | 'info';
79
+ }>;
80
+
57
81
  /** Diagnostics are provider-free and never contain keys, origins or model paths. */
58
82
  export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[] {
59
83
  const diagnostics: EmbeddingDiagnostic[] = [];
@@ -83,6 +107,20 @@ export function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRo
83
107
  add('gateway-key-unconfigured');
84
108
  break;
85
109
  }
110
+ case 'openrouter':
111
+ if (trim(settings.providers?.openrouter?.apiKey) === undefined && trim(process.env.OPENROUTER_API_KEY) === undefined)
112
+ add('openrouter-key-unconfigured');
113
+ break;
114
+ case 'cloudflare': {
115
+ const cloudflare = settings.providers?.cloudflare;
116
+ if (trim(cloudflare?.accountId) === undefined && trim(process.env.CLOUDFLARE_ACCOUNT_ID) === undefined)
117
+ add('cloudflare-account-unconfigured');
118
+ if (trim(cloudflare?.apiKey) === undefined && trim(process.env.CLOUDFLARE_API_TOKEN) === undefined)
119
+ add('cloudflare-key-unconfigured');
120
+ if (trim(cloudflare?.gatewayId) === undefined && trim(process.env.CLOUDFLARE_AI_GATEWAY_ID) === undefined)
121
+ add('cloudflare-gateway-unconfigured');
122
+ break;
123
+ }
86
124
  }
87
125
  return diagnostics;
88
126
  }
@@ -93,6 +131,12 @@ const credential = (configured: string | undefined, env: string | undefined): st
93
131
  return value;
94
132
  };
95
133
 
134
+ const headerCredential = (configured: string | undefined, env: string | undefined): string => {
135
+ const value = credential(configured, env);
136
+ if (!headerValueIsSafe(value)) throw new EmbeddingsError('configuration-invalid');
137
+ return value;
138
+ };
139
+
96
140
  /** The documented text-string path avoids the token-array schema contradiction without truncating. */
97
141
  const openAIPrepare = (
98
142
  encoding: ReturnType<typeof getEncoding>,
@@ -257,6 +301,109 @@ class GatewayProvider implements EmbeddingsProvider {
257
301
  }
258
302
  }
259
303
 
304
+ class OpenRouterProvider implements EmbeddingsProvider {
305
+ readonly route = 'openrouter' as const;
306
+ readonly model = OPENROUTER_EMBEDDING_MODELS[0];
307
+ readonly space: EmbeddingSpace = OPENAI_EMBEDDING_SPACE;
308
+ readonly maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
309
+ readonly maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
310
+ readonly #encoding = getEncoding('cl100k_base');
311
+ readonly #key: string;
312
+
313
+ constructor(key: string) {
314
+ this.#key = key;
315
+ }
316
+
317
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
318
+ return openAIPrepare(this.#encoding, text, signal);
319
+ }
320
+
321
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
322
+ const response = await requestJson({
323
+ url: new URL(OPENROUTER_EMBEDDINGS_URL),
324
+ signal,
325
+ headers: { authorization: `Bearer ${this.#key}` },
326
+ body: {
327
+ model: this.model,
328
+ dimensions: this.space.dimensions,
329
+ input: providerTexts(inputs),
330
+ encoding_format: 'float',
331
+ },
332
+ });
333
+ const count = preparedTokens(inputs);
334
+ return parseBatchResponse({
335
+ response,
336
+ space: this.space,
337
+ expectedModels: [this.model],
338
+ expectedPreparedTokens: count,
339
+ preparedInputTokens: count,
340
+ });
341
+ }
342
+
343
+ async close(): Promise<void> {
344
+ // js-tiktoken is pure JavaScript and owns no process or handle.
345
+ }
346
+ }
347
+
348
+ class CloudflareProvider implements EmbeddingsProvider {
349
+ readonly route = 'cloudflare' as const;
350
+ readonly model = CLOUDFLARE_EMBEDDING_MODELS[0];
351
+ readonly space: EmbeddingSpace;
352
+ // Workers AI documents a 512-token input ceiling for this model but no aggregate request cap.
353
+ // The model-owned tokenizer is not available here, so no approximate local cap is invented.
354
+ readonly maxRequestInputs = Number.POSITIVE_INFINITY;
355
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
356
+ readonly #url: URL;
357
+ readonly #key: string;
358
+ readonly #gatewayId: string;
359
+ readonly #pooling: CloudflarePooling;
360
+
361
+ constructor(config: {
362
+ accountId: string;
363
+ apiKey: string;
364
+ gatewayId: string;
365
+ model: typeof CLOUDFLARE_EMBEDDING_MODELS[number];
366
+ pooling: CloudflarePooling;
367
+ }) {
368
+ this.#url = new URL(
369
+ `${CLOUDFLARE_ORIGIN}/${encodeURIComponent(config.accountId)}/ai/run/${config.model}`
370
+ );
371
+ this.#key = config.apiKey;
372
+ this.#gatewayId = config.gatewayId;
373
+ this.#pooling = config.pooling;
374
+ this.space = cloudflareEmbeddingSpace(config.pooling);
375
+ // The model is pinned from settings; this guard keeps the fixed URL invariant explicit.
376
+ if (config.model !== CLOUDFLARE_EMBEDDING_MODELS[0])
377
+ throw new EmbeddingsError('configuration-invalid');
378
+ }
379
+
380
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
381
+ signal.throwIfAborted();
382
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
383
+ }
384
+
385
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
386
+ const response = await requestJson({
387
+ url: this.#url,
388
+ signal,
389
+ headers: {
390
+ authorization: `Bearer ${this.#key}`,
391
+ 'cf-aig-gateway-id': this.#gatewayId,
392
+ },
393
+ body: { text: providerTexts(inputs), pooling: this.#pooling },
394
+ });
395
+ return parseCloudflareBatchResponse({
396
+ response,
397
+ space: this.space,
398
+ expectedCount: inputs.length,
399
+ });
400
+ }
401
+
402
+ async close(): Promise<void> {
403
+ // Native fetch owns no long-lived resource.
404
+ }
405
+ }
406
+
260
407
  export type AcquiredProvider = Readonly<{
261
408
  readonly provider: EmbeddingsProvider;
262
409
  readonly release: () => Promise<void>;
@@ -319,17 +466,52 @@ export async function acquireProvider({
319
466
  release: noRelease,
320
467
  };
321
468
  }
469
+ case 'openrouter':
470
+ return {
471
+ provider: new OpenRouterProvider(
472
+ headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)
473
+ ),
474
+ release: noRelease,
475
+ };
476
+ case 'cloudflare': {
477
+ const configured = settings.providers?.cloudflare;
478
+ const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
479
+ const gatewayId = trim(configured?.gatewayId) ?? trim(process.env.CLOUDFLARE_AI_GATEWAY_ID);
480
+ if (accountId === undefined || gatewayId === undefined)
481
+ throw new EmbeddingsError('configuration-invalid');
482
+ if (!headerValueIsSafe(accountId) || !headerValueIsSafe(gatewayId))
483
+ throw new EmbeddingsError('configuration-invalid');
484
+ const model = trim(configured?.model) ?? CLOUDFLARE_EMBEDDING_MODELS[0];
485
+ if (model !== CLOUDFLARE_EMBEDDING_MODELS[0]) throw new EmbeddingsError('configuration-invalid');
486
+ const pooling: CloudflarePooling = configured?.pooling ?? 'mean';
487
+ return {
488
+ provider: new CloudflareProvider({
489
+ accountId,
490
+ apiKey: headerCredential(configured?.apiKey, process.env.CLOUDFLARE_API_TOKEN),
491
+ gatewayId,
492
+ model,
493
+ pooling,
494
+ }),
495
+ release: noRelease,
496
+ };
497
+ }
322
498
  }
323
499
  }
324
500
 
325
- export const spaceForRoute = (route: EmbeddingRoute): EmbeddingSpace => {
501
+ export const spaceForRoute = (
502
+ route: EmbeddingRoute,
503
+ settings?: EmbeddingSettings | undefined
504
+ ): EmbeddingSpace => {
326
505
  switch (route.provider) {
327
506
  case 'local':
328
507
  return LOCAL_EMBEDDING_SPACE;
329
508
  case 'openai':
330
509
  case 'gateway':
510
+ case 'openrouter':
331
511
  return OPENAI_EMBEDDING_SPACE;
332
512
  case 'sarvam':
333
513
  return SARVAM_EMBEDDING_SPACE;
514
+ case 'cloudflare':
515
+ return cloudflareEmbeddingSpace(settings?.providers?.cloudflare?.pooling ?? 'mean');
334
516
  }
335
517
  };
package/src/response.ts CHANGED
@@ -17,6 +17,25 @@ const responseSchema = Type.Object({
17
17
  }),
18
18
  });
19
19
 
20
+ const cloudflareResponseSchema = Type.Object({
21
+ shape: Type.Optional(Type.Array(Type.Integer({ minimum: 0 }))),
22
+ data: Type.Array(Type.Array(Type.Number())),
23
+ pooling: Type.Optional(Type.Union([Type.Literal('mean'), Type.Literal('cls')])),
24
+ });
25
+
26
+ /** Cloudflare REST wraps model output in a standard API envelope; bindings return the raw model output. */
27
+ function unwrapCloudflareModelOutput(response: unknown): unknown {
28
+ if (typeof response !== 'object' || response === null || Array.isArray(response))
29
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
30
+ const envelope = response as Record<string, unknown>;
31
+ if (
32
+ envelope.success === false ||
33
+ (Array.isArray(envelope.errors) && envelope.errors.length > 0)
34
+ )
35
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
36
+ return Object.hasOwn(envelope, 'result') ? envelope.result : envelope;
37
+ }
38
+
20
39
  /** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
21
40
  export function normalizeVector(vector: readonly number[], dimensions: number): number[] {
22
41
  if (vector.length !== dimensions || vector.some((value) => !Number.isFinite(value)))
@@ -72,3 +91,35 @@ export function parseBatchResponse(args: {
72
91
  },
73
92
  };
74
93
  }
94
+
95
+ /** Cloudflare Workers AI `/ai/run` wraps ordered vectors without usage in the REST API envelope. */
96
+ export function parseCloudflareBatchResponse(args: {
97
+ response: unknown;
98
+ space: EmbeddingSpace;
99
+ expectedCount: number;
100
+ }): ProviderBatchResult {
101
+ const output = unwrapCloudflareModelOutput(args.response);
102
+ if (!Value.Check(cloudflareResponseSchema, output))
103
+ throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
104
+ const parsed = output;
105
+ if (parsed.data.length !== args.expectedCount)
106
+ throw new EmbeddingsError('provider-response-mismatch', { knownUsage: {} });
107
+ let vectors: number[][];
108
+ try {
109
+ vectors = parsed.data.map((vector) => normalizeVector(vector, args.space.dimensions));
110
+ } catch (error) {
111
+ if (error instanceof EmbeddingsError)
112
+ throw new EmbeddingsError(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid', {
113
+ knownUsage: {},
114
+ });
115
+ throw error;
116
+ }
117
+ return {
118
+ vectors,
119
+ usage: {
120
+ providerReportedInputTokens: null,
121
+ preparedInputTokens: null,
122
+ billedTokens: null,
123
+ },
124
+ };
125
+ }
package/src/runtime.ts CHANGED
@@ -1,4 +1,11 @@
1
- import { acquireProvider, routeDiagnostics, routeKey, spaceForRoute, type AcquiredProvider } from './providers.js';
1
+ import {
2
+ acquireProvider,
3
+ routeDiagnostics,
4
+ routeKey,
5
+ spaceForRoute,
6
+ type AcquiredProvider,
7
+ type EmbeddingDiagnostic,
8
+ } from './providers.js';
2
9
  import { configuredDefault, configuredRoutes, validateEmbeddingSettings } from './settings.js';
3
10
  import { executeCompare, executeEmbeddings } from './execute.js';
4
11
  import { EmbeddingsError } from './errors.js';
@@ -6,7 +13,6 @@ import {
6
13
  EMBEDDINGS_PROTOCOL_VERSION,
7
14
  type EmbeddingCompareResult,
8
15
  type EmbeddingContext,
9
- type EmbeddingDescribe,
10
16
  type EmbeddingRequest,
11
17
  type EmbeddingResult,
12
18
  type EmbeddingRoute,
@@ -24,16 +30,31 @@ export interface EmbeddingsRuntime {
24
30
  request: EmbeddingRequest,
25
31
  options?: { signal?: AbortSignal | undefined; context?: EmbeddingContext | undefined }
26
32
  ): Promise<EmbeddingCompareResult>;
27
- describe(): EmbeddingDescribe;
28
33
  close(): Promise<void>;
29
34
  }
30
35
 
36
+ /** Internal diagnostics for Pi commands and host startup; never registered as a tool. */
37
+ export interface RuntimeDiagnostics {
38
+ readonly schemaVersion: typeof EMBEDDINGS_PROTOCOL_VERSION;
39
+ readonly ready: boolean;
40
+ readonly selected: EmbeddingRoute;
41
+ readonly space: ReturnType<typeof spaceForRoute> | null;
42
+ readonly default: EmbeddingRoute;
43
+ readonly fallback: readonly EmbeddingRoute[];
44
+ readonly compare: readonly EmbeddingRoute[];
45
+ readonly diagnostics: readonly EmbeddingDiagnostic[];
46
+ }
47
+
48
+ export interface EmbeddingsRuntimeWithDiagnostics extends EmbeddingsRuntime {
49
+ describe(): RuntimeDiagnostics;
50
+ }
51
+
31
52
  const noSignal = (signal: AbortSignal | undefined): AbortSignal => signal ?? new AbortController().signal;
32
53
 
33
- export function createEmbeddingsRuntime(args: {
54
+ function createRuntime(args: {
34
55
  settings: EmbeddingSettings;
35
56
  cwd?: string | undefined;
36
- }): EmbeddingsRuntime {
57
+ }): EmbeddingsRuntimeWithDiagnostics {
37
58
  const settings = validateEmbeddingSettings(args.settings);
38
59
  const defaultRoute = configuredDefault(settings);
39
60
  const fallbackRoutes = configuredRoutes(settings, 'fallback');
@@ -121,7 +142,7 @@ export function createEmbeddingsRuntime(args: {
121
142
  schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
122
143
  ready: defaultDiagnostics.length === 0,
123
144
  selected: defaultRoute,
124
- space: spaceForRoute(defaultRoute),
145
+ space: spaceForRoute(defaultRoute, settings),
125
146
  default: defaultRoute,
126
147
  fallback: [...fallbackRoutes],
127
148
  compare: [...compareRoutes],
@@ -144,3 +165,20 @@ export function createEmbeddingsRuntime(args: {
144
165
  },
145
166
  };
146
167
  }
168
+
169
+ /** Public factory: callers cannot obtain describe metadata from the runtime API. */
170
+ export function createEmbeddingsRuntime(args: {
171
+ settings: EmbeddingSettings;
172
+ cwd?: string | undefined;
173
+ }): EmbeddingsRuntime {
174
+ const { start, embed, compare, close } = createRuntime(args);
175
+ return { start, embed, compare, close };
176
+ }
177
+
178
+ /** Package-internal factory for Pi command output and provider-free host startup checks. */
179
+ export function createEmbeddingsRuntimeWithDiagnostics(args: {
180
+ settings: EmbeddingSettings;
181
+ cwd?: string | undefined;
182
+ }): EmbeddingsRuntimeWithDiagnostics {
183
+ return createRuntime(args);
184
+ }