@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,244 @@
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 } from 'typebox';
9
+ export const EMBEDDINGS_SETTINGS_KEY = 'pi-embeddings';
10
+ export const EMBEDDINGS_PROTOCOL_VERSION = 2;
11
+ export const EMBEDDING_FORMAT_VERSION = 'host-display-attributes-v1';
12
+ export const EMBEDDING_DOCUMENT_PREFIX = 'title: none | text: ';
13
+ export const EMBEDDING_NORMALIZATION_VERSION = 'finite-nonzero-l2-v1';
14
+ export const EMBEDDING_CONTEXT_META_KEY = 'pi-embeddings/context';
15
+ export const EMBEDDING_ROUTE_IDS = [
16
+ 'local',
17
+ 'openai',
18
+ 'sarvam',
19
+ 'gateway',
20
+ 'openrouter',
21
+ 'cloudflare',
22
+ ];
23
+ export const GATEWAY_EMBEDDING_MODELS = [
24
+ 'text-embedding-3-small',
25
+ 'openai/text-embedding-3-small',
26
+ ];
27
+ export const OPENROUTER_EMBEDDING_MODELS = ['openai/text-embedding-3-small'];
28
+ export const CLOUDFLARE_EMBEDDING_MODELS = ['@cf/baai/bge-base-en-v1.5'];
29
+ const gatewayModelSchema = Type.Union([
30
+ Type.Literal('text-embedding-3-small'),
31
+ Type.Literal('openai/text-embedding-3-small'),
32
+ ]);
33
+ const openRouterModelSchema = Type.Literal('openai/text-embedding-3-small');
34
+ const cloudflareModelSchema = Type.Literal('@cf/baai/bge-base-en-v1.5');
35
+ const embeddingErrorCodeSchema = Type.Union([
36
+ Type.Literal('configuration-invalid'),
37
+ Type.Literal('route-unconfigured'),
38
+ Type.Literal('missing-credentials'),
39
+ Type.Literal('http-auth'),
40
+ Type.Literal('http-not-found'),
41
+ Type.Literal('http-rate-limit'),
42
+ Type.Literal('http-forbidden'),
43
+ Type.Literal('http-bad-request'),
44
+ Type.Literal('http-server-error'),
45
+ Type.Literal('transport-failed'),
46
+ Type.Literal('provider-response-invalid'),
47
+ Type.Literal('provider-response-mismatch'),
48
+ Type.Literal('vector-invalid'),
49
+ Type.Literal('vector-zero'),
50
+ Type.Literal('input-empty'),
51
+ Type.Literal('input-too-long'),
52
+ Type.Literal('tokenizer-roundtrip-failed'),
53
+ Type.Literal('attribution-unavailable'),
54
+ Type.Literal('local-resources-unavailable'),
55
+ Type.Literal('local-model-mismatch'),
56
+ Type.Literal('local-runtime-mismatch'),
57
+ Type.Literal('local-startup-failed'),
58
+ Type.Literal('local-cpu-startup-invalid'),
59
+ Type.Literal('cancelled'),
60
+ Type.Literal('unstarted'),
61
+ ]);
62
+ export const EMBEDDING_ERROR_CODES = [
63
+ 'configuration-invalid',
64
+ 'route-unconfigured',
65
+ 'missing-credentials',
66
+ 'http-auth',
67
+ 'http-not-found',
68
+ 'http-rate-limit',
69
+ 'http-forbidden',
70
+ 'http-bad-request',
71
+ 'http-server-error',
72
+ 'transport-failed',
73
+ 'provider-response-invalid',
74
+ 'provider-response-mismatch',
75
+ 'vector-invalid',
76
+ 'vector-zero',
77
+ 'input-empty',
78
+ 'input-too-long',
79
+ 'tokenizer-roundtrip-failed',
80
+ 'attribution-unavailable',
81
+ 'local-resources-unavailable',
82
+ 'local-model-mismatch',
83
+ 'local-runtime-mismatch',
84
+ 'local-startup-failed',
85
+ 'local-cpu-startup-invalid',
86
+ 'cancelled',
87
+ 'unstarted',
88
+ ];
89
+ const embeddingProviderSchema = Type.Union([
90
+ Type.Literal('local'),
91
+ Type.Literal('openai'),
92
+ Type.Literal('sarvam'),
93
+ Type.Literal('gateway'),
94
+ Type.Literal('openrouter'),
95
+ Type.Literal('cloudflare'),
96
+ ]);
97
+ export const embeddingRouteSchema = Type.Object({
98
+ provider: embeddingProviderSchema,
99
+ model: Type.String({ minLength: 1 }),
100
+ }, { additionalProperties: false });
101
+ const spaceCommon = {
102
+ format: Type.Literal(EMBEDDING_FORMAT_VERSION),
103
+ prefix: Type.Literal(EMBEDDING_DOCUMENT_PREFIX),
104
+ normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
105
+ };
106
+ /**
107
+ * Complete generating-space identity. `provider` is canonical: the gateway route deliberately
108
+ * reports the OpenAI recipe it declares, not its transport alias.
109
+ */
110
+ export const embeddingSpaceSchema = Type.Union([
111
+ Type.Object({
112
+ ...spaceCommon,
113
+ provider: Type.Literal('local'),
114
+ model: Type.Literal('embeddinggemma-2'),
115
+ revision: Type.String({ minLength: 1 }),
116
+ quantization: Type.Literal('Q8_0'),
117
+ runtime: Type.String({ minLength: 1 }),
118
+ dimensions: Type.Literal(768),
119
+ }, { additionalProperties: false }),
120
+ Type.Object({
121
+ ...spaceCommon,
122
+ provider: Type.Literal('openai'),
123
+ model: Type.Literal('text-embedding-3-small'),
124
+ revision: Type.Null(),
125
+ quantization: Type.Null(),
126
+ runtime: Type.Null(),
127
+ dimensions: Type.Literal(1536),
128
+ }, { additionalProperties: false }),
129
+ Type.Object({
130
+ ...spaceCommon,
131
+ provider: Type.Literal('sarvam'),
132
+ model: Type.Literal('embeddinggemma-2'),
133
+ revision: Type.Null(),
134
+ quantization: Type.Null(),
135
+ runtime: Type.Literal('sarvam-v2'),
136
+ dimensions: Type.Literal(768),
137
+ }, { additionalProperties: false }),
138
+ Type.Object({
139
+ ...spaceCommon,
140
+ provider: Type.Literal('cloudflare'),
141
+ model: cloudflareModelSchema,
142
+ revision: Type.Null(),
143
+ quantization: Type.Null(),
144
+ runtime: Type.Literal('cloudflare-workers-ai'),
145
+ dimensions: Type.Literal(768),
146
+ pooling: Type.Union([Type.Literal('mean'), Type.Literal('cls')]),
147
+ }, { additionalProperties: false }),
148
+ ]);
149
+ export const embeddingSettingsSchema = Type.Object({
150
+ version: Type.Optional(Type.Literal(1)),
151
+ default: embeddingRouteSchema,
152
+ fallback: Type.Optional(Type.Array(embeddingRouteSchema)),
153
+ compare: Type.Optional(Type.Array(embeddingRouteSchema)),
154
+ providers: Type.Optional(Type.Object({
155
+ local: Type.Optional(Type.Object({
156
+ executable: Type.String({ minLength: 1 }),
157
+ modelPath: Type.String({ minLength: 1 }),
158
+ port: Type.Optional(Type.Integer({ minimum: 1, maximum: 65535 })),
159
+ }, { additionalProperties: false })),
160
+ openai: Type.Optional(Type.Object({ apiKey: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false })),
161
+ sarvam: Type.Optional(Type.Object({ apiKey: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false })),
162
+ gateway: Type.Optional(Type.Object({
163
+ baseUrl: Type.String({ minLength: 1 }),
164
+ apiKey: Type.String({ minLength: 1 }),
165
+ model: gatewayModelSchema,
166
+ stage: Type.Union([Type.Literal('dev'), Type.Literal('prod')]),
167
+ }, { additionalProperties: false })),
168
+ openrouter: Type.Optional(Type.Object({ apiKey: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false })),
169
+ cloudflare: Type.Optional(Type.Object({
170
+ accountId: Type.Optional(Type.String({ minLength: 1 })),
171
+ apiKey: Type.Optional(Type.String({ minLength: 1 })),
172
+ gatewayId: Type.Optional(Type.String({ minLength: 1 })),
173
+ model: Type.Optional(cloudflareModelSchema),
174
+ pooling: Type.Optional(Type.Union([Type.Literal('mean'), Type.Literal('cls')])),
175
+ }, { additionalProperties: false })),
176
+ }, { additionalProperties: false })),
177
+ }, { additionalProperties: false });
178
+ export const embeddingRequestSchema = Type.Object({
179
+ inputs: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
180
+ }, { additionalProperties: false });
181
+ /** Generic, host-owned attribution. It is never a model argument or proof of ownership. */
182
+ export const embeddingContextSchema = Type.Object({
183
+ endUser: Type.String({ minLength: 1 }),
184
+ tags: Type.Array(Type.String({ minLength: 1 })),
185
+ }, { additionalProperties: false });
186
+ export const embeddingUsageSchema = Type.Object({
187
+ providerReportedInputTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
188
+ preparedInputTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
189
+ billedTokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
190
+ }, { additionalProperties: false });
191
+ export const embeddingAttemptSchema = Type.Object({
192
+ id: Type.String({ minLength: 1 }),
193
+ route: embeddingProviderSchema,
194
+ model: Type.String({ minLength: 1 }),
195
+ routeIndex: Type.Integer({ minimum: 0 }),
196
+ status: Type.Union([Type.Literal('success'), Type.Literal('error'), Type.Literal('cancelled')]),
197
+ usage: Type.Union([embeddingUsageSchema, Type.Null()]),
198
+ errorCode: Type.Optional(embeddingErrorCodeSchema),
199
+ }, { additionalProperties: false });
200
+ const successOutcomeSchema = Type.Object({
201
+ status: Type.Literal('success'),
202
+ index: Type.Integer({ minimum: 0 }),
203
+ vector: Type.Array(Type.Number()),
204
+ route: embeddingProviderSchema,
205
+ model: Type.String({ minLength: 1 }),
206
+ space: embeddingSpaceSchema,
207
+ attemptId: Type.String({ minLength: 1 }),
208
+ normalization: Type.Literal(EMBEDDING_NORMALIZATION_VERSION),
209
+ }, { additionalProperties: false });
210
+ const errorOutcomeSchema = Type.Object({
211
+ status: Type.Literal('error'),
212
+ index: Type.Integer({ minimum: 0 }),
213
+ code: embeddingErrorCodeSchema,
214
+ attemptId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
215
+ }, { additionalProperties: false });
216
+ export const embeddingOutcomeSchema = Type.Union([successOutcomeSchema, errorOutcomeSchema]);
217
+ /**
218
+ * Actual generating identity observed on successful outcomes. `generations` is the complete set;
219
+ * the singular fields are populated only when every successful vector came from one generation.
220
+ */
221
+ export const embeddingGenerationSchema = Type.Object({
222
+ provider: embeddingProviderSchema,
223
+ model: Type.String({ minLength: 1 }),
224
+ space: embeddingSpaceSchema,
225
+ }, { additionalProperties: false });
226
+ export const embeddingResultSchema = Type.Object({
227
+ schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
228
+ provider: Type.Union([embeddingProviderSchema, Type.Null()]),
229
+ model: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
230
+ space: Type.Union([embeddingSpaceSchema, Type.Null()]),
231
+ generations: Type.Array(embeddingGenerationSchema),
232
+ outcomes: Type.Array(embeddingOutcomeSchema),
233
+ attempts: Type.Array(embeddingAttemptSchema),
234
+ }, { additionalProperties: false });
235
+ export const embeddingCompareEntrySchema = Type.Object({
236
+ route: embeddingProviderSchema,
237
+ model: Type.String({ minLength: 1 }),
238
+ status: Type.Union([Type.Literal('success'), Type.Literal('error'), Type.Literal('cancelled')]),
239
+ result: embeddingResultSchema,
240
+ }, { additionalProperties: false });
241
+ export const embeddingCompareResultSchema = Type.Object({
242
+ schemaVersion: Type.Literal(EMBEDDINGS_PROTOCOL_VERSION),
243
+ entries: Type.Array(embeddingCompareEntrySchema),
244
+ }, { additionalProperties: false });
@@ -0,0 +1,9 @@
1
+ import { type EmbeddingRoute } from './schemas.js';
2
+ export declare class EmbeddingsSettingsWriteError extends Error {
3
+ }
4
+ /** Update only the trusted project's `pi-embeddings.default`, preserving every unrelated key. */
5
+ export declare function updateProjectEmbeddingSettings({ cwd, projectTrusted, route, }: {
6
+ cwd: string;
7
+ projectTrusted: boolean;
8
+ route: EmbeddingRoute;
9
+ }): Promise<void>;
@@ -0,0 +1,77 @@
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 } from './schemas.js';
7
+ export class EmbeddingsSettingsWriteError extends Error {
8
+ }
9
+ /** Update only the trusted project's `pi-embeddings.default`, preserving every unrelated key. */
10
+ export function updateProjectEmbeddingSettings({ cwd, projectTrusted, route, }) {
11
+ validateEmbeddingSettings({ default: route });
12
+ const settingsPath = resolve(cwd, '.pi', 'settings.json');
13
+ return withFileMutationQueue(settingsPath, () => updateProjectEmbeddingSettingsNow({ cwd, projectTrusted, route }));
14
+ }
15
+ async function updateProjectEmbeddingSettingsNow(args) {
16
+ if (!args.projectTrusted)
17
+ throw new EmbeddingsSettingsWriteError('Project settings are not trusted. Trust this project before changing .pi/settings.json.');
18
+ const settingsDir = join(args.cwd, '.pi');
19
+ const settingsPath = join(settingsDir, 'settings.json');
20
+ await rejectSymlink(settingsDir);
21
+ await mkdir(settingsDir, { recursive: true, mode: 0o700 });
22
+ await rejectSymlink(settingsPath);
23
+ let root = {};
24
+ let mode = 0o600;
25
+ try {
26
+ const [text, stat] = await Promise.all([readFile(settingsPath, 'utf8'), lstat(settingsPath)]);
27
+ const parsed = JSON.parse(text);
28
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
29
+ throw new EmbeddingsSettingsWriteError('Project settings must contain a JSON object.');
30
+ root = { ...parsed };
31
+ mode = stat.mode & 0o777;
32
+ }
33
+ catch (error) {
34
+ if (error instanceof EmbeddingsSettingsWriteError)
35
+ throw error;
36
+ const code = error.code;
37
+ if (code !== 'ENOENT') {
38
+ if (error instanceof SyntaxError)
39
+ throw new EmbeddingsSettingsWriteError('Project settings contain invalid JSON. Fix .pi/settings.json before changing embedding settings.');
40
+ throw new EmbeddingsSettingsWriteError('Could not read project settings.');
41
+ }
42
+ }
43
+ const current = root[EMBEDDINGS_SETTINGS_KEY];
44
+ if (current !== undefined && (typeof current !== 'object' || current === null || Array.isArray(current)))
45
+ throw new EmbeddingsSettingsWriteError('pi-embeddings settings must contain a JSON object.');
46
+ root[EMBEDDINGS_SETTINGS_KEY] = { ...(current ?? {}), default: args.route };
47
+ const tempPath = join(settingsDir, `.settings.json.pi-embeddings-${randomUUID()}`);
48
+ let handle;
49
+ let created = false;
50
+ try {
51
+ handle = await open(tempPath, 'wx', mode);
52
+ created = true;
53
+ await handle.writeFile(`${JSON.stringify(root, null, 2)}\n`, 'utf8');
54
+ await handle.close();
55
+ handle = undefined;
56
+ await rename(tempPath, settingsPath);
57
+ }
58
+ catch {
59
+ if (handle)
60
+ await handle.close().catch(() => undefined);
61
+ if (created)
62
+ await unlink(tempPath).catch(() => undefined);
63
+ throw new EmbeddingsSettingsWriteError('Could not update project settings.');
64
+ }
65
+ }
66
+ async function rejectSymlink(path) {
67
+ try {
68
+ if ((await lstat(path)).isSymbolicLink())
69
+ throw new EmbeddingsSettingsWriteError('The project settings path must not be a symbolic link.');
70
+ }
71
+ catch (error) {
72
+ if (error instanceof EmbeddingsSettingsWriteError)
73
+ throw error;
74
+ if (error.code !== 'ENOENT')
75
+ throw new EmbeddingsSettingsWriteError('Could not inspect project settings.');
76
+ }
77
+ }
@@ -0,0 +1,8 @@
1
+ import { type EmbeddingRoute, type EmbeddingSettings } from './schemas.js';
2
+ export declare const isEmbeddingSettings: (value: unknown) => value is EmbeddingSettings;
3
+ /** Validate the whole settings object before any route is resolved or inference is attempted. */
4
+ export declare function validateEmbeddingSettings(value: unknown): EmbeddingSettings;
5
+ /** Shared precedence: global < agent config < explicitly trusted project. */
6
+ export declare function loadEmbeddingSettings(cwd: string, projectTrusted?: boolean): EmbeddingSettings;
7
+ export declare const configuredDefault: (settings: EmbeddingSettings) => EmbeddingRoute;
8
+ export declare const configuredRoutes: (settings: EmbeddingSettings, kind: "fallback" | "compare") => readonly EmbeddingRoute[];
@@ -0,0 +1,99 @@
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 { CLOUDFLARE_EMBEDDING_MODELS, EMBEDDINGS_SETTINGS_KEY, GATEWAY_EMBEDDING_MODELS, OPENROUTER_EMBEDDING_MODELS, embeddingSettingsSchema, } from './schemas.js';
8
+ const MODELS_BY_PROVIDER = {
9
+ local: ['embeddinggemma-2'],
10
+ openai: ['text-embedding-3-small'],
11
+ sarvam: ['embeddinggemma-2'],
12
+ gateway: GATEWAY_EMBEDDING_MODELS,
13
+ openrouter: OPENROUTER_EMBEDDING_MODELS,
14
+ cloudflare: CLOUDFLARE_EMBEDDING_MODELS,
15
+ };
16
+ export const isEmbeddingSettings = (value) => Value.Check(embeddingSettingsSchema, value);
17
+ function configuration(message) {
18
+ throw new EmbeddingsError(message);
19
+ }
20
+ function assertRoute(value, location) {
21
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
22
+ return configuration('configuration-invalid');
23
+ const record = value;
24
+ const provider = record.provider;
25
+ const model = record.model;
26
+ if (typeof provider !== 'string' || typeof model !== 'string' || model.length === 0)
27
+ return configuration('configuration-invalid');
28
+ if (!Object.hasOwn(MODELS_BY_PROVIDER, provider))
29
+ return configuration('configuration-invalid');
30
+ const allowed = MODELS_BY_PROVIDER[provider];
31
+ if (allowed === undefined || !allowed.includes(model))
32
+ return configuration('configuration-invalid');
33
+ return { provider: provider, model };
34
+ }
35
+ /** Validate the whole settings object before any route is resolved or inference is attempted. */
36
+ export function validateEmbeddingSettings(value) {
37
+ if (!isEmbeddingSettings(value))
38
+ return configuration('configuration-invalid');
39
+ assertRoute(value.default, 'default');
40
+ for (const [index, route] of (value.fallback ?? []).entries())
41
+ assertRoute(route, `fallback[${index}]`);
42
+ for (const [index, route] of (value.compare ?? []).entries())
43
+ assertRoute(route, `compare[${index}]`);
44
+ if (value.version !== undefined && value.version !== 1)
45
+ return configuration('configuration-invalid');
46
+ return value;
47
+ }
48
+ function validateSettingsLayer(path) {
49
+ let text;
50
+ try {
51
+ text = readFileSync(path, 'utf8');
52
+ }
53
+ catch (error) {
54
+ if (error.code === 'ENOENT')
55
+ return;
56
+ throw error;
57
+ }
58
+ if (text.charCodeAt(0) === 0xfeff)
59
+ return configuration('configuration-invalid');
60
+ const root = JSON.parse(text);
61
+ if (typeof root !== 'object' ||
62
+ root === null ||
63
+ Array.isArray(root) ||
64
+ (Object.hasOwn(root, EMBEDDINGS_SETTINGS_KEY) &&
65
+ (typeof root[EMBEDDINGS_SETTINGS_KEY] !== 'object' ||
66
+ root[EMBEDDINGS_SETTINGS_KEY] === null ||
67
+ Array.isArray(root[EMBEDDINGS_SETTINGS_KEY]))))
68
+ return configuration('configuration-invalid');
69
+ }
70
+ /** Shared precedence: global < agent config < explicitly trusted project. */
71
+ export function loadEmbeddingSettings(cwd, projectTrusted = false) {
72
+ try {
73
+ const paths = new Set([
74
+ join(resolveConfigDir(join(homedir(), '.pi', 'agent')), 'settings.json'),
75
+ join(resolveConfigDir(), 'settings.json'),
76
+ ...(projectTrusted ? [join(resolve(cwd), '.pi', 'settings.json')] : []),
77
+ ]);
78
+ for (const path of paths) {
79
+ statSync(path, { throwIfNoEntry: false });
80
+ validateSettingsLayer(path);
81
+ }
82
+ const raw = loadPiSettings(EMBEDDINGS_SETTINGS_KEY, {
83
+ cwd,
84
+ projectTrusted,
85
+ strictProjectSettings: true,
86
+ });
87
+ return validateEmbeddingSettings(raw);
88
+ }
89
+ catch (error) {
90
+ if (error instanceof EmbeddingsError)
91
+ throw error;
92
+ return configuration('configuration-invalid');
93
+ }
94
+ }
95
+ export const configuredDefault = (settings) => assertRoute(settings.default, 'default');
96
+ export const configuredRoutes = (settings, kind) => {
97
+ const raw = kind === 'fallback' ? settings.fallback : settings.compare;
98
+ return (raw ?? []).map((route, index) => assertRoute(route, `${kind}[${index}]`));
99
+ };