@abhishek944/pi-embeddings 0.0.0-stage → 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.
Files changed (51) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +97 -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 +264 -0
  7. package/dist/extension.d.ts +2 -0
  8. package/dist/extension.js +164 -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 +141 -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 +25 -0
  22. package/dist/providers.js +415 -0
  23. package/dist/response.d.ts +17 -0
  24. package/dist/response.js +105 -0
  25. package/dist/runtime.d.ts +39 -0
  26. package/dist/runtime.js +130 -0
  27. package/dist/schemas.d.ts +758 -0
  28. package/dist/schemas.js +244 -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 +99 -0
  33. package/dist/tool-contracts.d.ts +343 -0
  34. package/dist/tool-contracts.js +10 -0
  35. package/package.json +83 -4
  36. package/src/errors.ts +52 -0
  37. package/src/execute.ts +300 -0
  38. package/src/extension.ts +210 -0
  39. package/src/index.ts +36 -0
  40. package/src/local-runtime.ts +273 -0
  41. package/src/mcp-cli.ts +52 -0
  42. package/src/mcp-server.ts +187 -0
  43. package/src/provider-http.ts +67 -0
  44. package/src/provider-types.ts +33 -0
  45. package/src/providers.ts +517 -0
  46. package/src/response.ts +125 -0
  47. package/src/runtime.ts +184 -0
  48. package/src/schemas.ts +368 -0
  49. package/src/settings-write.ts +96 -0
  50. package/src/settings.ts +119 -0
  51. package/src/tool-contracts.ts +22 -0
@@ -0,0 +1,164 @@
1
+ import { isProjectTrusted } from '@amaster.ai/pi-shared/settings';
2
+ import { defineTool, } from '@earendil-works/pi-coding-agent';
3
+ import { EmbeddingsError } from './errors.js';
4
+ import { createEmbeddingsRuntimeWithDiagnostics, } from './runtime.js';
5
+ import { loadEmbeddingSettings, validateEmbeddingSettings } from './settings.js';
6
+ import { updateProjectEmbeddingSettings } from './settings-write.js';
7
+ import { EMBEDDINGS_SETTINGS_KEY, } from './schemas.js';
8
+ import { EMBED_COMPARE_TOOL, EMBED_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, embedCompareOutput, embedCompareParameters, embedOutput, embedParameters, } from './tool-contracts.js';
9
+ const summary = (result) => {
10
+ const successes = result.outcomes.filter((outcome) => outcome.status === 'success');
11
+ const routes = [...new Set(successes.map((outcome) => `${outcome.route}:${outcome.model}`))].join(', ');
12
+ return `Embedded ${successes.length}/${result.outcomes.length} input(s)${routes === '' ? '' : ` via ${routes}`}.`;
13
+ };
14
+ const codeOf = (error) => error instanceof EmbeddingsError ? error.code : 'configuration-invalid';
15
+ const signalOptions = (signal) => signal === undefined ? {} : { signal };
16
+ export default function piEmbeddingsExtension(pi) {
17
+ let settings;
18
+ let runtime;
19
+ let cwd = process.cwd();
20
+ const refresh = async (next, nextCwd = cwd) => {
21
+ await runtime?.close();
22
+ settings = next;
23
+ cwd = nextCwd;
24
+ runtime = createEmbeddingsRuntimeWithDiagnostics({ settings: next, cwd: nextCwd });
25
+ };
26
+ const currentRuntime = (ctx) => {
27
+ if (runtime === undefined || cwd !== ctx.cwd)
28
+ throw new EmbeddingsError('configuration-invalid');
29
+ return runtime;
30
+ };
31
+ pi.on('session_start', async (_event, ctx) => {
32
+ await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd);
33
+ });
34
+ pi.on('session_shutdown', async () => {
35
+ await runtime?.close();
36
+ runtime = undefined;
37
+ });
38
+ pi.registerTool(defineTool({
39
+ name: EMBED_TOOL,
40
+ label: 'Embed text',
41
+ description: EMBED_TOOL_DESCRIPTION,
42
+ promptSnippet: 'Return text vectors and their actual generating space using the configured embedding route; full input text is preserved and the package owns provider batching.',
43
+ promptGuidelines: [
44
+ 'Provider, model, credentials and caller storage policy are fixed by trusted settings and cannot be overridden through this tool.',
45
+ 'Use embed_compare only when the user explicitly asks to compare configured embedding routes.',
46
+ 'The embed result reports the actual generating provider, model and space, including mixed fallback generations.',
47
+ ],
48
+ parameters: embedParameters,
49
+ outputSchema: embedOutput,
50
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
51
+ async execute(_id, params, signal, _onUpdate, ctx) {
52
+ try {
53
+ const result = await currentRuntime(ctx).embed(params, signalOptions(signal ?? undefined));
54
+ return {
55
+ content: [{ type: 'text', text: summary(result) }],
56
+ details: result,
57
+ structuredContent: result,
58
+ };
59
+ }
60
+ catch (error) {
61
+ throw new Error(codeOf(error));
62
+ }
63
+ },
64
+ }));
65
+ pi.registerTool(defineTool({
66
+ name: EMBED_COMPARE_TOOL,
67
+ label: 'Compare embedding routes',
68
+ description: EMBED_COMPARE_TOOL_DESCRIPTION,
69
+ promptSnippet: 'Compare configured embedding routes only on explicit user request; each entry is labeled and may incur charges.',
70
+ promptGuidelines: [
71
+ 'Never use comparison to recover from an ordinary embedding failure.',
72
+ 'Each configured entry is an independent request with its own usage and generating space; results are not merged or ranked.',
73
+ ],
74
+ parameters: embedCompareParameters,
75
+ outputSchema: embedCompareOutput,
76
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
77
+ async execute(_id, params, signal, _onUpdate, ctx) {
78
+ try {
79
+ const result = await currentRuntime(ctx).compare(params, signalOptions(signal ?? undefined));
80
+ return {
81
+ content: [
82
+ { type: 'text', text: `Compared ${result.entries.length} configured embedding route(s).` },
83
+ ],
84
+ details: result,
85
+ structuredContent: result,
86
+ };
87
+ }
88
+ catch (error) {
89
+ throw new Error(codeOf(error));
90
+ }
91
+ },
92
+ }));
93
+ pi.registerCommand('embeddings', {
94
+ description: 'Embeddings: /embeddings list | doctor | reload | use <provider> <model> | compare <text>. list and doctor make no inference calls.',
95
+ handler: async (args, ctx) => {
96
+ const raw = (args ?? '').trim();
97
+ const parts = raw.split(/\s+/).filter(Boolean);
98
+ const command = parts[0] ?? 'list';
99
+ try {
100
+ if (command === 'list' || command === 'doctor' || command === 'status') {
101
+ if (parts.length !== 1)
102
+ throw new EmbeddingsError('configuration-invalid');
103
+ const active = currentRuntime(ctx);
104
+ const described = active.describe();
105
+ if (command === 'doctor') {
106
+ reply(pi, ctx, described.diagnostics.length === 0
107
+ ? 'Embeddings settings are valid. No provider call was made.'
108
+ : described.diagnostics.map((entry) => `${entry.severity}: ${entry.code}`).join('\n'));
109
+ return;
110
+ }
111
+ reply(pi, ctx, JSON.stringify({
112
+ selected: described.selected,
113
+ space: described.space,
114
+ default: described.default,
115
+ fallback: described.fallback,
116
+ compare: described.compare,
117
+ ready: described.ready,
118
+ }, null, 2));
119
+ return;
120
+ }
121
+ if (command === 'reload') {
122
+ if (parts.length !== 1)
123
+ throw new EmbeddingsError('configuration-invalid');
124
+ const next = loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx));
125
+ await refresh(next, ctx.cwd);
126
+ reply(pi, ctx, `${EMBEDDINGS_SETTINGS_KEY} settings reloaded. No inference was run.`);
127
+ return;
128
+ }
129
+ if (command === 'use') {
130
+ if (parts.length !== 3)
131
+ throw new EmbeddingsError('configuration-invalid');
132
+ const route = { provider: parts[1], model: parts[2] ?? '' };
133
+ validateEmbeddingSettings({ default: route });
134
+ await updateProjectEmbeddingSettings({
135
+ cwd: ctx.cwd,
136
+ projectTrusted: isProjectTrusted(ctx),
137
+ route,
138
+ });
139
+ await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd);
140
+ reply(pi, ctx, `Selected ${route.provider}/${route.model} in trusted project settings.`);
141
+ return;
142
+ }
143
+ if (command === 'compare') {
144
+ const text = raw.slice('compare'.length).trim();
145
+ if (text === '')
146
+ throw new EmbeddingsError('configuration-invalid');
147
+ const result = await currentRuntime(ctx).compare({ inputs: [text] }, signalOptions(ctx.signal ?? undefined));
148
+ reply(pi, ctx, `Compared ${result.entries.length} configured route(s).\n${summary(result.entries[0]?.result ?? { outcomes: [] })}`);
149
+ return;
150
+ }
151
+ reply(pi, ctx, 'Usage: /embeddings list | doctor | reload | use <provider> <model> | compare <text>');
152
+ }
153
+ catch (error) {
154
+ reply(pi, ctx, `Embeddings command failed: ${codeOf(error)}`);
155
+ }
156
+ },
157
+ });
158
+ }
159
+ function reply(pi, ctx, text) {
160
+ if (ctx.hasUI)
161
+ ctx.ui.notify(text, 'info');
162
+ else
163
+ pi.sendMessage({ customType: 'pi-embeddings', content: text, display: true }, { triggerTurn: false });
164
+ }
@@ -0,0 +1,5 @@
1
+ export { createEmbeddingsRuntime, type EmbeddingsRuntime } from './runtime.js';
2
+ export { loadEmbeddingSettings, validateEmbeddingSettings, configuredDefault, configuredRoutes, isEmbeddingSettings, } from './settings.js';
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, EmbeddingGeneration, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult, EmbeddingErrorCode, } from './schemas.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createEmbeddingsRuntime } from './runtime.js';
2
+ export { loadEmbeddingSettings, validateEmbeddingSettings, configuredDefault, configuredRoutes, isEmbeddingSettings, } from './settings.js';
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';
@@ -0,0 +1,14 @@
1
+ import type { EmbeddingsProvider } from './provider-types.js';
2
+ import { type EmbeddingSpace } from './schemas.js';
3
+ export type LocalRuntimeConfig = Readonly<{
4
+ executable: string;
5
+ modelPath: string;
6
+ port: number;
7
+ }>;
8
+ export declare const LOCAL_EMBEDDING_SPACE: EmbeddingSpace;
9
+ export type AcquiredLocalRuntime = Readonly<{
10
+ readonly provider: EmbeddingsProvider;
11
+ readonly release: () => Promise<void>;
12
+ }>;
13
+ /** One owned child per pinned configuration, shared across all runtimes that resolve it. */
14
+ export declare function acquireLocalRuntime(config: LocalRuntimeConfig, signal: AbortSignal): Promise<AcquiredLocalRuntime>;
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Package-owned pinned CPU EmbeddingGemma 2 runtime.
3
+ *
4
+ * The operator supplies compatible assets through package settings. Nothing is downloaded, installed,
5
+ * discovered globally, inherited from a provider or borrowed from a foreign listener.
6
+ */
7
+ import { spawn, execFile } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
9
+ import { constants } from 'node:fs';
10
+ import { createReadStream } from 'node:fs';
11
+ import { access } from 'node:fs/promises';
12
+ import { createInterface } from 'node:readline';
13
+ import { promisify } from 'node:util';
14
+ import { Type } from 'typebox';
15
+ import { Value } from 'typebox/value';
16
+ import { EmbeddingsError } from './errors.js';
17
+ import { requestJson } from './provider-http.js';
18
+ import { parseBatchResponse } from './response.js';
19
+ import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, } from './schemas.js';
20
+ const MODEL_SHA256 = '2188ac1deca4b77dffefd603c2776a9d76d9d74ec01841392982ebb840b09135';
21
+ const RUNTIME_COMMIT = 'af6b5243d6871923dfecbe06814bd566d9dc383b';
22
+ const DEFAULT_PORT = 8791;
23
+ const tokenResponseSchema = Type.Object({
24
+ tokens: Type.Array(Type.Integer({ minimum: 0 }), { minItems: 1 }),
25
+ });
26
+ export const LOCAL_EMBEDDING_SPACE = Object.freeze({
27
+ provider: 'local',
28
+ model: 'embeddinggemma-2',
29
+ revision: `6ea3e3a309d12a4779cfda98b8c19800d2d5da71:sha256:${MODEL_SHA256}`,
30
+ quantization: 'Q8_0',
31
+ runtime: `llama.cpp:${RUNTIME_COMMIT}:mean`,
32
+ dimensions: 768,
33
+ format: EMBEDDING_FORMAT_VERSION,
34
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
35
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
36
+ });
37
+ class LocalRuntimeProvider {
38
+ route = 'local';
39
+ model = 'embeddinggemma-2';
40
+ space = LOCAL_EMBEDDING_SPACE;
41
+ maxRequestInputs = Number.POSITIVE_INFINITY;
42
+ maxRequestTokens = Number.POSITIVE_INFINITY;
43
+ #origin;
44
+ #process;
45
+ #closed;
46
+ #closeStarted = false;
47
+ constructor(child, port, closed) {
48
+ this.#process = child;
49
+ this.#origin = new URL(`http://127.0.0.1:${port}`);
50
+ this.#closed = closed;
51
+ }
52
+ static async open(config, signal) {
53
+ const environment = { PATH: process.env.PATH, HOME: process.env.HOME };
54
+ try {
55
+ await access(config.executable, constants.X_OK);
56
+ const digest = createHash('sha256');
57
+ for await (const chunk of createReadStream(config.modelPath, { signal }))
58
+ digest.update(chunk);
59
+ if (digest.digest('hex') !== MODEL_SHA256)
60
+ throw new EmbeddingsError('local-model-mismatch');
61
+ const version = await promisify(execFile)(config.executable, ['--version'], {
62
+ signal,
63
+ env: environment,
64
+ });
65
+ if (!(version.stdout + version.stderr).includes('af6b5243'))
66
+ throw new EmbeddingsError('local-runtime-mismatch');
67
+ }
68
+ catch (error) {
69
+ if (error instanceof EmbeddingsError)
70
+ throw error;
71
+ if (signal.aborted)
72
+ throw new EmbeddingsError('cancelled');
73
+ throw new EmbeddingsError('local-resources-unavailable');
74
+ }
75
+ signal.throwIfAborted();
76
+ const child = spawn(config.executable, [
77
+ '--model', config.modelPath,
78
+ '--alias', 'embeddinggemma-2',
79
+ '--offline',
80
+ '--embedding',
81
+ '--pooling', 'mean',
82
+ '--embd-normalize', '2',
83
+ '--ctx-size', '8192',
84
+ '--parallel', '1',
85
+ '--batch-size', '8192',
86
+ '--ubatch-size', '8192',
87
+ '--gpu-layers', '0',
88
+ '--device', 'none',
89
+ '--no-op-offload',
90
+ '--no-kv-offload',
91
+ '--no-cache-prompt',
92
+ '--host', '127.0.0.1',
93
+ '--port', String(config.port),
94
+ '--no-webui',
95
+ '--no-warmup',
96
+ '--log-colors', 'off',
97
+ '--verbosity', '4',
98
+ ], { env: environment, stdio: ['ignore', 'pipe', 'pipe'] });
99
+ const closed = new Promise((resolve) => child.once('close', () => resolve()));
100
+ const provider = new LocalRuntimeProvider(child, config.port, closed);
101
+ const abort = () => {
102
+ child.kill('SIGTERM');
103
+ };
104
+ signal.addEventListener('abort', abort, { once: true });
105
+ try {
106
+ await new Promise((resolve, reject) => {
107
+ let cpuBuffer = false;
108
+ let gpuBuffer = false;
109
+ const observe = (line) => {
110
+ cpuBuffer ||= /CPU[^\n]*model buffer|model buffer[^\n]*CPU/iu.test(line);
111
+ gpuBuffer ||=
112
+ /(Metal|MTL\d|CUDA|Vulkan)[^\n]*(model|compute|KV).*buffer size|offloaded\s+[1-9]\d*\//iu.test(line);
113
+ if (line.includes('listening on http://127.0.0.1:')) {
114
+ if (cpuBuffer && !gpuBuffer && !signal.aborted)
115
+ resolve();
116
+ else
117
+ reject(new EmbeddingsError('local-cpu-startup-invalid'));
118
+ }
119
+ };
120
+ if (child.stdout)
121
+ createInterface({ input: child.stdout }).on('line', observe);
122
+ if (child.stderr)
123
+ createInterface({ input: child.stderr }).on('line', observe);
124
+ child.once('error', () => reject(new EmbeddingsError('local-startup-failed')));
125
+ child.once('close', () => reject(new EmbeddingsError('local-startup-failed')));
126
+ });
127
+ const health = await fetch(new URL('/health', provider.#origin), { signal, redirect: 'error' });
128
+ if (!health.ok)
129
+ throw new EmbeddingsError('local-startup-failed');
130
+ return provider;
131
+ }
132
+ catch (error) {
133
+ await provider.close();
134
+ throw error;
135
+ }
136
+ finally {
137
+ signal.removeEventListener('abort', abort);
138
+ }
139
+ }
140
+ async prepare(text, signal) {
141
+ const response = await requestJson({
142
+ url: new URL('/tokenize', this.#origin),
143
+ body: { content: EMBEDDING_DOCUMENT_PREFIX + text, add_special: true, parse_special: false },
144
+ signal,
145
+ });
146
+ if (!Value.Check(tokenResponseSchema, response))
147
+ throw new EmbeddingsError('provider-response-invalid');
148
+ if (response.tokens.length > 8192)
149
+ throw new EmbeddingsError('input-too-long');
150
+ return { kind: 'tokens', tokens: response.tokens };
151
+ }
152
+ async embed(inputs, signal) {
153
+ const tokens = inputs.map((input) => {
154
+ if (input.kind !== 'tokens')
155
+ throw new EmbeddingsError('provider-response-invalid');
156
+ return input.tokens;
157
+ });
158
+ const response = await requestJson({
159
+ url: new URL('/v1/embeddings', this.#origin),
160
+ body: { model: this.model, input: tokens, encoding_format: 'float' },
161
+ signal,
162
+ });
163
+ const prepared = tokens.reduce((sum, item) => sum + item.length, 0);
164
+ return parseBatchResponse({
165
+ response,
166
+ space: this.space,
167
+ expectedPreparedTokens: prepared,
168
+ preparedInputTokens: prepared,
169
+ });
170
+ }
171
+ async close() {
172
+ if (this.#closeStarted)
173
+ return;
174
+ this.#closeStarted = true;
175
+ if (this.#process.exitCode === null && this.#process.signalCode === null)
176
+ this.#process.kill('SIGTERM');
177
+ await this.#closed;
178
+ }
179
+ }
180
+ const entries = new Map();
181
+ const waitFor = (promise, signal) => {
182
+ if (signal.aborted)
183
+ return Promise.reject(new EmbeddingsError('cancelled'));
184
+ let listener;
185
+ const cancelled = new Promise((_resolve, reject) => {
186
+ listener = () => reject(new EmbeddingsError('cancelled'));
187
+ signal.addEventListener('abort', listener, { once: true });
188
+ });
189
+ return Promise.race([promise, cancelled]).finally(() => {
190
+ if (listener !== undefined)
191
+ signal.removeEventListener('abort', listener);
192
+ });
193
+ };
194
+ /** One owned child per pinned configuration, shared across all runtimes that resolve it. */
195
+ export async function acquireLocalRuntime(config, signal) {
196
+ signal.throwIfAborted();
197
+ const normalized = {
198
+ executable: config.executable,
199
+ modelPath: config.modelPath,
200
+ port: config.port || DEFAULT_PORT,
201
+ };
202
+ const key = JSON.stringify(normalized);
203
+ let entry = entries.get(key);
204
+ while (entry !== undefined && entry.closing !== null) {
205
+ await entry.closing;
206
+ entry = entries.get(key);
207
+ }
208
+ if (entry === undefined) {
209
+ const controller = new AbortController();
210
+ const promise = LocalRuntimeProvider.open(normalized, controller.signal).catch((error) => {
211
+ if (entries.get(key)?.controller === controller)
212
+ entries.delete(key);
213
+ throw error;
214
+ });
215
+ entry = { key, controller, promise, refs: 0, closing: null };
216
+ entries.set(key, entry);
217
+ }
218
+ const acquired = entry;
219
+ acquired.refs += 1;
220
+ let released = false;
221
+ const release = async () => {
222
+ if (released)
223
+ return;
224
+ released = true;
225
+ acquired.refs -= 1;
226
+ if (acquired.refs > 0)
227
+ return;
228
+ if (acquired.closing === null)
229
+ acquired.closing = (async () => {
230
+ acquired.controller.abort();
231
+ const provider = await acquired.promise.catch(() => undefined);
232
+ await provider?.close();
233
+ })().finally(() => {
234
+ if (entries.get(acquired.key) === acquired)
235
+ entries.delete(acquired.key);
236
+ });
237
+ await acquired.closing;
238
+ };
239
+ try {
240
+ return { provider: await waitFor(acquired.promise, signal), release };
241
+ }
242
+ catch (error) {
243
+ await release();
244
+ throw error;
245
+ }
246
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ // pi-embeddings-mcp: JSON-RPC only on stdout; all diagnostics go to stderr.
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { createEmbeddingsRuntime } from './runtime.js';
5
+ import { loadEmbeddingSettings } from './settings.js';
6
+ import { createEmbeddingsMcpServer } from './mcp-server.js';
7
+ console.log = console.info = console.debug = console.error;
8
+ let closing = false;
9
+ let server;
10
+ let runtime;
11
+ const shutdown = async (code) => {
12
+ if (closing)
13
+ return;
14
+ closing = true;
15
+ try {
16
+ await server?.close();
17
+ }
18
+ catch (error) {
19
+ console.error('pi-embeddings-mcp: server close failed:', error instanceof Error ? error.message : 'unknown');
20
+ }
21
+ try {
22
+ await runtime?.close();
23
+ }
24
+ catch (error) {
25
+ console.error('pi-embeddings-mcp: runtime close failed:', error instanceof Error ? error.message : 'unknown');
26
+ }
27
+ process.exit(code);
28
+ };
29
+ process.stdin.once('end', () => void shutdown(0));
30
+ process.stdin.once('close', () => void shutdown(0));
31
+ process.once('SIGINT', () => void shutdown(0));
32
+ process.once('SIGTERM', () => void shutdown(0));
33
+ try {
34
+ const cwd = process.cwd();
35
+ runtime = createEmbeddingsRuntime({
36
+ settings: loadEmbeddingSettings(cwd, false),
37
+ cwd,
38
+ });
39
+ server = await createEmbeddingsMcpServer({ cwd, runtime });
40
+ await server.connect(new StdioServerTransport());
41
+ }
42
+ catch (error) {
43
+ console.error('pi-embeddings-mcp: failed to start:', error instanceof Error ? error.message : 'unknown');
44
+ await runtime?.close().catch(() => undefined);
45
+ process.exit(1);
46
+ }
@@ -0,0 +1,23 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { type EmbeddingsRuntime } from './runtime.js';
3
+ import { type EmbeddingSettings } from './schemas.js';
4
+ export declare const embeddingsMcpServerInfo: {
5
+ name: string;
6
+ version: string;
7
+ };
8
+ export interface EmbeddingsMcpServerOptions {
9
+ cwd?: string | undefined;
10
+ settings?: EmbeddingSettings;
11
+ /** Project settings are never read unless the host explicitly asserts trust. */
12
+ projectTrusted?: boolean;
13
+ runtime?: EmbeddingsRuntime;
14
+ info?: {
15
+ name: string;
16
+ version: string;
17
+ };
18
+ }
19
+ /**
20
+ * Create one MCP server around a package-owned runtime. The caller owns transport, the returned
21
+ * server, and runtime shutdown; closing a session never closes the shared runtime.
22
+ */
23
+ export declare function createEmbeddingsMcpServer(options?: EmbeddingsMcpServerOptions): Promise<Server>;
@@ -0,0 +1,141 @@
1
+ import { createRequire } from 'node:module';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from '@modelcontextprotocol/sdk/types.js';
4
+ import { Value } from 'typebox/value';
5
+ import { EmbeddingsError } from './errors.js';
6
+ import { createEmbeddingsRuntime } from './runtime.js';
7
+ import { loadEmbeddingSettings } from './settings.js';
8
+ import { EMBEDDING_CONTEXT_META_KEY, embeddingContextSchema, embeddingRequestSchema, } from './schemas.js';
9
+ import { EMBED_COMPARE_TOOL, EMBED_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, embedCompareParameters, embedParameters, } from './tool-contracts.js';
10
+ const require = createRequire(import.meta.url);
11
+ const manifest = require('../package.json');
12
+ const version = typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
13
+ ? manifest.version
14
+ : '0.0.0';
15
+ export const embeddingsMcpServerInfo = { name: 'pi-embeddings', version };
16
+ const errorResult = (text) => ({
17
+ content: [{ type: 'text', text }],
18
+ isError: true,
19
+ });
20
+ const jsonResult = (value, text) => ({
21
+ content: [{ type: 'text', text }],
22
+ structuredContent: { result: value },
23
+ });
24
+ const isRequest = (value) => Value.Check(embeddingRequestSchema, value);
25
+ const validationProblems = (schema, args) => {
26
+ if (Value.Check(schema, args))
27
+ return [];
28
+ const problems = new Set();
29
+ for (const issue of Value.Errors(schema, args)) {
30
+ if (issue.keyword === 'boolean')
31
+ continue;
32
+ const path = issue.instancePath === '' ? 'arguments' : issue.instancePath;
33
+ const extra = issue.params.additionalProperties;
34
+ problems.add(extra === undefined
35
+ ? `${path}: ${issue.message ?? 'invalid value'}`
36
+ : `${path}: unknown or server-owned properties ${extra.join(', ')}`);
37
+ }
38
+ return [...problems];
39
+ };
40
+ /** Trusted host attribution is read only from namespaced MCP metadata, never from model arguments. */
41
+ function readContext(request) {
42
+ if (typeof request !== 'object' || request === null || !('params' in request))
43
+ throw new EmbeddingsError('configuration-invalid');
44
+ const requestParams = request.params;
45
+ if (typeof requestParams !== 'object' || requestParams === null)
46
+ throw new EmbeddingsError('configuration-invalid');
47
+ const params = { ...requestParams };
48
+ const meta = params['_meta'];
49
+ if (meta === undefined)
50
+ return undefined;
51
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta))
52
+ throw new EmbeddingsError('configuration-invalid');
53
+ const namespaced = meta[EMBEDDING_CONTEXT_META_KEY];
54
+ if (namespaced === undefined)
55
+ return undefined;
56
+ if (!Value.Check(embeddingContextSchema, namespaced))
57
+ throw new EmbeddingsError('configuration-invalid');
58
+ return namespaced;
59
+ }
60
+ const summary = (result) => {
61
+ const successes = result.outcomes.filter((outcome) => outcome.status === 'success');
62
+ const errors = result.outcomes.length - successes.length;
63
+ const routes = [
64
+ ...new Set(successes.map((outcome) => `${outcome.route}:${outcome.model}`)),
65
+ ].join(', ');
66
+ return `Embedded ${successes.length}/${result.outcomes.length} input(s)${routes === '' ? '' : ` via ${routes}`}${errors === 0 ? '' : `; ${errors} failed`}.`;
67
+ };
68
+ /**
69
+ * Create one MCP server around a package-owned runtime. The caller owns transport, the returned
70
+ * server, and runtime shutdown; closing a session never closes the shared runtime.
71
+ */
72
+ export async function createEmbeddingsMcpServer(options = {}) {
73
+ const ownsRuntime = options.runtime === undefined;
74
+ const runtime = options.runtime ??
75
+ createEmbeddingsRuntime({
76
+ settings: options.settings ?? loadEmbeddingSettings(options.cwd ?? process.cwd(), options.projectTrusted ?? false),
77
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
78
+ });
79
+ await runtime.start();
80
+ const server = new Server(options.info ?? embeddingsMcpServerInfo, {
81
+ capabilities: { tools: {} },
82
+ instructions: 'Independent pi-embeddings MCP server. Provider, model and credentials stay on the server and cannot be overridden by tool arguments. Vectors are returned in structuredContent.result. Comparison runs only on explicit request and may incur multiple charges.',
83
+ });
84
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
85
+ tools: [
86
+ {
87
+ name: EMBED_TOOL,
88
+ description: EMBED_TOOL_DESCRIPTION,
89
+ inputSchema: embedParameters,
90
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
91
+ },
92
+ {
93
+ name: EMBED_COMPARE_TOOL,
94
+ description: EMBED_COMPARE_TOOL_DESCRIPTION,
95
+ inputSchema: embedCompareParameters,
96
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
97
+ },
98
+ ],
99
+ }));
100
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
101
+ const args = request.params.arguments ?? {};
102
+ try {
103
+ switch (request.params.name) {
104
+ case EMBED_TOOL:
105
+ case EMBED_COMPARE_TOOL: {
106
+ const problems = validationProblems(embeddingRequestSchema, args);
107
+ if (problems.length > 0)
108
+ return errorResult(`Invalid arguments for ${request.params.name}:\n- ${problems.join('\n- ')}`);
109
+ if (!isRequest(args))
110
+ return errorResult('Invalid embedding request.');
111
+ const context = readContext(request);
112
+ if (request.params.name === EMBED_TOOL) {
113
+ const result = await runtime.embed(args, { signal: extra.signal, context });
114
+ return jsonResult(result, summary(result));
115
+ }
116
+ const compared = await runtime.compare(args, { signal: extra.signal, context });
117
+ return jsonResult(compared, `Compared ${compared.entries.length} configured embedding route(s).`);
118
+ }
119
+ default:
120
+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${request.params.name}`);
121
+ }
122
+ }
123
+ catch (error) {
124
+ const code = error instanceof EmbeddingsError ? error.code : 'configuration-invalid';
125
+ return errorResult(`${request.params.name} failed: ${code}`);
126
+ }
127
+ });
128
+ if (ownsRuntime) {
129
+ let ownClosed = false;
130
+ const closeServer = server.close.bind(server);
131
+ const wrapped = server;
132
+ wrapped.close = async () => {
133
+ if (ownClosed)
134
+ return;
135
+ ownClosed = true;
136
+ await closeServer();
137
+ await runtime.close();
138
+ };
139
+ }
140
+ return server;
141
+ }
@@ -0,0 +1,11 @@
1
+ /** Native fetch with fixed URLs, no retries and no response bodies in diagnostics. */
2
+ export declare function requestJson(args: {
3
+ url: URL;
4
+ body: unknown;
5
+ signal: AbortSignal;
6
+ headers?: Readonly<Record<string, string>>;
7
+ }): Promise<unknown>;
8
+ /** Fixed origins only; project settings cannot introduce an arbitrary provider endpoint. */
9
+ export declare const fixedOrigin: (raw: string) => URL;
10
+ /** One-line header values with no control characters are the only labels this package forwards. */
11
+ export declare const headerValueIsSafe: (value: string) => boolean;