@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
package/src/runtime.ts ADDED
@@ -0,0 +1,184 @@
1
+ import {
2
+ acquireProvider,
3
+ routeDiagnostics,
4
+ routeKey,
5
+ spaceForRoute,
6
+ type AcquiredProvider,
7
+ type EmbeddingDiagnostic,
8
+ } from './providers.js';
9
+ import { configuredDefault, configuredRoutes, validateEmbeddingSettings } from './settings.js';
10
+ import { executeCompare, executeEmbeddings } from './execute.js';
11
+ import { EmbeddingsError } from './errors.js';
12
+ import {
13
+ EMBEDDINGS_PROTOCOL_VERSION,
14
+ type EmbeddingCompareResult,
15
+ type EmbeddingContext,
16
+ type EmbeddingRequest,
17
+ type EmbeddingResult,
18
+ type EmbeddingRoute,
19
+ type EmbeddingSettings,
20
+ } from './schemas.js';
21
+
22
+ export interface EmbeddingsRuntime {
23
+ /** Acquire the selected local child at MCP startup; cloud selections start no local process. */
24
+ start(): Promise<void>;
25
+ embed(
26
+ request: EmbeddingRequest,
27
+ options?: { signal?: AbortSignal | undefined; context?: EmbeddingContext | undefined }
28
+ ): Promise<EmbeddingResult>;
29
+ compare(
30
+ request: EmbeddingRequest,
31
+ options?: { signal?: AbortSignal | undefined; context?: EmbeddingContext | undefined }
32
+ ): Promise<EmbeddingCompareResult>;
33
+ close(): Promise<void>;
34
+ }
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
+
52
+ const noSignal = (signal: AbortSignal | undefined): AbortSignal => signal ?? new AbortController().signal;
53
+
54
+ function createRuntime(args: {
55
+ settings: EmbeddingSettings;
56
+ cwd?: string | undefined;
57
+ }): EmbeddingsRuntimeWithDiagnostics {
58
+ const settings = validateEmbeddingSettings(args.settings);
59
+ const defaultRoute = configuredDefault(settings);
60
+ const fallbackRoutes = configuredRoutes(settings, 'fallback');
61
+ const compareRoutes = configuredRoutes(settings, 'compare');
62
+ const acquired = new Map<string, AcquiredProvider>();
63
+ const pending = new Map<string, Promise<AcquiredProvider>>();
64
+ const lateReleases: Promise<void>[] = [];
65
+ const lifetime = new AbortController();
66
+ let closed = false;
67
+ let closing: Promise<void> | undefined;
68
+
69
+ /**
70
+ * Acquisitions belong to the runtime, not to one call. A caller's cancellation only stops waiting;
71
+ * it never releases a shared local child that another call may be using.
72
+ */
73
+ const acquireShared = (route: EmbeddingRoute): Promise<AcquiredProvider> => {
74
+ const key = routeKey(route);
75
+ const cached = acquired.get(key);
76
+ if (cached !== undefined) return Promise.resolve(cached);
77
+ const inFlight = pending.get(key);
78
+ if (inFlight !== undefined) return inFlight;
79
+ const promise = acquireProvider({ settings, route, signal: lifetime.signal })
80
+ .then((entry) => {
81
+ pending.delete(key);
82
+ if (closed || closing !== undefined) {
83
+ lateReleases.push(entry.release());
84
+ throw new Error('The embeddings runtime is closed.');
85
+ }
86
+ acquired.set(key, entry);
87
+ return entry;
88
+ })
89
+ .catch((error: unknown) => {
90
+ pending.delete(key);
91
+ throw error;
92
+ });
93
+ pending.set(key, promise);
94
+ return promise;
95
+ };
96
+
97
+ const acquire = (route: EmbeddingRoute, signal: AbortSignal): Promise<AcquiredProvider> => {
98
+ if (closed || closing !== undefined) return Promise.reject(new Error('The embeddings runtime is closed.'));
99
+ if (signal.aborted) return Promise.reject(new EmbeddingsError('cancelled'));
100
+ let listener: (() => void) | undefined;
101
+ const cancelled = new Promise<never>((_resolve, reject) => {
102
+ listener = () => reject(new EmbeddingsError('cancelled'));
103
+ signal.addEventListener('abort', listener, { once: true });
104
+ });
105
+ return Promise.race([acquireShared(route), cancelled]).finally(() => {
106
+ if (listener !== undefined) signal.removeEventListener('abort', listener);
107
+ });
108
+ };
109
+
110
+ return {
111
+ async start(): Promise<void> {
112
+ if (defaultRoute.provider === 'local') await acquire(defaultRoute, lifetime.signal);
113
+ },
114
+ async embed(request, options) {
115
+ return executeEmbeddings({
116
+ routes: [defaultRoute, ...fallbackRoutes],
117
+ request,
118
+ context: options?.context,
119
+ signal: noSignal(options?.signal),
120
+ allowFallback: true,
121
+ acquire,
122
+ });
123
+ },
124
+ async compare(request, options) {
125
+ return executeCompare({
126
+ routes: compareRoutes,
127
+ request,
128
+ context: options?.context,
129
+ signal: noSignal(options?.signal),
130
+ acquire,
131
+ });
132
+ },
133
+ describe() {
134
+ const defaultDiagnostics = routeDiagnostics(settings, defaultRoute);
135
+ const diagnostics = [...defaultDiagnostics];
136
+ for (const route of fallbackRoutes)
137
+ diagnostics.push(...routeDiagnostics(settings, route).map((entry) => ({
138
+ ...entry,
139
+ severity: 'warning' as const,
140
+ })));
141
+ return {
142
+ schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
143
+ ready: defaultDiagnostics.length === 0,
144
+ selected: defaultRoute,
145
+ space: spaceForRoute(defaultRoute, settings),
146
+ default: defaultRoute,
147
+ fallback: [...fallbackRoutes],
148
+ compare: [...compareRoutes],
149
+ diagnostics,
150
+ };
151
+ },
152
+ close() {
153
+ closing ??= (async () => {
154
+ closed = true;
155
+ lifetime.abort();
156
+ const inFlight = [...pending.values()];
157
+ const entries = [...acquired.values()];
158
+ acquired.clear();
159
+ await Promise.allSettled(inFlight);
160
+ await Promise.allSettled(lateReleases);
161
+ for (const entry of entries) await entry.release();
162
+ pending.clear();
163
+ })();
164
+ return closing;
165
+ },
166
+ };
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
+ }
package/src/schemas.ts ADDED
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Authoritative public schemas for pi-embeddings.
3
+ *
4
+ * Types across the library, Pi extension and MCP server derive from this file. The descriptor shape
5
+ * deliberately matches the stored HighSKU vector space document, so legacy vectors remain compatible
6
+ * without rewriting stored bytes or inventing unknown provenance.
7
+ */
8
+ import { Type, type Static } from 'typebox';
9
+
10
+ export const EMBEDDINGS_SETTINGS_KEY = 'pi-embeddings';
11
+ export const EMBEDDINGS_PROTOCOL_VERSION = 2;
12
+ export const EMBEDDING_FORMAT_VERSION = 'host-display-attributes-v1';
13
+ export const EMBEDDING_DOCUMENT_PREFIX = 'title: none | text: ';
14
+ export const EMBEDDING_NORMALIZATION_VERSION = 'finite-nonzero-l2-v1';
15
+ export const EMBEDDING_CONTEXT_META_KEY = 'pi-embeddings/context';
16
+
17
+ export const EMBEDDING_ROUTE_IDS = [
18
+ 'local',
19
+ 'openai',
20
+ 'sarvam',
21
+ 'gateway',
22
+ 'openrouter',
23
+ 'cloudflare',
24
+ ] as const;
25
+ export type EmbeddingRouteId = (typeof EMBEDDING_ROUTE_IDS)[number];
26
+
27
+ export const GATEWAY_EMBEDDING_MODELS = [
28
+ 'text-embedding-3-small',
29
+ 'openai/text-embedding-3-small',
30
+ ] as const;
31
+
32
+ export const OPENROUTER_EMBEDDING_MODELS = ['openai/text-embedding-3-small'] as const;
33
+ export const CLOUDFLARE_EMBEDDING_MODELS = ['@cf/baai/bge-base-en-v1.5'] as const;
34
+
35
+ const gatewayModelSchema = Type.Union([
36
+ Type.Literal('text-embedding-3-small'),
37
+ Type.Literal('openai/text-embedding-3-small'),
38
+ ]);
39
+
40
+ const openRouterModelSchema = Type.Literal('openai/text-embedding-3-small');
41
+ const cloudflareModelSchema = Type.Literal('@cf/baai/bge-base-en-v1.5');
42
+
43
+ const embeddingErrorCodeSchema = Type.Union([
44
+ Type.Literal('configuration-invalid'),
45
+ Type.Literal('route-unconfigured'),
46
+ Type.Literal('missing-credentials'),
47
+ Type.Literal('http-auth'),
48
+ Type.Literal('http-not-found'),
49
+ Type.Literal('http-rate-limit'),
50
+ Type.Literal('http-forbidden'),
51
+ Type.Literal('http-bad-request'),
52
+ Type.Literal('http-server-error'),
53
+ Type.Literal('transport-failed'),
54
+ Type.Literal('provider-response-invalid'),
55
+ Type.Literal('provider-response-mismatch'),
56
+ Type.Literal('vector-invalid'),
57
+ Type.Literal('vector-zero'),
58
+ Type.Literal('input-empty'),
59
+ Type.Literal('input-too-long'),
60
+ Type.Literal('tokenizer-roundtrip-failed'),
61
+ Type.Literal('attribution-unavailable'),
62
+ Type.Literal('local-resources-unavailable'),
63
+ Type.Literal('local-model-mismatch'),
64
+ Type.Literal('local-runtime-mismatch'),
65
+ Type.Literal('local-startup-failed'),
66
+ Type.Literal('local-cpu-startup-invalid'),
67
+ Type.Literal('cancelled'),
68
+ Type.Literal('unstarted'),
69
+ ]);
70
+
71
+ export const EMBEDDING_ERROR_CODES = [
72
+ 'configuration-invalid',
73
+ 'route-unconfigured',
74
+ 'missing-credentials',
75
+ 'http-auth',
76
+ 'http-not-found',
77
+ 'http-rate-limit',
78
+ 'http-forbidden',
79
+ 'http-bad-request',
80
+ 'http-server-error',
81
+ 'transport-failed',
82
+ 'provider-response-invalid',
83
+ 'provider-response-mismatch',
84
+ 'vector-invalid',
85
+ 'vector-zero',
86
+ 'input-empty',
87
+ 'input-too-long',
88
+ 'tokenizer-roundtrip-failed',
89
+ 'attribution-unavailable',
90
+ 'local-resources-unavailable',
91
+ 'local-model-mismatch',
92
+ 'local-runtime-mismatch',
93
+ 'local-startup-failed',
94
+ 'local-cpu-startup-invalid',
95
+ 'cancelled',
96
+ 'unstarted',
97
+ ] as const;
98
+ export type EmbeddingErrorCode = (typeof EMBEDDING_ERROR_CODES)[number];
99
+
100
+ const embeddingProviderSchema = Type.Union([
101
+ Type.Literal('local'),
102
+ Type.Literal('openai'),
103
+ Type.Literal('sarvam'),
104
+ Type.Literal('gateway'),
105
+ Type.Literal('openrouter'),
106
+ Type.Literal('cloudflare'),
107
+ ]);
108
+
109
+ export const embeddingRouteSchema = Type.Object(
110
+ {
111
+ provider: embeddingProviderSchema,
112
+ model: Type.String({ minLength: 1 }),
113
+ },
114
+ { additionalProperties: false }
115
+ );
116
+
117
+ const spaceCommon = {
118
+ format: Type.Literal(EMBEDDING_FORMAT_VERSION),
119
+ prefix: Type.Literal(EMBEDDING_DOCUMENT_PREFIX),
120
+ normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
121
+ };
122
+
123
+ /**
124
+ * Complete generating-space identity. `provider` is canonical: the gateway route deliberately
125
+ * reports the OpenAI recipe it declares, not its transport alias.
126
+ */
127
+ export const embeddingSpaceSchema = Type.Union([
128
+ Type.Object(
129
+ {
130
+ ...spaceCommon,
131
+ provider: Type.Literal('local'),
132
+ model: Type.Literal('embeddinggemma-2'),
133
+ revision: Type.String({ minLength: 1 }),
134
+ quantization: Type.Literal('Q8_0'),
135
+ runtime: Type.String({ minLength: 1 }),
136
+ dimensions: Type.Literal(768),
137
+ },
138
+ { additionalProperties: false }
139
+ ),
140
+ Type.Object(
141
+ {
142
+ ...spaceCommon,
143
+ provider: Type.Literal('openai'),
144
+ model: Type.Literal('text-embedding-3-small'),
145
+ revision: Type.Null(),
146
+ quantization: Type.Null(),
147
+ runtime: Type.Null(),
148
+ dimensions: Type.Literal(1536),
149
+ },
150
+ { additionalProperties: false }
151
+ ),
152
+ Type.Object(
153
+ {
154
+ ...spaceCommon,
155
+ provider: Type.Literal('sarvam'),
156
+ model: Type.Literal('embeddinggemma-2'),
157
+ revision: Type.Null(),
158
+ quantization: Type.Null(),
159
+ runtime: Type.Literal('sarvam-v2'),
160
+ dimensions: Type.Literal(768),
161
+ },
162
+ { additionalProperties: false }
163
+ ),
164
+ Type.Object(
165
+ {
166
+ ...spaceCommon,
167
+ provider: Type.Literal('cloudflare'),
168
+ model: cloudflareModelSchema,
169
+ revision: Type.Null(),
170
+ quantization: Type.Null(),
171
+ runtime: Type.Literal('cloudflare-workers-ai'),
172
+ dimensions: Type.Literal(768),
173
+ pooling: Type.Union([Type.Literal('mean'), Type.Literal('cls')]),
174
+ },
175
+ { additionalProperties: false }
176
+ ),
177
+ ]);
178
+
179
+ export const embeddingSettingsSchema = Type.Object(
180
+ {
181
+ version: Type.Optional(Type.Literal(1)),
182
+ default: embeddingRouteSchema,
183
+ fallback: Type.Optional(Type.Array(embeddingRouteSchema)),
184
+ compare: Type.Optional(Type.Array(embeddingRouteSchema)),
185
+ providers: Type.Optional(
186
+ Type.Object(
187
+ {
188
+ local: Type.Optional(
189
+ Type.Object(
190
+ {
191
+ executable: Type.String({ minLength: 1 }),
192
+ modelPath: Type.String({ minLength: 1 }),
193
+ port: Type.Optional(Type.Integer({ minimum: 1, maximum: 65535 })),
194
+ },
195
+ { additionalProperties: false }
196
+ )
197
+ ),
198
+ openai: Type.Optional(
199
+ Type.Object(
200
+ { apiKey: Type.Optional(Type.String({ minLength: 1 })) },
201
+ { additionalProperties: false }
202
+ )
203
+ ),
204
+ sarvam: Type.Optional(
205
+ Type.Object(
206
+ { apiKey: Type.Optional(Type.String({ minLength: 1 })) },
207
+ { additionalProperties: false }
208
+ )
209
+ ),
210
+ gateway: Type.Optional(
211
+ Type.Object(
212
+ {
213
+ baseUrl: Type.String({ minLength: 1 }),
214
+ apiKey: Type.String({ minLength: 1 }),
215
+ model: gatewayModelSchema,
216
+ stage: Type.Union([Type.Literal('dev'), Type.Literal('prod')]),
217
+ },
218
+ { additionalProperties: false }
219
+ )
220
+ ),
221
+ openrouter: Type.Optional(
222
+ Type.Object(
223
+ { apiKey: Type.Optional(Type.String({ minLength: 1 })) },
224
+ { additionalProperties: false }
225
+ )
226
+ ),
227
+ cloudflare: Type.Optional(
228
+ Type.Object(
229
+ {
230
+ accountId: Type.Optional(Type.String({ minLength: 1 })),
231
+ apiKey: Type.Optional(Type.String({ minLength: 1 })),
232
+ gatewayId: Type.Optional(Type.String({ minLength: 1 })),
233
+ model: Type.Optional(cloudflareModelSchema),
234
+ pooling: Type.Optional(
235
+ Type.Union([Type.Literal('mean'), Type.Literal('cls')])
236
+ ),
237
+ },
238
+ { additionalProperties: false }
239
+ )
240
+ ),
241
+ },
242
+ { additionalProperties: false }
243
+ )
244
+ ),
245
+ },
246
+ { additionalProperties: false }
247
+ );
248
+
249
+ export const embeddingRequestSchema = Type.Object(
250
+ {
251
+ inputs: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
252
+ },
253
+ { additionalProperties: false }
254
+ );
255
+
256
+ /** Generic, host-owned attribution. It is never a model argument or proof of ownership. */
257
+ export const embeddingContextSchema = Type.Object(
258
+ {
259
+ endUser: Type.String({ minLength: 1 }),
260
+ tags: Type.Array(Type.String({ minLength: 1 })),
261
+ },
262
+ { additionalProperties: false }
263
+ );
264
+
265
+ export const embeddingUsageSchema = Type.Object(
266
+ {
267
+ providerReportedInputTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
268
+ preparedInputTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
269
+ billedTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
270
+ },
271
+ { additionalProperties: false }
272
+ );
273
+
274
+ export const embeddingAttemptSchema = Type.Object(
275
+ {
276
+ id: Type.String({ minLength: 1 }),
277
+ route: embeddingProviderSchema,
278
+ model: Type.String({ minLength: 1 }),
279
+ routeIndex: Type.Integer({ minimum: 0 }),
280
+ status: Type.Union([Type.Literal('success'), Type.Literal('error'), Type.Literal('cancelled')]),
281
+ usage: Type.Union([embeddingUsageSchema, Type.Null()]),
282
+ errorCode: Type.Optional(embeddingErrorCodeSchema),
283
+ },
284
+ { additionalProperties: false }
285
+ );
286
+
287
+ const successOutcomeSchema = Type.Object(
288
+ {
289
+ status: Type.Literal('success'),
290
+ index: Type.Integer({ minimum: 0 }),
291
+ vector: Type.Array(Type.Number()),
292
+ route: embeddingProviderSchema,
293
+ model: Type.String({ minLength: 1 }),
294
+ space: embeddingSpaceSchema,
295
+ attemptId: Type.String({ minLength: 1 }),
296
+ normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
297
+ },
298
+ { additionalProperties: false }
299
+ );
300
+
301
+ const errorOutcomeSchema = Type.Object(
302
+ {
303
+ status: Type.Literal('error'),
304
+ index: Type.Integer({ minimum: 0 }),
305
+ code: embeddingErrorCodeSchema,
306
+ attemptId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
307
+ },
308
+ { additionalProperties: false }
309
+ );
310
+
311
+ export const embeddingOutcomeSchema = Type.Union([successOutcomeSchema, errorOutcomeSchema]);
312
+
313
+ /**
314
+ * Actual generating identity observed on successful outcomes. `generations` is the complete set;
315
+ * the singular fields are populated only when every successful vector came from one generation.
316
+ */
317
+ export const embeddingGenerationSchema = Type.Object(
318
+ {
319
+ provider: embeddingProviderSchema,
320
+ model: Type.String({ minLength: 1 }),
321
+ space: embeddingSpaceSchema,
322
+ },
323
+ { additionalProperties: false }
324
+ );
325
+
326
+ export const embeddingResultSchema = Type.Object(
327
+ {
328
+ schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
329
+ provider: Type.Union([embeddingProviderSchema, Type.Null()]),
330
+ model: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
331
+ space: Type.Union([embeddingSpaceSchema, Type.Null()]),
332
+ generations: Type.Array(embeddingGenerationSchema),
333
+ outcomes: Type.Array(embeddingOutcomeSchema),
334
+ attempts: Type.Array(embeddingAttemptSchema),
335
+ },
336
+ { additionalProperties: false }
337
+ );
338
+
339
+ export const embeddingCompareEntrySchema = Type.Object(
340
+ {
341
+ route: embeddingProviderSchema,
342
+ model: Type.String({ minLength: 1 }),
343
+ status: Type.Union([Type.Literal('success'), Type.Literal('error'), Type.Literal('cancelled')]),
344
+ result: embeddingResultSchema,
345
+ },
346
+ { additionalProperties: false }
347
+ );
348
+
349
+ export const embeddingCompareResultSchema = Type.Object(
350
+ {
351
+ schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
352
+ entries: Type.Array(embeddingCompareEntrySchema),
353
+ },
354
+ { additionalProperties: false }
355
+ );
356
+
357
+ export type EmbeddingSettings = Static<typeof embeddingSettingsSchema>;
358
+ export type EmbeddingRoute = Static<typeof embeddingRouteSchema>;
359
+ export type EmbeddingSpace = Static<typeof embeddingSpaceSchema>;
360
+ export type EmbeddingRequest = Static<typeof embeddingRequestSchema>;
361
+ export type EmbeddingContext = Static<typeof embeddingContextSchema>;
362
+ export type EmbeddingUsage = Static<typeof embeddingUsageSchema>;
363
+ export type EmbeddingAttempt = Static<typeof embeddingAttemptSchema>;
364
+ export type EmbeddingOutcome = Static<typeof embeddingOutcomeSchema>;
365
+ export type EmbeddingGeneration = Static<typeof embeddingGenerationSchema>;
366
+ export type EmbeddingResult = Static<typeof embeddingResultSchema>;
367
+ export type EmbeddingCompareEntry = Static<typeof embeddingCompareEntrySchema>;
368
+ export type EmbeddingCompareResult = Static<typeof embeddingCompareResultSchema>;
@@ -0,0 +1,96 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
3
+ import { withFileMutationQueue } from '@earendil-works/pi-coding-agent';
4
+ import { join, resolve } from 'node:path';
5
+ import { validateEmbeddingSettings } from './settings.js';
6
+ import { EMBEDDINGS_SETTINGS_KEY, type EmbeddingRoute } from './schemas.js';
7
+
8
+ export class EmbeddingsSettingsWriteError extends Error {}
9
+
10
+ /** Update only the trusted project's `pi-embeddings.default`, preserving every unrelated key. */
11
+ export function updateProjectEmbeddingSettings({
12
+ cwd,
13
+ projectTrusted,
14
+ route,
15
+ }: {
16
+ cwd: string;
17
+ projectTrusted: boolean;
18
+ route: EmbeddingRoute;
19
+ }): Promise<void> {
20
+ validateEmbeddingSettings({ default: route });
21
+ const settingsPath = resolve(cwd, '.pi', 'settings.json');
22
+ return withFileMutationQueue(settingsPath, () =>
23
+ updateProjectEmbeddingSettingsNow({ cwd, projectTrusted, route })
24
+ );
25
+ }
26
+
27
+ async function updateProjectEmbeddingSettingsNow(args: {
28
+ cwd: string;
29
+ projectTrusted: boolean;
30
+ route: EmbeddingRoute;
31
+ }): Promise<void> {
32
+ if (!args.projectTrusted)
33
+ throw new EmbeddingsSettingsWriteError(
34
+ 'Project settings are not trusted. Trust this project before changing .pi/settings.json.'
35
+ );
36
+ const settingsDir = join(args.cwd, '.pi');
37
+ const settingsPath = join(settingsDir, 'settings.json');
38
+ await rejectSymlink(settingsDir);
39
+ await mkdir(settingsDir, { recursive: true, mode: 0o700 });
40
+ await rejectSymlink(settingsPath);
41
+
42
+ let root: Record<string, unknown> = {};
43
+ let mode = 0o600;
44
+ try {
45
+ const [text, stat] = await Promise.all([readFile(settingsPath, 'utf8'), lstat(settingsPath)]);
46
+ const parsed: unknown = JSON.parse(text);
47
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
48
+ throw new EmbeddingsSettingsWriteError('Project settings must contain a JSON object.');
49
+ root = { ...parsed } as Record<string, unknown>;
50
+ mode = stat.mode & 0o777;
51
+ } catch (error) {
52
+ if (error instanceof EmbeddingsSettingsWriteError) throw error;
53
+ const code = (error as NodeJS.ErrnoException).code;
54
+ if (code !== 'ENOENT') {
55
+ if (error instanceof SyntaxError)
56
+ throw new EmbeddingsSettingsWriteError(
57
+ 'Project settings contain invalid JSON. Fix .pi/settings.json before changing embedding settings.'
58
+ );
59
+ throw new EmbeddingsSettingsWriteError('Could not read project settings.');
60
+ }
61
+ }
62
+
63
+ const current = root[EMBEDDINGS_SETTINGS_KEY];
64
+ if (current !== undefined && (typeof current !== 'object' || current === null || Array.isArray(current)))
65
+ throw new EmbeddingsSettingsWriteError(
66
+ 'pi-embeddings settings must contain a JSON object.'
67
+ );
68
+ root[EMBEDDINGS_SETTINGS_KEY] = { ...(current ?? {}), default: args.route };
69
+
70
+ const tempPath = join(settingsDir, `.settings.json.pi-embeddings-${randomUUID()}`);
71
+ let handle: Awaited<ReturnType<typeof open>> | undefined;
72
+ let created = false;
73
+ try {
74
+ handle = await open(tempPath, 'wx', mode);
75
+ created = true;
76
+ await handle.writeFile(`${JSON.stringify(root, null, 2)}\n`, 'utf8');
77
+ await handle.close();
78
+ handle = undefined;
79
+ await rename(tempPath, settingsPath);
80
+ } catch {
81
+ if (handle) await handle.close().catch(() => undefined);
82
+ if (created) await unlink(tempPath).catch(() => undefined);
83
+ throw new EmbeddingsSettingsWriteError('Could not update project settings.');
84
+ }
85
+ }
86
+
87
+ async function rejectSymlink(path: string): Promise<void> {
88
+ try {
89
+ if ((await lstat(path)).isSymbolicLink())
90
+ throw new EmbeddingsSettingsWriteError('The project settings path must not be a symbolic link.');
91
+ } catch (error) {
92
+ if (error instanceof EmbeddingsSettingsWriteError) throw error;
93
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
94
+ throw new EmbeddingsSettingsWriteError('Could not inspect project settings.');
95
+ }
96
+ }