@muggleai/works 5.26.0-staging.218 → 5.26.0-staging.219

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.
@@ -1,6 +1,6 @@
1
1
  import * as fs4 from 'fs';
2
2
  import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'fs';
3
- import * as path15 from 'path';
3
+ import * as path16 from 'path';
4
4
  import { join, dirname } from 'path';
5
5
  import { fileURLToPath } from 'url';
6
6
  import * as crypto from 'crypto';
@@ -10,7 +10,7 @@ import { platform } from 'os';
10
10
  import winston from 'winston';
11
11
  import { execFile, exec, spawn } from 'child_process';
12
12
  import axios, { AxiosError } from 'axios';
13
- import * as fs13 from 'fs/promises';
13
+ import * as fs14 from 'fs/promises';
14
14
  import { z } from 'zod';
15
15
  import AppInsights from 'applicationinsights';
16
16
 
@@ -35,11 +35,22 @@ __export(src_exports, {
35
35
  BRANCH_CREATION_REFLOG_PREFIX: () => BRANCH_CREATION_REFLOG_PREFIX,
36
36
  BUSY_EXIT_CODE: () => BUSY_EXIT_CODE,
37
37
  CheckoutFreshnessVerdict: () => CheckoutFreshnessVerdict,
38
+ DEFAULT_LOCAL_LLM_BASE_URL: () => DEFAULT_LOCAL_LLM_BASE_URL,
38
39
  DEFAULT_PREFERENCES: () => DEFAULT_PREFERENCES,
39
40
  ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS: () => ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS,
40
41
  ElectronAppPlatform: () => ElectronAppPlatform,
41
42
  ElectronAppReleaseStream: () => ElectronAppReleaseStream,
42
43
  HTML_VIEW_OFFER_LINE: () => HTML_VIEW_OFFER_LINE,
44
+ LLM_CREDENTIALS_FILE_MODE: () => LLM_CREDENTIALS_FILE_MODE,
45
+ LLM_CREDENTIALS_FILE_NAME: () => LLM_CREDENTIALS_FILE_NAME,
46
+ LLM_SOURCE_HEADER: () => LLM_SOURCE_HEADER,
47
+ LLM_SOURCE_OPTIONS: () => LLM_SOURCE_OPTIONS,
48
+ LLM_SOURCE_OWNED_ENV_NAMES: () => LLM_SOURCE_OWNED_ENV_NAMES,
49
+ LLM_SOURCE_PROMPT: () => LLM_SOURCE_PROMPT,
50
+ LLM_SOURCE_SCOPE_NOTE: () => LLM_SOURCE_SCOPE_NOTE,
51
+ LlmSource: () => LlmSource,
52
+ MASKED_API_KEY_PREFIX: () => MASKED_API_KEY_PREFIX,
53
+ MASKED_API_KEY_VISIBLE_CHARS: () => MASKED_API_KEY_VISIBLE_CHARS,
43
54
  MAX_LISTED_INHERITED_COMMITS: () => MAX_LISTED_INHERITED_COMMITS,
44
55
  ONBOARDING_BLANKET_OPTIONS: () => ONBOARDING_BLANKET_OPTIONS,
45
56
  ONBOARDING_CHOICE_GROUPS: () => ONBOARDING_CHOICE_GROUPS,
@@ -70,12 +81,14 @@ __export(src_exports, {
70
81
  StackPortAction: () => StackPortAction,
71
82
  WATCHER_LIFETIME_SECONDS: () => WATCHER_LIFETIME_SECONDS,
72
83
  WATCHER_LIFETIME_UNBOUNDED_SECONDS: () => WATCHER_LIFETIME_UNBOUNDED_SECONDS,
84
+ applyLlmSourceSelection: () => applyLlmSourceSelection,
73
85
  applyOnboardingAnswers: () => applyOnboardingAnswers,
74
86
  assertDeviceCodeClientProvisioned: () => assertDeviceCodeClientProvisioned,
75
87
  buildElectronAppChecksumsUrl: () => buildElectronAppChecksumsUrl,
76
88
  buildElectronAppDirName: () => buildElectronAppDirName,
77
89
  buildElectronAppReleaseAssetUrl: () => buildElectronAppReleaseAssetUrl,
78
90
  buildElectronAppReleaseTag: () => buildElectronAppReleaseTag,
91
+ buildLlmSourcePlan: () => buildLlmSourcePlan,
79
92
  buildOnboardingPlan: () => buildOnboardingPlan,
80
93
  buildToolInputJsonSchema: () => buildToolInputJsonSchema,
81
94
  calculateFileChecksum: () => calculateFileChecksum,
@@ -89,6 +102,7 @@ __export(src_exports, {
89
102
  decideStackRenewal: () => decideStackRenewal,
90
103
  deleteApiKeyData: () => deleteApiKeyData,
91
104
  deleteCredentials: () => deleteCredentials,
105
+ describeLlmSourceStatus: () => describeLlmSourceStatus,
92
106
  e2e: () => e2e_exports2,
93
107
  evaluateCheckoutFreshness: () => evaluateCheckoutFreshness,
94
108
  formatPreferencesOneLiner: () => formatPreferencesOneLiner,
@@ -112,6 +126,7 @@ __export(src_exports, {
112
126
  getElectronAppSignedFromVersion: () => getElectronAppSignedFromVersion,
113
127
  getElectronAppVersion: () => getElectronAppVersion,
114
128
  getElectronAppVersionSource: () => getElectronAppVersionSource,
129
+ getLlmSourceOption: () => getLlmSourceOption,
115
130
  getLocalQaTools: () => getLocalQaTools,
116
131
  getLogger: () => getLogger,
117
132
  getOnboardingToggleKeys: () => getOnboardingToggleKeys,
@@ -125,10 +140,12 @@ __export(src_exports, {
125
140
  isElectronAppInstalled: () => isElectronAppInstalled,
126
141
  isElectronAppPlatform: () => isElectronAppPlatform,
127
142
  isFirstRun: () => isFirstRun,
143
+ isValidLocalBaseUrl: () => isValidLocalBaseUrl,
128
144
  loadApiKeyData: () => loadApiKeyData,
129
145
  loadCredentials: () => loadCredentials,
130
146
  localQa: () => local_exports2,
131
147
  markOnboardingCompleted: () => markOnboardingCompleted,
148
+ maskLlmApiKey: () => maskLlmApiKey,
132
149
  mcp: () => mcp_exports,
133
150
  needsConflict: () => needsConflict,
134
151
  needsOnboarding: () => needsOnboarding,
@@ -156,6 +173,7 @@ __export(src_exports, {
156
173
  resolveBlanketPreferences: () => resolveBlanketPreferences,
157
174
  resolveElectronAppExecutablePath: () => resolveElectronAppExecutablePath,
158
175
  resolveElectronAppPathOrNull: () => resolveElectronAppPathOrNull,
176
+ resolveLlmSourceStatus: () => resolveLlmSourceStatus,
159
177
  resolveOnboardingAnswers: () => resolveOnboardingAnswers,
160
178
  resolvePreferences: () => resolvePreferences,
161
179
  resolveRunSessionPath: () => resolveRunSessionPath,
@@ -170,7 +188,8 @@ __export(src_exports, {
170
188
  toolRequiresAuth: () => toolRequiresAuth,
171
189
  validatePreference: () => validatePreference,
172
190
  verifyFileChecksum: () => verifyFileChecksum,
173
- writePreferences: () => writePreferences2,
191
+ writeLlmEnvBlock: () => writeLlmEnvBlock,
192
+ writePreferences: () => writePreferences,
174
193
  writePreferencesWithMetadata: () => writePreferencesWithMetadata,
175
194
  writeRunViewHtml: () => writeRunViewHtml
176
195
  });
@@ -190,26 +209,26 @@ var ElectronAppReleaseStream = /* @__PURE__ */ ((ElectronAppReleaseStream4) => {
190
209
  var DEFAULT_AUTH0_SCOPE = "openid profile email offline_access";
191
210
  var DEFAULT_WEB_SERVICE_URL = "http://localhost:3001";
192
211
  var RUNTIME_TARGET_ENV_VAR = "MUGGLE_MCP_PROMPT_SERVICE_TARGET";
193
- var RUNTIME_TARGETS_FILE = path15.join("config", "runtime-targets.json");
212
+ var RUNTIME_TARGETS_FILE = path16.join("config", "runtime-targets.json");
194
213
  function getPackageRoot() {
195
- const currentDir = path15.dirname(fileURLToPath(import.meta.url));
196
- if (currentDir.includes(path15.join("dist", "shared"))) {
197
- return path15.resolve(currentDir, "..", "..");
214
+ const currentDir = path16.dirname(fileURLToPath(import.meta.url));
215
+ if (currentDir.includes(path16.join("dist", "shared"))) {
216
+ return path16.resolve(currentDir, "..", "..");
198
217
  }
199
218
  if (currentDir.endsWith("dist")) {
200
- return path15.resolve(currentDir, "..");
219
+ return path16.resolve(currentDir, "..");
201
220
  }
202
- if (currentDir.includes(path15.join("src", "shared"))) {
203
- return path15.resolve(currentDir, "..", "..", "..", "..");
221
+ if (currentDir.includes(path16.join("src", "shared"))) {
222
+ return path16.resolve(currentDir, "..", "..", "..", "..");
204
223
  }
205
- return path15.dirname(currentDir);
224
+ return path16.dirname(currentDir);
206
225
  }
207
226
  var runtimeTargetDataCache = null;
208
227
  function getRuntimeTargetData() {
209
228
  if (runtimeTargetDataCache) {
210
229
  return runtimeTargetDataCache;
211
230
  }
212
- const profilesPath = path15.join(getPackageRoot(), RUNTIME_TARGETS_FILE);
231
+ const profilesPath = path16.join(getPackageRoot(), RUNTIME_TARGETS_FILE);
213
232
  let parsedData;
214
233
  try {
215
234
  parsedData = JSON.parse(fs4.readFileSync(profilesPath, "utf-8"));
@@ -288,7 +307,7 @@ function assertDeviceCodeClientProvisioned(target) {
288
307
  }
289
308
  var DATA_DIR_NAME = ".muggle-ai";
290
309
  function getDataDir() {
291
- return path15.join(os4.homedir(), DATA_DIR_NAME);
310
+ return path16.join(os4.homedir(), DATA_DIR_NAME);
292
311
  }
293
312
 
294
313
  // packages/mcps/src/shared/electron-app-executable-types.ts
@@ -314,7 +333,7 @@ function resolveElectronAppExecutablePath(params) {
314
333
  if (!isElectronAppPlatform(params.platformName)) {
315
334
  throw new Error(`Unsupported platform: ${params.platformName}`);
316
335
  }
317
- return path15.join(params.installDir, ...ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS[params.platformName]);
336
+ return path16.join(params.installDir, ...ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS[params.platformName]);
318
337
  }
319
338
 
320
339
  // packages/mcps/src/shared/electron-app-install-dir-constants.ts
@@ -393,24 +412,24 @@ var configInstance = null;
393
412
  var muggleConfigCache = null;
394
413
  function getPackageRoot2() {
395
414
  const currentFilePath = fileURLToPath(import.meta.url);
396
- const currentDir = path15.dirname(currentFilePath);
397
- if (currentDir.includes(path15.join("dist", "shared"))) {
398
- return path15.resolve(currentDir, "..", "..");
415
+ const currentDir = path16.dirname(currentFilePath);
416
+ if (currentDir.includes(path16.join("dist", "shared"))) {
417
+ return path16.resolve(currentDir, "..", "..");
399
418
  }
400
419
  if (currentDir.endsWith("dist")) {
401
- return path15.resolve(currentDir, "..");
420
+ return path16.resolve(currentDir, "..");
402
421
  }
403
- if (currentDir.includes(path15.join("src", "shared"))) {
404
- return path15.resolve(currentDir, "..", "..", "..", "..");
422
+ if (currentDir.includes(path16.join("src", "shared"))) {
423
+ return path16.resolve(currentDir, "..", "..", "..", "..");
405
424
  }
406
- return path15.dirname(currentDir);
425
+ return path16.dirname(currentDir);
407
426
  }
408
427
  function getMuggleConfig() {
409
428
  if (muggleConfigCache) {
410
429
  return muggleConfigCache;
411
430
  }
412
431
  const packageRoot = getPackageRoot2();
413
- const packageJsonPath = path15.join(packageRoot, "package.json");
432
+ const packageJsonPath = path16.join(packageRoot, "package.json");
414
433
  let packageJson;
415
434
  try {
416
435
  const content = fs4.readFileSync(packageJsonPath, "utf-8");
@@ -482,7 +501,7 @@ function getDownloadedElectronAppPath() {
482
501
  if (!isElectronAppPlatform(platformName)) {
483
502
  return null;
484
503
  }
485
- const baseDir = path15.join(
504
+ const baseDir = path16.join(
486
505
  getDataDir2(),
487
506
  ELECTRON_APP_DIR,
488
507
  buildElectronAppDirName({
@@ -502,13 +521,13 @@ function getSystemElectronAppPath() {
502
521
  let installDir;
503
522
  switch (platformName) {
504
523
  case "darwin":
505
- installDir = path15.join(homeDir, "Applications");
524
+ installDir = path16.join(homeDir, "Applications");
506
525
  break;
507
526
  case "win32":
508
- installDir = path15.join(homeDir, "AppData", "Local", "Programs", "MuggleAI");
527
+ installDir = path16.join(homeDir, "AppData", "Local", "Programs", "MuggleAI");
509
528
  break;
510
529
  case "linux":
511
- installDir = path15.join(homeDir, ".local", "share", "muggle-ai");
530
+ installDir = path16.join(homeDir, ".local", "share", "muggle-ai");
512
531
  break;
513
532
  default:
514
533
  return null;
@@ -540,7 +559,7 @@ function resolveWebServicePath() {
540
559
  return customPath;
541
560
  }
542
561
  const packageRoot = getPackageRoot2();
543
- const siblingPath = path15.resolve(packageRoot, "..", "web-service", "dist", "src", "index.js");
562
+ const siblingPath = path16.resolve(packageRoot, "..", "web-service", "dist", "src", "index.js");
544
563
  if (fs4.existsSync(siblingPath)) {
545
564
  return siblingPath;
546
565
  }
@@ -586,16 +605,16 @@ function buildLocalQaConfig() {
586
605
  webServiceUrl: process.env.WEB_SERVICE_URL ?? DEFAULT_WEB_SERVICE_URL,
587
606
  promptServiceUrl: process.env.PROMPT_SERVICE_BASE_URL ?? activeProfile.promptServiceBaseUrl,
588
607
  dataDir,
589
- sessionsDir: path15.join(dataDir, "sessions"),
590
- projectsDir: path15.join(dataDir, "projects"),
591
- tempDir: path15.join(dataDir, "temp"),
592
- apiKeyFilePath: path15.join(dataDir, API_KEY_FILE),
593
- oauthSessionFilePath: path15.join(
608
+ sessionsDir: path16.join(dataDir, "sessions"),
609
+ projectsDir: path16.join(dataDir, "projects"),
610
+ tempDir: path16.join(dataDir, "temp"),
611
+ apiKeyFilePath: path16.join(dataDir, API_KEY_FILE),
612
+ oauthSessionFilePath: path16.join(
594
613
  dataDir,
595
614
  buildOAuthSessionFileName({ runtimeTarget: getActiveRuntimeTarget() })
596
615
  ),
597
616
  webServicePath: resolveWebServicePath(),
598
- webServicePidFile: path15.join(dataDir, "web-service.pid"),
617
+ webServicePidFile: path16.join(dataDir, "web-service.pid"),
599
618
  auth0: {
600
619
  domain: process.env.AUTH0_DOMAIN ?? activeProfile.auth0Domain,
601
620
  clientId: process.env.AUTH0_CLIENT_ID ?? activeProfile.auth0ClientId,
@@ -630,7 +649,7 @@ function getElectronAppVersion() {
630
649
  if (envVersion && /^\d+\.\d+\.\d+$/.test(envVersion)) {
631
650
  return envVersion;
632
651
  }
633
- const overridePath = path15.join(getDataDir2(), VERSION_OVERRIDE_FILE);
652
+ const overridePath = path16.join(getDataDir2(), VERSION_OVERRIDE_FILE);
634
653
  if (fs4.existsSync(overridePath)) {
635
654
  try {
636
655
  const content = JSON.parse(fs4.readFileSync(overridePath, "utf-8"));
@@ -647,7 +666,7 @@ function getElectronAppVersionSource() {
647
666
  if (envVersion && /^\d+\.\d+\.\d+$/.test(envVersion)) {
648
667
  return "env";
649
668
  }
650
- const overridePath = path15.join(getDataDir2(), VERSION_OVERRIDE_FILE);
669
+ const overridePath = path16.join(getDataDir2(), VERSION_OVERRIDE_FILE);
651
670
  if (fs4.existsSync(overridePath)) {
652
671
  try {
653
672
  const content = JSON.parse(fs4.readFileSync(overridePath, "utf-8"));
@@ -694,7 +713,7 @@ function isElectronAppInstalled() {
694
713
  }
695
714
  function getElectronAppDir(version) {
696
715
  const resolvedVersion = version ?? getElectronAppVersion();
697
- return path15.join(
716
+ return path16.join(
698
717
  getDataDir2(),
699
718
  ELECTRON_APP_DIR,
700
719
  buildElectronAppDirName({
@@ -775,7 +794,7 @@ async function calculateFileChecksum(filePath) {
775
794
  async function verifyFileChecksum(filePath, expectedChecksum) {
776
795
  if (!expectedChecksum || expectedChecksum.trim() === "") {
777
796
  logger.warn("Checksum verification skipped - no checksum provided", {
778
- file: path15.basename(filePath)
797
+ file: path16.basename(filePath)
779
798
  });
780
799
  return {
781
800
  valid: true,
@@ -791,13 +810,13 @@ async function verifyFileChecksum(filePath, expectedChecksum) {
791
810
  const valid = normalizedExpected === normalizedActual;
792
811
  if (!valid) {
793
812
  logger.error("Checksum verification failed", {
794
- file: path15.basename(filePath),
813
+ file: path16.basename(filePath),
795
814
  expected: normalizedExpected,
796
815
  actual: normalizedActual
797
816
  });
798
817
  } else {
799
818
  logger.info("Checksum verified successfully", {
800
- file: path15.basename(filePath),
819
+ file: path16.basename(filePath),
801
820
  checksum: normalizedActual
802
821
  });
803
822
  }
@@ -810,7 +829,7 @@ async function verifyFileChecksum(filePath, expectedChecksum) {
810
829
  } catch (error) {
811
830
  const errorMessage = error instanceof Error ? error.message : String(error);
812
831
  logger.error("Checksum calculation failed", {
813
- file: path15.basename(filePath),
832
+ file: path16.basename(filePath),
814
833
  error: errorMessage
815
834
  });
816
835
  return {
@@ -1004,11 +1023,11 @@ var StorageService = class {
1004
1023
  createSessionDirectory(sessionId) {
1005
1024
  const logger7 = getLogger();
1006
1025
  this.ensureDirectories();
1007
- const sessionDir = path15.join(this.sessionsDir, sessionId);
1026
+ const sessionDir = path16.join(this.sessionsDir, sessionId);
1008
1027
  if (!fs4.existsSync(sessionDir)) {
1009
1028
  fs4.mkdirSync(sessionDir, { recursive: true });
1010
- fs4.mkdirSync(path15.join(sessionDir, "screenshots"), { recursive: true });
1011
- fs4.mkdirSync(path15.join(sessionDir, "logs"), { recursive: true });
1029
+ fs4.mkdirSync(path16.join(sessionDir, "screenshots"), { recursive: true });
1030
+ fs4.mkdirSync(path16.join(sessionDir, "logs"), { recursive: true });
1012
1031
  logger7.info("Created session directory", { sessionId, path: sessionDir });
1013
1032
  }
1014
1033
  return sessionDir;
@@ -1020,7 +1039,7 @@ var StorageService = class {
1020
1039
  saveSessionMetadata(metadata) {
1021
1040
  const logger7 = getLogger();
1022
1041
  const sessionDir = this.createSessionDirectory(metadata.sessionId);
1023
- const metadataPath = path15.join(sessionDir, "metadata.json");
1042
+ const metadataPath = path16.join(sessionDir, "metadata.json");
1024
1043
  fs4.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), "utf-8");
1025
1044
  logger7.debug("Saved session metadata", { sessionId: metadata.sessionId });
1026
1045
  }
@@ -1031,7 +1050,7 @@ var StorageService = class {
1031
1050
  */
1032
1051
  loadSessionMetadata(sessionId) {
1033
1052
  const logger7 = getLogger();
1034
- const metadataPath = path15.join(this.sessionsDir, sessionId, "metadata.json");
1053
+ const metadataPath = path16.join(this.sessionsDir, sessionId, "metadata.json");
1035
1054
  if (!fs4.existsSync(metadataPath)) {
1036
1055
  return null;
1037
1056
  }
@@ -1055,7 +1074,7 @@ var StorageService = class {
1055
1074
  return [];
1056
1075
  }
1057
1076
  return fs4.readdirSync(this.sessionsDir).filter((entry) => {
1058
- const entryPath = path15.join(this.sessionsDir, entry);
1077
+ const entryPath = path16.join(this.sessionsDir, entry);
1059
1078
  return fs4.statSync(entryPath).isDirectory();
1060
1079
  });
1061
1080
  }
@@ -1064,13 +1083,13 @@ var StorageService = class {
1064
1083
  * @returns Current session ID, or null.
1065
1084
  */
1066
1085
  getCurrentSessionId() {
1067
- const currentPath = path15.join(this.sessionsDir, "current");
1086
+ const currentPath = path16.join(this.sessionsDir, "current");
1068
1087
  if (!fs4.existsSync(currentPath)) {
1069
1088
  return null;
1070
1089
  }
1071
1090
  try {
1072
1091
  const target = fs4.readlinkSync(currentPath);
1073
- return path15.basename(target);
1092
+ return path16.basename(target);
1074
1093
  } catch {
1075
1094
  return null;
1076
1095
  }
@@ -1081,8 +1100,8 @@ var StorageService = class {
1081
1100
  */
1082
1101
  setCurrentSession(sessionId) {
1083
1102
  const logger7 = getLogger();
1084
- const currentPath = path15.join(this.sessionsDir, "current");
1085
- const targetPath = path15.join(this.sessionsDir, sessionId);
1103
+ const currentPath = path16.join(this.sessionsDir, "current");
1104
+ const targetPath = path16.join(this.sessionsDir, sessionId);
1086
1105
  if (fs4.existsSync(currentPath)) {
1087
1106
  fs4.unlinkSync(currentPath);
1088
1107
  }
@@ -1097,7 +1116,7 @@ var StorageService = class {
1097
1116
  const { sessionId, filename, data } = params;
1098
1117
  const logger7 = getLogger();
1099
1118
  const sessionDir = this.createSessionDirectory(sessionId);
1100
- const screenshotPath = path15.join(sessionDir, "screenshots", filename);
1119
+ const screenshotPath = path16.join(sessionDir, "screenshots", filename);
1101
1120
  fs4.writeFileSync(screenshotPath, data);
1102
1121
  logger7.debug("Saved screenshot", { sessionId, filename });
1103
1122
  return screenshotPath;
@@ -1110,7 +1129,7 @@ var StorageService = class {
1110
1129
  const { sessionId, content } = params;
1111
1130
  const logger7 = getLogger();
1112
1131
  const sessionDir = this.createSessionDirectory(sessionId);
1113
- const resultsPath = path15.join(sessionDir, "results.md");
1132
+ const resultsPath = path16.join(sessionDir, "results.md");
1114
1133
  fs4.appendFileSync(resultsPath, content + "\n", "utf-8");
1115
1134
  logger7.debug("Appended to results", { sessionId });
1116
1135
  }
@@ -1120,7 +1139,7 @@ var StorageService = class {
1120
1139
  * @returns Results content, or null if not found.
1121
1140
  */
1122
1141
  getResults(sessionId) {
1123
- const resultsPath = path15.join(this.sessionsDir, sessionId, "results.md");
1142
+ const resultsPath = path16.join(this.sessionsDir, sessionId, "results.md");
1124
1143
  if (!fs4.existsSync(resultsPath)) {
1125
1144
  return null;
1126
1145
  }
@@ -1189,7 +1208,7 @@ var StorageService = class {
1189
1208
  const { sessionId, targetUrl, testInstructions } = params;
1190
1209
  const logger7 = getLogger();
1191
1210
  const sessionDir = this.createSessionDirectory(sessionId);
1192
- const resultsPath = path15.join(sessionDir, "results.md");
1211
+ const resultsPath = path16.join(sessionDir, "results.md");
1193
1212
  const header = [
1194
1213
  `# Test Results: ${sessionId}`,
1195
1214
  "",
@@ -1213,7 +1232,7 @@ var StorageService = class {
1213
1232
  const { sessionId, step } = params;
1214
1233
  const logger7 = getLogger();
1215
1234
  const sessionDir = this.createSessionDirectory(sessionId);
1216
- const resultsPath = path15.join(sessionDir, "results.md");
1235
+ const resultsPath = path16.join(sessionDir, "results.md");
1217
1236
  const statusIcon = step.success ? "\u2713" : "\u2717";
1218
1237
  const stepContent = [
1219
1238
  `### Step ${step.stepNumber}: ${step.action}`,
@@ -1238,8 +1257,8 @@ var StorageService = class {
1238
1257
  finalizeResults(params) {
1239
1258
  const { sessionId, status, summary } = params;
1240
1259
  const logger7 = getLogger();
1241
- const sessionDir = path15.join(this.sessionsDir, sessionId);
1242
- const resultsPath = path15.join(sessionDir, "results.md");
1260
+ const sessionDir = path16.join(this.sessionsDir, sessionId);
1261
+ const resultsPath = path16.join(sessionDir, "results.md");
1243
1262
  if (!fs4.existsSync(resultsPath)) {
1244
1263
  logger7.warn("Results file not found for finalization", { sessionId });
1245
1264
  return;
@@ -1321,7 +1340,7 @@ var StorageService = class {
1321
1340
  }
1322
1341
  const sessionDate = new Date(metadata.startTime);
1323
1342
  if (sessionDate < cutoffDate) {
1324
- const sessionDir = path15.join(this.sessionsDir, sessionId);
1343
+ const sessionDir = path16.join(this.sessionsDir, sessionId);
1325
1344
  try {
1326
1345
  fs4.rmSync(sessionDir, { recursive: true, force: true });
1327
1346
  deletedCount++;
@@ -1351,7 +1370,7 @@ var StorageService = class {
1351
1370
  * @returns Session directory path.
1352
1371
  */
1353
1372
  getSessionPath(sessionId) {
1354
- return path15.join(this.sessionsDir, sessionId);
1373
+ return path16.join(this.sessionsDir, sessionId);
1355
1374
  }
1356
1375
  /**
1357
1376
  * Delete a specific session.
@@ -1360,7 +1379,7 @@ var StorageService = class {
1360
1379
  */
1361
1380
  deleteSession(sessionId) {
1362
1381
  const logger7 = getLogger();
1363
- const sessionDir = path15.join(this.sessionsDir, sessionId);
1382
+ const sessionDir = path16.join(this.sessionsDir, sessionId);
1364
1383
  if (!fs4.existsSync(sessionDir)) {
1365
1384
  logger7.warn("Session not found for deletion", { sessionId });
1366
1385
  return false;
@@ -1368,7 +1387,7 @@ var StorageService = class {
1368
1387
  try {
1369
1388
  const currentId = this.getCurrentSessionId();
1370
1389
  if (currentId === sessionId) {
1371
- const currentPath = path15.join(this.sessionsDir, "current");
1390
+ const currentPath = path16.join(this.sessionsDir, "current");
1372
1391
  if (fs4.existsSync(currentPath)) {
1373
1392
  fs4.unlinkSync(currentPath);
1374
1393
  }
@@ -1404,8 +1423,8 @@ var RunResultStorageService = class {
1404
1423
  constructor() {
1405
1424
  const storageService = getStorageService();
1406
1425
  const dataDir = storageService.getDataDir();
1407
- this.runResultsDir = path15.join(dataDir, "run-results");
1408
- this.testScriptsDir = path15.join(dataDir, "test-scripts");
1426
+ this.runResultsDir = path16.join(dataDir, "run-results");
1427
+ this.testScriptsDir = path16.join(dataDir, "test-scripts");
1409
1428
  this.ensureDirectories();
1410
1429
  }
1411
1430
  /**
@@ -1431,7 +1450,7 @@ var RunResultStorageService = class {
1431
1450
  const results = [];
1432
1451
  for (const file of files) {
1433
1452
  try {
1434
- const content = fs4.readFileSync(path15.join(this.runResultsDir, file), "utf-8");
1453
+ const content = fs4.readFileSync(path16.join(this.runResultsDir, file), "utf-8");
1435
1454
  results.push(JSON.parse(content));
1436
1455
  } catch {
1437
1456
  logger3.warn("Failed to read run result file", { file });
@@ -1446,7 +1465,7 @@ var RunResultStorageService = class {
1446
1465
  * Get a run result by ID.
1447
1466
  */
1448
1467
  getRunResult(runId) {
1449
- const filePath = path15.join(this.runResultsDir, `${runId}.json`);
1468
+ const filePath = path16.join(this.runResultsDir, `${runId}.json`);
1450
1469
  if (!fs4.existsSync(filePath)) {
1451
1470
  return void 0;
1452
1471
  }
@@ -1461,7 +1480,7 @@ var RunResultStorageService = class {
1461
1480
  * Save a run result.
1462
1481
  */
1463
1482
  saveRunResult(result) {
1464
- const filePath = path15.join(this.runResultsDir, `${result.id}.json`);
1483
+ const filePath = path16.join(this.runResultsDir, `${result.id}.json`);
1465
1484
  fs4.writeFileSync(filePath, JSON.stringify(result, null, 2));
1466
1485
  }
1467
1486
  /**
@@ -1514,7 +1533,7 @@ var RunResultStorageService = class {
1514
1533
  const scripts = [];
1515
1534
  for (const file of files) {
1516
1535
  try {
1517
- const content = fs4.readFileSync(path15.join(this.testScriptsDir, file), "utf-8");
1536
+ const content = fs4.readFileSync(path16.join(this.testScriptsDir, file), "utf-8");
1518
1537
  scripts.push(JSON.parse(content));
1519
1538
  } catch {
1520
1539
  logger3.warn("Failed to read test script file", { file });
@@ -1529,7 +1548,7 @@ var RunResultStorageService = class {
1529
1548
  * Get a test script by ID.
1530
1549
  */
1531
1550
  getTestScript(testScriptId) {
1532
- const filePath = path15.join(this.testScriptsDir, `${testScriptId}.json`);
1551
+ const filePath = path16.join(this.testScriptsDir, `${testScriptId}.json`);
1533
1552
  if (!fs4.existsSync(filePath)) {
1534
1553
  return void 0;
1535
1554
  }
@@ -1544,7 +1563,7 @@ var RunResultStorageService = class {
1544
1563
  * Save a test script.
1545
1564
  */
1546
1565
  saveTestScript(script) {
1547
- const filePath = path15.join(this.testScriptsDir, `${script.id}.json`);
1566
+ const filePath = path16.join(this.testScriptsDir, `${script.id}.json`);
1548
1567
  fs4.writeFileSync(filePath, JSON.stringify(script, null, 2));
1549
1568
  }
1550
1569
  /**
@@ -1596,7 +1615,7 @@ function resetRunResultStorageService() {
1596
1615
 
1597
1616
  // packages/mcps/src/mcp/local/services/run-view/read-run-view.ts
1598
1617
  function getRunSessionsDir() {
1599
- return path15.join(getDataDir(), RUN_SESSIONS_DIR_NAME);
1618
+ return path16.join(getDataDir(), RUN_SESSIONS_DIR_NAME);
1600
1619
  }
1601
1620
  var RunViewError = class extends Error {
1602
1621
  };
@@ -1613,16 +1632,16 @@ function resolveRunSessionPath(runId) {
1613
1632
  throw new RunViewError(`No runs found under ${sessionsDir}`);
1614
1633
  }
1615
1634
  if (!runId) {
1616
- const newest = names.map((name) => ({ name, modifiedAtMs: fs4.statSync(path15.join(sessionsDir, name)).mtimeMs })).sort((left, right) => right.modifiedAtMs - left.modifiedAtMs)[0];
1617
- return path15.join(sessionsDir, newest.name);
1635
+ const newest = names.map((name) => ({ name, modifiedAtMs: fs4.statSync(path16.join(sessionsDir, name)).mtimeMs })).sort((left, right) => right.modifiedAtMs - left.modifiedAtMs)[0];
1636
+ return path16.join(sessionsDir, newest.name);
1618
1637
  }
1619
1638
  const exact = names.find((name) => name === runId);
1620
1639
  if (exact) {
1621
- return path15.join(sessionsDir, exact);
1640
+ return path16.join(sessionsDir, exact);
1622
1641
  }
1623
1642
  const prefixed = names.filter((name) => name.startsWith(runId));
1624
1643
  if (prefixed.length === 1) {
1625
- return path15.join(sessionsDir, prefixed[0]);
1644
+ return path16.join(sessionsDir, prefixed[0]);
1626
1645
  }
1627
1646
  if (prefixed.length > 1) {
1628
1647
  throw new RunViewError(
@@ -1632,7 +1651,7 @@ function resolveRunSessionPath(runId) {
1632
1651
  throw new RunViewError(`No run matching "${runId}" under ${sessionsDir}`);
1633
1652
  }
1634
1653
  var listScreenshotFileNames = (sessionPath) => {
1635
- const screenshotDir = path15.join(sessionPath, ...SCREENSHOT_DIR_RELATIVE_PATH.split("/"));
1654
+ const screenshotDir = path16.join(sessionPath, ...SCREENSHOT_DIR_RELATIVE_PATH.split("/"));
1636
1655
  if (!fs4.existsSync(screenshotDir)) {
1637
1656
  return [];
1638
1657
  }
@@ -1647,14 +1666,14 @@ var resolveScreenshotPath = (sessionPath, screenshotFileNames, recordedPath) =>
1647
1666
  return null;
1648
1667
  }
1649
1668
  const match = screenshotFileNames.find((name) => name === recordedName) ?? screenshotFileNames.find((name) => name.endsWith(recordedName));
1650
- return match ? path15.join(sessionPath, ...SCREENSHOT_DIR_RELATIVE_PATH.split("/"), match) : null;
1669
+ return match ? path16.join(sessionPath, ...SCREENSHOT_DIR_RELATIVE_PATH.split("/"), match) : null;
1651
1670
  };
1652
1671
  function readRunView(runId) {
1653
1672
  const sessionPath = resolveRunSessionPath(runId);
1654
- const actionScriptPath = path15.join(sessionPath, ACTION_SCRIPT_FILE_NAME);
1673
+ const actionScriptPath = path16.join(sessionPath, ACTION_SCRIPT_FILE_NAME);
1655
1674
  if (!fs4.existsSync(actionScriptPath)) {
1656
1675
  throw new RunViewError(
1657
- `Run ${path15.basename(sessionPath)} has no ${ACTION_SCRIPT_FILE_NAME} \u2014 it died before writing one. Looked in ${sessionPath}`
1676
+ `Run ${path16.basename(sessionPath)} has no ${ACTION_SCRIPT_FILE_NAME} \u2014 it died before writing one. Looked in ${sessionPath}`
1658
1677
  );
1659
1678
  }
1660
1679
  let actionScript;
@@ -1665,7 +1684,7 @@ function readRunView(runId) {
1665
1684
  `Could not read ${actionScriptPath}: ${parseError instanceof Error ? parseError.message : String(parseError)}`
1666
1685
  );
1667
1686
  }
1668
- const resolvedRunId = path15.basename(sessionPath);
1687
+ const resolvedRunId = path16.basename(sessionPath);
1669
1688
  const storedRunResult = getRunResultStorageService().getRunResult(resolvedRunId);
1670
1689
  const recordedOutcome = storedRunResult?.status ?? null;
1671
1690
  const screenshotFileNames = listScreenshotFileNames(sessionPath);
@@ -1787,13 +1806,13 @@ ${runView.steps.map(renderStep).join("\n")}
1787
1806
  function writeRunViewHtml(runView, outputDir) {
1788
1807
  const targetDir = outputDir ?? process.cwd();
1789
1808
  fs4.mkdirSync(targetDir, { recursive: true });
1790
- const targetPath = path15.join(targetDir, `run-${runView.runId}.html`);
1809
+ const targetPath = path16.join(targetDir, `run-${runView.runId}.html`);
1791
1810
  fs4.writeFileSync(targetPath, renderRunViewHtml(runView), "utf8");
1792
1811
  return targetPath;
1793
1812
  }
1794
1813
  var API_KEY_FILE2 = "api-key.json";
1795
1814
  function getApiKeyFilePath() {
1796
- return path15.join(getDataDir(), API_KEY_FILE2);
1815
+ return path16.join(getDataDir(), API_KEY_FILE2);
1797
1816
  }
1798
1817
  function ensureDataDir() {
1799
1818
  const dataDir = getDataDir();
@@ -1944,8 +1963,8 @@ var AuthService = class {
1944
1963
  constructor() {
1945
1964
  const config = getConfig();
1946
1965
  this.oauthSessionFilePath = config.localQa.oauthSessionFilePath;
1947
- this.pendingDeviceCodePath = path15.join(
1948
- path15.dirname(config.localQa.oauthSessionFilePath),
1966
+ this.pendingDeviceCodePath = path16.join(
1967
+ path16.dirname(config.localQa.oauthSessionFilePath),
1949
1968
  "pending-device-code.json"
1950
1969
  );
1951
1970
  }
@@ -2054,7 +2073,7 @@ var AuthService = class {
2054
2073
  */
2055
2074
  storePendingDeviceCode(params) {
2056
2075
  const logger7 = getLogger();
2057
- const dir = path15.dirname(this.pendingDeviceCodePath);
2076
+ const dir = path16.dirname(this.pendingDeviceCodePath);
2058
2077
  if (!fs4.existsSync(dir)) {
2059
2078
  fs4.mkdirSync(dir, { recursive: true });
2060
2079
  }
@@ -2268,7 +2287,7 @@ var AuthService = class {
2268
2287
  userId,
2269
2288
  runtimeTarget: getActiveRuntimeTarget()
2270
2289
  };
2271
- const dir = path15.dirname(this.oauthSessionFilePath);
2290
+ const dir = path16.dirname(this.oauthSessionFilePath);
2272
2291
  if (!fs4.existsSync(dir)) {
2273
2292
  fs4.mkdirSync(dir, { recursive: true });
2274
2293
  }
@@ -2392,7 +2411,7 @@ var AuthService = class {
2392
2411
  userId: storedAuth.userId,
2393
2412
  runtimeTarget: storedAuth.runtimeTarget ?? getActiveRuntimeTarget()
2394
2413
  };
2395
- const dir = path15.dirname(this.oauthSessionFilePath);
2414
+ const dir = path16.dirname(this.oauthSessionFilePath);
2396
2415
  if (!fs4.existsSync(dir)) {
2397
2416
  fs4.mkdirSync(dir, { recursive: true });
2398
2417
  }
@@ -2481,12 +2500,11 @@ function sleep(params) {
2481
2500
  }
2482
2501
 
2483
2502
  // packages/mcps/src/shared/llm-env-constants.ts
2484
- var LLM_ENV_PREFERENCE_KEY = "llmEnv";
2485
2503
  var FORWARDABLE_LLM_ENV_NAMES = [
2486
- "MUGGLE_LLM_PROVIDER",
2487
- "MUGGLE_LLM_BASE_URL",
2488
- "MUGGLE_LLM_API_KEY",
2489
- "MUGGLE_LLM_MODEL",
2504
+ "MUGGLE_LLM_PROVIDER" /* Provider */,
2505
+ "MUGGLE_LLM_BASE_URL" /* BaseUrl */,
2506
+ "MUGGLE_LLM_API_KEY" /* ApiKey */,
2507
+ "MUGGLE_LLM_MODEL" /* Model */,
2490
2508
  "MUGGLE_LLM_MODEL_PREDICTION",
2491
2509
  "MUGGLE_LLM_MODEL_SUMMARIZER",
2492
2510
  "MUGGLE_LLM_MODEL_EVAL",
@@ -2496,6 +2514,83 @@ var FORWARDABLE_LLM_ENV_NAMES = [
2496
2514
  "MUGGLE_LLM_TIMEOUT_MS"
2497
2515
  ];
2498
2516
 
2517
+ // packages/mcps/src/shared/llm-source/llm-source-types.ts
2518
+ var LlmSource = /* @__PURE__ */ ((LlmSource2) => {
2519
+ LlmSource2["MuggleCredit"] = "muggle-credit";
2520
+ LlmSource2["AnthropicApiKey"] = "anthropic-api-key";
2521
+ LlmSource2["LocalModel"] = "local-model";
2522
+ return LlmSource2;
2523
+ })(LlmSource || {});
2524
+
2525
+ // packages/mcps/src/shared/llm-source/llm-source-constants.ts
2526
+ var LLM_SOURCE_OWNED_ENV_NAMES = [
2527
+ "MUGGLE_LLM_PROVIDER" /* Provider */,
2528
+ "MUGGLE_LLM_BASE_URL" /* BaseUrl */,
2529
+ "MUGGLE_LLM_API_KEY" /* ApiKey */,
2530
+ "MUGGLE_LLM_MODEL" /* Model */
2531
+ ];
2532
+ var LLM_CREDENTIALS_FILE_NAME = "llm-credentials.json";
2533
+ var LLM_CREDENTIALS_FILE_MODE = 384;
2534
+ var LLM_SOURCE_HEADER = "LLM source";
2535
+ var LLM_SOURCE_PROMPT = "Who should supply the model for tests Studio runs on this computer?";
2536
+ var LLM_SOURCE_SCOPE_NOTE = "Applies to runs on this computer. Cloud runs always use Muggle AI credit.";
2537
+ var LLM_SOURCE_OPTIONS = [
2538
+ {
2539
+ source: "muggle-credit" /* MuggleCredit */,
2540
+ label: "Muggle AI credit",
2541
+ description: "Muggle's designated models, billed to your Muggle AI credit. No setup."
2542
+ },
2543
+ {
2544
+ source: "anthropic-api-key" /* AnthropicApiKey */,
2545
+ label: "My own Anthropic API key",
2546
+ description: "Muggle's designated models on your key. Anthropic bills you; no Muggle AI credit is used."
2547
+ },
2548
+ {
2549
+ source: "local-model" /* LocalModel */,
2550
+ label: "A local or self-hosted model",
2551
+ description: "Any OpenAI-compatible endpoint serving a vision model (Ollama, LM Studio, vLLM). No Muggle AI credit is used."
2552
+ }
2553
+ ];
2554
+ var DEFAULT_LOCAL_LLM_BASE_URL = "http://localhost:11434/v1";
2555
+ var MASKED_API_KEY_VISIBLE_CHARS = 4;
2556
+ var MASKED_API_KEY_PREFIX = "\u2026";
2557
+
2558
+ // packages/mcps/src/shared/llm-source/llm-credentials-store.ts
2559
+ function getLlmCredentialsFilePath(dataDirOverride2) {
2560
+ return path16.join(dataDirOverride2 ?? getDataDir(), LLM_CREDENTIALS_FILE_NAME);
2561
+ }
2562
+ function readStoredLlmApiKey(dataDirOverride2) {
2563
+ const filePath = getLlmCredentialsFilePath(dataDirOverride2);
2564
+ try {
2565
+ if (!fs4.existsSync(filePath)) {
2566
+ return void 0;
2567
+ }
2568
+ const stored = JSON.parse(fs4.readFileSync(filePath, "utf-8"));
2569
+ return typeof stored.apiKey === "string" && stored.apiKey.length > 0 ? stored.apiKey : void 0;
2570
+ } catch (error) {
2571
+ getLogger().warn("Failed to read LLM credentials file", {
2572
+ path: filePath,
2573
+ error: error instanceof Error ? error.message : String(error)
2574
+ });
2575
+ return void 0;
2576
+ }
2577
+ }
2578
+ function writeStoredLlmApiKey(apiKey, dataDirOverride2) {
2579
+ const dir = dataDirOverride2 ?? getDataDir();
2580
+ fs4.mkdirSync(dir, { recursive: true });
2581
+ const credentials = { apiKey };
2582
+ const filePath = getLlmCredentialsFilePath(dataDirOverride2);
2583
+ fs4.writeFileSync(filePath, `${JSON.stringify(credentials, null, 2)}
2584
+ `, {
2585
+ encoding: "utf-8",
2586
+ mode: LLM_CREDENTIALS_FILE_MODE
2587
+ });
2588
+ fs4.chmodSync(filePath, LLM_CREDENTIALS_FILE_MODE);
2589
+ }
2590
+ function deleteStoredLlmApiKey(dataDirOverride2) {
2591
+ fs4.rmSync(getLlmCredentialsFilePath(dataDirOverride2), { force: true });
2592
+ }
2593
+
2499
2594
  // packages/mcps/src/shared/preferences-types.ts
2500
2595
  var PreferenceKey = /* @__PURE__ */ ((PreferenceKey2) => {
2501
2596
  PreferenceKey2["AutoLogin"] = "autoLogin";
@@ -2540,6 +2635,14 @@ var PreferenceValue = /* @__PURE__ */ ((PreferenceValue2) => {
2540
2635
  return PreferenceValue2;
2541
2636
  })(PreferenceValue || {});
2542
2637
 
2638
+ // packages/mcps/src/shared/project-preferences-reconcile-types.ts
2639
+ var ProjectPreferencesReconcileOutcome = /* @__PURE__ */ ((ProjectPreferencesReconcileOutcome2) => {
2640
+ ProjectPreferencesReconcileOutcome2["NoAction"] = "noAction";
2641
+ ProjectPreferencesReconcileOutcome2["CopiedToGlobal"] = "copiedToGlobal";
2642
+ ProjectPreferencesReconcileOutcome2["KeysShadowed"] = "keysShadowed";
2643
+ return ProjectPreferencesReconcileOutcome2;
2644
+ })(ProjectPreferencesReconcileOutcome || {});
2645
+
2543
2646
  // packages/mcps/src/shared/preferences-constants.ts
2544
2647
  var PREFERENCES_FILE_NAME = "preferences.json";
2545
2648
  var PREFERENCES_PROJECT_DIR_NAME = ".muggle-ai";
@@ -2706,19 +2809,151 @@ var PREFERENCES_SCHEMA = {
2706
2809
  }
2707
2810
  };
2708
2811
 
2709
- // packages/mcps/src/shared/llm-env-service.ts
2710
- function resolveLlmEnvOverrides(dataDirOverride2) {
2711
- const filePath = path15.join(getDataDir(), PREFERENCES_FILE_NAME);
2712
- let block;
2812
+ // packages/mcps/src/shared/preferences-service.ts
2813
+ function getGlobalPreferencesFilePath(dataDirOverride2) {
2814
+ return path16.join(dataDirOverride2 ?? getDataDir(), PREFERENCES_FILE_NAME);
2815
+ }
2816
+ function isFirstRun(dataDirOverride2) {
2817
+ return !fs4.existsSync(getGlobalPreferencesFilePath(dataDirOverride2));
2818
+ }
2819
+ function readPreferencesFile(filePath) {
2713
2820
  try {
2714
2821
  if (!fs4.existsSync(filePath)) {
2715
2822
  return {};
2716
2823
  }
2717
2824
  const raw = JSON.parse(fs4.readFileSync(filePath, "utf-8"));
2718
- block = raw[LLM_ENV_PREFERENCE_KEY];
2825
+ return raw.preferences ?? {};
2826
+ } catch (error) {
2827
+ getLogger().warn("Failed to read preferences file", {
2828
+ path: filePath,
2829
+ error: error instanceof Error ? error.message : String(error)
2830
+ });
2831
+ return {};
2832
+ }
2833
+ }
2834
+ function writePreferencesFile(filePath, prefs) {
2835
+ const file = {
2836
+ ...readRawPreferencesFile(filePath),
2837
+ version: PREFERENCES_VERSION,
2838
+ preferences: prefs
2839
+ };
2840
+ fs4.writeFileSync(filePath, `${JSON.stringify(file, null, 2)}
2841
+ `, "utf-8");
2842
+ }
2843
+ function readRawPreferencesFile(filePath) {
2844
+ try {
2845
+ if (!fs4.existsSync(filePath)) {
2846
+ return {};
2847
+ }
2848
+ return JSON.parse(fs4.readFileSync(filePath, "utf-8"));
2719
2849
  } catch {
2720
2850
  return {};
2721
2851
  }
2852
+ }
2853
+ function resolvePreferences(dataDirOverride2) {
2854
+ const saved = readPreferencesFile(getGlobalPreferencesFilePath(dataDirOverride2));
2855
+ return { ...DEFAULT_PREFERENCES, ...saved };
2856
+ }
2857
+ function writePreferences(prefs, dataDirOverride2) {
2858
+ const dir = dataDirOverride2 ?? getDataDir();
2859
+ fs4.mkdirSync(dir, { recursive: true });
2860
+ const filePath = path16.join(dir, PREFERENCES_FILE_NAME);
2861
+ const existing = readPreferencesFile(filePath);
2862
+ writePreferencesFile(filePath, { ...existing, ...prefs });
2863
+ }
2864
+ function readPreferencesMetadata(dataDirOverride2) {
2865
+ const metadata = {
2866
+ ...readRawPreferencesFile(getGlobalPreferencesFilePath(dataDirOverride2))
2867
+ };
2868
+ delete metadata.preferences;
2869
+ return metadata;
2870
+ }
2871
+ function writePreferencesWithMetadata(prefs, metadata, dataDirOverride2) {
2872
+ const dir = dataDirOverride2 ?? getDataDir();
2873
+ fs4.mkdirSync(dir, { recursive: true });
2874
+ const filePath = path16.join(dir, PREFERENCES_FILE_NAME);
2875
+ const existing = readRawPreferencesFile(filePath);
2876
+ const file = {
2877
+ ...existing,
2878
+ ...metadata,
2879
+ version: PREFERENCES_VERSION,
2880
+ preferences: { ...existing.preferences ?? {}, ...prefs }
2881
+ };
2882
+ fs4.writeFileSync(filePath, `${JSON.stringify(file, null, 2)}
2883
+ `, "utf-8");
2884
+ }
2885
+ function writeLlmEnvBlock(llmEnv, dataDirOverride2) {
2886
+ const dir = dataDirOverride2 ?? getDataDir();
2887
+ fs4.mkdirSync(dir, { recursive: true });
2888
+ const filePath = path16.join(dir, PREFERENCES_FILE_NAME);
2889
+ const existing = readRawPreferencesFile(filePath);
2890
+ const file = {
2891
+ ...existing,
2892
+ version: PREFERENCES_VERSION,
2893
+ preferences: existing.preferences ?? {},
2894
+ llmEnv
2895
+ };
2896
+ if (llmEnv === void 0) {
2897
+ delete file.llmEnv;
2898
+ }
2899
+ fs4.writeFileSync(filePath, `${JSON.stringify(file, null, 2)}
2900
+ `, "utf-8");
2901
+ }
2902
+ function resetPreference(key, dataDirOverride2) {
2903
+ const filePath = getGlobalPreferencesFilePath(dataDirOverride2);
2904
+ if (!fs4.existsSync(filePath)) {
2905
+ return;
2906
+ }
2907
+ if (!key) {
2908
+ writePreferencesFile(filePath, {});
2909
+ return;
2910
+ }
2911
+ const existing = readPreferencesFile(filePath);
2912
+ delete existing[key];
2913
+ writePreferencesFile(filePath, existing);
2914
+ }
2915
+ function reconcileProjectPreferences(cwd, dataDirOverride2) {
2916
+ const projectFilePath = path16.join(cwd, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_FILE_NAME);
2917
+ const projectPreferences = readPreferencesFile(projectFilePath);
2918
+ const projectKeys = Object.keys(projectPreferences);
2919
+ if (projectKeys.length === 0) {
2920
+ return {
2921
+ outcome: "noAction" /* NoAction */,
2922
+ projectFilePath,
2923
+ shadowedKeys: []
2924
+ };
2925
+ }
2926
+ if (isFirstRun(dataDirOverride2)) {
2927
+ writePreferences(projectPreferences, dataDirOverride2);
2928
+ return {
2929
+ outcome: "copiedToGlobal" /* CopiedToGlobal */,
2930
+ projectFilePath,
2931
+ shadowedKeys: []
2932
+ };
2933
+ }
2934
+ const resolved = resolvePreferences(dataDirOverride2);
2935
+ const shadowedKeys = projectKeys.filter((key) => projectPreferences[key] !== resolved[key]);
2936
+ return {
2937
+ outcome: shadowedKeys.length > 0 ? "keysShadowed" /* KeysShadowed */ : "noAction" /* NoAction */,
2938
+ projectFilePath,
2939
+ shadowedKeys
2940
+ };
2941
+ }
2942
+ function validatePreference(key, value) {
2943
+ const validKeys = Object.values(PreferenceKey);
2944
+ if (!validKeys.includes(key)) {
2945
+ return false;
2946
+ }
2947
+ const allowed = PREFERENCE_ALLOWED_VALUES[key];
2948
+ return allowed.includes(value);
2949
+ }
2950
+ function formatPreferencesOneLiner(prefs) {
2951
+ return Object.entries(prefs).map(([key, value]) => `${key}=${value}`).join(" ");
2952
+ }
2953
+
2954
+ // packages/mcps/src/shared/llm-env-service.ts
2955
+ function resolveLlmEnvOverrides(dataDirOverride2) {
2956
+ const block = readPreferencesMetadata(dataDirOverride2).llmEnv;
2722
2957
  if (!block || typeof block !== "object" || Array.isArray(block)) {
2723
2958
  return {};
2724
2959
  }
@@ -2732,10 +2967,16 @@ function resolveLlmEnvOverrides(dataDirOverride2) {
2732
2967
  }
2733
2968
  overrides[name] = String(value);
2734
2969
  }
2970
+ if (overrides["MUGGLE_LLM_PROVIDER" /* Provider */] && !overrides["MUGGLE_LLM_API_KEY" /* ApiKey */]) {
2971
+ const storedApiKey = readStoredLlmApiKey(dataDirOverride2);
2972
+ if (storedApiKey) {
2973
+ overrides["MUGGLE_LLM_API_KEY" /* ApiKey */] = storedApiKey;
2974
+ }
2975
+ }
2735
2976
  return overrides;
2736
2977
  }
2737
2978
  function applyLlmEnvOverrides(baseEnv, dataDirOverride2) {
2738
- const overrides = resolveLlmEnvOverrides();
2979
+ const overrides = resolveLlmEnvOverrides(dataDirOverride2);
2739
2980
  const appliedNames = [];
2740
2981
  for (const [name, value] of Object.entries(overrides)) {
2741
2982
  if (baseEnv[name] !== void 0 && baseEnv[name] !== "") {
@@ -2981,11 +3222,11 @@ var STOP_REQUEST_FILE_SUFFIX = "_stop_requested";
2981
3222
  // packages/mcps/src/mcp/local/services/execution-stop.ts
2982
3223
  var logger4 = getLogger();
2983
3224
  function buildStopRequestFilePath(params) {
2984
- return path15.join(params.tempDir, `${params.runId}${STOP_REQUEST_FILE_SUFFIX}`);
3225
+ return path16.join(params.tempDir, `${params.runId}${STOP_REQUEST_FILE_SUFFIX}`);
2985
3226
  }
2986
3227
  async function requestGracefulStopAsync(params) {
2987
3228
  try {
2988
- await fs13.writeFile(buildStopRequestFilePath(params), params.reason, "utf-8");
3229
+ await fs14.writeFile(buildStopRequestFilePath(params), params.reason, "utf-8");
2989
3230
  } catch (writeError) {
2990
3231
  logger4.warn("Could not write the stop request; the run will be hard-killed after the grace period", {
2991
3232
  runId: params.runId,
@@ -3003,7 +3244,7 @@ async function requestGracefulStopAsync(params) {
3003
3244
  }, STOP_REQUEST_GRACE_MS);
3004
3245
  }
3005
3246
  async function removeStopRequestFileAsync(params) {
3006
- await fs13.unlink(buildStopRequestFilePath(params)).catch(() => void 0);
3247
+ await fs14.unlink(buildStopRequestFilePath(params)).catch(() => void 0);
3007
3248
  }
3008
3249
  function resolveStoppedRunStatus(reason) {
3009
3250
  return reason === "cancelled" /* Cancelled */ ? "cancelled" : "failed";
@@ -3025,13 +3266,13 @@ var MODIFY_LOCK_STALE_MS = 5e3;
3025
3266
 
3026
3267
  // packages/mcps/src/mcp/local/services/local-execution-lock.ts
3027
3268
  function lockFilePath() {
3028
- return path15.join(getDataDir(), LOCK_FILE_NAME);
3269
+ return path16.join(getDataDir(), LOCK_FILE_NAME);
3029
3270
  }
3030
3271
  function modifyLockPath() {
3031
3272
  return lockFilePath() + MODIFY_LOCK_SUFFIX;
3032
3273
  }
3033
3274
  function normalizeCwd(cwd) {
3034
- const resolved = path15.resolve(cwd);
3275
+ const resolved = path16.resolve(cwd);
3035
3276
  return os4.platform() === "win32" ? resolved.toLowerCase() : resolved;
3036
3277
  }
3037
3278
  function pidIsAlive(pid) {
@@ -3047,7 +3288,7 @@ function pidIsAlive(pid) {
3047
3288
  }
3048
3289
  async function readState() {
3049
3290
  try {
3050
- const raw = await fs13.readFile(lockFilePath(), "utf-8");
3291
+ const raw = await fs14.readFile(lockFilePath(), "utf-8");
3051
3292
  return JSON.parse(raw);
3052
3293
  } catch (error) {
3053
3294
  if (error.code === "ENOENT") return null;
@@ -3055,28 +3296,28 @@ async function readState() {
3055
3296
  }
3056
3297
  }
3057
3298
  async function writeState(state2) {
3058
- await fs13.writeFile(lockFilePath(), JSON.stringify(state2, null, 2), "utf-8");
3299
+ await fs14.writeFile(lockFilePath(), JSON.stringify(state2, null, 2), "utf-8");
3059
3300
  }
3060
3301
  async function deleteStateFile() {
3061
3302
  try {
3062
- await fs13.unlink(lockFilePath());
3303
+ await fs14.unlink(lockFilePath());
3063
3304
  } catch (error) {
3064
3305
  if (error.code !== "ENOENT") throw error;
3065
3306
  }
3066
3307
  }
3067
3308
  async function withModifyLock(fn) {
3068
- await fs13.mkdir(path15.dirname(modifyLockPath()), { recursive: true });
3309
+ await fs14.mkdir(path16.dirname(modifyLockPath()), { recursive: true });
3069
3310
  const modifyPath = modifyLockPath();
3070
3311
  let fileHandle = null;
3071
3312
  while (fileHandle === null) {
3072
3313
  try {
3073
- fileHandle = await fs13.open(modifyPath, "wx");
3314
+ fileHandle = await fs14.open(modifyPath, "wx");
3074
3315
  } catch (error) {
3075
3316
  if (error.code !== "EEXIST") throw error;
3076
3317
  try {
3077
- const stat3 = await fs13.stat(modifyPath);
3318
+ const stat3 = await fs14.stat(modifyPath);
3078
3319
  if (Date.now() - stat3.mtimeMs > MODIFY_LOCK_STALE_MS) {
3079
- await fs13.unlink(modifyPath).catch(() => void 0);
3320
+ await fs14.unlink(modifyPath).catch(() => void 0);
3080
3321
  continue;
3081
3322
  }
3082
3323
  } catch {
@@ -3089,7 +3330,7 @@ async function withModifyLock(fn) {
3089
3330
  return await fn();
3090
3331
  } finally {
3091
3332
  await fileHandle.close().catch(() => void 0);
3092
- await fs13.unlink(modifyPath).catch(() => void 0);
3333
+ await fs14.unlink(modifyPath).catch(() => void 0);
3093
3334
  }
3094
3335
  }
3095
3336
  async function tryAcquireOnce(params) {
@@ -3235,12 +3476,12 @@ function extractStudioCloudRefs(studioReturnedResult) {
3235
3476
  return refs;
3236
3477
  }
3237
3478
  async function readCloudRefsFile(inputFilePath) {
3238
- const cloudRefsPath = path15.join(
3239
- path15.dirname(inputFilePath),
3240
- `cloudrefs_${path15.basename(inputFilePath)}`
3479
+ const cloudRefsPath = path16.join(
3480
+ path16.dirname(inputFilePath),
3481
+ `cloudrefs_${path16.basename(inputFilePath)}`
3241
3482
  );
3242
3483
  try {
3243
- return JSON.parse(await fs13.readFile(cloudRefsPath, "utf-8"));
3484
+ return JSON.parse(await fs14.readFile(cloudRefsPath, "utf-8"));
3244
3485
  } catch {
3245
3486
  return void 0;
3246
3487
  }
@@ -3259,15 +3500,15 @@ function getAuthenticatedUserId() {
3259
3500
  }
3260
3501
  async function findPackageJsonAsync() {
3261
3502
  const currentFileUrl = import.meta.url;
3262
- const currentDir = path15.dirname(fileURLToPath(currentFileUrl));
3503
+ const currentDir = path16.dirname(fileURLToPath(currentFileUrl));
3263
3504
  const candidatePaths = [
3264
- path15.resolve(currentDir, "../../../package.json"),
3265
- path15.resolve(currentDir, "../package.json"),
3266
- path15.resolve(currentDir, "../../package.json")
3505
+ path16.resolve(currentDir, "../../../package.json"),
3506
+ path16.resolve(currentDir, "../package.json"),
3507
+ path16.resolve(currentDir, "../../package.json")
3267
3508
  ];
3268
3509
  for (const candidatePath of candidatePaths) {
3269
3510
  try {
3270
- const packageJsonRaw = await fs13.readFile(candidatePath, "utf-8");
3511
+ const packageJsonRaw = await fs14.readFile(candidatePath, "utf-8");
3271
3512
  const packageJson = JSON.parse(packageJsonRaw);
3272
3513
  if (packageJson.name === "@muggleai/works" && packageJson.version && packageJson.muggleConfig?.electronAppVersion) {
3273
3514
  return {
@@ -3313,20 +3554,20 @@ function buildStudioAuthContent() {
3313
3554
  }
3314
3555
  async function ensureTempDir() {
3315
3556
  const config = getConfig();
3316
- const tempDir = path15.join(config.localQa.dataDir, "temp");
3317
- await fs13.mkdir(tempDir, { recursive: true });
3557
+ const tempDir = path16.join(config.localQa.dataDir, "temp");
3558
+ await fs14.mkdir(tempDir, { recursive: true });
3318
3559
  return tempDir;
3319
3560
  }
3320
3561
  async function writeTempFile(params) {
3321
3562
  const tempDir = await ensureTempDir();
3322
- const filePath = path15.join(tempDir, params.filename);
3323
- await fs13.writeFile(filePath, JSON.stringify(params.data, null, 2));
3563
+ const filePath = path16.join(tempDir, params.filename);
3564
+ await fs14.writeFile(filePath, JSON.stringify(params.data, null, 2));
3324
3565
  return filePath;
3325
3566
  }
3326
3567
  async function cleanupTempFiles(params) {
3327
3568
  for (const filePath of params.filePaths) {
3328
3569
  try {
3329
- await fs13.unlink(filePath);
3570
+ await fs14.unlink(filePath);
3330
3571
  } catch {
3331
3572
  }
3332
3573
  }
@@ -3334,12 +3575,12 @@ async function cleanupTempFiles(params) {
3334
3575
  async function moveResultsToArtifacts(params) {
3335
3576
  const storageService = getStorageService();
3336
3577
  const sessionsDir = storageService.getSessionsDir();
3337
- const artifactsDir = path15.join(sessionsDir, params.runId);
3338
- const actionScriptPath = path15.join(artifactsDir, "action-script.json");
3339
- await fs13.mkdir(artifactsDir, { recursive: true });
3340
- await fs13.copyFile(params.generatedScriptPath, actionScriptPath);
3578
+ const artifactsDir = path16.join(sessionsDir, params.runId);
3579
+ const actionScriptPath = path16.join(artifactsDir, "action-script.json");
3580
+ await fs14.mkdir(artifactsDir, { recursive: true });
3581
+ await fs14.copyFile(params.generatedScriptPath, actionScriptPath);
3341
3582
  try {
3342
- await fs13.unlink(params.generatedScriptPath);
3583
+ await fs14.unlink(params.generatedScriptPath);
3343
3584
  } catch {
3344
3585
  }
3345
3586
  return artifactsDir;
@@ -3347,13 +3588,13 @@ async function moveResultsToArtifacts(params) {
3347
3588
  async function writeExecutionLogs(params) {
3348
3589
  const storageService = getStorageService();
3349
3590
  const sessionsDir = storageService.getSessionsDir();
3350
- const artifactsDir = path15.join(sessionsDir, params.runId);
3351
- await fs13.mkdir(artifactsDir, { recursive: true });
3352
- const stdoutPath = path15.join(artifactsDir, "stdout.log");
3353
- const stderrPath = path15.join(artifactsDir, "stderr.log");
3591
+ const artifactsDir = path16.join(sessionsDir, params.runId);
3592
+ await fs14.mkdir(artifactsDir, { recursive: true });
3593
+ const stdoutPath = path16.join(artifactsDir, "stdout.log");
3594
+ const stderrPath = path16.join(artifactsDir, "stderr.log");
3354
3595
  await Promise.all([
3355
- fs13.writeFile(stdoutPath, params.stdout, "utf-8"),
3356
- fs13.writeFile(stderrPath, params.stderr, "utf-8")
3596
+ fs14.writeFile(stdoutPath, params.stdout, "utf-8"),
3597
+ fs14.writeFile(stderrPath, params.stderr, "utf-8")
3357
3598
  ]);
3358
3599
  logger5.info("Wrote execution logs to artifacts directory", {
3359
3600
  runId: params.runId,
@@ -3363,10 +3604,10 @@ async function writeExecutionLogs(params) {
3363
3604
  async function preserveElectronRuntimeArtifacts(params) {
3364
3605
  try {
3365
3606
  const tempDir = await ensureTempDir();
3366
- const markerPath = path15.join(tempDir, `${params.runId}_runtime_dir.txt`);
3607
+ const markerPath = path16.join(tempDir, `${params.runId}_runtime_dir.txt`);
3367
3608
  let runtimeDir = null;
3368
3609
  try {
3369
- const marker = await fs13.readFile(markerPath, "utf-8");
3610
+ const marker = await fs14.readFile(markerPath, "utf-8");
3370
3611
  const trimmed = marker.trim();
3371
3612
  if (trimmed.length > 0) runtimeDir = trimmed;
3372
3613
  } catch (markerReadError) {
@@ -3388,25 +3629,25 @@ async function preserveElectronRuntimeArtifacts(params) {
3388
3629
  return;
3389
3630
  }
3390
3631
  try {
3391
- await fs13.access(runtimeDir);
3632
+ await fs14.access(runtimeDir);
3392
3633
  } catch {
3393
3634
  logger5.warn("Electron runtime dir referenced but missing on disk", {
3394
3635
  runId: params.runId,
3395
3636
  runtimeDir
3396
3637
  });
3397
- await fs13.unlink(markerPath).catch(() => void 0);
3638
+ await fs14.unlink(markerPath).catch(() => void 0);
3398
3639
  return;
3399
3640
  }
3400
3641
  const storage = getStorageService();
3401
- const destDir = path15.join(storage.getSessionsDir(), params.runId, "electron-runtime");
3402
- await fs13.mkdir(destDir, { recursive: true });
3403
- await fs13.cp(runtimeDir, destDir, { recursive: true });
3642
+ const destDir = path16.join(storage.getSessionsDir(), params.runId, "electron-runtime");
3643
+ await fs14.mkdir(destDir, { recursive: true });
3644
+ await fs14.cp(runtimeDir, destDir, { recursive: true });
3404
3645
  logger5.info("Preserved Electron runtime artifacts", {
3405
3646
  runId: params.runId,
3406
3647
  sourceDir: runtimeDir,
3407
3648
  destDir
3408
3649
  });
3409
- await fs13.unlink(markerPath).catch(() => void 0);
3650
+ await fs14.unlink(markerPath).catch(() => void 0);
3410
3651
  } catch (preserveError) {
3411
3652
  logger5.warn("Failed to preserve Electron runtime artifacts", {
3412
3653
  runId: params.runId,
@@ -3415,14 +3656,14 @@ async function preserveElectronRuntimeArtifacts(params) {
3415
3656
  }
3416
3657
  }
3417
3658
  async function scanForRuntimeDirByMtime(params) {
3418
- const runtimeRoot = path15.join(params.electronCwd, "user_data", "runtime");
3659
+ const runtimeRoot = path16.join(params.electronCwd, "user_data", "runtime");
3419
3660
  try {
3420
- const entries = await fs13.readdir(runtimeRoot, { withFileTypes: true });
3661
+ const entries = await fs14.readdir(runtimeRoot, { withFileTypes: true });
3421
3662
  let bestCandidate = null;
3422
3663
  for (const entry of entries) {
3423
3664
  if (!entry.isDirectory()) continue;
3424
- const fullPath = path15.join(runtimeRoot, entry.name);
3425
- const stat3 = await fs13.stat(fullPath);
3665
+ const fullPath = path16.join(runtimeRoot, entry.name);
3666
+ const stat3 = await fs14.stat(fullPath);
3426
3667
  if (stat3.mtimeMs < params.spawnAtMs) continue;
3427
3668
  if (bestCandidate === null || stat3.mtimeMs > bestCandidate.mtimeMs) {
3428
3669
  bestCandidate = { path: fullPath, mtimeMs: stat3.mtimeMs };
@@ -3509,7 +3750,7 @@ async function executeElectronAppAsync(params) {
3509
3750
  spawnArgs,
3510
3751
  llmEnvOverrideNames
3511
3752
  });
3512
- const electronCwd = path15.dirname(electronAppPath);
3753
+ const electronCwd = path16.dirname(electronAppPath);
3513
3754
  const child = spawn(electronAppPath, spawnArgs, {
3514
3755
  stdio: ["ignore", "pipe", "pipe"],
3515
3756
  env: electronEnv,
@@ -3703,17 +3944,17 @@ async function runTestGenerationLocked(params) {
3703
3944
  if (executionResult.exitCode !== 0 || executionResult.stopReason !== void 0) {
3704
3945
  const failureMessage = describeElectronFailure({ executionResult, timeoutMs });
3705
3946
  const sessionsDir = getStorageService().getSessionsDir();
3706
- const artifactsDir2 = path15.join(sessionsDir, runId);
3707
- const generatedScriptPath2 = path15.join(
3708
- path15.dirname(inputFilePath),
3709
- `gen_${path15.basename(inputFilePath)}`
3947
+ const artifactsDir2 = path16.join(sessionsDir, runId);
3948
+ const generatedScriptPath2 = path16.join(
3949
+ path16.dirname(inputFilePath),
3950
+ `gen_${path16.basename(inputFilePath)}`
3710
3951
  );
3711
3952
  let failedStudioResult;
3712
3953
  try {
3713
- const failedScriptRaw = await fs13.readFile(generatedScriptPath2, "utf-8");
3954
+ const failedScriptRaw = await fs14.readFile(generatedScriptPath2, "utf-8");
3714
3955
  failedStudioResult = JSON.parse(failedScriptRaw);
3715
- await fs13.copyFile(generatedScriptPath2, path15.join(artifactsDir2, "action-script.json"));
3716
- await fs13.unlink(generatedScriptPath2).catch(() => {
3956
+ await fs14.copyFile(generatedScriptPath2, path16.join(artifactsDir2, "action-script.json"));
3957
+ await fs14.unlink(generatedScriptPath2).catch(() => {
3717
3958
  });
3718
3959
  } catch {
3719
3960
  }
@@ -3742,11 +3983,11 @@ async function runTestGenerationLocked(params) {
3742
3983
  errorMessage: failureMessage
3743
3984
  };
3744
3985
  }
3745
- const generatedScriptPath = path15.join(
3746
- path15.dirname(inputFilePath),
3747
- `gen_${path15.basename(inputFilePath)}`
3986
+ const generatedScriptPath = path16.join(
3987
+ path16.dirname(inputFilePath),
3988
+ `gen_${path16.basename(inputFilePath)}`
3748
3989
  );
3749
- const generatedScriptRaw = await fs13.readFile(generatedScriptPath, "utf-8");
3990
+ const generatedScriptRaw = await fs14.readFile(generatedScriptPath, "utf-8");
3750
3991
  const generatedScript = JSON.parse(generatedScriptRaw);
3751
3992
  const generatedSteps = generatedScript.steps;
3752
3993
  if (!Array.isArray(generatedSteps)) {
@@ -3888,7 +4129,7 @@ async function runReplayLocked(params) {
3888
4129
  });
3889
4130
  if (executionResult.exitCode !== 0 || executionResult.stopReason !== void 0) {
3890
4131
  const failureMessage = describeElectronFailure({ executionResult, timeoutMs });
3891
- const artifactsDir2 = path15.join(getStorageService().getSessionsDir(), runId);
4132
+ const artifactsDir2 = path16.join(getStorageService().getSessionsDir(), runId);
3892
4133
  const failedReplayStudioResult = await readCloudRefsFile(inputFilePath);
3893
4134
  storage.updateRunResult(runId, {
3894
4135
  status: resolveFailedRunStatus(executionResult),
@@ -3909,7 +4150,7 @@ async function runReplayLocked(params) {
3909
4150
  errorMessage: failureMessage
3910
4151
  };
3911
4152
  }
3912
- const artifactsDir = path15.join(getStorageService().getSessionsDir(), runId);
4153
+ const artifactsDir = path16.join(getStorageService().getSessionsDir(), runId);
3913
4154
  const replayStudioResult = await readCloudRefsFile(inputFilePath);
3914
4155
  const replayStudioCloudRefs = extractStudioCloudRefs(replayStudioResult);
3915
4156
  storage.updateRunResult(runId, {
@@ -4157,10 +4398,10 @@ var WORKFLOW_EVENTS_FILE_NAME = "workflow-events.jsonl";
4157
4398
 
4158
4399
  // packages/mcps/src/shared/telemetry-event-log.ts
4159
4400
  function getFailureEventsFilePath() {
4160
- return path15.join(getDataDir(), TELEMETRY_DIR_NAME, FAILURE_EVENTS_FILE_NAME);
4401
+ return path16.join(getDataDir(), TELEMETRY_DIR_NAME, FAILURE_EVENTS_FILE_NAME);
4161
4402
  }
4162
4403
  function getWorkflowEventsFilePath() {
4163
- return path15.join(getDataDir(), TELEMETRY_DIR_NAME, WORKFLOW_EVENTS_FILE_NAME);
4404
+ return path16.join(getDataDir(), TELEMETRY_DIR_NAME, WORKFLOW_EVENTS_FILE_NAME);
4164
4405
  }
4165
4406
  function appendFailureEvent(record) {
4166
4407
  const timestampedRecord = { ts: (/* @__PURE__ */ new Date()).toISOString(), ...record };
@@ -4172,7 +4413,7 @@ function appendWorkflowEvent(record) {
4172
4413
  }
4173
4414
  function appendTelemetryEventLine(logFilePath, record) {
4174
4415
  try {
4175
- fs4.mkdirSync(path15.dirname(logFilePath), { recursive: true });
4416
+ fs4.mkdirSync(path16.dirname(logFilePath), { recursive: true });
4176
4417
  fs4.appendFileSync(logFilePath, `${JSON.stringify(record)}
4177
4418
  `, "utf-8");
4178
4419
  } catch (error) {
@@ -4193,7 +4434,7 @@ var PREFS_FILENAME = "preferences.json";
4193
4434
  var OAUTH_SESSION_FILENAME = "oauth-session.json";
4194
4435
  var RELEASE_MANIFEST_FILENAME = "release-manifest.json";
4195
4436
  function getDataDir3() {
4196
- return path15.join(os4.homedir(), DATA_DIR_NAME2);
4437
+ return path16.join(os4.homedir(), DATA_DIR_NAME2);
4197
4438
  }
4198
4439
 
4199
4440
  var cachedInstallId;
@@ -4379,7 +4620,7 @@ function readPreferences() {
4379
4620
  return {};
4380
4621
  }
4381
4622
  }
4382
- function writePreferences(prefs) {
4623
+ function writePreferences2(prefs) {
4383
4624
  const filePath = prefsFilePath();
4384
4625
  mkdirSync(dirname(filePath), { recursive: true });
4385
4626
  writeFileSync(filePath, JSON.stringify(prefs, null, 2) + "\n", "utf8");
@@ -4387,7 +4628,7 @@ function writePreferences(prefs) {
4387
4628
  function updatePreference(key, value) {
4388
4629
  const prefs = readPreferences();
4389
4630
  prefs[key] = value;
4390
- writePreferences(prefs);
4631
+ writePreferences2(prefs);
4391
4632
  }
4392
4633
  function preferencesFileExists() {
4393
4634
  return existsSync(prefsFilePath());
@@ -4924,7 +5165,7 @@ async function readGenerationStore(params) {
4924
5165
  const newest = (await listGenerations(params.directory)).at(-1);
4925
5166
  if (newest === void 0) return { generation: 0, record: params.emptyRecord };
4926
5167
  try {
4927
- const raw = await fs13.readFile(path15.join(params.directory, generationFileName(newest)), "utf-8");
5168
+ const raw = await fs14.readFile(path16.join(params.directory, generationFileName(newest)), "utf-8");
4928
5169
  return { generation: newest, record: JSON.parse(raw) };
4929
5170
  } catch (error) {
4930
5171
  if (error.code === "ENOENT") continue;
@@ -4956,30 +5197,30 @@ async function updateGenerationStore(params) {
4956
5197
  return { isCommitted: false, generation: lastDecision.generation, result: lastDecision.result };
4957
5198
  }
4958
5199
  async function commitGeneration(params) {
4959
- await fs13.mkdir(params.directory, { recursive: true });
5200
+ await fs14.mkdir(params.directory, { recursive: true });
4960
5201
  const nextGeneration = params.expectedGeneration + 1;
4961
- const pendingPath = path15.join(params.directory, `${PENDING_FILE_PREFIX}${process.pid}-${randomUUID()}.json`);
4962
- await fs13.writeFile(pendingPath, JSON.stringify(params.record, null, 2), "utf-8");
5202
+ const pendingPath = path16.join(params.directory, `${PENDING_FILE_PREFIX}${process.pid}-${randomUUID()}.json`);
5203
+ await fs14.writeFile(pendingPath, JSON.stringify(params.record, null, 2), "utf-8");
4963
5204
  try {
4964
- await fs13.link(pendingPath, path15.join(params.directory, generationFileName(nextGeneration)));
5205
+ await fs14.link(pendingPath, path16.join(params.directory, generationFileName(nextGeneration)));
4965
5206
  } catch (error) {
4966
5207
  if (error.code === "EEXIST") return false;
4967
5208
  throw error;
4968
5209
  } finally {
4969
- await fs13.unlink(pendingPath).catch(() => void 0);
5210
+ await fs14.unlink(pendingPath).catch(() => void 0);
4970
5211
  }
4971
5212
  await pruneGenerations({ directory: params.directory, newestGeneration: nextGeneration });
4972
5213
  return true;
4973
5214
  }
4974
5215
  async function pruneGenerations(params) {
4975
- const fileNames = await fs13.readdir(params.directory).catch(() => []);
5216
+ const fileNames = await fs14.readdir(params.directory).catch(() => []);
4976
5217
  const oldestKept = params.newestGeneration - GENERATIONS_KEPT;
4977
5218
  await Promise.all(
4978
5219
  fileNames.map(async (fileName) => {
4979
5220
  const generation = parseGenerationFileName(fileName);
4980
5221
  const isOldGeneration = generation !== null && generation < oldestKept;
4981
5222
  if (isOldGeneration || isOrphanedPendingFile(fileName)) {
4982
- await fs13.unlink(path15.join(params.directory, fileName)).catch(() => void 0);
5223
+ await fs14.unlink(path16.join(params.directory, fileName)).catch(() => void 0);
4983
5224
  }
4984
5225
  })
4985
5226
  );
@@ -4991,7 +5232,7 @@ function isOrphanedPendingFile(fileName) {
4991
5232
  }
4992
5233
  async function listGenerations(directory) {
4993
5234
  try {
4994
- return (await fs13.readdir(directory)).map((fileName) => parseGenerationFileName(fileName)).filter((generation) => generation !== null).sort((left, right) => left - right);
5235
+ return (await fs14.readdir(directory)).map((fileName) => parseGenerationFileName(fileName)).filter((generation) => generation !== null).sort((left, right) => left - right);
4995
5236
  } catch (error) {
4996
5237
  if (error.code === "ENOENT") return [];
4997
5238
  throw error;
@@ -5316,12 +5557,12 @@ function trackedServiceOnPort(params) {
5316
5557
  return params.services.find((service) => service.port === params.port) ?? null;
5317
5558
  }
5318
5559
  async function readTrackedServices() {
5319
- const directory = path15.join(getDataDir(), ...PREPARE_TRACKING_DIR_SEGMENTS);
5320
- const fileNames = await fs13.readdir(directory).catch(() => []);
5560
+ const directory = path16.join(getDataDir(), ...PREPARE_TRACKING_DIR_SEGMENTS);
5561
+ const fileNames = await fs14.readdir(directory).catch(() => []);
5321
5562
  const perFile = await Promise.all(
5322
5563
  fileNames.filter((fileName) => fileName.endsWith(".json")).map(async (fileName) => {
5323
5564
  try {
5324
- const parsed = JSON.parse(await fs13.readFile(path15.join(directory, fileName), "utf-8"));
5565
+ const parsed = JSON.parse(await fs14.readFile(path16.join(directory, fileName), "utf-8"));
5325
5566
  return (parsed.services ?? []).filter((service) => typeof service.port === "number" && typeof service.pid === "number").filter((service) => isProcessAlive(service.pid)).map(
5326
5567
  (service) => ({
5327
5568
  name: service.name ?? "",
@@ -5354,11 +5595,11 @@ async function resolveCheckoutRoot(params) {
5354
5595
  return normalizePath(root ?? params.cwd);
5355
5596
  }
5356
5597
  function normalizePath(directory) {
5357
- const resolved = path15.resolve(directory);
5598
+ const resolved = path16.resolve(directory);
5358
5599
  return os4.platform() === "win32" ? resolved.toLowerCase() : resolved;
5359
5600
  }
5360
5601
  function ledgerDir() {
5361
- return path15.join(getDataDir(), STACK_LEDGER_DIR_NAME);
5602
+ return path16.join(getDataDir(), STACK_LEDGER_DIR_NAME);
5362
5603
  }
5363
5604
  function shortSha2(sha) {
5364
5605
  return sha.slice(0, 7);
@@ -8871,139 +9112,6 @@ var LastHostClearInputSchema = z.object({
8871
9112
  cwd: z.string().describe("Project root directory whose last-used host cache to remove.")
8872
9113
  });
8873
9114
 
8874
- // packages/mcps/src/shared/project-preferences-reconcile-types.ts
8875
- var ProjectPreferencesReconcileOutcome = /* @__PURE__ */ ((ProjectPreferencesReconcileOutcome2) => {
8876
- ProjectPreferencesReconcileOutcome2["NoAction"] = "noAction";
8877
- ProjectPreferencesReconcileOutcome2["CopiedToGlobal"] = "copiedToGlobal";
8878
- ProjectPreferencesReconcileOutcome2["KeysShadowed"] = "keysShadowed";
8879
- return ProjectPreferencesReconcileOutcome2;
8880
- })(ProjectPreferencesReconcileOutcome || {});
8881
-
8882
- // packages/mcps/src/shared/preferences-service.ts
8883
- function getGlobalPreferencesFilePath(dataDirOverride2) {
8884
- return path15.join(dataDirOverride2 ?? getDataDir(), PREFERENCES_FILE_NAME);
8885
- }
8886
- function isFirstRun(dataDirOverride2) {
8887
- return !fs4.existsSync(getGlobalPreferencesFilePath(dataDirOverride2));
8888
- }
8889
- function readPreferencesFile(filePath) {
8890
- try {
8891
- if (!fs4.existsSync(filePath)) {
8892
- return {};
8893
- }
8894
- const raw = JSON.parse(fs4.readFileSync(filePath, "utf-8"));
8895
- return raw.preferences ?? {};
8896
- } catch (error) {
8897
- getLogger().warn("Failed to read preferences file", {
8898
- path: filePath,
8899
- error: error instanceof Error ? error.message : String(error)
8900
- });
8901
- return {};
8902
- }
8903
- }
8904
- function writePreferencesFile(filePath, prefs) {
8905
- const file = {
8906
- ...readRawPreferencesFile(filePath),
8907
- version: PREFERENCES_VERSION,
8908
- preferences: prefs
8909
- };
8910
- fs4.writeFileSync(filePath, `${JSON.stringify(file, null, 2)}
8911
- `, "utf-8");
8912
- }
8913
- function readRawPreferencesFile(filePath) {
8914
- try {
8915
- if (!fs4.existsSync(filePath)) {
8916
- return {};
8917
- }
8918
- return JSON.parse(fs4.readFileSync(filePath, "utf-8"));
8919
- } catch {
8920
- return {};
8921
- }
8922
- }
8923
- function resolvePreferences(dataDirOverride2) {
8924
- const saved = readPreferencesFile(getGlobalPreferencesFilePath(dataDirOverride2));
8925
- return { ...DEFAULT_PREFERENCES, ...saved };
8926
- }
8927
- function writePreferences2(prefs, dataDirOverride2) {
8928
- const dir = dataDirOverride2 ?? getDataDir();
8929
- fs4.mkdirSync(dir, { recursive: true });
8930
- const filePath = path15.join(dir, PREFERENCES_FILE_NAME);
8931
- const existing = readPreferencesFile(filePath);
8932
- writePreferencesFile(filePath, { ...existing, ...prefs });
8933
- }
8934
- function readPreferencesMetadata(dataDirOverride2) {
8935
- const metadata = {
8936
- ...readRawPreferencesFile(getGlobalPreferencesFilePath(dataDirOverride2))
8937
- };
8938
- delete metadata.preferences;
8939
- return metadata;
8940
- }
8941
- function writePreferencesWithMetadata(prefs, metadata, dataDirOverride2) {
8942
- const dir = dataDirOverride2 ?? getDataDir();
8943
- fs4.mkdirSync(dir, { recursive: true });
8944
- const filePath = path15.join(dir, PREFERENCES_FILE_NAME);
8945
- const existing = readRawPreferencesFile(filePath);
8946
- const file = {
8947
- ...existing,
8948
- ...metadata,
8949
- version: PREFERENCES_VERSION,
8950
- preferences: { ...existing.preferences ?? {}, ...prefs }
8951
- };
8952
- fs4.writeFileSync(filePath, `${JSON.stringify(file, null, 2)}
8953
- `, "utf-8");
8954
- }
8955
- function resetPreference(key, dataDirOverride2) {
8956
- const filePath = getGlobalPreferencesFilePath(dataDirOverride2);
8957
- if (!fs4.existsSync(filePath)) {
8958
- return;
8959
- }
8960
- if (!key) {
8961
- writePreferencesFile(filePath, {});
8962
- return;
8963
- }
8964
- const existing = readPreferencesFile(filePath);
8965
- delete existing[key];
8966
- writePreferencesFile(filePath, existing);
8967
- }
8968
- function reconcileProjectPreferences(cwd, dataDirOverride2) {
8969
- const projectFilePath = path15.join(cwd, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_FILE_NAME);
8970
- const projectPreferences = readPreferencesFile(projectFilePath);
8971
- const projectKeys = Object.keys(projectPreferences);
8972
- if (projectKeys.length === 0) {
8973
- return {
8974
- outcome: "noAction" /* NoAction */,
8975
- projectFilePath,
8976
- shadowedKeys: []
8977
- };
8978
- }
8979
- if (isFirstRun(dataDirOverride2)) {
8980
- writePreferences2(projectPreferences, dataDirOverride2);
8981
- return {
8982
- outcome: "copiedToGlobal" /* CopiedToGlobal */,
8983
- projectFilePath,
8984
- shadowedKeys: []
8985
- };
8986
- }
8987
- const resolved = resolvePreferences(dataDirOverride2);
8988
- const shadowedKeys = projectKeys.filter((key) => projectPreferences[key] !== resolved[key]);
8989
- return {
8990
- outcome: shadowedKeys.length > 0 ? "keysShadowed" /* KeysShadowed */ : "noAction" /* NoAction */,
8991
- projectFilePath,
8992
- shadowedKeys
8993
- };
8994
- }
8995
- function validatePreference(key, value) {
8996
- const validKeys = Object.values(PreferenceKey);
8997
- if (!validKeys.includes(key)) {
8998
- return false;
8999
- }
9000
- const allowed = PREFERENCE_ALLOWED_VALUES[key];
9001
- return allowed.includes(value);
9002
- }
9003
- function formatPreferencesOneLiner(prefs) {
9004
- return Object.entries(prefs).map(([key, value]) => `${key}=${value}`).join(" ");
9005
- }
9006
-
9007
9115
  // packages/mcps/src/shared/cwd-keyed-cache-constants.ts
9008
9116
  var CWD_KEYED_CACHE_VERSION = 1;
9009
9117
  var LEGACY_CACHE_DIR_NAME = ".muggle-ai";
@@ -9011,10 +9119,10 @@ var MUGGLE_HOME_DISPLAY_DIR = "~/.muggle-ai";
9011
9119
 
9012
9120
  // packages/mcps/src/shared/cwd-keyed-cache.ts
9013
9121
  function resolveHomeFilePath(cache) {
9014
- return path15.join(getDataDir(), cache.fileName);
9122
+ return path16.join(getDataDir(), cache.fileName);
9015
9123
  }
9016
9124
  function resolveLegacyFilePath(cache, cwd) {
9017
- return path15.join(cwd, LEGACY_CACHE_DIR_NAME, cache.fileName);
9125
+ return path16.join(cwd, LEGACY_CACHE_DIR_NAME, cache.fileName);
9018
9126
  }
9019
9127
  function parseJsonFile(filePath) {
9020
9128
  try {
@@ -9054,7 +9162,7 @@ function readLegacyEntry(cache, cwd) {
9054
9162
  return parsed?.[cache.legacyEntryKey] ?? null;
9055
9163
  }
9056
9164
  function readCwdEntry(cache, cwd) {
9057
- const cwdKey = path15.resolve(cwd);
9165
+ const cwdKey = path16.resolve(cwd);
9058
9166
  const entries = readHomeEntries(cache);
9059
9167
  const homeEntry = entries[cwdKey];
9060
9168
  if (homeEntry) {
@@ -9076,11 +9184,11 @@ function readCwdEntry(cache, cwd) {
9076
9184
  }
9077
9185
  function writeCwdEntry(cache, cwd, entry) {
9078
9186
  const entries = readHomeEntries(cache);
9079
- writeHomeEntries(cache, { ...entries, [path15.resolve(cwd)]: entry });
9187
+ writeHomeEntries(cache, { ...entries, [path16.resolve(cwd)]: entry });
9080
9188
  }
9081
9189
  function clearCwdEntry(cache, cwd) {
9082
9190
  const entries = readHomeEntries(cache);
9083
- const cwdKey = path15.resolve(cwd);
9191
+ const cwdKey = path16.resolve(cwd);
9084
9192
  if (cwdKey in entries) {
9085
9193
  delete entries[cwdKey];
9086
9194
  writeHomeEntries(cache, entries);
@@ -9362,11 +9470,11 @@ var runResultGetTool = {
9362
9470
  `**Location:** \`${storedRunResult.artifactsDir}\``,
9363
9471
  ""
9364
9472
  );
9365
- const actionScriptPath = path15.join(storedRunResult.artifactsDir, "action-script.json");
9366
- const resultsMdPath = path15.join(storedRunResult.artifactsDir, "results.md");
9367
- const screenshotsDir = path15.join(storedRunResult.artifactsDir, "screenshots");
9368
- const stdoutLogPath = path15.join(storedRunResult.artifactsDir, "stdout.log");
9369
- const stderrLogPath = path15.join(storedRunResult.artifactsDir, "stderr.log");
9473
+ const actionScriptPath = path16.join(storedRunResult.artifactsDir, "action-script.json");
9474
+ const resultsMdPath = path16.join(storedRunResult.artifactsDir, "results.md");
9475
+ const screenshotsDir = path16.join(storedRunResult.artifactsDir, "screenshots");
9476
+ const stdoutLogPath = path16.join(storedRunResult.artifactsDir, "stdout.log");
9477
+ const stderrLogPath = path16.join(storedRunResult.artifactsDir, "stderr.log");
9370
9478
  const artifactItems = [];
9371
9479
  if (fs4.existsSync(actionScriptPath)) {
9372
9480
  artifactItems.push("- `action-script.json` \u2014 generated test steps");
@@ -9594,7 +9702,7 @@ var preferencesSetTool = {
9594
9702
  const logger7 = createChildLogger2(ctx.correlationId);
9595
9703
  logger7.info("Executing muggle-local-preferences-set");
9596
9704
  const input = PreferencesSetInputSchema.parse(ctx.input);
9597
- writePreferences2({ [input.key]: input.value });
9705
+ writePreferences({ [input.key]: input.value });
9598
9706
  return {
9599
9707
  content: `**${input.key}** set to **${input.value}**.`,
9600
9708
  isError: false
@@ -10355,4 +10463,111 @@ function applyOnboardingAnswers(answers, dataDirOverride2, now = /* @__PURE__ */
10355
10463
  return { isCompleted: true, preferences: prefs };
10356
10464
  }
10357
10465
 
10358
- export { ACTION_SCRIPT_FILE_NAME, BASE_REMOTE_NAME, BLOCKING_FRESHNESS_VERDICTS, BRANCH_CREATION_REFLOG_PREFIX, BUSY_EXIT_CODE, CheckoutFreshnessVerdict, DEFAULT_PREFERENCES, ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS, ElectronAppPlatform, ElectronAppReleaseStream, EventName, HTML_VIEW_OFFER_LINE, MAX_LISTED_INHERITED_COMMITS, ONBOARDING_BLANKET_OPTIONS, ONBOARDING_CHOICE_GROUPS, ONBOARDING_MAX_OFFERS, ONBOARDING_PRIMER_BULLETS, ONBOARDING_PRIMER_HEADLINE, ONBOARDING_TOGGLE_GROUPS, ONBOARDING_TOGGLE_PROMPT, ONBOARDING_UNSELECTED_TOGGLE_VALUE, OnboardingBlanketChoice, OnboardingGroupKind, PREFERENCES_FILE_NAME, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_SCHEMA, PREFERENCES_VERSION, PREFERENCE_ALLOWED_VALUES, PreferenceKey, PreferenceValue, ProjectPreferencesReconcileOutcome, RUN_SESSIONS_DIR_NAME, RUN_VIEW_DASHBOARD_LINK_LABEL, RunViewError, RuntimeTarget, SCREENSHOT_DIR_RELATIVE_PATH, SCREENSHOT_FILE_EXTENSION, ServiceName, StackCheckVerdict, StackClaimVerdict, StackPortAction, Surface, WATCHER_LIFETIME_SECONDS, WATCHER_LIFETIME_UNBOUNDED_SECONDS, __export, __require, applyOnboardingAnswers, assertDeviceCodeClientProvisioned, buildElectronAppChecksumsUrl, buildElectronAppDirName, buildElectronAppReleaseAssetUrl, buildElectronAppReleaseTag, buildOnboardingPlan, buildToolInputJsonSchema, calculateFileChecksum, checkServiceStack, claimServiceStack, completeOnboarding, createApiKeyWithToken, createChildLogger, decideStackClaim, decideStackRelease, decideStackRenewal, deleteApiKeyData, deleteCredentials, e2e_exports2 as e2e_exports, evaluateCheckoutFreshness, formatPreferencesOneLiner, getActiveElectronAppReleaseStream, getActiveRuntimeTarget, getApiKey, getApiKeyFilePath, getAuthService, getBundledElectronAppVersion, getCallerCredentials, getCallerCredentialsAsync, getChecksumForPlatform, getConfig, getCredentialsFilePath, getDashboardBaseUrl, getDataDir, getDataDir2, getDisclosureCopy, getDownloadBaseUrl, getElectronAppChecksums, getElectronAppDir, getElectronAppReleaseTagPrefix, getElectronAppSignedFromVersion, getElectronAppVersion, getElectronAppVersionSource, getLocalQaTools, getLogger, getOnboardingToggleKeys, getPlatformKey, getQaTools, getReleaseSignerIdentityUri, getRunSessionsDir, getValidApiKeyData, getValidCredentials, hasApiKey, hasShownDisclosure, initTelemetry, isElectronAppInstalled, isElectronAppPlatform, isFirstRun, loadApiKeyData, loadCredentials, local_exports2 as local_exports, markDisclosureShown, markOnboardingCompleted, mcp_exports, needsConflict, needsOnboarding, openBrowserUrl, parseElectronAppDirName, performLogin, performLogout, pollDeviceCode, portOfUrl, readPreferencesMetadata, readRunView, readServiceStackStatus, reconcileProjectPreferences, recordOnboardingSkip, releaseServiceStack, renderRunViewHtml, renderRunViewText, resetConfig, resetLogger, resetPreference, resolveActiveProfile, resolveActiveReleaseStream, resolveActiveReleaseTagPrefix, resolveBlanketPreferences, resolveElectronAppExecutablePath, resolveElectronAppPathOrNull, resolveOnboardingAnswers, resolvePreferences, resolveRunSessionPath, resolveRuntimeTarget, resolveTogglePreferences, runGitCommand, saveApiKey, saveApiKeyData, saveCredentials, src_exports, startDeviceCodeFlow, toDisplayRef, toolRequiresAuth, track, validatePreference, verifyFileChecksum, writePreferences2 as writePreferences, writePreferencesWithMetadata, writeRunViewHtml };
10466
+ // packages/mcps/src/shared/llm-source/llm-source-service.ts
10467
+ function readLlmEnvBlock(dataDirOverride2) {
10468
+ const llmEnv = readPreferencesMetadata(dataDirOverride2).llmEnv;
10469
+ if (!llmEnv || typeof llmEnv !== "object" || Array.isArray(llmEnv)) {
10470
+ return {};
10471
+ }
10472
+ return llmEnv;
10473
+ }
10474
+ function maskLlmApiKey(apiKey) {
10475
+ if (apiKey.length <= MASKED_API_KEY_VISIBLE_CHARS) {
10476
+ return MASKED_API_KEY_PREFIX;
10477
+ }
10478
+ return `${MASKED_API_KEY_PREFIX}${apiKey.slice(-MASKED_API_KEY_VISIBLE_CHARS)}`;
10479
+ }
10480
+ function isValidLocalBaseUrl(candidateBaseUrl) {
10481
+ try {
10482
+ const parsed = new URL(candidateBaseUrl);
10483
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
10484
+ } catch {
10485
+ return false;
10486
+ }
10487
+ }
10488
+ function resolveLlmSourceStatus(dataDirOverride2) {
10489
+ const llmEnv = readLlmEnvBlock(dataDirOverride2);
10490
+ const apiKey = llmEnv["MUGGLE_LLM_API_KEY" /* ApiKey */] ?? readStoredLlmApiKey(dataDirOverride2);
10491
+ const maskedApiKey = apiKey ? maskLlmApiKey(apiKey) : void 0;
10492
+ if (llmEnv["MUGGLE_LLM_PROVIDER" /* Provider */] === "anthropic" /* Anthropic */ && maskedApiKey) {
10493
+ return { source: "anthropic-api-key" /* AnthropicApiKey */, maskedApiKey };
10494
+ }
10495
+ if (llmEnv["MUGGLE_LLM_PROVIDER" /* Provider */] === "local" /* Local */) {
10496
+ return {
10497
+ source: "local-model" /* LocalModel */,
10498
+ maskedApiKey,
10499
+ localBaseUrl: llmEnv["MUGGLE_LLM_BASE_URL" /* BaseUrl */],
10500
+ localModel: llmEnv["MUGGLE_LLM_MODEL" /* Model */]
10501
+ };
10502
+ }
10503
+ return { source: "muggle-credit" /* MuggleCredit */ };
10504
+ }
10505
+ function getLlmSourceOption(source) {
10506
+ return LLM_SOURCE_OPTIONS.find((option) => option.source === source) ?? LLM_SOURCE_OPTIONS[0];
10507
+ }
10508
+ function buildLlmSourcePlan(dataDirOverride2) {
10509
+ return {
10510
+ header: LLM_SOURCE_HEADER,
10511
+ prompt: LLM_SOURCE_PROMPT,
10512
+ scopeNote: LLM_SOURCE_SCOPE_NOTE,
10513
+ options: [...LLM_SOURCE_OPTIONS],
10514
+ current: resolveLlmSourceStatus(dataDirOverride2)
10515
+ };
10516
+ }
10517
+ function describeLlmSourceStatus(status) {
10518
+ const label = getLlmSourceOption(status.source).label;
10519
+ if (status.source === "anthropic-api-key" /* AnthropicApiKey */) {
10520
+ return `LLM source: ${label} (${status.maskedApiKey})`;
10521
+ }
10522
+ if (status.source === "local-model" /* LocalModel */) {
10523
+ return `LLM source: ${label} \u2014 ${status.localModel} at ${status.localBaseUrl}`;
10524
+ }
10525
+ return `LLM source: ${label}`;
10526
+ }
10527
+ function assertValidSelection(selection) {
10528
+ if (selection.source === "anthropic-api-key" /* AnthropicApiKey */ && !selection.apiKey?.trim()) {
10529
+ throw new Error("An Anthropic API key is required for this source.");
10530
+ }
10531
+ if (selection.source === "local-model" /* LocalModel */) {
10532
+ if (!selection.localBaseUrl || !isValidLocalBaseUrl(selection.localBaseUrl)) {
10533
+ throw new Error("A local model needs an http(s) endpoint URL, e.g. http://localhost:11434/v1.");
10534
+ }
10535
+ if (!selection.localModel?.trim()) {
10536
+ throw new Error("A local model needs the model name the endpoint serves.");
10537
+ }
10538
+ }
10539
+ }
10540
+ function applyLlmSourceSelection(selection, dataDirOverride2) {
10541
+ assertValidSelection(selection);
10542
+ if (selection.source === "muggle-credit" /* MuggleCredit */) {
10543
+ writeLlmEnvBlock(void 0, dataDirOverride2);
10544
+ deleteStoredLlmApiKey(dataDirOverride2);
10545
+ return resolveLlmSourceStatus(dataDirOverride2);
10546
+ }
10547
+ if (selection.source === "anthropic-api-key" /* AnthropicApiKey */) {
10548
+ writeStoredLlmApiKey(selection.apiKey.trim(), dataDirOverride2);
10549
+ writeLlmEnvBlock({ ["MUGGLE_LLM_PROVIDER" /* Provider */]: "anthropic" /* Anthropic */ }, dataDirOverride2);
10550
+ return resolveLlmSourceStatus(dataDirOverride2);
10551
+ }
10552
+ const userTuning = Object.fromEntries(
10553
+ Object.entries(readLlmEnvBlock(dataDirOverride2)).filter(([name]) => !LLM_SOURCE_OWNED_ENV_NAMES.includes(name))
10554
+ );
10555
+ const localApiKey = selection.apiKey?.trim();
10556
+ if (localApiKey) {
10557
+ writeStoredLlmApiKey(localApiKey, dataDirOverride2);
10558
+ } else {
10559
+ deleteStoredLlmApiKey(dataDirOverride2);
10560
+ }
10561
+ writeLlmEnvBlock(
10562
+ {
10563
+ ...userTuning,
10564
+ ["MUGGLE_LLM_PROVIDER" /* Provider */]: "local" /* Local */,
10565
+ ["MUGGLE_LLM_BASE_URL" /* BaseUrl */]: selection.localBaseUrl,
10566
+ ["MUGGLE_LLM_MODEL" /* Model */]: selection.localModel.trim()
10567
+ },
10568
+ dataDirOverride2
10569
+ );
10570
+ return resolveLlmSourceStatus(dataDirOverride2);
10571
+ }
10572
+
10573
+ export { ACTION_SCRIPT_FILE_NAME, BASE_REMOTE_NAME, BLOCKING_FRESHNESS_VERDICTS, BRANCH_CREATION_REFLOG_PREFIX, BUSY_EXIT_CODE, CheckoutFreshnessVerdict, DEFAULT_LOCAL_LLM_BASE_URL, DEFAULT_PREFERENCES, ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS, ElectronAppPlatform, ElectronAppReleaseStream, EventName, HTML_VIEW_OFFER_LINE, LLM_CREDENTIALS_FILE_MODE, LLM_CREDENTIALS_FILE_NAME, LLM_SOURCE_HEADER, LLM_SOURCE_OPTIONS, LLM_SOURCE_OWNED_ENV_NAMES, LLM_SOURCE_PROMPT, LLM_SOURCE_SCOPE_NOTE, LlmSource, MASKED_API_KEY_PREFIX, MASKED_API_KEY_VISIBLE_CHARS, MAX_LISTED_INHERITED_COMMITS, ONBOARDING_BLANKET_OPTIONS, ONBOARDING_CHOICE_GROUPS, ONBOARDING_MAX_OFFERS, ONBOARDING_PRIMER_BULLETS, ONBOARDING_PRIMER_HEADLINE, ONBOARDING_TOGGLE_GROUPS, ONBOARDING_TOGGLE_PROMPT, ONBOARDING_UNSELECTED_TOGGLE_VALUE, OnboardingBlanketChoice, OnboardingGroupKind, PREFERENCES_FILE_NAME, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_SCHEMA, PREFERENCES_VERSION, PREFERENCE_ALLOWED_VALUES, PreferenceKey, PreferenceValue, ProjectPreferencesReconcileOutcome, RUN_SESSIONS_DIR_NAME, RUN_VIEW_DASHBOARD_LINK_LABEL, RunViewError, RuntimeTarget, SCREENSHOT_DIR_RELATIVE_PATH, SCREENSHOT_FILE_EXTENSION, ServiceName, StackCheckVerdict, StackClaimVerdict, StackPortAction, Surface, WATCHER_LIFETIME_SECONDS, WATCHER_LIFETIME_UNBOUNDED_SECONDS, __export, __require, applyLlmSourceSelection, applyOnboardingAnswers, assertDeviceCodeClientProvisioned, buildElectronAppChecksumsUrl, buildElectronAppDirName, buildElectronAppReleaseAssetUrl, buildElectronAppReleaseTag, buildLlmSourcePlan, buildOnboardingPlan, buildToolInputJsonSchema, calculateFileChecksum, checkServiceStack, claimServiceStack, completeOnboarding, createApiKeyWithToken, createChildLogger, decideStackClaim, decideStackRelease, decideStackRenewal, deleteApiKeyData, deleteCredentials, describeLlmSourceStatus, e2e_exports2 as e2e_exports, evaluateCheckoutFreshness, formatPreferencesOneLiner, getActiveElectronAppReleaseStream, getActiveRuntimeTarget, getApiKey, getApiKeyFilePath, getAuthService, getBundledElectronAppVersion, getCallerCredentials, getCallerCredentialsAsync, getChecksumForPlatform, getConfig, getCredentialsFilePath, getDashboardBaseUrl, getDataDir, getDataDir2, getDisclosureCopy, getDownloadBaseUrl, getElectronAppChecksums, getElectronAppDir, getElectronAppReleaseTagPrefix, getElectronAppSignedFromVersion, getElectronAppVersion, getElectronAppVersionSource, getLlmSourceOption, getLocalQaTools, getLogger, getOnboardingToggleKeys, getPlatformKey, getQaTools, getReleaseSignerIdentityUri, getRunSessionsDir, getValidApiKeyData, getValidCredentials, hasApiKey, hasShownDisclosure, initTelemetry, isElectronAppInstalled, isElectronAppPlatform, isFirstRun, isValidLocalBaseUrl, loadApiKeyData, loadCredentials, local_exports2 as local_exports, markDisclosureShown, markOnboardingCompleted, maskLlmApiKey, mcp_exports, needsConflict, needsOnboarding, openBrowserUrl, parseElectronAppDirName, performLogin, performLogout, pollDeviceCode, portOfUrl, readPreferencesMetadata, readRunView, readServiceStackStatus, reconcileProjectPreferences, recordOnboardingSkip, releaseServiceStack, renderRunViewHtml, renderRunViewText, resetConfig, resetLogger, resetPreference, resolveActiveProfile, resolveActiveReleaseStream, resolveActiveReleaseTagPrefix, resolveBlanketPreferences, resolveElectronAppExecutablePath, resolveElectronAppPathOrNull, resolveLlmSourceStatus, resolveOnboardingAnswers, resolvePreferences, resolveRunSessionPath, resolveRuntimeTarget, resolveTogglePreferences, runGitCommand, saveApiKey, saveApiKeyData, saveCredentials, src_exports, startDeviceCodeFlow, toDisplayRef, toolRequiresAuth, track, validatePreference, verifyFileChecksum, writeLlmEnvBlock, writePreferences, writePreferencesWithMetadata, writeRunViewHtml };