@abhishek944/pi-embeddings 0.0.0-stage → 0.1.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.
Files changed (51) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +87 -2
  3. package/dist/errors.d.ts +21 -0
  4. package/dist/errors.js +41 -0
  5. package/dist/execute.d.ts +25 -0
  6. package/dist/execute.js +229 -0
  7. package/dist/extension.d.ts +2 -0
  8. package/dist/extension.js +195 -0
  9. package/dist/index.d.ts +5 -0
  10. package/dist/index.js +4 -0
  11. package/dist/local-runtime.d.ts +14 -0
  12. package/dist/local-runtime.js +246 -0
  13. package/dist/mcp-cli.d.ts +2 -0
  14. package/dist/mcp-cli.js +46 -0
  15. package/dist/mcp-server.d.ts +23 -0
  16. package/dist/mcp-server.js +154 -0
  17. package/dist/provider-http.d.ts +11 -0
  18. package/dist/provider-http.js +60 -0
  19. package/dist/provider-types.d.ts +30 -0
  20. package/dist/provider-types.js +1 -0
  21. package/dist/providers.d.ts +18 -0
  22. package/dist/providers.js +265 -0
  23. package/dist/response.d.ts +11 -0
  24. package/dist/response.js +62 -0
  25. package/dist/runtime.d.ts +19 -0
  26. package/dist/runtime.js +121 -0
  27. package/dist/schemas.d.ts +431 -0
  28. package/dist/schemas.js +214 -0
  29. package/dist/settings-write.d.ts +9 -0
  30. package/dist/settings-write.js +77 -0
  31. package/dist/settings.d.ts +8 -0
  32. package/dist/settings.js +97 -0
  33. package/dist/tool-contracts.d.ts +200 -0
  34. package/dist/tool-contracts.js +19 -0
  35. package/package.json +83 -4
  36. package/src/errors.ts +52 -0
  37. package/src/execute.ts +261 -0
  38. package/src/extension.ts +245 -0
  39. package/src/index.ts +37 -0
  40. package/src/local-runtime.ts +273 -0
  41. package/src/mcp-cli.ts +52 -0
  42. package/src/mcp-server.ts +206 -0
  43. package/src/provider-http.ts +67 -0
  44. package/src/provider-types.ts +33 -0
  45. package/src/providers.ts +335 -0
  46. package/src/response.ts +74 -0
  47. package/src/runtime.ts +146 -0
  48. package/src/schemas.ts +326 -0
  49. package/src/settings-write.ts +96 -0
  50. package/src/settings.ts +115 -0
  51. package/src/tool-contracts.ts +34 -0
package/package.json CHANGED
@@ -1,6 +1,85 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-embeddings",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam and gateway routes, ordered fallback and explicit comparisons.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "embeddings",
9
+ "mcp",
10
+ "openai",
11
+ "sarvam",
12
+ "embeddinggemma",
13
+ "litellm"
14
+ ],
15
+ "license": "Apache-2.0",
16
+ "type": "module",
17
+ "engines": {
18
+ "node": ">=22.19.0"
19
+ },
20
+ "sideEffects": false,
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "bin": {
24
+ "pi-embeddings-mcp": "dist/mcp-cli.js"
25
+ },
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ },
31
+ "./schemas": {
32
+ "types": "./dist/schemas.d.ts",
33
+ "import": "./dist/schemas.js"
34
+ },
35
+ "./extension": {
36
+ "types": "./dist/extension.d.ts",
37
+ "import": "./dist/extension.js"
38
+ },
39
+ "./mcp": {
40
+ "types": "./dist/mcp-server.d.ts",
41
+ "import": "./dist/mcp-server.js"
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "src",
48
+ "README.md",
49
+ "LICENSE"
50
+ ],
51
+ "pi": {
52
+ "extensions": [
53
+ "./dist/extension.js"
54
+ ]
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
59
+ "scripts": {
60
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
61
+ "build": "npm run clean && tsc -p tsconfig.build.json",
62
+ "typecheck": "tsc -p tsconfig.json --noEmit --pretty false",
63
+ "check": "npm run typecheck && npm run build && npm pack --dry-run"
64
+ },
65
+ "dependencies": {
66
+ "@amaster.ai/pi-shared": "^0.1.10",
67
+ "@modelcontextprotocol/sdk": "1.32.1",
68
+ "js-tiktoken": "1.0.21"
69
+ },
70
+ "peerDependencies": {
71
+ "@earendil-works/pi-coding-agent": ">=1.2.0",
72
+ "typebox": "*"
73
+ },
74
+ "peerDependenciesMeta": {
75
+ "@earendil-works/pi-coding-agent": {
76
+ "optional": true
77
+ }
78
+ },
79
+ "devDependencies": {
80
+ "@earendil-works/pi-coding-agent": "1.5.2",
81
+ "@types/node": "24.19.2",
82
+ "typebox": "1.3.27",
83
+ "typescript": "5.9.3"
84
+ }
85
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type { EmbeddingErrorCode } from './schemas.js';
2
+
3
+ /** Fixed, redacted diagnostics. Provider bodies, input text and credentials never enter an error. */
4
+ export type KnownUsage = Readonly<{
5
+ readonly providerReportedInputTokens?: number | null | undefined;
6
+ readonly preparedInputTokens?: number | null | undefined;
7
+ }>;
8
+
9
+ export class EmbeddingsError extends Error {
10
+ readonly code: EmbeddingErrorCode;
11
+ readonly httpStatus: number | undefined;
12
+ /** Counts already known when a later validation or transport step failed; billing stays unknown. */
13
+ readonly knownUsage: KnownUsage | undefined;
14
+
15
+ constructor(
16
+ code: EmbeddingErrorCode,
17
+ options?: { httpStatus?: number; knownUsage?: KnownUsage }
18
+ ) {
19
+ super(code);
20
+ this.code = code;
21
+ this.httpStatus = options?.httpStatus;
22
+ this.knownUsage = options?.knownUsage;
23
+ this.name = 'EmbeddingsError';
24
+ }
25
+ }
26
+
27
+ export const codeOf = (error: unknown): EmbeddingErrorCode =>
28
+ error instanceof EmbeddingsError ? error.code : 'transport-failed';
29
+
30
+ /** Only these typed failures may advance an ordinary call to the next configured fallback route. */
31
+ export const fallbackCodeForStatus = (status: number): EmbeddingErrorCode | undefined => {
32
+ if (status === 401) return 'http-auth';
33
+ if (status === 404) return 'http-not-found';
34
+ if (status === 429) return 'http-rate-limit';
35
+ return undefined;
36
+ };
37
+
38
+ export const isFallbackError = (error: unknown): boolean =>
39
+ error instanceof EmbeddingsError &&
40
+ (error.code === 'missing-credentials' ||
41
+ error.code === 'http-auth' ||
42
+ error.code === 'http-not-found' ||
43
+ error.code === 'http-rate-limit');
44
+
45
+ export const statusCode = (status: number): EmbeddingErrorCode => {
46
+ const fallback = fallbackCodeForStatus(status);
47
+ if (fallback !== undefined) return fallback;
48
+ if (status === 403) return 'http-forbidden';
49
+ if (status === 400 || status === 422) return 'http-bad-request';
50
+ if (status >= 500) return 'http-server-error';
51
+ return 'http-bad-request';
52
+ };
package/src/execute.ts ADDED
@@ -0,0 +1,261 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { EmbeddingsError, codeOf, isFallbackError } from './errors.js';
3
+ import type { AcquiredProvider } from './providers.js';
4
+ import type { PreparedInput } from './provider-types.js';
5
+ import {
6
+ EMBEDDINGS_PROTOCOL_VERSION,
7
+ EMBEDDING_NORMALIZATION_VERSION,
8
+ type EmbeddingAttempt,
9
+ type EmbeddingCompareEntry,
10
+ type EmbeddingCompareResult,
11
+ type EmbeddingContext,
12
+ type EmbeddingErrorCode,
13
+ type EmbeddingOutcome,
14
+ type EmbeddingRequest,
15
+ type EmbeddingResult,
16
+ type EmbeddingRoute,
17
+ } from './schemas.js';
18
+
19
+ type Pending = Readonly<{ readonly index: number; readonly input: PreparedInput }>;
20
+
21
+ type ExecuteArgs = Readonly<{
22
+ routes: readonly EmbeddingRoute[];
23
+ request: EmbeddingRequest;
24
+ context: EmbeddingContext | undefined;
25
+ signal: AbortSignal;
26
+ allowFallback: boolean;
27
+ acquire: (route: EmbeddingRoute, signal: AbortSignal) => Promise<AcquiredProvider>;
28
+ idPrefix?: string;
29
+ }>;
30
+
31
+ const cancelled = (index: number): EmbeddingOutcome => ({
32
+ status: 'error',
33
+ index,
34
+ code: 'cancelled',
35
+ attemptId: null,
36
+ });
37
+
38
+ const unstarted = (index: number): EmbeddingOutcome => ({
39
+ status: 'error',
40
+ index,
41
+ code: 'unstarted',
42
+ attemptId: null,
43
+ });
44
+
45
+ const preparedTokenCount = (input: PreparedInput): number =>
46
+ input.kind === 'tokens' ? input.tokens.length : (input.tokenCount ?? 0);
47
+
48
+ /**
49
+ * Runs one ordinary call or one explicit comparison entry. Successful inputs are never replayed on a
50
+ * fallback route; only unfinished inputs continue. Every input keeps its original zero-based index.
51
+ */
52
+ export async function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingResult> {
53
+ const prefix = args.idPrefix ?? randomUUID();
54
+ const outcomes = new Array<EmbeddingOutcome | undefined>(args.request.inputs.length);
55
+ const attempts: EmbeddingAttempt[] = [];
56
+ const failureByIndex = new Map<number, { readonly code: EmbeddingErrorCode; readonly attemptId: string | null }>();
57
+ let remaining = args.request.inputs.map((_input, index) => index);
58
+
59
+ for (const [routeIndex, route] of args.routes.entries()) {
60
+ if (remaining.length === 0) break;
61
+ if (args.signal.aborted) {
62
+ for (const index of remaining) outcomes[index] = cancelled(index);
63
+ remaining = [];
64
+ break;
65
+ }
66
+
67
+ let acquired: AcquiredProvider | undefined;
68
+ try {
69
+ acquired = await args.acquire(route, args.signal);
70
+ } catch (error) {
71
+ const code = codeOf(error);
72
+ const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
73
+ attempts.push({
74
+ id: attemptId,
75
+ route: route.provider,
76
+ model: route.model,
77
+ routeIndex,
78
+ status: 'error',
79
+ usage: null,
80
+ errorCode: code,
81
+ });
82
+ for (const index of remaining) failureByIndex.set(index, { code, attemptId });
83
+ if (args.allowFallback && isFallbackError(error)) continue;
84
+ for (const index of remaining) outcomes[index] = { status: 'error', index, code, attemptId };
85
+ remaining = [];
86
+ continue;
87
+ }
88
+
89
+ const unfinished: number[] = [];
90
+ {
91
+ const provider = acquired.provider;
92
+ const prepared: Pending[] = [];
93
+ for (const index of remaining) {
94
+ if (args.signal.aborted) {
95
+ outcomes[index] = cancelled(index);
96
+ continue;
97
+ }
98
+ try {
99
+ const input = await provider.prepare(args.request.inputs[index] ?? '', args.signal);
100
+ prepared.push({ index, input });
101
+ } catch (error) {
102
+ if (args.signal.aborted) outcomes[index] = cancelled(index);
103
+ else {
104
+ const code = codeOf(error);
105
+ failureByIndex.set(index, { code, attemptId: null });
106
+ outcomes[index] = { status: 'error', index, code, attemptId: null };
107
+ }
108
+ }
109
+ }
110
+
111
+ let batch: Pending[] = [];
112
+ let tokens = 0;
113
+ const flush = async (): Promise<void> => {
114
+ if (batch.length === 0) return;
115
+ const captured = batch;
116
+ batch = [];
117
+ tokens = 0;
118
+ const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
119
+ const preparedForBatch = captured.reduce((sum, entry) => sum + preparedTokenCount(entry.input), 0);
120
+ const attempt: EmbeddingAttempt = {
121
+ id: attemptId,
122
+ route: route.provider,
123
+ model: provider.model,
124
+ routeIndex,
125
+ status: 'success',
126
+ usage: {
127
+ providerReportedInputTokens: null,
128
+ preparedInputTokens: preparedForBatch > 0 ? preparedForBatch : null,
129
+ billedTokens: null,
130
+ },
131
+ };
132
+ attempts.push(attempt);
133
+ if (args.signal.aborted) {
134
+ attempt.status = 'cancelled';
135
+ for (const entry of captured) outcomes[entry.index] = cancelled(entry.index);
136
+ unfinished.push(...captured.map((entry) => entry.index));
137
+ return;
138
+ }
139
+ try {
140
+ const result = await provider.embed(
141
+ captured.map((entry) => entry.input),
142
+ args.signal,
143
+ args.context
144
+ );
145
+ attempt.usage = result.usage;
146
+ if (result.vectors.length !== captured.length)
147
+ throw new EmbeddingsError('provider-response-mismatch');
148
+ for (const [offset, entry] of captured.entries()) {
149
+ const vector = result.vectors[offset];
150
+ if (vector === undefined) throw new EmbeddingsError('provider-response-mismatch');
151
+ outcomes[entry.index] = {
152
+ status: 'success',
153
+ index: entry.index,
154
+ vector: [...vector],
155
+ route: route.provider,
156
+ model: provider.model,
157
+ space: provider.space,
158
+ attemptId,
159
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
160
+ };
161
+ }
162
+ } catch (error) {
163
+ const code = codeOf(error);
164
+ attempt.status = 'error';
165
+ attempt.errorCode = code;
166
+ const known = error instanceof EmbeddingsError ? error.knownUsage : undefined;
167
+ if (known !== undefined && attempt.usage !== null)
168
+ attempt.usage = {
169
+ providerReportedInputTokens: known.providerReportedInputTokens ?? attempt.usage.providerReportedInputTokens,
170
+ preparedInputTokens: known.preparedInputTokens ?? attempt.usage.preparedInputTokens,
171
+ billedTokens: null,
172
+ };
173
+ for (const entry of captured) failureByIndex.set(entry.index, { code, attemptId });
174
+ if (args.signal.aborted || code === 'cancelled') {
175
+ for (const entry of captured) outcomes[entry.index] = cancelled(entry.index);
176
+ } else if (args.allowFallback && isFallbackError(error)) {
177
+ unfinished.push(...captured.map((entry) => entry.index));
178
+ } else {
179
+ for (const entry of captured)
180
+ outcomes[entry.index] = { status: 'error', index: entry.index, code, attemptId };
181
+ }
182
+ }
183
+ };
184
+
185
+ for (const entry of prepared) {
186
+ const count = preparedTokenCount(entry.input);
187
+ if (batch.length > 0 && (batch.length + 1 > provider.maxRequestInputs || tokens + count > provider.maxRequestTokens))
188
+ await flush();
189
+ batch = [...batch, entry];
190
+ tokens += count;
191
+ }
192
+ await flush();
193
+ }
194
+ remaining = unfinished;
195
+ }
196
+
197
+ for (const index of remaining) {
198
+ if (outcomes[index] === undefined)
199
+ outcomes[index] = args.signal.aborted
200
+ ? cancelled(index)
201
+ : failureByIndex.get(index) === undefined
202
+ ? unstarted(index)
203
+ : {
204
+ status: 'error',
205
+ index,
206
+ code: failureByIndex.get(index)?.code ?? 'unstarted',
207
+ attemptId: failureByIndex.get(index)?.attemptId ?? null,
208
+ };
209
+ }
210
+ return {
211
+ schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
212
+ outcomes: outcomes.map((outcome, index) => outcome ?? unstarted(index)),
213
+ attempts,
214
+ };
215
+ }
216
+
217
+ /** Explicit comparison: configured entries only, no fallback, no ranking and no default mutation. */
218
+ export async function executeCompare(args: {
219
+ routes: readonly EmbeddingRoute[];
220
+ request: EmbeddingRequest;
221
+ context: EmbeddingContext | undefined;
222
+ signal: AbortSignal;
223
+ acquire: (route: EmbeddingRoute, signal: AbortSignal) => Promise<AcquiredProvider>;
224
+ }): Promise<EmbeddingCompareResult> {
225
+ const entries: EmbeddingCompareEntry[] = [];
226
+ for (const [index, route] of args.routes.entries()) {
227
+ if (args.signal.aborted) {
228
+ entries.push({
229
+ route: route.provider,
230
+ model: route.model,
231
+ status: 'cancelled',
232
+ result: {
233
+ schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
234
+ outcomes: args.request.inputs.map((_input, offset) => cancelled(offset)),
235
+ attempts: [],
236
+ },
237
+ });
238
+ continue;
239
+ }
240
+ const result = await executeEmbeddings({
241
+ routes: [route],
242
+ request: args.request,
243
+ context: args.context,
244
+ signal: args.signal,
245
+ allowFallback: false,
246
+ acquire: args.acquire,
247
+ idPrefix: `compare-${index}-${randomUUID()}`,
248
+ });
249
+ entries.push({
250
+ route: route.provider,
251
+ model: route.model,
252
+ status: result.outcomes.every((outcome) => outcome.status === 'success')
253
+ ? 'success'
254
+ : args.signal.aborted
255
+ ? 'cancelled'
256
+ : 'error',
257
+ result,
258
+ });
259
+ }
260
+ return { schemaVersion: EMBEDDINGS_PROTOCOL_VERSION, entries };
261
+ }
@@ -0,0 +1,245 @@
1
+ import { isProjectTrusted } from '@amaster.ai/pi-shared/settings';
2
+ import {
3
+ defineTool,
4
+ type ExtensionAPI,
5
+ type ExtensionContext,
6
+ } from '@earendil-works/pi-coding-agent';
7
+ import { EmbeddingsError } from './errors.js';
8
+ import { createEmbeddingsRuntime, type EmbeddingsRuntime } from './runtime.js';
9
+ import { loadEmbeddingSettings, validateEmbeddingSettings } from './settings.js';
10
+ import { updateProjectEmbeddingSettings } from './settings-write.js';
11
+ import {
12
+ EMBEDDINGS_SETTINGS_KEY,
13
+ type EmbeddingRoute,
14
+ type EmbeddingSettings,
15
+ } from './schemas.js';
16
+ import {
17
+ EMBED_COMPARE_TOOL,
18
+ EMBED_TOOL,
19
+ EMBEDDINGS_DESCRIBE_TOOL,
20
+ EMBED_COMPARE_TOOL_DESCRIPTION,
21
+ EMBED_TOOL_DESCRIPTION,
22
+ EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
23
+ embedCompareOutput,
24
+ embedCompareParameters,
25
+ embedOutput,
26
+ embedParameters,
27
+ embeddingsDescribeOutput,
28
+ embeddingsDescribeParameters,
29
+ } from './tool-contracts.js';
30
+
31
+ const summary = (result: {
32
+ outcomes: readonly { readonly status: string; readonly route?: string; readonly model?: string }[];
33
+ }): string => {
34
+ const successes = result.outcomes.filter((outcome) => outcome.status === 'success');
35
+ const routes = [...new Set(successes.map((outcome) => `${outcome.route}:${outcome.model}`))].join(', ');
36
+ return `Embedded ${successes.length}/${result.outcomes.length} input(s)${routes === '' ? '' : ` via ${routes}`}.`;
37
+ };
38
+
39
+ const codeOf = (error: unknown): string =>
40
+ error instanceof EmbeddingsError ? error.code : 'configuration-invalid';
41
+
42
+ const signalOptions = (signal: AbortSignal | undefined) =>
43
+ signal === undefined ? {} : { signal };
44
+
45
+ export default function piEmbeddingsExtension(pi: ExtensionAPI): void {
46
+ let settings: EmbeddingSettings | undefined;
47
+ let runtime: EmbeddingsRuntime | undefined;
48
+ let cwd = process.cwd();
49
+
50
+ const refresh = async (next: EmbeddingSettings, nextCwd = cwd): Promise<void> => {
51
+ await runtime?.close();
52
+ settings = next;
53
+ cwd = nextCwd;
54
+ runtime = createEmbeddingsRuntime({ settings: next, cwd: nextCwd });
55
+ };
56
+
57
+ const currentRuntime = (ctx: ExtensionContext): EmbeddingsRuntime => {
58
+ if (runtime === undefined || cwd !== ctx.cwd)
59
+ throw new EmbeddingsError('configuration-invalid');
60
+ return runtime;
61
+ };
62
+
63
+ pi.on('session_start', async (_event: unknown, ctx: ExtensionContext) => {
64
+ await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd);
65
+ });
66
+
67
+ pi.on('session_shutdown', async () => {
68
+ await runtime?.close();
69
+ runtime = undefined;
70
+ });
71
+
72
+ pi.registerTool(
73
+ defineTool({
74
+ name: EMBED_TOOL,
75
+ label: 'Embed text',
76
+ description: EMBED_TOOL_DESCRIPTION,
77
+ promptSnippet:
78
+ 'Return text vectors and their actual generating space using the configured embedding route; full input text is preserved and the package owns provider batching.',
79
+ promptGuidelines: [
80
+ 'Provider, model, credentials and caller storage policy are fixed by trusted settings and cannot be overridden through this tool.',
81
+ '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.',
83
+ ],
84
+ parameters: embedParameters,
85
+ outputSchema: embedOutput,
86
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
87
+ async execute(_id, params, signal, _onUpdate, ctx) {
88
+ try {
89
+ const result = await currentRuntime(ctx).embed(params, signalOptions(signal ?? undefined));
90
+ return {
91
+ content: [{ type: 'text', text: summary(result) }],
92
+ details: result,
93
+ structuredContent: result,
94
+ };
95
+ } catch (error) {
96
+ throw new Error(codeOf(error));
97
+ }
98
+ },
99
+ })
100
+ );
101
+
102
+ pi.registerTool(
103
+ defineTool({
104
+ name: EMBED_COMPARE_TOOL,
105
+ label: 'Compare embedding routes',
106
+ description: EMBED_COMPARE_TOOL_DESCRIPTION,
107
+ promptSnippet:
108
+ 'Compare configured embedding routes only on explicit user request; each entry is labeled and may incur charges.',
109
+ promptGuidelines: [
110
+ 'Never use comparison to recover from an ordinary embedding failure.',
111
+ 'Each configured entry is an independent request with its own usage and generating space; results are not merged or ranked.',
112
+ ],
113
+ parameters: embedCompareParameters,
114
+ outputSchema: embedCompareOutput,
115
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
116
+ async execute(_id, params, signal, _onUpdate, ctx) {
117
+ try {
118
+ const result = await currentRuntime(ctx).compare(params, signalOptions(signal ?? undefined));
119
+ return {
120
+ content: [
121
+ { type: 'text', text: `Compared ${result.entries.length} configured embedding route(s).` },
122
+ ],
123
+ details: result,
124
+ structuredContent: result,
125
+ };
126
+ } catch (error) {
127
+ throw new Error(codeOf(error));
128
+ }
129
+ },
130
+ })
131
+ );
132
+
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
+ pi.registerCommand('embeddings', {
168
+ description:
169
+ 'Embeddings: /embeddings list | doctor | reload | use <provider> <model> | compare <text>. list, doctor and describe make no inference calls.',
170
+ handler: async (args: string | undefined, ctx: ExtensionContext) => {
171
+ const raw = (args ?? '').trim();
172
+ const parts = raw.split(/\s+/).filter(Boolean);
173
+ const command = parts[0] ?? 'list';
174
+ try {
175
+ if (command === 'list' || command === 'doctor' || command === 'describe' || command === 'status') {
176
+ if (parts.length !== 1) throw new EmbeddingsError('configuration-invalid');
177
+ const active = currentRuntime(ctx);
178
+ const described = active.describe();
179
+ if (command === 'doctor') {
180
+ reply(
181
+ pi,
182
+ ctx,
183
+ described.diagnostics.length === 0
184
+ ? 'Embeddings settings are valid. No provider call was made.'
185
+ : described.diagnostics.map((entry) => `${entry.severity}: ${entry.code}`).join('\n')
186
+ );
187
+ return;
188
+ }
189
+ reply(
190
+ pi,
191
+ ctx,
192
+ JSON.stringify(
193
+ {
194
+ selected: described.selected,
195
+ space: described.space,
196
+ default: described.default,
197
+ fallback: described.fallback,
198
+ compare: described.compare,
199
+ ready: described.ready,
200
+ },
201
+ null,
202
+ 2
203
+ )
204
+ );
205
+ return;
206
+ }
207
+ if (command === 'reload') {
208
+ if (parts.length !== 1) throw new EmbeddingsError('configuration-invalid');
209
+ const next = loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx));
210
+ await refresh(next, ctx.cwd);
211
+ reply(pi, ctx, `${EMBEDDINGS_SETTINGS_KEY} settings reloaded. No inference was run.`);
212
+ return;
213
+ }
214
+ if (command === 'use') {
215
+ if (parts.length !== 3) throw new EmbeddingsError('configuration-invalid');
216
+ const route: EmbeddingRoute = { provider: parts[1] as EmbeddingRoute['provider'], model: parts[2] ?? '' };
217
+ validateEmbeddingSettings({ default: route });
218
+ await updateProjectEmbeddingSettings({
219
+ cwd: ctx.cwd,
220
+ projectTrusted: isProjectTrusted(ctx),
221
+ route,
222
+ });
223
+ await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd);
224
+ reply(pi, ctx, `Selected ${route.provider}/${route.model} in trusted project settings.`);
225
+ return;
226
+ }
227
+ if (command === 'compare') {
228
+ const text = raw.slice('compare'.length).trim();
229
+ if (text === '') throw new EmbeddingsError('configuration-invalid');
230
+ const result = await currentRuntime(ctx).compare({ inputs: [text] }, signalOptions(ctx.signal ?? undefined));
231
+ reply(pi, ctx, `Compared ${result.entries.length} configured route(s).\n${summary(result.entries[0]?.result ?? { outcomes: [] })}`);
232
+ return;
233
+ }
234
+ reply(pi, ctx, 'Usage: /embeddings list | doctor | reload | use <provider> <model> | compare <text>');
235
+ } catch (error) {
236
+ reply(pi, ctx, `Embeddings command failed: ${codeOf(error)}`);
237
+ }
238
+ },
239
+ });
240
+ }
241
+
242
+ function reply(pi: ExtensionAPI, ctx: ExtensionContext, text: string): void {
243
+ if (ctx.hasUI) ctx.ui.notify(text, 'info');
244
+ else pi.sendMessage({ customType: 'pi-embeddings', content: text, display: true }, { triggerTurn: false });
245
+ }
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ export { createEmbeddingsRuntime, type EmbeddingsRuntime } from './runtime.js';
2
+ export {
3
+ loadEmbeddingSettings,
4
+ validateEmbeddingSettings,
5
+ configuredDefault,
6
+ configuredRoutes,
7
+ isEmbeddingSettings,
8
+ } from './settings.js';
9
+ export { EmbeddingsError } from './errors.js';
10
+ export {
11
+ EMBEDDINGS_SETTINGS_KEY,
12
+ EMBEDDINGS_PROTOCOL_VERSION,
13
+ EMBEDDING_FORMAT_VERSION,
14
+ EMBEDDING_DOCUMENT_PREFIX,
15
+ EMBEDDING_NORMALIZATION_VERSION,
16
+ EMBEDDING_CONTEXT_META_KEY,
17
+ EMBEDDING_ROUTE_IDS,
18
+ GATEWAY_EMBEDDING_MODELS,
19
+ EMBEDDING_ERROR_CODES,
20
+ } from './schemas.js';
21
+ export type {
22
+ EmbeddingSettings,
23
+ EmbeddingRoute,
24
+ EmbeddingRouteId,
25
+ EmbeddingSpace,
26
+ EmbeddingRequest,
27
+ EmbeddingContext,
28
+ EmbeddingUsage,
29
+ EmbeddingAttempt,
30
+ EmbeddingOutcome,
31
+ EmbeddingResult,
32
+ EmbeddingCompareEntry,
33
+ EmbeddingCompareResult,
34
+ EmbeddingDiagnostic,
35
+ EmbeddingDescribe,
36
+ EmbeddingErrorCode,
37
+ } from './schemas.js';