@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
package/src/schemas.ts
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
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 = 1;
|
|
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 = ['local', 'openai', 'sarvam', 'gateway'] as const;
|
|
18
|
+
export type EmbeddingRouteId = (typeof EMBEDDING_ROUTE_IDS)[number];
|
|
19
|
+
|
|
20
|
+
export const GATEWAY_EMBEDDING_MODELS = [
|
|
21
|
+
'text-embedding-3-small',
|
|
22
|
+
'openai/text-embedding-3-small',
|
|
23
|
+
] as const;
|
|
24
|
+
|
|
25
|
+
const gatewayModelSchema = Type.Union([
|
|
26
|
+
Type.Literal('text-embedding-3-small'),
|
|
27
|
+
Type.Literal('openai/text-embedding-3-small'),
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
const embeddingErrorCodeSchema = Type.Union([
|
|
31
|
+
Type.Literal('configuration-invalid'),
|
|
32
|
+
Type.Literal('route-unconfigured'),
|
|
33
|
+
Type.Literal('missing-credentials'),
|
|
34
|
+
Type.Literal('http-auth'),
|
|
35
|
+
Type.Literal('http-not-found'),
|
|
36
|
+
Type.Literal('http-rate-limit'),
|
|
37
|
+
Type.Literal('http-forbidden'),
|
|
38
|
+
Type.Literal('http-bad-request'),
|
|
39
|
+
Type.Literal('http-server-error'),
|
|
40
|
+
Type.Literal('transport-failed'),
|
|
41
|
+
Type.Literal('provider-response-invalid'),
|
|
42
|
+
Type.Literal('provider-response-mismatch'),
|
|
43
|
+
Type.Literal('vector-invalid'),
|
|
44
|
+
Type.Literal('vector-zero'),
|
|
45
|
+
Type.Literal('input-empty'),
|
|
46
|
+
Type.Literal('input-too-long'),
|
|
47
|
+
Type.Literal('tokenizer-roundtrip-failed'),
|
|
48
|
+
Type.Literal('attribution-unavailable'),
|
|
49
|
+
Type.Literal('local-resources-unavailable'),
|
|
50
|
+
Type.Literal('local-model-mismatch'),
|
|
51
|
+
Type.Literal('local-runtime-mismatch'),
|
|
52
|
+
Type.Literal('local-startup-failed'),
|
|
53
|
+
Type.Literal('local-cpu-startup-invalid'),
|
|
54
|
+
Type.Literal('cancelled'),
|
|
55
|
+
Type.Literal('unstarted'),
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
export const EMBEDDING_ERROR_CODES = [
|
|
59
|
+
'configuration-invalid',
|
|
60
|
+
'route-unconfigured',
|
|
61
|
+
'missing-credentials',
|
|
62
|
+
'http-auth',
|
|
63
|
+
'http-not-found',
|
|
64
|
+
'http-rate-limit',
|
|
65
|
+
'http-forbidden',
|
|
66
|
+
'http-bad-request',
|
|
67
|
+
'http-server-error',
|
|
68
|
+
'transport-failed',
|
|
69
|
+
'provider-response-invalid',
|
|
70
|
+
'provider-response-mismatch',
|
|
71
|
+
'vector-invalid',
|
|
72
|
+
'vector-zero',
|
|
73
|
+
'input-empty',
|
|
74
|
+
'input-too-long',
|
|
75
|
+
'tokenizer-roundtrip-failed',
|
|
76
|
+
'attribution-unavailable',
|
|
77
|
+
'local-resources-unavailable',
|
|
78
|
+
'local-model-mismatch',
|
|
79
|
+
'local-runtime-mismatch',
|
|
80
|
+
'local-startup-failed',
|
|
81
|
+
'local-cpu-startup-invalid',
|
|
82
|
+
'cancelled',
|
|
83
|
+
'unstarted',
|
|
84
|
+
] as const;
|
|
85
|
+
export type EmbeddingErrorCode = (typeof EMBEDDING_ERROR_CODES)[number];
|
|
86
|
+
|
|
87
|
+
const embeddingProviderSchema = Type.Union([
|
|
88
|
+
Type.Literal('local'),
|
|
89
|
+
Type.Literal('openai'),
|
|
90
|
+
Type.Literal('sarvam'),
|
|
91
|
+
Type.Literal('gateway'),
|
|
92
|
+
]);
|
|
93
|
+
|
|
94
|
+
export const embeddingRouteSchema = Type.Object(
|
|
95
|
+
{
|
|
96
|
+
provider: embeddingProviderSchema,
|
|
97
|
+
model: Type.String({ minLength: 1 }),
|
|
98
|
+
},
|
|
99
|
+
{ additionalProperties: false }
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
const spaceCommon = {
|
|
103
|
+
format: Type.Literal(EMBEDDING_FORMAT_VERSION),
|
|
104
|
+
prefix: Type.Literal(EMBEDDING_DOCUMENT_PREFIX),
|
|
105
|
+
normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Complete generating-space identity. `provider` is canonical: the gateway route deliberately
|
|
110
|
+
* reports the OpenAI recipe it declares, not its transport alias.
|
|
111
|
+
*/
|
|
112
|
+
export const embeddingSpaceSchema = Type.Union([
|
|
113
|
+
Type.Object(
|
|
114
|
+
{
|
|
115
|
+
...spaceCommon,
|
|
116
|
+
provider: Type.Literal('local'),
|
|
117
|
+
model: Type.Literal('embeddinggemma-2'),
|
|
118
|
+
revision: Type.String({ minLength: 1 }),
|
|
119
|
+
quantization: Type.Literal('Q8_0'),
|
|
120
|
+
runtime: Type.String({ minLength: 1 }),
|
|
121
|
+
dimensions: Type.Literal(768),
|
|
122
|
+
},
|
|
123
|
+
{ additionalProperties: false }
|
|
124
|
+
),
|
|
125
|
+
Type.Object(
|
|
126
|
+
{
|
|
127
|
+
...spaceCommon,
|
|
128
|
+
provider: Type.Literal('openai'),
|
|
129
|
+
model: Type.Literal('text-embedding-3-small'),
|
|
130
|
+
revision: Type.Null(),
|
|
131
|
+
quantization: Type.Null(),
|
|
132
|
+
runtime: Type.Null(),
|
|
133
|
+
dimensions: Type.Literal(1536),
|
|
134
|
+
},
|
|
135
|
+
{ additionalProperties: false }
|
|
136
|
+
),
|
|
137
|
+
Type.Object(
|
|
138
|
+
{
|
|
139
|
+
...spaceCommon,
|
|
140
|
+
provider: Type.Literal('sarvam'),
|
|
141
|
+
model: Type.Literal('embeddinggemma-2'),
|
|
142
|
+
revision: Type.Null(),
|
|
143
|
+
quantization: Type.Null(),
|
|
144
|
+
runtime: Type.Literal('sarvam-v2'),
|
|
145
|
+
dimensions: Type.Literal(768),
|
|
146
|
+
},
|
|
147
|
+
{ additionalProperties: false }
|
|
148
|
+
),
|
|
149
|
+
]);
|
|
150
|
+
|
|
151
|
+
export const embeddingSettingsSchema = Type.Object(
|
|
152
|
+
{
|
|
153
|
+
version: Type.Optional(Type.Literal(1)),
|
|
154
|
+
default: embeddingRouteSchema,
|
|
155
|
+
fallback: Type.Optional(Type.Array(embeddingRouteSchema)),
|
|
156
|
+
compare: Type.Optional(Type.Array(embeddingRouteSchema)),
|
|
157
|
+
providers: Type.Optional(
|
|
158
|
+
Type.Object(
|
|
159
|
+
{
|
|
160
|
+
local: Type.Optional(
|
|
161
|
+
Type.Object(
|
|
162
|
+
{
|
|
163
|
+
executable: Type.String({ minLength: 1 }),
|
|
164
|
+
modelPath: Type.String({ minLength: 1 }),
|
|
165
|
+
port: Type.Optional(Type.Integer({ minimum: 1, maximum: 65535 })),
|
|
166
|
+
},
|
|
167
|
+
{ additionalProperties: false }
|
|
168
|
+
)
|
|
169
|
+
),
|
|
170
|
+
openai: Type.Optional(
|
|
171
|
+
Type.Object(
|
|
172
|
+
{ apiKey: Type.Optional(Type.String({ minLength: 1 })) },
|
|
173
|
+
{ additionalProperties: false }
|
|
174
|
+
)
|
|
175
|
+
),
|
|
176
|
+
sarvam: Type.Optional(
|
|
177
|
+
Type.Object(
|
|
178
|
+
{ apiKey: Type.Optional(Type.String({ minLength: 1 })) },
|
|
179
|
+
{ additionalProperties: false }
|
|
180
|
+
)
|
|
181
|
+
),
|
|
182
|
+
gateway: Type.Optional(
|
|
183
|
+
Type.Object(
|
|
184
|
+
{
|
|
185
|
+
baseUrl: Type.String({ minLength: 1 }),
|
|
186
|
+
apiKey: Type.String({ minLength: 1 }),
|
|
187
|
+
model: gatewayModelSchema,
|
|
188
|
+
stage: Type.Union([Type.Literal('dev'), Type.Literal('prod')]),
|
|
189
|
+
},
|
|
190
|
+
{ additionalProperties: false }
|
|
191
|
+
)
|
|
192
|
+
),
|
|
193
|
+
},
|
|
194
|
+
{ additionalProperties: false }
|
|
195
|
+
)
|
|
196
|
+
),
|
|
197
|
+
},
|
|
198
|
+
{ additionalProperties: false }
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
export const embeddingRequestSchema = Type.Object(
|
|
202
|
+
{
|
|
203
|
+
inputs: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
204
|
+
},
|
|
205
|
+
{ additionalProperties: false }
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
/** Generic, host-owned attribution. It is never a model argument or proof of ownership. */
|
|
209
|
+
export const embeddingContextSchema = Type.Object(
|
|
210
|
+
{
|
|
211
|
+
endUser: Type.String({ minLength: 1 }),
|
|
212
|
+
tags: Type.Array(Type.String({ minLength: 1 })),
|
|
213
|
+
},
|
|
214
|
+
{ additionalProperties: false }
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
export const embeddingUsageSchema = Type.Object(
|
|
218
|
+
{
|
|
219
|
+
providerReportedInputTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
|
|
220
|
+
preparedInputTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
|
|
221
|
+
billedTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
|
|
222
|
+
},
|
|
223
|
+
{ additionalProperties: false }
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
export const embeddingAttemptSchema = Type.Object(
|
|
227
|
+
{
|
|
228
|
+
id: Type.String({ minLength: 1 }),
|
|
229
|
+
route: embeddingProviderSchema,
|
|
230
|
+
model: Type.String({ minLength: 1 }),
|
|
231
|
+
routeIndex: Type.Integer({ minimum: 0 }),
|
|
232
|
+
status: Type.Union([Type.Literal('success'), Type.Literal('error'), Type.Literal('cancelled')]),
|
|
233
|
+
usage: Type.Union([embeddingUsageSchema, Type.Null()]),
|
|
234
|
+
errorCode: Type.Optional(embeddingErrorCodeSchema),
|
|
235
|
+
},
|
|
236
|
+
{ additionalProperties: false }
|
|
237
|
+
);
|
|
238
|
+
|
|
239
|
+
const successOutcomeSchema = Type.Object(
|
|
240
|
+
{
|
|
241
|
+
status: Type.Literal('success'),
|
|
242
|
+
index: Type.Integer({ minimum: 0 }),
|
|
243
|
+
vector: Type.Array(Type.Number()),
|
|
244
|
+
route: embeddingProviderSchema,
|
|
245
|
+
model: Type.String({ minLength: 1 }),
|
|
246
|
+
space: embeddingSpaceSchema,
|
|
247
|
+
attemptId: Type.String({ minLength: 1 }),
|
|
248
|
+
normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
|
|
249
|
+
},
|
|
250
|
+
{ additionalProperties: false }
|
|
251
|
+
);
|
|
252
|
+
|
|
253
|
+
const errorOutcomeSchema = Type.Object(
|
|
254
|
+
{
|
|
255
|
+
status: Type.Literal('error'),
|
|
256
|
+
index: Type.Integer({ minimum: 0 }),
|
|
257
|
+
code: embeddingErrorCodeSchema,
|
|
258
|
+
attemptId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
|
|
259
|
+
},
|
|
260
|
+
{ additionalProperties: false }
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
export const embeddingOutcomeSchema = Type.Union([successOutcomeSchema, errorOutcomeSchema]);
|
|
264
|
+
|
|
265
|
+
export const embeddingResultSchema = Type.Object(
|
|
266
|
+
{
|
|
267
|
+
schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
|
|
268
|
+
outcomes: Type.Array(embeddingOutcomeSchema),
|
|
269
|
+
attempts: Type.Array(embeddingAttemptSchema),
|
|
270
|
+
},
|
|
271
|
+
{ additionalProperties: false }
|
|
272
|
+
);
|
|
273
|
+
|
|
274
|
+
export const embeddingCompareEntrySchema = Type.Object(
|
|
275
|
+
{
|
|
276
|
+
route: embeddingProviderSchema,
|
|
277
|
+
model: Type.String({ minLength: 1 }),
|
|
278
|
+
status: Type.Union([Type.Literal('success'), Type.Literal('error'), Type.Literal('cancelled')]),
|
|
279
|
+
result: embeddingResultSchema,
|
|
280
|
+
},
|
|
281
|
+
{ additionalProperties: false }
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
export const embeddingCompareResultSchema = Type.Object(
|
|
285
|
+
{
|
|
286
|
+
schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
|
|
287
|
+
entries: Type.Array(embeddingCompareEntrySchema),
|
|
288
|
+
},
|
|
289
|
+
{ additionalProperties: false }
|
|
290
|
+
);
|
|
291
|
+
|
|
292
|
+
export const embeddingDiagnosticSchema = Type.Object(
|
|
293
|
+
{
|
|
294
|
+
code: Type.String({ minLength: 1 }),
|
|
295
|
+
severity: Type.Union([Type.Literal('error'), Type.Literal('warning'), Type.Literal('info')]),
|
|
296
|
+
},
|
|
297
|
+
{ additionalProperties: false }
|
|
298
|
+
);
|
|
299
|
+
|
|
300
|
+
export const embeddingDescribeSchema = Type.Object(
|
|
301
|
+
{
|
|
302
|
+
schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
|
|
303
|
+
ready: Type.Boolean(),
|
|
304
|
+
selected: embeddingRouteSchema,
|
|
305
|
+
space: Type.Union([embeddingSpaceSchema, Type.Null()]),
|
|
306
|
+
default: embeddingRouteSchema,
|
|
307
|
+
fallback: Type.Array(embeddingRouteSchema),
|
|
308
|
+
compare: Type.Array(embeddingRouteSchema),
|
|
309
|
+
diagnostics: Type.Array(embeddingDiagnosticSchema),
|
|
310
|
+
},
|
|
311
|
+
{ additionalProperties: false }
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
export type EmbeddingSettings = Static<typeof embeddingSettingsSchema>;
|
|
315
|
+
export type EmbeddingRoute = Static<typeof embeddingRouteSchema>;
|
|
316
|
+
export type EmbeddingSpace = Static<typeof embeddingSpaceSchema>;
|
|
317
|
+
export type EmbeddingRequest = Static<typeof embeddingRequestSchema>;
|
|
318
|
+
export type EmbeddingContext = Static<typeof embeddingContextSchema>;
|
|
319
|
+
export type EmbeddingUsage = Static<typeof embeddingUsageSchema>;
|
|
320
|
+
export type EmbeddingAttempt = Static<typeof embeddingAttemptSchema>;
|
|
321
|
+
export type EmbeddingOutcome = Static<typeof embeddingOutcomeSchema>;
|
|
322
|
+
export type EmbeddingResult = Static<typeof embeddingResultSchema>;
|
|
323
|
+
export type EmbeddingCompareEntry = Static<typeof embeddingCompareEntrySchema>;
|
|
324
|
+
export type EmbeddingCompareResult = Static<typeof embeddingCompareResultSchema>;
|
|
325
|
+
export type EmbeddingDiagnostic = Static<typeof embeddingDiagnosticSchema>;
|
|
326
|
+
export type EmbeddingDescribe = Static<typeof embeddingDescribeSchema>;
|
|
@@ -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
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { loadPiSettings, resolveConfigDir } from '@amaster.ai/pi-shared/settings';
|
|
5
|
+
import { Value } from 'typebox/value';
|
|
6
|
+
import { EmbeddingsError } from './errors.js';
|
|
7
|
+
import {
|
|
8
|
+
EMBEDDINGS_SETTINGS_KEY,
|
|
9
|
+
GATEWAY_EMBEDDING_MODELS,
|
|
10
|
+
embeddingSettingsSchema,
|
|
11
|
+
type EmbeddingRoute,
|
|
12
|
+
type EmbeddingSettings,
|
|
13
|
+
} from './schemas.js';
|
|
14
|
+
|
|
15
|
+
const MODELS_BY_PROVIDER: Readonly<Record<EmbeddingRoute['provider'], readonly string[]>> = {
|
|
16
|
+
local: ['embeddinggemma-2'],
|
|
17
|
+
openai: ['text-embedding-3-small'],
|
|
18
|
+
sarvam: ['embeddinggemma-2'],
|
|
19
|
+
gateway: GATEWAY_EMBEDDING_MODELS,
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const isEmbeddingSettings = (value: unknown): value is EmbeddingSettings =>
|
|
23
|
+
Value.Check(embeddingSettingsSchema, value);
|
|
24
|
+
|
|
25
|
+
function configuration(message: EmbeddingErrorCodeMessage): never {
|
|
26
|
+
throw new EmbeddingsError(message);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type EmbeddingErrorCodeMessage = ConstructorParameters<typeof EmbeddingsError>[0];
|
|
30
|
+
|
|
31
|
+
function assertRoute(value: unknown, location: string): EmbeddingRoute {
|
|
32
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
33
|
+
return configuration('configuration-invalid');
|
|
34
|
+
const record = value as Record<string, unknown>;
|
|
35
|
+
const provider = record.provider;
|
|
36
|
+
const model = record.model;
|
|
37
|
+
if (typeof provider !== 'string' || typeof model !== 'string' || model.length === 0)
|
|
38
|
+
return configuration('configuration-invalid');
|
|
39
|
+
if (!Object.hasOwn(MODELS_BY_PROVIDER, provider))
|
|
40
|
+
return configuration('configuration-invalid');
|
|
41
|
+
const allowed = MODELS_BY_PROVIDER[provider as EmbeddingRoute['provider']];
|
|
42
|
+
if (allowed === undefined || !allowed.includes(model))
|
|
43
|
+
return configuration('configuration-invalid');
|
|
44
|
+
return { provider: provider as EmbeddingRoute['provider'], model };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Validate the whole settings object before any route is resolved or inference is attempted. */
|
|
48
|
+
export function validateEmbeddingSettings(value: unknown): EmbeddingSettings {
|
|
49
|
+
if (!isEmbeddingSettings(value)) return configuration('configuration-invalid');
|
|
50
|
+
assertRoute(value.default, 'default');
|
|
51
|
+
for (const [index, route] of (value.fallback ?? []).entries())
|
|
52
|
+
assertRoute(route, `fallback[${index}]`);
|
|
53
|
+
for (const [index, route] of (value.compare ?? []).entries())
|
|
54
|
+
assertRoute(route, `compare[${index}]`);
|
|
55
|
+
if (value.version !== undefined && value.version !== 1)
|
|
56
|
+
return configuration('configuration-invalid');
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function validateSettingsLayer(path: string): void {
|
|
61
|
+
let text: string;
|
|
62
|
+
try {
|
|
63
|
+
text = readFileSync(path, 'utf8');
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
if (text.charCodeAt(0) === 0xfeff) return configuration('configuration-invalid');
|
|
69
|
+
const root: unknown = JSON.parse(text);
|
|
70
|
+
if (
|
|
71
|
+
typeof root !== 'object' ||
|
|
72
|
+
root === null ||
|
|
73
|
+
Array.isArray(root) ||
|
|
74
|
+
(Object.hasOwn(root, EMBEDDINGS_SETTINGS_KEY) &&
|
|
75
|
+
(typeof (root as Record<string, unknown>)[EMBEDDINGS_SETTINGS_KEY] !== 'object' ||
|
|
76
|
+
(root as Record<string, unknown>)[EMBEDDINGS_SETTINGS_KEY] === null ||
|
|
77
|
+
Array.isArray((root as Record<string, unknown>)[EMBEDDINGS_SETTINGS_KEY])))
|
|
78
|
+
)
|
|
79
|
+
return configuration('configuration-invalid');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Shared precedence: global < agent config < explicitly trusted project. */
|
|
83
|
+
export function loadEmbeddingSettings(cwd: string, projectTrusted = false): EmbeddingSettings {
|
|
84
|
+
try {
|
|
85
|
+
const paths = new Set([
|
|
86
|
+
join(resolveConfigDir(join(homedir(), '.pi', 'agent')), 'settings.json'),
|
|
87
|
+
join(resolveConfigDir(), 'settings.json'),
|
|
88
|
+
...(projectTrusted ? [join(resolve(cwd), '.pi', 'settings.json')] : []),
|
|
89
|
+
]);
|
|
90
|
+
for (const path of paths) {
|
|
91
|
+
statSync(path, { throwIfNoEntry: false });
|
|
92
|
+
validateSettingsLayer(path);
|
|
93
|
+
}
|
|
94
|
+
const raw = loadPiSettings<unknown>(EMBEDDINGS_SETTINGS_KEY, {
|
|
95
|
+
cwd,
|
|
96
|
+
projectTrusted,
|
|
97
|
+
strictProjectSettings: true,
|
|
98
|
+
});
|
|
99
|
+
return validateEmbeddingSettings(raw);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error instanceof EmbeddingsError) throw error;
|
|
102
|
+
return configuration('configuration-invalid');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export const configuredDefault = (settings: EmbeddingSettings): EmbeddingRoute =>
|
|
107
|
+
assertRoute(settings.default, 'default');
|
|
108
|
+
|
|
109
|
+
export const configuredRoutes = (
|
|
110
|
+
settings: EmbeddingSettings,
|
|
111
|
+
kind: 'fallback' | 'compare'
|
|
112
|
+
): readonly EmbeddingRoute[] => {
|
|
113
|
+
const raw = kind === 'fallback' ? settings.fallback : settings.compare;
|
|
114
|
+
return (raw ?? []).map((route, index) => assertRoute(route, `${kind}[${index}]`));
|
|
115
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Type } from 'typebox';
|
|
2
|
+
import {
|
|
3
|
+
embeddingDescribeSchema,
|
|
4
|
+
embeddingCompareResultSchema,
|
|
5
|
+
embeddingRequestSchema,
|
|
6
|
+
embeddingResultSchema,
|
|
7
|
+
} from './schemas.js';
|
|
8
|
+
|
|
9
|
+
export const EMBED_TOOL = 'embed';
|
|
10
|
+
export const EMBED_COMPARE_TOOL = 'embed_compare';
|
|
11
|
+
export const EMBEDDINGS_DESCRIBE_TOOL = 'embeddings_describe';
|
|
12
|
+
|
|
13
|
+
export const EMBED_TOOL_DESCRIPTION =
|
|
14
|
+
'Embed one or more text inputs with the server-configured embedding route. Provider, model, fallback routes and credentials stay in trusted settings; this tool cannot override them. Returns vectors and their actual generating space as structured data. Full text is preserved; the package owns prefixing and provider batching. Use embed_compare only for an explicit comparison.';
|
|
15
|
+
|
|
16
|
+
export const EMBED_COMPARE_TOOL_DESCRIPTION =
|
|
17
|
+
'Explicitly compare the same text inputs using exactly the configured compare routes. Every entry is a separate request and may incur charges. No implicit default, fallback, ranking or settings mutation.';
|
|
18
|
+
|
|
19
|
+
export const EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION =
|
|
20
|
+
'Report the selected configured embedding route, generating space and provider-free readiness diagnostics without inference or credentials. Information is not a reservation or a caller storage policy.';
|
|
21
|
+
|
|
22
|
+
export const embedParameters = embeddingRequestSchema;
|
|
23
|
+
export const embedCompareParameters = embeddingRequestSchema;
|
|
24
|
+
export const embeddingsDescribeParameters = Type.Object({}, { additionalProperties: false });
|
|
25
|
+
|
|
26
|
+
export const embedOutput = embeddingResultSchema;
|
|
27
|
+
export const embedCompareOutput = embeddingCompareResultSchema;
|
|
28
|
+
export const embeddingsDescribeOutput = embeddingDescribeSchema;
|
|
29
|
+
|
|
30
|
+
export const EMBEDDINGS_TOOL_NAMES = [
|
|
31
|
+
EMBED_TOOL,
|
|
32
|
+
EMBED_COMPARE_TOOL,
|
|
33
|
+
EMBEDDINGS_DESCRIBE_TOOL,
|
|
34
|
+
] as const;
|