@mthines/reaper-mcp 0.78.1 → 0.79.0-beta.96.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.js CHANGED
@@ -164,7 +164,30 @@ var ALLOWED_SPAN_ATTRIBUTES = /* @__PURE__ */ new Set([
164
164
  "reaper.plugin.style",
165
165
  "reaper.plugin.format",
166
166
  "reaper.plugin.instrument",
167
- "reaper.plugin.params_total"
167
+ "reaper.plugin.params_total",
168
+ // write_jsfx (tools/jsfx.ts): the shape of a generated plugin as closed values and capped counts
169
+ // (outcome, sizes, version, lint finding counts). Never its name, the request, its source or any
170
+ // control label: those describe what the person is making.
171
+ "reaper.jsfx.outcome",
172
+ "reaper.jsfx.overwrite",
173
+ "reaper.jsfx.sliders",
174
+ "reaper.jsfx.widgets.core",
175
+ "reaper.jsfx.widgets.advanced",
176
+ "reaper.jsfx.size",
177
+ "reaper.jsfx.version",
178
+ "reaper.jsfx.toolkit_version",
179
+ "reaper.jsfx.lint.errors",
180
+ "reaper.jsfx.lint.warnings",
181
+ "reaper.jsfx.presets",
182
+ "reaper.jsfx.accent",
183
+ // report_plugin_build (tools/plugin-build.ts): how a /make-plugin run ended, same rule
184
+ "reaper.plugin_build.outcome",
185
+ "reaper.plugin_build.example",
186
+ "reaper.plugin_build.rounds",
187
+ "reaper.plugin_build.checks_passed",
188
+ "reaper.plugin_build.checks_failed",
189
+ "reaper.plugin_build.cleaned_up",
190
+ "reaper.plugin_build.duration_s"
168
191
  ]);
169
192
  var AnonymizingSpanExporter = class {
170
193
  constructor(inner) {
@@ -407,8 +430,8 @@ function getTraceContext() {
407
430
  return { trace_id: ctx.traceId, span_id: ctx.spanId };
408
431
  }
409
432
  var HOME_DIR = homedir2();
410
- function redactHome(text7) {
411
- return HOME_DIR && HOME_DIR !== "/" ? text7.split(HOME_DIR).join("~") : text7;
433
+ function redactHome(text8) {
434
+ return HOME_DIR && HOME_DIR !== "/" ? text8.split(HOME_DIR).join("~") : text8;
412
435
  }
413
436
  var SEVERITY = {
414
437
  debug: SeverityNumber.DEBUG,
@@ -537,6 +560,14 @@ function getArrangeItemsHistogram() {
537
560
  });
538
561
  return _arrangeItems;
539
562
  }
563
+ var _jsfxFindings = null;
564
+ function getJsfxFindingsCounter() {
565
+ _jsfxFindings ??= getMeter().createCounter("reaper.jsfx.lint.findings", {
566
+ description: "Lint findings reported by write_jsfx for generated plugins",
567
+ unit: "{finding}"
568
+ });
569
+ return _jsfxFindings;
570
+ }
540
571
  var DIAGNOSTICS_MAX_AGE_MS = 3 * 6e4;
541
572
  var _diagnostics = null;
542
573
  function updateBridgeDiagnostics(d) {
@@ -1070,7 +1101,7 @@ var PLUGIN_CATEGORIES = [
1070
1101
  var PLUGIN_STYLES = ["transparent", "character", "vintage", "modern", "surgical"];
1071
1102
  var FX_FORMATS = ["VST", "VST3", "AU", "CLAP", "JS", "LV2", "DX"];
1072
1103
  var MAX_COUNT = { batch: 20, probed: 64, questions: 20, sources: 10 };
1073
- var SCRATCH_TRACK = /^\[MCP\] plugin-research (\S.*)$/;
1104
+ var SCRATCH_TRACK = /^\[MCP\] (?:plugin-research|make-plugin) (\S.*)$/;
1074
1105
  var MAX_RUN_MS = 2 * 60 * 60 * 1e3;
1075
1106
  var MAX_OPEN_RUNS = 50;
1076
1107
  var runStarts = /* @__PURE__ */ new Map();
@@ -3626,10 +3657,10 @@ function recordEdit(command2, args, data) {
3626
3657
  const d = data ?? {};
3627
3658
  const operation = command2 === "process_items" ? String(args["operation"]) : OPERATION[command2];
3628
3659
  const items = itemsChanged(command2, args, d);
3629
- const num2 = (k) => typeof d[k] === "number" ? d[k] : void 0;
3630
- const start = num2("start");
3631
- const end = num2("end");
3632
- const length = num2("length") ?? num2("span") ?? (start !== void 0 && end !== void 0 ? end - start : void 0);
3660
+ const num3 = (k) => typeof d[k] === "number" ? d[k] : void 0;
3661
+ const start = num3("start");
3662
+ const end = num3("end");
3663
+ const length = num3("length") ?? num3("span") ?? (start !== void 0 && end !== void 0 ? end - start : void 0);
3633
3664
  trace4.getActiveSpan()?.setAttributes({
3634
3665
  "reaper.arrange.operation": operation,
3635
3666
  "reaper.arrange.items_changed": items,
@@ -4167,6 +4198,11 @@ var TOOL_CATEGORIES = {
4167
4198
  name: "knowledge",
4168
4199
  description: "Built-in mix knowledge (read-only, curated in LoreKit): list/search plugin records and mixing lessons, read one by key. The user's own LoreKit layer (user:: keys) overrides it. report_plugin_research ends a plugin research run.",
4169
4200
  tools: ["list_builtin_knowledge", "get_builtin_knowledge", "report_plugin_research"]
4201
+ },
4202
+ plugin_authoring: {
4203
+ name: "plugin_authoring",
4204
+ description: "Make a plugin for the user (/make-plugin): write_jsfx writes a self-contained JSFX plugin with the shared UI toolkit into Effects/reaper-mcp-generated/ (linted first, an existing slider is never renumbered); report_plugin_build ends a run. Load, parameter reads and checks use the fx and analysis tools.",
4205
+ tools: ["write_jsfx", "report_plugin_build"]
4170
4206
  }
4171
4207
  };
4172
4208
  function registerExtensionCategory(extension, description, tools) {
@@ -4399,6 +4435,7 @@ var REAPER_ASSETS = [
4399
4435
  "mcp_crest_factor.jsfx",
4400
4436
  "mcp_midi_emitter.jsfx",
4401
4437
  "mcp_gain_trace.jsfx",
4438
+ "mcp_ui.jsfx-inc",
4402
4439
  "mcp_snapshot_lib.lua",
4403
4440
  "mcp_plan_lib.lua",
4404
4441
  "mcp_actions_lib.lua",
@@ -4489,15 +4526,15 @@ function ensureBridgeAutostart(startup) {
4489
4526
  const lines = startup.split(/\r?\n/);
4490
4527
  const begin = lines.indexOf(AUTOSTART_BEGIN);
4491
4528
  const end = begin === -1 ? -1 : lines.indexOf(AUTOSTART_END, begin);
4492
- let text7;
4529
+ let text8;
4493
4530
  if (begin !== -1 && end !== -1) {
4494
- text7 = [...lines.slice(0, begin), ...AUTOSTART_BLOCK, ...lines.slice(end + 1)].join(eol);
4531
+ text8 = [...lines.slice(0, begin), ...AUTOSTART_BLOCK, ...lines.slice(end + 1)].join(eol);
4495
4532
  } else if (startup.trim() === "") {
4496
- text7 = block + eol;
4533
+ text8 = block + eol;
4497
4534
  } else {
4498
- text7 = block + eol + eol + startup;
4535
+ text8 = block + eol + eol + startup;
4499
4536
  }
4500
- return { text: text7, changed: text7 !== startup };
4537
+ return { text: text8, changed: text8 !== startup };
4501
4538
  }
4502
4539
  function readExtState(ini, section, key) {
4503
4540
  let inSection = false;
@@ -4749,7 +4786,9 @@ var MCP_TOOL_NAMES = [
4749
4786
  "list_builtin_knowledge",
4750
4787
  "get_builtin_knowledge",
4751
4788
  // plugin research runs → usage telemetry (TS-only, no bridge command)
4752
- "report_plugin_research"
4789
+ "report_plugin_research",
4790
+ "write_jsfx",
4791
+ "report_plugin_build"
4753
4792
  // Note: 'render_track_to_wav', 'render_tracks_to_wav', 'remove_mcp_meters' (measure_tracks cleanup), 'insert_stem_tracks'
4754
4793
  // (the insertTracks option of separate_stems) and 'get_fx_state' / 'set_fx_state' / 'extension_call'
4755
4794
  // (extension plumbing) are internal
@@ -5524,7 +5563,7 @@ function offlineSummary(name, result) {
5524
5563
  const loud = obj(result["loudness"]);
5525
5564
  const spec = obj(result["spectrum"]);
5526
5565
  const ref = result["reference"] ? obj(result["reference"]) : null;
5527
- const sections2 = Array.isArray(loud["sections"]) ? loud["sections"] : [];
5566
+ const sections3 = Array.isArray(loud["sections"]) ? loud["sections"] : [];
5528
5567
  const resonances = Array.isArray(spec["resonances"]) ? spec["resonances"] : [];
5529
5568
  const bandsOf = (b) => BANDS.map((k) => num(obj(b)[k]) ?? null);
5530
5569
  return {
@@ -5535,7 +5574,7 @@ function offlineSummary(name, result) {
5535
5574
  peak: num(loud["samplePeakDbfs"]),
5536
5575
  crest: num(loud["crestFactorDb"]),
5537
5576
  dur: num(loud["durationSeconds"]),
5538
- sections: sections2.slice(0, MAX_SECTIONS).flatMap((s) => {
5577
+ sections: sections3.slice(0, MAX_SECTIONS).flatMap((s) => {
5539
5578
  const [a, b, l] = [num(s["start"]), num(s["end"]), num(s["lufs"])];
5540
5579
  return a !== void 0 && b !== void 0 && l !== void 0 ? [[a, b, l]] : [];
5541
5580
  }),
@@ -6588,7 +6627,7 @@ import { z as z31 } from "zod/v4";
6588
6627
  import { trace as trace6 } from "@opentelemetry/api";
6589
6628
  var SIDECAR_NOT_INSTALLED_MSG5 = `Audio understanding sidecar not installed. ${SETUP_SIDECAR_HINT}`;
6590
6629
  var MAX_QUANTIZE_SECONDS = 900;
6591
- var error4 = (text7) => ({ content: [{ type: "text", text: `Error: ${text7}` }], isError: true });
6630
+ var error4 = (text8) => ({ content: [{ type: "text", text: `Error: ${text8}` }], isError: true });
6592
6631
  var ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
6593
6632
  async function run3(command2, params, timeoutMs) {
6594
6633
  const res = await sendCommand(command2, params, timeoutMs);
@@ -6935,7 +6974,7 @@ function buildPairs(guideHits, doubleHits, g, opts) {
6935
6974
  // apps/reaper-mcp-server/src/tools/align.ts
6936
6975
  var SIDECAR_NOT_INSTALLED_MSG6 = `Audio understanding sidecar not installed. ${SETUP_SIDECAR_HINT}`;
6937
6976
  var MAX_ALIGN_SECONDS = 900;
6938
- var error5 = (text7) => ({ content: [{ type: "text", text: `Error: ${text7}` }], isError: true });
6977
+ var error5 = (text8) => ({ content: [{ type: "text", text: `Error: ${text8}` }], isError: true });
6939
6978
  var ok2 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
6940
6979
  var itemRef = z32.object({
6941
6980
  trackIndex: z32.coerce.number().int().min(0),
@@ -7087,15 +7126,15 @@ function pearson(a, b) {
7087
7126
  const n = a.length;
7088
7127
  const ma = a.reduce((s, x) => s + x, 0) / n;
7089
7128
  const mb = b.reduce((s, x) => s + x, 0) / n;
7090
- let num2 = 0;
7129
+ let num3 = 0;
7091
7130
  let da = 0;
7092
7131
  let db = 0;
7093
7132
  for (let i = 0; i < n; i++) {
7094
- num2 += (a[i] - ma) * (b[i] - mb);
7133
+ num3 += (a[i] - ma) * (b[i] - mb);
7095
7134
  da += (a[i] - ma) ** 2;
7096
7135
  db += (b[i] - mb) ** 2;
7097
7136
  }
7098
- return da > 0 && db > 0 ? num2 / Math.sqrt(da * db) : 0;
7137
+ return da > 0 && db > 0 ? num3 / Math.sqrt(da * db) : 0;
7099
7138
  }
7100
7139
  var keyName = (tonic, mode) => `${PITCH_CLASSES[tonic]} ${mode}`;
7101
7140
  function rankKeys(profile) {
@@ -8087,7 +8126,7 @@ function arrangeVoiceSketch(source, options) {
8087
8126
  }
8088
8127
  const edgeBars = bars >= 8 ? 2 : 1;
8089
8128
  const chorusBar = Math.floor(bars / 2);
8090
- const sections2 = [
8129
+ const sections3 = [
8091
8130
  { name: "intro", startBar: 1, bars: edgeBars },
8092
8131
  { name: "verse", startBar: edgeBars + 1, bars: chorusBar - edgeBars },
8093
8132
  { name: "chorus", startBar: chorusBar + 1, bars: bars - edgeBars - chorusBar },
@@ -8172,7 +8211,7 @@ function arrangeVoiceSketch(source, options) {
8172
8211
  motifBars: motifBeats / 4,
8173
8212
  key: `${key.tonic} ${key.mode}`,
8174
8213
  keySource,
8175
- sections: sections2,
8214
+ sections: sections3,
8176
8215
  chords,
8177
8216
  tempos,
8178
8217
  durationSeconds: secondsAtBeat(length, tempos),
@@ -8367,9 +8406,9 @@ async function callLoreKit(tool, args) {
8367
8406
  if (!res.ok) throw new Error(`LoreKit HTTP ${res.status}`);
8368
8407
  const body = await res.json();
8369
8408
  if (body.error) throw new Error(`LoreKit: ${body.error.message ?? "unknown error"}`);
8370
- const text7 = body.result?.content?.[0]?.text ?? "null";
8371
- if (body.result?.isError) throw new Error(`LoreKit: ${text7}`);
8372
- const data = JSON.parse(text7);
8409
+ const text8 = body.result?.content?.[0]?.text ?? "null";
8410
+ if (body.result?.isError) throw new Error(`LoreKit: ${text8}`);
8411
+ const data = JSON.parse(text8);
8373
8412
  cache.set(cacheKey, { expires: Date.now() + CACHE_TTL_MS, data });
8374
8413
  return data;
8375
8414
  }
@@ -8435,6 +8474,699 @@ function registerKnowledgeTools(server) {
8435
8474
  );
8436
8475
  }
8437
8476
 
8477
+ // apps/reaper-mcp-server/src/tools/jsfx.ts
8478
+ import { z as z36 } from "zod/v4";
8479
+ import { trace as trace9 } from "@opentelemetry/api";
8480
+ import { copyFileSync as copyFileSync3, existsSync as existsSync5, mkdirSync as mkdirSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "node:fs";
8481
+ import { homedir as homedir7 } from "node:os";
8482
+ import { dirname as dirname6, join as join9 } from "node:path";
8483
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
8484
+
8485
+ // apps/reaper-mcp-server/src/jsfx/accent.ts
8486
+ var L = 0.78;
8487
+ var C = 0.13;
8488
+ var SEMANTIC = ["#4ade80", "#f5b84b", "#f87171"];
8489
+ var AVOID = 22;
8490
+ var toLinear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
8491
+ var fromLinear = (c) => c <= 31308e-7 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
8492
+ function hexToRgb(hex) {
8493
+ const n = parseInt(hex.slice(1), 16);
8494
+ return [n >> 16 & 255, n >> 8 & 255, n & 255].map((v) => v / 255);
8495
+ }
8496
+ function rgbToHex(rgb) {
8497
+ return "#" + rgb.map((v) => Math.round(Math.min(1, Math.max(0, v)) * 255).toString(16).padStart(2, "0")).join("");
8498
+ }
8499
+ function oklchToLinear(l, c, h) {
8500
+ const a = c * Math.cos(h * Math.PI / 180);
8501
+ const b = c * Math.sin(h * Math.PI / 180);
8502
+ const l_ = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3;
8503
+ const m_ = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3;
8504
+ const s_ = (l - 0.0894841775 * a - 1.291485548 * b) ** 3;
8505
+ return [
8506
+ 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,
8507
+ -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,
8508
+ -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_
8509
+ ];
8510
+ }
8511
+ function hueOf(hex) {
8512
+ const [r, g, b] = hexToRgb(hex).map(toLinear);
8513
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
8514
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
8515
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
8516
+ const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
8517
+ const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
8518
+ return (Math.atan2(bb, a) * 180 / Math.PI + 360) % 360;
8519
+ }
8520
+ function accentForHue(h) {
8521
+ for (let c = C; c > 0; c -= 5e-3) {
8522
+ const lin = oklchToLinear(L, c, h);
8523
+ if (lin.every((v) => v >= -5e-4 && v <= 1.0005)) return rgbToHex(lin.map(fromLinear));
8524
+ }
8525
+ return rgbToHex(oklchToLinear(L, 0, h).map(fromLinear));
8526
+ }
8527
+ var NAMED_ACCENTS = Object.freeze({
8528
+ blue: "#7cc4ff",
8529
+ // the bridge page's own accent
8530
+ teal: accentForHue(195),
8531
+ green: accentForHue(150),
8532
+ amber: accentForHue(80),
8533
+ orange: accentForHue(55),
8534
+ red: accentForHue(25),
8535
+ pink: accentForHue(350),
8536
+ violet: accentForHue(300)
8537
+ });
8538
+ var ALLOWED_HUES = (() => {
8539
+ const semantic = SEMANTIC.map(hueOf);
8540
+ const out2 = [];
8541
+ for (let h = 0; h < 360; h++) {
8542
+ if (semantic.every((s) => Math.min(Math.abs(h - s), 360 - Math.abs(h - s)) > AVOID)) out2.push(h);
8543
+ }
8544
+ return out2;
8545
+ })();
8546
+ function fnv1a(text8) {
8547
+ let h = 2166136261;
8548
+ for (const ch of text8) {
8549
+ h ^= ch.codePointAt(0) ?? 0;
8550
+ h = Math.imul(h, 16777619) >>> 0;
8551
+ }
8552
+ return h;
8553
+ }
8554
+ function slugAccent(slug) {
8555
+ return accentForHue(ALLOWED_HUES[fnv1a(slug) % ALLOWED_HUES.length]);
8556
+ }
8557
+ function parseAccent(input) {
8558
+ const v = input.trim().toLowerCase();
8559
+ if (v === "" || v === "auto") return { kind: "auto" };
8560
+ if (NAMED_ACCENTS[v]) return { token: v, kind: "named" };
8561
+ if (/^#[0-9a-f]{6}$/.test(v)) return { token: v, kind: "custom" };
8562
+ return { error: `accent "${input}" is neither "auto", a name (${Object.keys(NAMED_ACCENTS).join(", ")}) nor a #rrggbb colour` };
8563
+ }
8564
+ function resolveAccent(slug, token) {
8565
+ const parsed = token ? parseAccent(token) : { kind: "auto" };
8566
+ if ("error" in parsed || parsed.kind === "auto" || !parsed.token) return { hex: slugAccent(slug), kind: "auto" };
8567
+ return parsed.kind === "named" ? { hex: NAMED_ACCENTS[parsed.token], kind: "named", token: parsed.token } : { hex: parsed.token, kind: "custom", token: parsed.token };
8568
+ }
8569
+ function readAccentToken(text8) {
8570
+ const m = text8.match(/^\/\/ accent: *(\S+)/m);
8571
+ if (!m) return void 0;
8572
+ const parsed = parseAccent(m[1]);
8573
+ return "error" in parsed ? void 0 : parsed.token;
8574
+ }
8575
+
8576
+ // apps/reaper-mcp-server/src/jsfx/inline.ts
8577
+ var TOOLKIT_FILE = "mcp_ui.jsfx-inc";
8578
+ var DEVELOPER_SUFFIX = " (reaper-mcp)";
8579
+ var MAX_USER_SLIDERS = 32;
8580
+ var BLOCK_START = "// ---- mcp_ui ";
8581
+ var BLOCK_END = "// ---- end mcp_ui ----";
8582
+ var OWN_LINE = /^\s*(import\s+mcp_ui\.jsfx-inc|tags:reaper-mcp-generated)\s*$/;
8583
+ var GENERATED_COMMENT = /^\/\/ (generated by reaper-mcp|version:|toolkit:|request:|accent:)/;
8584
+ var SLIDER_LINE = /^slider(\d+):(?:([A-Za-z_]\w*)=)?\s*(-?[\d.]+)\s*<\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*(?:,\s*(-?[\d.]+))?\s*(?:\{([^}]*)\})?\s*>\s*(.*)$/;
8585
+ function parseSliders(source) {
8586
+ const sliders = [];
8587
+ const bad = [];
8588
+ const lines = source.split("\n");
8589
+ for (let i = 0; i < lines.length; i++) {
8590
+ if (/^@/.test(lines[i])) break;
8591
+ if (!/^slider\d+:/.test(lines[i])) continue;
8592
+ const m = lines[i].replace(/\r$/, "").match(SLIDER_LINE);
8593
+ if (!m) {
8594
+ bad.push({ line: i + 1, text: lines[i].trim() });
8595
+ continue;
8596
+ }
8597
+ const label = m[8].trim();
8598
+ sliders.push({
8599
+ index: Number(m[1]),
8600
+ name: label.replace(/^-/, ""),
8601
+ min: Number(m[4]),
8602
+ max: Number(m[5]),
8603
+ step: m[6] === void 0 ? 0 : Number(m[6]),
8604
+ default: Number(m[3]),
8605
+ options: m[7] === void 0 ? [] : m[7].split(",").map((s) => s.trim()),
8606
+ hidden: label.startsWith("-"),
8607
+ named: m[2] !== void 0
8608
+ });
8609
+ }
8610
+ return { sliders, bad };
8611
+ }
8612
+ function num2(n) {
8613
+ return String(Number(n.toFixed(6)));
8614
+ }
8615
+ function toolkitVersion(toolkit) {
8616
+ return toolkit.match(/toolkit, v(\d+\.\d+\.\d+)/)?.[1] ?? toolkit.match(/\bv(\d+\.\d+\.\d+)/)?.[1] ?? "0.0.0";
8617
+ }
8618
+ function stripGenerated(source) {
8619
+ const out2 = [];
8620
+ let skipping = false;
8621
+ for (const line of source.replace(/\r\n/g, "\n").split("\n")) {
8622
+ if (line.startsWith(BLOCK_START)) skipping = true;
8623
+ if (!skipping && !GENERATED_COMMENT.test(line) && !OWN_LINE.test(line)) out2.push(line);
8624
+ if (skipping && line.trim() === BLOCK_END) skipping = false;
8625
+ }
8626
+ return out2.join("\n");
8627
+ }
8628
+ function plainDesc(desc) {
8629
+ let d = desc.trim();
8630
+ const suffix = DEVELOPER_SUFFIX.trim();
8631
+ while (suffix && d.toLowerCase().endsWith(suffix.toLowerCase())) d = d.slice(0, -suffix.length).trimEnd();
8632
+ return d;
8633
+ }
8634
+ function withDeveloper(desc) {
8635
+ const d = plainDesc(desc);
8636
+ return DEVELOPER_SUFFIX ? `${d}${DEVELOPER_SUFFIX}` : d;
8637
+ }
8638
+ var eelString = (s) => s.replace(/["\\\r\n]/g, "").slice(0, 60);
8639
+ function inlineToolkit(source, options) {
8640
+ const kept = readAccentToken(source);
8641
+ const lines = stripGenerated(source).split("\n");
8642
+ const first = lines.findIndex((l) => /^@/.test(l));
8643
+ const headerEnd = first === -1 ? lines.length : first;
8644
+ const header = lines.slice(0, headerEnd);
8645
+ let body = lines.slice(headerEnd);
8646
+ const descAt = header.findIndex((l) => /^desc:/.test(l));
8647
+ const name = descAt === -1 ? "Plugin" : plainDesc(header[descAt].replace(/^desc:/, ""));
8648
+ if (descAt !== -1) header[descAt] = `desc:${withDeveloper(header[descAt].replace(/^desc:/, ""))}`;
8649
+ const accent = inlineAccent(options, kept, name);
8650
+ const added = [
8651
+ ...header.some((l) => /^tags:/.test(l)) ? [] : ["tags:reaper-mcp-generated"],
8652
+ "// generated by reaper-mcp /make-plugin: edit the plugin part, never the inlined toolkit block",
8653
+ `// version: ${options.version}`,
8654
+ `// toolkit: mcp_ui ${toolkitVersion(options.toolkit)}`,
8655
+ ...accent.token ? [`// accent: ${accent.token}`] : [],
8656
+ ...options.request ? [`// request: ${options.request.replace(/[\r\n]+/g, " ").slice(0, 200)}`] : []
8657
+ ];
8658
+ header.splice(descAt + 1, 0, ...added);
8659
+ const sliders = parseSliders(header.join("\n")).sliders;
8660
+ const about = [
8661
+ `strcpy(#ui_name, "${eelString(name)}"); strcpy(#ui_date, "${eelString(options.date ?? "")}"); strcpy(#ui_tkv, "${toolkitVersion(options.toolkit)}");`,
8662
+ `ui_pver = ${Math.max(0, Math.floor(options.version))}; ui_nctl = ${sliders.length}; ui_akind = ${accent.kind === "custom" ? 2 : accent.kind === "named" ? 1 : 0}; ui_example = ${options.example ? 1 : 0};`,
8663
+ `ui_theme($x${accent.hex.slice(1)});`
8664
+ ];
8665
+ const meta = sliders.filter((s) => !s.named).flatMap((s) => [
8666
+ `ui_meta(${s.index}, ${num2(s.min)}, ${num2(s.max)}, ${num2(s.default)}, ${num2(s.step)});`,
8667
+ ...s.options.slice(0, 8).map((o, k) => `strcpy(${s.index * 8 + k}, "${o.replace(/"/g, "'")}");`)
8668
+ ]);
8669
+ const block = [
8670
+ `${BLOCK_START}${toolkitVersion(options.toolkit)} (inlined by reaper-mcp, do not edit) ----`,
8671
+ options.toolkit.replace(/\r\n/g, "\n").trimEnd(),
8672
+ ...meta,
8673
+ ...about,
8674
+ BLOCK_END
8675
+ ];
8676
+ const initAt = body.findIndex((l) => /^@init\b/.test(l));
8677
+ if (initAt === -1) body = ["@init", ...block, "", ...body];
8678
+ else body.splice(initAt + 1, 0, ...block);
8679
+ if (!body.some((l) => /^@serialize\b/.test(l))) body.push("", "@serialize", "file_var(0, ui_adv_open);");
8680
+ return [...header, ...body].join("\n").replace(/\n{3,}/g, "\n\n").replace(/\n*$/, "\n");
8681
+ }
8682
+ function inlineAccent(options, kept, name) {
8683
+ const slug = options.slug ?? name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
8684
+ const token = options.accent === void 0 ? kept : options.accent.trim().toLowerCase() === "auto" ? void 0 : options.accent;
8685
+ return resolveAccent(slug, token);
8686
+ }
8687
+ function readVersion(generated) {
8688
+ return Number(generated.match(/^\/\/ version: (\d+)/m)?.[1] ?? 0);
8689
+ }
8690
+
8691
+ // apps/reaper-mcp-server/src/jsfx/lint.ts
8692
+ var MAX_CORE_WIDGETS = 5;
8693
+ var MAX_ADVANCED_WIDGETS = 8;
8694
+ var MAX_FILE_BYTES = 64 * 1024;
8695
+ function stripComments(source) {
8696
+ return source.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/\/\/[^\n]*/g, (m) => " ".repeat(m.length));
8697
+ }
8698
+ function wrongMinMaxCalls(code) {
8699
+ const out2 = [];
8700
+ for (const m of code.matchAll(/\b(?:max|min)\s*\(/g)) {
8701
+ let depth = 1;
8702
+ let count = 1;
8703
+ for (let i = (m.index ?? 0) + m[0].length; i < code.length && depth > 0; i++) {
8704
+ const ch = code[i];
8705
+ if (ch === "(") depth++;
8706
+ else if (ch === ")") depth--;
8707
+ else if (ch === "," && depth === 1) count++;
8708
+ }
8709
+ if (count !== 2) out2.push({ at: m.index ?? 0, count });
8710
+ }
8711
+ return out2;
8712
+ }
8713
+ function sections2(code) {
8714
+ const out2 = /* @__PURE__ */ new Map();
8715
+ let name = "header";
8716
+ let line = 1;
8717
+ let buf = [];
8718
+ code.split("\n").forEach((l, i) => {
8719
+ const m = l.match(/^@(init|slider|block|sample|gfx|serialize)\b/);
8720
+ if (m) {
8721
+ out2.set(name, { text: buf.join("\n"), line });
8722
+ name = m[1];
8723
+ line = i + 1;
8724
+ buf = [];
8725
+ } else buf.push(l);
8726
+ });
8727
+ out2.set(name, { text: buf.join("\n"), line });
8728
+ return out2;
8729
+ }
8730
+ var WIDGET = /\bui_(knob|toggle|choice)\s*\(\s*(\d+)/g;
8731
+ var METER = /\bui_meter\s*\(/g;
8732
+ function lintJsfx(source) {
8733
+ const findings = [];
8734
+ const add2 = (rule, severity, message, line) => findings.push({ rule, severity, message, ...line ? { line } : {} });
8735
+ const code = stripComments(source.replace(/\r\n/g, "\n"));
8736
+ const secs = sections2(code);
8737
+ const lineOf = (index) => code.slice(0, index).split("\n").length;
8738
+ if (Buffer.byteLength(source) > MAX_FILE_BYTES) add2("file-size", "warning", `The source is over ${MAX_FILE_BYTES / 1024} KB: a generated plugin should be much smaller.`);
8739
+ if (!/^desc:\s*\S/m.test(source)) add2("no-desc", "error", 'Missing "desc:Name" line: REAPER lists the plugin by it.');
8740
+ const { sliders, bad } = parseSliders(source);
8741
+ for (const b of bad) add2("bad-slider", "error", `Slider line does not parse: "${b.text}". Use sliderN:default<min,max,step>Label (or {A,B,C} for options).`, b.line);
8742
+ const seen = /* @__PURE__ */ new Set();
8743
+ for (const s of sliders) {
8744
+ if (seen.has(s.index)) add2("duplicate-slider", "error", `slider${s.index} is declared twice.`);
8745
+ seen.add(s.index);
8746
+ if (s.index < 1 || s.index > MAX_USER_SLIDERS) add2("slider-limit", "error", `slider${s.index}: use slider1..slider${MAX_USER_SLIDERS}.`);
8747
+ if (s.named) add2("named-slider", "error", `slider${s.index} is named: the toolkit reads sliders by number, and a named slider's sliderN stays 0. Declare it unnamed (slider${s.index}:${s.default}<...>) and read slider${s.index}.`);
8748
+ if (s.default < Math.min(s.min, s.max) || s.default > Math.max(s.min, s.max)) add2("default-out-of-range", "error", `slider${s.index}: default ${s.default} is outside ${s.min}..${s.max}.`);
8749
+ }
8750
+ for (const m of code.matchAll(/(?<![\w.])\d+(?:\.\d+)?[eE][+-]?\d+(?![\w.])/g)) {
8751
+ add2("science-literal", "error", `Literal ${m[0]}: EEL2 rejects scientific notation and the whole plugin then fails to compile. Write it out (0.000001).`, lineOf(m.index ?? 0));
8752
+ }
8753
+ for (const name of ["sample", "block"]) {
8754
+ const sec = secs.get(name);
8755
+ sec?.text.split("\n").forEach((l, i) => {
8756
+ if (/^\s*local\s*\(/i.test(l)) add2("local-top-level", "error", `local() at the top level of @${name} fails to compile: use plain variables, or local() inside a function.`, sec.line + i + 1);
8757
+ });
8758
+ }
8759
+ if (/\boptions:[^\n]*\bgmem\b/.test(code)) add2("gmem", "error", "No gmem: a generated plugin must not depend on the bridge or on other plugins.");
8760
+ const gfx = secs.get("gfx");
8761
+ if (!gfx || !/\S/.test(gfx.text)) add2("no-gfx", "error", "No @gfx section: every generated plugin draws its UI with the toolkit.");
8762
+ else {
8763
+ if (!/\bui_begin\s*\(/.test(gfx.text)) add2("no-ui-begin", "error", "@gfx must call ui_begin(core_rows, adv_rows) and draw inside it.", gfx.line);
8764
+ const at = gfx.text.search(/\bui_section\s*\(/);
8765
+ const core2 = at === -1 ? gfx.text : gfx.text.slice(0, at);
8766
+ const adv = at === -1 ? "" : gfx.text.slice(at);
8767
+ const widgets = (t) => [...t.matchAll(WIDGET)].length + [...t.matchAll(METER)].length;
8768
+ if (widgets(core2) > MAX_CORE_WIDGETS) add2("core-overflow", "error", `${widgets(core2)} widgets before the first ui_section (max ${MAX_CORE_WIDGETS}): keep the core view to what is changed in most uses and move the rest behind ui_section("Advanced").`, gfx.line);
8769
+ if (widgets(adv) > MAX_ADVANCED_WIDGETS) add2("advanced-overflow", "warning", `${widgets(adv)} advanced widgets (max ${MAX_ADVANCED_WIDGETS}): does every one earn its place?`, gfx.line);
8770
+ const byIndex = new Map(sliders.map((s) => [s.index, s]));
8771
+ const used = /* @__PURE__ */ new Set();
8772
+ for (const m of gfx.text.matchAll(WIDGET)) {
8773
+ const idx = Number(m[2]);
8774
+ used.add(idx);
8775
+ if (!byIndex.has(idx)) add2("widget-unknown-slider", "error", `ui_${m[1]}(${idx}, ...) points at slider${idx}, which is not declared.`, gfx.line + gfx.text.slice(0, m.index).split("\n").length);
8776
+ }
8777
+ for (const s of sliders) {
8778
+ if (!s.hidden && !used.has(s.index)) add2("slider-without-widget", "error", `slider${s.index} "${s.name}" has no widget in @gfx. Draw it, or hide it with a leading "-" in its label.`);
8779
+ }
8780
+ }
8781
+ const init2 = secs.get("init")?.text ?? "";
8782
+ if (!/\bui_boot\s*\(/.test(init2)) add2("no-ui-boot", "error", "@init must call ui_boot(animated) after the plugin's own setup (animated = 1 when the UI has a meter).");
8783
+ if (!/\bui_changed\s*\(/.test(secs.get("block")?.text ?? "") && !/\bui_changed\s*\(/.test(secs.get("sample")?.text ?? "")) {
8784
+ add2("no-changed", "error", "@block must call ui_changed() ? update(); so a knob moved in @gfx reaches the DSP.");
8785
+ }
8786
+ const ser = secs.get("serialize");
8787
+ if (ser && !/\bfile_var\s*\(\s*0\s*,\s*ui_adv_open\s*\)/.test(ser.text)) add2("no-serialize", "error", "The @serialize section must start with file_var(0, ui_adv_open); so the Advanced section keeps its state.", ser.line);
8788
+ for (const m of code.matchAll(/\bui_adv_open\s*=(?!=)/g)) {
8789
+ add2("ui-state-reset", "warning", "The plugin assigns ui_adv_open: REAPER re-runs @init (and this code) when playback starts, so the Advanced drawer would snap shut on Play. Leave it to the toolkit; @serialize restores it with file_var(0, ui_adv_open).", lineOf(m.index ?? 0));
8790
+ }
8791
+ for (const m of code.matchAll(/\bui_cAccent\s*=(?!=)|\bui_theme\s*\(/g)) {
8792
+ add2("accent-assign", "warning", 'The plugin sets the accent itself: write_jsfx sets it (pass accent: "orange" or "#rrggbb" and keep the source as it is). Plugin code that assigns ui_cAccent or calls ui_theme() is overridden on the next write.', lineOf(m.index ?? 0));
8793
+ }
8794
+ for (const m of code.matchAll(/\bgfx_getchar\s*\(/g)) {
8795
+ add2("own-key-handling", "warning", "The plugin reads the keyboard (gfx_getchar): the toolkit does that while a value box is open, so typed values would go missing. Leave keyboard and mouse handling to the toolkit.", lineOf(m.index ?? 0));
8796
+ }
8797
+ for (const c of wrongMinMaxCalls(code)) {
8798
+ add2("two-arg-minmax", "error", `max/min take exactly two arguments, this call has ${c.count}: REAPER would fail to compile the whole plugin and pass the audio through. Nest them: max(max(a, b), c).`, lineOf(c.at));
8799
+ }
8800
+ const sample = secs.get("sample");
8801
+ if (sample) {
8802
+ if (/\b(while|loop)\s*\(/.test(sample.text)) add2("sample-loop", "warning", "A loop in @sample runs per sample: move it to @init/@block, or keep it to a few iterations.", sample.line);
8803
+ if (/\b(memset|memcpy)\s*\(/.test(sample.text)) add2("sample-memset", "warning", "memset/memcpy in @sample runs per sample: clear buffers in @init or when a parameter changes.", sample.line);
8804
+ if (/\/=?\s*srate\b/.test(sample.text)) add2("sample-divide-srate", "warning", "Dividing by srate per sample: compute the coefficient in update() once.", sample.line);
8805
+ }
8806
+ for (const m of code.matchAll(/\b(?:buf|mem|memory)\w*\s*=\s*(\d+)\s*;/g)) {
8807
+ if (Number(m[1]) < 1024) add2("low-memory-index", "warning", `A buffer starts at index ${m[1]}: memory below ui_mem (1024) is reserved for the toolkit. Allocate from ui_mem.`, lineOf(m.index ?? 0));
8808
+ }
8809
+ return findings;
8810
+ }
8811
+ var errorsOf = (f) => f.filter((x) => x.severity === "error");
8812
+ var warningsOf = (f) => f.filter((x) => x.severity === "warning");
8813
+ function widgetCounts(source) {
8814
+ const gfx = sections2(stripComments(source.replace(/\r\n/g, "\n"))).get("gfx")?.text ?? "";
8815
+ const at = gfx.search(/\bui_section\s*\(/);
8816
+ const count = (t) => [...t.matchAll(WIDGET)].length + [...t.matchAll(METER)].length;
8817
+ return { core: count(at === -1 ? gfx : gfx.slice(0, at)), advanced: at === -1 ? 0 : count(gfx.slice(at)) };
8818
+ }
8819
+
8820
+ // apps/reaper-mcp-server/src/jsfx/presets.ts
8821
+ import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
8822
+ import { dirname as dirname5, join as join8 } from "node:path";
8823
+ var MAX_PRESETS = 8;
8824
+ var MAX_PRESET_NAME = 32;
8825
+ var JSFX_SLIDERS = 64;
8826
+ function presetFileName(effectPath) {
8827
+ return `js-${effectPath.replace(/[/\\.]/g, "_")}.ini`;
8828
+ }
8829
+ function onStep(s, v) {
8830
+ if (!(s.step > 0)) return true;
8831
+ const k = (v - s.min) / s.step;
8832
+ return Math.abs(k - Math.round(k)) < 1e-4;
8833
+ }
8834
+ function resolvePresets(presets, sliders) {
8835
+ const errors = [];
8836
+ const values = [];
8837
+ if (presets.length > MAX_PRESETS) errors.push(`${presets.length} presets: at most ${MAX_PRESETS}. Keep the few that teach the plugin.`);
8838
+ const names = /* @__PURE__ */ new Set();
8839
+ for (const p of presets) {
8840
+ const name = p.name.trim();
8841
+ if (!name || name.length > MAX_PRESET_NAME) errors.push(`Preset name "${p.name}": 1-${MAX_PRESET_NAME} characters.`);
8842
+ if (/["\r\n\t|]/.test(name)) errors.push(`Preset name "${p.name}": no quotes, tabs, line breaks or "|".`);
8843
+ if (names.has(name.toLowerCase())) errors.push(`Preset "${name}" is listed twice.`);
8844
+ names.add(name.toLowerCase());
8845
+ const set = new Map(sliders.filter((s) => !s.named).map((s) => [s.index, s.default]));
8846
+ for (const [key, v] of Object.entries(p.values)) {
8847
+ const m = key.trim().match(/^(?:slider)?(\d+)$/i);
8848
+ const s = m ? sliders.find((x) => x.index === Number(m[1])) : sliders.find((x) => x.name.toLowerCase() === key.trim().toLowerCase());
8849
+ if (!s) {
8850
+ errors.push(`Preset "${name}": no slider "${key}".`);
8851
+ continue;
8852
+ }
8853
+ const lo = Math.min(s.min, s.max), hi = Math.max(s.min, s.max);
8854
+ if (typeof v !== "number" || !Number.isFinite(v)) errors.push(`Preset "${name}": ${s.name} = ${String(v)} is not a number.`);
8855
+ else if (v < lo || v > hi) errors.push(`Preset "${name}": ${s.name} = ${v} is outside ${s.min}..${s.max}.`);
8856
+ else if (!onStep(s, v)) errors.push(`Preset "${name}": ${s.name} = ${v} is not on its step of ${s.step}.`);
8857
+ else set.set(s.index, v);
8858
+ }
8859
+ values.push(set);
8860
+ }
8861
+ return { values, errors };
8862
+ }
8863
+ function encodePreset(name, values) {
8864
+ const fields = [];
8865
+ for (let i = 1; i <= JSFX_SLIDERS; i++) fields.push(values.has(i) ? values.get(i).toFixed(6) : "-");
8866
+ const bytes = Buffer.from(`${fields.join(" ")} "${name}"`, "utf8");
8867
+ let sum = 0;
8868
+ for (const b of bytes) sum = sum + b & 255;
8869
+ return { name, data: bytes.toString("hex").toUpperCase() + sum.toString(16).toUpperCase().padStart(2, "0"), len: bytes.length };
8870
+ }
8871
+ function parsePresetFile(text8) {
8872
+ const out2 = [];
8873
+ let cur;
8874
+ const flush = () => {
8875
+ if (cur?.name !== void 0 && cur.data) out2.push({ name: cur.name, data: cur.data, len: cur.len ?? 0 });
8876
+ };
8877
+ for (const raw of text8.replace(/\r\n/g, "\n").split("\n")) {
8878
+ const line = raw.trim();
8879
+ if (/^\[Preset\d+\]$/i.test(line)) {
8880
+ flush();
8881
+ cur = {};
8882
+ continue;
8883
+ }
8884
+ if (/^\[/.test(line)) {
8885
+ flush();
8886
+ cur = void 0;
8887
+ continue;
8888
+ }
8889
+ if (!cur) continue;
8890
+ const eq = line.indexOf("=");
8891
+ if (eq < 0) continue;
8892
+ const k = line.slice(0, eq), v = line.slice(eq + 1);
8893
+ if (k === "Data") cur.data = v;
8894
+ else if (k === "Len") cur.len = Number(v);
8895
+ else if (k === "Name") cur.name = v;
8896
+ }
8897
+ flush();
8898
+ return out2;
8899
+ }
8900
+ function formatPresetFile(presets) {
8901
+ const lines = ["[General]", `NbPresets=${presets.length}`, ""];
8902
+ presets.forEach((p, k) => lines.push(`[Preset${k}]`, `Data=${p.data}`, `Len=${p.len}`, `Name=${p.name}`, ""));
8903
+ return lines.join("\n");
8904
+ }
8905
+ function mergePresets(existing, ours, owned) {
8906
+ const current = existing ? parsePresetFile(existing) : [];
8907
+ const keptUserEdits = [];
8908
+ const theirs = current.filter((p) => {
8909
+ if (!(p.name in owned)) return true;
8910
+ if (owned[p.name] === p.data) return false;
8911
+ keptUserEdits.push(p.name);
8912
+ return true;
8913
+ });
8914
+ const taken = new Set(theirs.map((p) => p.name));
8915
+ const add2 = ours.filter((p) => !taken.has(p.name));
8916
+ return { text: formatPresetFile([...theirs, ...add2]), written: add2.map((p) => p.name), keptUserEdits };
8917
+ }
8918
+ function writePresetFile(presetsDir2, effectPath, encoded, manifestPath) {
8919
+ const file = join8(presetsDir2, presetFileName(effectPath));
8920
+ let owned = {};
8921
+ try {
8922
+ owned = JSON.parse(readFileSync4(manifestPath, "utf8")).owned ?? {};
8923
+ } catch {
8924
+ }
8925
+ const merged = mergePresets(existsSync4(file) ? readFileSync4(file, "utf8") : void 0, encoded, owned);
8926
+ mkdirSync5(presetsDir2, { recursive: true });
8927
+ writeFileSync4(file, merged.text);
8928
+ mkdirSync5(dirname5(manifestPath), { recursive: true });
8929
+ const mine = Object.fromEntries(encoded.filter((p) => merged.written.includes(p.name)).map((p) => [p.name, p.data]));
8930
+ writeFileSync4(manifestPath, JSON.stringify({ owned: mine }, null, 2));
8931
+ return { file, written: merged.written, keptUserEdits: merged.keptUserEdits };
8932
+ }
8933
+
8934
+ // apps/reaper-mcp-server/src/tools/jsfx.ts
8935
+ var GENERATED_DIR = "reaper-mcp-generated";
8936
+ var MAX_SOURCE = 128 * 1024;
8937
+ var MAX_VERSION = 20;
8938
+ function slugify(name) {
8939
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
8940
+ }
8941
+ function generatedDir() {
8942
+ return join9(getReaperEffectsPath(), GENERATED_DIR);
8943
+ }
8944
+ function presetsDir() {
8945
+ return join9(dirname6(getReaperEffectsPath()), "presets");
8946
+ }
8947
+ function historyDir(slug) {
8948
+ return join9(process.env.REAPER_MCP_CONFIG_DIR || join9(homedir7(), ".config", "reaper-mcp"), "jsfx-history", slug);
8949
+ }
8950
+ var _toolkit;
8951
+ function loadToolkit() {
8952
+ if (_toolkit) return _toolkit;
8953
+ const dir = resolveAssetDir(dirname6(fileURLToPath4(import.meta.url)), "reaper");
8954
+ _toolkit = readFileSync5(join9(dir, TOOLKIT_FILE), "utf8");
8955
+ return _toolkit;
8956
+ }
8957
+ function sizeBucket(bytes) {
8958
+ const kb = bytes / 1024;
8959
+ return kb < 8 ? "<8k" : kb < 16 ? "8-16k" : kb < 32 ? "16-32k" : kb < 64 ? "32-64k" : "64k+";
8960
+ }
8961
+ function shapeAttributes(s) {
8962
+ const cap = (n, max) => Math.min(Math.max(0, Math.floor(n)), max);
8963
+ return {
8964
+ "reaper.jsfx.outcome": s.outcome,
8965
+ "reaper.jsfx.overwrite": s.overwrite,
8966
+ ...s.sliders !== void 0 ? { "reaper.jsfx.sliders": cap(s.sliders, MAX_USER_SLIDERS) } : {},
8967
+ ...s.widgets ? { "reaper.jsfx.widgets.core": cap(s.widgets.core, 16), "reaper.jsfx.widgets.advanced": cap(s.widgets.advanced, 16) } : {},
8968
+ ...s.bytes !== void 0 ? { "reaper.jsfx.size": sizeBucket(s.bytes) } : {},
8969
+ ...s.version !== void 0 ? { "reaper.jsfx.version": cap(s.version, MAX_VERSION) } : {},
8970
+ ...s.toolkit ? { "reaper.jsfx.toolkit_version": s.toolkit } : {},
8971
+ ...s.presets !== void 0 ? { "reaper.jsfx.presets": cap(s.presets, MAX_PRESETS) } : {},
8972
+ ...s.accent ? { "reaper.jsfx.accent": s.accent } : {},
8973
+ ...s.findings ? { "reaper.jsfx.lint.errors": cap(errorsOf(s.findings).length, 20), "reaper.jsfx.lint.warnings": cap(warningsOf(s.findings).length, 20) } : {}
8974
+ };
8975
+ }
8976
+ function record(shape2) {
8977
+ trace9.getActiveSpan()?.setAttributes(shapeAttributes(shape2));
8978
+ for (const f of shape2.findings ?? []) {
8979
+ getJsfxFindingsCounter().add(1, { "reaper.jsfx.lint.rule": f.rule, "reaper.jsfx.lint.severity": f.severity });
8980
+ }
8981
+ }
8982
+ function breakingChanges(before, after) {
8983
+ const out2 = [];
8984
+ for (const old of before) {
8985
+ const now = after.find((s) => s.index === old.index);
8986
+ if (!now) out2.push(`slider${old.index} "${old.name}" was removed`);
8987
+ else if (now.min !== old.min || now.max !== old.max || now.step !== old.step || now.options.length !== old.options.length || now.options.some((o, i) => o !== old.options[i])) {
8988
+ out2.push(`slider${old.index} "${old.name}" changed range, step or options`);
8989
+ }
8990
+ }
8991
+ return out2;
8992
+ }
8993
+ var text6 = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...isError ? { isError: true } : {} });
8994
+ var fmt = (f) => `- ${f.severity}${f.line ? ` (line ${f.line})` : ""} [${f.rule}]: ${f.message}`;
8995
+ function writeJsfx(input) {
8996
+ const args = { ...input, source: stripGenerated(input.source) };
8997
+ const overwrite2 = args.overwrite === true;
8998
+ const slug = slugify(args.name);
8999
+ if (!slug) {
9000
+ record({ outcome: "refused_name", overwrite: overwrite2 });
9001
+ return text6("Error: the name needs at least one letter or digit (it becomes the file name).", true);
9002
+ }
9003
+ let accentToken;
9004
+ if (args.accent !== void 0) {
9005
+ const parsed = parseAccent(args.accent);
9006
+ if ("error" in parsed) {
9007
+ record({ outcome: "refused_accent", overwrite: overwrite2 });
9008
+ return text6(`Error: nothing was written: ${parsed.error}.`, true);
9009
+ }
9010
+ accentToken = parsed.kind === "auto" ? "auto" : parsed.token;
9011
+ }
9012
+ const dir = generatedDir();
9013
+ const path = join9(dir, `${slug}.jsfx`);
9014
+ const existing = existsSync5(path) ? readFileSync5(path, "utf8") : void 0;
9015
+ accentToken ??= existing !== void 0 ? readAccentToken(existing) : void 0;
9016
+ const accent = resolveAccent(slug, accentToken === "auto" ? void 0 : accentToken);
9017
+ if (existing !== void 0 && !overwrite2) {
9018
+ record({ outcome: "refused_exists", overwrite: overwrite2 });
9019
+ return text6(`Error: ${slug}.jsfx already exists. Pass overwrite: true to replace it (the old file is kept in the history), or pick another name.`, true);
9020
+ }
9021
+ const findings = lintJsfx(args.source);
9022
+ const sliders = parseSliders(args.source).sliders;
9023
+ const widgets = widgetCounts(args.source);
9024
+ const toolkit = loadToolkit();
9025
+ const shape2 = { overwrite: overwrite2, sliders: sliders.length, widgets, bytes: Buffer.byteLength(args.source), toolkit: toolkitVersion(toolkit), findings, accent: accent.kind };
9026
+ if (errorsOf(findings).length) {
9027
+ record({ ...shape2, outcome: "refused_lint" });
9028
+ emitLog("warn", "write_jsfx refused: lint errors", { "reaper.jsfx.outcome": "refused_lint", "reaper.jsfx.lint.rules": [...new Set(errorsOf(findings).map((f) => f.rule))].join(",") });
9029
+ return text6(`Error: nothing was written, fix these and call write_jsfx again:
9030
+ ${findings.map(fmt).join("\n")}`, true);
9031
+ }
9032
+ if (existing !== void 0 && !args.breaking) {
9033
+ const broken = breakingChanges(parseSliders(existing).sliders, parseSliders(args.source).sliders);
9034
+ if (broken.length) {
9035
+ record({ ...shape2, outcome: "refused_breaking" });
9036
+ emitLog("warn", "write_jsfx refused: breaking slider change", { "reaper.jsfx.outcome": "refused_breaking", "reaper.jsfx.breaking_count": broken.length });
9037
+ return text6(`Error: nothing was written. This would break automation saved in projects that use the plugin:
9038
+ ${broken.map((b) => `- ${b}`).join("\n")}
9039
+ Keep existing sliders as they are and add new ones at the end, or pass breaking: true if that is intended.`, true);
9040
+ }
9041
+ }
9042
+ const resolved = args.presets ? resolvePresets(args.presets, sliders) : void 0;
9043
+ if (resolved?.errors.length) {
9044
+ record({ ...shape2, outcome: "refused_presets" });
9045
+ emitLog("warn", "write_jsfx refused: invalid presets", { "reaper.jsfx.outcome": "refused_presets", "reaper.jsfx.presets": Math.min(args.presets?.length ?? 0, MAX_PRESETS) });
9046
+ return text6(`Error: nothing was written, fix these presets and call write_jsfx again:
9047
+ ${resolved.errors.map((e) => `- ${e}`).join("\n")}`, true);
9048
+ }
9049
+ const version = existing !== void 0 ? readVersion(existing) + 1 : 1;
9050
+ const history = historyDir(slug);
9051
+ const manifestPath = join9(history, "presets.json");
9052
+ let presets;
9053
+ try {
9054
+ if (existing !== void 0) {
9055
+ mkdirSync6(history, { recursive: true });
9056
+ copyFileSync3(path, join9(history, `${readVersion(existing) || 0}.jsfx`));
9057
+ if (existsSync5(manifestPath)) copyFileSync3(manifestPath, join9(history, `${readVersion(existing) || 0}.presets.json`));
9058
+ }
9059
+ mkdirSync6(dir, { recursive: true });
9060
+ writeFileSync5(path, inlineToolkit(args.source, { toolkit, version, request: args.request, accent: accent.token ?? "auto", slug, date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) }));
9061
+ const effectPath = `${GENERATED_DIR}/${slug}.jsfx`;
9062
+ if (resolved && args.presets) {
9063
+ presets = writePresetFile(presetsDir(), effectPath, args.presets.map((p, i) => encodePreset(p.name.trim(), resolved.values[i])), manifestPath);
9064
+ } else if (existing !== void 0 && args.breaking && existsSync5(manifestPath)) {
9065
+ presets = { ...writePresetFile(presetsDir(), effectPath, [], manifestPath), removed: true };
9066
+ }
9067
+ } catch (err) {
9068
+ record({ ...shape2, outcome: "failed" });
9069
+ throw err;
9070
+ }
9071
+ record({ ...shape2, outcome: "written", version, ...presets ? { presets: presets.written.length } : {} });
9072
+ return text6(JSON.stringify({
9073
+ path,
9074
+ fxName: `${GENERATED_DIR}/${slug}`,
9075
+ version,
9076
+ accent: { color: accent.hex, kind: accent.kind },
9077
+ sliders: sliders.map((s) => ({ index: s.index, name: s.name, min: s.min, max: s.max, default: s.default, hidden: s.hidden })),
9078
+ ...presets ? { presets: {
9079
+ file: presets.file,
9080
+ written: presets.written,
9081
+ ...presets.keptUserEdits.length ? { keptUserEdits: presets.keptUserEdits } : {},
9082
+ ...args.presets && presets.written.length < args.presets.length ? { skipped: args.presets.map((p) => p.name.trim()).filter((n) => !presets?.written.includes(n)), why: "a preset of yours already has that name; it was left as it is" } : {},
9083
+ ...presets.removed ? { removed: "breaking: the earlier suggested presets were removed (their values meant something else); pass presets again" } : {}
9084
+ } } : {},
9085
+ warnings: warningsOf(findings).map(fmt),
9086
+ next: "remove_fx and add_fx the plugin again on the scratch track (a loaded instance does not recompile). JSFX code does not run until audio is processed, so a plugin that failed to compile loads fine and does nothing: prove it runs by measuring its output against bypass"
9087
+ }, null, 2));
9088
+ }
9089
+ function registerJsfxTools(server) {
9090
+ server.tool(
9091
+ "write_jsfx",
9092
+ "Write a generated REAPER plugin (JSFX) as one self-contained file in Effects/reaper-mcp-generated/. Give the plugin source (header, unnamed sliders, @init/@slider/@block/@sample, a @gfx section using the ui_* toolkit): the toolkit is inlined for you, the file is linted first and nothing is written when a rule fails. Use it from the /make-plugin skill. The plugin works without this server or the bridge. An existing slider is never renumbered or re-ranged without breaking: true (saved automation would break). Old versions are kept outside Effects/.",
9093
+ {
9094
+ name: z36.string().min(1).max(60).describe(`The plugin's display name, e.g. "Mutate Verb". Becomes the file name (lowercase, dashes).`),
9095
+ source: z36.string().min(1).max(MAX_SOURCE).describe("The plugin source, with or without the import line. May be a file this tool wrote earlier, edited: the old toolkit block is replaced."),
9096
+ request: z36.string().max(300).optional().describe("One line of what the user asked for. Written as a comment in the file only; never sent anywhere."),
9097
+ overwrite: z36.boolean().optional().describe("Replace an existing plugin of that name (version + 1; the old file goes to the history)"),
9098
+ breaking: z36.boolean().optional().describe("Allow an existing slider to change range, step or options, or to be removed"),
9099
+ accent: z36.string().max(20).optional().describe(`The plugin's accent colour: "auto" (from its name, the default), a name (blue, teal, green, amber, orange, red, pink, violet) or "#rrggbb". Leave it out to keep the current one. To recolour a plugin, call again with only this changed.`),
9100
+ presets: z36.array(z36.object({
9101
+ name: z36.string().min(1).max(MAX_PRESET_NAME).describe('2-3 words that say the intent, e.g. "Ghost tails"'),
9102
+ values: z36.record(z36.string(), z36.coerce.number()).describe(`Slider index ("3") or label ("Mix") \u2192 value in the slider's own units (dB, Hz, 0..1, option index). Sliders left out take their default.`)
9103
+ })).max(MAX_PRESETS).optional().describe(`Suggested presets (3-5, at most ${MAX_PRESETS}) that teach how the plugin is meant to be used. They appear in the plugin's preset dropdown; presets the user saved are kept. Every value is checked against its slider: one bad value refuses the whole call.`)
9104
+ },
9105
+ async (args) => {
9106
+ const startedAt = Date.now();
9107
+ try {
9108
+ const result = writeJsfx(args);
9109
+ const slug = slugify(args.name);
9110
+ const body = result.isError ? void 0 : JSON.parse(result.content[0].text);
9111
+ logToolResult(
9112
+ "write_jsfx",
9113
+ { name: slug, overwrite: args.overwrite === true },
9114
+ startedAt,
9115
+ body ? { name: args.name, slug, version: body.version, sliders: body.sliders.length, ...widgetCounts(args.source), ...args.presets ? { presets: args.presets.length } : {} } : null,
9116
+ result.isError ? result.content[0].text : void 0
9117
+ );
9118
+ return result;
9119
+ } catch (err) {
9120
+ logToolResult("write_jsfx", { name: slugify(args.name) }, startedAt, null, err instanceof Error ? err.message : String(err));
9121
+ throw err;
9122
+ }
9123
+ }
9124
+ );
9125
+ }
9126
+
9127
+ // apps/reaper-mcp-server/src/tools/plugin-build.ts
9128
+ import { z as z37 } from "zod/v4";
9129
+ import { trace as trace10 } from "@opentelemetry/api";
9130
+ var BUILD_OUTCOMES = ["shipped", "compile_failed", "checks_failed", "abandoned"];
9131
+ var BUILD_EXAMPLES = ["mutate-verb", "tape-sat", "width-bass-mono", "none"];
9132
+ var MAX = { rounds: 10, checks: 8 };
9133
+ function closed2(allowed, value) {
9134
+ const candidate = value?.trim().toLowerCase();
9135
+ return candidate !== void 0 && allowed.includes(candidate) ? candidate : "other";
9136
+ }
9137
+ function buildAttributes(args) {
9138
+ return {
9139
+ "reaper.plugin_build.outcome": closed2(BUILD_OUTCOMES, args.outcome),
9140
+ "reaper.plugin_build.example": closed2(BUILD_EXAMPLES, args.example ?? "none"),
9141
+ "reaper.plugin_build.rounds": Math.min(args.rounds ?? 1, MAX.rounds),
9142
+ "reaper.plugin_build.checks_passed": Math.min(args.checksPassed ?? 0, MAX.checks),
9143
+ "reaper.plugin_build.checks_failed": Math.min(args.checksFailed ?? 0, MAX.checks),
9144
+ ...args.cleanedUp !== void 0 ? { "reaper.plugin_build.cleaned_up": args.cleanedUp } : {},
9145
+ ...args.seconds !== void 0 ? { "reaper.plugin_build.duration_s": args.seconds } : {}
9146
+ };
9147
+ }
9148
+ function registerPluginBuildTools(server) {
9149
+ server.tool(
9150
+ "report_plugin_build",
9151
+ "Call once at the end of a /make-plugin run, after the scratch track is deleted, also when the run stopped early. Records how it went in pseudonymous usage telemetry as fixed values and counts \u2014 never the plugin's name or what it does. The result shows exactly what was sent. Changes nothing in REAPER.",
9152
+ {
9153
+ outcome: z37.string().describe("shipped: it compiled (the plugin changed the audio against bypass) and every check passed; compile_failed: the plugin loaded but left the audio unchanged or silent; checks_failed: it loaded but a check failed and was not fixed; abandoned: stopped early"),
9154
+ example: z37.string().optional().describe("The shipped example the plugin started from: mutate-verb, tape-sat, width-bass-mono, or none"),
9155
+ rounds: z37.coerce.number().int().min(1).optional().describe("write_jsfx \u2192 load \u2192 check rounds it took (default 1)"),
9156
+ checksPassed: z37.coerce.number().int().min(0).optional().describe("Verification checks that passed in the last round"),
9157
+ checksFailed: z37.coerce.number().int().min(0).optional().describe("Verification checks that failed in the last round"),
9158
+ cleanedUp: z37.boolean().optional().describe("The scratch track was deleted and nothing else changed"),
9159
+ scratchTag: z37.string().optional().describe('The <TAG> of your "[MCP] make-plugin <TAG>" track, so the server can time the run. Never sent.')
9160
+ },
9161
+ async (args) => {
9162
+ const attributes = buildAttributes({ ...args, seconds: runSeconds(args.scratchTag) });
9163
+ trace10.getActiveSpan()?.setAttributes(attributes);
9164
+ const mode = activeTelemetryMode();
9165
+ return { content: [{ type: "text", text: JSON.stringify({ telemetry: mode, sent: mode === "off" ? {} : attributes }, null, 2) }] };
9166
+ }
9167
+ );
9168
+ }
9169
+
8438
9170
  // apps/reaper-mcp-server/src/server.ts
8439
9171
  var MAX_STATUS_MESSAGE = 256;
8440
9172
  var TOOL_ERROR_MESSAGE = "reaper.tool.error.message";
@@ -8543,13 +9275,15 @@ function createServer() {
8543
9275
  registerVoiceSketchTools(server);
8544
9276
  registerKnowledgeTools(server);
8545
9277
  registerPluginResearchTools(server);
9278
+ registerJsfxTools(server);
9279
+ registerPluginBuildTools(server);
8546
9280
  return server;
8547
9281
  }
8548
9282
 
8549
9283
  // apps/reaper-mcp-server/src/extensions.ts
8550
9284
  import { copyFile, mkdir as mkdir2, readdir as readdir2, readFile as readFile4, realpath, stat as stat3 } from "node:fs/promises";
8551
- import { homedir as homedir7 } from "node:os";
8552
- import { join as join9, sep } from "node:path";
9285
+ import { homedir as homedir8 } from "node:os";
9286
+ import { join as join11, sep } from "node:path";
8553
9287
  import { pathToFileURL } from "node:url";
8554
9288
 
8555
9289
  // libs/extension-api/src/manifest.ts
@@ -8639,15 +9373,15 @@ function withVst3Lengths(header, state) {
8639
9373
  // libs/extension-api/src/fx-state.ts
8640
9374
  import { randomUUID as randomUUID7 } from "node:crypto";
8641
9375
  import { readFile as readFile3, writeFile as writeFile3, unlink as unlink3 } from "node:fs/promises";
8642
- import { join as join8 } from "node:path";
9376
+ import { join as join10 } from "node:path";
8643
9377
  var STATE_TIMEOUT_MS = 6e4;
8644
9378
  var b64 = (bytes) => Buffer.from(bytes).toString("base64");
8645
- var unb64 = (text7) => new Uint8Array(Buffer.from(text7, "base64"));
9379
+ var unb64 = (text8) => new Uint8Array(Buffer.from(text8, "base64"));
8646
9380
  var fail2 = (error7) => ({ ok: false, error: error7 });
8647
9381
  function createFxStateClient(host) {
8648
9382
  async function get(loc) {
8649
9383
  const dir = await host.bridgeDir();
8650
- const outFile = join8(dir, `fxstate_${randomUUID7()}.out`);
9384
+ const outFile = join10(dir, `fxstate_${randomUUID7()}.out`);
8651
9385
  try {
8652
9386
  const res = await host.bridge("get_fx_state", { trackIndex: loc.trackIndex, fxIndex: loc.fxIndex, outFile }, STATE_TIMEOUT_MS);
8653
9387
  if (!res.success) return fail2(res.error ?? "get_fx_state failed");
@@ -8679,7 +9413,7 @@ function createFxStateClient(host) {
8679
9413
  return fail2(err instanceof Error ? err.message : String(err));
8680
9414
  }
8681
9415
  const dir = await host.bridgeDir();
8682
- const inFile = join8(dir, `fxstate_${randomUUID7()}.in`);
9416
+ const inFile = join10(dir, `fxstate_${randomUUID7()}.in`);
8683
9417
  try {
8684
9418
  await writeFile3(inFile, `${b64(fixed.header)}
8685
9419
  ${b64(fixed.state)}
@@ -8701,10 +9435,10 @@ ${b64(fixed.state)}
8701
9435
  }
8702
9436
 
8703
9437
  // apps/reaper-mcp-server/src/extensions.ts
8704
- import { z as z36 } from "zod/v4";
8705
- import { existsSync as existsSync4 } from "node:fs";
9438
+ import { z as z38 } from "zod/v4";
9439
+ import { existsSync as existsSync6 } from "node:fs";
8706
9440
  function getExtensionsDir() {
8707
- return process.env["REAPER_MCP_EXTENSIONS"] || join9(homedir7(), ".reaper-mcp", "extensions");
9441
+ return process.env["REAPER_MCP_EXTENSIONS"] || join11(homedir8(), ".reaper-mcp", "extensions");
8708
9442
  }
8709
9443
  async function discoverExtensions(root = getExtensionsDir()) {
8710
9444
  let names;
@@ -8715,11 +9449,11 @@ async function discoverExtensions(root = getExtensionsDir()) {
8715
9449
  }
8716
9450
  const found = [];
8717
9451
  for (const folder of names) {
8718
- const dir = join9(root, folder);
9452
+ const dir = join11(root, folder);
8719
9453
  if (!(await stat3(dir).catch(() => null))?.isDirectory()) continue;
8720
9454
  let raw;
8721
9455
  try {
8722
- raw = JSON.parse(await readFile4(join9(dir, MANIFEST_FILE), "utf8"));
9456
+ raw = JSON.parse(await readFile4(join11(dir, MANIFEST_FILE), "utf8"));
8723
9457
  } catch (err) {
8724
9458
  const why = err.code === "ENOENT" ? `no ${MANIFEST_FILE}` : `${MANIFEST_FILE} is not valid JSON`;
8725
9459
  found.push({ folder, dir, errors: [why] });
@@ -8738,18 +9472,18 @@ async function discoverExtensions(root = getExtensionsDir()) {
8738
9472
  }
8739
9473
  var REGISTER_TIMEOUT_MS = 1e4;
8740
9474
  var TOOL_NAME = /^[a-z][a-z0-9_]{0,47}$/;
8741
- var text6 = (t) => ({ content: [{ type: "text", text: t }] });
9475
+ var text7 = (t) => ({ content: [{ type: "text", text: t }] });
8742
9476
  function createApi(server, manifest) {
8743
9477
  const prefix = manifest.name.replace(/-/g, "_");
8744
9478
  const toolNames = [];
8745
9479
  const registered = [];
8746
9480
  let categoryDescription;
8747
- const json2 = (data) => text6(JSON.stringify(data, null, 2));
9481
+ const json2 = (data) => text7(JSON.stringify(data, null, 2));
8748
9482
  const error7 = (message) => ({ content: [{ type: "text", text: `Error: ${message}` }], isError: true });
8749
9483
  const api = {
8750
9484
  name: manifest.name,
8751
9485
  apiVersion: EXTENSION_API_VERSION,
8752
- z: z36,
9486
+ z: z38,
8753
9487
  tool(name, description, shape2, handler) {
8754
9488
  if (!TOOL_NAME.test(name)) throw new Error(`tool name "${name}" must be lowercase letters, digits and underscores`);
8755
9489
  const full = `${prefix}_${name}`;
@@ -8788,10 +9522,10 @@ function createApi(server, manifest) {
8788
9522
  }
8789
9523
  async function installLua(dir, manifest) {
8790
9524
  if (!manifest.lua) return;
8791
- const target = join9(await ensureBridgeDir(), "extensions", manifest.name);
9525
+ const target = join11(await ensureBridgeDir(), "extensions", manifest.name);
8792
9526
  await mkdir2(target, { recursive: true });
8793
- const src = join9(dir, manifest.lua);
8794
- const dest = join9(target, "handlers.lua");
9527
+ const src = join11(dir, manifest.lua);
9528
+ const dest = join11(target, "handlers.lua");
8795
9529
  const [a, b] = await Promise.all([readFile4(src), readFile4(dest).catch(() => null)]);
8796
9530
  if (!b || !a.equals(b)) await copyFile(src, dest);
8797
9531
  }
@@ -8801,11 +9535,11 @@ async function loadOne(server, ext) {
8801
9535
  const built = createApi(server, manifest);
8802
9536
  try {
8803
9537
  const realDir = await realpath(dir);
8804
- const mainPath = await realpath(join9(dir, manifest.main)).catch(() => null);
9538
+ const mainPath = await realpath(join11(dir, manifest.main)).catch(() => null);
8805
9539
  if (!mainPath) return skipped(`"main" file ${manifest.main} does not exist (is the extension built?)`);
8806
9540
  if (!mainPath.startsWith(realDir + sep)) return skipped('"main" resolves outside the extension folder');
8807
9541
  if (manifest.lua) {
8808
- const luaPath = await realpath(join9(dir, manifest.lua)).catch(() => null);
9542
+ const luaPath = await realpath(join11(dir, manifest.lua)).catch(() => null);
8809
9543
  if (!luaPath) return skipped(`"lua" file ${manifest.lua} does not exist`);
8810
9544
  if (!luaPath.startsWith(realDir + sep)) return skipped('"lua" resolves outside the extension folder');
8811
9545
  }
@@ -8854,7 +9588,7 @@ async function checkExtensions(root = getExtensionsDir()) {
8854
9588
  const m = ext.manifest;
8855
9589
  const missing = [];
8856
9590
  for (const rel of [m.main, m.lua]) {
8857
- if (rel && !existsSync4(join9(ext.dir, rel))) missing.push(rel);
9591
+ if (rel && !existsSync6(join11(ext.dir, rel))) missing.push(rel);
8858
9592
  }
8859
9593
  checks.push(
8860
9594
  missing.length > 0 ? { label: m.name, status: "fail", detail: `missing ${missing.join(", ")}`, fix: `build it (pnpm nx build ${m.name}) or reinstall` } : { label: m.name, status: "ok", detail: `v${m.version}${m.description ? ` \xB7 ${m.description}` : ""}` }
@@ -8866,19 +9600,19 @@ async function checkExtensions(root = getExtensionsDir()) {
8866
9600
  // apps/reaper-mcp-server/src/extension-cli.ts
8867
9601
  import { execFile } from "node:child_process";
8868
9602
  import { cp, lstat, mkdir as mkdir3, mkdtemp, readFile as readFile5, readdir as readdir3, rm, symlink, unlink as unlink4, writeFile as writeFile4, stat as stat4 } from "node:fs/promises";
8869
- import { existsSync as existsSync5 } from "node:fs";
9603
+ import { existsSync as existsSync7 } from "node:fs";
8870
9604
  import { tmpdir } from "node:os";
8871
- import { basename as basename4, dirname as dirname5, join as join10, resolve as resolve2 } from "node:path";
9605
+ import { basename as basename4, dirname as dirname7, join as join12, resolve as resolve2 } from "node:path";
8872
9606
  import { createInterface as createInterface3 } from "node:readline/promises";
8873
9607
  import { promisify } from "node:util";
8874
- import { fileURLToPath as fileURLToPath4 } from "node:url";
9608
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
8875
9609
  var run4 = promisify(execFile);
8876
9610
  var NAME2 = /^[a-z][a-z0-9-]{1,31}$/;
8877
9611
  var fail3 = (error7) => ({ ok: false, error: error7 });
8878
9612
  async function readManifest(dir) {
8879
9613
  let raw;
8880
9614
  try {
8881
- raw = JSON.parse(await readFile5(join10(dir, MANIFEST_FILE), "utf8"));
9615
+ raw = JSON.parse(await readFile5(join12(dir, MANIFEST_FILE), "utf8"));
8882
9616
  } catch (err) {
8883
9617
  return fail3(err.code === "ENOENT" ? `${dir} has no ${MANIFEST_FILE}` : `${MANIFEST_FILE} in ${dir} is not valid JSON`);
8884
9618
  }
@@ -8891,7 +9625,7 @@ async function installExtension(src, opts) {
8891
9625
  if (!(await stat4(from).catch(() => null))?.isDirectory()) return fail3(`${from} is not a folder`);
8892
9626
  const m = await readManifest(from);
8893
9627
  if (!m.ok) return m;
8894
- const dest = join10(root, m.manifest.name);
9628
+ const dest = join12(root, m.manifest.name);
8895
9629
  const existing = await lstat(dest).catch(() => null);
8896
9630
  if (existing && !opts.force) return fail3(`extension "${m.manifest.name}" is already installed at ${dest} (use --force to replace it)`);
8897
9631
  await mkdir3(root, { recursive: true });
@@ -8910,7 +9644,7 @@ async function removeInstalled(path) {
8910
9644
  }
8911
9645
  async function removeExtension(name, root = getExtensionsDir()) {
8912
9646
  if (!NAME2.test(name)) return fail3(`"${name}" is not a valid extension name`);
8913
- const dest = join10(root, name);
9647
+ const dest = join12(root, name);
8914
9648
  const st = await lstat(dest).catch(() => null);
8915
9649
  if (!st) return fail3(`extension "${name}" is not installed`);
8916
9650
  await removeInstalled(dest);
@@ -8918,16 +9652,16 @@ async function removeExtension(name, root = getExtensionsDir()) {
8918
9652
  }
8919
9653
  async function scaffoldExtension(name, parent) {
8920
9654
  if (!NAME2.test(name)) return fail3("the name must be 2-32 characters: lowercase letters, digits and dashes, starting with a letter");
8921
- const dir = join10(resolve2(parent), name);
8922
- if (existsSync5(dir) && (await readdir3(dir)).length > 0) return fail3(`${dir} already exists and is not empty`);
9655
+ const dir = join12(resolve2(parent), name);
9656
+ if (existsSync7(dir) && (await readdir3(dir)).length > 0) return fail3(`${dir} already exists and is not empty`);
8923
9657
  await mkdir3(dir, { recursive: true });
8924
9658
  const tool = name.replace(/-/g, "_");
8925
9659
  await writeFile4(
8926
- join10(dir, MANIFEST_FILE),
9660
+ join12(dir, MANIFEST_FILE),
8927
9661
  JSON.stringify({ name, version: "0.1.0", apiVersion: EXTENSION_API_VERSION, description: `The ${name} extension`, main: "index.mjs" }, null, 2) + "\n"
8928
9662
  );
8929
9663
  await writeFile4(
8930
- join10(dir, "index.mjs"),
9664
+ join12(dir, "index.mjs"),
8931
9665
  `// ${name}: a reaper-mcp extension. Its tools appear as ${tool}_<tool name>.
8932
9666
  // Everything it may touch is on \`api\` (see libs/extension-api in the reaper-mcp repo).
8933
9667
 
@@ -8946,7 +9680,7 @@ export default {
8946
9680
  };
8947
9681
  `
8948
9682
  );
8949
- await writeFile4(join10(dir, "README.md"), `# ${name}
9683
+ await writeFile4(join12(dir, "README.md"), `# ${name}
8950
9684
 
8951
9685
  A reaper-mcp extension.
8952
9686
 
@@ -8958,9 +9692,9 @@ reaper-mcp extension link . # use this working copy; restart the MCP server to
8958
9692
  }
8959
9693
  function classifySource(arg, cloneRoot) {
8960
9694
  if (/^(https?:\/\/|git@|ssh:\/\/)/.test(arg) || /\.git$/.test(arg)) return { kind: "git", url: arg };
8961
- if (existsSync5(arg) && existsSync5(join10(arg, MANIFEST_FILE))) return { kind: "path", path: resolve2(arg) };
8962
- if (NAME2.test(arg) && cloneRoot && existsSync5(join10(cloneRoot, "extensions", arg, MANIFEST_FILE))) {
8963
- return { kind: "clone", path: join10(cloneRoot, "extensions", arg) };
9695
+ if (existsSync7(arg) && existsSync7(join12(arg, MANIFEST_FILE))) return { kind: "path", path: resolve2(arg) };
9696
+ if (NAME2.test(arg) && cloneRoot && existsSync7(join12(cloneRoot, "extensions", arg, MANIFEST_FILE))) {
9697
+ return { kind: "clone", path: join12(cloneRoot, "extensions", arg) };
8964
9698
  }
8965
9699
  return { kind: "unknown", arg };
8966
9700
  }
@@ -8998,7 +9732,7 @@ async function add(args) {
8998
9732
  console.error("Usage: reaper-mcp extension add <name | folder | git-url> [--force] [--yes]");
8999
9733
  return 2;
9000
9734
  }
9001
- const here = dirname5(fileURLToPath4(import.meta.url));
9735
+ const here = dirname7(fileURLToPath5(import.meta.url));
9002
9736
  const source = classifySource(arg, findCloneRoot(process.cwd()) ?? findCloneRoot(here));
9003
9737
  if (source.kind === "unknown") {
9004
9738
  console.error(`"${arg}" is not an extension folder, a git URL, or the name of an extension in this clone's extensions/ folder.`);
@@ -9009,8 +9743,8 @@ async function add(args) {
9009
9743
  let mode = "copy";
9010
9744
  try {
9011
9745
  if (source.kind === "git") {
9012
- tmp = await mkdtemp(join10(tmpdir(), "reaper-mcp-ext-"));
9013
- from = join10(tmp, "src");
9746
+ tmp = await mkdtemp(join12(tmpdir(), "reaper-mcp-ext-"));
9747
+ from = join12(tmp, "src");
9014
9748
  await run4("git", ["clone", "--depth", "1", source.url, from]);
9015
9749
  } else {
9016
9750
  from = source.path;
@@ -9035,7 +9769,7 @@ async function add(args) {
9035
9769
  return 1;
9036
9770
  }
9037
9771
  out(`${mode === "link" ? "Linked" : "Installed"} ${r.name} ${r.manifest.version} -> ${r.dir}`);
9038
- if (!existsSync5(join10(from, r.manifest.main))) {
9772
+ if (!existsSync7(join12(from, r.manifest.main))) {
9039
9773
  out(`Note: ${r.manifest.main} does not exist yet. Build it (pnpm nx build ${r.name}), then restart the MCP server.`);
9040
9774
  } else {
9041
9775
  out("Restart the MCP server (or your Claude Code session) to load it.");
@@ -9108,23 +9842,23 @@ Try it: reaper-mcp extension link ${basename4(r.dir)}`);
9108
9842
  }
9109
9843
 
9110
9844
  // apps/reaper-mcp-server/src/main.ts
9111
- import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync5, realpathSync, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "node:fs";
9112
- import { join as join12, dirname as dirname7, resolve as resolve3 } from "node:path";
9113
- import { fileURLToPath as fileURLToPath5 } from "node:url";
9114
- import { homedir as homedir8, platform as platform4 } from "node:os";
9845
+ import { existsSync as existsSync10, mkdirSync as mkdirSync9, readFileSync as readFileSync8, realpathSync, rmSync as rmSync2, writeFileSync as writeFileSync8 } from "node:fs";
9846
+ import { join as join15, dirname as dirname9, resolve as resolve3 } from "node:path";
9847
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
9848
+ import { homedir as homedir9, platform as platform4 } from "node:os";
9115
9849
  import { exec as execCb, execFileSync } from "node:child_process";
9116
9850
  import { promisify as promisifyUtil } from "node:util";
9117
9851
 
9118
9852
  // apps/reaper-mcp-server/src/claude-assets.ts
9119
9853
  import { createHash as createHash2 } from "node:crypto";
9120
- import { existsSync as existsSync6, lstatSync, mkdirSync as mkdirSync5, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync4 } from "node:fs";
9121
- import { dirname as dirname6, join as join11, relative } from "node:path";
9854
+ import { existsSync as existsSync8, lstatSync, mkdirSync as mkdirSync7, readFileSync as readFileSync6, readdirSync as readdirSync2, writeFileSync as writeFileSync6 } from "node:fs";
9855
+ import { dirname as dirname8, join as join13, relative } from "node:path";
9122
9856
  var CLAUDE_MANIFEST = ".reaper-mcp-installed.json";
9123
9857
  var sha = (buf) => createHash2("sha256").update(buf).digest("hex");
9124
9858
  function listFiles(dir) {
9125
9859
  const out2 = [];
9126
9860
  for (const entry of readdirSync2(dir, { withFileTypes: true })) {
9127
- const p = join11(dir, entry.name);
9861
+ const p = join13(dir, entry.name);
9128
9862
  if (entry.isDirectory()) out2.push(...listFiles(p));
9129
9863
  else if (entry.isFile()) out2.push(p);
9130
9864
  }
@@ -9139,7 +9873,7 @@ function isSymlink(path) {
9139
9873
  }
9140
9874
  function readManifest2(path) {
9141
9875
  try {
9142
- const m = JSON.parse(readFileSync4(path, "utf-8"));
9876
+ const m = JSON.parse(readFileSync6(path, "utf-8"));
9143
9877
  if (m && m.version === 1 && m.files && typeof m.files === "object") return m;
9144
9878
  } catch {
9145
9879
  }
@@ -9147,27 +9881,27 @@ function readManifest2(path) {
9147
9881
  }
9148
9882
  function installClaudeAssets(packageClaudeDir, claudeDir, opts = {}) {
9149
9883
  const result = { installed: [], updated: [], unchanged: 0, skipped: [] };
9150
- const manifestPath = join11(claudeDir, CLAUDE_MANIFEST);
9884
+ const manifestPath = join13(claudeDir, CLAUDE_MANIFEST);
9151
9885
  const manifest = readManifest2(manifestPath);
9152
9886
  const plan = [];
9153
- const skillsSrc = join11(packageClaudeDir, "skills");
9154
- if (existsSync6(skillsSrc)) {
9887
+ const skillsSrc = join13(packageClaudeDir, "skills");
9888
+ if (existsSync8(skillsSrc)) {
9155
9889
  for (const f of listFiles(skillsSrc)) {
9156
9890
  const rel = relative(skillsSrc, f);
9157
- plan.push([f, join11(claudeDir, "skills", rel), join11(claudeDir, "skills", rel.split(/[\\/]/)[0])]);
9891
+ plan.push([f, join13(claudeDir, "skills", rel), join13(claudeDir, "skills", rel.split(/[\\/]/)[0])]);
9158
9892
  }
9159
9893
  }
9160
- const agentsSrc = join11(packageClaudeDir, "agents");
9161
- if (existsSync6(agentsSrc)) {
9894
+ const agentsSrc = join13(packageClaudeDir, "agents");
9895
+ if (existsSync8(agentsSrc)) {
9162
9896
  for (const f of listFiles(agentsSrc)) {
9163
- const dest = join11(claudeDir, "agents", relative(agentsSrc, f));
9897
+ const dest = join13(claudeDir, "agents", relative(agentsSrc, f));
9164
9898
  plan.push([f, dest, dest]);
9165
9899
  }
9166
9900
  }
9167
- const knowledgeSrc = join11(packageClaudeDir, "knowledge");
9168
- if (existsSync6(knowledgeSrc)) {
9901
+ const knowledgeSrc = join13(packageClaudeDir, "knowledge");
9902
+ if (existsSync8(knowledgeSrc)) {
9169
9903
  for (const f of listFiles(knowledgeSrc)) {
9170
- plan.push([f, join11(claudeDir, "knowledge", relative(knowledgeSrc, f)), join11(claudeDir, "knowledge")]);
9904
+ plan.push([f, join13(claudeDir, "knowledge", relative(knowledgeSrc, f)), join13(claudeDir, "knowledge")]);
9171
9905
  }
9172
9906
  }
9173
9907
  const skippedSymlinks = /* @__PURE__ */ new Set();
@@ -9175,29 +9909,29 @@ function installClaudeAssets(packageClaudeDir, claudeDir, opts = {}) {
9175
9909
  if (isSymlink(linkRoot)) {
9176
9910
  if (!skippedSymlinks.has(linkRoot)) {
9177
9911
  skippedSymlinks.add(linkRoot);
9178
- result.skipped.push({ path: linkRoot, reason: existsSync6(linkRoot) ? "symlink" : "broken-symlink" });
9912
+ result.skipped.push({ path: linkRoot, reason: existsSync8(linkRoot) ? "symlink" : "broken-symlink" });
9179
9913
  }
9180
9914
  continue;
9181
9915
  }
9182
9916
  const key = relative(claudeDir, dest);
9183
- const content = readFileSync4(src);
9917
+ const content = readFileSync6(src);
9184
9918
  const hash = sha(content);
9185
- if (!existsSync6(dest)) {
9919
+ if (!existsSync8(dest)) {
9186
9920
  if (!opts.dryRun) {
9187
- mkdirSync5(dirname6(dest), { recursive: true });
9188
- writeFileSync4(dest, content);
9921
+ mkdirSync7(dirname8(dest), { recursive: true });
9922
+ writeFileSync6(dest, content);
9189
9923
  manifest.files[key] = hash;
9190
9924
  }
9191
9925
  result.installed.push(key);
9192
9926
  continue;
9193
9927
  }
9194
- const current = sha(readFileSync4(dest));
9928
+ const current = sha(readFileSync6(dest));
9195
9929
  if (current === hash) {
9196
9930
  if (!opts.dryRun) manifest.files[key] = hash;
9197
9931
  result.unchanged++;
9198
9932
  } else if (manifest.files[key] === current) {
9199
9933
  if (!opts.dryRun) {
9200
- writeFileSync4(dest, content);
9934
+ writeFileSync6(dest, content);
9201
9935
  manifest.files[key] = hash;
9202
9936
  }
9203
9937
  result.updated.push(key);
@@ -9206,9 +9940,56 @@ function installClaudeAssets(packageClaudeDir, claudeDir, opts = {}) {
9206
9940
  }
9207
9941
  }
9208
9942
  if (!opts.dryRun && (result.installed.length || result.updated.length || result.unchanged)) {
9209
- mkdirSync5(claudeDir, { recursive: true });
9210
- writeFileSync4(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
9943
+ mkdirSync7(claudeDir, { recursive: true });
9944
+ writeFileSync6(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
9945
+ }
9946
+ return result;
9947
+ }
9948
+
9949
+ // apps/reaper-mcp-server/src/jsfx/examples.ts
9950
+ import { createHash as createHash3 } from "node:crypto";
9951
+ import { existsSync as existsSync9, mkdirSync as mkdirSync8, readFileSync as readFileSync7, readdirSync as readdirSync3, writeFileSync as writeFileSync7 } from "node:fs";
9952
+ import { join as join14 } from "node:path";
9953
+ var MANIFEST = ".installed.json";
9954
+ var sha2 = (text8) => createHash3("sha256").update(text8).digest("hex");
9955
+ function installExamplePlugins(examplesDir, outDir, toolkit, presetsDir2) {
9956
+ const result = { installed: [], kept: [], presets: {}, presetErrors: [] };
9957
+ if (!existsSync9(examplesDir)) return result;
9958
+ mkdirSync8(outDir, { recursive: true });
9959
+ const manifestPath = join14(outDir, MANIFEST);
9960
+ let manifest = {};
9961
+ try {
9962
+ manifest = JSON.parse(readFileSync7(manifestPath, "utf8"));
9963
+ } catch {
9964
+ }
9965
+ for (const file of readdirSync3(examplesDir).filter((f) => f.endsWith(".jsfx")).sort()) {
9966
+ const dest = join14(outDir, file);
9967
+ const next = inlineToolkit(readFileSync7(join14(examplesDir, file), "utf8"), { toolkit, version: 1, request: "a plugin that ships with reaper-mcp", slug: file.replace(/\.jsfx$/, ""), example: true });
9968
+ const current = existsSync9(dest) ? readFileSync7(dest, "utf8") : void 0;
9969
+ if (current !== void 0 && current !== next && sha2(current) !== manifest[file]) {
9970
+ result.kept.push(file);
9971
+ continue;
9972
+ }
9973
+ if (current !== next) writeFileSync7(dest, next);
9974
+ manifest[file] = sha2(next);
9975
+ result.installed.push(file);
9976
+ }
9977
+ if (presetsDir2) {
9978
+ const folder = outDir.split(/[/\\]/).slice(-2).join("/");
9979
+ for (const file of readdirSync3(examplesDir).filter((f) => f.endsWith(".jsfx")).sort()) {
9980
+ const presetsPath = join14(examplesDir, file.replace(/\.jsfx$/, ".presets.json"));
9981
+ if (!existsSync9(presetsPath)) continue;
9982
+ const input = JSON.parse(readFileSync7(presetsPath, "utf8"));
9983
+ const { values, errors } = resolvePresets(input, parseSliders(readFileSync7(join14(examplesDir, file), "utf8")).sliders);
9984
+ if (errors.length) {
9985
+ result.presetErrors.push(`${file}: ${errors.join(" ")}`);
9986
+ continue;
9987
+ }
9988
+ const encoded = input.map((p, i) => encodePreset(p.name.trim(), values[i]));
9989
+ result.presets[file] = writePresetFile(presetsDir2, `${folder}/${file}`, encoded, join14(outDir, ".presets", `${file}.json`)).written;
9990
+ }
9211
9991
  }
9992
+ writeFileSync7(manifestPath, JSON.stringify(manifest, null, 2));
9212
9993
  return result;
9213
9994
  }
9214
9995
 
@@ -9220,13 +10001,13 @@ function useColor(stream = process.stdout, env = process.env) {
9220
10001
  if (env["FORCE_COLOR"] && env["FORCE_COLOR"] !== "0") return true;
9221
10002
  return Boolean(stream.isTTY);
9222
10003
  }
9223
- function renderDoctor(sections2, opts = {}) {
10004
+ function renderDoctor(sections3, opts = {}) {
9224
10005
  const paint = (code, s) => opts.color ? `\x1B[${code}m${s}\x1B[0m` : s;
9225
10006
  const bold = (s) => paint("1", s);
9226
10007
  const dim = (s) => paint("2", s);
9227
- const width = Math.max(...sections2.flatMap((s) => s.checks.map((c) => c.label.length)));
10008
+ const width = Math.max(...sections3.flatMap((s) => s.checks.map((c) => c.label.length)));
9228
10009
  const out2 = ["", ` ${bold("REAPER MCP")} ${dim("doctor")}${opts.version ? dim(` v${opts.version}`) : ""}`];
9229
- for (const section of sections2) {
10010
+ for (const section of sections3) {
9230
10011
  const state = section.state ? ` ${paint(CODE[section.state.status], section.state.text)}` : "";
9231
10012
  out2.push("", ` ${bold(section.title)}${section.note ? dim(` ${section.note}`) : ""}${state}`);
9232
10013
  for (const c of section.checks) {
@@ -9234,7 +10015,7 @@ function renderDoctor(sections2, opts = {}) {
9234
10015
  if (c.fix && c.status !== "ok") out2.push(` ${" ".repeat(width)}${dim("\u2192")} ${c.fix}`);
9235
10016
  }
9236
10017
  }
9237
- const problems = sections2.flatMap((s) => s.checks).filter((c) => c.status === "fail");
10018
+ const problems = sections3.flatMap((s) => s.checks).filter((c) => c.status === "fail");
9238
10019
  out2.push("");
9239
10020
  if (problems.length) {
9240
10021
  const fixes = [...new Set(problems.map((c) => c.fix).filter((f) => Boolean(f)))];
@@ -9248,16 +10029,16 @@ function renderDoctor(sections2, opts = {}) {
9248
10029
 
9249
10030
  // apps/reaper-mcp-server/src/main.ts
9250
10031
  var execAsync = promisifyUtil(execCb);
9251
- var __dirname2 = dirname7(fileURLToPath5(import.meta.url));
10032
+ var __dirname2 = dirname9(fileURLToPath6(import.meta.url));
9252
10033
  async function setup() {
9253
10034
  console.log("REAPER MCP Server \u2014 Setup\n");
9254
10035
  const bridgeDir = await ensureBridgeDir();
9255
10036
  console.log(`Bridge directory: ${bridgeDir}
9256
10037
  `);
9257
10038
  const scriptsDir = getReaperScriptsPath();
9258
- mkdirSync6(scriptsDir, { recursive: true });
10039
+ mkdirSync9(scriptsDir, { recursive: true });
9259
10040
  const reaperDir = resolveAssetDir(__dirname2, "reaper");
9260
- const filesPlan = setupFilesPlan(existsSync7(join12(scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua")), findCloneRoot(__dirname2) !== null);
10041
+ const filesPlan = setupFilesPlan(existsSync10(join15(scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua")), findCloneRoot(__dirname2) !== null);
9261
10042
  if (filesPlan === "leave") {
9262
10043
  console.log("The bridge is installed by ReaPack: leaving its scripts, JSFX and status page to ReaPack.");
9263
10044
  console.log("Setup only turns on starting with REAPER and the web interface.\n");
@@ -9277,8 +10058,8 @@ async function setup() {
9277
10058
  console.log("Installing Lua scripts...");
9278
10059
  for (const asset of REAPER_ASSETS) {
9279
10060
  if (!asset.endsWith(".lua")) continue;
9280
- const src = join12(reaperDir, asset);
9281
- const dest = join12(scriptsDir, asset);
10061
+ const src = join15(reaperDir, asset);
10062
+ const dest = join15(scriptsDir, asset);
9282
10063
  if (installFile(src, dest)) {
9283
10064
  console.log(` Installed: ${asset}`);
9284
10065
  } else {
@@ -9286,8 +10067,8 @@ async function setup() {
9286
10067
  }
9287
10068
  }
9288
10069
  for (const asset of RETIRED_ASSETS) {
9289
- const dest = join12(scriptsDir, asset);
9290
- if (existsSync7(dest)) {
10070
+ const dest = join15(scriptsDir, asset);
10071
+ if (existsSync10(dest)) {
9291
10072
  rmSync2(dest);
9292
10073
  console.log(` Removed: ${asset} (retired)`);
9293
10074
  }
@@ -9295,29 +10076,37 @@ async function setup() {
9295
10076
  const cloneRoot = findCloneRoot(__dirname2);
9296
10077
  if (cloneRoot) {
9297
10078
  const dev = isDevClone(await cloneState(cloneRoot));
9298
- writeFileSync5(join12(scriptsDir, "mcp_update.conf"), updateConfigText(cloneRoot, process.execPath, dev));
10079
+ writeFileSync8(join15(scriptsDir, "mcp_update.conf"), updateConfigText(cloneRoot, process.execPath, dev));
9299
10080
  console.log(` Installed: mcp_update.conf (${dev ? "developer clone: Rebuild & reload" : "one-click updates"} from the status page)`);
9300
10081
  }
9301
- const effectsDir = join12(getReaperEffectsPath(), "reaper-mcp");
9302
- mkdirSync6(effectsDir, { recursive: true });
10082
+ const effectsDir = join15(getReaperEffectsPath(), "reaper-mcp");
10083
+ mkdirSync9(effectsDir, { recursive: true });
9303
10084
  console.log("\nInstalling JSFX analyzers...");
9304
10085
  for (const asset of REAPER_ASSETS) {
9305
10086
  if (asset.endsWith(".lua")) continue;
9306
- const src = join12(reaperDir, asset);
9307
- const dest = join12(effectsDir, asset);
10087
+ const src = join15(reaperDir, asset);
10088
+ const dest = join15(effectsDir, asset);
9308
10089
  if (installFile(src, dest)) {
9309
10090
  console.log(` Installed: reaper-mcp/${asset}`);
9310
10091
  } else {
9311
10092
  console.log(` Not found: ${src}`);
9312
10093
  }
9313
10094
  }
10095
+ console.log("\nInstalling example plugins...");
10096
+ const examplesDir = join15(resolveAssetDir(__dirname2, "claude"), "skills", "make-plugin", "examples");
10097
+ const examples = installExamplePlugins(examplesDir, join15(generatedDir(), "examples"), loadToolkit(), presetsDir());
10098
+ for (const f of examples.installed) console.log(` Installed: reaper-mcp-generated/examples/${f}`);
10099
+ for (const f of examples.kept) console.log(` Kept your edited copy: reaper-mcp-generated/examples/${f}`);
10100
+ for (const [f, names] of Object.entries(examples.presets)) if (names.length) console.log(` Presets for ${f}: ${names.join(", ")}`);
10101
+ for (const e of examples.presetErrors) console.log(` Skipped presets (invalid): ${e}`);
10102
+ if (!examples.installed.length && !examples.kept.length) console.log(` Not found: ${examplesDir}`);
9314
10103
  const wwwSrc = resolveAssetDir(__dirname2, "bridge-ui");
9315
10104
  console.log("\nInstalling bridge status UI...");
9316
- if (existsSync7(join12(wwwSrc, BRIDGE_UI_FILE))) {
10105
+ if (existsSync10(join15(wwwSrc, BRIDGE_UI_FILE))) {
9317
10106
  const count = copyDirSync(wwwSrc, getReaperWwwPath());
9318
10107
  console.log(` Installed: reaper_www_root/${BRIDGE_UI_FILE} (+${count - 1} PWA files)`);
9319
10108
  } else {
9320
- console.log(` Not found: ${join12(wwwSrc, BRIDGE_UI_FILE)} (build bridge-ui first)`);
10109
+ console.log(` Not found: ${join15(wwwSrc, BRIDGE_UI_FILE)} (build bridge-ui first)`);
9321
10110
  }
9322
10111
  installBridgeAutostart(scriptsDir);
9323
10112
  const webPort = await enableWebInterface();
@@ -9326,7 +10115,7 @@ async function setup() {
9326
10115
  console.log("Next steps:");
9327
10116
  console.log(" 1. Start REAPER: the bridge starts with it. If REAPER is already open, restart it,");
9328
10117
  console.log(" or run the bridge once by hand: Actions > Show action list > Load ReaScript,");
9329
- console.log(` select ${join12(scriptsDir, "mcp_bridge.lua")} and click Run.`);
10118
+ console.log(` select ${join15(scriptsDir, "mcp_bridge.lua")} and click Run.`);
9330
10119
  console.log(" 2. Add reaper-mcp to your Claude Code config (see: reaper-mcp doctor)");
9331
10120
  if (webPort) {
9332
10121
  console.log(`
@@ -9354,13 +10143,13 @@ async function isReaperRunning() {
9354
10143
  }
9355
10144
  async function enableWebInterface() {
9356
10145
  console.log("\nEnabling REAPER web interface...");
9357
- const iniPath = join12(getReaperResourcePath(), "reaper.ini");
9358
- if (!existsSync7(iniPath)) {
10146
+ const iniPath = join15(getReaperResourcePath(), "reaper.ini");
10147
+ if (!existsSync10(iniPath)) {
9359
10148
  console.log(` Skipped: ${iniPath} not found (start REAPER once, quit it, then re-run setup)`);
9360
10149
  return null;
9361
10150
  }
9362
10151
  const requested = Number(process.env["REAPER_WEB_PORT"]) || DEFAULT_WEB_PORT;
9363
- const result = ensureWebInterface(readFileSync5(iniPath, "utf-8"), requested);
10152
+ const result = ensureWebInterface(readFileSync8(iniPath, "utf-8"), requested);
9364
10153
  if (!result.changed) {
9365
10154
  console.log(` Already enabled on port ${result.port}`);
9366
10155
  return result.port;
@@ -9375,41 +10164,41 @@ async function enableWebInterface() {
9375
10164
  console.log(" Quit REAPER to finish (Ctrl+C to skip)...");
9376
10165
  while (await isReaperRunning()) await new Promise((r) => setTimeout(r, 1e3));
9377
10166
  }
9378
- writeFileSync5(iniPath, ensureWebInterface(readFileSync5(iniPath, "utf-8"), requested).ini, "utf-8");
10167
+ writeFileSync8(iniPath, ensureWebInterface(readFileSync8(iniPath, "utf-8"), requested).ini, "utf-8");
9379
10168
  console.log(` Enabled on port ${result.port} (override with REAPER_WEB_PORT)`);
9380
10169
  return result.port;
9381
10170
  }
9382
10171
  function installBridgeAutostart(scriptsDir) {
9383
10172
  console.log("\nStarting the bridge with REAPER...");
9384
- const path = join12(scriptsDir, "__startup.lua");
9385
- const { text: text7, changed } = ensureBridgeAutostart(existsSync7(path) ? readFileSync5(path, "utf-8") : "");
9386
- if (changed) writeFileSync5(path, text7, "utf-8");
10173
+ const path = join15(scriptsDir, "__startup.lua");
10174
+ const { text: text8, changed } = ensureBridgeAutostart(existsSync10(path) ? readFileSync8(path, "utf-8") : "");
10175
+ if (changed) writeFileSync8(path, text8, "utf-8");
9387
10176
  console.log(changed ? " Added to Scripts/__startup.lua (REAPER runs it at launch)" : " Already in Scripts/__startup.lua");
9388
10177
  console.log(" Turn it off in the bridge window: Settings > Start with REAPER.");
9389
10178
  }
9390
10179
  async function registerSnapshotActions() {
9391
10180
  console.log("\nRegistering snapshot actions (quick save, next, previous)...");
9392
- const kbPath = join12(getReaperResourcePath(), "reaper-kb.ini");
9393
- const kb = existsSync7(kbPath) ? readFileSync5(kbPath, "utf-8") : "";
10181
+ const kbPath = join15(getReaperResourcePath(), "reaper-kb.ini");
10182
+ const kb = existsSync10(kbPath) ? readFileSync8(kbPath, "utf-8") : "";
9394
10183
  const { added } = ensureSnapshotActions(kb);
9395
10184
  if (!added.length) {
9396
10185
  console.log(" Already in the Action List");
9397
10186
  } else if (await isReaperRunning()) {
9398
10187
  console.log(" REAPER is running: the bridge adds them when it next starts (re-run mcp_bridge.lua).");
9399
10188
  } else {
9400
- writeFileSync5(kbPath, ensureSnapshotActions(kb).kb, "utf-8");
10189
+ writeFileSync8(kbPath, ensureSnapshotActions(kb).kb, "utf-8");
9401
10190
  console.log(` Added: ${added.join(", ")}`);
9402
10191
  }
9403
10192
  console.log(' Bind keys in Actions > Show action list: search "mcp_snapshot".');
9404
10193
  }
9405
10194
  async function init() {
9406
10195
  console.log("REAPER MCP \u2014 Configure Claude Code\n");
9407
- const settingsPath = join12(homedir8(), ".claude", "settings.json");
9408
- mkdirSync6(dirname7(settingsPath), { recursive: true });
10196
+ const settingsPath = join15(homedir9(), ".claude", "settings.json");
10197
+ mkdirSync9(dirname9(settingsPath), { recursive: true });
9409
10198
  const result = ensureClaudeSettings(settingsPath);
9410
10199
  console.log(`Claude settings (${MCP_TOOL_NAMES.length} REAPER tools allow-listed): ${result} \u2192 ${settingsPath}`);
9411
10200
  if (findCloneRoot(__dirname2)) {
9412
- const mcpJsonPath = join12(process.cwd(), ".mcp.json");
10201
+ const mcpJsonPath = join15(process.cwd(), ".mcp.json");
9413
10202
  if (createMcpJson(mcpJsonPath, resolve3(process.argv[1]))) {
9414
10203
  console.log(`Created: ${mcpJsonPath}`);
9415
10204
  } else {
@@ -9433,7 +10222,7 @@ async function init() {
9433
10222
  console.log('\nTry: /mixer "Please gain stage my tracks" \xB7 /critique "Roast my mix"');
9434
10223
  }
9435
10224
  function registerUserMcpServer() {
9436
- const claudeJson = join12(homedir8(), ".claude.json");
10225
+ const claudeJson = join15(homedir9(), ".claude.json");
9437
10226
  const registered = hasUserMcpServer(claudeJson);
9438
10227
  if (registered && !userMcpServerIsStale(claudeJson)) {
9439
10228
  console.log('Claude Code already knows REAPER (user-scope server "reaper" is registered).');
@@ -9458,13 +10247,13 @@ function installSkills(dryRun = false) {
9458
10247
  console.log("Running from a clone: scripts/sync-symlinks.sh links the skills and knowledge into ~/.claude.");
9459
10248
  return;
9460
10249
  }
9461
- const src = join12(resolveAssetDir(__dirname2, "claude"));
9462
- if (!existsSync7(src)) {
10250
+ const src = join15(resolveAssetDir(__dirname2, "claude"));
10251
+ if (!existsSync10(src)) {
9463
10252
  console.log(`Skills not found: ${src} (this build has no claude/ folder)`);
9464
10253
  process.exitCode = 1;
9465
10254
  return;
9466
10255
  }
9467
- const r = installClaudeAssets(src, join12(homedir8(), ".claude"), { dryRun });
10256
+ const r = installClaudeAssets(src, join15(homedir9(), ".claude"), { dryRun });
9468
10257
  const verb = dryRun ? "Would install" : "Installed";
9469
10258
  console.log(`${verb} the mix skills, agents and knowledge in ~/.claude: ${r.installed.length} new, ${r.updated.length} updated, ${r.unchanged} already current.`);
9470
10259
  for (const s of r.skipped) {
@@ -9512,25 +10301,25 @@ async function doctor() {
9512
10301
  core2.push(
9513
10302
  bridgeRunning ? { label: "Lua bridge", status: "ok", detail: "Connected" } : { label: "Lua bridge", status: "fail", detail: "Not detected", fix: "reaper-mcp setup, then run mcp_bridge.lua in REAPER" }
9514
10303
  );
9515
- const readIfExists = (path) => existsSync7(path) ? readFileSync5(path, "utf-8") : null;
10304
+ const readIfExists = (path) => existsSync10(path) ? readFileSync8(path, "utf-8") : null;
9516
10305
  core2.push(autostartCheck(
9517
- readIfExists(join12(getReaperScriptsPath(), "__startup.lua")),
9518
- readIfExists(join12(getReaperResourcePath(), "reaper-extstate.ini")),
10306
+ readIfExists(join15(getReaperScriptsPath(), "__startup.lua")),
10307
+ readIfExists(join15(getReaperResourcePath(), "reaper-extstate.ini")),
9519
10308
  await isReaperRunning()
9520
10309
  ));
9521
- const globalClaudeDir = join12(homedir8(), ".claude");
9522
- const localSkills = existsSync7(join12(process.cwd(), ".claude", "skills", "mixer", "SKILL.md"));
9523
- const globalSkills = existsSync7(join12(globalClaudeDir, "skills", "mixer", "SKILL.md"));
10310
+ const globalClaudeDir = join15(homedir9(), ".claude");
10311
+ const localSkills = existsSync10(join15(process.cwd(), ".claude", "skills", "mixer", "SKILL.md"));
10312
+ const globalSkills = existsSync10(join15(globalClaudeDir, "skills", "mixer", "SKILL.md"));
9524
10313
  core2.push(
9525
10314
  localSkills || globalSkills ? { label: "Mix skills", status: "ok", detail: localSkills ? ".claude/skills" : "~/.claude/skills" } : { label: "Mix skills", status: "fail", detail: "Not linked", fix: findCloneRoot(__dirname2) ? "scripts/sync-symlinks.sh (from your clone)" : "reaper-mcp install-skills" }
9526
10315
  );
9527
- const localKnowledge = existsSync7(join12(process.cwd(), ".claude", "knowledge"));
9528
- const knowledgeLinked = localKnowledge || existsSync7(join12(globalClaudeDir, "knowledge"));
10316
+ const localKnowledge = existsSync10(join15(process.cwd(), ".claude", "knowledge"));
10317
+ const knowledgeLinked = localKnowledge || existsSync10(join15(globalClaudeDir, "knowledge"));
9529
10318
  core2.push(
9530
10319
  knowledgeLinked ? { label: "Knowledge base", status: "ok", detail: localKnowledge ? ".claude/knowledge" : "~/.claude/knowledge" } : { label: "Knowledge base", status: "fail", detail: "Not linked", fix: findCloneRoot(__dirname2) ? "scripts/sync-symlinks.sh (from your clone)" : "reaper-mcp install-skills" }
9531
10320
  );
9532
- const userServer = hasUserMcpServer(join12(homedir8(), ".claude.json"));
9533
- const mcpJsonExists = existsSync7(join12(process.cwd(), ".mcp.json"));
10321
+ const userServer = hasUserMcpServer(join15(homedir9(), ".claude.json"));
10322
+ const mcpJsonExists = existsSync10(join15(process.cwd(), ".mcp.json"));
9534
10323
  const mcpRegistered = userServer || mcpJsonExists;
9535
10324
  core2.push(
9536
10325
  mcpRegistered ? { label: "MCP config", status: "ok", detail: userServer ? "Registered for your user (any folder)" : ".mcp.json in this folder" } : { label: "MCP config", status: "fail", detail: "Not registered", fix: findCloneRoot(__dirname2) ? "scripts/install.sh (from your clone)" : "reaper-mcp init" }
@@ -9542,11 +10331,11 @@ async function doctor() {
9542
10331
  status: "info",
9543
10332
  detail: { default: "On, pseudonymous \xB7 turn off: reaper-mcp telemetry off", custom: "Your own OTEL_* destination", off: "Off" }[telemetry]
9544
10333
  });
9545
- const sidecarVenvPath = join12(homedir8(), ".reaper-mcp", "sidecar-venv");
10334
+ const sidecarVenvPath = join15(homedir9(), ".reaper-mcp", "sidecar-venv");
9546
10335
  const venvBin = platform4() === "win32" ? "Scripts" : "bin";
9547
10336
  const venvPythonName = platform4() === "win32" ? "python.exe" : "python";
9548
- const venvPython = join12(sidecarVenvPath, venvBin, venvPythonName);
9549
- const hfCachePath = join12(homedir8(), ".cache", "huggingface", "hub");
10337
+ const venvPython = join15(sidecarVenvPath, venvBin, venvPythonName);
10338
+ const hfCachePath = join15(homedir9(), ".cache", "huggingface", "hub");
9550
10339
  let pythonOk = false;
9551
10340
  let pythonDetail = "Not found";
9552
10341
  try {
@@ -9563,9 +10352,9 @@ async function doctor() {
9563
10352
  } catch {
9564
10353
  pythonDetail = "Not found";
9565
10354
  }
9566
- const venvExists = existsSync7(sidecarVenvPath);
10355
+ const venvExists = existsSync10(sidecarVenvPath);
9567
10356
  let depsOk = false;
9568
- if (venvExists && existsSync7(venvPython)) {
10357
+ if (venvExists && existsSync10(venvPython)) {
9569
10358
  try {
9570
10359
  await execAsync(`"${venvPython}" -c "import audiobox_aesthetics.infer"`);
9571
10360
  depsOk = true;
@@ -9579,14 +10368,14 @@ async function doctor() {
9579
10368
  addOns.demucs = found.separation;
9580
10369
  addOns.lv_chordia = found.chords;
9581
10370
  }
9582
- const weightsPath = join12(hfCachePath, "models--facebook--audiobox-aesthetics");
9583
- const weightsExist = existsSync7(weightsPath);
10371
+ const weightsPath = join15(hfCachePath, "models--facebook--audiobox-aesthetics");
10372
+ const weightsExist = existsSync10(weightsPath);
9584
10373
  const sidecarReady = venvExists && depsOk;
9585
10374
  const sidecarOptedIn = venvExists;
9586
10375
  const sidecarBroken = sidecarOptedIn && !sidecarReady;
9587
10376
  const missing = sidecarOptedIn ? "fail" : "info";
9588
10377
  const repair = "reaper-mcp setup-sidecar";
9589
- const home = (p) => p.replace(homedir8(), "~");
10378
+ const home = (p) => p.replace(homedir9(), "~");
9590
10379
  const sidecar = {
9591
10380
  title: "Python sidecar",
9592
10381
  note: "optional \xB7 lets Claude listen to the audio",
@@ -9618,10 +10407,10 @@ async function doctor() {
9618
10407
  ]
9619
10408
  };
9620
10409
  const extensionChecks = await checkExtensions();
9621
- const sections2 = [{ title: "Core", checks: core2 }, sidecar];
9622
- if (extensionChecks.length > 0) sections2.push({ title: "Extensions", checks: extensionChecks });
10410
+ const sections3 = [{ title: "Core", checks: core2 }, sidecar];
10411
+ if (extensionChecks.length > 0) sections3.push({ title: "Extensions", checks: extensionChecks });
9623
10412
  const extensionsBroken = extensionChecks.some((c) => c.status === "fail");
9624
- console.log(renderDoctor(sections2, { version: readServiceVersion(), color: useColor() }));
10413
+ console.log(renderDoctor(sections3, { version: readServiceVersion(), color: useColor() }));
9625
10414
  process.exit(bridgeRunning && knowledgeLinked && mcpRegistered && !sidecarBroken && !extensionsBroken ? 0 : 1);
9626
10415
  }
9627
10416
  async function serve() {
@@ -9631,7 +10420,7 @@ async function serve() {
9631
10420
  startDiagnosticsPoller();
9632
10421
  startEventsPoller();
9633
10422
  log("Starting REAPER MCP Server...");
9634
- log(`Entry: ${fileURLToPath5(import.meta.url)}`);
10423
+ log(`Entry: ${fileURLToPath6(import.meta.url)}`);
9635
10424
  const tracer = getTracer();
9636
10425
  await tracer.startActiveSpan("reaper-mcp startup", { kind: SpanKind5.INTERNAL }, async (startupSpan) => {
9637
10426
  try {