@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.
- package/LICENSE +201 -0
- package/README.md +87 -2
- package/dist/errors.d.ts +21 -0
- package/dist/errors.js +41 -0
- package/dist/execute.d.ts +25 -0
- package/dist/execute.js +229 -0
- package/dist/extension.d.ts +2 -0
- package/dist/extension.js +195 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/local-runtime.d.ts +14 -0
- package/dist/local-runtime.js +246 -0
- package/dist/mcp-cli.d.ts +2 -0
- package/dist/mcp-cli.js +46 -0
- package/dist/mcp-server.d.ts +23 -0
- package/dist/mcp-server.js +154 -0
- package/dist/provider-http.d.ts +11 -0
- package/dist/provider-http.js +60 -0
- package/dist/provider-types.d.ts +30 -0
- package/dist/provider-types.js +1 -0
- package/dist/providers.d.ts +18 -0
- package/dist/providers.js +265 -0
- package/dist/response.d.ts +11 -0
- package/dist/response.js +62 -0
- package/dist/runtime.d.ts +19 -0
- package/dist/runtime.js +121 -0
- package/dist/schemas.d.ts +431 -0
- package/dist/schemas.js +214 -0
- package/dist/settings-write.d.ts +9 -0
- package/dist/settings-write.js +77 -0
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +97 -0
- package/dist/tool-contracts.d.ts +200 -0
- package/dist/tool-contracts.js +19 -0
- package/package.json +83 -4
- package/src/errors.ts +52 -0
- package/src/execute.ts +261 -0
- package/src/extension.ts +245 -0
- package/src/index.ts +37 -0
- package/src/local-runtime.ts +273 -0
- package/src/mcp-cli.ts +52 -0
- package/src/mcp-server.ts +206 -0
- package/src/provider-http.ts +67 -0
- package/src/provider-types.ts +33 -0
- package/src/providers.ts +335 -0
- package/src/response.ts +74 -0
- package/src/runtime.ts +146 -0
- package/src/schemas.ts +326 -0
- package/src/settings-write.ts +96 -0
- package/src/settings.ts +115 -0
- package/src/tool-contracts.ts +34 -0
|
@@ -0,0 +1,195 @@
|
|
|
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 { createEmbeddingsRuntime } 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, EMBEDDINGS_DESCRIBE_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION, embedCompareOutput, embedCompareParameters, embedOutput, embedParameters, embeddingsDescribeOutput, embeddingsDescribeParameters, } 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 = createEmbeddingsRuntime({ 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
|
+
'Describe reports configuration and readiness; it does not reserve a generating space or prove a caller can store the result.',
|
|
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.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
|
+
pi.registerCommand('embeddings', {
|
|
125
|
+
description: 'Embeddings: /embeddings list | doctor | reload | use <provider> <model> | compare <text>. list, doctor and describe make no inference calls.',
|
|
126
|
+
handler: async (args, ctx) => {
|
|
127
|
+
const raw = (args ?? '').trim();
|
|
128
|
+
const parts = raw.split(/\s+/).filter(Boolean);
|
|
129
|
+
const command = parts[0] ?? 'list';
|
|
130
|
+
try {
|
|
131
|
+
if (command === 'list' || command === 'doctor' || command === 'describe' || command === 'status') {
|
|
132
|
+
if (parts.length !== 1)
|
|
133
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
134
|
+
const active = currentRuntime(ctx);
|
|
135
|
+
const described = active.describe();
|
|
136
|
+
if (command === 'doctor') {
|
|
137
|
+
reply(pi, ctx, described.diagnostics.length === 0
|
|
138
|
+
? 'Embeddings settings are valid. No provider call was made.'
|
|
139
|
+
: described.diagnostics.map((entry) => `${entry.severity}: ${entry.code}`).join('\n'));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
reply(pi, ctx, JSON.stringify({
|
|
143
|
+
selected: described.selected,
|
|
144
|
+
space: described.space,
|
|
145
|
+
default: described.default,
|
|
146
|
+
fallback: described.fallback,
|
|
147
|
+
compare: described.compare,
|
|
148
|
+
ready: described.ready,
|
|
149
|
+
}, null, 2));
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (command === 'reload') {
|
|
153
|
+
if (parts.length !== 1)
|
|
154
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
155
|
+
const next = loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx));
|
|
156
|
+
await refresh(next, ctx.cwd);
|
|
157
|
+
reply(pi, ctx, `${EMBEDDINGS_SETTINGS_KEY} settings reloaded. No inference was run.`);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (command === 'use') {
|
|
161
|
+
if (parts.length !== 3)
|
|
162
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
163
|
+
const route = { provider: parts[1], model: parts[2] ?? '' };
|
|
164
|
+
validateEmbeddingSettings({ default: route });
|
|
165
|
+
await updateProjectEmbeddingSettings({
|
|
166
|
+
cwd: ctx.cwd,
|
|
167
|
+
projectTrusted: isProjectTrusted(ctx),
|
|
168
|
+
route,
|
|
169
|
+
});
|
|
170
|
+
await refresh(loadEmbeddingSettings(ctx.cwd, isProjectTrusted(ctx)), ctx.cwd);
|
|
171
|
+
reply(pi, ctx, `Selected ${route.provider}/${route.model} in trusted project settings.`);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (command === 'compare') {
|
|
175
|
+
const text = raw.slice('compare'.length).trim();
|
|
176
|
+
if (text === '')
|
|
177
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
178
|
+
const result = await currentRuntime(ctx).compare({ inputs: [text] }, signalOptions(ctx.signal ?? undefined));
|
|
179
|
+
reply(pi, ctx, `Compared ${result.entries.length} configured route(s).\n${summary(result.entries[0]?.result ?? { outcomes: [] })}`);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
reply(pi, ctx, 'Usage: /embeddings list | doctor | reload | use <provider> <model> | compare <text>');
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
reply(pi, ctx, `Embeddings command failed: ${codeOf(error)}`);
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
function reply(pi, ctx, text) {
|
|
191
|
+
if (ctx.hasUI)
|
|
192
|
+
ctx.ui.notify(text, 'info');
|
|
193
|
+
else
|
|
194
|
+
pi.sendMessage({ customType: 'pi-embeddings', content: text, display: true }, { triggerTurn: false });
|
|
195
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -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, EmbeddingResult, EmbeddingCompareEntry, EmbeddingCompareResult, EmbeddingDiagnostic, EmbeddingDescribe, 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
|
+
}
|
package/dist/mcp-cli.js
ADDED
|
@@ -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>;
|