@muggleai/works 5.25.0-staging.186 → 5.25.0-staging.187

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/{chunk-53MCWNVE.js → chunk-TDDPUID3.js} +2 -2
  3. package/dist/{chunk-C6OEDLIP.js → chunk-V5KNPQ7B.js} +846 -800
  4. package/dist/cli.js +2 -2
  5. package/dist/index.js +2 -2
  6. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  7. package/dist/plugin/.codex-mcp.json +1 -1
  8. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  9. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  10. package/dist/plugin/.mcp.json +1 -1
  11. package/dist/plugin/scripts/pr-watch-arm.sh +20 -1
  12. package/dist/plugin/skills/_shared/telemetry-events/muggle-do-cycle.md +18 -15
  13. package/dist/plugin/skills/_shared/telemetry-events/muggle-do-escalation.md +9 -7
  14. package/dist/plugin/skills/_shared/telemetry-events/muggle-do-resolve-reminder.md +11 -9
  15. package/dist/plugin/skills/_shared/telemetry-events/pr-followup-bootstrap.md +10 -8
  16. package/dist/plugin/skills/_shared/telemetry-events/pr-followup-tick.md +17 -15
  17. package/dist/plugin/skills/_shared/telemetry-events.md +1 -1
  18. package/dist/plugin/skills/muggle-pr-followup/blocked-tick.md +1 -1
  19. package/dist/plugin/skills/muggle-pr-followup/state-schemas.md +1 -1
  20. package/dist/release-manifest.json +3 -3
  21. package/dist/{src-V7DVV6KO.js → src-XKTB74LV.js} +1 -1
  22. package/package.json +1 -1
  23. package/plugin/.claude-plugin/plugin.json +1 -1
  24. package/plugin/.codex-mcp.json +1 -1
  25. package/plugin/.codex-plugin/plugin.json +1 -1
  26. package/plugin/.cursor-plugin/plugin.json +1 -1
  27. package/plugin/.mcp.json +1 -1
  28. package/plugin/scripts/pr-watch-arm.sh +20 -1
  29. package/plugin/skills/_shared/telemetry-events/muggle-do-cycle.md +18 -15
  30. package/plugin/skills/_shared/telemetry-events/muggle-do-escalation.md +9 -7
  31. package/plugin/skills/_shared/telemetry-events/muggle-do-resolve-reminder.md +11 -9
  32. package/plugin/skills/_shared/telemetry-events/pr-followup-bootstrap.md +10 -8
  33. package/plugin/skills/_shared/telemetry-events/pr-followup-tick.md +17 -15
  34. package/plugin/skills/_shared/telemetry-events.md +1 -1
  35. package/plugin/skills/muggle-pr-followup/blocked-tick.md +1 -1
  36. package/plugin/skills/muggle-pr-followup/state-schemas.md +1 -1
@@ -4131,828 +4131,930 @@ async function findRunCheckoutRefusal(params) {
4131
4131
  return BLOCKING_FRESHNESS_VERDICTS.has(report.verdict) ? report : null;
4132
4132
  }
4133
4133
 
4134
- // packages/mcps/src/shared/auth.ts
4135
- var logger6 = getLogger();
4136
- async function startDeviceCodeFlow(config, options) {
4137
- const deviceCodeUrl = `https://${config.domain}/oauth/device/code`;
4134
+ // packages/mcps/src/shared/telemetry-event-log-constants.ts
4135
+ var TELEMETRY_DIR_NAME = "telemetry";
4136
+ var FAILURE_EVENTS_FILE_NAME = "failure-events.jsonl";
4137
+ var WORKFLOW_EVENTS_FILE_NAME = "workflow-events.jsonl";
4138
+
4139
+ // packages/mcps/src/shared/telemetry-event-log.ts
4140
+ function getFailureEventsFilePath() {
4141
+ return path15.join(getDataDir(), TELEMETRY_DIR_NAME, FAILURE_EVENTS_FILE_NAME);
4142
+ }
4143
+ function getWorkflowEventsFilePath() {
4144
+ return path15.join(getDataDir(), TELEMETRY_DIR_NAME, WORKFLOW_EVENTS_FILE_NAME);
4145
+ }
4146
+ function appendFailureEvent(record) {
4147
+ const timestampedRecord = { ts: (/* @__PURE__ */ new Date()).toISOString(), ...record };
4148
+ appendTelemetryEventLine(getFailureEventsFilePath(), timestampedRecord);
4149
+ }
4150
+ function appendWorkflowEvent(record) {
4151
+ const timestampedRecord = { ts: (/* @__PURE__ */ new Date()).toISOString(), ...record };
4152
+ appendTelemetryEventLine(getWorkflowEventsFilePath(), timestampedRecord);
4153
+ }
4154
+ function appendTelemetryEventLine(logFilePath, record) {
4138
4155
  try {
4139
- logger6.info("[Auth] Starting device code flow", {
4140
- domain: config.domain,
4141
- clientId: config.clientId
4142
- });
4143
- const response = await axios.post(
4144
- deviceCodeUrl,
4145
- new URLSearchParams({
4146
- client_id: config.clientId,
4147
- scope: config.scope,
4148
- audience: config.audience
4149
- }).toString(),
4150
- {
4151
- headers: {
4152
- "Content-Type": "application/x-www-form-urlencoded"
4153
- }
4154
- }
4155
- );
4156
- const data = response.data;
4157
- logger6.info("[Auth] Device code flow started successfully", {
4158
- userCode: data.user_code,
4159
- expiresIn: data.expires_in
4160
- });
4161
- let browserUrl = data.verification_uri_complete;
4162
- if (options?.forceNewSession) {
4163
- const logoutUrl = new URL(`https://${config.domain}/v2/logout`);
4164
- logoutUrl.searchParams.set("client_id", config.clientId);
4165
- logoutUrl.searchParams.set("returnTo", data.verification_uri_complete);
4166
- browserUrl = logoutUrl.toString();
4167
- logger6.info("[Auth] Force new session: opening logout-redirect URL");
4168
- }
4169
- const browserOpenResult = await openBrowserUrl({
4170
- url: browserUrl
4171
- });
4172
- if (browserOpenResult.opened) {
4173
- logger6.info("[Auth] Browser opened for device code login");
4174
- } else {
4175
- logger6.warn("[Auth] Failed to open browser", {
4176
- error: browserOpenResult.error,
4177
- verificationUriComplete: data.verification_uri_complete
4178
- });
4179
- }
4180
- return {
4181
- deviceCode: data.device_code,
4182
- userCode: data.user_code,
4183
- verificationUri: data.verification_uri,
4184
- verificationUriComplete: data.verification_uri_complete,
4185
- expiresIn: data.expires_in,
4186
- interval: data.interval || 5,
4187
- browserOpened: browserOpenResult.opened,
4188
- browserOpenError: browserOpenResult.error
4189
- };
4156
+ fs4.mkdirSync(path15.dirname(logFilePath), { recursive: true });
4157
+ fs4.appendFileSync(logFilePath, `${JSON.stringify(record)}
4158
+ `, "utf-8");
4190
4159
  } catch (error) {
4191
- if (error instanceof AxiosError) {
4192
- logger6.error("[Auth] Failed to start device code flow", {
4193
- status: error.response?.status,
4194
- data: error.response?.data
4195
- });
4196
- throw new Error(
4197
- `Failed to start device code flow: ${error.response?.data?.error_description || error.message}`,
4198
- { cause: error }
4199
- );
4200
- }
4201
- throw error;
4160
+ getLogger().warn("Failed to append telemetry event", {
4161
+ logFilePath,
4162
+ error: error instanceof Error ? error.message : String(error)
4163
+ });
4202
4164
  }
4203
4165
  }
4204
- async function pollDeviceCode(config, deviceCode) {
4205
- const tokenUrl = `https://${config.domain}/oauth/token`;
4166
+
4167
+ var ENV_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING";
4168
+ var ENV_VITE_CONNECTION_STRING = "VITE_APPLICATIONINSIGHTS_CONNECTION_STRING";
4169
+ var ENV_TELEMETRY_DISABLED = "MUGGLE_TELEMETRY_DISABLED";
4170
+
4171
+ var DATA_DIR_NAME2 = ".muggle-ai";
4172
+ var INSTALL_ID_FILENAME = "install-id.json";
4173
+ var PREFS_FILENAME = "preferences.json";
4174
+ var OAUTH_SESSION_FILENAME = "oauth-session.json";
4175
+ var RELEASE_MANIFEST_FILENAME = "release-manifest.json";
4176
+ function getDataDir3() {
4177
+ return path15.join(os4.homedir(), DATA_DIR_NAME2);
4178
+ }
4179
+
4180
+ var cachedInstallId;
4181
+ function installIdFilePath() {
4182
+ return join(getDataDir3(), INSTALL_ID_FILENAME);
4183
+ }
4184
+ function generateAndPersist(filePath) {
4185
+ const installId = randomUUID();
4186
+ const contents = { installId };
4187
+ mkdirSync(dirname(filePath), { recursive: true });
4188
+ writeFileSync(filePath, JSON.stringify(contents, null, 2) + "\n", "utf8");
4189
+ return installId;
4190
+ }
4191
+ function isValid(value) {
4192
+ return typeof value === "object" && value !== null && typeof value.installId === "string" && value.installId.length > 0;
4193
+ }
4194
+ function getInstallId() {
4195
+ if (cachedInstallId !== void 0)
4196
+ return cachedInstallId;
4197
+ const filePath = installIdFilePath();
4198
+ if (!existsSync(filePath)) {
4199
+ cachedInstallId = generateAndPersist(filePath);
4200
+ return cachedInstallId;
4201
+ }
4206
4202
  try {
4207
- const response = await axios.post(
4208
- tokenUrl,
4209
- new URLSearchParams({
4210
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
4211
- device_code: deviceCode,
4212
- client_id: config.clientId
4213
- }).toString(),
4214
- {
4215
- headers: {
4216
- "Content-Type": "application/x-www-form-urlencoded"
4217
- }
4218
- }
4219
- );
4220
- logger6.info("[Auth] Authorization successful");
4221
- return {
4222
- status: "authorized",
4223
- accessToken: response.data.access_token,
4224
- tokenType: response.data.token_type,
4225
- expiresIn: response.data.expires_in
4226
- };
4227
- } catch (error) {
4228
- if (error instanceof AxiosError && error.response) {
4229
- const data = error.response.data;
4230
- const errorCode = data.error;
4231
- if (errorCode === "authorization_pending") {
4232
- return {
4233
- status: "authorization_pending",
4234
- error: errorCode,
4235
- errorDescription: data.error_description || "User has not yet authorized"
4236
- };
4237
- }
4238
- if (errorCode === "slow_down") {
4239
- return {
4240
- status: "slow_down",
4241
- error: errorCode,
4242
- errorDescription: data.error_description || "Too many requests, slow down"
4243
- };
4244
- }
4245
- if (errorCode === "expired_token") {
4246
- return {
4247
- status: "expired_token",
4248
- error: errorCode,
4249
- errorDescription: data.error_description || "Device code expired, please restart flow"
4250
- };
4251
- }
4252
- if (errorCode === "access_denied") {
4253
- return {
4254
- status: "access_denied",
4255
- error: errorCode,
4256
- errorDescription: data.error_description || "User denied access"
4257
- };
4258
- }
4259
- logger6.error("[Auth] Unexpected error during poll", {
4260
- status: error.response.status,
4261
- error: errorCode,
4262
- description: data.error_description
4263
- });
4264
- throw new Error(
4265
- `Device code poll failed: ${data.error_description || data.error || "Unknown error"}`,
4266
- { cause: error }
4267
- );
4203
+ const raw = readFileSync(filePath, "utf8");
4204
+ const parsed = JSON.parse(raw);
4205
+ if (isValid(parsed)) {
4206
+ cachedInstallId = parsed.installId;
4207
+ return cachedInstallId;
4268
4208
  }
4269
- throw error;
4209
+ cachedInstallId = generateAndPersist(filePath);
4210
+ return cachedInstallId;
4211
+ } catch {
4212
+ cachedInstallId = generateAndPersist(filePath);
4213
+ return cachedInstallId;
4270
4214
  }
4271
4215
  }
4272
- async function createApiKeyWithToken(accessToken, keyName, expiry = "90d") {
4273
- const config = getConfig();
4274
- const apiKeyUrl = `${config.e2e.promptServiceBaseUrl}/v1/protected/api-keys`;
4216
+
4217
+ var DEV_MANIFEST2 = {
4218
+ release: "dev",
4219
+ buildId: "dev",
4220
+ commitSha: "dev",
4221
+ buildTime: "1970-01-01T00:00:00Z",
4222
+ serviceName: "muggle-ai-telemetry"
4223
+ };
4224
+
4225
+ var MANIFEST_PATH2 = (() => {
4275
4226
  try {
4276
- logger6.info("[Auth] Creating API key", {
4277
- keyName,
4278
- expiry
4279
- });
4280
- const response = await axios.post(
4281
- apiKeyUrl,
4282
- {
4283
- name: keyName || "MCP Auto-Generated",
4284
- expiry
4285
- },
4286
- {
4287
- headers: {
4288
- Authorization: `Bearer ${accessToken}`,
4289
- "Content-Type": "application/json"
4290
- }
4291
- }
4292
- );
4293
- logger6.info("[Auth] API key created successfully", {
4294
- keyId: response.data.id
4295
- });
4296
- return response.data;
4297
- } catch (error) {
4298
- if (error instanceof AxiosError) {
4299
- logger6.error("[Auth] Failed to create API key", {
4300
- status: error.response?.status,
4301
- data: error.response?.data
4227
+ return join(dirname(fileURLToPath(import.meta.url)), RELEASE_MANIFEST_FILENAME);
4228
+ } catch {
4229
+ return RELEASE_MANIFEST_FILENAME;
4230
+ }
4231
+ })();
4232
+ var cachedManifest2;
4233
+ function isValid2(value) {
4234
+ if (typeof value !== "object" || value === null)
4235
+ return false;
4236
+ const m = value;
4237
+ return typeof m.release === "string" && typeof m.buildId === "string" && typeof m.commitSha === "string" && typeof m.buildTime === "string" && typeof m.serviceName === "string";
4238
+ }
4239
+ function readReleaseManifest2() {
4240
+ if (cachedManifest2 !== void 0)
4241
+ return cachedManifest2;
4242
+ const path21 = MANIFEST_PATH2;
4243
+ try {
4244
+ const raw = readFileSync(path21, "utf8");
4245
+ const parsed = JSON.parse(raw);
4246
+ cachedManifest2 = isValid2(parsed) ? parsed : DEV_MANIFEST2;
4247
+ return cachedManifest2;
4248
+ } catch (err) {
4249
+ const code = err.code;
4250
+ if (code !== "ENOENT") {
4251
+ console.warn("release-manifest: unexpected read error, using DEV fallback", {
4252
+ error: err.message
4302
4253
  });
4303
- throw new Error(
4304
- `Failed to create API key: ${error.response?.data?.message || error.message}`,
4305
- { cause: error }
4306
- );
4307
4254
  }
4308
- throw error;
4255
+ cachedManifest2 = DEV_MANIFEST2;
4256
+ return cachedManifest2;
4309
4257
  }
4310
4258
  }
4311
- async function performLogin(keyName, keyExpiry = "90d", timeoutMs = 12e4) {
4312
- const authService = getAuthService();
4259
+ function readUserId() {
4260
+ const filePath = join(getDataDir3(), OAUTH_SESSION_FILENAME);
4261
+ if (!existsSync(filePath))
4262
+ return void 0;
4313
4263
  try {
4314
- const authDeviceCodeResponse = await authService.startDeviceCodeFlow();
4315
- const deviceCodeResponse = {
4316
- deviceCode: authDeviceCodeResponse.deviceCode,
4317
- userCode: authDeviceCodeResponse.userCode,
4318
- verificationUri: authDeviceCodeResponse.verificationUri,
4319
- verificationUriComplete: authDeviceCodeResponse.verificationUriComplete,
4320
- expiresIn: authDeviceCodeResponse.expiresIn,
4321
- interval: authDeviceCodeResponse.interval,
4322
- browserOpened: authDeviceCodeResponse.browserOpened ?? false,
4323
- browserOpenError: authDeviceCodeResponse.browserOpenError
4324
- };
4325
- const pollResult = await authService.waitForDeviceCodeAuthorization({
4326
- deviceCode: deviceCodeResponse.deviceCode,
4327
- intervalSeconds: deviceCodeResponse.interval,
4328
- timeoutMs
4329
- });
4330
- if (pollResult.status === "complete") {
4331
- const storedAuth = authService.loadStoredAuth();
4332
- const credentials = {
4333
- accessToken: storedAuth?.accessToken ?? "",
4334
- expiresAt: storedAuth?.expiresAt ?? "",
4335
- email: storedAuth?.email,
4336
- userId: storedAuth?.userId
4337
- };
4338
- if (keyName && storedAuth?.accessToken) {
4339
- logger6.info("[Auth] Creating API key as explicitly requested", {
4340
- keyName
4341
- });
4342
- const apiKeyResult = await createApiKeyWithToken(
4343
- storedAuth.accessToken,
4344
- keyName,
4345
- keyExpiry
4346
- );
4347
- credentials.apiKey = apiKeyResult.key;
4348
- credentials.apiKeyId = apiKeyResult.id;
4349
- saveApiKeyData(credentials);
4350
- }
4351
- return {
4352
- success: true,
4353
- deviceCodeResponse,
4354
- credentials
4355
- };
4356
- }
4357
- if (pollResult.status === "expired") {
4358
- return {
4359
- success: false,
4360
- deviceCodeResponse,
4361
- error: "Device code expired. Please try again."
4362
- };
4363
- }
4364
- if (pollResult.status === "error") {
4365
- return {
4366
- success: false,
4367
- deviceCodeResponse,
4368
- error: pollResult.error ?? pollResult.message
4369
- };
4264
+ const raw = readFileSync(filePath, "utf8");
4265
+ const parsed = JSON.parse(raw);
4266
+ if (typeof parsed.userId === "string" && parsed.userId.length > 0) {
4267
+ return parsed.userId;
4370
4268
  }
4371
- return {
4372
- success: false,
4373
- deviceCodeResponse,
4374
- error: pollResult.message
4375
- };
4376
- } catch (error) {
4377
- return {
4378
- success: false,
4379
- error: error instanceof Error ? error.message : String(error)
4380
- };
4269
+ return void 0;
4270
+ } catch {
4271
+ return void 0;
4381
4272
  }
4382
4273
  }
4383
- function performLogout() {
4384
- const authService = getAuthService();
4385
- authService.logout();
4386
- deleteApiKeyData();
4387
- logger6.info("[Auth] Logged out successfully");
4274
+
4275
+ var state = null;
4276
+ function resolveConnectionString(explicit) {
4277
+ if (explicit && explicit.length > 0)
4278
+ return explicit;
4279
+ return process.env[ENV_CONNECTION_STRING] ?? process.env[ENV_VITE_CONNECTION_STRING] ?? void 0;
4388
4280
  }
4389
- function getCallerCredentials() {
4390
- const apiKeyData = getValidApiKeyData();
4391
- if (apiKeyData?.apiKey) {
4392
- return { apiKey: apiKeyData.apiKey };
4393
- }
4394
- const authService = getAuthService();
4395
- const accessToken = authService.getAccessToken();
4396
- if (accessToken) {
4397
- return { bearerToken: accessToken };
4398
- }
4399
- return {};
4281
+ function buildCommonProperties(serviceName, surface) {
4282
+ const manifest = readReleaseManifest2();
4283
+ const props = {
4284
+ source: "client",
4285
+ serviceName,
4286
+ surface,
4287
+ release: manifest.release,
4288
+ buildId: manifest.buildId,
4289
+ commitSha: manifest.commitSha,
4290
+ buildTime: manifest.buildTime,
4291
+ installId: getInstallId(),
4292
+ nodeVersion: process.version,
4293
+ platform: process.platform
4294
+ };
4295
+ const userId = readUserId();
4296
+ if (userId !== void 0)
4297
+ props.userId = userId;
4298
+ return props;
4400
4299
  }
4401
- async function getCallerCredentialsAsync() {
4402
- const apiKeyData = getValidApiKeyData();
4403
- if (apiKeyData?.apiKey) {
4404
- return { apiKey: apiKeyData.apiKey };
4300
+ function initTelemetry(options) {
4301
+ if (state !== null && state.initialized)
4302
+ return;
4303
+ const connectionString = resolveConnectionString(options.connectionString);
4304
+ if (!connectionString) {
4305
+ state = {
4306
+ client: null,
4307
+ serviceName: options.serviceName,
4308
+ surface: options.surface,
4309
+ initialized: true
4310
+ };
4311
+ return;
4405
4312
  }
4406
- const authService = getAuthService();
4407
- const accessToken = await authService.getValidAccessToken();
4408
- if (accessToken) {
4409
- return { bearerToken: accessToken };
4313
+ try {
4314
+ AppInsights.setup(connectionString).setUseDiskRetryCaching(true).setDistributedTracingMode(AppInsights.DistributedTracingModes.AI_AND_W3C).setAutoCollectRequests(false).setAutoCollectPerformance(false, false).setAutoCollectExceptions(true).setAutoCollectDependencies(false).setAutoCollectConsole(false).setSendLiveMetrics(false);
4315
+ const client = AppInsights.defaultClient;
4316
+ const manifest = readReleaseManifest2();
4317
+ client.context.tags[client.context.keys.cloudRole] = options.serviceName;
4318
+ client.context.tags[client.context.keys.applicationVersion] = manifest.release;
4319
+ client.commonProperties = {
4320
+ ...client.commonProperties,
4321
+ ...buildCommonProperties(options.serviceName, options.surface)
4322
+ };
4323
+ AppInsights.start();
4324
+ state = {
4325
+ client,
4326
+ serviceName: options.serviceName,
4327
+ surface: options.surface,
4328
+ initialized: true
4329
+ };
4330
+ } catch (err) {
4331
+ console.warn("[muggle-telemetry] init failed; events will be dropped", {
4332
+ error: err.message
4333
+ });
4334
+ state = {
4335
+ client: null,
4336
+ serviceName: options.serviceName,
4337
+ surface: options.surface,
4338
+ initialized: true
4339
+ };
4410
4340
  }
4411
- return {};
4412
4341
  }
4413
- function toolRequiresAuth(toolName) {
4414
- const noAuthTools = [
4415
- // Auth tools (remote tools that don't require prior auth)
4416
- "muggle-remote-auth-status",
4417
- "muggle-remote-auth-login",
4418
- "muggle-remote-auth-poll",
4419
- "muggle-remote-auth-logout",
4420
- // Local project tools (no cloud)
4421
- "muggle-local-project-create",
4422
- "muggle-local-project-list",
4423
- "muggle-local-project-get",
4424
- "muggle-local-project-update",
4425
- "muggle-local-project-delete",
4426
- "muggle-local-use-case-save",
4427
- "muggle-local-use-case-list",
4428
- "muggle-local-use-case-get",
4429
- "muggle-local-use-case-update",
4430
- "muggle-local-use-case-delete",
4431
- "muggle-local-test-case-save",
4432
- "muggle-local-test-case-list",
4433
- "muggle-local-test-case-get",
4434
- "muggle-local-test-case-update",
4435
- "muggle-local-test-case-delete",
4436
- "muggle-local-test-script-save",
4437
- "muggle-local-test-script-list",
4438
- "muggle-local-test-script-get",
4439
- "muggle-local-test-script-delete",
4440
- "muggle-local-execute-test-generation",
4441
- "muggle-local-execute-replay",
4442
- "muggle-local-cancel-execution",
4443
- "muggle-local-check-status",
4444
- "muggle-local-list-sessions",
4445
- "muggle-local-cleanup-sessions",
4446
- "muggle-local-get-page-state",
4447
- "muggle-local-run-test",
4448
- "muggle-local-explore-page",
4449
- "muggle-local-execute-action",
4450
- "muggle-local-get-screenshot",
4451
- "muggle-local-run-result-list",
4452
- "muggle-local-run-result-get",
4453
- "muggle-local-secret-create",
4454
- "muggle-local-secret-list",
4455
- "muggle-local-secret-get",
4456
- "muggle-local-secret-update",
4457
- "muggle-local-secret-delete",
4458
- "muggle-local-workflow-file-create",
4459
- "muggle-local-workflow-file-list",
4460
- "muggle-local-workflow-file-list-available",
4461
- "muggle-local-workflow-file-get",
4462
- "muggle-local-workflow-file-update",
4463
- "muggle-local-workflow-file-delete"
4464
- ];
4465
- return !noAuthTools.includes(toolName);
4342
+ function getClient() {
4343
+ return state?.client ?? null;
4466
4344
  }
4467
- var ZOD_PATTERN_BY_STRING_FORMAT = /* @__PURE__ */ new Map([
4468
- ["uuid", z.toJSONSchema(z.uuid()).pattern],
4469
- ["email", z.toJSONSchema(z.email()).pattern]
4470
- ]);
4471
-
4472
- // packages/mcps/src/shared/tool-input-schema/tool-input-schema.ts
4473
- function buildToolInputJsonSchema(inputSchema) {
4474
- const { $schema: _dialect, ...schemaBody } = z.toJSONSchema(inputSchema);
4475
- return compactSchemaNode(schemaBody);
4345
+ function prefsFilePath() {
4346
+ return join(getDataDir3(), PREFS_FILENAME);
4476
4347
  }
4477
- function compactSchemaNode(node) {
4478
- if (Array.isArray(node)) {
4479
- return node.map(compactSchemaNode);
4480
- }
4481
- if (node === null || typeof node !== "object") {
4482
- return node;
4483
- }
4484
- const schemaNode = node;
4485
- const compactedNode = {};
4486
- for (const [keyword, value] of Object.entries(schemaNode)) {
4487
- if (!isRestatedKeyword(schemaNode, keyword, value)) {
4488
- compactedNode[keyword] = compactSchemaNode(value);
4348
+ function readPreferences() {
4349
+ const filePath = prefsFilePath();
4350
+ if (!existsSync(filePath))
4351
+ return {};
4352
+ try {
4353
+ const raw = readFileSync(filePath, "utf8");
4354
+ const parsed = JSON.parse(raw);
4355
+ if (typeof parsed === "object" && parsed !== null) {
4356
+ return parsed;
4489
4357
  }
4358
+ return {};
4359
+ } catch {
4360
+ return {};
4490
4361
  }
4491
- return compactedNode;
4492
4362
  }
4493
- function isRestatedKeyword(schemaNode, keyword, value) {
4494
- switch (keyword) {
4495
- case "pattern":
4496
- return typeof schemaNode.format === "string" && ZOD_PATTERN_BY_STRING_FORMAT.get(schemaNode.format) === value;
4497
- case "maximum":
4498
- return value === Number.MAX_SAFE_INTEGER;
4499
- case "minimum":
4500
- return value === Number.MIN_SAFE_INTEGER;
4501
- default:
4502
- return false;
4503
- }
4363
+ function writePreferences(prefs) {
4364
+ const filePath = prefsFilePath();
4365
+ mkdirSync(dirname(filePath), { recursive: true });
4366
+ writeFileSync(filePath, JSON.stringify(prefs, null, 2) + "\n", "utf8");
4367
+ }
4368
+ function updatePreference(key, value) {
4369
+ const prefs = readPreferences();
4370
+ prefs[key] = value;
4371
+ writePreferences(prefs);
4372
+ }
4373
+ function preferencesFileExists() {
4374
+ return existsSync(prefsFilePath());
4504
4375
  }
4505
4376
 
4506
- // packages/mcps/src/mcp/index.ts
4507
- var mcp_exports = {};
4508
- __export(mcp_exports, {
4509
- agents: () => agents_exports,
4510
- e2e: () => e2e_exports2,
4511
- localQa: () => local_exports2,
4512
- plugins: () => plugins_exports,
4513
- qa: () => e2e_exports2,
4514
- skills: () => skills_exports,
4515
- tools: () => tools_exports
4516
- });
4517
-
4518
- // packages/mcps/src/mcp/tools/index.ts
4519
- var tools_exports = {};
4520
- __export(tools_exports, {
4521
- e2e: () => e2e_exports,
4522
- localQa: () => local_exports,
4523
- qa: () => e2e_exports
4524
- });
4525
-
4526
- // packages/mcps/src/mcp/tools/e2e/index.ts
4527
- var e2e_exports = {};
4528
- __export(e2e_exports, {
4529
- allQaToolDefinitions: () => allQaToolDefinitions,
4530
- executeQaTool: () => executeQaTool,
4531
- getQaToolByName: () => getQaToolByName
4532
- });
4533
-
4534
- // packages/mcps/src/shared/dashboard-link/dashboard-link-constants.ts
4535
- var DASHBOARD_PROJECT_PAGE_SEGMENTS = {
4536
- ["project" /* Project */]: "",
4537
- ["test-cases" /* TestCases */]: "testcases",
4538
- ["scripts" /* Scripts */]: "scripts",
4539
- ["runs" /* Runs */]: "runs"
4540
- };
4541
- var SCRIPTS_MODAL_QUERY_KEY = "modal";
4542
- var SCRIPT_DETAILS_MODAL_VALUE = "script-details";
4543
- var SCRIPTS_MODAL_TEST_CASE_ID_KEY = "testCaseId";
4544
- var SCRIPTS_MODAL_ACTION_SCRIPT_ID_KEY = "actionScriptId";
4545
- var DASHBOARD_URL_FIELD = "dashboardUrl";
4377
+ function isTelemetryEnabled() {
4378
+ if (process.env[ENV_TELEMETRY_DISABLED] === "1")
4379
+ return false;
4380
+ const prefs = readPreferences();
4381
+ if (prefs.telemetryEnabled === false)
4382
+ return false;
4383
+ return true;
4384
+ }
4546
4385
 
4547
- // packages/mcps/src/shared/dashboard-link/dashboard-link.ts
4548
- function buildDashboardUrl(target, dashboardBaseUrl = getDashboardBaseUrl()) {
4549
- if (target.page === "projects" /* Projects */) {
4550
- return dashboardBaseUrl;
4551
- }
4552
- const projectUrl = `${dashboardBaseUrl}/${encodeURIComponent(target.projectId)}`;
4553
- if (target.page === "script-details" /* ScriptDetails */) {
4554
- const query = new URLSearchParams({
4555
- [SCRIPTS_MODAL_QUERY_KEY]: SCRIPT_DETAILS_MODAL_VALUE,
4556
- [SCRIPTS_MODAL_TEST_CASE_ID_KEY]: target.testCaseId
4386
+ function track(event) {
4387
+ if (!isTelemetryEnabled())
4388
+ return;
4389
+ const client = getClient();
4390
+ if (!client)
4391
+ return;
4392
+ try {
4393
+ client.trackEvent({
4394
+ name: event.name,
4395
+ properties: event.props
4557
4396
  });
4558
- if (target.actionScriptId) {
4559
- query.set(SCRIPTS_MODAL_ACTION_SCRIPT_ID_KEY, target.actionScriptId);
4560
- }
4561
- return `${projectUrl}/${DASHBOARD_PROJECT_PAGE_SEGMENTS["scripts" /* Scripts */]}?${query.toString()}`;
4562
- }
4563
- const segment = DASHBOARD_PROJECT_PAGE_SEGMENTS[target.page];
4564
- return segment ? `${projectUrl}/${segment}` : projectUrl;
4565
- }
4566
- function withDashboardUrl(toolOutput, dashboardUrl) {
4567
- if (toolOutput === null || typeof toolOutput !== "object" || Array.isArray(toolOutput)) {
4568
- return toolOutput;
4397
+ } catch {
4569
4398
  }
4570
- return { ...toolOutput, [DASHBOARD_URL_FIELD]: dashboardUrl };
4571
4399
  }
4572
- var INSTALL_ID_FILENAME = "install-id.json";
4573
- var cachedInstallId;
4574
- function installIdFilePath() {
4575
- return join(getDataDir(), INSTALL_ID_FILENAME);
4400
+
4401
+ var DISCLOSURE_COPY = `Muggle Test collects anonymous usage telemetry \u2014 which features you use, how long they take, and whether they succeed \u2014 to help us improve the product. We attach an opaque install ID, your account ID (when signed in), and your IP. We do not collect file contents, OS username, hostname, or file paths. To opt out, set telemetryEnabled to false in ~/.muggle-ai/preferences.json or run \`muggle preferences set telemetryEnabled false\`.`;
4402
+
4403
+ function getDisclosureCopy() {
4404
+ return DISCLOSURE_COPY;
4576
4405
  }
4577
- function generateAndPersist(filePath) {
4578
- const installId = randomUUID();
4579
- const contents = { installId };
4580
- mkdirSync(dirname(filePath), { recursive: true });
4581
- writeFileSync(filePath, JSON.stringify(contents, null, 2) + "\n", "utf8");
4582
- return installId;
4406
+ function hasShownDisclosure() {
4407
+ if (!preferencesFileExists())
4408
+ return false;
4409
+ const prefs = readPreferences();
4410
+ return typeof prefs.disclosureShownAt === "string" && prefs.disclosureShownAt.length > 0;
4583
4411
  }
4584
- function isValid(value) {
4585
- return typeof value === "object" && value !== null && typeof value.installId === "string" && value.installId.length > 0;
4412
+ function markDisclosureShown(now = /* @__PURE__ */ new Date()) {
4413
+ updatePreference("disclosureShownAt", now.toISOString());
4586
4414
  }
4587
- function getInstallId() {
4588
- if (cachedInstallId !== void 0) return cachedInstallId;
4589
- const filePath = installIdFilePath();
4590
- if (!existsSync(filePath)) {
4591
- cachedInstallId = generateAndPersist(filePath);
4592
- return cachedInstallId;
4593
- }
4594
- try {
4595
- const raw = readFileSync(filePath, "utf8");
4596
- const parsed = JSON.parse(raw);
4597
- if (isValid(parsed)) {
4598
- cachedInstallId = parsed.installId;
4599
- return cachedInstallId;
4600
- }
4601
- cachedInstallId = generateAndPersist(filePath);
4602
- return cachedInstallId;
4603
- } catch {
4604
- cachedInstallId = generateAndPersist(filePath);
4605
- return cachedInstallId;
4415
+
4416
+ var Trigger;
4417
+ (function(Trigger2) {
4418
+ Trigger2["UserSlash"] = "user-slash";
4419
+ Trigger2["ClaudeProactive"] = "claude-proactive";
4420
+ Trigger2["NestedSkill"] = "nested-skill";
4421
+ })(Trigger || (Trigger = {}));
4422
+ var Outcome;
4423
+ (function(Outcome2) {
4424
+ Outcome2["Success"] = "success";
4425
+ Outcome2["Error"] = "error";
4426
+ Outcome2["Cancelled"] = "cancelled";
4427
+ })(Outcome || (Outcome = {}));
4428
+ var ToolSurface;
4429
+ (function(ToolSurface2) {
4430
+ ToolSurface2["Local"] = "local";
4431
+ ToolSurface2["Remote"] = "remote";
4432
+ })(ToolSurface || (ToolSurface = {}));
4433
+ var Surface;
4434
+ (function(Surface2) {
4435
+ Surface2["McpLocal"] = "mcp-local";
4436
+ Surface2["McpRemote"] = "mcp-remote";
4437
+ Surface2["Skill"] = "skill";
4438
+ Surface2["Electron"] = "electron";
4439
+ })(Surface || (Surface = {}));
4440
+ var ServiceName;
4441
+ (function(ServiceName2) {
4442
+ ServiceName2["MuggleMcp"] = "muggle-mcp";
4443
+ ServiceName2["MuggleElectron"] = "muggle-electron";
4444
+ ServiceName2["MuggleSkill"] = "muggle-skill";
4445
+ })(ServiceName || (ServiceName = {}));
4446
+ var EventName;
4447
+ (function(EventName2) {
4448
+ EventName2["SkillInvoked"] = "skill.invoked";
4449
+ EventName2["SkillCompleted"] = "skill.completed";
4450
+ EventName2["McpToolInvoked"] = "mcp.tool.invoked";
4451
+ EventName2["McpToolCompleted"] = "mcp.tool.completed";
4452
+ EventName2["SystemStartup"] = "system.startup";
4453
+ EventName2["SystemOptOutChanged"] = "system.opt_out_changed";
4454
+ EventName2["SystemDisclosureShown"] = "system.disclosure_shown";
4455
+ })(EventName || (EventName = {}));
4456
+ var SkillTelemetryEmitInputSchema = z.object({
4457
+ skillName: z.string().min(1).describe("Name of the skill being invoked, e.g. 'muggle-test'."),
4458
+ trigger: z.nativeEnum(Trigger).default(Trigger.UserSlash).describe("Why this skill ran. Defaults to 'user-slash' (user typed /skill-name).")
4459
+ });
4460
+ var FailureEventType = /* @__PURE__ */ ((FailureEventType2) => {
4461
+ FailureEventType2["PreExecutionClassification"] = "pre-execution-classification";
4462
+ FailureEventType2["ReplayFailureClassified"] = "replay-failure-classified";
4463
+ FailureEventType2["ReplayFailureResolved"] = "replay-failure-resolved";
4464
+ FailureEventType2["RegenFailureClassified"] = "regen-failure-classified";
4465
+ FailureEventType2["RegenFailureResolved"] = "regen-failure-resolved";
4466
+ return FailureEventType2;
4467
+ })(FailureEventType || {});
4468
+ var WorkflowEventType = /* @__PURE__ */ ((WorkflowEventType2) => {
4469
+ WorkflowEventType2["MuggleDoCycle"] = "muggle-do:cycle";
4470
+ WorkflowEventType2["MuggleDoEscalation"] = "muggle-do:escalation";
4471
+ WorkflowEventType2["MuggleDoResolveReminder"] = "muggle-do:resolve-reminder";
4472
+ WorkflowEventType2["PrFollowupTick"] = "muggle-pr-followup:tick";
4473
+ WorkflowEventType2["PrFollowupBootstrap"] = "muggle-pr-followup:bootstrap";
4474
+ return WorkflowEventType2;
4475
+ })(WorkflowEventType || {});
4476
+ var EventTelemetryEmitInputSchema = z.object({
4477
+ eventType: z.union([z.nativeEnum(FailureEventType), z.nativeEnum(WorkflowEventType)]).describe(
4478
+ "What this event records: a failure-mode decision point (the pre-execution replay-vs-regen choice or a classify\u2192resolve pair) or a skill workflow event from the telemetry catalog."
4479
+ ),
4480
+ skillName: z.string().min(1).describe("Skill that emitted this event (e.g. 'muggle-test', 'muggle-test-feature-local')."),
4481
+ aiClassification: z.string().optional().describe(
4482
+ "What the AI classified the situation as. pre-execution: 'replay' or 'regen'. replay-failure: 'infra' | 'stale-script' | 'product-defect'. regen-failure: 'transient' | 'infra' | 'agent-course' | 'product-uxux'."
4483
+ ),
4484
+ aiSuggestion: z.string().optional().describe(
4485
+ "What the AI suggested the user do. Examples: 'regenerate', 'report-bug', 'muggle-feedback', 'retry', 'wait-and-share'."
4486
+ ),
4487
+ userAction: z.string().optional().describe(
4488
+ "What the user actually picked (only set on *-resolved events). Compare against aiSuggestion to measure classification accuracy."
4489
+ ),
4490
+ runId: z.string().optional().describe("Anchor: local run ID for the affected execution."),
4491
+ testCaseId: z.string().optional().describe("Anchor: cloud test case ID."),
4492
+ projectId: z.string().optional().describe("Anchor: cloud project ID."),
4493
+ signals: z.array(z.string()).optional().describe(
4494
+ "Signals that drove the classification, e.g. ['element-not-found', 'selector-timeout', 'electron-exit-26', 'goal-not-achievable']. Used to refine the rules later."
4495
+ ),
4496
+ metadata: z.record(z.string(), z.unknown()).optional().describe("Free-form additional context (e.g. error excerpt). A workflow event's catalog payload goes here.")
4497
+ });
4498
+
4499
+ // packages/mcps/src/mcp/local/services/telemetry-event-service.ts
4500
+ function recordTelemetryEvent(telemetryEvent) {
4501
+ if (isWorkflowEventType(telemetryEvent.eventType)) {
4502
+ appendWorkflowEvent({
4503
+ eventType: telemetryEvent.eventType,
4504
+ skillName: telemetryEvent.skillName,
4505
+ metadata: telemetryEvent.metadata
4506
+ });
4507
+ return;
4606
4508
  }
4509
+ appendFailureEvent({
4510
+ eventType: telemetryEvent.eventType,
4511
+ skillName: telemetryEvent.skillName,
4512
+ aiClassification: telemetryEvent.aiClassification,
4513
+ aiSuggestion: telemetryEvent.aiSuggestion,
4514
+ userAction: telemetryEvent.userAction,
4515
+ runId: telemetryEvent.runId,
4516
+ testCaseId: telemetryEvent.testCaseId,
4517
+ projectId: telemetryEvent.projectId,
4518
+ signals: telemetryEvent.signals,
4519
+ metadata: telemetryEvent.metadata
4520
+ });
4521
+ }
4522
+ function isWorkflowEventType(eventType) {
4523
+ return Object.values(WorkflowEventType).includes(eventType);
4607
4524
  }
4608
4525
 
4609
- // packages/mcps/src/shared/register.ts
4610
- var CONFLICT_STATUS = 409;
4611
- var THROTTLED_STATUS = 429;
4612
- async function registerAccount(email, userProvidedPassword) {
4613
- const logger7 = getLogger();
4614
- const config = getConfig();
4615
- const registerUrl = `${config.e2e.promptServiceBaseUrl}/v1/public/auth/register`;
4526
+ // packages/mcps/src/shared/auth.ts
4527
+ var logger6 = getLogger();
4528
+ async function startDeviceCodeFlow(config, options) {
4529
+ const deviceCodeUrl = `https://${config.domain}/oauth/device/code`;
4616
4530
  try {
4531
+ logger6.info("[Auth] Starting device code flow", {
4532
+ domain: config.domain,
4533
+ clientId: config.clientId
4534
+ });
4617
4535
  const response = await axios.post(
4618
- registerUrl,
4536
+ deviceCodeUrl,
4537
+ new URLSearchParams({
4538
+ client_id: config.clientId,
4539
+ scope: config.scope,
4540
+ audience: config.audience
4541
+ }).toString(),
4619
4542
  {
4620
- email,
4621
- password: userProvidedPassword,
4622
- installId: getInstallId()
4623
- },
4624
- { headers: { "Content-Type": "application/json" } }
4543
+ headers: {
4544
+ "Content-Type": "application/x-www-form-urlencoded"
4545
+ }
4546
+ }
4625
4547
  );
4626
- const created = response.data;
4627
- saveApiKey({ apiKey: created.apiKey, apiKeyId: created.userId });
4628
- logger7.info("[Register] Account created and credential stored", {
4629
- userId: created.userId,
4630
- plan: created.plan
4548
+ const data = response.data;
4549
+ logger6.info("[Auth] Device code flow started successfully", {
4550
+ userCode: data.user_code,
4551
+ expiresIn: data.expires_in
4552
+ });
4553
+ let browserUrl = data.verification_uri_complete;
4554
+ if (options?.forceNewSession) {
4555
+ const logoutUrl = new URL(`https://${config.domain}/v2/logout`);
4556
+ logoutUrl.searchParams.set("client_id", config.clientId);
4557
+ logoutUrl.searchParams.set("returnTo", data.verification_uri_complete);
4558
+ browserUrl = logoutUrl.toString();
4559
+ logger6.info("[Auth] Force new session: opening logout-redirect URL");
4560
+ }
4561
+ const browserOpenResult = await openBrowserUrl({
4562
+ url: browserUrl
4631
4563
  });
4564
+ if (browserOpenResult.opened) {
4565
+ logger6.info("[Auth] Browser opened for device code login");
4566
+ } else {
4567
+ logger6.warn("[Auth] Failed to open browser", {
4568
+ error: browserOpenResult.error,
4569
+ verificationUriComplete: data.verification_uri_complete
4570
+ });
4571
+ }
4632
4572
  return {
4633
- outcome: "created" /* Created */,
4634
- userId: created.userId,
4635
- email: created.email,
4636
- plan: created.plan,
4637
- emailVerified: created.emailVerified,
4638
- tokensGranted: created.tokensGranted,
4639
- tokensOnVerification: created.tokensOnVerification,
4640
- credentialStored: true,
4641
- message: `Account created on the ${created.plan} plan and the API key stored \u2014 remote tools will use it automatically. ${created.tokensGranted.toLocaleString()} tokens are available now. Verifying ${created.email} upgrades the account to the Starter package \u2014 free and permanent \u2014 and raises that to ${created.tokensOnVerification.toLocaleString()}.`
4573
+ deviceCode: data.device_code,
4574
+ userCode: data.user_code,
4575
+ verificationUri: data.verification_uri,
4576
+ verificationUriComplete: data.verification_uri_complete,
4577
+ expiresIn: data.expires_in,
4578
+ interval: data.interval || 5,
4579
+ browserOpened: browserOpenResult.opened,
4580
+ browserOpenError: browserOpenResult.error
4642
4581
  };
4643
4582
  } catch (error) {
4644
- const status = axios.isAxiosError(error) ? error.response?.status : void 0;
4645
- if (status === CONFLICT_STATUS) {
4646
- return {
4647
- outcome: "already-registered" /* AlreadyRegistered */,
4648
- message: "An account already exists for this email. Use muggle-remote-auth-login to sign in instead."
4649
- };
4650
- }
4651
- if (status === THROTTLED_STATUS) {
4652
- const retryAfterSeconds = axios.isAxiosError(error) ? error.response?.data?.retryAfterSeconds : void 0;
4653
- return {
4654
- outcome: "throttled" /* Throttled */,
4655
- retryAfterSeconds,
4656
- message: retryAfterSeconds ? `Too many registrations from this machine. Try again in ${retryAfterSeconds} seconds.` : "Too many registrations from this machine. Try again later."
4657
- };
4583
+ if (error instanceof AxiosError) {
4584
+ logger6.error("[Auth] Failed to start device code flow", {
4585
+ status: error.response?.status,
4586
+ data: error.response?.data
4587
+ });
4588
+ throw new Error(
4589
+ `Failed to start device code flow: ${error.response?.data?.error_description || error.message}`,
4590
+ { cause: error }
4591
+ );
4658
4592
  }
4659
- logger7.error("[Register] Registration failed", {
4660
- error: error instanceof Error ? error.message : String(error)
4661
- });
4662
4593
  throw error;
4663
4594
  }
4664
4595
  }
4665
-
4666
- var ENV_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING";
4667
- var ENV_VITE_CONNECTION_STRING = "VITE_APPLICATIONINSIGHTS_CONNECTION_STRING";
4668
- var ENV_TELEMETRY_DISABLED = "MUGGLE_TELEMETRY_DISABLED";
4669
-
4670
- var DATA_DIR_NAME2 = ".muggle-ai";
4671
- var INSTALL_ID_FILENAME2 = "install-id.json";
4672
- var PREFS_FILENAME = "preferences.json";
4673
- var OAUTH_SESSION_FILENAME = "oauth-session.json";
4674
- var RELEASE_MANIFEST_FILENAME = "release-manifest.json";
4675
- function getDataDir3() {
4676
- return path15.join(os4.homedir(), DATA_DIR_NAME2);
4677
- }
4678
-
4679
- var cachedInstallId2;
4680
- function installIdFilePath2() {
4681
- return join(getDataDir3(), INSTALL_ID_FILENAME2);
4682
- }
4683
- function generateAndPersist2(filePath) {
4684
- const installId = randomUUID();
4685
- const contents = { installId };
4686
- mkdirSync(dirname(filePath), { recursive: true });
4687
- writeFileSync(filePath, JSON.stringify(contents, null, 2) + "\n", "utf8");
4688
- return installId;
4689
- }
4690
- function isValid2(value) {
4691
- return typeof value === "object" && value !== null && typeof value.installId === "string" && value.installId.length > 0;
4692
- }
4693
- function getInstallId2() {
4694
- if (cachedInstallId2 !== void 0)
4695
- return cachedInstallId2;
4696
- const filePath = installIdFilePath2();
4697
- if (!existsSync(filePath)) {
4698
- cachedInstallId2 = generateAndPersist2(filePath);
4699
- return cachedInstallId2;
4700
- }
4596
+ async function pollDeviceCode(config, deviceCode) {
4597
+ const tokenUrl = `https://${config.domain}/oauth/token`;
4701
4598
  try {
4702
- const raw = readFileSync(filePath, "utf8");
4703
- const parsed = JSON.parse(raw);
4704
- if (isValid2(parsed)) {
4705
- cachedInstallId2 = parsed.installId;
4706
- return cachedInstallId2;
4599
+ const response = await axios.post(
4600
+ tokenUrl,
4601
+ new URLSearchParams({
4602
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
4603
+ device_code: deviceCode,
4604
+ client_id: config.clientId
4605
+ }).toString(),
4606
+ {
4607
+ headers: {
4608
+ "Content-Type": "application/x-www-form-urlencoded"
4609
+ }
4610
+ }
4611
+ );
4612
+ logger6.info("[Auth] Authorization successful");
4613
+ return {
4614
+ status: "authorized",
4615
+ accessToken: response.data.access_token,
4616
+ tokenType: response.data.token_type,
4617
+ expiresIn: response.data.expires_in
4618
+ };
4619
+ } catch (error) {
4620
+ if (error instanceof AxiosError && error.response) {
4621
+ const data = error.response.data;
4622
+ const errorCode = data.error;
4623
+ if (errorCode === "authorization_pending") {
4624
+ return {
4625
+ status: "authorization_pending",
4626
+ error: errorCode,
4627
+ errorDescription: data.error_description || "User has not yet authorized"
4628
+ };
4629
+ }
4630
+ if (errorCode === "slow_down") {
4631
+ return {
4632
+ status: "slow_down",
4633
+ error: errorCode,
4634
+ errorDescription: data.error_description || "Too many requests, slow down"
4635
+ };
4636
+ }
4637
+ if (errorCode === "expired_token") {
4638
+ return {
4639
+ status: "expired_token",
4640
+ error: errorCode,
4641
+ errorDescription: data.error_description || "Device code expired, please restart flow"
4642
+ };
4643
+ }
4644
+ if (errorCode === "access_denied") {
4645
+ return {
4646
+ status: "access_denied",
4647
+ error: errorCode,
4648
+ errorDescription: data.error_description || "User denied access"
4649
+ };
4650
+ }
4651
+ logger6.error("[Auth] Unexpected error during poll", {
4652
+ status: error.response.status,
4653
+ error: errorCode,
4654
+ description: data.error_description
4655
+ });
4656
+ throw new Error(
4657
+ `Device code poll failed: ${data.error_description || data.error || "Unknown error"}`,
4658
+ { cause: error }
4659
+ );
4707
4660
  }
4708
- cachedInstallId2 = generateAndPersist2(filePath);
4709
- return cachedInstallId2;
4710
- } catch {
4711
- cachedInstallId2 = generateAndPersist2(filePath);
4712
- return cachedInstallId2;
4713
- }
4714
- }
4715
-
4716
- var DEV_MANIFEST2 = {
4717
- release: "dev",
4718
- buildId: "dev",
4719
- commitSha: "dev",
4720
- buildTime: "1970-01-01T00:00:00Z",
4721
- serviceName: "muggle-ai-telemetry"
4722
- };
4723
-
4724
- var MANIFEST_PATH2 = (() => {
4725
- try {
4726
- return join(dirname(fileURLToPath(import.meta.url)), RELEASE_MANIFEST_FILENAME);
4727
- } catch {
4728
- return RELEASE_MANIFEST_FILENAME;
4661
+ throw error;
4729
4662
  }
4730
- })();
4731
- var cachedManifest2;
4732
- function isValid3(value) {
4733
- if (typeof value !== "object" || value === null)
4734
- return false;
4735
- const m = value;
4736
- return typeof m.release === "string" && typeof m.buildId === "string" && typeof m.commitSha === "string" && typeof m.buildTime === "string" && typeof m.serviceName === "string";
4737
4663
  }
4738
- function readReleaseManifest2() {
4739
- if (cachedManifest2 !== void 0)
4740
- return cachedManifest2;
4741
- const path21 = MANIFEST_PATH2;
4664
+ async function createApiKeyWithToken(accessToken, keyName, expiry = "90d") {
4665
+ const config = getConfig();
4666
+ const apiKeyUrl = `${config.e2e.promptServiceBaseUrl}/v1/protected/api-keys`;
4742
4667
  try {
4743
- const raw = readFileSync(path21, "utf8");
4744
- const parsed = JSON.parse(raw);
4745
- cachedManifest2 = isValid3(parsed) ? parsed : DEV_MANIFEST2;
4746
- return cachedManifest2;
4747
- } catch (err) {
4748
- const code = err.code;
4749
- if (code !== "ENOENT") {
4750
- console.warn("release-manifest: unexpected read error, using DEV fallback", {
4751
- error: err.message
4668
+ logger6.info("[Auth] Creating API key", {
4669
+ keyName,
4670
+ expiry
4671
+ });
4672
+ const response = await axios.post(
4673
+ apiKeyUrl,
4674
+ {
4675
+ name: keyName || "MCP Auto-Generated",
4676
+ expiry
4677
+ },
4678
+ {
4679
+ headers: {
4680
+ Authorization: `Bearer ${accessToken}`,
4681
+ "Content-Type": "application/json"
4682
+ }
4683
+ }
4684
+ );
4685
+ logger6.info("[Auth] API key created successfully", {
4686
+ keyId: response.data.id
4687
+ });
4688
+ return response.data;
4689
+ } catch (error) {
4690
+ if (error instanceof AxiosError) {
4691
+ logger6.error("[Auth] Failed to create API key", {
4692
+ status: error.response?.status,
4693
+ data: error.response?.data
4752
4694
  });
4695
+ throw new Error(
4696
+ `Failed to create API key: ${error.response?.data?.message || error.message}`,
4697
+ { cause: error }
4698
+ );
4753
4699
  }
4754
- cachedManifest2 = DEV_MANIFEST2;
4755
- return cachedManifest2;
4700
+ throw error;
4756
4701
  }
4757
4702
  }
4758
- function readUserId() {
4759
- const filePath = join(getDataDir3(), OAUTH_SESSION_FILENAME);
4760
- if (!existsSync(filePath))
4761
- return void 0;
4703
+ async function performLogin(keyName, keyExpiry = "90d", timeoutMs = 12e4) {
4704
+ const authService = getAuthService();
4762
4705
  try {
4763
- const raw = readFileSync(filePath, "utf8");
4764
- const parsed = JSON.parse(raw);
4765
- if (typeof parsed.userId === "string" && parsed.userId.length > 0) {
4766
- return parsed.userId;
4706
+ const authDeviceCodeResponse = await authService.startDeviceCodeFlow();
4707
+ const deviceCodeResponse = {
4708
+ deviceCode: authDeviceCodeResponse.deviceCode,
4709
+ userCode: authDeviceCodeResponse.userCode,
4710
+ verificationUri: authDeviceCodeResponse.verificationUri,
4711
+ verificationUriComplete: authDeviceCodeResponse.verificationUriComplete,
4712
+ expiresIn: authDeviceCodeResponse.expiresIn,
4713
+ interval: authDeviceCodeResponse.interval,
4714
+ browserOpened: authDeviceCodeResponse.browserOpened ?? false,
4715
+ browserOpenError: authDeviceCodeResponse.browserOpenError
4716
+ };
4717
+ const pollResult = await authService.waitForDeviceCodeAuthorization({
4718
+ deviceCode: deviceCodeResponse.deviceCode,
4719
+ intervalSeconds: deviceCodeResponse.interval,
4720
+ timeoutMs
4721
+ });
4722
+ if (pollResult.status === "complete") {
4723
+ const storedAuth = authService.loadStoredAuth();
4724
+ const credentials = {
4725
+ accessToken: storedAuth?.accessToken ?? "",
4726
+ expiresAt: storedAuth?.expiresAt ?? "",
4727
+ email: storedAuth?.email,
4728
+ userId: storedAuth?.userId
4729
+ };
4730
+ if (keyName && storedAuth?.accessToken) {
4731
+ logger6.info("[Auth] Creating API key as explicitly requested", {
4732
+ keyName
4733
+ });
4734
+ const apiKeyResult = await createApiKeyWithToken(
4735
+ storedAuth.accessToken,
4736
+ keyName,
4737
+ keyExpiry
4738
+ );
4739
+ credentials.apiKey = apiKeyResult.key;
4740
+ credentials.apiKeyId = apiKeyResult.id;
4741
+ saveApiKeyData(credentials);
4742
+ }
4743
+ return {
4744
+ success: true,
4745
+ deviceCodeResponse,
4746
+ credentials
4747
+ };
4767
4748
  }
4768
- return void 0;
4769
- } catch {
4770
- return void 0;
4749
+ if (pollResult.status === "expired") {
4750
+ return {
4751
+ success: false,
4752
+ deviceCodeResponse,
4753
+ error: "Device code expired. Please try again."
4754
+ };
4755
+ }
4756
+ if (pollResult.status === "error") {
4757
+ return {
4758
+ success: false,
4759
+ deviceCodeResponse,
4760
+ error: pollResult.error ?? pollResult.message
4761
+ };
4762
+ }
4763
+ return {
4764
+ success: false,
4765
+ deviceCodeResponse,
4766
+ error: pollResult.message
4767
+ };
4768
+ } catch (error) {
4769
+ return {
4770
+ success: false,
4771
+ error: error instanceof Error ? error.message : String(error)
4772
+ };
4771
4773
  }
4772
4774
  }
4775
+ function performLogout() {
4776
+ const authService = getAuthService();
4777
+ authService.logout();
4778
+ deleteApiKeyData();
4779
+ logger6.info("[Auth] Logged out successfully");
4780
+ }
4781
+ function getCallerCredentials() {
4782
+ const apiKeyData = getValidApiKeyData();
4783
+ if (apiKeyData?.apiKey) {
4784
+ return { apiKey: apiKeyData.apiKey };
4785
+ }
4786
+ const authService = getAuthService();
4787
+ const accessToken = authService.getAccessToken();
4788
+ if (accessToken) {
4789
+ return { bearerToken: accessToken };
4790
+ }
4791
+ return {};
4792
+ }
4793
+ async function getCallerCredentialsAsync() {
4794
+ const apiKeyData = getValidApiKeyData();
4795
+ if (apiKeyData?.apiKey) {
4796
+ return { apiKey: apiKeyData.apiKey };
4797
+ }
4798
+ const authService = getAuthService();
4799
+ const accessToken = await authService.getValidAccessToken();
4800
+ if (accessToken) {
4801
+ return { bearerToken: accessToken };
4802
+ }
4803
+ return {};
4804
+ }
4805
+ function toolRequiresAuth(toolName) {
4806
+ const noAuthTools = [
4807
+ // Auth tools (remote tools that don't require prior auth)
4808
+ "muggle-remote-auth-status",
4809
+ "muggle-remote-auth-login",
4810
+ "muggle-remote-auth-poll",
4811
+ "muggle-remote-auth-logout",
4812
+ // Local project tools (no cloud)
4813
+ "muggle-local-project-create",
4814
+ "muggle-local-project-list",
4815
+ "muggle-local-project-get",
4816
+ "muggle-local-project-update",
4817
+ "muggle-local-project-delete",
4818
+ "muggle-local-use-case-save",
4819
+ "muggle-local-use-case-list",
4820
+ "muggle-local-use-case-get",
4821
+ "muggle-local-use-case-update",
4822
+ "muggle-local-use-case-delete",
4823
+ "muggle-local-test-case-save",
4824
+ "muggle-local-test-case-list",
4825
+ "muggle-local-test-case-get",
4826
+ "muggle-local-test-case-update",
4827
+ "muggle-local-test-case-delete",
4828
+ "muggle-local-test-script-save",
4829
+ "muggle-local-test-script-list",
4830
+ "muggle-local-test-script-get",
4831
+ "muggle-local-test-script-delete",
4832
+ "muggle-local-execute-test-generation",
4833
+ "muggle-local-execute-replay",
4834
+ "muggle-local-cancel-execution",
4835
+ "muggle-local-check-status",
4836
+ "muggle-local-list-sessions",
4837
+ "muggle-local-cleanup-sessions",
4838
+ "muggle-local-get-page-state",
4839
+ "muggle-local-run-test",
4840
+ "muggle-local-explore-page",
4841
+ "muggle-local-execute-action",
4842
+ "muggle-local-get-screenshot",
4843
+ "muggle-local-run-result-list",
4844
+ "muggle-local-run-result-get",
4845
+ "muggle-local-secret-create",
4846
+ "muggle-local-secret-list",
4847
+ "muggle-local-secret-get",
4848
+ "muggle-local-secret-update",
4849
+ "muggle-local-secret-delete",
4850
+ "muggle-local-workflow-file-create",
4851
+ "muggle-local-workflow-file-list",
4852
+ "muggle-local-workflow-file-list-available",
4853
+ "muggle-local-workflow-file-get",
4854
+ "muggle-local-workflow-file-update",
4855
+ "muggle-local-workflow-file-delete"
4856
+ ];
4857
+ return !noAuthTools.includes(toolName);
4858
+ }
4859
+ var ZOD_PATTERN_BY_STRING_FORMAT = /* @__PURE__ */ new Map([
4860
+ ["uuid", z.toJSONSchema(z.uuid()).pattern],
4861
+ ["email", z.toJSONSchema(z.email()).pattern]
4862
+ ]);
4773
4863
 
4774
- var state = null;
4775
- function resolveConnectionString(explicit) {
4776
- if (explicit && explicit.length > 0)
4777
- return explicit;
4778
- return process.env[ENV_CONNECTION_STRING] ?? process.env[ENV_VITE_CONNECTION_STRING] ?? void 0;
4864
+ // packages/mcps/src/shared/tool-input-schema/tool-input-schema.ts
4865
+ function buildToolInputJsonSchema(inputSchema) {
4866
+ const { $schema: _dialect, ...schemaBody } = z.toJSONSchema(inputSchema);
4867
+ return compactSchemaNode(schemaBody);
4779
4868
  }
4780
- function buildCommonProperties(serviceName, surface) {
4781
- const manifest = readReleaseManifest2();
4782
- const props = {
4783
- source: "client",
4784
- serviceName,
4785
- surface,
4786
- release: manifest.release,
4787
- buildId: manifest.buildId,
4788
- commitSha: manifest.commitSha,
4789
- buildTime: manifest.buildTime,
4790
- installId: getInstallId2(),
4791
- nodeVersion: process.version,
4792
- platform: process.platform
4793
- };
4794
- const userId = readUserId();
4795
- if (userId !== void 0)
4796
- props.userId = userId;
4797
- return props;
4869
+ function compactSchemaNode(node) {
4870
+ if (Array.isArray(node)) {
4871
+ return node.map(compactSchemaNode);
4872
+ }
4873
+ if (node === null || typeof node !== "object") {
4874
+ return node;
4875
+ }
4876
+ const schemaNode = node;
4877
+ const compactedNode = {};
4878
+ for (const [keyword, value] of Object.entries(schemaNode)) {
4879
+ if (!isRestatedKeyword(schemaNode, keyword, value)) {
4880
+ compactedNode[keyword] = compactSchemaNode(value);
4881
+ }
4882
+ }
4883
+ return compactedNode;
4798
4884
  }
4799
- function initTelemetry(options) {
4800
- if (state !== null && state.initialized)
4801
- return;
4802
- const connectionString = resolveConnectionString(options.connectionString);
4803
- if (!connectionString) {
4804
- state = {
4805
- client: null,
4806
- serviceName: options.serviceName,
4807
- surface: options.surface,
4808
- initialized: true
4809
- };
4810
- return;
4885
+ function isRestatedKeyword(schemaNode, keyword, value) {
4886
+ switch (keyword) {
4887
+ case "pattern":
4888
+ return typeof schemaNode.format === "string" && ZOD_PATTERN_BY_STRING_FORMAT.get(schemaNode.format) === value;
4889
+ case "maximum":
4890
+ return value === Number.MAX_SAFE_INTEGER;
4891
+ case "minimum":
4892
+ return value === Number.MIN_SAFE_INTEGER;
4893
+ default:
4894
+ return false;
4811
4895
  }
4812
- try {
4813
- AppInsights.setup(connectionString).setUseDiskRetryCaching(true).setDistributedTracingMode(AppInsights.DistributedTracingModes.AI_AND_W3C).setAutoCollectRequests(false).setAutoCollectPerformance(false, false).setAutoCollectExceptions(true).setAutoCollectDependencies(false).setAutoCollectConsole(false).setSendLiveMetrics(false);
4814
- const client = AppInsights.defaultClient;
4815
- const manifest = readReleaseManifest2();
4816
- client.context.tags[client.context.keys.cloudRole] = options.serviceName;
4817
- client.context.tags[client.context.keys.applicationVersion] = manifest.release;
4818
- client.commonProperties = {
4819
- ...client.commonProperties,
4820
- ...buildCommonProperties(options.serviceName, options.surface)
4821
- };
4822
- AppInsights.start();
4823
- state = {
4824
- client,
4825
- serviceName: options.serviceName,
4826
- surface: options.surface,
4827
- initialized: true
4828
- };
4829
- } catch (err) {
4830
- console.warn("[muggle-telemetry] init failed; events will be dropped", {
4831
- error: err.message
4896
+ }
4897
+
4898
+ // packages/mcps/src/mcp/index.ts
4899
+ var mcp_exports = {};
4900
+ __export(mcp_exports, {
4901
+ agents: () => agents_exports,
4902
+ e2e: () => e2e_exports2,
4903
+ localQa: () => local_exports2,
4904
+ plugins: () => plugins_exports,
4905
+ qa: () => e2e_exports2,
4906
+ skills: () => skills_exports,
4907
+ tools: () => tools_exports
4908
+ });
4909
+
4910
+ // packages/mcps/src/mcp/tools/index.ts
4911
+ var tools_exports = {};
4912
+ __export(tools_exports, {
4913
+ e2e: () => e2e_exports,
4914
+ localQa: () => local_exports,
4915
+ qa: () => e2e_exports
4916
+ });
4917
+
4918
+ // packages/mcps/src/mcp/tools/e2e/index.ts
4919
+ var e2e_exports = {};
4920
+ __export(e2e_exports, {
4921
+ allQaToolDefinitions: () => allQaToolDefinitions,
4922
+ executeQaTool: () => executeQaTool,
4923
+ getQaToolByName: () => getQaToolByName
4924
+ });
4925
+
4926
+ // packages/mcps/src/shared/dashboard-link/dashboard-link-constants.ts
4927
+ var DASHBOARD_PROJECT_PAGE_SEGMENTS = {
4928
+ ["project" /* Project */]: "",
4929
+ ["test-cases" /* TestCases */]: "testcases",
4930
+ ["scripts" /* Scripts */]: "scripts",
4931
+ ["runs" /* Runs */]: "runs"
4932
+ };
4933
+ var SCRIPTS_MODAL_QUERY_KEY = "modal";
4934
+ var SCRIPT_DETAILS_MODAL_VALUE = "script-details";
4935
+ var SCRIPTS_MODAL_TEST_CASE_ID_KEY = "testCaseId";
4936
+ var SCRIPTS_MODAL_ACTION_SCRIPT_ID_KEY = "actionScriptId";
4937
+ var DASHBOARD_URL_FIELD = "dashboardUrl";
4938
+
4939
+ // packages/mcps/src/shared/dashboard-link/dashboard-link.ts
4940
+ function buildDashboardUrl(target, dashboardBaseUrl = getDashboardBaseUrl()) {
4941
+ if (target.page === "projects" /* Projects */) {
4942
+ return dashboardBaseUrl;
4943
+ }
4944
+ const projectUrl = `${dashboardBaseUrl}/${encodeURIComponent(target.projectId)}`;
4945
+ if (target.page === "script-details" /* ScriptDetails */) {
4946
+ const query = new URLSearchParams({
4947
+ [SCRIPTS_MODAL_QUERY_KEY]: SCRIPT_DETAILS_MODAL_VALUE,
4948
+ [SCRIPTS_MODAL_TEST_CASE_ID_KEY]: target.testCaseId
4832
4949
  });
4833
- state = {
4834
- client: null,
4835
- serviceName: options.serviceName,
4836
- surface: options.surface,
4837
- initialized: true
4838
- };
4950
+ if (target.actionScriptId) {
4951
+ query.set(SCRIPTS_MODAL_ACTION_SCRIPT_ID_KEY, target.actionScriptId);
4952
+ }
4953
+ return `${projectUrl}/${DASHBOARD_PROJECT_PAGE_SEGMENTS["scripts" /* Scripts */]}?${query.toString()}`;
4839
4954
  }
4955
+ const segment = DASHBOARD_PROJECT_PAGE_SEGMENTS[target.page];
4956
+ return segment ? `${projectUrl}/${segment}` : projectUrl;
4840
4957
  }
4841
- function getClient() {
4842
- return state?.client ?? null;
4958
+ function withDashboardUrl(toolOutput, dashboardUrl) {
4959
+ if (toolOutput === null || typeof toolOutput !== "object" || Array.isArray(toolOutput)) {
4960
+ return toolOutput;
4961
+ }
4962
+ return { ...toolOutput, [DASHBOARD_URL_FIELD]: dashboardUrl };
4843
4963
  }
4844
- function prefsFilePath() {
4845
- return join(getDataDir3(), PREFS_FILENAME);
4964
+ var INSTALL_ID_FILENAME2 = "install-id.json";
4965
+ var cachedInstallId2;
4966
+ function installIdFilePath2() {
4967
+ return join(getDataDir(), INSTALL_ID_FILENAME2);
4846
4968
  }
4847
- function readPreferences() {
4848
- const filePath = prefsFilePath();
4849
- if (!existsSync(filePath))
4850
- return {};
4969
+ function generateAndPersist2(filePath) {
4970
+ const installId = randomUUID();
4971
+ const contents = { installId };
4972
+ mkdirSync(dirname(filePath), { recursive: true });
4973
+ writeFileSync(filePath, JSON.stringify(contents, null, 2) + "\n", "utf8");
4974
+ return installId;
4975
+ }
4976
+ function isValid3(value) {
4977
+ return typeof value === "object" && value !== null && typeof value.installId === "string" && value.installId.length > 0;
4978
+ }
4979
+ function getInstallId2() {
4980
+ if (cachedInstallId2 !== void 0) return cachedInstallId2;
4981
+ const filePath = installIdFilePath2();
4982
+ if (!existsSync(filePath)) {
4983
+ cachedInstallId2 = generateAndPersist2(filePath);
4984
+ return cachedInstallId2;
4985
+ }
4851
4986
  try {
4852
4987
  const raw = readFileSync(filePath, "utf8");
4853
4988
  const parsed = JSON.parse(raw);
4854
- if (typeof parsed === "object" && parsed !== null) {
4855
- return parsed;
4989
+ if (isValid3(parsed)) {
4990
+ cachedInstallId2 = parsed.installId;
4991
+ return cachedInstallId2;
4856
4992
  }
4857
- return {};
4993
+ cachedInstallId2 = generateAndPersist2(filePath);
4994
+ return cachedInstallId2;
4858
4995
  } catch {
4859
- return {};
4996
+ cachedInstallId2 = generateAndPersist2(filePath);
4997
+ return cachedInstallId2;
4860
4998
  }
4861
4999
  }
4862
- function writePreferences(prefs) {
4863
- const filePath = prefsFilePath();
4864
- mkdirSync(dirname(filePath), { recursive: true });
4865
- writeFileSync(filePath, JSON.stringify(prefs, null, 2) + "\n", "utf8");
4866
- }
4867
- function updatePreference(key, value) {
4868
- const prefs = readPreferences();
4869
- prefs[key] = value;
4870
- writePreferences(prefs);
4871
- }
4872
- function preferencesFileExists() {
4873
- return existsSync(prefsFilePath());
4874
- }
4875
-
4876
- function isTelemetryEnabled() {
4877
- if (process.env[ENV_TELEMETRY_DISABLED] === "1")
4878
- return false;
4879
- const prefs = readPreferences();
4880
- if (prefs.telemetryEnabled === false)
4881
- return false;
4882
- return true;
4883
- }
4884
5000
 
4885
- function track(event) {
4886
- if (!isTelemetryEnabled())
4887
- return;
4888
- const client = getClient();
4889
- if (!client)
4890
- return;
5001
+ // packages/mcps/src/shared/register.ts
5002
+ var CONFLICT_STATUS = 409;
5003
+ var THROTTLED_STATUS = 429;
5004
+ async function registerAccount(email, userProvidedPassword) {
5005
+ const logger7 = getLogger();
5006
+ const config = getConfig();
5007
+ const registerUrl = `${config.e2e.promptServiceBaseUrl}/v1/public/auth/register`;
4891
5008
  try {
4892
- client.trackEvent({
4893
- name: event.name,
4894
- properties: event.props
5009
+ const response = await axios.post(
5010
+ registerUrl,
5011
+ {
5012
+ email,
5013
+ password: userProvidedPassword,
5014
+ installId: getInstallId2()
5015
+ },
5016
+ { headers: { "Content-Type": "application/json" } }
5017
+ );
5018
+ const created = response.data;
5019
+ saveApiKey({ apiKey: created.apiKey, apiKeyId: created.userId });
5020
+ logger7.info("[Register] Account created and credential stored", {
5021
+ userId: created.userId,
5022
+ plan: created.plan
4895
5023
  });
4896
- } catch {
5024
+ return {
5025
+ outcome: "created" /* Created */,
5026
+ userId: created.userId,
5027
+ email: created.email,
5028
+ plan: created.plan,
5029
+ emailVerified: created.emailVerified,
5030
+ tokensGranted: created.tokensGranted,
5031
+ tokensOnVerification: created.tokensOnVerification,
5032
+ credentialStored: true,
5033
+ message: `Account created on the ${created.plan} plan and the API key stored \u2014 remote tools will use it automatically. ${created.tokensGranted.toLocaleString()} tokens are available now. Verifying ${created.email} upgrades the account to the Starter package \u2014 free and permanent \u2014 and raises that to ${created.tokensOnVerification.toLocaleString()}.`
5034
+ };
5035
+ } catch (error) {
5036
+ const status = axios.isAxiosError(error) ? error.response?.status : void 0;
5037
+ if (status === CONFLICT_STATUS) {
5038
+ return {
5039
+ outcome: "already-registered" /* AlreadyRegistered */,
5040
+ message: "An account already exists for this email. Use muggle-remote-auth-login to sign in instead."
5041
+ };
5042
+ }
5043
+ if (status === THROTTLED_STATUS) {
5044
+ const retryAfterSeconds = axios.isAxiosError(error) ? error.response?.data?.retryAfterSeconds : void 0;
5045
+ return {
5046
+ outcome: "throttled" /* Throttled */,
5047
+ retryAfterSeconds,
5048
+ message: retryAfterSeconds ? `Too many registrations from this machine. Try again in ${retryAfterSeconds} seconds.` : "Too many registrations from this machine. Try again later."
5049
+ };
5050
+ }
5051
+ logger7.error("[Register] Registration failed", {
5052
+ error: error instanceof Error ? error.message : String(error)
5053
+ });
5054
+ throw error;
4897
5055
  }
4898
5056
  }
4899
5057
 
4900
- var DISCLOSURE_COPY = `Muggle Test collects anonymous usage telemetry \u2014 which features you use, how long they take, and whether they succeed \u2014 to help us improve the product. We attach an opaque install ID, your account ID (when signed in), and your IP. We do not collect file contents, OS username, hostname, or file paths. To opt out, set telemetryEnabled to false in ~/.muggle-ai/preferences.json or run \`muggle preferences set telemetryEnabled false\`.`;
4901
-
4902
- function getDisclosureCopy() {
4903
- return DISCLOSURE_COPY;
4904
- }
4905
- function hasShownDisclosure() {
4906
- if (!preferencesFileExists())
4907
- return false;
4908
- const prefs = readPreferences();
4909
- return typeof prefs.disclosureShownAt === "string" && prefs.disclosureShownAt.length > 0;
4910
- }
4911
- function markDisclosureShown(now = /* @__PURE__ */ new Date()) {
4912
- updatePreference("disclosureShownAt", now.toISOString());
4913
- }
4914
-
4915
- var Trigger;
4916
- (function(Trigger2) {
4917
- Trigger2["UserSlash"] = "user-slash";
4918
- Trigger2["ClaudeProactive"] = "claude-proactive";
4919
- Trigger2["NestedSkill"] = "nested-skill";
4920
- })(Trigger || (Trigger = {}));
4921
- var Outcome;
4922
- (function(Outcome2) {
4923
- Outcome2["Success"] = "success";
4924
- Outcome2["Error"] = "error";
4925
- Outcome2["Cancelled"] = "cancelled";
4926
- })(Outcome || (Outcome = {}));
4927
- var ToolSurface;
4928
- (function(ToolSurface2) {
4929
- ToolSurface2["Local"] = "local";
4930
- ToolSurface2["Remote"] = "remote";
4931
- })(ToolSurface || (ToolSurface = {}));
4932
- var Surface;
4933
- (function(Surface2) {
4934
- Surface2["McpLocal"] = "mcp-local";
4935
- Surface2["McpRemote"] = "mcp-remote";
4936
- Surface2["Skill"] = "skill";
4937
- Surface2["Electron"] = "electron";
4938
- })(Surface || (Surface = {}));
4939
- var ServiceName;
4940
- (function(ServiceName2) {
4941
- ServiceName2["MuggleMcp"] = "muggle-mcp";
4942
- ServiceName2["MuggleElectron"] = "muggle-electron";
4943
- ServiceName2["MuggleSkill"] = "muggle-skill";
4944
- })(ServiceName || (ServiceName = {}));
4945
- var EventName;
4946
- (function(EventName2) {
4947
- EventName2["SkillInvoked"] = "skill.invoked";
4948
- EventName2["SkillCompleted"] = "skill.completed";
4949
- EventName2["McpToolInvoked"] = "mcp.tool.invoked";
4950
- EventName2["McpToolCompleted"] = "mcp.tool.completed";
4951
- EventName2["SystemStartup"] = "system.startup";
4952
- EventName2["SystemOptOutChanged"] = "system.opt_out_changed";
4953
- EventName2["SystemDisclosureShown"] = "system.disclosure_shown";
4954
- })(EventName || (EventName = {}));
4955
-
4956
5058
  // packages/mcps/src/mcp/contracts/entity-reference-constants.ts
4957
5059
  var SHORT_ID_REFERENCE_PATTERN = /^\s*(UC|TC|TS|R)[-\s]?0*([1-9]\d*)\s*$/i;
4958
5060
  var ENTITY_REFERENCE_INVALID_MESSAGE = "Expected a full ID or a short ID such as TC-42";
@@ -5584,7 +5686,7 @@ var PromptServiceClient = class {
5584
5686
  */
5585
5687
  buildHeaders(credentials, correlationId) {
5586
5688
  const manifest = readReleaseManifest();
5587
- const installId = getInstallId();
5689
+ const installId = getInstallId2();
5588
5690
  const host = detectMcpHost();
5589
5691
  const headers = {
5590
5692
  "X-Correlation-Id": correlationId,
@@ -7986,56 +8088,6 @@ var LastHostSetInputSchema = z.object({
7986
8088
  var LastHostClearInputSchema = z.object({
7987
8089
  cwd: z.string().describe("Project root directory whose last-used host cache to remove.")
7988
8090
  });
7989
- var SkillTelemetryEmitInputSchema = z.object({
7990
- skillName: z.string().min(1).describe("Name of the skill being invoked, e.g. 'muggle-test'."),
7991
- trigger: z.nativeEnum(Trigger).default(Trigger.UserSlash).describe("Why this skill ran. Defaults to 'user-slash' (user typed /skill-name).")
7992
- });
7993
- var FailureEventType = /* @__PURE__ */ ((FailureEventType2) => {
7994
- FailureEventType2["PreExecutionClassification"] = "pre-execution-classification";
7995
- FailureEventType2["ReplayFailureClassified"] = "replay-failure-classified";
7996
- FailureEventType2["ReplayFailureResolved"] = "replay-failure-resolved";
7997
- FailureEventType2["RegenFailureClassified"] = "regen-failure-classified";
7998
- FailureEventType2["RegenFailureResolved"] = "regen-failure-resolved";
7999
- return FailureEventType2;
8000
- })(FailureEventType || {});
8001
- var EventTelemetryEmitInputSchema = z.object({
8002
- eventType: z.nativeEnum(FailureEventType).describe(
8003
- "Which decision point this event records. Five values cover the AI's pre-execution replay-vs-regen choice and the four post-failure classify\u2192resolve pairs."
8004
- ),
8005
- skillName: z.string().min(1).describe("Skill that emitted this event (e.g. 'muggle-test', 'muggle-test-feature-local')."),
8006
- aiClassification: z.string().optional().describe(
8007
- "What the AI classified the situation as. pre-execution: 'replay' or 'regen'. replay-failure: 'infra' | 'stale-script' | 'product-defect'. regen-failure: 'transient' | 'infra' | 'agent-course' | 'product-uxux'."
8008
- ),
8009
- aiSuggestion: z.string().optional().describe(
8010
- "What the AI suggested the user do. Examples: 'regenerate', 'report-bug', 'muggle-feedback', 'retry', 'wait-and-share'."
8011
- ),
8012
- userAction: z.string().optional().describe(
8013
- "What the user actually picked (only set on *-resolved events). Compare against aiSuggestion to measure classification accuracy."
8014
- ),
8015
- runId: z.string().optional().describe("Anchor: local run ID for the affected execution."),
8016
- testCaseId: z.string().optional().describe("Anchor: cloud test case ID."),
8017
- projectId: z.string().optional().describe("Anchor: cloud project ID."),
8018
- signals: z.array(z.string()).optional().describe(
8019
- "Signals that drove the classification, e.g. ['element-not-found', 'selector-timeout', 'electron-exit-26', 'goal-not-achievable']. Used to refine the rules later."
8020
- ),
8021
- metadata: z.record(z.string(), z.unknown()).optional().describe("Free-form additional context (e.g. error excerpt, last step name).")
8022
- });
8023
- var TELEMETRY_DIR_NAME = "telemetry";
8024
- var FAILURE_EVENTS_FILE_NAME = "failure-events.jsonl";
8025
- function appendFailureEvent(record) {
8026
- try {
8027
- const dir = path15.join(getDataDir(), TELEMETRY_DIR_NAME);
8028
- fs4.mkdirSync(dir, { recursive: true });
8029
- const filePath = path15.join(dir, FAILURE_EVENTS_FILE_NAME);
8030
- const full = { ts: (/* @__PURE__ */ new Date()).toISOString(), ...record };
8031
- fs4.appendFileSync(filePath, `${JSON.stringify(full)}
8032
- `, "utf-8");
8033
- } catch (error) {
8034
- getLogger().warn("Failed to append failure event", {
8035
- error: error instanceof Error ? error.message : String(error)
8036
- });
8037
- }
8038
- }
8039
8091
 
8040
8092
  // packages/mcps/src/shared/project-preferences-reconcile-types.ts
8041
8093
  var ProjectPreferencesReconcileOutcome = /* @__PURE__ */ ((ProjectPreferencesReconcileOutcome2) => {
@@ -8839,24 +8891,16 @@ var telemetrySkillEmitTool = {
8839
8891
  return { content: "ok", isError: false, data: { recorded: true } };
8840
8892
  }
8841
8893
  };
8894
+ function formatQuotedEventTypes(eventTypes) {
8895
+ return eventTypes.map((eventType) => `'${eventType}'`).join(", ");
8896
+ }
8842
8897
  var telemetryEventEmitTool = {
8843
8898
  name: "muggle-local-telemetry-event-emit",
8844
- description: "Emit a structured failure-mode telemetry event recording how a Muggle Test skill classified a situation and what action the user took. Used at five decision points: 'pre-execution-classification' (replay vs regen), 'replay-failure-classified', 'replay-failure-resolved', 'regen-failure-classified', 'regen-failure-resolved'. Records to ~/.muggle-ai/telemetry/failure-events.jsonl. Never fails the skill on telemetry errors.",
8899
+ description: `Emit a structured Muggle Test skill telemetry event. Failure-mode events (${formatQuotedEventTypes(Object.values(FailureEventType))}) record how a skill classified a replay or regen situation and what action the user took \u2014 recorded to ${MUGGLE_HOME_DISPLAY_DIR}/${TELEMETRY_DIR_NAME}/${FAILURE_EVENTS_FILE_NAME}. Workflow events (${formatQuotedEventTypes(Object.values(WorkflowEventType))}) carry their catalog payload in metadata \u2014 recorded to ${MUGGLE_HOME_DISPLAY_DIR}/${TELEMETRY_DIR_NAME}/${WORKFLOW_EVENTS_FILE_NAME}. Never fails the skill on telemetry errors.`,
8845
8900
  inputSchema: EventTelemetryEmitInputSchema,
8846
8901
  execute: async (ctx) => {
8847
8902
  const input = EventTelemetryEmitInputSchema.parse(ctx.input);
8848
- appendFailureEvent({
8849
- eventType: input.eventType,
8850
- skillName: input.skillName,
8851
- aiClassification: input.aiClassification,
8852
- aiSuggestion: input.aiSuggestion,
8853
- userAction: input.userAction,
8854
- runId: input.runId,
8855
- testCaseId: input.testCaseId,
8856
- projectId: input.projectId,
8857
- signals: input.signals,
8858
- metadata: input.metadata
8859
- });
8903
+ recordTelemetryEvent(input);
8860
8904
  return { content: "ok", isError: false, data: { recorded: true } };
8861
8905
  }
8862
8906
  };
@@ -9112,6 +9156,7 @@ __export(local_exports2, {
9112
9156
  TestScriptDetailsSchema: () => TestScriptDetailsSchema,
9113
9157
  TestScriptGetInputSchema: () => TestScriptGetInputSchema2,
9114
9158
  TestScriptListInputSchema: () => TestScriptListInputSchema2,
9159
+ WorkflowEventType: () => WorkflowEventType,
9115
9160
  acquireLocalExecutionLock: () => acquireLocalExecutionLock,
9116
9161
  allLocalQaTools: () => allLocalQaTools,
9117
9162
  cancelExecution: () => cancelExecution,
@@ -9127,6 +9172,7 @@ __export(local_exports2, {
9127
9172
  isLoopbackUrl: () => isLoopbackUrl,
9128
9173
  listActiveExecutions: () => listActiveExecutions,
9129
9174
  readLocalExecutionLockState: () => readLocalExecutionLockState,
9175
+ recordTelemetryEvent: () => recordTelemetryEvent,
9130
9176
  resetAuthService: () => resetAuthService,
9131
9177
  resetRunResultStorageService: () => resetRunResultStorageService,
9132
9178
  resetStorageService: () => resetStorageService