@muggleai/works 5.34.0-staging.309 → 5.34.0-staging.311

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,24 +1,25 @@
1
- import { __export, getLogger, TelemetryEnvironment, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, buildElectronAppChecksumsUrl, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, buildLlmSourcePlan, describeLlmSourceStatus, resolveLlmSourceStatus, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, OnboardingBlanketChoice, PreferenceKey, LlmSource, applyLlmSourceSelection, describeStackMismatch, getDataDir, DEFAULT_LOCAL_LLM_BASE_URL, isValidLocalBaseUrl, local_exports } from './chunk-SMUHQITB.js';
1
+ import { __export, getLogger, TelemetryEnvironment, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, buildLlmSourcePlan, describeLlmSourceStatus, resolveLlmSourceStatus, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, buildElectronAppChecksumsUrl, OnboardingBlanketChoice, PreferenceKey, LlmSource, applyLlmSourceSelection, describeStackMismatch, ELECTRON_APP_CHECKSUMS_ASSET_NAME, getDataDir, DEFAULT_LOCAL_LLM_BASE_URL, isValidLocalBaseUrl, local_exports } from './chunk-H47WQEDR.js';
2
2
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { v4 } from 'uuid';
5
5
  import { z, ZodError } from 'zod';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
7
  import * as fs from 'fs';
8
- import { readFileSync, existsSync, rmSync, mkdirSync, readdirSync, createWriteStream, writeFileSync, statSync, readlinkSync, realpathSync, openSync, closeSync, writeSync, unlinkSync, copyFileSync, renameSync, appendFileSync, readSync, fstatSync } from 'fs';
8
+ import { readFileSync, existsSync, rmSync, readdirSync, mkdirSync, writeFileSync, renameSync, createWriteStream, statSync, readlinkSync, realpathSync, openSync, closeSync, writeSync, unlinkSync, copyFileSync, appendFileSync, readSync, fstatSync } from 'fs';
9
9
  import * as path from 'path';
10
10
  import { join, dirname, resolve, win32, basename } from 'path';
11
11
  import { fileURLToPath, pathToFileURL } from 'url';
12
12
  import { Command } from 'commander';
13
13
  import axios from 'axios';
14
- import { createHash } from 'crypto';
14
+ import { createHash, X509Certificate, verify } from 'crypto';
15
15
  import { platform, homedir, arch, tmpdir, hostname } from 'os';
16
16
  import { execFile, execFileSync, spawnSync, spawn } from 'child_process';
17
17
  import { createInterface } from 'readline/promises';
18
18
  import { Writable } from 'stream';
19
19
  import { pipeline } from 'stream/promises';
20
20
  import { readFile } from 'fs/promises';
21
- import { verify } from 'sigstore';
21
+ import { createVerifier, TUFError } from 'sigstore';
22
+ import { setTimeout as setTimeout$1 } from 'timers/promises';
22
23
 
23
24
  var registeredTools = [];
24
25
  function registerTools(tools) {
@@ -254,8 +255,8 @@ function createUnifiedMcpServer(options) {
254
255
  errors: error.issues
255
256
  });
256
257
  const issueMessages = error.issues.slice(0, 3).map((issue) => {
257
- const path6 = issue.path.join(".");
258
- return path6 ? `'${path6}': ${issue.message}` : issue.message;
258
+ const path7 = issue.path.join(".");
259
+ return path7 ? `'${path7}': ${issue.message}` : issue.message;
259
260
  });
260
261
  return {
261
262
  content: [
@@ -1255,7 +1256,7 @@ async function resolveGsScreenshotUrls(report, opts) {
1255
1256
  if (gsUrls.length === 0) {
1256
1257
  return report;
1257
1258
  }
1258
- const mcps = await import('./src-5M2MYBRC.js');
1259
+ const mcps = await import('./src-5BGECNR4.js');
1259
1260
  const credentials = await mcps.getCallerCredentialsAsync();
1260
1261
  if (!credentials.bearerToken && !credentials.apiKey) {
1261
1262
  stderrWrite(
@@ -1492,12 +1493,12 @@ var WORKFLOW_WRITING_OUTCOMES = /* @__PURE__ */ new Set([
1492
1493
  "replaced" /* Replaced */
1493
1494
  ]);
1494
1495
  var CI_INSTALL_MESSAGES = {
1495
- ["installed" /* Installed */]: (path6) => `Wrote ${path6}
1496
+ ["installed" /* Installed */]: (path7) => `Wrote ${path7}
1496
1497
  Commit it, and every pull request here will owe a settled Muggle AI walkthrough comment.`,
1497
- ["updated" /* Updated */]: (path6) => `Updated ${path6} from an earlier Muggle release to the current workflow. Commit it.`,
1498
- ["already-current" /* AlreadyCurrent */]: (path6) => `${path6} is already the current workflow \u2014 nothing to do.`,
1499
- ["kept-customized" /* KeptCustomized */]: (path6) => `${path6} has been edited since Muggle wrote it \u2014 left untouched. Re-run with --force to replace it.`,
1500
- ["replaced" /* Replaced */]: (path6) => `Replaced ${path6} with the current workflow. Commit it.`,
1498
+ ["updated" /* Updated */]: (path7) => `Updated ${path7} from an earlier Muggle release to the current workflow. Commit it.`,
1499
+ ["already-current" /* AlreadyCurrent */]: (path7) => `${path7} is already the current workflow \u2014 nothing to do.`,
1500
+ ["kept-customized" /* KeptCustomized */]: (path7) => `${path7} has been edited since Muggle wrote it \u2014 left untouched. Re-run with --force to replace it.`,
1501
+ ["replaced" /* Replaced */]: (path7) => `Replaced ${path7} with the current workflow. Commit it.`,
1501
1502
  ["not-a-repository" /* NotARepository */]: () => "Not a git repository \u2014 run this from the repo that should carry the check."
1502
1503
  };
1503
1504
 
@@ -2753,8 +2754,8 @@ ${title}`, COLORS.bold + COLORS.cyan);
2753
2754
  function cmd(cmd2) {
2754
2755
  return colorize(cmd2, COLORS.green);
2755
2756
  }
2756
- function path3(path6) {
2757
- return colorize(path6, COLORS.yellow);
2757
+ function path3(path7) {
2758
+ return colorize(path7, COLORS.yellow);
2758
2759
  }
2759
2760
  function getHelpGuidance() {
2760
2761
  const lines = [
@@ -4153,6 +4154,32 @@ async function serveCommand(options) {
4153
4154
  var SIGNATURE_BUNDLE_SUFFIX = ".sigstore.json";
4154
4155
  var SIGNER_CERTIFICATE_ISSUER = "https://token.actions.githubusercontent.com";
4155
4156
  var SIGNATURE_FETCH_TIMEOUT_MS = 3e4;
4157
+ var SIGNATURE_TRUST_ROOT_HOST = "tuf-repo-cdn.sigstore.dev";
4158
+ var SIGNATURE_VERIFIED_MESSAGE = "Signature verified successfully.";
4159
+ var SIGNATURE_REFUSAL_PREFIX = "Signature verification failed, refusing to install: ";
4160
+ var BUNDLE_DIGEST_ALGORITHM = "SHA2_256";
4161
+ var BUNDLE_HASH_ALGORITHM = "sha256";
4162
+ var CERTIFICATE_URI_SAN_PREFIX = "URI:";
4163
+ var CERTIFICATE_SAN_SEPARATOR = ", ";
4164
+ var TRUST_ROOT_FETCH_ERROR_CODES = /* @__PURE__ */ new Set([
4165
+ "TUF_REFRESH_METADATA_ERROR",
4166
+ "TUF_DOWNLOAD_TARGET_ERROR"
4167
+ ]);
4168
+ var HOST_UNREACHABLE_ERROR_CODES = /* @__PURE__ */ new Set([
4169
+ "ENOTFOUND",
4170
+ "EAI_AGAIN",
4171
+ "ECONNREFUSED",
4172
+ "ECONNRESET",
4173
+ "ETIMEDOUT",
4174
+ "ENETUNREACH",
4175
+ "EHOSTUNREACH",
4176
+ "ENETDOWN",
4177
+ "UND_ERR_CONNECT_TIMEOUT",
4178
+ "UND_ERR_SOCKET"
4179
+ ]);
4180
+ var FETCH_TIMEOUT_ERROR_NAME = "TimeoutError";
4181
+ var FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN = /^Unable to load (?:snapshot metadata|targets) error TimeoutError: The operation was aborted due to timeout$/;
4182
+ var MAX_ERROR_CAUSE_DEPTH = 5;
4156
4183
 
4157
4184
  // scripts/release-integrity/compareVersions.mjs
4158
4185
  function compareVersions2(a, b) {
@@ -4172,10 +4199,12 @@ function compareVersions2(a, b) {
4172
4199
  }
4173
4200
 
4174
4201
  // scripts/release-integrity/resolveIntegrityPolicy.mjs
4202
+ function hasExpectedChecksum(expectedChecksum) {
4203
+ return Boolean(expectedChecksum && expectedChecksum.trim());
4204
+ }
4175
4205
  function resolveIntegrityPolicy({ version, signedFromVersion, expectedChecksum }) {
4176
4206
  const requiresSignature = Boolean(signedFromVersion) && compareVersions2(version, signedFromVersion) >= 0;
4177
- const hasChecksum = Boolean(expectedChecksum && expectedChecksum.trim());
4178
- if (!requiresSignature && !hasChecksum) {
4207
+ if (!requiresSignature && !hasExpectedChecksum(expectedChecksum)) {
4179
4208
  return {
4180
4209
  requiresSignature: false,
4181
4210
  requiresChecksum: false,
@@ -4188,9 +4217,66 @@ function resolveIntegrityPolicy({ version, signedFromVersion, expectedChecksum }
4188
4217
  unverifiableReason: ""
4189
4218
  };
4190
4219
  }
4220
+ function listErrorChain(error) {
4221
+ const chain = [];
4222
+ let current = error;
4223
+ while (current && chain.length < MAX_ERROR_CAUSE_DEPTH) {
4224
+ chain.push(current);
4225
+ current = current.cause;
4226
+ }
4227
+ return chain;
4228
+ }
4229
+ function isTrustRootUnreachable(trustRootError) {
4230
+ if (!(trustRootError instanceof TUFError) || !TRUST_ROOT_FETCH_ERROR_CODES.has(trustRootError.code)) {
4231
+ return false;
4232
+ }
4233
+ return listErrorChain(trustRootError.cause).some(
4234
+ (chainedError) => chainedError.name === FETCH_TIMEOUT_ERROR_NAME || HOST_UNREACHABLE_ERROR_CODES.has(chainedError.code) || FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN.test(chainedError.message ?? "")
4235
+ );
4236
+ }
4237
+ function describeErrorChain(error) {
4238
+ return listErrorChain(error).map((chainedError) => chainedError.message).filter(Boolean).join(": ");
4239
+ }
4240
+ function findBundleMismatch({ bundle, artifactBytes, signerIdentityUri }) {
4241
+ const messageSignature = bundle?.messageSignature;
4242
+ const messageDigest = messageSignature?.messageDigest;
4243
+ const certificateRawBytes = bundle?.verificationMaterial?.certificate?.rawBytes;
4244
+ if (!messageDigest?.digest || !messageSignature?.signature || !certificateRawBytes) {
4245
+ return "the signature bundle is missing its digest, signature or signing certificate";
4246
+ }
4247
+ if (messageDigest.algorithm !== BUNDLE_DIGEST_ALGORITHM) {
4248
+ return `the signature bundle uses an unexpected digest algorithm: ${messageDigest.algorithm}`;
4249
+ }
4250
+ const artifactDigest = createHash(BUNDLE_HASH_ALGORITHM).update(artifactBytes).digest();
4251
+ if (!artifactDigest.equals(Buffer.from(messageDigest.digest, "base64"))) {
4252
+ return "the download does not match the digest recorded in its signature bundle";
4253
+ }
4254
+ try {
4255
+ const signingCertificate = new X509Certificate(Buffer.from(certificateRawBytes, "base64"));
4256
+ const certificateNames = (signingCertificate.subjectAltName ?? "").split(CERTIFICATE_SAN_SEPARATOR);
4257
+ if (!certificateNames.includes(`${CERTIFICATE_URI_SAN_PREFIX}${signerIdentityUri}`)) {
4258
+ return `the signing certificate was not issued to ${signerIdentityUri}`;
4259
+ }
4260
+ const isSignatureMatching = verify(
4261
+ BUNDLE_HASH_ALGORITHM,
4262
+ artifactBytes,
4263
+ signingCertificate.publicKey,
4264
+ Buffer.from(messageSignature.signature, "base64")
4265
+ );
4266
+ return isSignatureMatching ? "" : "the signature in the bundle does not match the download";
4267
+ } catch (error) {
4268
+ return `the signature bundle could not be read: ${error.message}`;
4269
+ }
4270
+ }
4271
+
4272
+ // scripts/release-integrity/verifyReleaseSignature.mjs
4191
4273
  async function verifyReleaseSignature({ artifactPath, bundleUrl, signerIdentityUri }) {
4192
4274
  if (!signerIdentityUri) {
4193
- return { valid: false, reason: "no signer identity is configured to verify against" };
4275
+ return {
4276
+ valid: false,
4277
+ reason: "no signer identity is configured to verify against",
4278
+ isTrustRootUnreachable: false
4279
+ };
4194
4280
  }
4195
4281
  const controller = new AbortController();
4196
4282
  const timer = setTimeout(() => controller.abort(), SIGNATURE_FETCH_TIMEOUT_MS);
@@ -4200,23 +4286,161 @@ async function verifyReleaseSignature({ artifactPath, bundleUrl, signerIdentityU
4200
4286
  if (!response.ok) {
4201
4287
  return {
4202
4288
  valid: false,
4203
- reason: `signature bundle unavailable (HTTP ${response.status}) at ${bundleUrl}`
4289
+ reason: `signature bundle unavailable (HTTP ${response.status}) at ${bundleUrl}`,
4290
+ isTrustRootUnreachable: false
4204
4291
  };
4205
4292
  }
4206
4293
  bundle = await response.json();
4207
4294
  } catch (error) {
4208
- return { valid: false, reason: `could not fetch signature bundle: ${error.message}` };
4295
+ return {
4296
+ valid: false,
4297
+ reason: `could not fetch signature bundle: ${error.message}`,
4298
+ isTrustRootUnreachable: false
4299
+ };
4209
4300
  } finally {
4210
4301
  clearTimeout(timer);
4211
4302
  }
4303
+ let artifactBytes;
4304
+ try {
4305
+ artifactBytes = await readFile(artifactPath);
4306
+ } catch (error) {
4307
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
4308
+ }
4309
+ let bundleVerifier;
4212
4310
  try {
4213
- await verify(bundle, await readFile(artifactPath), {
4311
+ bundleVerifier = await createVerifier({
4214
4312
  certificateIssuer: SIGNER_CERTIFICATE_ISSUER,
4215
4313
  certificateIdentityURI: signerIdentityUri
4216
4314
  });
4217
- return { valid: true, reason: "" };
4218
4315
  } catch (error) {
4219
- return { valid: false, reason: error.message };
4316
+ const failureDescription = describeErrorChain(error);
4317
+ if (!isTrustRootUnreachable(error)) {
4318
+ return {
4319
+ valid: false,
4320
+ reason: `could not load the trust root from ${SIGNATURE_TRUST_ROOT_HOST}: ${failureDescription}`,
4321
+ isTrustRootUnreachable: false
4322
+ };
4323
+ }
4324
+ const bundleMismatch = findBundleMismatch({
4325
+ bundle,
4326
+ artifactBytes,
4327
+ signerIdentityUri
4328
+ });
4329
+ return {
4330
+ valid: false,
4331
+ reason: bundleMismatch || failureDescription,
4332
+ isTrustRootUnreachable: !bundleMismatch
4333
+ };
4334
+ }
4335
+ try {
4336
+ bundleVerifier.verify(bundle, artifactBytes);
4337
+ return { valid: true, reason: "", isTrustRootUnreachable: false };
4338
+ } catch (error) {
4339
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
4340
+ }
4341
+ }
4342
+
4343
+ // scripts/release-integrity/enforceReleaseSignature.mjs
4344
+ async function enforceReleaseSignature({
4345
+ artifactPath,
4346
+ bundleUrl,
4347
+ signerIdentityUri,
4348
+ expectedChecksum,
4349
+ logInfo,
4350
+ logWarning
4351
+ }) {
4352
+ const signatureOutcome = await verifyReleaseSignature({
4353
+ artifactPath,
4354
+ bundleUrl,
4355
+ signerIdentityUri
4356
+ });
4357
+ if (signatureOutcome.valid) {
4358
+ logInfo(SIGNATURE_VERIFIED_MESSAGE);
4359
+ return { isSignatureVerified: true };
4360
+ }
4361
+ if (!signatureOutcome.isTrustRootUnreachable) {
4362
+ throw new Error(SIGNATURE_REFUSAL_PREFIX + signatureOutcome.reason);
4363
+ }
4364
+ const networkFailure = `a network failure kept ${SIGNATURE_TRUST_ROOT_HOST} out of reach (${signatureOutcome.reason})`;
4365
+ if (!hasExpectedChecksum(expectedChecksum)) {
4366
+ throw new Error(`${SIGNATURE_REFUSAL_PREFIX}${networkFailure}, and no checksum is available to check instead.`);
4367
+ }
4368
+ logWarning(
4369
+ `WARNING: The signature was NOT verified: ${networkFailure}. Falling back to the checksum check only.`
4370
+ );
4371
+ return { isSignatureVerified: false };
4372
+ }
4373
+
4374
+ // src/cli/studio-install-staging-constants.ts
4375
+ var STUDIO_STAGING_DIR_NAME = "studio-stage";
4376
+ var RETIRED_INSTALL_SUFFIX = ".retired";
4377
+ var INSTALL_MOVE_MAX_ATTEMPTS = 10;
4378
+ var INSTALL_MOVE_RETRY_DELAY_MS = 500;
4379
+ var INSTALL_MOVE_RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
4380
+
4381
+ // src/cli/studio-install-staging.ts
4382
+ function getStudioStagingDir(versionDir) {
4383
+ return path.join(getDataDir2(), STUDIO_STAGING_DIR_NAME, path.basename(versionDir));
4384
+ }
4385
+ function getRetiredInstallDir(stagingDir) {
4386
+ return `${stagingDir}${RETIRED_INSTALL_SUFFIX}`;
4387
+ }
4388
+ function prepareStudioStagingDir(params) {
4389
+ const { stagingDir, versionDir } = params;
4390
+ const retiredDir = getRetiredInstallDir(stagingDir);
4391
+ if (existsSync(retiredDir) && !existsSync(versionDir)) {
4392
+ renameSync(retiredDir, versionDir);
4393
+ }
4394
+ rmSync(stagingDir, { recursive: true, force: true });
4395
+ rmSync(retiredDir, { recursive: true, force: true });
4396
+ mkdirSync(stagingDir, { recursive: true });
4397
+ }
4398
+ function discardStudioStagingDir(stagingDir) {
4399
+ try {
4400
+ rmSync(stagingDir, { recursive: true, force: true });
4401
+ } catch {
4402
+ }
4403
+ }
4404
+ async function moveDirectory(fromDir, toDir) {
4405
+ for (let attempt = 1; ; attempt++) {
4406
+ try {
4407
+ renameSync(fromDir, toDir);
4408
+ return;
4409
+ } catch (error) {
4410
+ const errorCode = error.code ?? "";
4411
+ if (attempt >= INSTALL_MOVE_MAX_ATTEMPTS || !INSTALL_MOVE_RETRYABLE_ERROR_CODES.has(errorCode)) {
4412
+ throw error;
4413
+ }
4414
+ await setTimeout$1(INSTALL_MOVE_RETRY_DELAY_MS);
4415
+ }
4416
+ }
4417
+ }
4418
+ async function replaceStudioInstall(params) {
4419
+ const { stagingDir, versionDir } = params;
4420
+ mkdirSync(path.dirname(versionDir), { recursive: true });
4421
+ if (!existsSync(versionDir)) {
4422
+ await moveDirectory(stagingDir, versionDir);
4423
+ return;
4424
+ }
4425
+ const retiredDir = getRetiredInstallDir(stagingDir);
4426
+ try {
4427
+ await moveDirectory(versionDir, retiredDir);
4428
+ } catch (error) {
4429
+ const errorMessage = error instanceof Error ? error.message : String(error);
4430
+ throw new Error(
4431
+ `Could not replace the install at ${versionDir}, which may be in use. It was left as it was: ${errorMessage}`,
4432
+ { cause: error }
4433
+ );
4434
+ }
4435
+ try {
4436
+ await moveDirectory(stagingDir, versionDir);
4437
+ } catch (error) {
4438
+ await moveDirectory(retiredDir, versionDir);
4439
+ throw error;
4440
+ }
4441
+ try {
4442
+ rmSync(retiredDir, { recursive: true, force: true });
4443
+ } catch {
4220
4444
  }
4221
4445
  }
4222
4446
 
@@ -4324,14 +4548,6 @@ function writeInstallMetadata(params) {
4324
4548
  writeFileSync(params.metadataPath, `${JSON.stringify(metadata, null, 2)}
4325
4549
  `, "utf-8");
4326
4550
  }
4327
- function cleanupFailedInstall(versionDir) {
4328
- if (existsSync(versionDir)) {
4329
- try {
4330
- rmSync(versionDir, { recursive: true, force: true });
4331
- } catch {
4332
- }
4333
- }
4334
- }
4335
4551
  function upsertCursorMcpConfig() {
4336
4552
  const cursorMcpConfigPath = path.join(homedir(), ".cursor", "mcp.json");
4337
4553
  const cursorDir = path.join(homedir(), ".cursor");
@@ -4392,12 +4608,10 @@ async function setupCommand(options) {
4392
4608
  });
4393
4609
  console.log(`Downloading Muggle Test Electron app v${version}...`);
4394
4610
  console.log(`URL: ${downloadUrl}`);
4611
+ const stagingDir = getStudioStagingDir(versionDir);
4395
4612
  try {
4396
- if (existsSync(versionDir)) {
4397
- rmSync(versionDir, { recursive: true, force: true });
4398
- }
4399
- mkdirSync(versionDir, { recursive: true });
4400
- const tempFile = path.join(versionDir, binaryName);
4613
+ prepareStudioStagingDir({ stagingDir, versionDir });
4614
+ const tempFile = path.join(stagingDir, binaryName);
4401
4615
  await downloadWithRetry(downloadUrl, tempFile);
4402
4616
  console.log("Download complete, verifying integrity...");
4403
4617
  const checksums = getElectronAppChecksums();
@@ -4408,24 +4622,23 @@ async function setupCommand(options) {
4408
4622
  expectedChecksum: expectedChecksum ?? ""
4409
4623
  });
4410
4624
  if (integrityPolicy.unverifiableReason) {
4411
- cleanupFailedInstall(versionDir);
4412
4625
  throw new Error("Refusing to install an unverifiable download: " + integrityPolicy.unverifiableReason);
4413
4626
  }
4627
+ let isSignatureVerified = false;
4414
4628
  if (integrityPolicy.requiresSignature) {
4415
- const signatureResult = await verifyReleaseSignature({
4629
+ const signatureEnforcement = await enforceReleaseSignature({
4416
4630
  artifactPath: tempFile,
4417
4631
  bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
4418
- signerIdentityUri: getReleaseSignerIdentityUri()
4632
+ signerIdentityUri: getReleaseSignerIdentityUri(),
4633
+ expectedChecksum: expectedChecksum ?? "",
4634
+ logInfo: console.log,
4635
+ logWarning: console.warn
4419
4636
  });
4420
- if (!signatureResult.valid) {
4421
- cleanupFailedInstall(versionDir);
4422
- throw new Error("Signature verification failed, refusing to install: " + signatureResult.reason);
4423
- }
4424
- console.log("Signature verified successfully.");
4637
+ isSignatureVerified = signatureEnforcement.isSignatureVerified;
4425
4638
  }
4426
4639
  const checksumResult = await verifyFileChecksum(tempFile, expectedChecksum);
4427
4640
  if (!checksumResult.valid && expectedChecksum) {
4428
- if (!integrityPolicy.requiresChecksum) {
4641
+ if (isSignatureVerified) {
4429
4642
  console.warn(
4430
4643
  `Pinned checksum does not match this download, but its signature verified.
4431
4644
  Expected: ${checksumResult.expected}
@@ -4433,7 +4646,6 @@ Actual: ${checksumResult.actual}
4433
4646
  The pin in package.json muggleConfig.checksumsByStream is stale for this release; continuing on the signature.`
4434
4647
  );
4435
4648
  } else {
4436
- cleanupFailedInstall(versionDir);
4437
4649
  throw new Error(
4438
4650
  `Checksum verification failed!
4439
4651
  Expected: ${checksumResult.expected}
@@ -4447,13 +4659,12 @@ The downloaded file may be corrupted or tampered with.`
4447
4659
  }
4448
4660
  console.log("Extracting...");
4449
4661
  if (binaryName.endsWith(".zip")) {
4450
- await extractZip(tempFile, versionDir);
4662
+ await extractZip(tempFile, stagingDir);
4451
4663
  } else if (binaryName.endsWith(".tar.gz")) {
4452
- await extractTarGz(tempFile, versionDir);
4664
+ await extractTarGz(tempFile, stagingDir);
4453
4665
  }
4454
- const executablePath = resolveElectronAppExecutablePath({ installDir: versionDir, platformName: platform() });
4666
+ const executablePath = resolveElectronAppExecutablePath({ installDir: stagingDir, platformName: platform() });
4455
4667
  if (!existsSync(executablePath)) {
4456
- cleanupFailedInstall(versionDir);
4457
4668
  throw new Error(
4458
4669
  `Extraction failed: executable not found at expected path.
4459
4670
  Expected: ${executablePath}
@@ -4461,7 +4672,7 @@ The archive may be corrupted or in an unexpected format.`
4461
4672
  );
4462
4673
  }
4463
4674
  const executableChecksum = await calculateFileChecksum(executablePath);
4464
- const metadataPath = path.join(versionDir, INSTALL_METADATA_FILE_NAME);
4675
+ const metadataPath = path.join(stagingDir, INSTALL_METADATA_FILE_NAME);
4465
4676
  writeInstallMetadata({
4466
4677
  metadataPath,
4467
4678
  version,
@@ -4471,9 +4682,11 @@ The archive may be corrupted or in an unexpected format.`
4471
4682
  expectedArchiveChecksum: expectedChecksum
4472
4683
  });
4473
4684
  rmSync(tempFile, { force: true });
4685
+ await replaceStudioInstall({ stagingDir, versionDir });
4474
4686
  console.log(`Electron app installed to ${versionDir}`);
4475
4687
  logger6.info("Setup complete", { version, path: versionDir });
4476
4688
  } catch (error) {
4689
+ discardStudioStagingDir(stagingDir);
4477
4690
  const errorMessage = error instanceof Error ? error.message : String(error);
4478
4691
  console.error(`Failed to download Electron app: ${errorMessage}`);
4479
4692
  logger6.error("Setup failed", { error: errorMessage });
@@ -4584,8 +4797,95 @@ function seconds(ms) {
4584
4797
  function minutes(ms) {
4585
4798
  return `${Math.max(0, Math.round(ms / 6e4))}m`;
4586
4799
  }
4587
- var logger7 = getLogger();
4800
+
4801
+ // src/cli/studio-release/constants.ts
4588
4802
  var GITHUB_RELEASES_API = "https://api.github.com/repos/multiplex-ai/muggle-ai-works/releases?per_page=100";
4803
+ var GITHUB_RELEASES_API_HEADERS = {
4804
+ "Accept": "application/vnd.github.v3+json",
4805
+ "User-Agent": "muggle"
4806
+ };
4807
+ var PAGINATION_LINK_HEADER = "link";
4808
+ var NEXT_PAGE_LINK_PATTERN = /<([^>]+)>;\s*rel="next"/;
4809
+ var MAX_RELEASE_LIST_PAGES = 50;
4810
+
4811
+ // src/cli/studio-release/newest-release.ts
4812
+ function extractVersionFromTag(tag, releaseTagPrefix) {
4813
+ if (!tag.startsWith(releaseTagPrefix)) {
4814
+ return null;
4815
+ }
4816
+ const match = tag.slice(releaseTagPrefix.length).match(/^(\d+\.\d+\.\d+)$/);
4817
+ return match ? match[1] : null;
4818
+ }
4819
+ function listRequiredAssetNames(params) {
4820
+ const requiredAssetNames = [params.platformArchiveName, ELECTRON_APP_CHECKSUMS_ASSET_NAME];
4821
+ const integrityPolicy = resolveIntegrityPolicy({
4822
+ version: params.version,
4823
+ signedFromVersion: params.signedFromVersion,
4824
+ expectedChecksum: ""
4825
+ });
4826
+ if (integrityPolicy.requiresSignature) {
4827
+ requiredAssetNames.push(params.platformArchiveName + SIGNATURE_BUNDLE_SUFFIX);
4828
+ }
4829
+ return requiredAssetNames;
4830
+ }
4831
+ function hasEveryRequiredAsset(params) {
4832
+ const uploadedAssetNames = new Set(
4833
+ params.release.assets.filter((asset) => asset.state === "uploaded" /* Uploaded */).map((asset) => asset.name)
4834
+ );
4835
+ return params.requiredAssetNames.every((assetName) => uploadedAssetNames.has(assetName));
4836
+ }
4837
+ function selectNewestInstallableVersion(params) {
4838
+ let newestVersion = null;
4839
+ for (const release of params.releases) {
4840
+ if (release.draft) {
4841
+ continue;
4842
+ }
4843
+ const version = extractVersionFromTag(release.tag_name, params.releaseTagPrefix);
4844
+ if (!version || newestVersion && compareVersions2(version, newestVersion) <= 0) {
4845
+ continue;
4846
+ }
4847
+ const requiredAssetNames = listRequiredAssetNames({
4848
+ version,
4849
+ platformArchiveName: params.platformArchiveName,
4850
+ signedFromVersion: params.signedFromVersion
4851
+ });
4852
+ if (hasEveryRequiredAsset({ release, requiredAssetNames })) {
4853
+ newestVersion = version;
4854
+ }
4855
+ }
4856
+ return newestVersion;
4857
+ }
4858
+ function parseNextPageUrl(linkHeader) {
4859
+ const nextPageMatch = linkHeader?.match(NEXT_PAGE_LINK_PATTERN);
4860
+ return nextPageMatch ? nextPageMatch[1] : null;
4861
+ }
4862
+ async function fetchStudioReleases() {
4863
+ const releases = [];
4864
+ let pageUrl = GITHUB_RELEASES_API;
4865
+ for (let pagesRead = 0; pageUrl; pagesRead++) {
4866
+ if (pagesRead === MAX_RELEASE_LIST_PAGES) {
4867
+ throw new Error(`The release list runs past ${MAX_RELEASE_LIST_PAGES} pages.`);
4868
+ }
4869
+ const response = await fetch(pageUrl, { headers: GITHUB_RELEASES_API_HEADERS });
4870
+ if (!response.ok) {
4871
+ throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
4872
+ }
4873
+ releases.push(...await response.json());
4874
+ pageUrl = parseNextPageUrl(response.headers.get(PAGINATION_LINK_HEADER));
4875
+ }
4876
+ return releases;
4877
+ }
4878
+ async function resolveNewestInstallableVersion(requirements) {
4879
+ return selectNewestInstallableVersion({
4880
+ releases: await fetchStudioReleases(),
4881
+ releaseTagPrefix: requirements.releaseTagPrefix,
4882
+ platformArchiveName: requirements.platformArchiveName,
4883
+ signedFromVersion: requirements.signedFromVersion
4884
+ });
4885
+ }
4886
+
4887
+ // src/cli/upgrade.ts
4888
+ var logger7 = getLogger();
4589
4889
  var INSTALL_METADATA_FILE_NAME2 = ".install-metadata.json";
4590
4890
  var VERSION_OVERRIDE_FILE = "electron-app-version-override.json";
4591
4891
  function getBinaryName2() {
@@ -4602,13 +4902,6 @@ function getBinaryName2() {
4602
4902
  throw new Error(`Unsupported platform: ${os}`);
4603
4903
  }
4604
4904
  }
4605
- function extractVersionFromTag(tag, releaseTagPrefix) {
4606
- if (!tag.startsWith(releaseTagPrefix)) {
4607
- return null;
4608
- }
4609
- const match = tag.slice(releaseTagPrefix.length).match(/^(\d+\.\d+\.\d+)$/);
4610
- return match ? match[1] : null;
4611
- }
4612
4905
  function getVersionOverridePath() {
4613
4906
  return path.join(getDataDir2(), VERSION_OVERRIDE_FILE);
4614
4907
  }
@@ -4639,40 +4932,27 @@ function saveVersionOverride(version) {
4639
4932
  async function checkForUpdates() {
4640
4933
  const currentVersion = getEffectiveElectronAppVersion();
4641
4934
  try {
4642
- const response = await fetch(GITHUB_RELEASES_API, {
4643
- headers: {
4644
- "Accept": "application/vnd.github.v3+json",
4645
- "User-Agent": "muggle"
4646
- }
4935
+ const binaryName = getBinaryName2();
4936
+ const newestVersion = await resolveNewestInstallableVersion({
4937
+ releaseTagPrefix: getElectronAppReleaseTagPrefix(),
4938
+ platformArchiveName: binaryName,
4939
+ signedFromVersion: getElectronAppSignedFromVersion()
4647
4940
  });
4648
- if (!response.ok) {
4649
- throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
4650
- }
4651
- const releases = await response.json();
4652
- const releaseTagPrefix = getElectronAppReleaseTagPrefix();
4653
- for (const release of releases) {
4654
- if (release.draft) {
4655
- continue;
4656
- }
4657
- const version = extractVersionFromTag(release.tag_name, releaseTagPrefix);
4658
- if (version) {
4659
- const updateAvailable = compareVersions2(version, currentVersion) > 0;
4660
- const binaryName = getBinaryName2();
4661
- return {
4662
- currentVersion,
4663
- latestVersion: version,
4664
- updateAvailable,
4665
- downloadUrl: buildElectronAppReleaseAssetUrl({
4666
- version,
4667
- assetFileName: binaryName
4668
- })
4669
- };
4670
- }
4941
+ if (!newestVersion) {
4942
+ return {
4943
+ currentVersion,
4944
+ latestVersion: currentVersion,
4945
+ updateAvailable: false
4946
+ };
4671
4947
  }
4672
4948
  return {
4673
4949
  currentVersion,
4674
- latestVersion: currentVersion,
4675
- updateAvailable: false
4950
+ latestVersion: newestVersion,
4951
+ updateAvailable: compareVersions2(newestVersion, currentVersion) > 0,
4952
+ downloadUrl: buildElectronAppReleaseAssetUrl({
4953
+ version: newestVersion,
4954
+ assetFileName: binaryName
4955
+ })
4676
4956
  };
4677
4957
  } catch (error) {
4678
4958
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -4773,21 +5053,15 @@ async function fetchChecksumFromRelease(version) {
4773
5053
  return "";
4774
5054
  }
4775
5055
  }
4776
- async function downloadAndInstall(version, downloadUrl, checksum) {
4777
- const versionDir = getElectronAppDir(version);
5056
+ async function stageVerifiedDownload(params) {
5057
+ const { version, downloadUrl, checksum, stagingDir } = params;
4778
5058
  const binaryName = getBinaryName2();
4779
5059
  const platformKey = getPlatformKey();
4780
- console.log(`Downloading Muggle Test Electron app v${version}...`);
4781
- console.log(`URL: ${downloadUrl}`);
4782
- if (existsSync(versionDir)) {
4783
- rmSync(versionDir, { recursive: true, force: true });
4784
- }
4785
- mkdirSync(versionDir, { recursive: true });
4786
5060
  const response = await fetch(downloadUrl);
4787
5061
  if (!response.ok) {
4788
5062
  throw new Error(`Download failed: ${response.status} ${response.statusText}`);
4789
5063
  }
4790
- const tempFile = path.join(versionDir, binaryName);
5064
+ const tempFile = path.join(stagingDir, binaryName);
4791
5065
  const fileStream = createWriteStream(tempFile);
4792
5066
  if (!response.body) {
4793
5067
  throw new Error("No response body");
@@ -4804,24 +5078,20 @@ async function downloadAndInstall(version, downloadUrl, checksum) {
4804
5078
  expectedChecksum: expectedChecksum ?? ""
4805
5079
  });
4806
5080
  if (integrityPolicy.unverifiableReason) {
4807
- rmSync(versionDir, { recursive: true, force: true });
4808
5081
  throw new Error("Refusing to install an unverifiable download: " + integrityPolicy.unverifiableReason);
4809
5082
  }
4810
5083
  if (integrityPolicy.requiresSignature) {
4811
- const signatureResult = await verifyReleaseSignature({
5084
+ await enforceReleaseSignature({
4812
5085
  artifactPath: tempFile,
4813
5086
  bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
4814
- signerIdentityUri: getReleaseSignerIdentityUri()
5087
+ signerIdentityUri: getReleaseSignerIdentityUri(),
5088
+ expectedChecksum: expectedChecksum ?? "",
5089
+ logInfo: console.log,
5090
+ logWarning: console.warn
4815
5091
  });
4816
- if (!signatureResult.valid) {
4817
- rmSync(versionDir, { recursive: true, force: true });
4818
- throw new Error("Signature verification failed, refusing to install: " + signatureResult.reason);
4819
- }
4820
- console.log("Signature verified successfully.");
4821
5092
  }
4822
5093
  const checksumResult = await verifyFileChecksum(tempFile, expectedChecksum || "");
4823
5094
  if (!checksumResult.valid && expectedChecksum) {
4824
- rmSync(versionDir, { recursive: true, force: true });
4825
5095
  throw new Error(
4826
5096
  `Checksum verification failed!
4827
5097
  Expected: ${checksumResult.expected}
@@ -4834,13 +5104,12 @@ The downloaded file may be corrupted or tampered with.`
4834
5104
  }
4835
5105
  console.log("Extracting...");
4836
5106
  if (binaryName.endsWith(".zip")) {
4837
- await extractZip2(tempFile, versionDir);
5107
+ await extractZip2(tempFile, stagingDir);
4838
5108
  } else if (binaryName.endsWith(".tar.gz")) {
4839
- await extractTarGz2(tempFile, versionDir);
5109
+ await extractTarGz2(tempFile, stagingDir);
4840
5110
  }
4841
- const executablePath = resolveElectronAppExecutablePath({ installDir: versionDir, platformName: platform() });
5111
+ const executablePath = resolveElectronAppExecutablePath({ installDir: stagingDir, platformName: platform() });
4842
5112
  if (!existsSync(executablePath)) {
4843
- rmSync(versionDir, { recursive: true, force: true });
4844
5113
  throw new Error(
4845
5114
  `Extraction failed: executable not found at expected path.
4846
5115
  Expected: ${executablePath}
@@ -4848,7 +5117,7 @@ The archive may be corrupted or in an unexpected format.`
4848
5117
  );
4849
5118
  }
4850
5119
  const executableChecksum = await calculateFileChecksum(executablePath);
4851
- const metadataPath = path.join(versionDir, INSTALL_METADATA_FILE_NAME2);
5120
+ const metadataPath = path.join(stagingDir, INSTALL_METADATA_FILE_NAME2);
4852
5121
  writeInstallMetadata2({
4853
5122
  metadataPath,
4854
5123
  version,
@@ -4858,6 +5127,25 @@ The archive may be corrupted or in an unexpected format.`
4858
5127
  expectedArchiveChecksum: expectedChecksum || ""
4859
5128
  });
4860
5129
  rmSync(tempFile, { force: true });
5130
+ }
5131
+ async function downloadAndInstall(version, downloadUrl, checksum) {
5132
+ const versionDir = getElectronAppDir(version);
5133
+ const stagingDir = getStudioStagingDir(versionDir);
5134
+ console.log(`Downloading Muggle Test Electron app v${version}...`);
5135
+ console.log(`URL: ${downloadUrl}`);
5136
+ try {
5137
+ prepareStudioStagingDir({ stagingDir, versionDir });
5138
+ await stageVerifiedDownload({
5139
+ version,
5140
+ downloadUrl,
5141
+ checksum,
5142
+ stagingDir
5143
+ });
5144
+ await replaceStudioInstall({ stagingDir, versionDir });
5145
+ } catch (error) {
5146
+ discardStudioStagingDir(stagingDir);
5147
+ throw error;
5148
+ }
4861
5149
  saveVersionOverride(version);
4862
5150
  console.log(`Electron app v${version} installed to ${versionDir}`);
4863
5151
  logger7.info("Upgrade complete", { version, path: versionDir });