@prompt-optimizer/mcp-server 0.1.0 → 0.1.1

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 (67) hide show
  1. package/README.md +9 -7
  2. package/dist/browser.js +10 -4200
  3. package/dist/chunk-2AOVKKBT.js +7 -0
  4. package/dist/chunk-5QROM7SH.js +3 -0
  5. package/dist/chunk-7FYOSVIN.js +3 -0
  6. package/dist/chunk-AKXNS3YY.js +4 -0
  7. package/dist/chunk-BBXFEEUH.js +43 -0
  8. package/dist/chunk-CHINCAF5.js +33 -0
  9. package/dist/chunk-EJ2IIPFF.js +3 -0
  10. package/dist/chunk-FLQML3XF.js +64 -0
  11. package/dist/chunk-GA7S5A7R.js +3 -0
  12. package/dist/chunk-IABPRAPS.js +3 -0
  13. package/dist/chunk-JE2EBI2C.js +3 -0
  14. package/dist/chunk-JL6XIA4S.js +4 -0
  15. package/dist/chunk-JXWLV6TC.js +12 -0
  16. package/dist/chunk-MUXGFCOV.js +7012 -0
  17. package/dist/chunk-NT2DBZVA.js +3 -0
  18. package/dist/chunk-NVZFDKDX.js +3 -0
  19. package/dist/chunk-PKJ2PK6J.js +106 -0
  20. package/dist/chunk-SDHFVY4F.js +6 -0
  21. package/dist/chunk-TWLLFRFQ.js +6 -0
  22. package/dist/desktop-business.js +4 -1225
  23. package/dist/desktop-comparison-UIIN3WK4.js +3 -0
  24. package/dist/desktop-storage-KJWV2A3P.js +3 -0
  25. package/dist/desktop.js +1 -24
  26. package/dist/dist-OM6QMJNC.js +10 -0
  27. package/dist/dist-YR425RV6.js +3 -0
  28. package/dist/index.js +1 -10
  29. package/dist/legacy.js +97 -26634
  30. package/dist/multipart-parser-XGXMMB2Z.js +4 -0
  31. package/dist/node-2SMUH4FH.js +3 -0
  32. package/dist/node-NX6BPYD5.js +3 -0
  33. package/dist/node-U7LDATXE.js +17 -0
  34. package/dist/registry-H5F4DGAM-2GPEVJMD.js +3 -0
  35. package/dist/src-3F22P42W.js +5 -0
  36. package/dist/start.js +2 -13
  37. package/package.json +10 -1
  38. package/preload-env.cjs +3 -352
  39. package/dist/chunk-3FYJ3FRD.js +0 -57
  40. package/dist/chunk-E7Z4Y3F4.js +0 -36402
  41. package/dist/chunk-GBDJTSRW.js +0 -298
  42. package/dist/chunk-HLCN3DLS.js +0 -19745
  43. package/dist/chunk-HYVN7FZZ.js +0 -4787
  44. package/dist/chunk-MEUCFQGU.js +0 -537
  45. package/dist/chunk-N6AUTPPS.js +0 -10647
  46. package/dist/chunk-Q52SACHI.js +0 -304
  47. package/dist/chunk-Q5B3KFB3.js +0 -31
  48. package/dist/chunk-QSPNNVX3.js +0 -49017
  49. package/dist/chunk-SO4YJHYW.js +0 -13450
  50. package/dist/chunk-SV2GETJH.js +0 -65
  51. package/dist/chunk-TFH2LO2H.js +0 -58
  52. package/dist/chunk-TFJEYQ3G.js +0 -786
  53. package/dist/chunk-TLOFCHZI.js +0 -70
  54. package/dist/chunk-TQGHULC7.js +0 -188
  55. package/dist/chunk-UTOMPKTK.js +0 -2209
  56. package/dist/chunk-XXALDAL7.js +0 -1838
  57. package/dist/chunk-YT3U6B54.js +0 -21
  58. package/dist/desktop-comparison-HDIQ6K45.js +0 -22
  59. package/dist/desktop-storage-YRABQCLF.js +0 -14
  60. package/dist/dist-O5VNBF5I.js +0 -622
  61. package/dist/dist-UMX52UME.js +0 -481
  62. package/dist/multipart-parser-XE6WGDAU.js +0 -373
  63. package/dist/node-2RBNZOSK.js +0 -2225
  64. package/dist/node-4Z3USCHW.js +0 -21
  65. package/dist/node-QHGLD5ST.js +0 -25
  66. package/dist/registry-H5F4DGAM-UHR4F6LL.js +0 -13
  67. package/dist/src-7PBMYCGI.js +0 -1398
@@ -1,1838 +0,0 @@
1
- import { createRequire as __mcpCreateRequire } from "node:module";
2
- const require = __mcpCreateRequire(import.meta.url);
3
- import {
4
- APIError,
5
- InitializationError,
6
- RequestConfigError,
7
- TextAdapterRegistry,
8
- isPublicTextRequestOmissions,
9
- isPublicTextRequestParameters,
10
- normalizeCustomRequestHeaders,
11
- projectTextRequestEvidence,
12
- validateCustomRequestHeaders
13
- } from "./chunk-QSPNNVX3.js";
14
- import {
15
- createAssetReadAccess,
16
- hashText,
17
- isTextModelConfig,
18
- mergeOverrides,
19
- record,
20
- resolveTextModelMetadata,
21
- splitOverridesBySchema,
22
- text
23
- } from "./chunk-UTOMPKTK.js";
24
- import {
25
- CORE_ERROR_CODES,
26
- __publicField
27
- } from "./chunk-TQGHULC7.js";
28
-
29
- // ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/native.js
30
- import { randomUUID } from "node:crypto";
31
- var native_default = { randomUUID };
32
-
33
- // ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/rng.js
34
- import { randomFillSync } from "node:crypto";
35
- var rnds8Pool = new Uint8Array(256);
36
- var poolPtr = rnds8Pool.length;
37
- function rng() {
38
- if (poolPtr > rnds8Pool.length - 16) {
39
- randomFillSync(rnds8Pool);
40
- poolPtr = 0;
41
- }
42
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
43
- }
44
-
45
- // ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/stringify.js
46
- var byteToHex = [];
47
- for (let i = 0; i < 256; ++i) {
48
- byteToHex.push((i + 256).toString(16).slice(1));
49
- }
50
- function unsafeStringify(arr, offset = 0) {
51
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
52
- }
53
-
54
- // ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/v4.js
55
- function _v4(options, buf, offset) {
56
- options = options || {};
57
- const rnds = options.random ?? options.rng?.() ?? rng();
58
- if (rnds.length < 16) {
59
- throw new Error("Random bytes length must be >= 16");
60
- }
61
- rnds[6] = rnds[6] & 15 | 64;
62
- rnds[8] = rnds[8] & 63 | 128;
63
- if (buf) {
64
- offset = offset || 0;
65
- if (offset < 0 || offset + 16 > buf.length) {
66
- throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
67
- }
68
- for (let i = 0; i < 16; ++i) {
69
- buf[offset + i] = rnds[i];
70
- }
71
- return buf;
72
- }
73
- return unsafeStringify(rnds);
74
- }
75
- function v4(options, buf, offset) {
76
- if (native_default.randomUUID && !buf && !options) {
77
- return native_default.randomUUID();
78
- }
79
- return _v4(options, buf, offset);
80
- }
81
- var v4_default = v4;
82
-
83
- // ../core/dist/chunk-YNYWQDD2.js
84
- var COMPARISON_RECORD_LIMIT = 1024 * 1024;
85
- var COMPARISON_STORAGE_LIMIT = 16 * COMPARISON_RECORD_LIMIT;
86
- var encoder = new TextEncoder();
87
- var ComparisonRepositoryError = class extends Error {
88
- constructor(code) {
89
- super(`Saved comparison request failed (${code}).`);
90
- __publicField(this, "code", code);
91
- this.name = "ComparisonRepositoryError";
92
- }
93
- };
94
- function invalidComparisonData() {
95
- throw new ComparisonRepositoryError("COMPARISON_DATA_INVALID");
96
- }
97
- var object = (value, keys) => value !== null && typeof value === "object" && !Array.isArray(value) && (!keys || Object.keys(value).every((key) => keys.includes(key)));
98
- var named = (value) => typeof value === "string" && value.trim().length > 0;
99
- var uuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
100
- var timestamp = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
101
- var terminal = (value) => value === "success" || value === "error" || value === "cancelled";
102
- var byteLength = (value) => encoder.encode(value).byteLength;
103
- function parseJson(raw) {
104
- try {
105
- return JSON.parse(raw);
106
- } catch {
107
- return invalidComparisonData();
108
- }
109
- }
110
- function canonical(value) {
111
- if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]";
112
- if (object(value)) {
113
- return "{" + Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => JSON.stringify(key) + ":" + canonical(value[key])).join(",") + "}";
114
- }
115
- return JSON.stringify(value) ?? "null";
116
- }
117
- function evidence(value) {
118
- return object(value, ["api", "modelId", "parameters", "omittedParameterNames"]) && (value.api === "chat-completions" || value.api === "responses") && named(value.modelId) && isPublicTextRequestParameters(value.parameters) && isPublicTextRequestOmissions(value.omittedParameterNames);
119
- }
120
- function validRun(value, id2) {
121
- if (!object(value, ["id", "runId", "model", "effective", "status", "output", "reasoning", "errorCode", "startedAt", "completedAt"]) || value.id !== id2 || !uuid(value.runId) || !terminal(value.status) || !timestamp(value.startedAt) || !timestamp(value.completedAt) || value.completedAt < value.startedAt || typeof value.output !== "string" || typeof value.reasoning !== "string" || value.errorCode !== void 0 && (typeof value.errorCode !== "string" || !/^[A-Z_]{1,64}$/.test(value.errorCode))) return false;
122
- const { effective, model } = value;
123
- if (!object(model, ["configKey", "name", "providerId", "modelId"]) || ![model.configKey, model.name, model.providerId, model.modelId].every(named) || !object(effective, ["parameterCoverage", "parameters", "omittedParameterNames", "requestEvidence", "preview", "request"]) || effective.parameterCoverage !== "declared" || !isPublicTextRequestParameters(effective.parameters) || !isPublicTextRequestOmissions(effective.omittedParameterNames) || effective.preview !== void 0 && (!evidence(effective.preview) || effective.preview.modelId !== model.modelId)) return false;
124
- if (effective.requestEvidence === "captured") return evidence(effective.request) && effective.request.modelId === model.modelId;
125
- return effective.requestEvidence === "pending" && effective.request === void 0 && value.status !== "success";
126
- }
127
- function validRequest(value) {
128
- return object(value, ["rawPrompt", "messages", "variables"]) && named(value.rawPrompt) && Array.isArray(value.messages) && value.messages.length === 1 && object(value.messages[0], ["role", "content"]) && value.messages[0].role === "user" && named(value.messages[0].content) && object(value.variables) && Object.values(value.variables).every((item) => typeof item === "string");
129
- }
130
- function validCandidatePrompt(value, baselineVersionId) {
131
- if (!object(value) || !validRequest(value.request)) return false;
132
- if (value.kind === "draft") return object(value, ["kind", "request"]);
133
- return value.kind === "saved-version" && object(value, ["kind", "versionId", "version", "request"]) && named(value.versionId) && value.versionId !== baselineVersionId && timestamp(value.version) && value.version > 0;
134
- }
135
- function isSavedComparison(value) {
136
- if (!object(value, ["schemaVersion", "id", "savedAt", "source", "executionSource", "request", "candidatePrompt", "runs"]) || value.schemaVersion !== "saved-comparison/v1" && value.schemaVersion !== "saved-comparison/v2" || !uuid(value.id) || !timestamp(value.savedAt)) return false;
137
- const { source, executionSource, request, candidatePrompt, runs } = value;
138
- if (!object(source, ["favoriteId", "assetId", "versionId", "expectedRevision", "title"]) || ![source.favoriteId, source.assetId, source.versionId, source.expectedRevision, source.title].every(named) || !object(executionSource, ["kind", "sourceId", "sourceEpoch", "connectionGeneration", "label"]) || executionSource.kind !== "desktop" && executionSource.kind !== "browser" || ![executionSource.sourceId, executionSource.sourceEpoch, executionSource.connectionGeneration, executionSource.label].every(named) || !validRequest(request) || !Array.isArray(runs) || runs.length !== 2 || !validRun(runs[0], "a") || !validRun(runs[1], "b") || runs[0].runId === runs[1].runId) return false;
139
- const [baseline, candidate] = runs;
140
- if (value.schemaVersion === "saved-comparison/v1") {
141
- return candidatePrompt === void 0 && baseline.model.configKey !== candidate.model.configKey;
142
- }
143
- return validCandidatePrompt(candidatePrompt, source.versionId) && canonical(baseline.model) === canonical(candidate.model) && evidence(baseline.effective.preview) && canonical(baseline.effective.preview) === canonical(candidate.effective.preview);
144
- }
145
- var PREFIX = "comparison/v1/";
146
- var INDEX_KEY = PREFIX + "catalog";
147
- var RECORD_PREFIX = PREFIX + "records/";
148
- var INTENT_PREFIX = PREFIX + "intents/";
149
- var hashPattern = /^[a-f0-9]{64}$/;
150
- function parseStored(value, id2) {
151
- if (!object(value, ["id", "revision", "comparison"]) || !uuid(value.id) || !uuid(value.revision) || id2 !== void 0 && id2 !== value.id || value.comparison !== null && (!isSavedComparison(value.comparison) || value.comparison.id !== value.id)) {
152
- return invalidComparisonData();
153
- }
154
- return { id: value.id, revision: value.revision, comparison: value.comparison };
155
- }
156
- function readStored(raw, id2) {
157
- return raw === null ? null : parseStored(parseJson(raw), id2);
158
- }
159
- function isIndexEntry(value) {
160
- return object(value, ["id", "favoriteId", "title", "savedAt", "statuses", "revision", "bytes"]) && uuid(value.id) && named(value.favoriteId) && named(value.title) && timestamp(value.savedAt) && Array.isArray(value.statuses) && value.statuses.length === 2 && value.statuses.every(terminal) && uuid(value.revision) && timestamp(value.bytes) && value.bytes > 0 && value.bytes <= COMPARISON_RECORD_LIMIT;
161
- }
162
- function readCatalog(raw) {
163
- if (raw === null) return [];
164
- const parsed = parseJson(raw);
165
- if (!Array.isArray(parsed) || !parsed.every(isIndexEntry) || new Set(parsed.map((item) => item.id)).size !== parsed.length) return invalidComparisonData();
166
- return parsed;
167
- }
168
- function indexEntry(record2) {
169
- const { comparison, revision, id: id2 } = record2;
170
- if (!comparison) return null;
171
- const bytes = byteLength(JSON.stringify(comparison));
172
- if (bytes > COMPARISON_RECORD_LIMIT) throw new ComparisonRepositoryError("RESULT_STORAGE_LIMIT");
173
- return {
174
- id: id2,
175
- revision,
176
- bytes,
177
- favoriteId: comparison.source.favoriteId,
178
- title: comparison.source.title,
179
- savedAt: comparison.savedAt,
180
- statuses: [comparison.runs[0].status, comparison.runs[1].status]
181
- };
182
- }
183
- function checkBudget(catalog) {
184
- if (catalog.reduce((total, item) => total + item.bytes, 0) > COMPARISON_STORAGE_LIMIT) {
185
- throw new ComparisonRepositoryError("RESULT_STORAGE_LIMIT");
186
- }
187
- }
188
- function parseBackup(value) {
189
- if (!object(value, ["version", "records", "intents"]) || value.version !== 1 || !Array.isArray(value.records) || !Array.isArray(value.intents)) return invalidComparisonData();
190
- const records = value.records.map((record2) => parseStored(record2));
191
- const ids = new Set(records.map((record2) => record2.id));
192
- if (ids.size !== records.length) return invalidComparisonData();
193
- const hashes = /* @__PURE__ */ new Set();
194
- const intents = value.intents.map((intent) => {
195
- if (!object(intent, ["hash", "id"]) || typeof intent.hash !== "string" || !hashPattern.test(intent.hash) || !uuid(intent.id) || !ids.has(intent.id) || hashes.has(intent.hash)) return invalidComparisonData();
196
- hashes.add(intent.hash);
197
- return { hash: intent.hash, id: intent.id };
198
- });
199
- checkBudget(records.flatMap((record2) => indexEntry(record2) ?? []));
200
- return { version: 1, records, intents };
201
- }
202
- function same(a, b) {
203
- return canonical(a) === canonical(b);
204
- }
205
- function planImport(store, backup) {
206
- const catalog = readCatalog(store.getItem(INDEX_KEY));
207
- const indexed = new Set(catalog.map((item) => item.id));
208
- const writes = [];
209
- for (const record2 of backup.records) {
210
- const key = RECORD_PREFIX + record2.id;
211
- const current = readStored(store.getItem(key), record2.id);
212
- if (current) {
213
- if (!same(current, record2)) throw new ComparisonRepositoryError("IDEMPOTENCY_CONFLICT");
214
- if (indexed.has(record2.id) !== (record2.comparison !== null)) return invalidComparisonData();
215
- continue;
216
- }
217
- if (indexed.has(record2.id)) return invalidComparisonData();
218
- const summary = indexEntry(record2);
219
- if (summary) catalog.push(summary);
220
- writes.push([key, JSON.stringify(record2)]);
221
- }
222
- for (const { hash, id: id2 } of backup.intents) {
223
- const key = INTENT_PREFIX + hash;
224
- const current = store.getItem(key);
225
- if (current !== null && current !== id2) throw new ComparisonRepositoryError("IDEMPOTENCY_CONFLICT");
226
- if (current === null) writes.push([key, id2]);
227
- }
228
- checkBudget(catalog);
229
- if (writes.length) writes.push([INDEX_KEY, JSON.stringify(catalog)]);
230
- return writes;
231
- }
232
- function backupFromSnapshot(snapshot) {
233
- const records = [];
234
- const intents = [];
235
- let catalog = [];
236
- for (const [key, value] of snapshot) {
237
- if (key === INDEX_KEY) catalog = readCatalog(value);
238
- else if (key.startsWith(RECORD_PREFIX)) records.push(parseStored(parseJson(value), key.slice(RECORD_PREFIX.length)));
239
- else if (key.startsWith(INTENT_PREFIX)) intents.push({ hash: key.slice(INTENT_PREFIX.length), id: value });
240
- else return invalidComparisonData();
241
- }
242
- const expected = records.flatMap((record2) => indexEntry(record2) ?? []);
243
- const ordered = (items) => [...items].sort((a, b) => a.id.localeCompare(b.id));
244
- if (!same(ordered(catalog), ordered(expected))) return invalidComparisonData();
245
- return parseBackup({ version: 1, records, intents });
246
- }
247
- function checkId(id2) {
248
- if (!uuid(id2)) throw new ComparisonRepositoryError("INVALID_INPUT");
249
- }
250
- async function intentHash(key) {
251
- if (typeof key !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/.test(key)) {
252
- throw new ComparisonRepositoryError("INVALID_INPUT");
253
- }
254
- return hashText(key);
255
- }
256
- function order(a, b) {
257
- return b.savedAt - a.savedAt || a.id.localeCompare(b.id);
258
- }
259
- function listAfter(catalog, options) {
260
- const limit = options.limit ?? 20;
261
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || options.favoriteId !== void 0 && !named(options.favoriteId)) {
262
- throw new ComparisonRepositoryError("INVALID_INPUT");
263
- }
264
- let cursor;
265
- if (options.cursor !== void 0) {
266
- const parts = typeof options.cursor === "string" ? /^(0|[1-9][0-9]*)\.([a-f0-9-]+)$/.exec(options.cursor) : null;
267
- if (!parts || !timestamp(Number(parts[1])) || !uuid(parts[2])) throw new ComparisonRepositoryError("INVALID_INPUT");
268
- cursor = { savedAt: Number(parts[1]), id: parts[2] };
269
- }
270
- const sorted = catalog.filter((item) => (options.favoriteId === void 0 || options.favoriteId === item.favoriteId) && (!cursor || order(item, cursor) > 0)).sort(order);
271
- const items = sorted.slice(0, limit).map(({ id: id2, title, savedAt, statuses, revision }) => ({ id: id2, title, savedAt, statuses, revision }));
272
- const last = items[items.length - 1];
273
- return { items, ...last && sorted.length > limit ? { nextCursor: `${last.savedAt}.${last.id}` } : {} };
274
- }
275
- function createComparisonRepository(storage) {
276
- return {
277
- async save(completed, saveKey) {
278
- const { candidatePrompt, ...comparison } = structuredClone(completed);
279
- const savedAt = Date.now();
280
- const currentComparison = candidatePrompt === void 0 ? { ...comparison, schemaVersion: "saved-comparison/v1", savedAt } : { ...comparison, candidatePrompt, schemaVersion: "saved-comparison/v2", savedAt };
281
- if (!isSavedComparison(currentComparison)) return invalidComparisonData();
282
- if (byteLength(JSON.stringify(currentComparison)) > COMPARISON_RECORD_LIMIT) {
283
- throw new ComparisonRepositoryError("RESULT_STORAGE_LIMIT");
284
- }
285
- const intent = INTENT_PREFIX + await intentHash(saveKey);
286
- const id2 = currentComparison.id;
287
- const key = RECORD_PREFIX + id2;
288
- return storage.withWriteTransaction((store) => {
289
- const intended = store.getItem(intent);
290
- if (intended !== null && intended !== id2) throw new ComparisonRepositoryError("IDEMPOTENCY_CONFLICT");
291
- const existing = readStored(store.getItem(key), id2);
292
- if (existing) {
293
- if (!existing.comparison) throw new ComparisonRepositoryError("COMPARISON_DELETED");
294
- if (!same(existing.comparison, { ...currentComparison, savedAt: existing.comparison.savedAt })) {
295
- throw new ComparisonRepositoryError("IDEMPOTENCY_CONFLICT");
296
- }
297
- if (intended === null) store.setItem(intent, id2);
298
- return { comparison: existing.comparison, revision: existing.revision };
299
- }
300
- const catalog = readCatalog(store.getItem(INDEX_KEY));
301
- if (intended !== null || catalog.some((item) => item.id === id2)) return invalidComparisonData();
302
- const revision = v4_default();
303
- const record2 = { id: id2, revision, comparison: currentComparison };
304
- catalog.push(indexEntry(record2));
305
- checkBudget(catalog);
306
- store.setItem(key, JSON.stringify(record2));
307
- store.setItem(intent, id2);
308
- store.setItem(INDEX_KEY, JSON.stringify(catalog));
309
- return { comparison: currentComparison, revision };
310
- });
311
- },
312
- async list(options = {}) {
313
- if (!object(options, ["limit", "cursor", "favoriteId"])) throw new ComparisonRepositoryError("INVALID_INPUT");
314
- return listAfter(readCatalog(await storage.getItem(INDEX_KEY)), options);
315
- },
316
- async get(id2) {
317
- checkId(id2);
318
- const record2 = readStored(await storage.getItem(RECORD_PREFIX + id2), id2);
319
- if (!record2?.comparison) throw new ComparisonRepositoryError("COMPARISON_NOT_FOUND");
320
- return { comparison: record2.comparison, revision: record2.revision };
321
- },
322
- async delete(id2, expectedRevision) {
323
- checkId(id2);
324
- if (!uuid(expectedRevision)) throw new ComparisonRepositoryError("INVALID_INPUT");
325
- return storage.withWriteTransaction((store) => {
326
- const key = RECORD_PREFIX + id2;
327
- const record2 = readStored(store.getItem(key), id2);
328
- if (!record2) throw new ComparisonRepositoryError("COMPARISON_NOT_FOUND");
329
- if (record2.revision !== expectedRevision) throw new ComparisonRepositoryError("REVISION_CONFLICT");
330
- if (!record2.comparison) return { deleted: false, alreadyDeleted: true };
331
- const catalog = readCatalog(store.getItem(INDEX_KEY));
332
- if (!catalog.some((item) => item.id === id2)) return invalidComparisonData();
333
- store.setItem(key, JSON.stringify({ id: id2, revision: record2.revision, comparison: null }));
334
- store.setItem(INDEX_KEY, JSON.stringify(catalog.filter((item) => item.id !== id2)));
335
- return { deleted: true, alreadyDeleted: false };
336
- });
337
- },
338
- async exportData() {
339
- return backupFromSnapshot(await storage.getEntriesByPrefix(PREFIX));
340
- },
341
- async getDataType() {
342
- return "savedComparisons";
343
- },
344
- async validateData(value) {
345
- try {
346
- const backup = parseBackup(value);
347
- const snapshot = new Map(await storage.getEntriesByPrefix(PREFIX));
348
- planImport({ getItem: (key) => snapshot.get(key) ?? null }, backup);
349
- return true;
350
- } catch (error) {
351
- if (error instanceof ComparisonRepositoryError) return false;
352
- throw error;
353
- }
354
- },
355
- async importData(value) {
356
- const backup = parseBackup(value);
357
- await storage.withWriteTransaction((store) => {
358
- for (const [key, contents] of planImport(store, backup)) store.setItem(key, contents);
359
- });
360
- }
361
- };
362
- }
363
- var CONNECTION_KEYS = /^(?:__proto__|prototype|constructor|api.?key|secret|client.?secret|access.?token|refresh.?token|password|authorization|credentials?|headers|base.?url|endpoint)$/i;
364
- function cleanLocalParameterOverrides(value) {
365
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
366
- const ancestors = /* @__PURE__ */ new WeakSet();
367
- const clean = (item) => {
368
- if (item === null || typeof item === "string" || typeof item === "boolean") return item;
369
- if (typeof item === "number") return Number.isFinite(item) ? item : void 0;
370
- if (typeof item !== "object" || ancestors.has(item)) return void 0;
371
- ancestors.add(item);
372
- const result = Array.isArray(item) ? item.map((entry) => clean(entry) ?? null) : Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, clean(entry)]).filter(([, entry]) => entry !== void 0));
373
- ancestors.delete(item);
374
- return result;
375
- };
376
- return Object.fromEntries(Object.entries(value).filter(([key]) => !CONNECTION_KEYS.test(key)).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, clean(item)]).filter(([, item]) => item !== void 0));
377
- }
378
- function inheritParameters(base, previousSchema, schema) {
379
- const previousNames = new Set(previousSchema.map((definition) => definition.name));
380
- const names = new Set(schema.map((definition) => definition.name));
381
- return Object.fromEntries(Object.entries({ ...base.customParamOverrides, ...base.paramOverrides }).filter(([name]) => !previousNames.has(name) || names.has(name)));
382
- }
383
- function resolveRuntimeImageModel(base, selection, registry) {
384
- const modelId = selection.modelId?.trim() || base.modelId;
385
- const adapter = registry.getAdapter(base.providerId);
386
- const model = modelId === base.modelId ? base.model : adapter.getModels().find((m) => m.id === modelId) ?? adapter.buildDefaultModel(modelId);
387
- const inherited = inheritParameters(base, base.model.parameterDefinitions, model.parameterDefinitions);
388
- return {
389
- ...base,
390
- modelId,
391
- model,
392
- connectionConfig: { ...base.connectionConfig },
393
- customParamOverrides: void 0,
394
- paramOverrides: mergeOverrides({ schema: model.parameterDefinitions, requestOverrides: { ...inherited, ...cleanLocalParameterOverrides(selection.paramOverrides) } })
395
- };
396
- }
397
- function describeRuntimeModel(config) {
398
- const text2 = "modelMeta" in config;
399
- const connection = {};
400
- for (const key of ["baseURL", "baseUrl", "endpoint", "region", "apiVersion", "organization", "project", "requestStyle", "timeout", "accountId", "deploymentName"]) {
401
- const value = config.connectionConfig?.[key];
402
- if (typeof value === "number" || typeof value === "boolean") {
403
- connection[key] = value;
404
- continue;
405
- }
406
- if (typeof value !== "string") continue;
407
- try {
408
- const url = new URL(value);
409
- url.username = "";
410
- url.password = "";
411
- url.search = "";
412
- url.hash = "";
413
- connection[key] = url.toString();
414
- } catch {
415
- connection[key] = value;
416
- }
417
- }
418
- return {
419
- providerId: text2 ? config.providerMeta.id : config.providerId,
420
- modelId: text2 ? config.modelMeta.id : config.modelId,
421
- connection,
422
- parameters: cleanLocalParameterOverrides(mergeOverrides({
423
- schema: text2 ? config.modelMeta.parameterDefinitions : config.model.parameterDefinitions,
424
- includeDefaults: true,
425
- customOverrides: config.customParamOverrides,
426
- requestOverrides: config.paramOverrides
427
- }))
428
- };
429
- }
430
- function resolveRuntimeTextModel(base, selection, registry) {
431
- const modelId = selection.modelId?.trim() || base.modelMeta.id;
432
- const providerId = base.providerId || base.providerMeta.id;
433
- const metadata = resolveTextModelMetadata({
434
- providerId,
435
- modelId,
436
- registry,
437
- existingProviderMeta: base.providerMeta,
438
- existingModelMeta: base.modelMeta
439
- });
440
- const schema = metadata.modelMeta.parameterDefinitions;
441
- const inherited = inheritParameters(base, base.modelMeta.parameterDefinitions, schema);
442
- return {
443
- ...base,
444
- ...metadata,
445
- providerId,
446
- modelId,
447
- connectionConfig: { ...base.connectionConfig },
448
- customParamOverrides: void 0,
449
- paramOverrides: mergeOverrides({ schema, includeDefaults: false, requestOverrides: { ...inherited, ...cleanLocalParameterOverrides(selection.paramOverrides) } })
450
- };
451
- }
452
- var DEFAULT_VITE_ENV = {
453
- VITE_ENABLE_PROMPT_GARDEN_IMPORT: "1",
454
- VITE_PROMPT_GARDEN_BASE_URL: "https://garden.always200.com"
455
- };
456
- var getDefaultEnvVar = (key) => {
457
- return DEFAULT_VITE_ENV[key] ?? "";
458
- };
459
- var CUSTOM_API_PATTERN = /^VITE_CUSTOM_API_(KEY|BASE_URL|MODEL|PARAMS|HEADERS)_(.+)$/;
460
- var SUFFIX_PATTERN = /^[a-zA-Z0-9_-]+$/;
461
- var MAX_SUFFIX_LENGTH = 50;
462
- var FORBIDDEN_CUSTOM_PARAM_KEYS = /* @__PURE__ */ new Set(["model", "messages", "stream"]);
463
- var cachedCustomModels = null;
464
- function validateCustomModelConfig(config) {
465
- const result = {
466
- valid: true,
467
- errors: [],
468
- warnings: []
469
- };
470
- if (!config.suffix) {
471
- result.errors.push("Suffix is required");
472
- result.valid = false;
473
- } else if (config.suffix.length > MAX_SUFFIX_LENGTH || !SUFFIX_PATTERN.test(config.suffix)) {
474
- result.errors.push(`Invalid suffix: ${config.suffix}. Use 1-${MAX_SUFFIX_LENGTH} alphanumeric characters, underscores, or hyphens`);
475
- result.valid = false;
476
- }
477
- if (!config.apiKey) {
478
- result.errors.push("API key is required");
479
- result.valid = false;
480
- } else if (config.apiKey.length < 8) {
481
- result.warnings.push("API key seems too short, please verify it is correct");
482
- }
483
- if (!config.baseURL) {
484
- result.errors.push("Base URL is required");
485
- result.valid = false;
486
- } else {
487
- try {
488
- const url = new URL(config.baseURL);
489
- if (!["http:", "https:"].includes(url.protocol)) {
490
- result.warnings.push(`Unusual protocol in baseURL: ${url.protocol}. Expected http: or https:`);
491
- }
492
- } catch (error) {
493
- result.errors.push(`Invalid baseURL format: ${config.baseURL}`);
494
- result.valid = false;
495
- }
496
- }
497
- if (!config.model) {
498
- result.errors.push("Model name is required");
499
- result.valid = false;
500
- }
501
- return result;
502
- }
503
- function parseCustomModelParams(rawParams, suffix) {
504
- try {
505
- const parsed = JSON.parse(rawParams);
506
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
507
- console.warn(`[scanCustomModelEnvVars] Invalid PARAMS for ${suffix}: must be a JSON object`);
508
- return void 0;
509
- }
510
- const sanitizedParams = { ...parsed };
511
- const removedKeys = [];
512
- FORBIDDEN_CUSTOM_PARAM_KEYS.forEach((key) => {
513
- if (key in sanitizedParams) {
514
- delete sanitizedParams[key];
515
- removedKeys.push(key);
516
- }
517
- });
518
- if (removedKeys.length > 0) {
519
- console.warn(
520
- `[scanCustomModelEnvVars] Ignored forbidden PARAMS keys for ${suffix}: ${removedKeys.join(", ")}`
521
- );
522
- }
523
- return sanitizedParams;
524
- } catch (error) {
525
- console.warn(`[scanCustomModelEnvVars] Failed to parse PARAMS for ${suffix}:`, error);
526
- return void 0;
527
- }
528
- }
529
- function parseCustomModelHeaders(rawHeaders, suffix) {
530
- try {
531
- const parsed = JSON.parse(rawHeaders);
532
- if (typeof parsed !== "object" || parsed === null) {
533
- console.warn(`[scanCustomModelEnvVars] Invalid HEADERS for ${suffix}: must be a JSON object or array`);
534
- return void 0;
535
- }
536
- const validation = validateCustomRequestHeaders(parsed);
537
- if (!validation.valid) {
538
- const details = validation.errors.map((error) => `${error.key} (${error.reason})`).join(", ");
539
- console.warn(`[scanCustomModelEnvVars] Ignored invalid HEADERS for ${suffix}: ${details}`);
540
- return void 0;
541
- }
542
- return normalizeCustomRequestHeaders(parsed);
543
- } catch (error) {
544
- console.warn(`[scanCustomModelEnvVars] Failed to parse HEADERS for ${suffix}:`, error);
545
- return void 0;
546
- }
547
- }
548
- var isBrowser = () => {
549
- return typeof window !== "undefined";
550
- };
551
- function isDevelopment() {
552
- const localDev = getEnvVar("VITE_LOCAL_DEV");
553
- return localDev === "true";
554
- }
555
- function isRunningInElectron() {
556
- if (typeof window === "undefined") {
557
- return false;
558
- }
559
- const platformEnv = getEnvVar("VITE_APP_PLATFORM");
560
- if (platformEnv) {
561
- console.log("[isRunningInElectron] Using platform from env:", platformEnv);
562
- return platformEnv === "electron";
563
- }
564
- const hasElectronAPI = typeof window.electronAPI !== "undefined";
565
- if (hasElectronAPI) {
566
- console.log("[isRunningInElectron] Verdict: true (via electronAPI)");
567
- return true;
568
- }
569
- const hasValidElectronProcess = typeof window.process !== "undefined" && window.process?.type === "renderer" && window.process?.versions?.electron;
570
- if (hasValidElectronProcess) {
571
- console.log("[isRunningInElectron] Verdict: true (via process.versions.electron)");
572
- return true;
573
- }
574
- console.log("[isRunningInElectron] Verdict: false (no Electron features detected)");
575
- return false;
576
- }
577
- function isElectronApiReady() {
578
- if (!isRunningInElectron()) {
579
- return false;
580
- }
581
- const window_any = window;
582
- const hasElectronAPI = typeof window_any.electronAPI !== "undefined";
583
- const hasPreferenceApi = hasElectronAPI && typeof window_any.electronAPI.preference !== "undefined";
584
- console.log("[isElectronApiReady] API readiness check:", {
585
- hasElectronAPI,
586
- hasPreferenceApi
587
- });
588
- return hasElectronAPI && hasPreferenceApi;
589
- }
590
- function waitForElectronApi(timeout = 5e3) {
591
- return new Promise((resolve) => {
592
- if (isElectronApiReady()) {
593
- console.log("[waitForElectronApi] API already ready");
594
- resolve(true);
595
- return;
596
- }
597
- console.log("[waitForElectronApi] Waiting for Electron API...");
598
- const startTime = Date.now();
599
- const checkInterval = setInterval(() => {
600
- if (isElectronApiReady()) {
601
- clearInterval(checkInterval);
602
- console.log("[waitForElectronApi] API ready after", Date.now() - startTime, "ms");
603
- resolve(true);
604
- } else if (Date.now() - startTime > timeout) {
605
- clearInterval(checkInterval);
606
- console.warn("[waitForElectronApi] Timeout waiting for Electron API after", timeout, "ms");
607
- resolve(false);
608
- }
609
- }, 50);
610
- });
611
- }
612
- var getEnvVar = (key) => {
613
- if (typeof window !== "undefined" && window.runtime_config) {
614
- const runtimeKey = key.replace("VITE_", "");
615
- const value = window.runtime_config[runtimeKey] ?? window.runtime_config[key];
616
- if (value !== void 0 && value !== null) {
617
- return String(value);
618
- }
619
- }
620
- if (typeof process !== "undefined" && process.env && process.env[key] !== void 0) {
621
- return process.env[key] || "";
622
- }
623
- try {
624
- if (typeof import.meta !== "undefined" && import.meta.env) {
625
- const value = import.meta.env[key];
626
- if (value) return value;
627
- }
628
- } catch {
629
- }
630
- const defaultValue = getDefaultEnvVar(key);
631
- if (defaultValue) return defaultValue;
632
- return "";
633
- };
634
- function scanCustomModelEnvVars(useCache = true) {
635
- if (useCache && cachedCustomModels) {
636
- return cachedCustomModels;
637
- }
638
- const customModels = {};
639
- const mergedEnv = {};
640
- try {
641
- if (typeof import.meta !== "undefined" && import.meta.env) {
642
- Object.entries(import.meta.env).forEach(([key, value]) => {
643
- if (value !== void 0 && value !== null) {
644
- mergedEnv[key] = String(value);
645
- }
646
- });
647
- }
648
- } catch (error) {
649
- console.warn("[scanCustomModelEnvVars] Failed to access import.meta.env:", error);
650
- }
651
- if (typeof process !== "undefined" && process.env) {
652
- Object.entries(process.env).forEach(([key, value]) => {
653
- if (value !== void 0) {
654
- mergedEnv[key] = value;
655
- }
656
- });
657
- }
658
- if (typeof window !== "undefined" && window.runtime_config) {
659
- Object.entries(window.runtime_config).forEach(([key, value]) => {
660
- if (value !== void 0 && value !== null) {
661
- mergedEnv[`VITE_${key}`] = String(value);
662
- }
663
- });
664
- }
665
- console.log(`[scanCustomModelEnvVars] Environment sources loaded`);
666
- const customApiPattern = CUSTOM_API_PATTERN;
667
- Object.entries(mergedEnv).forEach(([key, value]) => {
668
- if (value === void 0 || value === null || value === "") return;
669
- const match = key.match(customApiPattern);
670
- if (match) {
671
- const [, configType, suffix] = match;
672
- if (!suffix || suffix.length > MAX_SUFFIX_LENGTH || !SUFFIX_PATTERN.test(suffix)) {
673
- console.warn(`[scanCustomModelEnvVars] Invalid suffix in ${key}: ${suffix}`);
674
- return;
675
- }
676
- if (!customModels[suffix]) {
677
- customModels[suffix] = {
678
- suffix,
679
- apiKey: void 0,
680
- baseURL: void 0,
681
- model: void 0,
682
- params: void 0,
683
- headers: void 0
684
- };
685
- }
686
- switch (configType) {
687
- case "KEY":
688
- customModels[suffix].apiKey = value;
689
- break;
690
- case "BASE_URL":
691
- customModels[suffix].baseURL = value;
692
- break;
693
- case "MODEL":
694
- customModels[suffix].model = value;
695
- break;
696
- case "PARAMS":
697
- customModels[suffix].params = value;
698
- break;
699
- case "HEADERS":
700
- customModels[suffix].headers = value;
701
- break;
702
- default:
703
- console.warn(`[scanCustomModelEnvVars] Unknown config type: ${configType} in ${key}`);
704
- break;
705
- }
706
- }
707
- });
708
- const validModels = {};
709
- Object.entries(customModels).forEach(([suffix, config]) => {
710
- const validation = validateCustomModelConfig(config);
711
- if (validation.valid) {
712
- const validatedConfig = {
713
- suffix: config.suffix,
714
- apiKey: config.apiKey,
715
- baseURL: config.baseURL,
716
- model: config.model
717
- };
718
- if (config.params) {
719
- const parsedParams = parseCustomModelParams(config.params, suffix);
720
- if (parsedParams !== void 0) {
721
- validatedConfig.params = parsedParams;
722
- }
723
- }
724
- if (config.headers) {
725
- const parsedHeaders = parseCustomModelHeaders(config.headers, suffix);
726
- if (parsedHeaders !== void 0) {
727
- validatedConfig.customHeaders = parsedHeaders;
728
- }
729
- }
730
- validModels[suffix] = validatedConfig;
731
- if (validation.warnings.length > 0) {
732
- console.warn(`[scanCustomModelEnvVars] Warnings for ${suffix}:`);
733
- validation.warnings.forEach((warning) => {
734
- console.warn(` - ${warning}`);
735
- });
736
- }
737
- } else {
738
- console.error(`[scanCustomModelEnvVars] Skipping ${suffix} due to validation errors:`);
739
- validation.errors.forEach((error) => {
740
- console.error(` - ${error}`);
741
- });
742
- if (validation.warnings.length > 0) {
743
- console.warn(`[scanCustomModelEnvVars] Additional warnings for ${suffix}:`);
744
- validation.warnings.forEach((warning) => {
745
- console.warn(` - ${warning}`);
746
- });
747
- }
748
- }
749
- });
750
- console.log(`[scanCustomModelEnvVars] Found ${Object.keys(validModels).length} valid custom models:`, Object.keys(validModels));
751
- if (useCache) {
752
- cachedCustomModels = validModels;
753
- }
754
- return validModels;
755
- }
756
- function clearCustomModelEnvCache() {
757
- cachedCustomModels = null;
758
- console.log("[clearCustomModelEnvCache] Cache cleared");
759
- }
760
- var IpcSerializationError = class extends Error {
761
- constructor(details) {
762
- super(`[${CORE_ERROR_CODES.IPC_SERIALIZATION_FAILED}] ${details}`);
763
- __publicField(this, "code");
764
- __publicField(this, "params");
765
- this.name = "IpcSerializationError";
766
- this.code = CORE_ERROR_CODES.IPC_SERIALIZATION_FAILED;
767
- this.params = { details };
768
- }
769
- };
770
- function safeSerializeForIPC(obj) {
771
- if (obj === null || obj === void 0) {
772
- return obj;
773
- }
774
- if (typeof obj !== "object") {
775
- return obj;
776
- }
777
- try {
778
- const undefinedPaths = [];
779
- const paths = /* @__PURE__ */ new WeakMap();
780
- let root = true;
781
- const serialized = JSON.stringify(obj, function(key, value) {
782
- const path = root ? [] : [...paths.get(this) || [], key];
783
- root = false;
784
- if (value !== null && typeof value === "object") {
785
- paths.set(value, path);
786
- } else if (value === void 0 && !Array.isArray(this)) {
787
- undefinedPaths.push(path);
788
- }
789
- return value;
790
- });
791
- const result = JSON.parse(serialized);
792
- for (const path of undefinedPaths) {
793
- let parent = result;
794
- for (const key of path.slice(0, -1)) parent = parent[key];
795
- Object.defineProperty(parent, path[path.length - 1], {
796
- value: void 0,
797
- enumerable: true,
798
- configurable: true,
799
- writable: true
800
- });
801
- }
802
- return result;
803
- } catch (error) {
804
- console.error("[IPC Serialization] Failed to serialize object:", error);
805
- const details = error instanceof Error ? error.message : String(error);
806
- throw new IpcSerializationError(`Failed to serialize object for IPC: ${details}`);
807
- }
808
- }
809
- function debugIPCSerializability(obj, label = "object") {
810
- try {
811
- JSON.stringify(obj);
812
- console.log(`[IPC Debug] ${label} is serializable`);
813
- } catch (error) {
814
- console.error(`[IPC Debug] ${label} is NOT serializable:`, error);
815
- console.error(`[IPC Debug] Object:`, obj);
816
- }
817
- }
818
- function safeSerializeArgs(...args) {
819
- return args.map((arg) => safeSerializeForIPC(arg));
820
- }
821
- function runIpcStream(callbacks, start, cancel) {
822
- const { signal, ...handlers } = callbacks;
823
- if (!signal) return start(callbacks);
824
- if (signal.aborted) return Promise.reject(signal.reason);
825
- let id2;
826
- let settled = false;
827
- let terminal2 = false;
828
- let abort;
829
- const result = new Promise((resolve, reject) => {
830
- const cancelRequest = () => {
831
- if (id2) void cancel?.(id2).catch(() => {
832
- });
833
- };
834
- const fail = (error) => {
835
- if (!settled) {
836
- settled = true;
837
- reject(error);
838
- }
839
- };
840
- abort = () => {
841
- cancelRequest();
842
- fail(signal.reason);
843
- };
844
- signal.addEventListener("abort", abort, { once: true });
845
- const guard = (callback) => (...args) => {
846
- if (settled) return;
847
- try {
848
- callback?.(...args);
849
- } catch (error) {
850
- cancelRequest();
851
- fail(error);
852
- }
853
- };
854
- const complete = async (response) => {
855
- if (settled || terminal2) return;
856
- terminal2 = true;
857
- try {
858
- await handlers.onComplete(response);
859
- if (!settled) {
860
- settled = true;
861
- resolve();
862
- }
863
- } catch (error) {
864
- fail(error);
865
- }
866
- };
867
- Promise.resolve().then(() => start({
868
- ...handlers,
869
- onStart: (streamId) => {
870
- id2 = streamId;
871
- if (signal.aborted) cancelRequest();
872
- },
873
- onToken: guard(handlers.onToken),
874
- onReasoningToken: guard(handlers.onReasoningToken),
875
- onToolCall: guard(handlers.onToolCall),
876
- onComplete: complete,
877
- onError: (error) => {
878
- guard(handlers.onError)(error);
879
- fail(error);
880
- }
881
- })).then(() => {
882
- if (!terminal2 && !settled) void complete();
883
- }, fail);
884
- });
885
- return result.finally(() => signal.removeEventListener("abort", abort));
886
- }
887
- var ElectronLLMProxy = class {
888
- constructor() {
889
- __publicField(this, "electronAPI");
890
- if (typeof window === "undefined" || !window.electronAPI) {
891
- throw new InitializationError("ElectronLLMProxy can only be used in Electron renderer process");
892
- }
893
- this.electronAPI = window.electronAPI;
894
- }
895
- async testConnection(provider) {
896
- await this.electronAPI.llm.testConnection(provider);
897
- }
898
- async sendMessage(messages, provider) {
899
- const safeMessages = safeSerializeForIPC(messages);
900
- return this.electronAPI.llm.sendMessage(safeMessages, provider);
901
- }
902
- async sendMessageStructured(messages, provider) {
903
- const safeMessages = safeSerializeForIPC(messages);
904
- return this.electronAPI.llm.sendMessageStructured(safeMessages, provider);
905
- }
906
- async sendMessageStream(messages, provider, callbacks, selection) {
907
- const safeMessages = safeSerializeForIPC(messages);
908
- await runIpcStream(callbacks, async (handlers) => {
909
- const adaptedCallbacks = {
910
- onStart: handlers.onStart,
911
- onContent: handlers.onToken,
912
- // 映射 onToken -> onContent
913
- onThinking: handlers.onReasoningToken || (() => {
914
- }),
915
- // 映射推理流
916
- onFinish: () => handlers.onComplete(),
917
- // 映射完成回调
918
- onError: handlers.onError
919
- };
920
- await this.electronAPI.llm.sendMessageStream(safeMessages, provider, adaptedCallbacks, selection ? safeSerializeForIPC(selection) : void 0);
921
- }, this.electronAPI.cancelStream);
922
- }
923
- async sendMessageStreamWithTools(messages, provider, tools, callbacks) {
924
- const safeMessages = safeSerializeForIPC(messages);
925
- const safeTools = safeSerializeForIPC(tools);
926
- await runIpcStream(callbacks, async (handlers) => {
927
- const adaptedCallbacks = {
928
- onStart: handlers.onStart,
929
- onContent: handlers.onToken,
930
- // 映射 onToken -> onContent
931
- onThinking: handlers.onReasoningToken || (() => {
932
- }),
933
- // 映射推理流
934
- onToolCall: handlers.onToolCall || (() => {
935
- }),
936
- // 🆕 映射工具调用回调
937
- onFinish: () => handlers.onComplete(),
938
- // 映射完成回调
939
- onError: handlers.onError
940
- };
941
- const maybe = this.electronAPI.llm.sendMessageStreamWithTools;
942
- if (typeof maybe === "function") {
943
- await maybe(safeMessages, provider, safeTools, adaptedCallbacks);
944
- return;
945
- }
946
- await this.electronAPI.llm.sendMessageStream(safeMessages, provider, adaptedCallbacks);
947
- }, this.electronAPI.cancelStream);
948
- }
949
- async fetchModelList(provider, customConfig) {
950
- const safeCustomConfig = customConfig ? safeSerializeForIPC(customConfig) : customConfig;
951
- return this.electronAPI.llm.fetchModelList(provider, safeCustomConfig);
952
- }
953
- };
954
- var LLMService = class {
955
- constructor(modelManager, registry) {
956
- __publicField(this, "modelManager", modelManager);
957
- __publicField(this, "registry");
958
- this.registry = registry ?? new TextAdapterRegistry();
959
- }
960
- /**
961
- * 验证消息格式
962
- */
963
- validateMessages(messages) {
964
- if (!Array.isArray(messages)) {
965
- throw new RequestConfigError("Messages must be an array");
966
- }
967
- if (messages.length === 0) {
968
- throw new RequestConfigError("Messages array cannot be empty");
969
- }
970
- messages.forEach((msg) => {
971
- if (!msg.role || !msg.content) {
972
- throw new RequestConfigError("Invalid message format: missing required fields");
973
- }
974
- if (!["system", "user", "assistant", "tool"].includes(msg.role)) {
975
- throw new RequestConfigError(`Unsupported message role: ${msg.role}`);
976
- }
977
- if (typeof msg.content !== "string") {
978
- throw new RequestConfigError("Message content must be a string");
979
- }
980
- });
981
- }
982
- /**
983
- * 验证模型配置
984
- */
985
- validateModelConfig(modelConfig, options = {}) {
986
- if (!modelConfig) {
987
- throw new RequestConfigError("Model config cannot be empty");
988
- }
989
- if (!modelConfig.providerMeta || !modelConfig.providerMeta.id) {
990
- throw new RequestConfigError("Model provider metadata cannot be empty");
991
- }
992
- if (!modelConfig.modelMeta || !modelConfig.modelMeta.id) {
993
- throw new RequestConfigError("Model metadata cannot be empty");
994
- }
995
- if (!options.allowDisabled && !modelConfig.enabled) {
996
- throw new RequestConfigError("Model is not enabled");
997
- }
998
- }
999
- /**
1000
- * 发送消息(结构化格式)
1001
- */
1002
- async sendMessageStructured(messages, provider) {
1003
- try {
1004
- if (!provider) {
1005
- throw new RequestConfigError("Model provider cannot be empty");
1006
- }
1007
- const modelConfig = await this.modelManager.getModel(provider);
1008
- if (!modelConfig) {
1009
- throw new RequestConfigError(`Model ${provider} not found`);
1010
- }
1011
- this.validateModelConfig(modelConfig);
1012
- this.validateMessages(messages);
1013
- const adapter = this.registry.getAdapter(modelConfig.providerMeta.id);
1014
- const runtimeConfig = this.prepareRuntimeConfig(modelConfig);
1015
- return await adapter.sendMessage(messages, runtimeConfig);
1016
- } catch (error) {
1017
- if (error instanceof RequestConfigError || error instanceof APIError) {
1018
- throw error;
1019
- }
1020
- throw new APIError(`Failed to send message: ${error.message}`);
1021
- }
1022
- }
1023
- /**
1024
- * 发送消息(传统格式,只返回主要内容)
1025
- */
1026
- async sendMessage(messages, provider) {
1027
- const response = await this.sendMessageStructured(messages, provider);
1028
- return response.content;
1029
- }
1030
- /** Preview the public SDK request fields without invoking the adapter's network path. */
1031
- describeStreamRequest(config) {
1032
- this.validateModelConfig(config);
1033
- const adapter = this.registry.getAdapter(config.providerMeta.id);
1034
- return adapter.describeStreamRequest?.(this.prepareRuntimeConfig(config));
1035
- }
1036
- /**
1037
- * 发送消息(流式,支持结构化和传统格式)
1038
- */
1039
- async sendMessageStream(messages, provider, callbacks, selection) {
1040
- try {
1041
- this.validateMessages(messages);
1042
- const modelConfig = selection?.configSnapshot ?? await this.modelManager.getModel(provider);
1043
- if (!modelConfig) {
1044
- throw new RequestConfigError(`Model ${provider} not found`);
1045
- }
1046
- this.validateModelConfig(modelConfig);
1047
- const adapter = this.registry.getAdapter(modelConfig.providerMeta.id);
1048
- const runtimeConfig = this.prepareRuntimeConfig(selection?.modelId ? resolveRuntimeTextModel(modelConfig, selection, this.registry) : modelConfig);
1049
- if (callbacks.onRequest && !adapter.describeStreamRequest?.(runtimeConfig)) {
1050
- throw new RequestConfigError("This adapter cannot capture text request evidence");
1051
- }
1052
- await adapter.sendMessageStream(messages, runtimeConfig, callbacks);
1053
- } catch (error) {
1054
- if (!callbacks.onRequest) console.error("Stream request failed:", error);
1055
- callbacks.onError(error instanceof Error ? error : new Error(String(error)));
1056
- throw error;
1057
- }
1058
- }
1059
- /**
1060
- * 发送消息(流式,支持工具调用)
1061
- * 🆕 支持工具调用的流式消息发送
1062
- */
1063
- async sendMessageStreamWithTools(messages, provider, tools, callbacks) {
1064
- try {
1065
- this.validateMessages(messages);
1066
- const modelConfig = await this.modelManager.getModel(provider);
1067
- if (!modelConfig) {
1068
- throw new RequestConfigError(`Model ${provider} not found`);
1069
- }
1070
- this.validateModelConfig(modelConfig);
1071
- const adapter = this.registry.getAdapter(modelConfig.providerMeta.id);
1072
- const runtimeConfig = this.prepareRuntimeConfig(modelConfig);
1073
- await adapter.sendMessageStreamWithTools(messages, runtimeConfig, tools, callbacks);
1074
- } catch (error) {
1075
- console.error("Stream request with tools failed:", error);
1076
- callbacks.onError(error instanceof Error ? error : new Error(String(error)));
1077
- throw error;
1078
- }
1079
- }
1080
- /**
1081
- * 测试连接
1082
- */
1083
- async testConnection(provider) {
1084
- try {
1085
- if (!provider) {
1086
- throw new RequestConfigError("Model provider cannot be empty");
1087
- }
1088
- const modelConfig = await this.modelManager.getModel(provider);
1089
- if (!modelConfig) {
1090
- throw new RequestConfigError(`Model ${provider} not found`);
1091
- }
1092
- this.validateModelConfig(modelConfig, { allowDisabled: true });
1093
- const testMessages = [
1094
- {
1095
- role: "user",
1096
- content: "Please reply ok"
1097
- }
1098
- ];
1099
- this.validateMessages(testMessages);
1100
- const adapter = this.registry.getAdapter(modelConfig.providerMeta.id);
1101
- const runtimeConfig = this.prepareRuntimeConfig(modelConfig);
1102
- await adapter.sendMessage(testMessages, runtimeConfig);
1103
- } catch (error) {
1104
- if (error instanceof RequestConfigError || error instanceof APIError) {
1105
- throw error;
1106
- }
1107
- throw new APIError(`Connection test failed: ${error.message}`);
1108
- }
1109
- }
1110
- /**
1111
- * 获取模型列表,以下拉选项格式返回
1112
- * @param provider 提供商标识
1113
- * @param customConfig 自定义配置(可选)
1114
- */
1115
- async fetchModelList(provider, customConfig) {
1116
- try {
1117
- const baseConfig = await this.modelManager.getModel(provider);
1118
- const modelConfig = await this.buildEffectiveModelConfig(provider, baseConfig, customConfig);
1119
- const providerId = modelConfig.providerMeta.id;
1120
- let models = [];
1121
- if (this.registry.supportsDynamicModels(providerId)) {
1122
- const dynamicModels = await this.registry.getDynamicModels(providerId, modelConfig);
1123
- const staticModels = this.registry.getStaticModels(providerId);
1124
- const dynamicIds = new Set(dynamicModels.map((m) => m.id));
1125
- models = [
1126
- ...dynamicModels,
1127
- ...staticModels.filter((m) => !dynamicIds.has(m.id))
1128
- ];
1129
- } else {
1130
- models = this.registry.getStaticModels(providerId);
1131
- }
1132
- return models.map((model) => ({
1133
- value: model.id,
1134
- label: model.name
1135
- }));
1136
- } catch (error) {
1137
- console.error("Failed to fetch model list:", error);
1138
- if (error instanceof RequestConfigError || error instanceof APIError) {
1139
- throw error;
1140
- }
1141
- throw new APIError(`Failed to fetch model list: ${error.message}`);
1142
- }
1143
- }
1144
- prepareRuntimeConfig(modelConfig) {
1145
- const schema = modelConfig.modelMeta?.parameterDefinitions ?? [];
1146
- const mergedOverrides = mergeOverrides({
1147
- schema,
1148
- includeDefaults: false,
1149
- customOverrides: modelConfig.customParamOverrides,
1150
- // 🔧 兼容旧格式:自定义参数
1151
- requestOverrides: modelConfig.paramOverrides
1152
- // 当前参数(包含内置 + 可能已合并的自定义)
1153
- });
1154
- return {
1155
- ...modelConfig,
1156
- paramOverrides: mergedOverrides
1157
- };
1158
- }
1159
- /**
1160
- * 构建用于获取模型列表的有效模型配置
1161
- * 支持 TextModelConfig 与 传统 ModelConfig 两种输入结构
1162
- */
1163
- async buildEffectiveModelConfig(provider, baseConfig, customConfig) {
1164
- const customTextConfig = isTextConfigLike(customConfig) ? customConfig : void 0;
1165
- const customLegacyConfig = isLegacyConfigLike(customConfig) ? customConfig : void 0;
1166
- const providerId = (customTextConfig?.providerMeta?.id ?? normalizeLegacyProviderId(customLegacyConfig?.provider) ?? baseConfig?.providerMeta.id ?? provider).toLowerCase();
1167
- const baseProviderId = baseConfig?.providerMeta.id?.toLowerCase();
1168
- const adapter = this.registry.getAdapter(providerId);
1169
- const desiredModelId = customTextConfig?.modelMeta?.id ?? customLegacyConfig?.defaultModel ?? (baseProviderId === providerId ? baseConfig?.modelMeta.id : void 0) ?? adapter.getModels()[0]?.id ?? providerId;
1170
- const { providerMeta, modelMeta } = resolveTextModelMetadata({
1171
- providerId,
1172
- modelId: desiredModelId,
1173
- registry: this.registry,
1174
- existingProviderMeta: customTextConfig?.providerMeta ?? (baseProviderId === providerId ? baseConfig?.providerMeta : void 0),
1175
- existingModelMeta: customTextConfig?.modelMeta ?? (baseProviderId === providerId ? baseConfig?.modelMeta : void 0)
1176
- });
1177
- const connectionConfig = {
1178
- ...baseConfig?.connectionConfig ?? {},
1179
- ...customTextConfig?.connectionConfig ?? {}
1180
- };
1181
- if (customLegacyConfig?.apiKey) {
1182
- connectionConfig.apiKey = customLegacyConfig.apiKey;
1183
- }
1184
- if (customLegacyConfig?.baseURL) {
1185
- connectionConfig.baseURL = customLegacyConfig.baseURL;
1186
- }
1187
- if (!connectionConfig.baseURL && providerMeta.defaultBaseURL) {
1188
- connectionConfig.baseURL = providerMeta.defaultBaseURL;
1189
- }
1190
- const schema = modelMeta.parameterDefinitions ?? [];
1191
- const legacySplit = splitOverridesBySchema(schema, customLegacyConfig?.llmParams ?? {});
1192
- const combinedBuiltIn = {
1193
- ...baseConfig?.paramOverrides ?? {},
1194
- ...customTextConfig?.paramOverrides ?? {},
1195
- ...legacySplit.builtIn
1196
- };
1197
- const combinedCustom = {
1198
- ...baseConfig?.customParamOverrides ?? {},
1199
- ...customTextConfig?.customParamOverrides ?? {},
1200
- ...legacySplit.custom
1201
- };
1202
- return {
1203
- id: baseConfig?.id ?? provider,
1204
- name: customTextConfig?.name ?? customLegacyConfig?.name ?? baseConfig?.name ?? providerMeta.name,
1205
- enabled: baseConfig?.enabled ?? (customTextConfig?.enabled ?? true),
1206
- providerMeta,
1207
- modelMeta,
1208
- connectionConfig,
1209
- paramOverrides: combinedBuiltIn,
1210
- customParamOverrides: combinedCustom
1211
- };
1212
- }
1213
- };
1214
- function createLLMService(modelManager) {
1215
- if (isRunningInElectron()) {
1216
- console.log("[LLM Service Factory] Electron environment detected, using proxy.");
1217
- return new ElectronLLMProxy();
1218
- }
1219
- const registry = new TextAdapterRegistry();
1220
- return new LLMService(modelManager, registry);
1221
- }
1222
- function isTextConfigLike(config) {
1223
- return !!config && typeof config === "object" && "providerMeta" in config;
1224
- }
1225
- function isLegacyConfigLike(config) {
1226
- return !!config && typeof config === "object" && ("provider" in config || "defaultModel" in config || "baseURL" in config);
1227
- }
1228
- function normalizeLegacyProviderId(provider) {
1229
- if (!provider) {
1230
- return void 0;
1231
- }
1232
- return provider === "custom" ? "openai-compatible" : provider;
1233
- }
1234
- var TextComparisonError = class extends Error {
1235
- constructor(code, missingVariables) {
1236
- super(code === "MISSING_VARIABLES" && missingVariables?.length ? "Missing variables: " + missingVariables.join(", ") : "Text comparison request failed (" + code + ").");
1237
- __publicField(this, "code", code);
1238
- __publicField(this, "missingVariables", missingVariables);
1239
- this.name = "TextComparisonError";
1240
- }
1241
- };
1242
- var MAX_VARIABLE_VALUE_LENGTH = 1e4;
1243
- var FORBIDDEN_PREFIX_PATTERN = /^[#/^!>&]/u;
1244
- var RESERVED_VARIABLE_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
1245
- var isValidVariableName = (name) => name.length > 0 && name.length <= 50 && !/^[\d]|[\s{}]/u.test(name) && !FORBIDDEN_PREFIX_PATTERN.test(name) && !RESERVED_VARIABLE_NAMES.has(name);
1246
- var getVariable = (variables, name) => Object.prototype.hasOwnProperty.call(variables, name) ? variables[name] : void 0;
1247
- var VARIABLE_PATTERN = /\{\{\s*([^\d{}\s][^{}\s]*)\s*\}\}/gu;
1248
- var isMustacheControlTag = (name) => {
1249
- const trimmed = name.trim();
1250
- return FORBIDDEN_PREFIX_PATTERN.test(trimmed);
1251
- };
1252
- var scanVariableNames = (content) => {
1253
- const result = [];
1254
- if (!content) return result;
1255
- const seen = /* @__PURE__ */ new Set();
1256
- for (const match of content.matchAll(VARIABLE_PATTERN)) {
1257
- const rawName = String(match[1] || "").trim();
1258
- if (!rawName) continue;
1259
- if (isMustacheControlTag(rawName)) continue;
1260
- if (!isValidVariableName(rawName)) continue;
1261
- if (seen.has(rawName)) continue;
1262
- seen.add(rawName);
1263
- result.push(rawName);
1264
- }
1265
- return result;
1266
- };
1267
- var findForbiddenTemplateSyntax = (content) => {
1268
- if (!content) return [];
1269
- const found = [];
1270
- if (/\{\{\{[\s\S]*?\}\}\}/u.test(content)) found.push("triple_braces");
1271
- if (/\{\{\s*&/u.test(content)) found.push("ampersand_unescaped");
1272
- return found;
1273
- };
1274
- var findMissingVariables = (content, variables) => {
1275
- const used = scanVariableNames(content);
1276
- return used.filter((name) => {
1277
- const value = getVariable(variables, name);
1278
- if (value === void 0) return true;
1279
- return String(value).trim() === "";
1280
- });
1281
- };
1282
- var PromptRenderLimitError = class extends Error {
1283
- constructor() {
1284
- super("Rendered prompt exceeds the allowed length");
1285
- this.name = "PromptRenderLimitError";
1286
- }
1287
- };
1288
- var replaceVariablesInContent = (content, variables, maxRenderedLength = Number.POSITIVE_INFINITY) => {
1289
- if (!content) return content;
1290
- let renderedLength = 0;
1291
- let previousEnd = 0;
1292
- const rendered = content.replace(VARIABLE_PATTERN, (match, varName, offset) => {
1293
- const name = String(varName || "").trim();
1294
- const value = isValidVariableName(name) ? getVariable(variables, name) : void 0;
1295
- const replacement = value === void 0 ? match : String(value);
1296
- renderedLength += offset - previousEnd + replacement.length;
1297
- if (renderedLength > maxRenderedLength) throw new PromptRenderLimitError();
1298
- previousEnd = offset + match.length;
1299
- return replacement;
1300
- });
1301
- if (rendered.length > maxRenderedLength) throw new PromptRenderLimitError();
1302
- return rendered;
1303
- };
1304
- var hashString = (input) => {
1305
- let hash = 5381;
1306
- for (let i = 0; i < input.length; i++) {
1307
- hash = (hash << 5) + hash ^ input.charCodeAt(i);
1308
- }
1309
- return (hash >>> 0).toString(36);
1310
- };
1311
- var stableStringifyVars = (vars) => {
1312
- const keys = Object.keys(vars).sort();
1313
- let out = "";
1314
- for (const key of keys) {
1315
- out += `${key}=${vars[key] ?? ""}
1316
- `;
1317
- }
1318
- return out;
1319
- };
1320
- var hashVariables = (vars) => {
1321
- return hashString(stableStringifyVars(vars));
1322
- };
1323
- var buildPromptExecutionContext = (content, variables, maxRenderedLength) => {
1324
- return {
1325
- variables,
1326
- variablesHash: hashVariables(variables),
1327
- missingVariables: findMissingVariables(content, variables),
1328
- renderedContent: replaceVariablesInContent(content, variables, maxRenderedLength),
1329
- forbiddenTemplateSyntax: findForbiddenTemplateSyntax(content)
1330
- };
1331
- };
1332
- var buildConversationExecutionContext = (messages, variables) => {
1333
- const missing = /* @__PURE__ */ new Set();
1334
- const forbidden = /* @__PURE__ */ new Set();
1335
- const renderedMessages = (messages || []).map((msg) => {
1336
- const ctx = buildPromptExecutionContext(msg.content || "", variables);
1337
- ctx.missingVariables.forEach((name) => missing.add(name));
1338
- ctx.forbiddenTemplateSyntax.forEach((syntax) => forbidden.add(syntax));
1339
- return { ...msg, content: ctx.renderedContent };
1340
- });
1341
- return {
1342
- variables,
1343
- variablesHash: hashVariables(variables),
1344
- missingVariables: Array.from(missing),
1345
- renderedMessages,
1346
- forbiddenTemplateSyntax: Array.from(forbidden)
1347
- };
1348
- };
1349
- var CONTEXT_STORE_KEY = "ctx:store";
1350
- var DEFAULT_CONTEXT_MODE = "system";
1351
- var PREDEFINED_VARIABLES = [
1352
- "originalPrompt",
1353
- "lastOptimizedPrompt",
1354
- "iterateInput",
1355
- "currentPrompt",
1356
- // 测试阶段使用的当前提示词变量
1357
- "userQuestion",
1358
- // 用户问题变量
1359
- "conversationContext",
1360
- // 会话上下文变量
1361
- "toolsContext"
1362
- // 可用工具上下文(由模板处理器/服务注入)
1363
- ];
1364
- var DEFAULT_CONTEXT_CONFIG = {
1365
- id: "default",
1366
- title: "Default Context",
1367
- version: "1.0.0"
1368
- };
1369
- var CONTEXT_STORE_VERSION = "1.0.0";
1370
- var CONTEXT_UI_LABELS = {
1371
- /** 默认上下文标题模板 */
1372
- DEFAULT_TITLE_TEMPLATE: "Context",
1373
- // 将与日期组合使用
1374
- /** 副本后缀 */
1375
- DUPLICATE_SUFFIX: " (Copy)"
1376
- };
1377
- var MAX_PROMPT_LENGTH = 64 * 1024;
1378
- var VARIABLE_PREFERENCE_KEY = "pref:variableManager.storage";
1379
- var PREDEFINED_NAMES = new Set(PREDEFINED_VARIABLES);
1380
- var SUPPORTED_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openai-compatible"]);
1381
- function optionalRecord(value) {
1382
- return value === void 0 || record(value);
1383
- }
1384
- function validConfig(value) {
1385
- return isTextModelConfig(value) && record(value.connectionConfig) && Array.isArray(value.modelMeta.parameterDefinitions) && value.modelMeta.parameterDefinitions.every((item) => record(item) && text(item.name) && !["__proto__", "prototype", "constructor"].includes(item.name)) && optionalRecord(value.paramOverrides) && optionalRecord(value.customParamOverrides);
1386
- }
1387
- function isCredentialFieldValid(config, field) {
1388
- const value = config.connectionConfig[field];
1389
- return value === void 0 || typeof value === "string";
1390
- }
1391
- function inspectCandidate(entry, registry, llm) {
1392
- const { model, raw } = entry;
1393
- if (model.unavailableReason !== "EXECUTION_NOT_CONNECTED") return model.unavailableReason;
1394
- if (!SUPPORTED_PROVIDERS.has(model.providerId)) return "MODEL_EXECUTION_UNSUPPORTED";
1395
- if (!validConfig(raw) || !isCredentialFieldValid(raw, "baseURL") || !isCredentialFieldValid(raw, "apiKey")) {
1396
- return "MODEL_CONFIGURATION_INVALID";
1397
- }
1398
- try {
1399
- const adapter = registry.getAdapter(model.providerId);
1400
- if (!adapter.describeStreamRequest) return "MODEL_EXECUTION_UNSUPPORTED";
1401
- if (adapter.getProvider().requiresApiKey && !text(raw.connectionConfig.apiKey)) return "MODEL_CONFIGURATION_INVALID";
1402
- const config = resolveRuntimeTextModel(structuredClone(raw), { modelId: model.modelId }, registry);
1403
- const preview = llm.describeStreamRequest(config);
1404
- if (!preview || preview.modelId !== model.modelId) return "MODEL_CONFIGURATION_INVALID";
1405
- const declared = projectTextRequestEvidence(preview.api, { ...describeRuntimeModel(config).parameters, model: model.modelId });
1406
- const effective = {
1407
- parameterCoverage: "declared",
1408
- parameters: declared.parameters,
1409
- omittedParameterNames: Array.from(/* @__PURE__ */ new Set([...declared.omittedParameterNames, ...preview.omittedParameterNames])).sort(),
1410
- requestEvidence: "pending",
1411
- preview
1412
- };
1413
- return {
1414
- config,
1415
- model: { configKey: model.configKey, name: model.name, providerId: model.providerId, modelId: model.modelId },
1416
- effective
1417
- };
1418
- } catch {
1419
- return "MODEL_CONFIGURATION_INVALID";
1420
- }
1421
- }
1422
- function validateComparisonSelection(input) {
1423
- if (!record(input) || !record(input.source) || !record(input.variables) || ![input.source.favoriteId, input.source.assetId, input.source.versionId, input.source.expectedRevision].every(text) || !Array.isArray(input.candidates) || input.candidates.length !== 2 || input.candidates[0]?.id !== "a" || input.candidates[1]?.id !== "b" || !input.candidates.every((candidate2) => text(candidate2.configKey) && text(candidate2.expectedRevision))) {
1424
- throw new TextComparisonError("INVALID_INPUT");
1425
- }
1426
- const { candidatePrompt, candidates: [baseline, candidate], source } = input;
1427
- const sameModel = baseline.configKey === candidate.configKey;
1428
- if (candidatePrompt === void 0) {
1429
- if (sameModel) throw new TextComparisonError("INVALID_INPUT");
1430
- } else {
1431
- if (!sameModel || baseline.expectedRevision !== candidate.expectedRevision) throw new TextComparisonError("INVALID_INPUT");
1432
- if (object(candidatePrompt, ["kind", "text"]) && candidatePrompt.kind === "draft" && text(candidatePrompt.text)) {
1433
- if (candidatePrompt.text.length > MAX_PROMPT_LENGTH) throw new TextComparisonError("TEXT_LIMIT");
1434
- } else if (!object(candidatePrompt, ["kind", "versionId"]) || candidatePrompt.kind !== "saved-version" || !text(candidatePrompt.versionId) || candidatePrompt.versionId === source.versionId) {
1435
- throw new TextComparisonError("INVALID_INPUT");
1436
- }
1437
- }
1438
- let suppliedLength = 0;
1439
- for (const [name, value] of Object.entries(input.variables)) {
1440
- if (!isValidVariableName(name) || PREDEFINED_NAMES.has(name) || typeof value !== "string" || value.length > MAX_VARIABLE_VALUE_LENGTH) throw new TextComparisonError("INVALID_INPUT");
1441
- suppliedLength += name.length + value.length;
1442
- if (suppliedLength > MAX_PROMPT_LENGTH) throw new TextComparisonError("TEXT_LIMIT");
1443
- }
1444
- }
1445
- async function readSavedVariables(storage) {
1446
- try {
1447
- const raw = await storage.getItem(VARIABLE_PREFERENCE_KEY);
1448
- if (raw === null) return {};
1449
- const data = JSON.parse(raw);
1450
- if (!record(data) || !record(data.customVariables)) throw new TextComparisonError("INVALID_VARIABLE_STORAGE");
1451
- return Object.fromEntries(Object.entries(data.customVariables).filter(
1452
- (item) => isValidVariableName(item[0]) && !PREDEFINED_NAMES.has(item[0]) && typeof item[1] === "string"
1453
- ));
1454
- } catch {
1455
- throw new TextComparisonError("INVALID_VARIABLE_STORAGE");
1456
- }
1457
- }
1458
- function prepareRequest(sourcePrompt, savedVariables, suppliedVariables) {
1459
- const rawPrompt = sourcePrompt.trim();
1460
- if (!rawPrompt) throw new TextComparisonError("ASSET_CONTENT_UNSUPPORTED");
1461
- if (rawPrompt.length > MAX_PROMPT_LENGTH) throw new TextComparisonError("TEXT_LIMIT");
1462
- const merged = { ...savedVariables, ...suppliedVariables, currentPrompt: rawPrompt, userQuestion: rawPrompt };
1463
- const used = scanVariableNames(rawPrompt);
1464
- const variables = Object.fromEntries(used.filter((name) => Object.prototype.hasOwnProperty.call(merged, name)).map(
1465
- (name) => [name, merged[name]]
1466
- ));
1467
- if (Object.values(variables).reduce((size, value) => size + value.length, 0) > MAX_PROMPT_LENGTH * 3) {
1468
- throw new TextComparisonError("TEXT_LIMIT");
1469
- }
1470
- try {
1471
- const ctx = buildPromptExecutionContext(rawPrompt, variables, MAX_PROMPT_LENGTH);
1472
- if (ctx.forbiddenTemplateSyntax.length) throw new TextComparisonError("FORBIDDEN_TEMPLATE_SYNTAX");
1473
- if (ctx.missingVariables.length) throw new TextComparisonError("MISSING_VARIABLES", ctx.missingVariables);
1474
- if (!ctx.renderedContent.trim()) throw new TextComparisonError("ASSET_CONTENT_UNSUPPORTED");
1475
- return { rawPrompt, messages: [{ role: "user", content: ctx.renderedContent }], variables };
1476
- } catch (error) {
1477
- if (error instanceof PromptRenderLimitError) throw new TextComparisonError("TEXT_LIMIT");
1478
- throw error;
1479
- }
1480
- }
1481
- function createComparisonPreparation(storage, executionSource, registry, llm) {
1482
- const access = createAssetReadAccess(storage, executionSource);
1483
- return {
1484
- reader: access.reader,
1485
- listModels(options = {}) {
1486
- return access.listModels(options, ({ model: { unavailableReason, executable, ...description }, raw }) => {
1487
- const candidate = inspectCandidate({ model: { ...description, unavailableReason, executable }, raw }, registry, llm);
1488
- return typeof candidate === "string" ? { ...description, executable: false, unavailableReason: candidate } : { ...description, executable: true };
1489
- });
1490
- },
1491
- async prepare(input) {
1492
- const { candidates, source, variables, candidatePrompt } = input;
1493
- const [asset, models, savedVariables] = await Promise.all([
1494
- access.reader.getAssetVersion(source),
1495
- access.readStoredModels(candidates.map((candidate) => candidate.configKey)),
1496
- readSavedVariables(storage)
1497
- ]);
1498
- if (asset.modeKey !== "pro-variable") throw new TextComparisonError("ASSET_CONTENT_UNSUPPORTED");
1499
- const request = prepareRequest(asset.content.text, savedVariables, variables);
1500
- let candidateSnapshot;
1501
- if (candidatePrompt?.kind === "draft") {
1502
- candidateSnapshot = { kind: "draft", request: prepareRequest(candidatePrompt.text, savedVariables, variables) };
1503
- } else if (candidatePrompt) {
1504
- const selected = await access.reader.getAssetVersion({ ...source, versionId: candidatePrompt.versionId });
1505
- candidateSnapshot = {
1506
- kind: "saved-version",
1507
- versionId: selected.versionId,
1508
- version: selected.version,
1509
- request: prepareRequest(selected.content.text, savedVariables, variables)
1510
- };
1511
- }
1512
- function resolveCandidate(selection) {
1513
- const entry = models.find((item) => item.model.configKey === selection.configKey);
1514
- if (!entry) throw new TextComparisonError("MODEL_NOT_FOUND");
1515
- if (entry.model.revision !== selection.expectedRevision) throw new TextComparisonError("REVISION_CONFLICT");
1516
- const candidate = inspectCandidate(entry, registry, llm);
1517
- if (typeof candidate === "string") throw new TextComparisonError(candidate);
1518
- return candidate;
1519
- }
1520
- const baseline = resolveCandidate(candidates[0]);
1521
- return {
1522
- source: {
1523
- favoriteId: asset.favoriteId,
1524
- assetId: asset.assetId,
1525
- versionId: asset.versionId,
1526
- expectedRevision: asset.revision,
1527
- title: asset.title
1528
- },
1529
- request,
1530
- candidatePrompt: candidateSnapshot,
1531
- candidates: [baseline, candidateSnapshot ? structuredClone(baseline) : resolveCandidate(candidates[1])]
1532
- };
1533
- }
1534
- };
1535
- }
1536
- var MAX_RETAINED_COMPARISONS = 8;
1537
- var PREVIEW_LIFETIME_MS = 5 * 6e4;
1538
- var RUN_TIMEOUT_MS = 10 * 6e4;
1539
- var RESULT_LIFETIME_MS = 30 * 6e4;
1540
- var MAX_OUTPUT_CHARS = 8e4;
1541
- var id = () => v4_default();
1542
- function createRun(side, candidate) {
1543
- return {
1544
- id: side,
1545
- runId: id(),
1546
- model: candidate.model,
1547
- effective: candidate.effective,
1548
- status: "prepared",
1549
- output: "",
1550
- reasoning: ""
1551
- };
1552
- }
1553
- function isCompleted(run) {
1554
- return terminal(run.status) && run.startedAt !== void 0 && run.completedAt !== void 0;
1555
- }
1556
- function createTextComparisonService({
1557
- storage,
1558
- executionSource,
1559
- registry = new TextAdapterRegistry(),
1560
- llm: connectedLLM
1561
- }) {
1562
- const source = {
1563
- kind: executionSource.kind,
1564
- sourceId: executionSource.sourceId,
1565
- sourceEpoch: executionSource.sourceEpoch,
1566
- connectionGeneration: executionSource.connectionGeneration,
1567
- label: executionSource.label
1568
- };
1569
- const llm = connectedLLM ?? new LLMService({
1570
- async getModel() {
1571
- throw new TextComparisonError("MODEL_CONFIGURATION_INVALID");
1572
- }
1573
- }, registry);
1574
- const preparation = createComparisonPreparation(storage, source, registry, llm);
1575
- const groups = /* @__PURE__ */ new Map();
1576
- let pendingPrepares = 0;
1577
- let disposed = false;
1578
- function assertOpen() {
1579
- if (disposed) throw new TextComparisonError("COMPARISON_SERVICE_CLOSED");
1580
- }
1581
- function requireGroup(preparedId) {
1582
- assertOpen();
1583
- const group = groups.get(preparedId);
1584
- if (!group) throw new TextComparisonError("PREPARATION_NOT_FOUND");
1585
- return group;
1586
- }
1587
- function expire(group) {
1588
- if (group.timer !== void 0) clearTimeout(group.timer);
1589
- groups.delete(group.view.preparedId);
1590
- group.selection = void 0;
1591
- group.candidates = void 0;
1592
- for (const controller of group.controllers.values()) controller.abort();
1593
- group.controllers.clear();
1594
- }
1595
- function schedule(group, delay, action) {
1596
- if (group.timer !== void 0) clearTimeout(group.timer);
1597
- group.timer = setTimeout(action, delay);
1598
- if (typeof group.timer === "object") group.timer.unref?.();
1599
- }
1600
- function finishRun(group, run, status, errorCode) {
1601
- if (disposed || !groups.has(group.view.preparedId) || terminal(run.status)) return;
1602
- run.completedAt = Math.max(run.startedAt ?? 0, Date.now());
1603
- run.startedAt ?? (run.startedAt = run.completedAt);
1604
- run.status = status;
1605
- if (errorCode) run.errorCode = errorCode;
1606
- const controller = group.controllers.get(run.runId);
1607
- group.controllers.delete(run.runId);
1608
- if (status !== "success") controller?.abort();
1609
- if (group.view.runs.every(isCompleted)) {
1610
- group.selection = void 0;
1611
- group.candidates = void 0;
1612
- schedule(group, RESULT_LIFETIME_MS, () => expire(group));
1613
- }
1614
- }
1615
- async function sendRun(group, run, candidate, controller) {
1616
- const active = () => run.status === "running" && !controller.signal.aborted;
1617
- const acceptEvidence = (evidence2) => {
1618
- if (!active()) throw new Error("Comparison request is no longer active");
1619
- if (canonical(evidence2) !== canonical(candidate.effective.preview)) {
1620
- finishRun(group, run, "error", "REQUEST_CHANGED");
1621
- throw new Error("Unexpected comparison request");
1622
- }
1623
- run.effective.request = structuredClone(evidence2);
1624
- run.effective.requestEvidence = "captured";
1625
- };
1626
- const append = (field, token) => {
1627
- if (!active()) return;
1628
- const remaining = MAX_OUTPUT_CHARS - run.output.length - run.reasoning.length;
1629
- if (token.length <= remaining) {
1630
- run[field] += token;
1631
- return;
1632
- }
1633
- let partial = token.slice(0, remaining);
1634
- if (/[\uD800-\uDBFF]$/u.test(partial)) partial = partial.slice(0, -1);
1635
- run[field] += partial;
1636
- finishRun(group, run, "error", "OUTPUT_LIMIT");
1637
- };
1638
- try {
1639
- const request = run.id === "b" && group.view.candidatePrompt ? group.view.candidatePrompt.request : group.view.request;
1640
- await llm.sendMessageStream(structuredClone(request.messages), run.model.configKey, {
1641
- signal: controller.signal,
1642
- onRequest: acceptEvidence,
1643
- onToken: (token) => {
1644
- append("output", token);
1645
- },
1646
- onReasoningToken: (token) => {
1647
- append("reasoning", token);
1648
- },
1649
- onComplete: (response) => {
1650
- if (!response) return;
1651
- if (!run.output) append("output", response.content);
1652
- if (!run.reasoning && response.reasoning) append("reasoning", response.reasoning);
1653
- },
1654
- onError: () => {
1655
- finishRun(group, run, "error", "MODEL_REQUEST_FAILED");
1656
- }
1657
- }, { configSnapshot: candidate.config });
1658
- if (run.effective.requestEvidence !== "captured") {
1659
- finishRun(group, run, "error", "REQUEST_EVIDENCE_MISSING");
1660
- } else if (!run.output.trim() && !run.reasoning.trim()) {
1661
- finishRun(group, run, "error", "MODEL_EMPTY_OUTPUT");
1662
- } else {
1663
- finishRun(group, run, "success");
1664
- }
1665
- } catch {
1666
- finishRun(group, run, "error", "MODEL_REQUEST_FAILED");
1667
- }
1668
- }
1669
- async function start(group, selection, candidates) {
1670
- try {
1671
- const current = await preparation.prepare(selection);
1672
- if (canonical(current.request) !== canonical(group.view.request) || canonical(current.candidatePrompt) !== canonical(group.view.candidatePrompt) || current.candidates.some((item, index) => canonical(item.effective.preview) !== canonical(candidates[index].effective.preview))) {
1673
- throw new TextComparisonError("STALE_PREPARATION");
1674
- }
1675
- } catch {
1676
- assertOpen();
1677
- expire(group);
1678
- throw new TextComparisonError("STALE_PREPARATION");
1679
- }
1680
- requireGroup(group.view.preparedId);
1681
- group.selection = void 0;
1682
- group.candidates = void 0;
1683
- const actions = group.view.runs.flatMap((run, index) => {
1684
- if (run.status !== "prepared") return [];
1685
- const controller = new AbortController();
1686
- group.controllers.set(run.runId, controller);
1687
- run.startedAt = Date.now();
1688
- run.status = "running";
1689
- return [{ run, candidate: candidates[index], controller }];
1690
- });
1691
- if (!actions.length) return;
1692
- schedule(group, RUN_TIMEOUT_MS, () => {
1693
- for (const run of group.view.runs) finishRun(group, run, "error", "REQUEST_TIMEOUT");
1694
- });
1695
- for (const { run, candidate, controller } of actions) void sendRun(group, run, candidate, controller);
1696
- }
1697
- return {
1698
- reader: preparation.reader,
1699
- listModels(options) {
1700
- assertOpen();
1701
- return preparation.listModels(options);
1702
- },
1703
- async prepare(input) {
1704
- assertOpen();
1705
- validateComparisonSelection(input);
1706
- if (groups.size + pendingPrepares >= MAX_RETAINED_COMPARISONS) throw new TextComparisonError("PREPARATION_LIMIT");
1707
- const selection = structuredClone(input);
1708
- pendingPrepares += 1;
1709
- try {
1710
- const result = await preparation.prepare(selection);
1711
- assertOpen();
1712
- const view = {
1713
- preparedId: id(),
1714
- comparisonId: id(),
1715
- previewRevision: id(),
1716
- expiresAt: Date.now() + PREVIEW_LIFETIME_MS,
1717
- executionSource: source,
1718
- source: result.source,
1719
- request: result.request,
1720
- ...result.candidatePrompt ? { candidatePrompt: result.candidatePrompt } : {},
1721
- runs: [createRun("a", result.candidates[0]), createRun("b", result.candidates[1])]
1722
- };
1723
- const group = {
1724
- view,
1725
- selection,
1726
- candidates: result.candidates,
1727
- controllers: /* @__PURE__ */ new Map()
1728
- };
1729
- groups.set(view.preparedId, group);
1730
- schedule(group, PREVIEW_LIFETIME_MS, () => expire(group));
1731
- return structuredClone(view);
1732
- } finally {
1733
- pendingPrepares -= 1;
1734
- }
1735
- },
1736
- async execute(preparedId, previewRevision) {
1737
- const group = requireGroup(preparedId);
1738
- if (group.view.previewRevision !== previewRevision) throw new TextComparisonError("REVISION_CONFLICT");
1739
- if (!group.starting && group.selection && group.candidates) {
1740
- if (Date.now() >= group.view.expiresAt) {
1741
- expire(group);
1742
- throw new TextComparisonError("STALE_PREPARATION");
1743
- }
1744
- group.starting = start(group, group.selection, group.candidates);
1745
- }
1746
- if (group.starting) {
1747
- try {
1748
- await group.starting;
1749
- } finally {
1750
- group.starting = void 0;
1751
- }
1752
- }
1753
- requireGroup(preparedId);
1754
- return structuredClone(group.view);
1755
- },
1756
- get(preparedId) {
1757
- return structuredClone(requireGroup(preparedId).view);
1758
- },
1759
- cancel(preparedId, runId) {
1760
- const group = requireGroup(preparedId);
1761
- const runs = runId === void 0 ? group.view.runs : group.view.runs.filter((run) => run.runId === runId);
1762
- if (!runs.length) throw new TextComparisonError("RUN_NOT_FOUND");
1763
- if (!group.starting && runs.some((run) => run.status === "prepared")) throw new TextComparisonError("COMPARISON_NOT_RUNNING");
1764
- for (const run of runs) finishRun(group, run, "cancelled");
1765
- return structuredClone(group.view);
1766
- },
1767
- completed(preparedId) {
1768
- const { view } = requireGroup(preparedId);
1769
- const [a, b] = view.runs;
1770
- if (!isCompleted(a) || !isCompleted(b)) throw new TextComparisonError("COMPARISON_NOT_COMPLETE");
1771
- return structuredClone({
1772
- id: view.comparisonId,
1773
- executionSource: view.executionSource,
1774
- source: view.source,
1775
- request: view.request,
1776
- ...view.candidatePrompt ? { candidatePrompt: view.candidatePrompt } : {},
1777
- runs: [a, b]
1778
- });
1779
- },
1780
- dispose() {
1781
- if (disposed) return;
1782
- disposed = true;
1783
- for (const group of groups.values()) expire(group);
1784
- }
1785
- };
1786
- }
1787
-
1788
- export {
1789
- v4_default,
1790
- ComparisonRepositoryError,
1791
- canonical,
1792
- createComparisonRepository,
1793
- cleanLocalParameterOverrides,
1794
- resolveRuntimeImageModel,
1795
- describeRuntimeModel,
1796
- resolveRuntimeTextModel,
1797
- DEFAULT_VITE_ENV,
1798
- getDefaultEnvVar,
1799
- CUSTOM_API_PATTERN,
1800
- SUFFIX_PATTERN,
1801
- MAX_SUFFIX_LENGTH,
1802
- validateCustomModelConfig,
1803
- isBrowser,
1804
- isDevelopment,
1805
- isRunningInElectron,
1806
- isElectronApiReady,
1807
- waitForElectronApi,
1808
- getEnvVar,
1809
- scanCustomModelEnvVars,
1810
- clearCustomModelEnvCache,
1811
- safeSerializeForIPC,
1812
- debugIPCSerializability,
1813
- safeSerializeArgs,
1814
- runIpcStream,
1815
- ElectronLLMProxy,
1816
- LLMService,
1817
- createLLMService,
1818
- TextComparisonError,
1819
- MAX_VARIABLE_VALUE_LENGTH,
1820
- isValidVariableName,
1821
- scanVariableNames,
1822
- findForbiddenTemplateSyntax,
1823
- findMissingVariables,
1824
- PromptRenderLimitError,
1825
- replaceVariablesInContent,
1826
- hashString,
1827
- stableStringifyVars,
1828
- hashVariables,
1829
- buildPromptExecutionContext,
1830
- buildConversationExecutionContext,
1831
- CONTEXT_STORE_KEY,
1832
- DEFAULT_CONTEXT_MODE,
1833
- PREDEFINED_VARIABLES,
1834
- DEFAULT_CONTEXT_CONFIG,
1835
- CONTEXT_STORE_VERSION,
1836
- CONTEXT_UI_LABELS,
1837
- createTextComparisonService
1838
- };