@prompt-optimizer/mcp-server 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +669 -0
- package/README.md +267 -0
- package/THIRD_PARTY_NOTICES.txt +4476 -0
- package/bin/prompt-optimizer-desktop-mcp.cjs +10 -0
- package/bin/prompt-optimizer-mcp.cjs +20 -0
- package/dist/browser.cjs +1 -0
- package/dist/browser.js +4202 -0
- package/dist/chunk-3FYJ3FRD.js +57 -0
- package/dist/chunk-E7Z4Y3F4.js +36402 -0
- package/dist/chunk-GBDJTSRW.js +298 -0
- package/dist/chunk-HLCN3DLS.js +19745 -0
- package/dist/chunk-HYVN7FZZ.js +4787 -0
- package/dist/chunk-MEUCFQGU.js +537 -0
- package/dist/chunk-N6AUTPPS.js +10647 -0
- package/dist/chunk-Q52SACHI.js +304 -0
- package/dist/chunk-Q5B3KFB3.js +31 -0
- package/dist/chunk-QSPNNVX3.js +49017 -0
- package/dist/chunk-SO4YJHYW.js +13450 -0
- package/dist/chunk-SV2GETJH.js +65 -0
- package/dist/chunk-TFH2LO2H.js +58 -0
- package/dist/chunk-TFJEYQ3G.js +786 -0
- package/dist/chunk-TLOFCHZI.js +70 -0
- package/dist/chunk-TQGHULC7.js +188 -0
- package/dist/chunk-UTOMPKTK.js +2209 -0
- package/dist/chunk-XXALDAL7.js +1838 -0
- package/dist/chunk-YT3U6B54.js +21 -0
- package/dist/desktop-business.cjs +1 -0
- package/dist/desktop-business.js +1227 -0
- package/dist/desktop-comparison-HDIQ6K45.js +22 -0
- package/dist/desktop-storage-YRABQCLF.js +14 -0
- package/dist/desktop.cjs +1 -0
- package/dist/desktop.js +26 -0
- package/dist/dist-O5VNBF5I.js +622 -0
- package/dist/dist-UMX52UME.js +481 -0
- package/dist/index.cjs +1 -0
- package/dist/index.js +12 -0
- package/dist/legacy.cjs +1 -0
- package/dist/legacy.js +26933 -0
- package/dist/multipart-parser-XE6WGDAU.js +373 -0
- package/dist/node-2RBNZOSK.js +2225 -0
- package/dist/node-4Z3USCHW.js +21 -0
- package/dist/node-QHGLD5ST.js +25 -0
- package/dist/registry-H5F4DGAM-UHR4F6LL.js +13 -0
- package/dist/src-7PBMYCGI.js +1398 -0
- package/dist/start.cjs +1 -0
- package/dist/start.js +16 -0
- package/package.json +30 -0
- package/preload-env.cjs +352 -0
- package/skills/prompt-optimizer-compare/SKILL.md +21 -0
|
@@ -0,0 +1,1227 @@
|
|
|
1
|
+
import { createRequire as __mcpCreateRequire } from "node:module";
|
|
2
|
+
const require = __mcpCreateRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
openComparisonDesktop
|
|
5
|
+
} from "./chunk-SV2GETJH.js";
|
|
6
|
+
import {
|
|
7
|
+
createDesktopToolDispatcher
|
|
8
|
+
} from "./chunk-Q52SACHI.js";
|
|
9
|
+
import {
|
|
10
|
+
createDesktopComparisonRouter,
|
|
11
|
+
publicDesktopError
|
|
12
|
+
} from "./chunk-GBDJTSRW.js";
|
|
13
|
+
import {
|
|
14
|
+
DesktopRunRepositoryError,
|
|
15
|
+
FavoriteManager,
|
|
16
|
+
VARIABLE_VALIDATION,
|
|
17
|
+
WorkspaceSessionTransfer,
|
|
18
|
+
createContextRepo,
|
|
19
|
+
createDataManager,
|
|
20
|
+
createDesktopRunRepository,
|
|
21
|
+
createEvaluationService,
|
|
22
|
+
createHistoryManager,
|
|
23
|
+
createImageAdapterRegistry,
|
|
24
|
+
createImageModelManager,
|
|
25
|
+
createImageService,
|
|
26
|
+
createImageUnderstandingService,
|
|
27
|
+
createModelManager,
|
|
28
|
+
createPreferenceService,
|
|
29
|
+
createPromptService,
|
|
30
|
+
createTemplateLanguageService,
|
|
31
|
+
createTemplateManager,
|
|
32
|
+
createVariableExtractionService,
|
|
33
|
+
createVariableValueGenerationService,
|
|
34
|
+
decodeTextModelSelection
|
|
35
|
+
} from "./chunk-E7Z4Y3F4.js";
|
|
36
|
+
import {
|
|
37
|
+
PREDEFINED_VARIABLES,
|
|
38
|
+
createComparisonRepository,
|
|
39
|
+
createLLMService,
|
|
40
|
+
findMissingVariables,
|
|
41
|
+
isValidVariableName,
|
|
42
|
+
replaceVariablesInContent
|
|
43
|
+
} from "./chunk-XXALDAL7.js";
|
|
44
|
+
import {
|
|
45
|
+
createTextAdapterRegistry
|
|
46
|
+
} from "./chunk-QSPNNVX3.js";
|
|
47
|
+
import "./chunk-SO4YJHYW.js";
|
|
48
|
+
import "./chunk-TFH2LO2H.js";
|
|
49
|
+
import {
|
|
50
|
+
CallToolRequestSchema,
|
|
51
|
+
ListToolsRequestSchema,
|
|
52
|
+
Server,
|
|
53
|
+
StdioServerTransport
|
|
54
|
+
} from "./chunk-N6AUTPPS.js";
|
|
55
|
+
import "./chunk-HLCN3DLS.js";
|
|
56
|
+
import {
|
|
57
|
+
AssetReadError,
|
|
58
|
+
createReadonlyAssetReader
|
|
59
|
+
} from "./chunk-UTOMPKTK.js";
|
|
60
|
+
import {
|
|
61
|
+
openExistingDesktopStorageForWriting
|
|
62
|
+
} from "./chunk-MEUCFQGU.js";
|
|
63
|
+
import "./chunk-Q5B3KFB3.js";
|
|
64
|
+
import "./chunk-TQGHULC7.js";
|
|
65
|
+
import "./chunk-3FYJ3FRD.js";
|
|
66
|
+
|
|
67
|
+
// src/desktop-business.ts
|
|
68
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
69
|
+
import { writeFile as writeFile2 } from "node:fs/promises";
|
|
70
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
71
|
+
|
|
72
|
+
// src/desktop-business-services.ts
|
|
73
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
74
|
+
|
|
75
|
+
// src/desktop-business-catalog.ts
|
|
76
|
+
var definitions = {
|
|
77
|
+
favorites: {
|
|
78
|
+
getFavorites: ["read", "options?"],
|
|
79
|
+
getFavorite: ["read", "id"],
|
|
80
|
+
searchFavorites: ["read", "keyword", "options?"],
|
|
81
|
+
getCategories: ["read"],
|
|
82
|
+
getStats: ["read"],
|
|
83
|
+
getAllTags: ["read"],
|
|
84
|
+
getCategoryUsage: ["read", "categoryId"],
|
|
85
|
+
exportFavorites: ["read", "ids?"],
|
|
86
|
+
validateImportData: ["read", "data", "options?"],
|
|
87
|
+
addFavorite: ["write", "favorite"],
|
|
88
|
+
updateFavorite: ["write", "id", "updates"],
|
|
89
|
+
setFavoritePromptAssetCurrentVersion: ["write", "id", "versionId"],
|
|
90
|
+
deleteFavoritePromptAssetVersion: ["write", "id", "versionId"],
|
|
91
|
+
deleteFavorite: ["write", "id"],
|
|
92
|
+
deleteFavorites: ["write", "ids"],
|
|
93
|
+
incrementUseCount: ["write", "id"],
|
|
94
|
+
addCategory: ["write", "category"],
|
|
95
|
+
updateCategory: ["write", "id", "updates"],
|
|
96
|
+
deleteCategory: ["write", "id"],
|
|
97
|
+
reorderCategories: ["write", "categoryIds"],
|
|
98
|
+
addTag: ["write", "tag"],
|
|
99
|
+
renameTag: ["write", "oldTag", "newTag"],
|
|
100
|
+
mergeTags: ["write", "sourceTags", "targetTag"],
|
|
101
|
+
deleteTag: ["write", "tag"],
|
|
102
|
+
importFavorites: ["write", "data", "options?"]
|
|
103
|
+
},
|
|
104
|
+
templates: {
|
|
105
|
+
listTemplates: ["read"],
|
|
106
|
+
getTemplate: ["read", "id"],
|
|
107
|
+
listTemplatesByType: ["read", "type"],
|
|
108
|
+
exportTemplate: ["read", "id"],
|
|
109
|
+
getCurrentBuiltinTemplateLanguage: ["read"],
|
|
110
|
+
getSupportedBuiltinTemplateLanguages: ["read"],
|
|
111
|
+
saveTemplate: ["write", "template"],
|
|
112
|
+
deleteTemplate: ["write", "id"],
|
|
113
|
+
importTemplate: ["write", "jsonString"],
|
|
114
|
+
changeBuiltinTemplateLanguage: ["write", "language"]
|
|
115
|
+
},
|
|
116
|
+
models: {
|
|
117
|
+
getAllModels: ["read"],
|
|
118
|
+
getEnabledModels: ["read"],
|
|
119
|
+
getModel: ["read", "key"],
|
|
120
|
+
addModel: ["write", "key", "config"],
|
|
121
|
+
updateModel: ["write", "key", "config"],
|
|
122
|
+
deleteModel: ["write", "key"],
|
|
123
|
+
enableModel: ["write", "key"],
|
|
124
|
+
disableModel: ["write", "key"]
|
|
125
|
+
},
|
|
126
|
+
imageModels: {
|
|
127
|
+
getAllConfigs: ["read"],
|
|
128
|
+
getEnabledConfigs: ["read"],
|
|
129
|
+
getConfig: ["read", "id"],
|
|
130
|
+
addConfig: ["write", "config"],
|
|
131
|
+
updateConfig: ["write", "id", "updates"],
|
|
132
|
+
deleteConfig: ["write", "id"]
|
|
133
|
+
},
|
|
134
|
+
contexts: {
|
|
135
|
+
list: ["read"],
|
|
136
|
+
get: ["read", "id"],
|
|
137
|
+
getCurrentId: ["read"],
|
|
138
|
+
exportAll: ["read"],
|
|
139
|
+
create: ["write", "meta?"],
|
|
140
|
+
duplicate: ["write", "id", "options?"],
|
|
141
|
+
rename: ["write", "id", "title"],
|
|
142
|
+
save: ["write", "context"],
|
|
143
|
+
update: ["write", "id", "patch"],
|
|
144
|
+
remove: ["write", "id"],
|
|
145
|
+
setCurrentId: ["write", "id"],
|
|
146
|
+
importAll: ["write", "bundle", "mode"]
|
|
147
|
+
},
|
|
148
|
+
history: {
|
|
149
|
+
getRecords: ["read"],
|
|
150
|
+
getRecord: ["read", "id"],
|
|
151
|
+
getAllChains: ["read"],
|
|
152
|
+
getChain: ["read", "chainId"],
|
|
153
|
+
getIterationChain: ["read", "recordId"],
|
|
154
|
+
addRecord: ["write", "record"],
|
|
155
|
+
createNewChain: ["write", "params"],
|
|
156
|
+
addIteration: ["write", "params"],
|
|
157
|
+
deleteRecord: ["write", "id"],
|
|
158
|
+
deleteChain: ["write", "chainId"],
|
|
159
|
+
clearHistory: ["write"]
|
|
160
|
+
},
|
|
161
|
+
settings: {
|
|
162
|
+
get: ["read", "key", "defaultValue"],
|
|
163
|
+
getAll: ["read"],
|
|
164
|
+
keys: ["read"],
|
|
165
|
+
exportData: ["read"],
|
|
166
|
+
set: ["write", "key", "value"],
|
|
167
|
+
delete: ["write", "key"],
|
|
168
|
+
importData: ["write", "data"]
|
|
169
|
+
},
|
|
170
|
+
variables: {
|
|
171
|
+
list: ["read"],
|
|
172
|
+
get: ["read", "name"],
|
|
173
|
+
set: ["write", "name", "value"],
|
|
174
|
+
delete: ["write", "name"]
|
|
175
|
+
},
|
|
176
|
+
workspaces: {
|
|
177
|
+
exportData: ["read"],
|
|
178
|
+
validateData: ["read", "data"],
|
|
179
|
+
importData: ["write", "data"]
|
|
180
|
+
},
|
|
181
|
+
providers: {
|
|
182
|
+
getAllProviders: ["read"],
|
|
183
|
+
getProvider: ["read", "id"],
|
|
184
|
+
getStaticModels: ["read", "providerId"]
|
|
185
|
+
},
|
|
186
|
+
imageProviders: {
|
|
187
|
+
getAllProviders: ["read"],
|
|
188
|
+
getProvider: ["read", "id"],
|
|
189
|
+
getStaticModels: ["read", "providerId"]
|
|
190
|
+
},
|
|
191
|
+
data: {
|
|
192
|
+
exportAllData: ["read"],
|
|
193
|
+
validateImportData: ["read", "dataString"],
|
|
194
|
+
importAllData: ["write", "dataString"]
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
var businessOperations = Object.entries(definitions).flatMap(([domain, operations]) => Object.entries(operations).map(([operation, [access, ...parameters]]) => ({
|
|
198
|
+
domain,
|
|
199
|
+
operation,
|
|
200
|
+
access,
|
|
201
|
+
arguments: parameters,
|
|
202
|
+
minimum: parameters.filter((parameter) => !parameter.endsWith("?")).length
|
|
203
|
+
})));
|
|
204
|
+
var DesktopBusinessError = class extends Error {
|
|
205
|
+
constructor(code) {
|
|
206
|
+
super(`Desktop business request failed (${code}).`);
|
|
207
|
+
this.code = code;
|
|
208
|
+
}
|
|
209
|
+
code;
|
|
210
|
+
};
|
|
211
|
+
function assertJson(value, depth = 0, budget = { remaining: 1e5 }) {
|
|
212
|
+
if (depth > 48 || --budget.remaining < 0) throw new DesktopBusinessError("INVALID_INPUT");
|
|
213
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
214
|
+
if (typeof value === "number" && Number.isFinite(value)) return;
|
|
215
|
+
if (Array.isArray(value)) {
|
|
216
|
+
for (const item of value) assertJson(item, depth + 1, budget);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
|
|
220
|
+
throw new DesktopBusinessError("INVALID_INPUT");
|
|
221
|
+
}
|
|
222
|
+
for (const [key, item] of Object.entries(value)) {
|
|
223
|
+
if (["__proto__", "constructor", "prototype"].includes(key)) throw new DesktopBusinessError("INVALID_INPUT");
|
|
224
|
+
assertJson(item, depth + 1, budget);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function publicBusinessError(error) {
|
|
228
|
+
const code = error instanceof DesktopBusinessError || error instanceof DesktopRunRepositoryError || error instanceof AssetReadError ? error.code : "BUSINESS_OPERATION_FAILED";
|
|
229
|
+
return { code, message: `Desktop business request failed (${code}).` };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// src/desktop-business-services.ts
|
|
233
|
+
var internalKey = (key) => key.startsWith("mcp:");
|
|
234
|
+
var revisionSecret = randomBytes(32);
|
|
235
|
+
function snapshotRevision(snapshot) {
|
|
236
|
+
return createHmac("sha256", revisionSecret).update(JSON.stringify([...snapshot].filter(([key]) => !internalKey(key)).sort(([left], [right]) => left.localeCompare(right)))).digest("hex");
|
|
237
|
+
}
|
|
238
|
+
function redactConfiguration(value) {
|
|
239
|
+
if (typeof value === "string" && /^\s*[[{]/.test(value)) {
|
|
240
|
+
try {
|
|
241
|
+
return JSON.stringify(redactConfiguration(JSON.parse(value)));
|
|
242
|
+
} catch {
|
|
243
|
+
return value;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (Array.isArray(value)) return value.map(redactConfiguration);
|
|
247
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, field]) => {
|
|
248
|
+
if (/api.?key|access.?key|authorization|password|secret|token|headers|credential|connectionConfig/i.test(key)) return [key, "[REDACTED]"];
|
|
249
|
+
if (/url|endpoint|proxy/i.test(key) && typeof field === "string") {
|
|
250
|
+
try {
|
|
251
|
+
const url = new URL(field);
|
|
252
|
+
return [key, `${url.protocol}//${url.hostname}${url.port ? `:${url.port}` : ""}/[REDACTED]`];
|
|
253
|
+
} catch {
|
|
254
|
+
return [key, "[REDACTED]"];
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return [key, redactConfiguration(field)];
|
|
258
|
+
}));
|
|
259
|
+
return value;
|
|
260
|
+
}
|
|
261
|
+
var BusinessStage = class {
|
|
262
|
+
constructor(original) {
|
|
263
|
+
this.original = original;
|
|
264
|
+
this.values = new Map(original);
|
|
265
|
+
const known = ["models", "image-models", "user-templates", "prompt_history", "favorites", "favorite_categories", "favorite_tags", "favorite_stats"];
|
|
266
|
+
for (const key of known) {
|
|
267
|
+
const value = original.get(key);
|
|
268
|
+
if (value !== void 0) {
|
|
269
|
+
try {
|
|
270
|
+
const parsed = JSON.parse(value);
|
|
271
|
+
if (!parsed || typeof parsed !== "object") throw new Error();
|
|
272
|
+
} catch {
|
|
273
|
+
throw new DesktopBusinessError("SOURCE_DATA_INVALID");
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
original;
|
|
279
|
+
values;
|
|
280
|
+
observed = /* @__PURE__ */ new Set();
|
|
281
|
+
changed = /* @__PURE__ */ new Set();
|
|
282
|
+
services = /* @__PURE__ */ new Map();
|
|
283
|
+
async getItem(key) {
|
|
284
|
+
this.observed.add(key);
|
|
285
|
+
return this.values.get(key) ?? null;
|
|
286
|
+
}
|
|
287
|
+
async setItem(key, value) {
|
|
288
|
+
this.changed.add(key);
|
|
289
|
+
this.values.set(key, value);
|
|
290
|
+
}
|
|
291
|
+
async removeItem(key) {
|
|
292
|
+
this.changed.add(key);
|
|
293
|
+
this.values.delete(key);
|
|
294
|
+
}
|
|
295
|
+
async clearAll() {
|
|
296
|
+
for (const key of this.values.keys()) await this.removeItem(key);
|
|
297
|
+
}
|
|
298
|
+
async compareAndSetItem(key, expected, value) {
|
|
299
|
+
if (await this.getItem(key) !== expected) return false;
|
|
300
|
+
if (value === null) await this.removeItem(key);
|
|
301
|
+
else await this.setItem(key, value);
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
async updateData(key, modifier) {
|
|
305
|
+
const stored = await this.getItem(key);
|
|
306
|
+
await this.setItem(key, JSON.stringify(modifier(stored === null ? null : JSON.parse(stored))));
|
|
307
|
+
}
|
|
308
|
+
async batchUpdate(operations) {
|
|
309
|
+
for (const operation of operations) {
|
|
310
|
+
if (operation.operation === "remove") await this.removeItem(operation.key);
|
|
311
|
+
else if (operation.value !== void 0) await this.setItem(operation.key, operation.value);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
async getEntriesByPrefix(prefix) {
|
|
315
|
+
return [...this.values].filter(([key]) => key.startsWith(prefix)).map(([key, value]) => {
|
|
316
|
+
this.observed.add(key);
|
|
317
|
+
return [key, value];
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
async withWriteTransaction(modifier) {
|
|
321
|
+
const previous = new Map(this.values);
|
|
322
|
+
try {
|
|
323
|
+
const result = modifier({
|
|
324
|
+
getItem: (key) => {
|
|
325
|
+
this.observed.add(key);
|
|
326
|
+
return this.values.get(key) ?? null;
|
|
327
|
+
},
|
|
328
|
+
setItem: (key, value) => {
|
|
329
|
+
this.changed.add(key);
|
|
330
|
+
this.values.set(key, value);
|
|
331
|
+
},
|
|
332
|
+
removeItem: (key) => {
|
|
333
|
+
this.changed.add(key);
|
|
334
|
+
this.values.delete(key);
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
if (result && typeof result.then === "function") throw new DesktopBusinessError("ASYNC_TRANSACTION_REFUSED");
|
|
338
|
+
return result;
|
|
339
|
+
} catch (error) {
|
|
340
|
+
this.values.clear();
|
|
341
|
+
for (const [key, value] of previous) this.values.set(key, value);
|
|
342
|
+
throw error;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
getCapabilities() {
|
|
346
|
+
return { supportsAtomic: true, supportsBatch: true };
|
|
347
|
+
}
|
|
348
|
+
service(domain) {
|
|
349
|
+
if (!this.services.has(domain)) this.services.set(domain, this.createService(domain));
|
|
350
|
+
return this.services.get(domain);
|
|
351
|
+
}
|
|
352
|
+
async createService(domain) {
|
|
353
|
+
const typed = async (name) => await this.service(name);
|
|
354
|
+
switch (domain) {
|
|
355
|
+
case "favorites":
|
|
356
|
+
return new FavoriteManager(this);
|
|
357
|
+
case "settings":
|
|
358
|
+
return createPreferenceService(this);
|
|
359
|
+
case "variables": {
|
|
360
|
+
const preferences = await typed("settings");
|
|
361
|
+
const load = async () => {
|
|
362
|
+
const value = await preferences.get("variableManager.storage", { customVariables: {}, advancedModeEnabled: false, lastConversationMessages: [] });
|
|
363
|
+
if (!value || !value.customVariables || typeof value.customVariables !== "object" || Array.isArray(value.customVariables)) throw new DesktopBusinessError("SOURCE_DATA_INVALID");
|
|
364
|
+
return value;
|
|
365
|
+
};
|
|
366
|
+
const valid = (name) => {
|
|
367
|
+
if (typeof name !== "string" || !isValidVariableName(name) || PREDEFINED_VARIABLES.includes(name)) {
|
|
368
|
+
throw new DesktopBusinessError("INVALID_VARIABLE_NAME");
|
|
369
|
+
}
|
|
370
|
+
return name;
|
|
371
|
+
};
|
|
372
|
+
return {
|
|
373
|
+
list: async () => (await load()).customVariables,
|
|
374
|
+
get: async (name) => (await load()).customVariables[valid(name)] ?? null,
|
|
375
|
+
set: async (name, value) => {
|
|
376
|
+
valid(name);
|
|
377
|
+
if (typeof value !== "string" || value.length > VARIABLE_VALIDATION.MAX_VALUE_LENGTH) throw new DesktopBusinessError("INVALID_VARIABLE_VALUE");
|
|
378
|
+
const stored = await load();
|
|
379
|
+
stored.customVariables[name] = value;
|
|
380
|
+
await preferences.set("variableManager.storage", stored);
|
|
381
|
+
},
|
|
382
|
+
delete: async (name) => {
|
|
383
|
+
valid(name);
|
|
384
|
+
const stored = await load();
|
|
385
|
+
delete stored.customVariables[name];
|
|
386
|
+
await preferences.set("variableManager.storage", stored);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
case "contexts":
|
|
391
|
+
return createContextRepo(this);
|
|
392
|
+
case "models": {
|
|
393
|
+
const manager = createModelManager(this);
|
|
394
|
+
await manager.ensureInitialized();
|
|
395
|
+
return manager;
|
|
396
|
+
}
|
|
397
|
+
case "providers":
|
|
398
|
+
return this.providerService(createTextAdapterRegistry());
|
|
399
|
+
case "imageProviders":
|
|
400
|
+
return this.providerService(createImageAdapterRegistry());
|
|
401
|
+
case "imageModels": {
|
|
402
|
+
const manager = createImageModelManager(this, createImageAdapterRegistry());
|
|
403
|
+
await manager.ensureInitialized();
|
|
404
|
+
return manager;
|
|
405
|
+
}
|
|
406
|
+
case "templates": {
|
|
407
|
+
const language = createTemplateLanguageService(await typed("settings"));
|
|
408
|
+
await language.initialize();
|
|
409
|
+
return createTemplateManager(this, language);
|
|
410
|
+
}
|
|
411
|
+
case "history":
|
|
412
|
+
return createHistoryManager(this, await typed("models"));
|
|
413
|
+
case "llm":
|
|
414
|
+
return createLLMService(await typed("models"));
|
|
415
|
+
case "prompt":
|
|
416
|
+
return createPromptService(
|
|
417
|
+
await typed("models"),
|
|
418
|
+
await typed("llm"),
|
|
419
|
+
await typed("templates"),
|
|
420
|
+
await typed("history"),
|
|
421
|
+
createImageUnderstandingService()
|
|
422
|
+
);
|
|
423
|
+
case "evaluation":
|
|
424
|
+
return createEvaluationService(
|
|
425
|
+
await typed("llm"),
|
|
426
|
+
await typed("models"),
|
|
427
|
+
await typed("templates")
|
|
428
|
+
);
|
|
429
|
+
case "image":
|
|
430
|
+
return createImageService(await typed("imageModels"), createImageAdapterRegistry());
|
|
431
|
+
case "imageUnderstanding":
|
|
432
|
+
return createImageUnderstandingService();
|
|
433
|
+
case "variableExtraction":
|
|
434
|
+
return createVariableExtractionService(
|
|
435
|
+
await typed("llm"),
|
|
436
|
+
await typed("models"),
|
|
437
|
+
await typed("templates")
|
|
438
|
+
);
|
|
439
|
+
case "variableValues":
|
|
440
|
+
return createVariableValueGenerationService(
|
|
441
|
+
await typed("llm"),
|
|
442
|
+
await typed("models"),
|
|
443
|
+
await typed("templates")
|
|
444
|
+
);
|
|
445
|
+
case "workspaces":
|
|
446
|
+
return new WorkspaceSessionTransfer(await typed("settings"));
|
|
447
|
+
case "data":
|
|
448
|
+
return createDataManager(
|
|
449
|
+
await typed("models"),
|
|
450
|
+
await typed("templates"),
|
|
451
|
+
await typed("history"),
|
|
452
|
+
await typed("settings"),
|
|
453
|
+
await typed("contexts"),
|
|
454
|
+
await typed("imageModels"),
|
|
455
|
+
createComparisonRepository(this),
|
|
456
|
+
createDesktopRunRepository(this)
|
|
457
|
+
);
|
|
458
|
+
default:
|
|
459
|
+
throw new DesktopBusinessError("UNKNOWN_DOMAIN");
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
providerService(registry) {
|
|
463
|
+
return {
|
|
464
|
+
getAllProviders: () => registry.getAllProviders(),
|
|
465
|
+
getStaticModels: (providerId) => registry.getStaticModels(providerId),
|
|
466
|
+
getProvider: (id) => registry.getAllProviders().find((provider) => provider.id === id) ?? null
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
async invoke(domain, operation, parameters, access) {
|
|
470
|
+
const spec2 = businessOperations.find((item) => item.domain === domain && item.operation === operation && item.access === access);
|
|
471
|
+
if (!spec2) throw new DesktopBusinessError("UNKNOWN_OPERATION");
|
|
472
|
+
assertJson(parameters);
|
|
473
|
+
if (!Array.isArray(parameters) || parameters.length < spec2.minimum || parameters.length > spec2.arguments.length) {
|
|
474
|
+
throw new DesktopBusinessError("INVALID_ARGUMENTS");
|
|
475
|
+
}
|
|
476
|
+
if (domain === "settings" && typeof parameters[0] === "string" && (parameters[0].startsWith("mcp:") || parameters[0].startsWith("session/"))) {
|
|
477
|
+
throw new DesktopBusinessError("USE_WORKSPACE_OPERATIONS");
|
|
478
|
+
}
|
|
479
|
+
const service = await this.service(domain);
|
|
480
|
+
const result = await service[operation](...parameters);
|
|
481
|
+
return result ?? null;
|
|
482
|
+
}
|
|
483
|
+
async commit(provider, extra) {
|
|
484
|
+
await provider.withWriteTransaction((transaction) => {
|
|
485
|
+
for (const key of /* @__PURE__ */ new Set([...this.observed, ...this.changed])) {
|
|
486
|
+
if (transaction.getItem(key) !== (this.original.get(key) ?? null)) throw new DesktopBusinessError("REVISION_CONFLICT");
|
|
487
|
+
}
|
|
488
|
+
if (extra && transaction.getItem(extra.key) !== null) throw new DesktopBusinessError("REQUEST_ALREADY_COMMITTED");
|
|
489
|
+
for (const key of this.changed) {
|
|
490
|
+
const value = this.values.get(key);
|
|
491
|
+
if (value === void 0) transaction.removeItem(key);
|
|
492
|
+
else transaction.setItem(key, value);
|
|
493
|
+
}
|
|
494
|
+
if (extra) transaction.setItem(extra.key, extra.value);
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
// src/desktop-business-runs.ts
|
|
500
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
501
|
+
var runKinds = [
|
|
502
|
+
"optimize",
|
|
503
|
+
"optimize-message",
|
|
504
|
+
"iterate",
|
|
505
|
+
"test",
|
|
506
|
+
"test-conversation",
|
|
507
|
+
"evaluate",
|
|
508
|
+
"image",
|
|
509
|
+
"test-batch",
|
|
510
|
+
"extract-variables",
|
|
511
|
+
"generate-variable-values",
|
|
512
|
+
"model-list",
|
|
513
|
+
"model-test",
|
|
514
|
+
"image-model-list",
|
|
515
|
+
"image-model-test",
|
|
516
|
+
"image-understand"
|
|
517
|
+
];
|
|
518
|
+
var DesktopBusinessRuns = class {
|
|
519
|
+
constructor(provider, sourceId, revisionKey = globalThis.crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, false, ["sign"])) {
|
|
520
|
+
this.provider = provider;
|
|
521
|
+
this.sourceId = sourceId;
|
|
522
|
+
this.revisionKey = revisionKey;
|
|
523
|
+
this.repository = createDesktopRunRepository(provider);
|
|
524
|
+
}
|
|
525
|
+
provider;
|
|
526
|
+
sourceId;
|
|
527
|
+
revisionKey;
|
|
528
|
+
repository;
|
|
529
|
+
ownerId = `${process.pid}:${randomUUID()}`;
|
|
530
|
+
active = /* @__PURE__ */ new Map();
|
|
531
|
+
closing = false;
|
|
532
|
+
async start(input, requestKey, snapshot) {
|
|
533
|
+
assertJson(input);
|
|
534
|
+
if (this.closing) throw new DesktopBusinessError("SOURCE_CLOSING");
|
|
535
|
+
if (!input || typeof input !== "object" || !runKinds.includes(input.kind) || !input.request || typeof input.request !== "object" || Array.isArray(input.request) || Object.keys(input).some((key) => !["kind", "request", "source", "promptField", "inputRunId", "timeoutMs"].includes(key))) {
|
|
536
|
+
throw new DesktopBusinessError("INVALID_INPUT");
|
|
537
|
+
}
|
|
538
|
+
if (input.promptField !== void 0 && !["systemPrompt", "userPrompt"].includes(input.promptField)) throw new DesktopBusinessError("INVALID_INPUT");
|
|
539
|
+
if (input.source && (!input.source.expectedRevision || typeof input.source.expectedRevision !== "string")) {
|
|
540
|
+
throw new DesktopBusinessError("ASSET_REVISION_REQUIRED");
|
|
541
|
+
}
|
|
542
|
+
if ("configSnapshot" in input.request || "modelConfig" in input.request) throw new DesktopBusinessError("USE_SAVED_MODEL_CONFIGURATION");
|
|
543
|
+
if (input.timeoutMs !== void 0 && (!Number.isInteger(input.timeoutMs) || input.timeoutMs < 100 || input.timeoutMs > 6e5)) {
|
|
544
|
+
throw new DesktopBusinessError("INVALID_TIMEOUT");
|
|
545
|
+
}
|
|
546
|
+
const requestHash = createHash("sha256").update(JSON.stringify(input)).digest("hex");
|
|
547
|
+
const previous = (await this.repository.list()).find((run) => run.requestKey === requestKey);
|
|
548
|
+
if (previous) {
|
|
549
|
+
if (previous.deleted) throw new DesktopBusinessError("RUN_DELETED");
|
|
550
|
+
if (previous.requestHash !== requestHash) throw new DesktopBusinessError("REQUEST_KEY_REUSED");
|
|
551
|
+
return this.get(previous.id);
|
|
552
|
+
}
|
|
553
|
+
if (this.active.size >= 4) throw new DesktopBusinessError("RUN_CAPACITY_REACHED");
|
|
554
|
+
const stage = new BusinessStage(snapshot);
|
|
555
|
+
const request = structuredClone(input.request);
|
|
556
|
+
if (input.inputRunId) {
|
|
557
|
+
const dependency = await this.get(input.inputRunId);
|
|
558
|
+
if (dependency.status !== "succeeded") throw new DesktopBusinessError("INPUT_RUN_NOT_SUCCEEDED");
|
|
559
|
+
const output = dependency.output ?? dependency.partial;
|
|
560
|
+
if (typeof output !== "string" || !output.trim()) throw new DesktopBusinessError("INPUT_RUN_NOT_TEXT");
|
|
561
|
+
if (input.kind === "test") request[input.promptField ?? "systemPrompt"] = output;
|
|
562
|
+
else if (input.kind === "evaluate") {
|
|
563
|
+
const original = dependency.input.request;
|
|
564
|
+
request.target ??= { workspacePrompt: dependency.kind === "optimize" ? output : original.systemPrompt || original.userPrompt };
|
|
565
|
+
if (request.type === "result") {
|
|
566
|
+
request.testCase = { id: dependency.id, input: { kind: "text", label: "MCP test input", content: original.userPrompt ?? "" } };
|
|
567
|
+
request.snapshot = {
|
|
568
|
+
id: dependency.id,
|
|
569
|
+
label: "MCP test result",
|
|
570
|
+
testCaseId: dependency.id,
|
|
571
|
+
promptRef: { kind: "custom" },
|
|
572
|
+
promptText: original.systemPrompt ?? "",
|
|
573
|
+
output,
|
|
574
|
+
modelKey: original.modelKey
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
} else throw new DesktopBusinessError("INPUT_RUN_NOT_SUPPORTED");
|
|
578
|
+
}
|
|
579
|
+
if (input.source) {
|
|
580
|
+
const reader = createReadonlyAssetReader(stage, { sourceId: this.sourceId, sourceEpoch: "business-v1" }, { revisionKey: this.revisionKey });
|
|
581
|
+
const version = await reader.getAssetVersion(input.source);
|
|
582
|
+
const text2 = version.content.text;
|
|
583
|
+
if (input.kind === "optimize") request.targetPrompt = text2;
|
|
584
|
+
else if (input.kind === "iterate") request.originalPrompt = text2;
|
|
585
|
+
else if (input.kind === "test") request[input.promptField ?? "systemPrompt"] = text2;
|
|
586
|
+
else if (input.kind === "evaluate") request.target = { ...request.target ?? {}, workspacePrompt: text2 };
|
|
587
|
+
else throw new DesktopBusinessError("SOURCE_NOT_SUPPORTED_FOR_RUN");
|
|
588
|
+
}
|
|
589
|
+
const prepareTest = async (candidate) => {
|
|
590
|
+
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate) || "configSnapshot" in candidate || "modelConfig" in candidate) {
|
|
591
|
+
throw new DesktopBusinessError("INVALID_CANDIDATE");
|
|
592
|
+
}
|
|
593
|
+
if (candidate.source) {
|
|
594
|
+
const selection = candidate.source;
|
|
595
|
+
if (!selection.expectedRevision) throw new DesktopBusinessError("ASSET_REVISION_REQUIRED");
|
|
596
|
+
const reader = createReadonlyAssetReader(stage, { sourceId: this.sourceId, sourceEpoch: "business-v1" }, { revisionKey: this.revisionKey });
|
|
597
|
+
const version = await reader.getAssetVersion(selection);
|
|
598
|
+
if (candidate.promptField !== void 0 && !["systemPrompt", "userPrompt"].includes(candidate.promptField)) throw new DesktopBusinessError("INVALID_INPUT");
|
|
599
|
+
candidate[candidate.promptField ?? "systemPrompt"] = version.content.text;
|
|
600
|
+
}
|
|
601
|
+
if (candidate.variables !== void 0) {
|
|
602
|
+
const variables = candidate.variables;
|
|
603
|
+
if (!variables || typeof variables !== "object" || Array.isArray(variables) || Object.values(variables).some((value) => typeof value !== "string")) {
|
|
604
|
+
throw new DesktopBusinessError("INVALID_VARIABLES");
|
|
605
|
+
}
|
|
606
|
+
for (const field of ["systemPrompt", "userPrompt"]) {
|
|
607
|
+
if (typeof candidate[field] !== "string") continue;
|
|
608
|
+
if (findMissingVariables(candidate[field], variables).length) throw new DesktopBusinessError("MISSING_VARIABLES");
|
|
609
|
+
candidate[field] = replaceVariablesInContent(candidate[field], variables, 1024 * 1024);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
return candidate;
|
|
613
|
+
};
|
|
614
|
+
if (input.kind === "test") await prepareTest(request);
|
|
615
|
+
if (input.kind === "test-batch") {
|
|
616
|
+
if (!Array.isArray(request.candidates) || request.candidates.length < 2 || request.candidates.length > 4) throw new DesktopBusinessError("INVALID_CANDIDATES");
|
|
617
|
+
request.candidates = await Promise.all(request.candidates.map((candidate) => prepareTest(candidate)));
|
|
618
|
+
}
|
|
619
|
+
const candidates = input.kind === "test-batch" ? request.candidates : [request];
|
|
620
|
+
const executionModels = [];
|
|
621
|
+
const imageKind = ["image", "image-model-list", "image-model-test"].includes(input.kind);
|
|
622
|
+
for (const candidate of candidates) {
|
|
623
|
+
const key = candidate.modelKey ?? candidate.evaluationModelKey ?? candidate.extractionModelKey ?? candidate.generationModelKey ?? candidate.configId;
|
|
624
|
+
if (typeof key !== "string") throw new DesktopBusinessError("INVALID_MODEL_KEY");
|
|
625
|
+
const stored = JSON.parse(snapshot.get(imageKind ? "image-models" : "models") ?? "{}");
|
|
626
|
+
const configKey = imageKind ? key : decodeTextModelSelection(key)?.configId ?? key;
|
|
627
|
+
if (!Object.hasOwn(stored, configKey)) throw new DesktopBusinessError("MODEL_NOT_CONFIGURED");
|
|
628
|
+
const config = await (await stage.service(imageKind ? "imageModels" : "models"))[imageKind ? "getConfig" : "getModel"](key);
|
|
629
|
+
if (!config) throw new DesktopBusinessError("MODEL_NOT_FOUND");
|
|
630
|
+
executionModels.push(redactConfiguration({
|
|
631
|
+
configKey,
|
|
632
|
+
name: config.name,
|
|
633
|
+
providerId: config.providerId,
|
|
634
|
+
modelId: config.modelId,
|
|
635
|
+
paramOverrides: config.paramOverrides,
|
|
636
|
+
coverage: "frozen-saved-config"
|
|
637
|
+
}));
|
|
638
|
+
}
|
|
639
|
+
const state = {
|
|
640
|
+
id: randomUUID(),
|
|
641
|
+
requestKey,
|
|
642
|
+
requestHash,
|
|
643
|
+
ownerId: this.ownerId,
|
|
644
|
+
kind: input.kind,
|
|
645
|
+
status: "running",
|
|
646
|
+
createdAt: Date.now(),
|
|
647
|
+
updatedAt: Date.now(),
|
|
648
|
+
saved: false,
|
|
649
|
+
input: redactConfiguration({ ...input, request, executionModels, sourceRevision: input.source?.expectedRevision }),
|
|
650
|
+
partial: "",
|
|
651
|
+
reasoning: ""
|
|
652
|
+
};
|
|
653
|
+
const persisted = await this.repository.create(state);
|
|
654
|
+
if (persisted.id !== state.id) return this.get(persisted.id);
|
|
655
|
+
const controller = new AbortController();
|
|
656
|
+
const active = { controller, state, task: Promise.resolve() };
|
|
657
|
+
this.active.set(state.id, active);
|
|
658
|
+
active.task = this.execute(stage, input.kind, request, controller, state, input.timeoutMs ?? 18e4).finally(() => {
|
|
659
|
+
if (state.error?.code !== "RUN_PERSISTENCE_FAILED") this.active.delete(state.id);
|
|
660
|
+
});
|
|
661
|
+
return structuredClone(state);
|
|
662
|
+
}
|
|
663
|
+
async execute(stage, kind, request, controller, state, timeoutMs) {
|
|
664
|
+
const timer = setTimeout(() => controller.abort(new DesktopBusinessError("RUN_TIMEOUT")), timeoutMs);
|
|
665
|
+
let pollPending = false;
|
|
666
|
+
const cancellationTimer = setInterval(() => {
|
|
667
|
+
if (pollPending) return;
|
|
668
|
+
pollPending = true;
|
|
669
|
+
void this.repository.get(state.id).then((run) => {
|
|
670
|
+
if (run.cancelRequested) controller.abort(new DesktopBusinessError("RUN_CANCELLED"));
|
|
671
|
+
}).catch(() => {
|
|
672
|
+
}).finally(() => {
|
|
673
|
+
pollPending = false;
|
|
674
|
+
});
|
|
675
|
+
}, 500);
|
|
676
|
+
const handlers = {
|
|
677
|
+
signal: controller.signal,
|
|
678
|
+
onToken: (token) => {
|
|
679
|
+
controller.signal.throwIfAborted();
|
|
680
|
+
if ((state.partial?.length ?? 0) + token.length > 4 * 1024 * 1024) {
|
|
681
|
+
controller.abort(new DesktopBusinessError("OUTPUT_LIMIT_REACHED"));
|
|
682
|
+
controller.signal.throwIfAborted();
|
|
683
|
+
}
|
|
684
|
+
state.partial += token;
|
|
685
|
+
},
|
|
686
|
+
onReasoningToken: (token) => {
|
|
687
|
+
controller.signal.throwIfAborted();
|
|
688
|
+
if ((state.reasoning?.length ?? 0) + token.length > 4 * 1024 * 1024) {
|
|
689
|
+
controller.abort(new DesktopBusinessError("OUTPUT_LIMIT_REACHED"));
|
|
690
|
+
controller.signal.throwIfAborted();
|
|
691
|
+
}
|
|
692
|
+
state.reasoning += token;
|
|
693
|
+
},
|
|
694
|
+
onComplete: () => {
|
|
695
|
+
},
|
|
696
|
+
onError: (error) => {
|
|
697
|
+
throw error;
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
try {
|
|
701
|
+
let onAbort;
|
|
702
|
+
const interrupted = new Promise((_resolve, reject) => {
|
|
703
|
+
onAbort = () => reject(controller.signal.reason);
|
|
704
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
705
|
+
if (controller.signal.aborted) onAbort();
|
|
706
|
+
});
|
|
707
|
+
let output;
|
|
708
|
+
try {
|
|
709
|
+
output = await Promise.race([this.perform(stage, kind, request, handlers), interrupted]);
|
|
710
|
+
} finally {
|
|
711
|
+
if (onAbort) controller.signal.removeEventListener("abort", onAbort);
|
|
712
|
+
}
|
|
713
|
+
controller.signal.throwIfAborted();
|
|
714
|
+
state.status = "succeeded";
|
|
715
|
+
state.output = output ?? state.partial;
|
|
716
|
+
} catch (error) {
|
|
717
|
+
state.status = controller.signal.aborted ? "cancelled" : "failed";
|
|
718
|
+
state.error = publicBusinessError(controller.signal.aborted ? controller.signal.reason : error);
|
|
719
|
+
} finally {
|
|
720
|
+
clearTimeout(timer);
|
|
721
|
+
clearInterval(cancellationTimer);
|
|
722
|
+
state.updatedAt = Date.now();
|
|
723
|
+
try {
|
|
724
|
+
Object.assign(state, await this.repository.update(state.id, state));
|
|
725
|
+
} catch {
|
|
726
|
+
state.error = publicBusinessError(new DesktopBusinessError("RUN_PERSISTENCE_FAILED"));
|
|
727
|
+
state.status = "failed";
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
async perform(stage, kind, request, handlers) {
|
|
732
|
+
if (kind === "extract-variables") return (await stage.service("variableExtraction")).extract(request);
|
|
733
|
+
if (kind === "generate-variable-values") return (await stage.service("variableValues")).generate(request);
|
|
734
|
+
if (kind === "model-list" || kind === "model-test") {
|
|
735
|
+
if (typeof request.modelKey !== "string") throw new DesktopBusinessError("INVALID_MODEL_KEY");
|
|
736
|
+
const service2 = await stage.service("llm");
|
|
737
|
+
if (kind === "model-list") return service2.fetchModelList(request.modelKey);
|
|
738
|
+
await service2.testConnection(request.modelKey);
|
|
739
|
+
return { connected: true };
|
|
740
|
+
}
|
|
741
|
+
if (kind === "image-model-list" || kind === "image-model-test") {
|
|
742
|
+
if (typeof request.modelKey !== "string") throw new DesktopBusinessError("INVALID_MODEL_KEY");
|
|
743
|
+
const config = await (await stage.service("imageModels")).getConfig(request.modelKey);
|
|
744
|
+
if (!config) throw new DesktopBusinessError("MODEL_NOT_FOUND");
|
|
745
|
+
const service2 = await stage.service("image");
|
|
746
|
+
return kind === "image-model-list" ? service2.getDynamicModels(config.providerId, config.connectionConfig) : service2.testConnection(config);
|
|
747
|
+
}
|
|
748
|
+
if (kind === "image-understand") {
|
|
749
|
+
if (typeof request.modelKey !== "string") throw new DesktopBusinessError("INVALID_MODEL_KEY");
|
|
750
|
+
const modelConfig = await (await stage.service("models")).getModel(request.modelKey);
|
|
751
|
+
await (await stage.service("imageUnderstanding")).understandStream({ ...request, modelConfig }, handlers);
|
|
752
|
+
return void 0;
|
|
753
|
+
}
|
|
754
|
+
if (kind === "evaluate") {
|
|
755
|
+
const service2 = await stage.service("evaluation");
|
|
756
|
+
let output;
|
|
757
|
+
await service2.evaluateStream(request, {
|
|
758
|
+
...handlers,
|
|
759
|
+
onComplete: (result) => {
|
|
760
|
+
output = result;
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
if (!output) throw new DesktopBusinessError("EVALUATION_RESULT_MISSING");
|
|
764
|
+
return output;
|
|
765
|
+
}
|
|
766
|
+
if (kind === "image") {
|
|
767
|
+
const service2 = await stage.service("image");
|
|
768
|
+
return service2.generate(request);
|
|
769
|
+
}
|
|
770
|
+
if (kind === "test-batch") {
|
|
771
|
+
const candidates = request.candidates;
|
|
772
|
+
if (!Array.isArray(candidates) || candidates.length < 2 || candidates.length > 4) throw new DesktopBusinessError("INVALID_CANDIDATES");
|
|
773
|
+
return Promise.all(candidates.map(async (candidate, index) => {
|
|
774
|
+
let text2 = "";
|
|
775
|
+
try {
|
|
776
|
+
await this.perform(stage, "test", candidate, { ...handlers, onToken: (token) => {
|
|
777
|
+
handlers.signal?.throwIfAborted();
|
|
778
|
+
if (text2.length + token.length > 1024 * 1024) throw new DesktopBusinessError("OUTPUT_LIMIT_REACHED");
|
|
779
|
+
text2 += token;
|
|
780
|
+
} });
|
|
781
|
+
return { id: String(index + 1), status: "succeeded", output: text2 };
|
|
782
|
+
} catch (error) {
|
|
783
|
+
return { id: String(index + 1), status: handlers.signal?.aborted ? "cancelled" : "failed", output: text2, error: publicBusinessError(error) };
|
|
784
|
+
}
|
|
785
|
+
}));
|
|
786
|
+
}
|
|
787
|
+
const service = await stage.service("prompt");
|
|
788
|
+
if (kind === "optimize") await service.optimizePromptStream(request, handlers);
|
|
789
|
+
else if (kind === "optimize-message") await service.optimizeMessageStream(request, handlers);
|
|
790
|
+
else if (kind === "test-conversation") await service.testCustomConversationStream(request, handlers);
|
|
791
|
+
else if (kind === "test") await service.testPromptStream(request.systemPrompt ?? "", request.userPrompt ?? "", request.modelKey, handlers, request.inputImages);
|
|
792
|
+
else if (kind === "iterate") await service.iteratePromptStream(
|
|
793
|
+
request.originalPrompt,
|
|
794
|
+
request.lastOptimizedPrompt,
|
|
795
|
+
request.iterateInput,
|
|
796
|
+
request.modelKey,
|
|
797
|
+
handlers,
|
|
798
|
+
request.templateId,
|
|
799
|
+
request.contextData
|
|
800
|
+
);
|
|
801
|
+
else throw new DesktopBusinessError("INVALID_RUN_KIND");
|
|
802
|
+
return void 0;
|
|
803
|
+
}
|
|
804
|
+
async get(id) {
|
|
805
|
+
const active = this.active.get(id);
|
|
806
|
+
const state = active?.state ?? await this.repository.get(id);
|
|
807
|
+
if (state.status === "running" && state.ownerId !== this.ownerId) {
|
|
808
|
+
const ownerPid = Number(state.ownerId.split(":")[0]);
|
|
809
|
+
if (Number.isSafeInteger(ownerPid) && ownerPid > 0) {
|
|
810
|
+
try {
|
|
811
|
+
process.kill(ownerPid, 0);
|
|
812
|
+
} catch (error) {
|
|
813
|
+
if (error.code === "ESRCH") return this.repository.update(id, {
|
|
814
|
+
status: "interrupted",
|
|
815
|
+
error: publicBusinessError(new DesktopBusinessError("RUN_INTERRUPTED"))
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
const output = structuredClone(state);
|
|
821
|
+
if (output.status === "succeeded" && output.output === void 0) output.output = output.partial;
|
|
822
|
+
return output;
|
|
823
|
+
}
|
|
824
|
+
async cancel(id) {
|
|
825
|
+
const run = await this.get(id);
|
|
826
|
+
if (run.status !== "running") return run;
|
|
827
|
+
const active = this.active.get(id);
|
|
828
|
+
await this.repository.update(id, { cancelRequested: true });
|
|
829
|
+
active?.controller.abort(new DesktopBusinessError("RUN_CANCELLED"));
|
|
830
|
+
return this.get(id);
|
|
831
|
+
}
|
|
832
|
+
async save(id, target = "archive") {
|
|
833
|
+
const run = await this.get(id);
|
|
834
|
+
if (run.status === "running") throw new DesktopBusinessError("RUN_ACTIVE");
|
|
835
|
+
if (target === "history") {
|
|
836
|
+
if (run.historyChainId) return run;
|
|
837
|
+
if (run.status !== "succeeded" || typeof run.output !== "string" || !["optimize", "optimize-message", "iterate"].includes(run.kind)) throw new DesktopBusinessError("RUN_NOT_HISTORY_COMPATIBLE");
|
|
838
|
+
const stage = new BusinessStage(new Map(await this.provider.getAllEntries()));
|
|
839
|
+
const input = run.input.request;
|
|
840
|
+
const chain = await (await stage.service("history")).createNewChain({
|
|
841
|
+
id: randomUUID(),
|
|
842
|
+
originalPrompt: input.targetPrompt ?? input.originalPrompt ?? "",
|
|
843
|
+
optimizedPrompt: run.output,
|
|
844
|
+
type: input.optimizationMode === "user" ? "userOptimize" : "optimize",
|
|
845
|
+
timestamp: Date.now(),
|
|
846
|
+
modelKey: input.modelKey,
|
|
847
|
+
templateId: input.templateId ?? "",
|
|
848
|
+
metadata: { desktopRunId: run.id }
|
|
849
|
+
});
|
|
850
|
+
const saved = await createDesktopRunRepository(stage).update(id, { saved: true, historyChainId: chain.chainId });
|
|
851
|
+
await stage.commit(this.provider);
|
|
852
|
+
return saved;
|
|
853
|
+
}
|
|
854
|
+
return this.repository.update(id, { ...run, saved: true, input: redactConfiguration(run.input) });
|
|
855
|
+
}
|
|
856
|
+
async close() {
|
|
857
|
+
this.closing = true;
|
|
858
|
+
const runs = [...this.active.values()];
|
|
859
|
+
for (const run of runs) run.controller.abort(new DesktopBusinessError("SOURCE_CLOSING"));
|
|
860
|
+
await Promise.all(runs.map((run) => run.task));
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
|
|
864
|
+
// src/desktop-business-resources.ts
|
|
865
|
+
import { createConnection } from "node:net";
|
|
866
|
+
import { randomUUID as randomUUID2, createHash as createHash2 } from "node:crypto";
|
|
867
|
+
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
868
|
+
import { isAbsolute } from "node:path";
|
|
869
|
+
var resourceOperations = ["images.list", "images.get", "images.save", "images.delete", "package.export", "package.import"];
|
|
870
|
+
async function requestDesktopResource(storage, input) {
|
|
871
|
+
if (!resourceOperations.includes(input.operation)) throw new DesktopBusinessError("UNKNOWN_OPERATION");
|
|
872
|
+
if (["images.save", "images.get", "package.export", "package.import"].includes(input.operation) && (typeof input.file !== "string" || !isAbsolute(input.file))) throw new DesktopBusinessError("ABSOLUTE_FILE_REQUIRED");
|
|
873
|
+
if (["package.export", "package.import"].includes(input.operation) && input.includeCredentials !== true) {
|
|
874
|
+
throw new DesktopBusinessError("CREDENTIAL_TRANSFER_CONFIRMATION_REQUIRED");
|
|
875
|
+
}
|
|
876
|
+
const raw = await storage.getItem("mcp:renderer:resources");
|
|
877
|
+
if (!raw) throw new DesktopBusinessError("DESKTOP_RENDERER_REQUIRED");
|
|
878
|
+
const descriptor = JSON.parse(raw);
|
|
879
|
+
if (typeof descriptor.pipe !== "string" || !descriptor.pipe.startsWith(String.raw`\\.\pipe\po-desktop-resources-`) || typeof descriptor.token !== "string") throw new DesktopBusinessError("DESKTOP_RENDERER_REQUIRED");
|
|
880
|
+
const argumentsValue = { store: input.store, id: input.id, mimeType: input.mimeType, expectedDigest: input.expectedDigest };
|
|
881
|
+
if (input.operation === "images.save" || input.operation === "package.import") {
|
|
882
|
+
if ((await stat(input.file)).size > 20 * 1024 * 1024) throw new DesktopBusinessError("RESOURCE_INPUT_LIMIT");
|
|
883
|
+
const bytes = await readFile(input.file);
|
|
884
|
+
if (bytes.length > 20 * 1024 * 1024) throw new DesktopBusinessError("RESOURCE_INPUT_LIMIT");
|
|
885
|
+
argumentsValue.data = bytes.toString("base64");
|
|
886
|
+
if (input.operation === "images.save" && !argumentsValue.id) argumentsValue.id = `img_mcp_${createHash2("sha256").update(input.requestKey).digest("hex").slice(0, 24)}`;
|
|
887
|
+
}
|
|
888
|
+
const result = await new Promise((resolve, reject) => {
|
|
889
|
+
const socket = createConnection(descriptor.pipe);
|
|
890
|
+
socket.setEncoding("utf8");
|
|
891
|
+
let buffer = "";
|
|
892
|
+
const fail = () => {
|
|
893
|
+
socket.destroy();
|
|
894
|
+
reject(new DesktopBusinessError("RESOURCE_RESULT_UNKNOWN"));
|
|
895
|
+
};
|
|
896
|
+
socket.setTimeout(3e4, fail);
|
|
897
|
+
socket.once("error", fail);
|
|
898
|
+
socket.once("connect", () => socket.write(JSON.stringify({
|
|
899
|
+
...descriptor,
|
|
900
|
+
id: randomUUID2(),
|
|
901
|
+
requestKey: input.requestKey,
|
|
902
|
+
operation: input.operation,
|
|
903
|
+
arguments: argumentsValue
|
|
904
|
+
}) + "\n"));
|
|
905
|
+
socket.on("data", (chunk) => {
|
|
906
|
+
buffer += chunk.toString("utf8");
|
|
907
|
+
if (Buffer.byteLength(buffer) > 32 * 1024 * 1024) {
|
|
908
|
+
fail();
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
if (!buffer.includes("\n")) return;
|
|
912
|
+
socket.destroy();
|
|
913
|
+
try {
|
|
914
|
+
const response = JSON.parse(buffer.trim());
|
|
915
|
+
if (response.error) reject(new DesktopBusinessError(["REQUEST_KEY_REUSED", "RESOURCE_RESULT_UNKNOWN", "WORKSPACE_BUSY", "IMAGE_NOT_FOUND", "IMAGE_REVISION_CONFLICT", "IMAGE_REFERENCED"].includes(response.error) ? response.error : "RESOURCE_OPERATION_FAILED"));
|
|
916
|
+
else resolve(response.result);
|
|
917
|
+
} catch {
|
|
918
|
+
reject(new DesktopBusinessError("RESOURCE_RESPONSE_INVALID"));
|
|
919
|
+
}
|
|
920
|
+
});
|
|
921
|
+
socket.once("end", () => {
|
|
922
|
+
if (!buffer.includes("\n")) fail();
|
|
923
|
+
});
|
|
924
|
+
});
|
|
925
|
+
if (input.operation === "images.get" || input.operation === "package.export") {
|
|
926
|
+
const data = result.data;
|
|
927
|
+
if (typeof data !== "string") throw new DesktopBusinessError("RESOURCE_RESPONSE_INVALID");
|
|
928
|
+
await writeFile(input.file, Buffer.from(data, "base64"), { flag: "wx", mode: 384 });
|
|
929
|
+
const summary = { ...result };
|
|
930
|
+
delete summary.data;
|
|
931
|
+
return { ...summary, written: true };
|
|
932
|
+
}
|
|
933
|
+
return result;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// src/desktop-business.ts
|
|
937
|
+
var text = { type: "string", minLength: 1 };
|
|
938
|
+
var read = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
|
|
939
|
+
var write = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };
|
|
940
|
+
var sourceFields = { sourceId: text };
|
|
941
|
+
function spec(name, description, properties, required, annotations = read) {
|
|
942
|
+
return { name, description, inputSchema: { type: "object", properties, required, additionalProperties: false }, annotations };
|
|
943
|
+
}
|
|
944
|
+
var desktopBusinessTools = [
|
|
945
|
+
spec(
|
|
946
|
+
"po_resources",
|
|
947
|
+
"Use the open desktop renderer for real image stores or full ZIP import/export (app data, favorites and image resources). Windows desktop must be running this version. File writes create a NEW absolute file. Package transfers contain credentials and require includeCredentials=true. Input limit 20MiB. image deletion requires expectedDigest returned by images.get and refuses referenced images. A RESOURCE_RESULT_UNKNOWN may mean an edit applied; do not automatically retry with a new key.",
|
|
948
|
+
{
|
|
949
|
+
...sourceFields,
|
|
950
|
+
operation: { type: "string", enum: resourceOperations },
|
|
951
|
+
requestKey: text,
|
|
952
|
+
file: text,
|
|
953
|
+
store: { type: "string", enum: ["imageCache", "favoriteImages"] },
|
|
954
|
+
id: text,
|
|
955
|
+
mimeType: text,
|
|
956
|
+
expectedDigest: text,
|
|
957
|
+
includeCredentials: { type: "boolean" }
|
|
958
|
+
},
|
|
959
|
+
["sourceId", "operation", "requestKey"],
|
|
960
|
+
write
|
|
961
|
+
),
|
|
962
|
+
spec("po_sources_list", "List explicitly configured local desktop sources. Does not open or create a profile.", {}, []),
|
|
963
|
+
spec("po_desktop_catalog", "Discover available desktop business operations, ordered positional arguments, and asynchronous run kinds. Optional arguments have ?. Queries return a source revision; writes require that revision and a unique requestKey. No arbitrary service methods are callable.", { domain: text }, []),
|
|
964
|
+
spec(
|
|
965
|
+
"po_desktop_query",
|
|
966
|
+
"Read current desktop data through the product business services. Call the catalog first. Model credentials and private endpoint details are redacted. Assets expose exact saved versions.",
|
|
967
|
+
{ ...sourceFields, domain: text, operation: text, arguments: { type: "array", items: {} } },
|
|
968
|
+
["sourceId", "domain", "operation"]
|
|
969
|
+
),
|
|
970
|
+
spec(
|
|
971
|
+
"po_desktop_mutate",
|
|
972
|
+
"Perform an explicitly selected desktop edit using existing service validation. Requires a recent query revision. Reuse requestKey only for an exact retry; conflicting desktop edits are not overwritten. Deletion and import can be destructive.",
|
|
973
|
+
{ ...sourceFields, domain: text, operation: text, arguments: { type: "array", items: {} }, expectedRevision: text, requestKey: text },
|
|
974
|
+
["sourceId", "domain", "operation", "expectedRevision", "requestKey"],
|
|
975
|
+
write
|
|
976
|
+
),
|
|
977
|
+
spec(
|
|
978
|
+
"po_runs_start",
|
|
979
|
+
"Start optimization, message optimization, iteration, one test, a conversation test, evaluation, image generation, or 2-4 tests. This uses saved model credentials and can incur charges. Input and configurations are frozen from a single desktop snapshot. Query status with po_runs_get; network requests use the local Node runtime, not Electron proxy settings.",
|
|
980
|
+
{ ...sourceFields, requestKey: text, expectedRevision: text, input: { type: "object", properties: {
|
|
981
|
+
kind: { type: "string", enum: [...runKinds] },
|
|
982
|
+
request: { type: "object" },
|
|
983
|
+
source: { type: "object" },
|
|
984
|
+
promptField: { type: "string", enum: ["systemPrompt", "userPrompt"] },
|
|
985
|
+
inputRunId: text,
|
|
986
|
+
timeoutMs: { type: "integer", minimum: 100, maximum: 6e5 }
|
|
987
|
+
}, required: ["kind", "request"], additionalProperties: false } },
|
|
988
|
+
["sourceId", "requestKey", "expectedRevision", "input"],
|
|
989
|
+
{ ...write, destructiveHint: false, openWorldHint: true }
|
|
990
|
+
),
|
|
991
|
+
spec(
|
|
992
|
+
"po_runs_get",
|
|
993
|
+
"Get the current state, partial output, reasoning, final output, and sanitized failure for one run.",
|
|
994
|
+
{ ...sourceFields, runId: text },
|
|
995
|
+
["sourceId", "runId"]
|
|
996
|
+
),
|
|
997
|
+
spec(
|
|
998
|
+
"po_runs_list",
|
|
999
|
+
"List run summaries, optionally only explicitly saved results. No model calls are made.",
|
|
1000
|
+
{ ...sourceFields, savedOnly: { type: "boolean" } },
|
|
1001
|
+
["sourceId"]
|
|
1002
|
+
),
|
|
1003
|
+
spec(
|
|
1004
|
+
"po_runs_cancel",
|
|
1005
|
+
"Request cancellation of a running operation, including another client connected to the same source. Partial text is retained. Providers may continue processing a request already submitted.",
|
|
1006
|
+
{ ...sourceFields, runId: text },
|
|
1007
|
+
["sourceId", "runId"],
|
|
1008
|
+
{ ...write, destructiveHint: false }
|
|
1009
|
+
),
|
|
1010
|
+
spec(
|
|
1011
|
+
"po_runs_save",
|
|
1012
|
+
"Save a terminal optimization, test, evaluation, or image run for desktop reopening without overwriting the current workspace.",
|
|
1013
|
+
{ ...sourceFields, runId: text, target: { type: "string", enum: ["archive", "history"] } },
|
|
1014
|
+
["sourceId", "runId"],
|
|
1015
|
+
{ ...write, destructiveHint: false }
|
|
1016
|
+
),
|
|
1017
|
+
spec(
|
|
1018
|
+
"po_runs_delete",
|
|
1019
|
+
"Delete one terminal run with an optimistic timestamp guard.",
|
|
1020
|
+
{ ...sourceFields, runId: text, expectedUpdatedAt: { type: "integer", minimum: 0 } },
|
|
1021
|
+
["sourceId", "runId", "expectedUpdatedAt"],
|
|
1022
|
+
write
|
|
1023
|
+
),
|
|
1024
|
+
spec(
|
|
1025
|
+
"po_data_export_file",
|
|
1026
|
+
"Explicitly export the current product data to a NEW absolute local file, including model credentials. Never overwrites a file. Do not upload or share the result without user authorization.",
|
|
1027
|
+
{ ...sourceFields, destination: text, includeCredentials: { type: "boolean", const: true } },
|
|
1028
|
+
["sourceId", "destination", "includeCredentials"],
|
|
1029
|
+
{ ...write, destructiveHint: false }
|
|
1030
|
+
)
|
|
1031
|
+
];
|
|
1032
|
+
function createDesktopBusinessServer(profiles) {
|
|
1033
|
+
const router = createDesktopComparisonRouter(profiles, openComparisonDesktop);
|
|
1034
|
+
const comparison = createDesktopToolDispatcher("compare", router);
|
|
1035
|
+
const isComparisonTool = (name) => name !== "po_sources_list" && comparison.has(name);
|
|
1036
|
+
const tools = [...desktopBusinessTools, ...comparison.specs.filter((tool) => isComparisonTool(tool.name))];
|
|
1037
|
+
const sourceLeases = /* @__PURE__ */ new Map();
|
|
1038
|
+
const revisionKey = globalThis.crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
1039
|
+
const server = new Server({ name: "prompt-optimizer-desktop", version: "0.2.0" }, { capabilities: { tools: {} } });
|
|
1040
|
+
let closing;
|
|
1041
|
+
const open = async (sourceId) => {
|
|
1042
|
+
if (closing) throw new DesktopBusinessError("SOURCE_CLOSING");
|
|
1043
|
+
let opening = sourceLeases.get(sourceId);
|
|
1044
|
+
if (!opening) {
|
|
1045
|
+
const profile = router.getSourceProfile(sourceId);
|
|
1046
|
+
if (!profile) throw new DesktopBusinessError("SOURCE_NOT_FOUND");
|
|
1047
|
+
opening = (async () => {
|
|
1048
|
+
const lease = await openExistingDesktopStorageForWriting(profile.userDataPath);
|
|
1049
|
+
return { lease, runs: new DesktopBusinessRuns(lease.provider, sourceId, revisionKey) };
|
|
1050
|
+
})();
|
|
1051
|
+
sourceLeases.set(sourceId, opening);
|
|
1052
|
+
}
|
|
1053
|
+
try {
|
|
1054
|
+
return await opening;
|
|
1055
|
+
} catch {
|
|
1056
|
+
if (sourceLeases.get(sourceId) === opening) sourceLeases.delete(sourceId);
|
|
1057
|
+
throw new DesktopBusinessError("SOURCE_NOT_READY");
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
const callBusiness = async (name, args) => {
|
|
1061
|
+
const definition = desktopBusinessTools.find((item) => item.name === name);
|
|
1062
|
+
if (!definition) throw new DesktopBusinessError("UNKNOWN_TOOL");
|
|
1063
|
+
assertJson(args);
|
|
1064
|
+
if (args.savedOnly !== void 0 && typeof args.savedOnly !== "boolean") throw new DesktopBusinessError("INVALID_INPUT");
|
|
1065
|
+
if (JSON.stringify(args).length > 8 * 1024 * 1024) throw new DesktopBusinessError("INPUT_LIMIT_REACHED");
|
|
1066
|
+
if ((definition.inputSchema.required ?? []).some((key) => args[key] === void 0) || Object.keys(args).some((key) => !Object.hasOwn(definition.inputSchema.properties ?? {}, key))) throw new DesktopBusinessError("INVALID_INPUT");
|
|
1067
|
+
for (const key of ["sourceId", "domain", "operation", "expectedRevision", "requestKey", "runId"]) {
|
|
1068
|
+
if (args[key] !== void 0 && (typeof args[key] !== "string" || !args[key].trim() || args[key].length > 512)) {
|
|
1069
|
+
throw new DesktopBusinessError("INVALID_INPUT");
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
if (name === "po_sources_list") {
|
|
1073
|
+
return { sources: router.listSources().sources.map(({ sourceId, label }) => ({ sourceId, label, access: "business" })) };
|
|
1074
|
+
}
|
|
1075
|
+
if (name === "po_desktop_catalog") return {
|
|
1076
|
+
operations: businessOperations.filter((item) => !args.domain || item.domain === args.domain),
|
|
1077
|
+
assets: { domain: "assets", operations: ["listAssets(options?)", "listAssetVersions(selection, options?)", "getAssetVersion(selection)"] },
|
|
1078
|
+
runKinds,
|
|
1079
|
+
runInput: "request uses the existing product service request. source optionally selects favoriteId/assetId/versionId/expectedRevision. test: systemPrompt,userPrompt,modelKey,inputImages?; optimize: targetPrompt,optimizationMode,modelKey,templateId?; iterate: originalPrompt,lastOptimizedPrompt,iterateInput,modelKey,templateId; evaluate: EvaluationRequest; test-batch: candidates of 2-4 test requests."
|
|
1080
|
+
};
|
|
1081
|
+
const { lease, runs } = await open(args.sourceId);
|
|
1082
|
+
if (name === "po_resources") return requestDesktopResource(lease.provider, args);
|
|
1083
|
+
if (name === "po_runs_get") return runs.get(args.runId);
|
|
1084
|
+
if (name === "po_runs_cancel") return runs.cancel(args.runId);
|
|
1085
|
+
if (name === "po_runs_save") {
|
|
1086
|
+
if (args.target !== void 0 && !["archive", "history"].includes(args.target)) throw new DesktopBusinessError("INVALID_INPUT");
|
|
1087
|
+
return runs.save(args.runId, args.target);
|
|
1088
|
+
}
|
|
1089
|
+
if (name === "po_runs_delete") {
|
|
1090
|
+
if (!Number.isSafeInteger(args.expectedUpdatedAt) || args.expectedUpdatedAt < 0) throw new DesktopBusinessError("INVALID_INPUT");
|
|
1091
|
+
await runs.repository.delete(args.runId, args.expectedUpdatedAt);
|
|
1092
|
+
return { deleted: true };
|
|
1093
|
+
}
|
|
1094
|
+
if (name === "po_runs_list") return { runs: (await runs.repository.list()).filter((run) => !run.deleted && (!args.savedOnly || run.saved)).map(({ id, kind, status, createdAt, updatedAt, saved }) => ({ id, kind, status, createdAt, updatedAt, saved })) };
|
|
1095
|
+
const snapshot = new Map(await lease.provider.getAllEntries());
|
|
1096
|
+
const revision = snapshotRevision(snapshot);
|
|
1097
|
+
const stage = new BusinessStage(snapshot);
|
|
1098
|
+
const parameters = args.arguments ?? [];
|
|
1099
|
+
if (!Array.isArray(parameters)) throw new DesktopBusinessError("INVALID_ARGUMENTS");
|
|
1100
|
+
if (name === "po_desktop_query") {
|
|
1101
|
+
let result2;
|
|
1102
|
+
if (args.domain === "assets") {
|
|
1103
|
+
const reader = createReadonlyAssetReader(stage, { sourceId: args.sourceId, sourceEpoch: "business-v1" }, { revisionKey });
|
|
1104
|
+
if (!["listAssets", "listAssetVersions", "getAssetVersion"].includes(args.operation)) throw new DesktopBusinessError("UNKNOWN_OPERATION");
|
|
1105
|
+
result2 = await reader[args.operation](...parameters);
|
|
1106
|
+
} else result2 = await stage.invoke(args.domain, args.operation, parameters, "read");
|
|
1107
|
+
if (args.domain === "settings" && args.operation === "get" && typeof parameters[0] === "string") {
|
|
1108
|
+
result2 = redactConfiguration({ [parameters[0]]: result2 })[parameters[0]];
|
|
1109
|
+
}
|
|
1110
|
+
if (["models", "imageModels", "settings", "data"].includes(args.domain)) {
|
|
1111
|
+
result2 = typeof result2 === "string" && args.domain === "data" ? JSON.stringify(redactConfiguration(JSON.parse(result2))) : redactConfiguration(result2);
|
|
1112
|
+
}
|
|
1113
|
+
return { revision, result: result2 };
|
|
1114
|
+
}
|
|
1115
|
+
if (name === "po_data_export_file") {
|
|
1116
|
+
if (args.includeCredentials !== true || typeof args.destination !== "string" || !isAbsolute2(args.destination)) throw new DesktopBusinessError("INVALID_INPUT");
|
|
1117
|
+
const data = await stage.invoke("data", "exportAllData", [], "read");
|
|
1118
|
+
await writeFile2(args.destination, data, { flag: "wx", mode: 384 });
|
|
1119
|
+
return { exported: true, containsCredentials: true };
|
|
1120
|
+
}
|
|
1121
|
+
const signature = createHash3("sha256").update(JSON.stringify({ domain: args.domain, operation: args.operation, parameters })).digest("hex");
|
|
1122
|
+
const receiptKey = "mcp:receipt:" + createHash3("sha256").update(args.requestKey).digest("hex");
|
|
1123
|
+
if (name === "po_desktop_mutate") {
|
|
1124
|
+
const previous = snapshot.get(receiptKey);
|
|
1125
|
+
if (previous) {
|
|
1126
|
+
const receipt = JSON.parse(previous);
|
|
1127
|
+
if (receipt.signature !== signature) throw new DesktopBusinessError("REQUEST_KEY_REUSED");
|
|
1128
|
+
return receipt.result;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
if (name === "po_runs_start") {
|
|
1132
|
+
const previous = (await runs.repository.list()).find((run) => run.requestKey === args.requestKey);
|
|
1133
|
+
if (!previous && revision !== args.expectedRevision) throw new DesktopBusinessError("REVISION_CONFLICT");
|
|
1134
|
+
return runs.start(args.input, args.requestKey, snapshot);
|
|
1135
|
+
}
|
|
1136
|
+
if (revision !== args.expectedRevision) throw new DesktopBusinessError("REVISION_CONFLICT");
|
|
1137
|
+
if (["workspaces", "settings", "variables", "data"].includes(args.domain)) {
|
|
1138
|
+
const descriptor = await stage.getItem("mcp:renderer:resources");
|
|
1139
|
+
if (descriptor) {
|
|
1140
|
+
const owner = JSON.parse(descriptor);
|
|
1141
|
+
if (Number.isSafeInteger(owner.pid) && owner.pid > 0) {
|
|
1142
|
+
let active = true;
|
|
1143
|
+
try {
|
|
1144
|
+
process.kill(owner.pid, 0);
|
|
1145
|
+
} catch (error) {
|
|
1146
|
+
active = error.code !== "ESRCH";
|
|
1147
|
+
}
|
|
1148
|
+
if (active) throw new DesktopBusinessError("DESKTOP_STATE_IN_USE");
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
const result = redactConfiguration(await stage.invoke(args.domain, args.operation, parameters, "write"));
|
|
1153
|
+
const response = { revision: snapshotRevision(stage.values), result };
|
|
1154
|
+
await stage.commit(lease.provider, { key: receiptKey, value: JSON.stringify({ signature, result: response }) });
|
|
1155
|
+
return response;
|
|
1156
|
+
};
|
|
1157
|
+
const call = (name, args) => isComparisonTool(name) ? comparison.call(name, args) : callBusiness(name, args);
|
|
1158
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
1159
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
1160
|
+
const { name, arguments: args } = request.params;
|
|
1161
|
+
try {
|
|
1162
|
+
const result = await call(name, args ?? {});
|
|
1163
|
+
const payload = result;
|
|
1164
|
+
return { structuredContent: payload, content: [{ type: "text", text: JSON.stringify(result) }] };
|
|
1165
|
+
} catch (error) {
|
|
1166
|
+
const payload = { error: isComparisonTool(name) ? publicDesktopError(error, "compare") : publicBusinessError(error) };
|
|
1167
|
+
return { isError: true, structuredContent: payload, content: [{ type: "text", text: JSON.stringify(payload) }] };
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
return {
|
|
1171
|
+
server,
|
|
1172
|
+
call,
|
|
1173
|
+
close() {
|
|
1174
|
+
closing ??= (async () => {
|
|
1175
|
+
const results = await Promise.allSettled([
|
|
1176
|
+
router.dispose(),
|
|
1177
|
+
...Array.from(sourceLeases.values(), async (opening) => {
|
|
1178
|
+
const opened = await opening.catch(() => void 0);
|
|
1179
|
+
if (!opened) return;
|
|
1180
|
+
try {
|
|
1181
|
+
await opened.runs.close();
|
|
1182
|
+
} finally {
|
|
1183
|
+
await opened.lease.provider.close();
|
|
1184
|
+
}
|
|
1185
|
+
})
|
|
1186
|
+
]);
|
|
1187
|
+
sourceLeases.clear();
|
|
1188
|
+
const failure = results.find((result) => result.status === "rejected");
|
|
1189
|
+
if (failure) throw failure.reason;
|
|
1190
|
+
})();
|
|
1191
|
+
return closing;
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
async function startDesktopBusinessStdio(profiles) {
|
|
1196
|
+
const host = createDesktopBusinessServer(profiles);
|
|
1197
|
+
let shutdown;
|
|
1198
|
+
const close = () => {
|
|
1199
|
+
shutdown ??= (async () => {
|
|
1200
|
+
try {
|
|
1201
|
+
await host.close();
|
|
1202
|
+
} finally {
|
|
1203
|
+
await host.server.close();
|
|
1204
|
+
process.stdin.pause();
|
|
1205
|
+
process.stdin.destroy();
|
|
1206
|
+
}
|
|
1207
|
+
})();
|
|
1208
|
+
return shutdown;
|
|
1209
|
+
};
|
|
1210
|
+
const onClose = () => {
|
|
1211
|
+
void close().catch(() => {
|
|
1212
|
+
process.exitCode = 1;
|
|
1213
|
+
});
|
|
1214
|
+
};
|
|
1215
|
+
process.stdin.once("end", onClose);
|
|
1216
|
+
process.stdin.once("close", onClose);
|
|
1217
|
+
process.once("SIGINT", onClose);
|
|
1218
|
+
process.once("SIGTERM", onClose);
|
|
1219
|
+
host.server.onclose = onClose;
|
|
1220
|
+
await host.server.connect(new StdioServerTransport());
|
|
1221
|
+
return { ...host, close };
|
|
1222
|
+
}
|
|
1223
|
+
export {
|
|
1224
|
+
createDesktopBusinessServer,
|
|
1225
|
+
desktopBusinessTools,
|
|
1226
|
+
startDesktopBusinessStdio
|
|
1227
|
+
};
|