@mthines/reaper-mcp 0.104.0 → 0.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.js CHANGED
@@ -108,7 +108,7 @@ function createUi(opts = {}) {
108
108
  return chars.map((ch, i) => ch === " " ? ch : `\x1B[${rgb(lerp(BRAND, from + (to - from) * i / Math.max(chars.length - 1, 1)))}m${ch}`).join("") + "\x1B[0m";
109
109
  };
110
110
  const fancy = tty && columns >= LOGO_WIDTH + 2;
111
- const ui2 = {
111
+ const ui3 = {
112
112
  level,
113
113
  columns,
114
114
  tty,
@@ -137,7 +137,7 @@ ${sgr("1", title)}`,
137
137
  return ["", ...logo, "", wave, ""].join("\n");
138
138
  }
139
139
  };
140
- return ui2;
140
+ return ui3;
141
141
  }
142
142
 
143
143
  // apps/reaper-mcp-server/src/telemetry-consent.ts
@@ -149,17 +149,17 @@ var DEFAULT_DESTINATION = {
149
149
  };
150
150
  var CONSENT_SERVICE_NAME = "reaper-mcp-consent";
151
151
  var TELEMETRY_DOC_URL = "https://github.com/mthines/reaper-mcp/blob/main/TELEMETRY.md";
152
- function renderTelemetryNotice(ui2 = createUi({ level: 0, tty: false })) {
153
- return `${ui2.bold("Pseudonymous usage telemetry is ON by default.")}
152
+ function renderTelemetryNotice(ui3 = createUi({ level: 0, tty: false })) {
153
+ return `${ui3.bold("Pseudonymous usage telemetry is ON by default.")}
154
154
  reaper-mcp is built by one developer. To see which tools people use, which fail,
155
155
  and how fast they are, it sends pseudonymous usage data: tool names, error types,
156
156
  timings, and app/OS versions, tagged with a random install id.
157
157
  It never sends your projects, track names, parameters, file paths or error text.
158
158
  Your answer below is counted once, anonymously (on or off, no install id).
159
159
 
160
- Opt out any time: ${ui2.cmd("reaper-mcp telemetry off")}
161
- ${ui2.dim("(or set REAPER_MCP_TELEMETRY=0 or DO_NOT_TRACK=1)")}
162
- Details: ${ui2.link(TELEMETRY_DOC_URL)}`;
160
+ Opt out any time: ${ui3.cmd("reaper-mcp telemetry off")}
161
+ ${ui3.dim("(or set REAPER_MCP_TELEMETRY=0 or DO_NOT_TRACK=1)")}
162
+ Details: ${ui3.link(TELEMETRY_DOC_URL)}`;
163
163
  }
164
164
  var TELEMETRY_NOTICE = renderTelemetryNotice();
165
165
  var FALSY = /* @__PURE__ */ new Set(["0", "false", "off", "no"]);
@@ -238,13 +238,13 @@ function lineReader(input) {
238
238
  close: () => rl.close()
239
239
  };
240
240
  }
241
- async function confirmOptOut(lines, output, ui2) {
241
+ async function confirmOptOut(lines, output, ui3) {
242
242
  output.write(`
243
- ${ui2.bold("Totally your call, no hard feelings \u{1F64F}")}
243
+ ${ui3.bold("Totally your call, no hard feelings \u{1F64F}")}
244
244
  reaper-mcp is just me: one developer, building it in my spare time. These counts help me a ton,
245
245
  they show me what to fix next. I can't see your music, projects, track names or files. Ever.
246
246
 
247
- ${ui2.bold("Turn telemetry off anyway?")} ${ui2.dim("[y/N]")} `);
247
+ ${ui3.bold("Turn telemetry off anyway?")} ${ui3.dim("[y/N]")} `);
248
248
  const answer = (await lines.next()).trim().toLowerCase();
249
249
  return answer === "y" || answer === "yes";
250
250
  }
@@ -260,20 +260,20 @@ async function confirmOptOutPrompt(io) {
260
260
  async function firstRunTelemetryNotice(io, dir = defaultConfigDir(), env = process.env, destination = DEFAULT_DESTINATION) {
261
261
  const config = readTelemetryConfig(dir);
262
262
  if (config.telemetryNoticeShown || resolveTelemetry(env, config, destination).mode !== "default") return void 0;
263
- const ui2 = io.ui ?? createUi({ level: 0, tty: false });
263
+ const ui3 = io.ui ?? createUi({ level: 0, tty: false });
264
264
  io.output.write(`
265
- ${renderTelemetryNotice(ui2)}
265
+ ${renderTelemetryNotice(ui3)}
266
266
 
267
267
  `);
268
268
  let keep = true;
269
269
  if (io.interactive) {
270
270
  const lines = lineReader(io.input);
271
- io.output.write(`${ui2.bold("Keep usage telemetry on?")} ${ui2.dim("[Y/n]")} `);
271
+ io.output.write(`${ui3.bold("Keep usage telemetry on?")} ${ui3.dim("[Y/n]")} `);
272
272
  const answer = (await lines.next()).trim().toLowerCase();
273
- keep = !(answer === "n" || answer === "no") || !await confirmOptOut(lines, io.output, ui2);
273
+ keep = !(answer === "n" || answer === "no") || !await confirmOptOut(lines, io.output, ui3);
274
274
  lines.close();
275
- io.output.write(keep ? `${ui2.mark("ok")} Thanks \u2014 telemetry stays on.
276
- ` : `${ui2.mark("ok")} Telemetry is off. Turn it back on with \`${ui2.cmd("reaper-mcp telemetry on")}\`.
275
+ io.output.write(keep ? `${ui3.mark("ok")} Thanks \u2014 telemetry stays on.
276
+ ` : `${ui3.mark("ok")} Telemetry is off. Turn it back on with \`${ui3.cmd("reaper-mcp telemetry on")}\`.
277
277
  `);
278
278
  }
279
279
  writeTelemetryConfig({ telemetry: keep, telemetryNoticeShown: true }, dir);
@@ -1138,12 +1138,12 @@ async function sendCommand(type, params = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
1138
1138
  span.setAttribute("reaper.bridge.poll_attempts", pollAttempts);
1139
1139
  span.setStatus({ code: SpanStatusCode.ERROR, message: timeoutMsg });
1140
1140
  emitLog(
1141
- "error",
1141
+ untraced ? "warn" : "error",
1142
1142
  `Bridge command ${type} timed out after ${timeoutMs}ms`,
1143
1143
  { "rpc.method": type, "reaper.bridge.command.id": id, "error.type": "timeout", "reaper.bridge.timeout_ms": timeoutMs },
1144
1144
  { eventName: "reaper.bridge.command.timeout" }
1145
1145
  );
1146
- noteLoggedFailure(true);
1146
+ noteLoggedFailure(!untraced);
1147
1147
  finish("timeout");
1148
1148
  return {
1149
1149
  id,
@@ -1558,10 +1558,10 @@ function noteScratchTrack(name, now = Date.now()) {
1558
1558
  }
1559
1559
  function runSeconds(tag, now = Date.now()) {
1560
1560
  const key = tag?.trim();
1561
- const start = key ? runStarts.get(key) : void 0;
1561
+ const start2 = key ? runStarts.get(key) : void 0;
1562
1562
  if (key) runStarts.delete(key);
1563
- if (start === void 0 || now < start || now - start > MAX_RUN_MS) return void 0;
1564
- return Math.round((now - start) / 1e3);
1563
+ if (start2 === void 0 || now < start2 || now - start2 > MAX_RUN_MS) return void 0;
1564
+ return Math.round((now - start2) / 1e3);
1565
1565
  }
1566
1566
  function given(value) {
1567
1567
  return value?.trim() ? value : void 0;
@@ -1987,10 +1987,10 @@ function registerTrackTools(server) {
1987
1987
  tracks2 = tracks2.filter((t) => String(t.name ?? "").toLowerCase().includes(needle));
1988
1988
  }
1989
1989
  const total = tracks2.length;
1990
- const start = offset ?? 0;
1991
- const page = tracks2.slice(start, limit != null ? start + limit : void 0);
1990
+ const start2 = offset ?? 0;
1991
+ const page = tracks2.slice(start2, limit != null ? start2 + limit : void 0);
1992
1992
  const out2 = compact ? page.map(compactTrack) : page;
1993
- const body = { total, offset: start, returned: out2.length, hasMore: start + out2.length < total, tracks: out2 };
1993
+ const body = { total, offset: start2, returned: out2.length, hasMore: start2 + out2.length < total, tracks: out2 };
1994
1994
  return { content: [{ type: "text", text: JSON.stringify(body, null, 2) }] };
1995
1995
  }
1996
1996
  );
@@ -3291,12 +3291,12 @@ function registerSelectionTools(server) {
3291
3291
  start: z15.coerce.number().min(0).describe("Start position in seconds"),
3292
3292
  end: z15.coerce.number().min(0).describe("End position in seconds")
3293
3293
  },
3294
- async ({ start, end }) => {
3295
- const res = await sendCommand("set_time_selection", { start, end });
3294
+ async ({ start: start2, end }) => {
3295
+ const res = await sendCommand("set_time_selection", { start: start2, end });
3296
3296
  if (!res.success) {
3297
3297
  return { content: [{ type: "text", text: `Error: ${res.error}` }], isError: true };
3298
3298
  }
3299
- return { content: [{ type: "text", text: `Time selection set: ${start}s - ${end}s` }] };
3299
+ return { content: [{ type: "text", text: `Time selection set: ${start2}s - ${end}s` }] };
3300
3300
  }
3301
3301
  );
3302
3302
  const selectionMode = z15.enum(["replace", "add"]).optional().describe("replace (default): select exactly these; add: keep the current selection");
@@ -3561,8 +3561,8 @@ function registerMarkerTools(server) {
3561
3561
  name: z17.string().optional().describe("Region name"),
3562
3562
  color: z17.coerce.number().optional().describe("REAPER native color int (0 = default)")
3563
3563
  },
3564
- async ({ start, end, name, color }) => {
3565
- const res = await sendCommand("add_region", { start, end, name, color });
3564
+ async ({ start: start2, end, name, color }) => {
3565
+ const res = await sendCommand("add_region", { start: start2, end, name, color });
3566
3566
  if (!res.success) {
3567
3567
  return { content: [{ type: "text", text: `Error: ${res.error}` }], isError: true };
3568
3568
  }
@@ -4129,9 +4129,9 @@ function recordEdit(command2, args, data) {
4129
4129
  const operation = command2 === "process_items" ? String(args["operation"]) : OPERATION[command2];
4130
4130
  const items = itemsChanged(command2, args, d);
4131
4131
  const num3 = (k) => typeof d[k] === "number" ? d[k] : void 0;
4132
- const start = num3("start");
4132
+ const start2 = num3("start");
4133
4133
  const end = num3("end");
4134
- const length = num3("length") ?? num3("span") ?? (start !== void 0 && end !== void 0 ? end - start : void 0);
4134
+ const length = num3("length") ?? num3("span") ?? (start2 !== void 0 && end !== void 0 ? end - start2 : void 0);
4135
4135
  trace5.getActiveSpan()?.setAttributes({
4136
4136
  "reaper.arrange.operation": operation,
4137
4137
  "reaper.arrange.items_changed": items,
@@ -4974,18 +4974,18 @@ function ensureWebInterface(ini, port) {
4974
4974
  }
4975
4975
  const eol = ini.includes("\r\n") ? "\r\n" : "\n";
4976
4976
  const lines = ini.split(/\r?\n/);
4977
- let start = lines.findIndex((l) => l.trim() === "[REAPER]");
4978
- if (start === -1) {
4977
+ let start2 = lines.findIndex((l) => l.trim() === "[REAPER]");
4978
+ if (start2 === -1) {
4979
4979
  lines.unshift("[REAPER]");
4980
- start = 0;
4980
+ start2 = 0;
4981
4981
  }
4982
- let end = lines.findIndex((l, i) => i > start && l.startsWith("["));
4982
+ let end = lines.findIndex((l, i) => i > start2 && l.startsWith("["));
4983
4983
  if (end === -1) end = lines.length;
4984
- while (end - 1 > start && lines[end - 1].trim() === "") end--;
4985
- const cntIdx = lines.findIndex((l, i) => i > start && i < end && l.startsWith("csurf_cnt="));
4984
+ while (end - 1 > start2 && lines[end - 1].trim() === "") end--;
4985
+ const cntIdx = lines.findIndex((l, i) => i > start2 && i < end && l.startsWith("csurf_cnt="));
4986
4986
  const count = cntIdx === -1 ? 0 : Number(lines[cntIdx].slice("csurf_cnt=".length)) || 0;
4987
4987
  const entry = `csurf_${count}=HTTP 0 ${port} '' '${BRIDGE_UI_FILE}' 0 ''`;
4988
- const staleIdx = lines.findIndex((l, i) => i > start && i < end && l.startsWith(`csurf_${count}=`));
4988
+ const staleIdx = lines.findIndex((l, i) => i > start2 && i < end && l.startsWith(`csurf_${count}=`));
4989
4989
  if (staleIdx !== -1) lines[staleIdx] = entry;
4990
4990
  if (cntIdx === -1) {
4991
4991
  lines.splice(end, 0, `csurf_cnt=${count + 1}`, ...staleIdx === -1 ? [entry] : []);
@@ -5564,10 +5564,10 @@ function parseSetupArgs(argv, env = process.env, tty = Boolean(process.stdin.isT
5564
5564
  if (has("--without-aesthetics")) picks.aesthetics = false;
5565
5565
  const ci = Boolean(env["CI"]) && env["CI"] !== "false" && env["CI"] !== "0";
5566
5566
  const yes = has("--yes") || has("-y") || has("--non-interactive");
5567
- const list2 = has("--list");
5567
+ const list3 = has("--list");
5568
5568
  return {
5569
- interactive: tty && !ci && !yes && !list2 && Object.keys(picks).length === 0,
5570
- list: list2,
5569
+ interactive: tty && !ci && !yes && !list3 && Object.keys(picks).length === 0,
5570
+ list: list3,
5571
5571
  json: has("--json"),
5572
5572
  picks,
5573
5573
  unknown: argv.filter((a) => a.startsWith("-") && !SETUP_FLAGS.has(a))
@@ -6239,13 +6239,13 @@ function registerOfflineTools(server) {
6239
6239
  const startedAt = Date.now();
6240
6240
  const sidecar = getSidecarClient();
6241
6241
  if (!sidecar.isAvailable()) return error(SIDECAR_NOT_INSTALLED_MSG);
6242
- const start = startTime ?? 0;
6243
- const end = endTime ?? start + (durationSeconds ?? DEFAULT_OFFLINE_SECONDS);
6244
- if (end <= start) return error("endTime must be greater than startTime");
6245
- if (end - start > MAX_OFFLINE_SECONDS) return error(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call`);
6242
+ const start2 = startTime ?? 0;
6243
+ const end = endTime ?? start2 + (durationSeconds ?? DEFAULT_OFFLINE_SECONDS);
6244
+ if (end <= start2) return error("endTime must be greater than startTime");
6245
+ if (end - start2 > MAX_OFFLINE_SECONDS) return error(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call`);
6246
6246
  let wav;
6247
6247
  try {
6248
- wav = await renderTrack(trackIndex5, start, end);
6248
+ wav = await renderTrack(trackIndex5, start2, end);
6249
6249
  } catch (err) {
6250
6250
  return error(err instanceof Error ? err.message : String(err));
6251
6251
  }
@@ -6255,12 +6255,12 @@ function registerOfflineTools(server) {
6255
6255
  ...sectionSeconds ? { sectionSeconds } : {},
6256
6256
  ...referencePath ? { referencePath, referenceStartTime, referenceEndTime } : {}
6257
6257
  });
6258
- const data = toProjectTime(result, start);
6258
+ const data = toProjectTime(result, start2);
6259
6259
  logToolResult("analyze_track_offline", args, startedAt, offlineSummary(wav.trackName ?? `Track ${trackIndex5 + 1}`, data));
6260
6260
  return text({
6261
6261
  trackIndex: trackIndex5,
6262
6262
  trackName: wav.trackName,
6263
- startTime: start,
6263
+ startTime: start2,
6264
6264
  endTime: end,
6265
6265
  ...data
6266
6266
  });
@@ -6473,9 +6473,9 @@ function pulsePoints(hits, o, rangeStart) {
6473
6473
  });
6474
6474
  return points;
6475
6475
  }
6476
- function sections(hits, start, end, seconds2) {
6476
+ function sections(hits, start2, end, seconds2) {
6477
6477
  const out2 = [];
6478
- for (let s = start; s < end; s += seconds2) {
6478
+ for (let s = start2; s < end; s += seconds2) {
6479
6479
  const e = Math.min(end, s + seconds2);
6480
6480
  const inside = hits.filter((h) => h.time >= s && h.time < e);
6481
6481
  out2.push({
@@ -6510,31 +6510,31 @@ async function detect(args) {
6510
6510
  minGapMs: args.minGapMs ?? 50
6511
6511
  };
6512
6512
  let result;
6513
- let start;
6513
+ let start2;
6514
6514
  let end;
6515
6515
  let source;
6516
6516
  if (path != null) {
6517
6517
  const position = args.filePosition ?? 0;
6518
- start = args.startTime ?? position;
6518
+ start2 = args.startTime ?? position;
6519
6519
  end = args.endTime ?? null;
6520
- if (start < position) return `startTime ${start} is before the file starts (filePosition ${position})`;
6521
- if (end != null && end <= start) return "endTime must be greater than startTime";
6520
+ if (start2 < position) return `startTime ${start2} is before the file starts (filePosition ${position})`;
6521
+ if (end != null && end <= start2) return "endTime must be greater than startTime";
6522
6522
  result = await sidecar.transients({
6523
6523
  path,
6524
- ...start > position ? { startTime: start - position } : {},
6524
+ ...start2 > position ? { startTime: start2 - position } : {},
6525
6525
  ...end != null ? { endTime: end - position } : {},
6526
6526
  ...options
6527
6527
  });
6528
6528
  for (const t of result["transients"] ?? []) t.time = round(t.time + position);
6529
6529
  source = { path, filePosition: position };
6530
6530
  } else {
6531
- start = args.startTime ?? 0;
6532
- end = args.endTime ?? start + DEFAULT_TRACK_SECONDS;
6533
- if (end <= start) return "endTime must be greater than startTime";
6534
- if (end - start > MAX_OFFLINE_SECONDS) return `Range too long: max ${MAX_OFFLINE_SECONDS} s per call`;
6531
+ start2 = args.startTime ?? 0;
6532
+ end = args.endTime ?? start2 + DEFAULT_TRACK_SECONDS;
6533
+ if (end <= start2) return "endTime must be greater than startTime";
6534
+ if (end - start2 > MAX_OFFLINE_SECONDS) return `Range too long: max ${MAX_OFFLINE_SECONDS} s per call`;
6535
6535
  let wav;
6536
6536
  try {
6537
- wav = await renderTrack(trackIndex5, start, end, { dry: true });
6537
+ wav = await renderTrack(trackIndex5, start2, end, { dry: true });
6538
6538
  } catch (err) {
6539
6539
  return err instanceof Error ? err.message : String(err);
6540
6540
  }
@@ -6543,7 +6543,7 @@ async function detect(args) {
6543
6543
  } finally {
6544
6544
  await discardRender(wav);
6545
6545
  }
6546
- for (const t of result["transients"] ?? []) t.time = round(t.time + start);
6546
+ for (const t of result["transients"] ?? []) t.time = round(t.time + start2);
6547
6547
  source = { trackIndex: trackIndex5, trackName: wav.trackName };
6548
6548
  }
6549
6549
  const all = result["transients"] ?? [];
@@ -6552,8 +6552,8 @@ async function detect(args) {
6552
6552
  const durationSeconds = Number(result["durationSeconds"] ?? 0);
6553
6553
  return {
6554
6554
  source,
6555
- start,
6556
- end: end ?? round(start + durationSeconds, 3),
6555
+ start: start2,
6556
+ end: end ?? round(start2 + durationSeconds, 3),
6557
6557
  durationSeconds,
6558
6558
  tempo: result["tempo"],
6559
6559
  detected: all.length,
@@ -6756,20 +6756,20 @@ async function detect2(args) {
6756
6756
  minNoteMs: args.minNoteMs ?? 80
6757
6757
  };
6758
6758
  const position = args.filePosition ?? 0;
6759
- const start = args.startTime ?? position;
6760
- const end = args.endTime ?? start + DEFAULT_TRACK_SECONDS2;
6761
- if (end <= start) return "endTime must be greater than startTime";
6762
- if (end - start > MAX_OFFLINE_SECONDS) return `Range too long: max ${MAX_OFFLINE_SECONDS} s per call`;
6759
+ const start2 = args.startTime ?? position;
6760
+ const end = args.endTime ?? start2 + DEFAULT_TRACK_SECONDS2;
6761
+ if (end <= start2) return "endTime must be greater than startTime";
6762
+ if (end - start2 > MAX_OFFLINE_SECONDS) return `Range too long: max ${MAX_OFFLINE_SECONDS} s per call`;
6763
6763
  let result;
6764
6764
  let offset;
6765
6765
  if (path != null) {
6766
- if (start < position) return `startTime ${start} is before the file starts (filePosition ${position})`;
6767
- result = await sidecar.detectPitch({ path, startTime: start - position, endTime: end - position, ...options });
6766
+ if (start2 < position) return `startTime ${start2} is before the file starts (filePosition ${position})`;
6767
+ result = await sidecar.detectPitch({ path, startTime: start2 - position, endTime: end - position, ...options });
6768
6768
  offset = position;
6769
6769
  } else {
6770
6770
  let wav;
6771
6771
  try {
6772
- wav = await renderTrack(trackIndex5, start, end, { dry: true });
6772
+ wav = await renderTrack(trackIndex5, start2, end, { dry: true });
6773
6773
  } catch (err) {
6774
6774
  return err instanceof Error ? err.message : String(err);
6775
6775
  }
@@ -6778,7 +6778,7 @@ async function detect2(args) {
6778
6778
  } finally {
6779
6779
  await discardRender(wav);
6780
6780
  }
6781
- offset = start;
6781
+ offset = start2;
6782
6782
  }
6783
6783
  const notes = (result["notes"] ?? []).map((n) => ({
6784
6784
  ...n,
@@ -6786,30 +6786,30 @@ async function detect2(args) {
6786
6786
  end: round2(n.end + offset)
6787
6787
  }));
6788
6788
  const { notes: _notes, ...summary } = result;
6789
- return { start, end, notes, summary };
6789
+ return { start: start2, end, notes, summary };
6790
6790
  }
6791
6791
  async function listItems(trackIndex5) {
6792
6792
  const res = await sendCommand("list_media_items", { trackIndex: trackIndex5 });
6793
6793
  if (!res.success) return res.error ?? "list_media_items failed";
6794
6794
  return (res.data.items ?? []).filter((i) => !i.isMidi);
6795
6795
  }
6796
- async function isolate(trackIndex5, start, end) {
6796
+ async function isolate(trackIndex5, start2, end) {
6797
6797
  let items = await listItems(trackIndex5);
6798
6798
  if (typeof items === "string") return items;
6799
- const holds = (i) => i.position <= start + EPS && i.position + i.length >= end - EPS;
6799
+ const holds = (i) => i.position <= start2 + EPS && i.position + i.length >= end - EPS;
6800
6800
  let item = items.find(holds);
6801
6801
  if (!item) return "the note is not inside one item";
6802
6802
  if (end < item.position + item.length - EPS) {
6803
6803
  const res = await sendCommand("split_media_item", { trackIndex: trackIndex5, itemIndex: item.itemIndex, position: end });
6804
6804
  if (!res.success) return res.error ?? "split failed";
6805
6805
  }
6806
- if (start > item.position + EPS) {
6807
- const res = await sendCommand("split_media_item", { trackIndex: trackIndex5, itemIndex: item.itemIndex, position: start });
6806
+ if (start2 > item.position + EPS) {
6807
+ const res = await sendCommand("split_media_item", { trackIndex: trackIndex5, itemIndex: item.itemIndex, position: start2 });
6808
6808
  if (!res.success) return res.error ?? "split failed";
6809
6809
  }
6810
6810
  items = await listItems(trackIndex5);
6811
6811
  if (typeof items === "string") return items;
6812
- item = items.find((i) => Math.abs(i.position - start) < EPS && i.position + i.length <= end + EPS);
6812
+ item = items.find((i) => Math.abs(i.position - start2) < EPS && i.position + i.length <= end + EPS);
6813
6813
  return item ? item.itemIndex : "could not find the piece after splitting";
6814
6814
  }
6815
6815
  var { path: _path, filePosition: _filePosition, ...trackSchema } = {
@@ -6928,28 +6928,28 @@ async function resolveSource(args, maxSeconds, defaultSeconds = DEFAULT_TRACK_SE
6928
6928
  const { trackIndex: trackIndex5, path, startTime, endTime } = args;
6929
6929
  if (trackIndex5 == null === (path == null)) return "Give either trackIndex or path";
6930
6930
  if (startTime != null && endTime != null && endTime <= startTime) return "endTime must be greater than startTime";
6931
- const start = startTime ?? 0;
6931
+ const start2 = startTime ?? 0;
6932
6932
  if (path != null) {
6933
- if (endTime != null && endTime - start > maxSeconds) return `Range too long: max ${maxSeconds} s per call`;
6933
+ if (endTime != null && endTime - start2 > maxSeconds) return `Range too long: max ${maxSeconds} s per call`;
6934
6934
  return {
6935
6935
  path,
6936
6936
  name: basename2(path, extname(path)),
6937
6937
  offset: 0,
6938
6938
  window: { ...startTime != null ? { startTime } : {}, ...endTime != null ? { endTime } : {} },
6939
- ...endTime != null ? { seconds: endTime - start } : {}
6939
+ ...endTime != null ? { seconds: endTime - start2 } : {}
6940
6940
  };
6941
6941
  }
6942
- const end = endTime ?? start + Math.min(defaultSeconds, maxSeconds);
6943
- if (end - start > maxSeconds) return `Range too long: max ${maxSeconds} s per call`;
6944
- const wav = await renderTrack(trackIndex5, start, end);
6942
+ const end = endTime ?? start2 + Math.min(defaultSeconds, maxSeconds);
6943
+ if (end - start2 > maxSeconds) return `Range too long: max ${maxSeconds} s per call`;
6944
+ const wav = await renderTrack(trackIndex5, start2, end);
6945
6945
  return {
6946
6946
  path: wav.wavPath,
6947
6947
  name: wav.trackName ?? (trackIndex5 === -1 ? "Master" : `Track ${trackIndex5 + 1}`),
6948
- offset: start,
6948
+ offset: start2,
6949
6949
  window: {},
6950
6950
  temp: wav,
6951
6951
  trackIndex: trackIndex5,
6952
- seconds: end - start
6952
+ seconds: end - start2
6953
6953
  };
6954
6954
  }
6955
6955
  function shift(span, by) {
@@ -8034,14 +8034,14 @@ function parseSmf(data) {
8034
8034
  for (let t = 0; t < trackCount && !r.done; t++) {
8035
8035
  const id = r.ascii(4);
8036
8036
  const len = r.u32();
8037
- const start = r.pos;
8037
+ const start2 = r.pos;
8038
8038
  if (id !== "MTrk") {
8039
- r.pos = start + len;
8039
+ r.pos = start2 + len;
8040
8040
  t--;
8041
8041
  continue;
8042
8042
  }
8043
- const tr = new Reader(data, Math.min(start + len, data.length));
8044
- tr.pos = start;
8043
+ const tr = new Reader(data, Math.min(start2 + len, data.length));
8044
+ tr.pos = start2;
8045
8045
  const track = { name: "", notes: [], cc: [] };
8046
8046
  const open = /* @__PURE__ */ new Map();
8047
8047
  let tick = 0;
@@ -8110,7 +8110,7 @@ function parseSmf(data) {
8110
8110
  for (const n of track.notes) endTicks = Math.max(endTicks, Math.round((n.start + n.length) * ppq));
8111
8111
  track.notes.sort((a, b) => a.start - b.start || a.pitch - b.pitch);
8112
8112
  if (track.notes.length || track.cc.length) tracks2.push(track);
8113
- r.pos = start + len;
8113
+ r.pos = start2 + len;
8114
8114
  }
8115
8115
  return { format, ppq, tracks: tracks2, tempo, tempoChanges, timeSignature, lengthQN: endTicks / ppq, skipped };
8116
8116
  }
@@ -8370,8 +8370,8 @@ function registerCompositionTools(server) {
8370
8370
  args.startTime = r.startTime;
8371
8371
  args.endTime = r.endTime;
8372
8372
  }
8373
- const start = args.startTime ?? 0;
8374
- if (args.endTime != null && args.endTime <= start) return fail4("endTime must be greater than startTime");
8373
+ const start2 = args.startTime ?? 0;
8374
+ if (args.endTime != null && args.endTime <= start2) return fail4("endTime must be greater than startTime");
8375
8375
  if (trackIndex5 === -1 && args.source === "midi") return fail4('The master track holds no MIDI notes: give a track index, or source "audio"');
8376
8376
  let profile = null;
8377
8377
  let source;
@@ -8380,7 +8380,7 @@ function registerCompositionTools(server) {
8380
8380
  if (path == null && args.source !== "audio" && trackIndex5 >= 0) {
8381
8381
  const res = await sendCommand("_midi_pitch_profile", {
8382
8382
  trackIndex: trackIndex5,
8383
- startTime: start,
8383
+ startTime: start2,
8384
8384
  ...args.endTime != null ? { endTime: args.endTime } : {}
8385
8385
  });
8386
8386
  if (!res.success) return fail4(`Error: ${res.error}`);
@@ -8400,17 +8400,17 @@ function registerCompositionTools(server) {
8400
8400
  return fail4(SIDECAR_NOT_INSTALLED_MSG);
8401
8401
  }
8402
8402
  if (path != null) {
8403
- const c = await sidecar.chroma({ path, ...start > 0 ? { startTime: start } : {}, ...args.endTime != null ? { endTime: args.endTime } : {} });
8403
+ const c = await sidecar.chroma({ path, ...start2 > 0 ? { startTime: start2 } : {}, ...args.endTime != null ? { endTime: args.endTime } : {} });
8404
8404
  profile = c.chroma;
8405
8405
  source = "file";
8406
8406
  name = basename3(path);
8407
8407
  extra = { durationSeconds: c.durationSeconds };
8408
8408
  } else {
8409
- const end = args.endTime ?? start + DEFAULT_KEY_SECONDS;
8410
- if (end - start > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call`);
8409
+ const end = args.endTime ?? start2 + DEFAULT_KEY_SECONDS;
8410
+ if (end - start2 > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call`);
8411
8411
  let wav;
8412
8412
  try {
8413
- wav = await renderTrack(trackIndex5, start, end, { dry: true });
8413
+ wav = await renderTrack(trackIndex5, start2, end, { dry: true });
8414
8414
  } catch (err) {
8415
8415
  return fail4(err instanceof Error ? err.message : String(err));
8416
8416
  }
@@ -8514,41 +8514,41 @@ function registerCompositionTools(server) {
8514
8514
  };
8515
8515
  if (path != null) {
8516
8516
  if (!sidecar.isAvailable()) return needSidecar();
8517
- const start = args.startTime ?? 0;
8518
- const end = args.endTime ?? start + MAX_OFFLINE_SECONDS;
8519
- if (end - start > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call`);
8520
- const grid = fileGrid(end - start, args.bpm, args.beatsPerBar ?? 4, per, windowSeconds);
8517
+ const start2 = args.startTime ?? 0;
8518
+ const end = args.endTime ?? start2 + MAX_OFFLINE_SECONDS;
8519
+ if (end - start2 > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call`);
8520
+ const grid = fileGrid(end - start2, args.bpm, args.beatsPerBar ?? 4, per, windowSeconds);
8521
8521
  if (!grid) return fail4(`More than ${MAX_SEGMENTS} segments: use a shorter range, per "bar" or a longer windowSeconds`);
8522
8522
  const model = await useModel();
8523
8523
  if (typeof model === "string") return fail4(model);
8524
8524
  if (model) {
8525
- const m = await runModel(path, start, args.endTime, grid, end - start);
8525
+ const m = await runModel(path, start2, args.endTime, grid, end - start2);
8526
8526
  const dur = m.duration;
8527
8527
  const kept = grid.map((g, i) => ({ g, p: m.picks[i] })).filter(({ g }) => g.start < dur - 1e-6);
8528
- segments = kept.map(({ g }) => ({ ...g, start: start + g.start, end: start + Math.min(g.end, dur), profile: [] }));
8528
+ segments = kept.map(({ g }) => ({ ...g, start: start2 + g.start, end: start2 + Math.min(g.end, dur), profile: [] }));
8529
8529
  picks = kept.map(({ p }) => p);
8530
8530
  profile = m.profile;
8531
8531
  source = "file";
8532
8532
  name = basename3(path);
8533
- range = { startTime: start, endTime: start + dur };
8533
+ range = { startTime: start2, endTime: start2 + dur };
8534
8534
  } else {
8535
8535
  const c = await sidecar.chroma({
8536
8536
  path,
8537
- ...start > 0 ? { startTime: start } : {},
8537
+ ...start2 > 0 ? { startTime: start2 } : {},
8538
8538
  ...args.endTime != null ? { endTime: args.endTime } : {},
8539
8539
  segments: grid.map((g) => [g.start, g.end])
8540
8540
  });
8541
8541
  const dur = c.durationSeconds;
8542
8542
  segments = grid.filter((g) => g.start < dur - 1e-6).map((g, i) => ({
8543
8543
  ...g,
8544
- start: start + g.start,
8545
- end: start + Math.min(g.end, dur),
8544
+ start: start2 + g.start,
8545
+ end: start2 + Math.min(g.end, dur),
8546
8546
  profile: c.segments?.[i] ?? []
8547
8547
  }));
8548
8548
  profile = c.chroma;
8549
8549
  source = "file";
8550
8550
  name = basename3(path);
8551
- range = { startTime: start, endTime: start + dur };
8551
+ range = { startTime: start2, endTime: start2 + dur };
8552
8552
  }
8553
8553
  } else {
8554
8554
  const useMidi = args.source !== "audio" && engineArg !== "model" && trackIndex5 >= 0;
@@ -8571,20 +8571,20 @@ function registerCompositionTools(server) {
8571
8571
  } else {
8572
8572
  if (args.source === "midi") return fail4(`Track ${trackIndex5} has no MIDI notes in the range (drums on channel 10 are ignored)`);
8573
8573
  if (!sidecar.isAvailable()) return needSidecar();
8574
- const { startTime: start, endTime: end } = range;
8575
- if (end - start > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call (give startTime/endTime)`);
8574
+ const { startTime: start2, endTime: end } = range;
8575
+ if (end - start2 > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call (give startTime/endTime)`);
8576
8576
  const model = await useModel();
8577
8577
  if (typeof model === "string") return fail4(model);
8578
8578
  let wav;
8579
8579
  try {
8580
- wav = await renderTrack(trackIndex5, start, end, { dry: true });
8580
+ wav = await renderTrack(trackIndex5, start2, end, { dry: true });
8581
8581
  } catch (err) {
8582
8582
  return fail4(err instanceof Error ? err.message : String(err));
8583
8583
  }
8584
8584
  try {
8585
- const relative2 = g.segments.map((s) => ({ start: s.start - start, end: s.end - start }));
8585
+ const relative2 = g.segments.map((s) => ({ start: s.start - start2, end: s.end - start2 }));
8586
8586
  if (model) {
8587
- const m = await runModel(wav.wavPath, 0, void 0, relative2, end - start);
8587
+ const m = await runModel(wav.wavPath, 0, void 0, relative2, end - start2);
8588
8588
  segments = g.segments.map((s) => ({ ...s, profile: [] }));
8589
8589
  picks = m.picks;
8590
8590
  profile = m.profile;
@@ -8657,9 +8657,9 @@ function arrangeVoiceSketch(source, options) {
8657
8657
  const motifBeats = Math.max(4, Math.ceil(endBeat / 4) * 4);
8658
8658
  const length = bars * 4;
8659
8659
  const tempos = [];
8660
- for (let start = 0; start < length; start += motifBeats) {
8660
+ for (let start2 = 0; start2 < length; start2 += motifBeats) {
8661
8661
  for (const segment of segments) {
8662
- const beat = start + segment.beat;
8662
+ const beat = start2 + segment.beat;
8663
8663
  if (beat < length && tempos.at(-1)?.bpm !== segment.bpm) tempos.push({ beat, bpm: segment.bpm });
8664
8664
  }
8665
8665
  }
@@ -8670,12 +8670,12 @@ function arrangeVoiceSketch(source, options) {
8670
8670
  { name: "melody", channel: 0, program: 11, gain: 0.8, origin: "detected motif repeated", notes: [], cc: [] }
8671
8671
  ];
8672
8672
  const [drums, bass, harmony, melody] = tracks2;
8673
- const add2 = (track, start, duration, pitch, velocity) => {
8674
- if (start >= length || start < 0) return;
8675
- track.notes.push({ start, length: Math.min(duration, length - start), pitch, velocity, channel: track.channel });
8673
+ const add2 = (track, start2, duration, pitch, velocity) => {
8674
+ if (start2 >= length || start2 < 0) return;
8675
+ track.notes.push({ start: start2, length: Math.min(duration, length - start2), pitch, velocity, channel: track.channel });
8676
8676
  };
8677
- for (let start = 0; start < length; start += motifBeats) {
8678
- for (const n of source.melody) add2(melody, start + n.beat, n.lengthBeats, n.pitch, n.velocity);
8677
+ for (let start2 = 0; start2 < length; start2 += motifBeats) {
8678
+ for (const n of source.melody) add2(melody, start2 + n.beat, n.lengthBeats, n.pitch, n.velocity);
8679
8679
  }
8680
8680
  const edgeBars = bars >= 8 ? 2 : 1;
8681
8681
  const chorusBar = Math.floor(bars / 2);
@@ -10720,10 +10720,523 @@ Try it: reaper-mcp extension link ${basename4(r.dir)}`);
10720
10720
  }
10721
10721
  }
10722
10722
 
10723
+ // apps/reaper-mcp-server/src/instance-cli.ts
10724
+ import { execFileSync as execFileSync2, spawn as spawn2, spawnSync } from "node:child_process";
10725
+ import { existsSync as existsSync10, realpathSync, statSync as statSync3 } from "node:fs";
10726
+ import { homedir as homedir11, platform as platform6 } from "node:os";
10727
+ import { join as join15 } from "node:path";
10728
+
10729
+ // apps/reaper-mcp-server/src/harnesses.ts
10730
+ import { execFileSync } from "node:child_process";
10731
+ import { existsSync as existsSync8, mkdirSync as mkdirSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
10732
+ import { delimiter, dirname as dirname8, isAbsolute as isAbsolute3, join as join13 } from "node:path";
10733
+ import { homedir as homedir9, platform as platform4 } from "node:os";
10734
+ var HARNESSES = [
10735
+ { id: "claude", name: "Claude Code", binary: "claude", installHint: "https://claude.com/claude-code", skillsHome: "claude" },
10736
+ { id: "codex", name: "Codex CLI", binary: "codex", installHint: "npm install -g @openai/codex (or: brew install codex)", skillsHome: "agents" },
10737
+ { id: "gemini", name: "Gemini CLI", binary: "gemini", installHint: "npm install -g @google/gemini-cli", skillsHome: "agents" },
10738
+ { id: "cursor", name: "Cursor", binary: null, installHint: "https://cursor.com", skillsHome: "agents" }
10739
+ ];
10740
+ var SERVER_NAME = "reaper";
10741
+ var DEFAULT_SERVER = { name: SERVER_NAME, env: {} };
10742
+ function onPath(name, pathVar = process.env.PATH ?? "", win = platform4() === "win32") {
10743
+ const exts = win ? ["", ".exe", ".cmd", ".bat"] : [""];
10744
+ return pathVar.split(delimiter).filter(Boolean).some((dir) => exts.some((ext) => existsSync8(join13(dir, name + ext))));
10745
+ }
10746
+ function realEnv() {
10747
+ return { home: homedir9(), codexHome: process.env.CODEX_HOME || void 0, hasBinary: (name) => onPath(name) };
10748
+ }
10749
+ var configPath = (id, env) => ({
10750
+ claude: join13(env.home, ".claude.json"),
10751
+ codex: join13(env.codexHome ?? join13(env.home, ".codex"), "config.toml"),
10752
+ gemini: join13(env.home, ".gemini", "settings.json"),
10753
+ cursor: join13(env.home, ".cursor", "mcp.json")
10754
+ })[id];
10755
+ function detectHarnesses(env = realEnv()) {
10756
+ return HARNESSES.filter((h) => h.binary ? env.hasBinary(h.binary) : existsSync8(join13(env.home, ".cursor")));
10757
+ }
10758
+ function registeredServer(id, env = realEnv(), name = SERVER_NAME) {
10759
+ let text9;
10760
+ try {
10761
+ text9 = readFileSync6(configPath(id, env), "utf-8");
10762
+ } catch {
10763
+ return null;
10764
+ }
10765
+ if (id === "codex") return codexServer(text9, name);
10766
+ try {
10767
+ const server = JSON.parse(text9)?.mcpServers?.[name];
10768
+ if (!server || typeof server.command !== "string") return null;
10769
+ return { command: server.command, args: Array.isArray(server.args) ? server.args.filter((a) => typeof a === "string") : [] };
10770
+ } catch {
10771
+ return null;
10772
+ }
10773
+ }
10774
+ function codexServer(toml, name) {
10775
+ const header = new RegExp(`^\\[mcp_servers\\.(?:${name}|"${name}")\\]\\s*$`, "m").exec(toml);
10776
+ if (!header) return null;
10777
+ const rest = toml.slice(header.index + header[0].length);
10778
+ const next = /^\[/m.exec(rest);
10779
+ const section = next ? rest.slice(0, next.index) : rest;
10780
+ const command2 = /^command\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')/m.exec(section)?.[1];
10781
+ if (!command2) return null;
10782
+ const args = /^args\s*=\s*\[([^\]]*)\]/m.exec(section)?.[1] ?? "";
10783
+ const strings = (s) => [...s.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => m[1] !== void 0 ? JSON.parse(`"${m[1]}"`) : m[2]);
10784
+ return { command: strings(command2)[0], args: strings(args) };
10785
+ }
10786
+ function isStale(server) {
10787
+ return [server.command, ...server.args].filter(isAbsolute3).some((p) => !existsSync8(p));
10788
+ }
10789
+ var envFlags = (env, flag) => Object.entries(env).flatMap(([k, v]) => [flag, `${k}=${v}`]);
10790
+ function addCommand(id, node, mainJs, server = DEFAULT_SERVER) {
10791
+ switch (id) {
10792
+ case "claude":
10793
+ return { bin: "claude", args: ["mcp", "add", "--scope", "user", ...envFlags(server.env, "--env"), server.name, "--", node, mainJs, "serve"] };
10794
+ case "codex":
10795
+ return { bin: "codex", args: ["mcp", "add", server.name, ...envFlags(server.env, "--env"), "--", node, mainJs, "serve"] };
10796
+ case "gemini":
10797
+ return { bin: "gemini", args: ["mcp", "add", "--scope", "user", ...envFlags(server.env, "-e"), server.name, node, mainJs, "serve"] };
10798
+ case "cursor":
10799
+ return null;
10800
+ }
10801
+ }
10802
+ function removeCommand(id, name) {
10803
+ switch (id) {
10804
+ case "claude":
10805
+ return { bin: "claude", args: ["mcp", "remove", "--scope", "user", name] };
10806
+ case "codex":
10807
+ return { bin: "codex", args: ["mcp", "remove", name] };
10808
+ case "gemini":
10809
+ return { bin: "gemini", args: ["mcp", "remove", "--scope", "user", name] };
10810
+ case "cursor":
10811
+ return null;
10812
+ }
10813
+ }
10814
+ function manualCommand(id, node, mainJs, env = realEnv(), server = DEFAULT_SERVER) {
10815
+ const add2 = addCommand(id, node, mainJs, server);
10816
+ if (add2) return [add2.bin, ...add2.args].join(" ");
10817
+ const envPart = Object.keys(server.env).length ? `, "env": ${JSON.stringify(server.env)}` : "";
10818
+ return `add "${server.name}": { "command": "${node}", "args": ["${mainJs}", "serve"]${envPart} } under "mcpServers" in ${configPath(id, env)}`;
10819
+ }
10820
+ function quoteForCmd(arg) {
10821
+ return /[\s"]/.test(arg) ? `"${arg.replace(/"/g, '\\"')}"` : arg;
10822
+ }
10823
+ var realRunner = (bin, args) => {
10824
+ if (platform4() === "win32") execFileSync(quoteForCmd(bin), args.map(quoteForCmd), { stdio: "pipe", shell: true });
10825
+ else execFileSync(bin, args, { stdio: "pipe" });
10826
+ };
10827
+ function writeJsonServer(path, node, mainJs, server) {
10828
+ let config = {};
10829
+ if (existsSync8(path)) config = JSON.parse(readFileSync6(path, "utf-8"));
10830
+ const servers = config.mcpServers && typeof config.mcpServers === "object" ? config.mcpServers : {};
10831
+ servers[server.name] = { command: node, args: [mainJs, "serve"], ...Object.keys(server.env).length ? { env: server.env } : {} };
10832
+ config.mcpServers = servers;
10833
+ mkdirSync7(dirname8(path), { recursive: true });
10834
+ writeFileSync6(path, JSON.stringify(config, null, 2) + "\n", "utf-8");
10835
+ }
10836
+ function connectHarness(id, node, mainJs, env = realEnv(), run5 = realRunner, server = DEFAULT_SERVER) {
10837
+ const existing = registeredServer(id, env, server.name);
10838
+ if (existing && !isStale(existing)) return { id, status: "already" };
10839
+ const manual = manualCommand(id, node, mainJs, env, server);
10840
+ try {
10841
+ const add2 = addCommand(id, node, mainJs, server);
10842
+ if (!add2) {
10843
+ writeJsonServer(configPath(id, env), node, mainJs, server);
10844
+ } else {
10845
+ const remove2 = removeCommand(id, server.name);
10846
+ if (existing && remove2) run5(remove2.bin, remove2.args);
10847
+ run5(add2.bin, add2.args);
10848
+ }
10849
+ } catch (err) {
10850
+ const missing = err.code === "ENOENT";
10851
+ const first = String(err.message).split("\n")[0];
10852
+ return { id, status: "failed", detail: missing ? "its command was not found" : first, manual };
10853
+ }
10854
+ return { id, status: existing ? "replaced" : "connected" };
10855
+ }
10856
+ function parseHarnessFlag(argv) {
10857
+ if (argv.includes("--all")) return HARNESSES.map((h) => h.id);
10858
+ const i = argv.findIndex((a) => a === "--harness" || a.startsWith("--harness="));
10859
+ if (i < 0) return null;
10860
+ const value = argv[i].includes("=") ? argv[i].split("=")[1] : argv[i + 1];
10861
+ const ids = (value ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
10862
+ const known = HARNESSES.map((h) => h.id);
10863
+ const bad = ids.filter((s) => !known.includes(s));
10864
+ if (!ids.length || bad.length) {
10865
+ throw new Error(`Unknown harness${bad.length > 1 ? "es" : ""}: ${bad.join(", ") || "(none given)"}. Use one or more of: ${known.join(", ")}, or --all.`);
10866
+ }
10867
+ return [...new Set(ids)];
10868
+ }
10869
+ function skillsHomes(ids) {
10870
+ const chosen = HARNESSES.filter((h) => ids.includes(h.id));
10871
+ return { claude: chosen.some((h) => h.skillsHome === "claude"), agents: chosen.some((h) => h.skillsHome === "agents") };
10872
+ }
10873
+
10874
+ // apps/reaper-mcp-server/src/instance.ts
10875
+ import { copyFileSync as copyFileSync4, existsSync as existsSync9, mkdirSync as mkdirSync8, readdirSync as readdirSync2, readFileSync as readFileSync7, rmSync as rmSync2, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync7 } from "node:fs";
10876
+ import { homedir as homedir10, platform as platform5 } from "node:os";
10877
+ import { join as join14 } from "node:path";
10878
+ var INSTANCE_NAME = /^[a-z][a-z0-9-]{0,29}$/;
10879
+ function instancesRoot() {
10880
+ return process.env["REAPER_MCP_INSTANCES_DIR"] || join14(homedir10(), ".reaper-mcp", "instances");
10881
+ }
10882
+ function validateInstanceName(name) {
10883
+ if (!name || !INSTANCE_NAME.test(name)) {
10884
+ throw new Error(`Instance names are lowercase letters, digits and dashes, starting with a letter (got ${JSON.stringify(name ?? "")}), for example: background`);
10885
+ }
10886
+ if (name === "default") throw new Error('"default" is your own REAPER: pick another name');
10887
+ return name;
10888
+ }
10889
+ var instanceDir = (name, root = instancesRoot()) => join14(root, name);
10890
+ var infoPath = (name, root = instancesRoot()) => join14(instanceDir(name, root), "instance.json");
10891
+ function iniForInstance(mainIni, port) {
10892
+ const eol = mainIni.includes("\r\n") ? "\r\n" : "\n";
10893
+ const kept = mainIni.split(/\r?\n/).filter((line) => !/^csurf_(?:cnt|\d+)=/.test(line) && !/^loadlastproj=/.test(line));
10894
+ const header = kept.findIndex((l) => l.trim() === "[REAPER]");
10895
+ if (header === -1) kept.unshift("[REAPER]", "loadlastproj=0");
10896
+ else kept.splice(header + 1, 0, "loadlastproj=0");
10897
+ return ensureWebInterface(kept.join(eol), port).ini;
10898
+ }
10899
+ var SHARED_FILES = [/^reaper-vstplugins.*\.ini$/, /^reaper-auplugins.*\.ini$/, /^reaper-clap-.*\.ini$/, /^reaper-jsfx\.ini$/, /^reaper-fxfolders\.ini$/, /^reaper-fxtags\.ini$/, /^reaper-license\.rk$/];
10900
+ var SHARED_DIRS = ["UserPlugins", "FXChains", "TrackTemplates", "MIDINoteNames", "ProjectTemplates"];
10901
+ var SPLIT_DIRS = {
10902
+ Effects: /^reaper-mcp$/,
10903
+ "Effects/reaper-mcp-generated": /^examples$/,
10904
+ presets: /^js-reaper-mcp-generated_examples_/
10905
+ };
10906
+ function link(target, path, isDir) {
10907
+ try {
10908
+ symlinkSync(target, path, isDir ? platform5() === "win32" ? "junction" : "dir" : "file");
10909
+ } catch (err) {
10910
+ if (isDir) throw err;
10911
+ copyFileSync4(target, path);
10912
+ }
10913
+ }
10914
+ function linkSplit(main, instance, rel, linked) {
10915
+ const src = join14(main, rel);
10916
+ if (!existsSync9(src) || !statSync2(src).isDirectory()) return;
10917
+ const dest = join14(instance, rel);
10918
+ mkdirSync8(dest, { recursive: true });
10919
+ for (const entry of readdirSync2(src)) {
10920
+ const entryRel = `${rel}/${entry}`;
10921
+ if (SPLIT_DIRS[rel].test(entry)) continue;
10922
+ if (entryRel in SPLIT_DIRS) {
10923
+ linkSplit(main, instance, entryRel, linked);
10924
+ continue;
10925
+ }
10926
+ if (existsSync9(join14(dest, entry))) continue;
10927
+ link(join14(src, entry), join14(dest, entry), statSync2(join14(src, entry)).isDirectory());
10928
+ linked.push(entryRel);
10929
+ }
10930
+ }
10931
+ function linkShared(mainResource, instanceResource) {
10932
+ const linked = [];
10933
+ if (!existsSync9(mainResource)) return linked;
10934
+ for (const entry of readdirSync2(mainResource)) {
10935
+ if (SHARED_FILES.some((re) => re.test(entry)) || SHARED_DIRS.includes(entry)) {
10936
+ const dest = join14(instanceResource, entry);
10937
+ if (existsSync9(dest)) continue;
10938
+ link(join14(mainResource, entry), dest, SHARED_DIRS.includes(entry));
10939
+ linked.push(entry);
10940
+ }
10941
+ }
10942
+ for (const top of ["Effects", "presets"]) linkSplit(mainResource, instanceResource, top, linked);
10943
+ return linked;
10944
+ }
10945
+ function seedReaPack(mainResource, instanceResource) {
10946
+ const src = join14(mainResource, "reapack.ini");
10947
+ const dest = join14(instanceResource, "reapack.ini");
10948
+ if (!existsSync9(src) || existsSync9(dest)) return false;
10949
+ copyFileSync4(src, dest);
10950
+ return true;
10951
+ }
10952
+ function nextFreePort(used, from = DEFAULT_WEB_PORT + 1) {
10953
+ let port = from;
10954
+ while (used.includes(port)) port++;
10955
+ return port;
10956
+ }
10957
+ function listInstances(root = instancesRoot()) {
10958
+ if (!existsSync9(root)) return [];
10959
+ const out2 = [];
10960
+ for (const name of readdirSync2(root).sort()) {
10961
+ const info = readInstance(name, root);
10962
+ if (info) out2.push(info);
10963
+ }
10964
+ return out2;
10965
+ }
10966
+ function readInstance(name, root = instancesRoot()) {
10967
+ try {
10968
+ return JSON.parse(readFileSync7(infoPath(name, root), "utf-8"));
10969
+ } catch {
10970
+ return null;
10971
+ }
10972
+ }
10973
+ function createInstanceFiles(options) {
10974
+ const name = validateInstanceName(options.name);
10975
+ const root = options.root ?? instancesRoot();
10976
+ if (readInstance(name, root)) throw new Error(`Instance "${name}" exists already (reaper-mcp instance remove ${name} first, or pick another name)`);
10977
+ const mainIni = join14(options.mainResource, "reaper.ini");
10978
+ if (!existsSync9(mainIni)) throw new Error(`${mainIni} not found: start REAPER once, quit it, then create the instance (or set REAPER_RESOURCE_PATH to REAPER's resource folder)`);
10979
+ const taken = listInstances(root).map((i) => i.port);
10980
+ const port = options.port ?? nextFreePort([...taken, Number(process.env["REAPER_WEB_PORT"]) || DEFAULT_WEB_PORT]);
10981
+ if (taken.includes(port)) throw new Error(`Port ${port} is used by another instance (reaper-mcp instance list)`);
10982
+ const resourcePath = join14(instanceDir(name, root), "REAPER");
10983
+ mkdirSync8(join14(resourcePath, "Scripts"), { recursive: true });
10984
+ writeFileSync7(join14(resourcePath, "reaper.ini"), iniForInstance(readFileSync7(mainIni, "utf-8"), port), "utf-8");
10985
+ linkShared(options.mainResource, resourcePath);
10986
+ seedReaPack(options.mainResource, resourcePath);
10987
+ const info = {
10988
+ name,
10989
+ resourcePath,
10990
+ port,
10991
+ app: null,
10992
+ bundleId: null,
10993
+ appSourceMtimeMs: null,
10994
+ visible: options.visible ?? false,
10995
+ created: (/* @__PURE__ */ new Date()).toISOString()
10996
+ };
10997
+ saveInstance(info, root);
10998
+ return info;
10999
+ }
11000
+ function saveInstance(info, root = instancesRoot()) {
11001
+ writeFileSync7(infoPath(info.name, root), JSON.stringify(info, null, 2) + "\n", "utf-8");
11002
+ }
11003
+ function removeInstance(name, root = instancesRoot()) {
11004
+ validateInstanceName(name);
11005
+ if (!readInstance(name, root)) return false;
11006
+ rmSync2(instanceDir(name, root), { recursive: true, force: true });
11007
+ return true;
11008
+ }
11009
+ function launchCommand(info, project, os, reaperExe) {
11010
+ const reaperArgs = ["-newinst", "-nosplash", "-cfgfile", join14(info.resourcePath, "reaper.ini"), ...project ? [project] : []];
11011
+ if (os === "darwin" && info.app) return { bin: "open", args: ["-n", "-g", "-a", info.app, "--args", ...reaperArgs], detached: false };
11012
+ return { bin: reaperExe, args: reaperArgs, detached: true };
11013
+ }
11014
+ function bridgeAlive(resourcePath, now = Date.now()) {
11015
+ try {
11016
+ const ts = JSON.parse(readFileSync7(join14(resourcePath, "Scripts", "mcp_bridge_data", "heartbeat.json"), "utf-8")).timestamp;
11017
+ return typeof ts === "number" && Math.abs(now - ts) < 5e3;
11018
+ } catch {
11019
+ return false;
11020
+ }
11021
+ }
11022
+ function serverSpecFor(info) {
11023
+ return {
11024
+ name: `reaper-${info.name}`,
11025
+ env: { REAPER_RESOURCE_PATH: info.resourcePath, REAPER_WEB_PORT: String(info.port), REAPER_MCP_INSTANCE: info.name }
11026
+ };
11027
+ }
11028
+ function buildAppCopy(source, dest, bundleId, visible2, run5) {
11029
+ rmSync2(dest, { recursive: true, force: true });
11030
+ mkdirSync8(join14(dest, ".."), { recursive: true });
11031
+ run5("ditto", [source, dest]);
11032
+ const plist = join14(dest, "Contents", "Info.plist");
11033
+ const buddy = "/usr/libexec/PlistBuddy";
11034
+ run5(buddy, ["-c", `Set :CFBundleIdentifier ${bundleId}`, plist]);
11035
+ if (!visible2) {
11036
+ try {
11037
+ run5(buddy, ["-c", "Set :LSUIElement true", plist]);
11038
+ } catch {
11039
+ run5(buddy, ["-c", "Add :LSUIElement bool true", plist]);
11040
+ }
11041
+ }
11042
+ run5("xattr", ["-cr", dest]);
11043
+ run5("codesign", ["--force", "--deep", "--sign", "-", dest]);
11044
+ }
11045
+ function appCopyIsStale(info, sourceMtimeMs) {
11046
+ return Boolean(info.app) && info.appSourceMtimeMs !== sourceMtimeMs;
11047
+ }
11048
+
11049
+ // apps/reaper-mcp-server/src/instance-cli.ts
11050
+ var ui = createUi();
11051
+ function findReaper(os) {
11052
+ const fromEnv = process.env["REAPER_APP"];
11053
+ if (fromEnv) return existsSync10(fromEnv) ? fromEnv : null;
11054
+ const candidates = os === "darwin" ? ["/Applications/REAPER.app", join15(homedir11(), "Applications", "REAPER.app")] : os === "win32" ? ["C:\\Program Files\\REAPER (x64)\\reaper.exe", "C:\\Program Files\\REAPER\\reaper.exe"] : ["/opt/REAPER/reaper", "/usr/local/bin/reaper", "/usr/bin/reaper"];
11055
+ return candidates.find((c) => existsSync10(c)) ?? null;
11056
+ }
11057
+ function realInstanceDeps() {
11058
+ const os = platform6();
11059
+ return {
11060
+ mainResource: getReaperResourcePath(),
11061
+ runSetup: (info) => {
11062
+ const r = spawnSync(process.execPath, [realpathSync(process.argv[1]), "setup", "--no-init"], {
11063
+ env: { ...process.env, REAPER_RESOURCE_PATH: info.resourcePath, REAPER_WEB_PORT: String(info.port), REAPER_MCP_SKIP_SIDECAR_OFFER: "1" },
11064
+ encoding: "utf-8"
11065
+ });
11066
+ if (r.status !== 0) console.error(`${r.stdout ?? ""}${r.stderr ?? ""}`);
11067
+ return r.status === 0;
11068
+ },
11069
+ findReaper: () => findReaper(os),
11070
+ runner: (bin, args) => void execFileSync2(bin, args, { stdio: "pipe" }),
11071
+ launch: (bin, args, detached) => {
11072
+ const child = spawn2(bin, args, { detached, stdio: "ignore" });
11073
+ child.on("error", () => void 0);
11074
+ child.unref();
11075
+ },
11076
+ mtimeMs: (path) => {
11077
+ try {
11078
+ return statSync3(path).mtimeMs;
11079
+ } catch {
11080
+ return null;
11081
+ }
11082
+ },
11083
+ os,
11084
+ log: (line) => console.log(line)
11085
+ };
11086
+ }
11087
+ function flagValue(args, flag) {
11088
+ const i = args.findIndex((a) => a === flag || a.startsWith(`${flag}=`));
11089
+ if (i < 0) return void 0;
11090
+ return args[i].includes("=") ? args[i].split("=")[1] : args[i + 1];
11091
+ }
11092
+ var USAGE = `Usage: reaper-mcp instance <command>
11093
+
11094
+ create <name> [--port N] [--visible] make a second REAPER (own settings, bridge and status page port)
11095
+ start <name> [project.rpp] start it, optionally with a project
11096
+ stop <name> ask it to quit (macOS; elsewhere quit it from its window)
11097
+ connect <name> [--harness claude,...] let your agent use it as the "reaper-<name>" server
11098
+ list the instances, their port and whether their bridge answers
11099
+ remove <name> delete an instance's folder (it must not be running)`;
11100
+ async function instanceCommand(args, deps = realInstanceDeps()) {
11101
+ const [sub, ...rest] = args;
11102
+ const say = deps.log;
11103
+ try {
11104
+ switch (sub) {
11105
+ case "create":
11106
+ return create(rest, deps);
11107
+ case "start":
11108
+ return start(rest, deps);
11109
+ case "stop":
11110
+ return stop(rest, deps);
11111
+ case "connect":
11112
+ return connect(rest, deps);
11113
+ case "list":
11114
+ return list2(deps);
11115
+ case "remove":
11116
+ return remove(rest, deps);
11117
+ default:
11118
+ say(USAGE);
11119
+ return sub === void 0 || sub === "--help" || sub === "help" ? 0 : 1;
11120
+ }
11121
+ } catch (err) {
11122
+ console.error(`${ui.mark("fail")} ${err.message}`);
11123
+ return 1;
11124
+ }
11125
+ }
11126
+ function need(name) {
11127
+ const valid = validateInstanceName(name);
11128
+ const info = readInstance(valid);
11129
+ if (!info) throw new Error(`No instance "${valid}" (reaper-mcp instance list)`);
11130
+ return info;
11131
+ }
11132
+ function create(args, deps) {
11133
+ const name = args.find((a) => !a.startsWith("-") && a !== flagValue(args, "--port"));
11134
+ const portText = flagValue(args, "--port");
11135
+ const port = portText === void 0 ? void 0 : Number(portText);
11136
+ if (port !== void 0 && (!Number.isInteger(port) || port < 1024 || port > 65535)) throw new Error(`--port needs a number from 1024 to 65535 (got ${portText})`);
11137
+ const visible2 = args.includes("--visible");
11138
+ const reaper = deps.findReaper();
11139
+ if (!reaper) throw new Error("Could not find REAPER (set REAPER_APP to REAPER.app on macOS, or to the reaper executable)");
11140
+ const info = createInstanceFiles({ name: validateInstanceName(name), port, visible: visible2, mainResource: deps.mainResource });
11141
+ deps.log(`${ui.mark("ok")} Made ${ui.bold(info.name)}: ${ui.dim(info.resourcePath)}`);
11142
+ try {
11143
+ if (deps.os === "darwin") {
11144
+ const bundleId = `com.cockos.reaper.mcp-${info.name}`;
11145
+ const app = join15(info.resourcePath, "..", "REAPER.app");
11146
+ deps.log(ui.dim(" Copying REAPER.app (about 160 MB) so this instance has its own identity\u2026"));
11147
+ buildAppCopy(reaper, app, bundleId, visible2, deps.runner);
11148
+ Object.assign(info, { app, bundleId, appSourceMtimeMs: deps.mtimeMs(join15(reaper, "Contents", "MacOS", "REAPER")) });
11149
+ saveInstance(info);
11150
+ }
11151
+ if (!deps.runSetup(info)) throw new Error("Installing the bridge into the instance failed (output above)");
11152
+ } catch (err) {
11153
+ removeInstance(info.name);
11154
+ throw err;
11155
+ }
11156
+ deps.log(`${ui.mark("ok")} Bridge installed. Status page: ${ui.link(`http://localhost:${info.port}/mcp_bridge.html`)}`);
11157
+ deps.log(`
11158
+ Next: ${ui.cmd(`reaper-mcp instance connect ${info.name}`)}, then ${ui.cmd(`reaper-mcp instance start ${info.name} <project.rpp>`)}`);
11159
+ return 0;
11160
+ }
11161
+ function start(args, deps) {
11162
+ const info = need(args[0]);
11163
+ const reaper = deps.findReaper();
11164
+ if (!reaper) throw new Error("Could not find REAPER (set REAPER_APP)");
11165
+ if (bridgeAlive(info.resourcePath)) {
11166
+ deps.log(`${ui.mark("info")} ${info.name} is running already.`);
11167
+ return 0;
11168
+ }
11169
+ if (deps.os === "darwin" && info.app) {
11170
+ const source = deps.mtimeMs(join15(reaper, "Contents", "MacOS", "REAPER"));
11171
+ if (!existsSync10(info.app) || appCopyIsStale(info, source)) {
11172
+ deps.log(ui.dim(" REAPER was updated: refreshing this instance's copy of it\u2026"));
11173
+ buildAppCopy(reaper, info.app, info.bundleId ?? `com.cockos.reaper.mcp-${info.name}`, info.visible, deps.runner);
11174
+ saveInstance({ ...info, appSourceMtimeMs: source });
11175
+ }
11176
+ }
11177
+ const project = args[1];
11178
+ if (project && !existsSync10(project)) throw new Error(`Project not found: ${project}`);
11179
+ const cmd = launchCommand(info, project ? realpathSync(project) : void 0, deps.os, reaper);
11180
+ deps.launch(cmd.bin, cmd.args, cmd.detached);
11181
+ deps.log(`${ui.mark("ok")} Starting ${ui.bold(info.name)}${project ? ` with ${project}` : ""}. Its bridge comes up with REAPER: ${ui.link(`http://localhost:${info.port}/mcp_bridge.html`)}`);
11182
+ return 0;
11183
+ }
11184
+ function stop(args, deps) {
11185
+ const info = need(args[0]);
11186
+ if (deps.os === "darwin" && info.bundleId) {
11187
+ deps.runner("osascript", ["-e", `tell application id "${info.bundleId}" to quit`]);
11188
+ deps.log(`${ui.mark("ok")} Asked ${ui.bold(info.name)} to quit. If it holds unsaved changes it waits for you to answer.`);
11189
+ return 0;
11190
+ }
11191
+ deps.log(`${ui.mark("info")} Quit ${info.name} from its own window (REAPER asks about unsaved changes there).`);
11192
+ return 0;
11193
+ }
11194
+ function connect(args, deps) {
11195
+ const info = need(args.find((a) => !a.startsWith("-")));
11196
+ const env = realEnv();
11197
+ const ids = parseHarnessFlag(["", "", ...args]) ?? detectHarnesses(env).map((h) => h.id);
11198
+ if (ids.length === 0) throw new Error("No supported harness found (install Claude Code, Codex CLI, Gemini CLI or Cursor, or pass --harness)");
11199
+ const server = serverSpecFor(info);
11200
+ const mainJs = realpathSync(process.argv[1]);
11201
+ let failed = false;
11202
+ for (const id of ids) {
11203
+ const h = HARNESSES.find((x) => x.id === id);
11204
+ const r = connectHarness(id, process.execPath, mainJs, env, void 0, server);
11205
+ if (r.status === "failed") {
11206
+ failed = true;
11207
+ deps.log(`${ui.mark("fail")} Could not connect ${h?.name ?? id}: ${r.detail}
11208
+ ${ui.dim("To connect it yourself:")} ${ui.cmd(r.manual ?? "")}`);
11209
+ } else {
11210
+ deps.log(`${ui.mark("ok")} ${h?.name ?? id}: ${r.status === "already" ? "already has" : "now has"} the "${server.name}" server`);
11211
+ }
11212
+ }
11213
+ if (!failed) deps.log(ui.dim(` Restart the agent, then tell it which REAPER to use: "${server.name}" is the background one, "reaper" is yours.`));
11214
+ return failed ? 1 : 0;
11215
+ }
11216
+ function list2(deps) {
11217
+ const all = listInstances();
11218
+ if (all.length === 0) {
11219
+ deps.log(`No instances yet (they live in ${instancesRoot()}). Make one: ${ui.cmd("reaper-mcp instance create background")}`);
11220
+ return 0;
11221
+ }
11222
+ for (const i of all) {
11223
+ const state = bridgeAlive(i.resourcePath) ? ui.mark("ok") + " bridge answers" : ui.mark("info") + " not running";
11224
+ deps.log(`${ui.bold(i.name.padEnd(16))} port ${i.port} ${state} ${ui.dim(i.visible ? "visible" : "background")}`);
11225
+ }
11226
+ return 0;
11227
+ }
11228
+ function remove(args, deps) {
11229
+ const info = need(args[0]);
11230
+ if (bridgeAlive(info.resourcePath)) throw new Error(`${info.name} is running: stop it first (reaper-mcp instance stop ${info.name})`);
11231
+ removeInstance(info.name);
11232
+ deps.log(`${ui.mark("ok")} Removed ${info.name}. Projects you saved are wherever you saved them; only the instance's settings and bridge went.`);
11233
+ return 0;
11234
+ }
11235
+
10723
11236
  // apps/reaper-mcp-server/src/flags.ts
10724
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
10725
- import { homedir as homedir9 } from "node:os";
10726
- import { join as join13 } from "node:path";
11237
+ import { mkdirSync as mkdirSync9, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "node:fs";
11238
+ import { homedir as homedir12 } from "node:os";
11239
+ import { join as join16 } from "node:path";
10727
11240
 
10728
11241
  // libs/feature-flags/src/bucketing.ts
10729
11242
  function fnv1aHash(input) {
@@ -10982,10 +11495,10 @@ async function evaluateDefinition(client, def, context = {}) {
10982
11495
  // apps/reaper-mcp-server/src/flags.ts
10983
11496
  var FLAGS_FILE = "flags.json";
10984
11497
  var FLAGS_ENV = "REAPER_MCP_FLAGS";
10985
- function defaultFlagsDir(env = process.env, platform7 = process.platform) {
10986
- if (env.XDG_CONFIG_HOME) return join13(env.XDG_CONFIG_HOME, "reaper-mcp");
10987
- if (platform7 === "win32" && env.APPDATA) return join13(env.APPDATA, "reaper-mcp");
10988
- return join13(homedir9(), ".config", "reaper-mcp");
11498
+ function defaultFlagsDir(env = process.env, platform9 = process.platform) {
11499
+ if (env.XDG_CONFIG_HOME) return join16(env.XDG_CONFIG_HOME, "reaper-mcp");
11500
+ if (platform9 === "win32" && env.APPDATA) return join16(env.APPDATA, "reaper-mcp");
11501
+ return join16(homedir12(), ".config", "reaper-mcp");
10989
11502
  }
10990
11503
  function parseJson(raw) {
10991
11504
  try {
@@ -10997,7 +11510,7 @@ function parseJson(raw) {
10997
11510
  function readFlagOverrides(dir = defaultFlagsDir(), env = process.env, registry = FLAG_REGISTRY) {
10998
11511
  let fromFile;
10999
11512
  try {
11000
- fromFile = parseJson(readFileSync6(join13(dir, FLAGS_FILE), "utf-8"));
11513
+ fromFile = parseJson(readFileSync8(join16(dir, FLAGS_FILE), "utf-8"));
11001
11514
  } catch {
11002
11515
  fromFile = void 0;
11003
11516
  }
@@ -11005,8 +11518,8 @@ function readFlagOverrides(dir = defaultFlagsDir(), env = process.env, registry
11005
11518
  return { ...sanitizeFlagOverrides(fromFile, registry), ...sanitizeFlagOverrides(fromEnv, registry) };
11006
11519
  }
11007
11520
  function writeFlagOverrides(overrides, dir = defaultFlagsDir()) {
11008
- mkdirSync7(dir, { recursive: true });
11009
- writeFileSync6(join13(dir, FLAGS_FILE), JSON.stringify(overrides, null, 2) + "\n", "utf-8");
11521
+ mkdirSync9(dir, { recursive: true });
11522
+ writeFileSync8(join16(dir, FLAGS_FILE), JSON.stringify(overrides, null, 2) + "\n", "utf-8");
11010
11523
  }
11011
11524
  function createServerFlags(options = {}) {
11012
11525
  const registry = options.registry ?? FLAG_REGISTRY;
@@ -11058,7 +11571,7 @@ function flagOverrideCheck(options = {}) {
11058
11571
  };
11059
11572
  }
11060
11573
  var defaultFlags = createServerFlags();
11061
- var USAGE = [
11574
+ var USAGE2 = [
11062
11575
  "Usage:",
11063
11576
  " reaper-mcp flags list Every flag, how it resolves for this install, and why",
11064
11577
  " reaper-mcp flags set <key> <variant> Force a variant on this install only",
@@ -11085,7 +11598,7 @@ function flagsCommand(args, options = {}) {
11085
11598
  }
11086
11599
  if (sub === "set") {
11087
11600
  if (!key || !variant) {
11088
- io.error(USAGE.join("\n"));
11601
+ io.error(USAGE2.join("\n"));
11089
11602
  return 1;
11090
11603
  }
11091
11604
  const def = registry.find((f) => f.key === key);
@@ -11115,22 +11628,22 @@ function flagsCommand(args, options = {}) {
11115
11628
  }
11116
11629
  return 0;
11117
11630
  }
11118
- io.error(USAGE.join("\n"));
11631
+ io.error(USAGE2.join("\n"));
11119
11632
  return 1;
11120
11633
  }
11121
11634
 
11122
11635
  // apps/reaper-mcp-server/src/main.ts
11123
- import { existsSync as existsSync13, mkdirSync as mkdirSync13, readFileSync as readFileSync15, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "node:fs";
11124
- import { join as join21, dirname as dirname13, resolve as resolve3 } from "node:path";
11636
+ import { existsSync as existsSync15, mkdirSync as mkdirSync14, readFileSync as readFileSync16, realpathSync as realpathSync3, rmSync as rmSync5, writeFileSync as writeFileSync13 } from "node:fs";
11637
+ import { join as join23, dirname as dirname13, resolve as resolve3 } from "node:path";
11125
11638
  import { fileURLToPath as fileURLToPath6 } from "node:url";
11126
- import { homedir as homedir12, platform as platform6 } from "node:os";
11127
- import { exec as execCb, spawn as spawn3 } from "node:child_process";
11639
+ import { homedir as homedir14, platform as platform8 } from "node:os";
11640
+ import { exec as execCb, spawn as spawn4 } from "node:child_process";
11128
11641
  import { promisify as promisifyUtil } from "node:util";
11129
11642
 
11130
11643
  // apps/reaper-mcp-server/src/update.ts
11131
- import { spawn as spawn2 } from "node:child_process";
11132
- import { dirname as dirname10, join as join16 } from "node:path";
11133
- import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
11644
+ import { spawn as spawn3 } from "node:child_process";
11645
+ import { dirname as dirname10, join as join18 } from "node:path";
11646
+ import { existsSync as existsSync11, readFileSync as readFileSync10 } from "node:fs";
11134
11647
 
11135
11648
  // apps/reaper-mcp-server/src/version.ts
11136
11649
  function compareVersions(a, b) {
@@ -11144,14 +11657,14 @@ function compareVersions(a, b) {
11144
11657
  }
11145
11658
 
11146
11659
  // apps/reaper-mcp-server/src/update-check.ts
11147
- import { mkdirSync as mkdirSync8, readFileSync as readFileSync7, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "node:fs";
11148
- import { dirname as dirname8, join as join14 } from "node:path";
11149
- import { homedir as homedir10 } from "node:os";
11660
+ import { mkdirSync as mkdirSync10, readFileSync as readFileSync9, rmSync as rmSync3, writeFileSync as writeFileSync9 } from "node:fs";
11661
+ import { dirname as dirname9, join as join17 } from "node:path";
11662
+ import { homedir as homedir13 } from "node:os";
11150
11663
  var NPM_PACKAGE = "@mthines/reaper-mcp";
11151
11664
  var PACKAGE_URL = "https://registry.npmjs.org/@mthines%2Freaper-mcp";
11152
11665
  var DAY_MS = 24 * 60 * 60 * 1e3;
11153
11666
  function defaultUpdateStatePath() {
11154
- return join14(homedir10(), ".reaper-mcp", "update-check.json");
11667
+ return join17(homedir13(), ".reaper-mcp", "update-check.json");
11155
11668
  }
11156
11669
  function updateCheckDisabled(env = process.env) {
11157
11670
  const setting = (env["REAPER_MCP_UPDATE_CHECK"] ?? "").trim().toLowerCase();
@@ -11176,7 +11689,7 @@ function updateNotice(current, latest) {
11176
11689
  }
11177
11690
  function readState(path) {
11178
11691
  try {
11179
- const s = JSON.parse(readFileSync7(path, "utf-8"));
11692
+ const s = JSON.parse(readFileSync9(path, "utf-8"));
11180
11693
  return s && typeof s === "object" ? s : {};
11181
11694
  } catch {
11182
11695
  return {};
@@ -11184,8 +11697,8 @@ function readState(path) {
11184
11697
  }
11185
11698
  function writeState(path, state) {
11186
11699
  try {
11187
- mkdirSync8(dirname8(path), { recursive: true });
11188
- writeFileSync7(path, JSON.stringify(state) + "\n", "utf-8");
11700
+ mkdirSync10(dirname9(path), { recursive: true });
11701
+ writeFileSync9(path, JSON.stringify(state) + "\n", "utf-8");
11189
11702
  } catch {
11190
11703
  }
11191
11704
  }
@@ -11212,172 +11725,30 @@ function cachedUpdateAvailable(current, statePath = defaultUpdateStatePath()) {
11212
11725
  return compareVersions(latest, current) > 0;
11213
11726
  }
11214
11727
  function defaultUpdateMarkerPath() {
11215
- return join14(homedir10(), ".reaper-mcp", "last-update.json");
11728
+ return join17(homedir13(), ".reaper-mcp", "last-update.json");
11216
11729
  }
11217
11730
  function writeUpdateMarker(path, marker) {
11218
11731
  try {
11219
- mkdirSync8(dirname8(path), { recursive: true });
11220
- writeFileSync7(path, JSON.stringify(marker) + "\n", "utf-8");
11732
+ mkdirSync10(dirname9(path), { recursive: true });
11733
+ writeFileSync9(path, JSON.stringify(marker) + "\n", "utf-8");
11221
11734
  } catch {
11222
11735
  }
11223
11736
  }
11224
11737
  function takeUpdateMarker(path, current) {
11225
11738
  let marker;
11226
11739
  try {
11227
- marker = JSON.parse(readFileSync7(path, "utf-8"));
11740
+ marker = JSON.parse(readFileSync9(path, "utf-8"));
11228
11741
  } catch {
11229
11742
  return void 0;
11230
11743
  }
11231
11744
  if (marker?.to !== current) return void 0;
11232
11745
  try {
11233
- rmSync2(path, { force: true });
11746
+ rmSync3(path, { force: true });
11234
11747
  } catch {
11235
11748
  }
11236
11749
  return marker.via === "bridge_page" || marker.via === "cli" ? marker.via : void 0;
11237
11750
  }
11238
11751
 
11239
- // apps/reaper-mcp-server/src/harnesses.ts
11240
- import { execFileSync } from "node:child_process";
11241
- import { existsSync as existsSync8, mkdirSync as mkdirSync9, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "node:fs";
11242
- import { delimiter, dirname as dirname9, isAbsolute as isAbsolute3, join as join15 } from "node:path";
11243
- import { homedir as homedir11, platform as platform4 } from "node:os";
11244
- var HARNESSES = [
11245
- { id: "claude", name: "Claude Code", binary: "claude", installHint: "https://claude.com/claude-code", skillsHome: "claude" },
11246
- { id: "codex", name: "Codex CLI", binary: "codex", installHint: "npm install -g @openai/codex (or: brew install codex)", skillsHome: "agents" },
11247
- { id: "gemini", name: "Gemini CLI", binary: "gemini", installHint: "npm install -g @google/gemini-cli", skillsHome: "agents" },
11248
- { id: "cursor", name: "Cursor", binary: null, installHint: "https://cursor.com", skillsHome: "agents" }
11249
- ];
11250
- var SERVER_NAME = "reaper";
11251
- function onPath(name, pathVar = process.env.PATH ?? "", win = platform4() === "win32") {
11252
- const exts = win ? ["", ".exe", ".cmd", ".bat"] : [""];
11253
- return pathVar.split(delimiter).filter(Boolean).some((dir) => exts.some((ext) => existsSync8(join15(dir, name + ext))));
11254
- }
11255
- function realEnv() {
11256
- return { home: homedir11(), codexHome: process.env.CODEX_HOME || void 0, hasBinary: (name) => onPath(name) };
11257
- }
11258
- var configPath = (id, env) => ({
11259
- claude: join15(env.home, ".claude.json"),
11260
- codex: join15(env.codexHome ?? join15(env.home, ".codex"), "config.toml"),
11261
- gemini: join15(env.home, ".gemini", "settings.json"),
11262
- cursor: join15(env.home, ".cursor", "mcp.json")
11263
- })[id];
11264
- function detectHarnesses(env = realEnv()) {
11265
- return HARNESSES.filter((h) => h.binary ? env.hasBinary(h.binary) : existsSync8(join15(env.home, ".cursor")));
11266
- }
11267
- function registeredServer(id, env = realEnv()) {
11268
- let text9;
11269
- try {
11270
- text9 = readFileSync8(configPath(id, env), "utf-8");
11271
- } catch {
11272
- return null;
11273
- }
11274
- if (id === "codex") return codexServer(text9);
11275
- try {
11276
- const server = JSON.parse(text9)?.mcpServers?.[SERVER_NAME];
11277
- if (!server || typeof server.command !== "string") return null;
11278
- return { command: server.command, args: Array.isArray(server.args) ? server.args.filter((a) => typeof a === "string") : [] };
11279
- } catch {
11280
- return null;
11281
- }
11282
- }
11283
- function codexServer(toml) {
11284
- const header = new RegExp(`^\\[mcp_servers\\.(?:${SERVER_NAME}|"${SERVER_NAME}")\\]\\s*$`, "m").exec(toml);
11285
- if (!header) return null;
11286
- const rest = toml.slice(header.index + header[0].length);
11287
- const next = /^\[/m.exec(rest);
11288
- const section = next ? rest.slice(0, next.index) : rest;
11289
- const command2 = /^command\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')/m.exec(section)?.[1];
11290
- if (!command2) return null;
11291
- const args = /^args\s*=\s*\[([^\]]*)\]/m.exec(section)?.[1] ?? "";
11292
- const strings = (s) => [...s.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => m[1] !== void 0 ? JSON.parse(`"${m[1]}"`) : m[2]);
11293
- return { command: strings(command2)[0], args: strings(args) };
11294
- }
11295
- function isStale(server) {
11296
- return [server.command, ...server.args].filter(isAbsolute3).some((p) => !existsSync8(p));
11297
- }
11298
- function addCommand(id, node, mainJs) {
11299
- switch (id) {
11300
- case "claude":
11301
- return { bin: "claude", args: ["mcp", "add", "--scope", "user", SERVER_NAME, "--", node, mainJs, "serve"] };
11302
- case "codex":
11303
- return { bin: "codex", args: ["mcp", "add", SERVER_NAME, "--", node, mainJs, "serve"] };
11304
- case "gemini":
11305
- return { bin: "gemini", args: ["mcp", "add", "--scope", "user", SERVER_NAME, node, mainJs, "serve"] };
11306
- case "cursor":
11307
- return null;
11308
- }
11309
- }
11310
- function removeCommand(id) {
11311
- switch (id) {
11312
- case "claude":
11313
- return { bin: "claude", args: ["mcp", "remove", "--scope", "user", SERVER_NAME] };
11314
- case "codex":
11315
- return { bin: "codex", args: ["mcp", "remove", SERVER_NAME] };
11316
- case "gemini":
11317
- return { bin: "gemini", args: ["mcp", "remove", "--scope", "user", SERVER_NAME] };
11318
- case "cursor":
11319
- return null;
11320
- }
11321
- }
11322
- function manualCommand(id, node, mainJs, env = realEnv()) {
11323
- const add2 = addCommand(id, node, mainJs);
11324
- if (add2) return [add2.bin, ...add2.args].join(" ");
11325
- return `add "${SERVER_NAME}": { "command": "${node}", "args": ["${mainJs}", "serve"] } under "mcpServers" in ${configPath(id, env)}`;
11326
- }
11327
- function quoteForCmd(arg) {
11328
- return /[\s"]/.test(arg) ? `"${arg.replace(/"/g, '\\"')}"` : arg;
11329
- }
11330
- var realRunner = (bin, args) => {
11331
- if (platform4() === "win32") execFileSync(quoteForCmd(bin), args.map(quoteForCmd), { stdio: "pipe", shell: true });
11332
- else execFileSync(bin, args, { stdio: "pipe" });
11333
- };
11334
- function writeJsonServer(path, node, mainJs) {
11335
- let config = {};
11336
- if (existsSync8(path)) config = JSON.parse(readFileSync8(path, "utf-8"));
11337
- const servers = config.mcpServers && typeof config.mcpServers === "object" ? config.mcpServers : {};
11338
- servers[SERVER_NAME] = { command: node, args: [mainJs, "serve"] };
11339
- config.mcpServers = servers;
11340
- mkdirSync9(dirname9(path), { recursive: true });
11341
- writeFileSync8(path, JSON.stringify(config, null, 2) + "\n", "utf-8");
11342
- }
11343
- function connectHarness(id, node, mainJs, env = realEnv(), run5 = realRunner) {
11344
- const existing = registeredServer(id, env);
11345
- if (existing && !isStale(existing)) return { id, status: "already" };
11346
- const manual = manualCommand(id, node, mainJs, env);
11347
- try {
11348
- const add2 = addCommand(id, node, mainJs);
11349
- if (!add2) {
11350
- writeJsonServer(configPath(id, env), node, mainJs);
11351
- } else {
11352
- const remove = removeCommand(id);
11353
- if (existing && remove) run5(remove.bin, remove.args);
11354
- run5(add2.bin, add2.args);
11355
- }
11356
- } catch (err) {
11357
- const missing = err.code === "ENOENT";
11358
- const first = String(err.message).split("\n")[0];
11359
- return { id, status: "failed", detail: missing ? "its command was not found" : first, manual };
11360
- }
11361
- return { id, status: existing ? "replaced" : "connected" };
11362
- }
11363
- function parseHarnessFlag(argv) {
11364
- if (argv.includes("--all")) return HARNESSES.map((h) => h.id);
11365
- const i = argv.findIndex((a) => a === "--harness" || a.startsWith("--harness="));
11366
- if (i < 0) return null;
11367
- const value = argv[i].includes("=") ? argv[i].split("=")[1] : argv[i + 1];
11368
- const ids = (value ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
11369
- const known = HARNESSES.map((h) => h.id);
11370
- const bad = ids.filter((s) => !known.includes(s));
11371
- if (!ids.length || bad.length) {
11372
- throw new Error(`Unknown harness${bad.length > 1 ? "es" : ""}: ${bad.join(", ") || "(none given)"}. Use one or more of: ${known.join(", ")}, or --all.`);
11373
- }
11374
- return [...new Set(ids)];
11375
- }
11376
- function skillsHomes(ids) {
11377
- const chosen = HARNESSES.filter((h) => ids.includes(h.id));
11378
- return { claude: chosen.some((h) => h.skillsHome === "claude"), agents: chosen.some((h) => h.skillsHome === "agents") };
11379
- }
11380
-
11381
11752
  // apps/reaper-mcp-server/src/update.ts
11382
11753
  async function runUpdate(deps) {
11383
11754
  const { current, log } = deps;
@@ -11441,13 +11812,13 @@ async function fetchLatestRelease(fetchImpl = fetch, timeoutMs = 3e3) {
11441
11812
  }
11442
11813
  function realUpdateDeps(current, cli, force = false, bridge = false) {
11443
11814
  const nodeDir = dirname10(process.execPath);
11444
- const npmBeside = join16(nodeDir, process.platform === "win32" ? "npm.cmd" : "npm");
11815
+ const npmBeside = join18(nodeDir, process.platform === "win32" ? "npm.cmd" : "npm");
11445
11816
  return {
11446
11817
  current,
11447
11818
  latest: () => fetchLatestVersion(fetch, 1e4),
11448
11819
  run: (command2, args) => new Promise((resolve4) => {
11449
11820
  const win = process.platform === "win32";
11450
- const child = spawn2(win ? quoteForCmd(command2) : command2, win ? args.map(quoteForCmd) : args, {
11821
+ const child = spawn3(win ? quoteForCmd(command2) : command2, win ? args.map(quoteForCmd) : args, {
11451
11822
  shell: win,
11452
11823
  stdio: ["ignore", "inherit", "inherit"],
11453
11824
  // The node that runs this first on PATH: npm's own shebang and the child reaper-mcp find it
@@ -11459,13 +11830,13 @@ function realUpdateDeps(current, cli, force = false, bridge = false) {
11459
11830
  released: () => fetchLatestRelease(fetch, 1e4),
11460
11831
  installed: () => {
11461
11832
  try {
11462
- const version = JSON.parse(readFileSync9(join16(dirname10(cli), "package.json"), "utf-8")).version;
11833
+ const version = JSON.parse(readFileSync10(join18(dirname10(cli), "package.json"), "utf-8")).version;
11463
11834
  return typeof version === "string" ? version : void 0;
11464
11835
  } catch {
11465
11836
  return void 0;
11466
11837
  }
11467
11838
  },
11468
- npm: existsSync9(npmBeside) ? npmBeside : "npm",
11839
+ npm: existsSync11(npmBeside) ? npmBeside : "npm",
11469
11840
  node: process.execPath,
11470
11841
  cli,
11471
11842
  log: (line) => console.log(line),
@@ -11477,14 +11848,14 @@ function realUpdateDeps(current, cli, force = false, bridge = false) {
11477
11848
 
11478
11849
  // apps/reaper-mcp-server/src/claude-assets.ts
11479
11850
  import { createHash as createHash2 } from "node:crypto";
11480
- import { existsSync as existsSync10, lstatSync, mkdirSync as mkdirSync10, readFileSync as readFileSync10, readdirSync as readdirSync2, writeFileSync as writeFileSync9 } from "node:fs";
11481
- import { dirname as dirname11, join as join17, relative } from "node:path";
11851
+ import { existsSync as existsSync12, lstatSync, mkdirSync as mkdirSync11, readFileSync as readFileSync11, readdirSync as readdirSync3, writeFileSync as writeFileSync10 } from "node:fs";
11852
+ import { dirname as dirname11, join as join19, relative } from "node:path";
11482
11853
  var CLAUDE_MANIFEST = ".reaper-mcp-installed.json";
11483
11854
  var sha = (buf) => createHash2("sha256").update(buf).digest("hex");
11484
11855
  function listFiles(dir) {
11485
11856
  const out2 = [];
11486
- for (const entry of readdirSync2(dir, { withFileTypes: true })) {
11487
- const p = join17(dir, entry.name);
11857
+ for (const entry of readdirSync3(dir, { withFileTypes: true })) {
11858
+ const p = join19(dir, entry.name);
11488
11859
  if (entry.isDirectory()) out2.push(...listFiles(p));
11489
11860
  else if (entry.isFile()) out2.push(p);
11490
11861
  }
@@ -11499,7 +11870,7 @@ function isSymlink(path) {
11499
11870
  }
11500
11871
  function readManifest2(path) {
11501
11872
  try {
11502
- const m = JSON.parse(readFileSync10(path, "utf-8"));
11873
+ const m = JSON.parse(readFileSync11(path, "utf-8"));
11503
11874
  if (m && m.version === 1 && m.files && typeof m.files === "object") return m;
11504
11875
  } catch {
11505
11876
  }
@@ -11508,28 +11879,28 @@ function readManifest2(path) {
11508
11879
  function installClaudeAssets(packageClaudeDir, claudeDir, opts = {}) {
11509
11880
  const wants = (part) => !opts.include || opts.include.includes(part);
11510
11881
  const result = { installed: [], updated: [], unchanged: 0, skipped: [] };
11511
- const manifestPath = join17(claudeDir, CLAUDE_MANIFEST);
11882
+ const manifestPath = join19(claudeDir, CLAUDE_MANIFEST);
11512
11883
  const manifest = readManifest2(manifestPath);
11513
11884
  const plan = [];
11514
- const skillsSrc = join17(packageClaudeDir, "skills");
11515
- if (wants("skills") && existsSync10(skillsSrc)) {
11885
+ const skillsSrc = join19(packageClaudeDir, "skills");
11886
+ if (wants("skills") && existsSync12(skillsSrc)) {
11516
11887
  for (const f of listFiles(skillsSrc)) {
11517
11888
  const rel = relative(skillsSrc, f);
11518
- if (existsSync10(join17(skillsSrc, rel.split(/[\\/]/)[0], ".repo-only"))) continue;
11519
- plan.push([f, join17(claudeDir, "skills", rel), join17(claudeDir, "skills", rel.split(/[\\/]/)[0])]);
11889
+ if (existsSync12(join19(skillsSrc, rel.split(/[\\/]/)[0], ".repo-only"))) continue;
11890
+ plan.push([f, join19(claudeDir, "skills", rel), join19(claudeDir, "skills", rel.split(/[\\/]/)[0])]);
11520
11891
  }
11521
11892
  }
11522
- const agentsSrc = join17(packageClaudeDir, "agents");
11523
- if (wants("agents") && existsSync10(agentsSrc)) {
11893
+ const agentsSrc = join19(packageClaudeDir, "agents");
11894
+ if (wants("agents") && existsSync12(agentsSrc)) {
11524
11895
  for (const f of listFiles(agentsSrc)) {
11525
- const dest = join17(claudeDir, "agents", relative(agentsSrc, f));
11896
+ const dest = join19(claudeDir, "agents", relative(agentsSrc, f));
11526
11897
  plan.push([f, dest, dest]);
11527
11898
  }
11528
11899
  }
11529
- const knowledgeSrc = join17(packageClaudeDir, "knowledge");
11530
- if (wants("knowledge") && existsSync10(knowledgeSrc)) {
11900
+ const knowledgeSrc = join19(packageClaudeDir, "knowledge");
11901
+ if (wants("knowledge") && existsSync12(knowledgeSrc)) {
11531
11902
  for (const f of listFiles(knowledgeSrc)) {
11532
- plan.push([f, join17(claudeDir, "knowledge", relative(knowledgeSrc, f)), join17(claudeDir, "knowledge")]);
11903
+ plan.push([f, join19(claudeDir, "knowledge", relative(knowledgeSrc, f)), join19(claudeDir, "knowledge")]);
11533
11904
  }
11534
11905
  }
11535
11906
  const skippedSymlinks = /* @__PURE__ */ new Set();
@@ -11537,29 +11908,29 @@ function installClaudeAssets(packageClaudeDir, claudeDir, opts = {}) {
11537
11908
  if (isSymlink(linkRoot)) {
11538
11909
  if (!skippedSymlinks.has(linkRoot)) {
11539
11910
  skippedSymlinks.add(linkRoot);
11540
- result.skipped.push({ path: linkRoot, reason: existsSync10(linkRoot) ? "symlink" : "broken-symlink" });
11911
+ result.skipped.push({ path: linkRoot, reason: existsSync12(linkRoot) ? "symlink" : "broken-symlink" });
11541
11912
  }
11542
11913
  continue;
11543
11914
  }
11544
11915
  const key = relative(claudeDir, dest);
11545
- const content = readFileSync10(src);
11916
+ const content = readFileSync11(src);
11546
11917
  const hash = sha(content);
11547
- if (!existsSync10(dest)) {
11918
+ if (!existsSync12(dest)) {
11548
11919
  if (!opts.dryRun) {
11549
- mkdirSync10(dirname11(dest), { recursive: true });
11550
- writeFileSync9(dest, content);
11920
+ mkdirSync11(dirname11(dest), { recursive: true });
11921
+ writeFileSync10(dest, content);
11551
11922
  manifest.files[key] = hash;
11552
11923
  }
11553
11924
  result.installed.push(key);
11554
11925
  continue;
11555
11926
  }
11556
- const current = sha(readFileSync10(dest));
11927
+ const current = sha(readFileSync11(dest));
11557
11928
  if (current === hash) {
11558
11929
  if (!opts.dryRun) manifest.files[key] = hash;
11559
11930
  result.unchanged++;
11560
11931
  } else if (manifest.files[key] === current) {
11561
11932
  if (!opts.dryRun) {
11562
- writeFileSync9(dest, content);
11933
+ writeFileSync10(dest, content);
11563
11934
  manifest.files[key] = hash;
11564
11935
  }
11565
11936
  result.updated.push(key);
@@ -11568,70 +11939,70 @@ function installClaudeAssets(packageClaudeDir, claudeDir, opts = {}) {
11568
11939
  }
11569
11940
  }
11570
11941
  if (!opts.dryRun && (result.installed.length || result.updated.length || result.unchanged)) {
11571
- mkdirSync10(claudeDir, { recursive: true });
11572
- writeFileSync9(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
11942
+ mkdirSync11(claudeDir, { recursive: true });
11943
+ writeFileSync10(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
11573
11944
  }
11574
11945
  return result;
11575
11946
  }
11576
11947
 
11577
11948
  // apps/reaper-mcp-server/src/jsfx/examples.ts
11578
11949
  import { createHash as createHash3 } from "node:crypto";
11579
- import { existsSync as existsSync11, mkdirSync as mkdirSync11, readFileSync as readFileSync11, readdirSync as readdirSync3, writeFileSync as writeFileSync10 } from "node:fs";
11580
- import { join as join18 } from "node:path";
11950
+ import { existsSync as existsSync13, mkdirSync as mkdirSync12, readFileSync as readFileSync12, readdirSync as readdirSync4, writeFileSync as writeFileSync11 } from "node:fs";
11951
+ import { join as join20 } from "node:path";
11581
11952
  var MANIFEST = ".installed.json";
11582
11953
  var sha2 = (text9) => createHash3("sha256").update(text9).digest("hex");
11583
11954
  function installExamplePlugins(examplesDir, outDir, toolkit, presetsDir2) {
11584
11955
  const result = { installed: [], kept: [], presets: {}, presetErrors: [] };
11585
- if (!existsSync11(examplesDir)) return result;
11586
- mkdirSync11(outDir, { recursive: true });
11587
- const manifestPath = join18(outDir, MANIFEST);
11956
+ if (!existsSync13(examplesDir)) return result;
11957
+ mkdirSync12(outDir, { recursive: true });
11958
+ const manifestPath = join20(outDir, MANIFEST);
11588
11959
  let manifest = {};
11589
11960
  try {
11590
- manifest = JSON.parse(readFileSync11(manifestPath, "utf8"));
11961
+ manifest = JSON.parse(readFileSync12(manifestPath, "utf8"));
11591
11962
  } catch {
11592
11963
  }
11593
- for (const file of readdirSync3(examplesDir).filter((f) => f.endsWith(".jsfx")).sort()) {
11594
- const dest = join18(outDir, file);
11595
- const next = inlineToolkit(readFileSync11(join18(examplesDir, file), "utf8"), { toolkit, version: 1, request: "a plugin that ships with reaper-mcp", slug: file.replace(/\.jsfx$/, ""), example: true });
11596
- const current = existsSync11(dest) ? readFileSync11(dest, "utf8") : void 0;
11964
+ for (const file of readdirSync4(examplesDir).filter((f) => f.endsWith(".jsfx")).sort()) {
11965
+ const dest = join20(outDir, file);
11966
+ const next = inlineToolkit(readFileSync12(join20(examplesDir, file), "utf8"), { toolkit, version: 1, request: "a plugin that ships with reaper-mcp", slug: file.replace(/\.jsfx$/, ""), example: true });
11967
+ const current = existsSync13(dest) ? readFileSync12(dest, "utf8") : void 0;
11597
11968
  if (current !== void 0 && current !== next && sha2(current) !== manifest[file]) {
11598
11969
  result.kept.push(file);
11599
11970
  continue;
11600
11971
  }
11601
- if (current !== next) writeFileSync10(dest, next);
11972
+ if (current !== next) writeFileSync11(dest, next);
11602
11973
  manifest[file] = sha2(next);
11603
11974
  result.installed.push(file);
11604
11975
  }
11605
11976
  if (presetsDir2) {
11606
11977
  const folder = outDir.split(/[/\\]/).slice(-2).join("/");
11607
- for (const file of readdirSync3(examplesDir).filter((f) => f.endsWith(".jsfx")).sort()) {
11608
- const presetsPath = join18(examplesDir, file.replace(/\.jsfx$/, ".presets.json"));
11609
- if (!existsSync11(presetsPath)) continue;
11610
- const input = JSON.parse(readFileSync11(presetsPath, "utf8"));
11611
- const { values, errors } = resolvePresets(input, parseSliders(readFileSync11(join18(examplesDir, file), "utf8")).sliders);
11978
+ for (const file of readdirSync4(examplesDir).filter((f) => f.endsWith(".jsfx")).sort()) {
11979
+ const presetsPath = join20(examplesDir, file.replace(/\.jsfx$/, ".presets.json"));
11980
+ if (!existsSync13(presetsPath)) continue;
11981
+ const input = JSON.parse(readFileSync12(presetsPath, "utf8"));
11982
+ const { values, errors } = resolvePresets(input, parseSliders(readFileSync12(join20(examplesDir, file), "utf8")).sliders);
11612
11983
  if (errors.length) {
11613
11984
  result.presetErrors.push(`${file}: ${errors.join(" ")}`);
11614
11985
  continue;
11615
11986
  }
11616
11987
  const encoded = input.map((p, i) => encodePreset(p.name.trim(), values[i]));
11617
- result.presets[file] = writePresetFile(presetsDir2, `${folder}/${file}`, encoded, join18(outDir, ".presets", `${file}.json`)).written;
11988
+ result.presets[file] = writePresetFile(presetsDir2, `${folder}/${file}`, encoded, join20(outDir, ".presets", `${file}.json`)).written;
11618
11989
  }
11619
11990
  }
11620
- writeFileSync10(manifestPath, JSON.stringify(manifest, null, 2));
11991
+ writeFileSync11(manifestPath, JSON.stringify(manifest, null, 2));
11621
11992
  return result;
11622
11993
  }
11623
11994
 
11624
11995
  // apps/reaper-mcp-server/src/doctor-report.ts
11625
11996
  function renderDoctor(sections3, opts = {}) {
11626
- const ui2 = createUi({ level: opts.color ? 1 : 0, tty: false });
11627
- const { bold, dim } = ui2;
11997
+ const ui3 = createUi({ level: opts.color ? 1 : 0, tty: false });
11998
+ const { bold, dim } = ui3;
11628
11999
  const width = Math.max(...sections3.flatMap((s) => s.checks.map((c) => c.label.length)));
11629
12000
  const out2 = opts.header === false ? [] : ["", ` ${bold("REAPER MCP")} ${dim("doctor")}${opts.version ? dim(` v${opts.version}`) : ""}`];
11630
12001
  for (const section of sections3) {
11631
- const state = section.state ? ` ${ui2.status(section.state.status, section.state.text)}` : "";
12002
+ const state = section.state ? ` ${ui3.status(section.state.status, section.state.text)}` : "";
11632
12003
  out2.push("", ` ${bold(section.title)}${section.note ? dim(` ${section.note}`) : ""}${state}`);
11633
12004
  for (const c of section.checks) {
11634
- out2.push(` ${ui2.mark(c.status)} ${c.label.padEnd(width)} ${c.status === "info" ? dim(c.detail) : c.detail}`);
12005
+ out2.push(` ${ui3.mark(c.status)} ${c.label.padEnd(width)} ${c.status === "info" ? dim(c.detail) : c.detail}`);
11635
12006
  if (c.fix && c.status !== "ok") out2.push(` ${" ".repeat(width)}${dim("\u2192")} ${c.fix}`);
11636
12007
  }
11637
12008
  }
@@ -11639,33 +12010,33 @@ function renderDoctor(sections3, opts = {}) {
11639
12010
  out2.push("");
11640
12011
  if (problems.length) {
11641
12012
  const fixes = [...new Set(problems.map((c) => c.fix).filter((f) => Boolean(f)))];
11642
- out2.push(` ${ui2.fail(`${problems.length} problem${problems.length === 1 ? "" : "s"}`)}${fixes.length ? dim(` \xB7 fix with: ${fixes.join(", then ")}`) : ""}`);
12013
+ out2.push(` ${ui3.fail(`${problems.length} problem${problems.length === 1 ? "" : "s"}`)}${fixes.length ? dim(` \xB7 fix with: ${fixes.join(", then ")}`) : ""}`);
11643
12014
  } else {
11644
- out2.push(` ${ui2.ok("All good.")}`);
12015
+ out2.push(` ${ui3.ok("All good.")}`);
11645
12016
  }
11646
12017
  out2.push("");
11647
12018
  return out2.join("\n");
11648
12019
  }
11649
12020
 
11650
12021
  // apps/reaper-mcp-server/src/bridge-repair.ts
11651
- import { existsSync as existsSync12, mkdirSync as mkdirSync12, readFileSync as readFileSync12, rmSync as rmSync3, writeFileSync as writeFileSync11 } from "node:fs";
11652
- import { dirname as dirname12, join as join19 } from "node:path";
12022
+ import { existsSync as existsSync14, mkdirSync as mkdirSync13, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "node:fs";
12023
+ import { dirname as dirname12, join as join21 } from "node:path";
11653
12024
  var BRIDGE_VERSION_FILE = "mcp_bridge_version.txt";
11654
12025
  function readBridgeVersion(scriptsDir) {
11655
12026
  try {
11656
- const v = readFileSync12(join19(scriptsDir, BRIDGE_VERSION_FILE), "utf-8").trim();
12027
+ const v = readFileSync13(join21(scriptsDir, BRIDGE_VERSION_FILE), "utf-8").trim();
11657
12028
  return /^\d+\.\d+\.\d+/.test(v) ? v : void 0;
11658
12029
  } catch {
11659
12030
  return void 0;
11660
12031
  }
11661
12032
  }
11662
12033
  function writeBridgeVersion(scriptsDir, version) {
11663
- writeFileSync11(join19(scriptsDir, BRIDGE_VERSION_FILE), `${version}
12034
+ writeFileSync12(join21(scriptsDir, BRIDGE_VERSION_FILE), `${version}
11664
12035
  `, "utf-8");
11665
12036
  }
11666
12037
  function sameContent(a, b) {
11667
12038
  try {
11668
- return readFileSync12(a).equals(readFileSync12(b));
12039
+ return readFileSync13(a).equals(readFileSync13(b));
11669
12040
  } catch {
11670
12041
  return false;
11671
12042
  }
@@ -11673,35 +12044,35 @@ function sameContent(a, b) {
11673
12044
  function installReaperFiles(paths, withPage = true) {
11674
12045
  let luaChanged = false;
11675
12046
  for (const asset of REAPER_ASSETS) {
11676
- const src = join19(paths.assetsDir, asset);
11677
- if (!existsSync12(src)) continue;
12047
+ const src = join21(paths.assetsDir, asset);
12048
+ if (!existsSync14(src)) continue;
11678
12049
  const lua = asset.endsWith(".lua");
11679
- const destDir = lua ? paths.scriptsDir : join19(paths.effectsDir, "reaper-mcp");
11680
- mkdirSync12(destDir, { recursive: true });
11681
- const dest = join19(destDir, asset);
12050
+ const destDir = lua ? paths.scriptsDir : join21(paths.effectsDir, "reaper-mcp");
12051
+ mkdirSync13(destDir, { recursive: true });
12052
+ const dest = join21(destDir, asset);
11682
12053
  if (lua && !sameContent(src, dest)) luaChanged = true;
11683
12054
  installFile(src, dest);
11684
12055
  }
11685
- for (const asset of RETIRED_ASSETS) rmSync3(join19(paths.scriptsDir, asset), { force: true });
11686
- if (withPage && existsSync12(join19(paths.wwwSrcDir, BRIDGE_UI_FILE))) copyDirSync(paths.wwwSrcDir, paths.wwwDir);
12056
+ for (const asset of RETIRED_ASSETS) rmSync4(join21(paths.scriptsDir, asset), { force: true });
12057
+ if (withPage && existsSync14(join21(paths.wwwSrcDir, BRIDGE_UI_FILE))) copyDirSync(paths.wwwSrcDir, paths.wwwDir);
11687
12058
  return luaChanged;
11688
12059
  }
11689
12060
  function repairBridgeInstall(paths, version, opts) {
11690
12061
  const none = { bridgeChanged: false, autostartAdded: false };
11691
12062
  if (opts.inClone) return { skipped: "clone", ...none };
11692
- const reapack = existsSync12(join19(paths.scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua"));
11693
- const ours = existsSync12(join19(paths.scriptsDir, "mcp_bridge.lua"));
11694
- const first = !reapack && !ours && opts.firstInstall === true && existsSync12(dirname12(paths.scriptsDir));
12063
+ const reapack = existsSync14(join21(paths.scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua"));
12064
+ const ours = existsSync14(join21(paths.scriptsDir, "mcp_bridge.lua"));
12065
+ const first = !reapack && !ours && opts.firstInstall === true && existsSync14(dirname12(paths.scriptsDir));
11695
12066
  if (!reapack && !ours && !first) return { skipped: "not_installed", ...none };
11696
12067
  const from = readBridgeVersion(paths.scriptsDir);
11697
12068
  if (from && compareVersions(from, version) >= 0) return { skipped: "current", from, ...none };
11698
- const withPage = !opts.firstInstall || existsSync12(join19(paths.wwwDir, BRIDGE_UI_FILE));
12069
+ const withPage = !opts.firstInstall || existsSync14(join21(paths.wwwDir, BRIDGE_UI_FILE));
11699
12070
  const bridgeChanged = reapack ? false : installReaperFiles(paths, withPage);
11700
- const startupPath = join19(paths.scriptsDir, "__startup.lua");
11701
- const startup = existsSync12(startupPath) ? readFileSync12(startupPath, "utf-8") : "";
12071
+ const startupPath = join21(paths.scriptsDir, "__startup.lua");
12072
+ const startup = existsSync14(startupPath) ? readFileSync13(startupPath, "utf-8") : "";
11702
12073
  const keepOff = opts.firstInstall === true && !first && !startup.includes(AUTOSTART_MARKER);
11703
12074
  const { text: text9, changed } = keepOff ? { text: startup, changed: false } : ensureBridgeAutostart(startup);
11704
- if (changed) writeFileSync11(startupPath, text9, "utf-8");
12075
+ if (changed) writeFileSync12(startupPath, text9, "utf-8");
11705
12076
  writeBridgeVersion(paths.scriptsDir, version);
11706
12077
  return { from, bridgeChanged, autostartAdded: !keepOff && !startup.includes(AUTOSTART_MARKER), ...first && { firstInstalled: true } };
11707
12078
  }
@@ -11754,9 +12125,9 @@ ${SIDECAR_OFFER_TEXT}
11754
12125
 
11755
12126
  // apps/reaper-mcp-server/src/setup-health.ts
11756
12127
  import { execFile as execFile2 } from "node:child_process";
11757
- import { readFileSync as readFileSync13 } from "node:fs";
11758
- import { join as join20 } from "node:path";
11759
- import { platform as platform5 } from "node:os";
12128
+ import { readFileSync as readFileSync14 } from "node:fs";
12129
+ import { join as join22 } from "node:path";
12130
+ import { platform as platform7 } from "node:os";
11760
12131
  function heartbeatAgeBucket(ms) {
11761
12132
  const min = 6e4;
11762
12133
  if (ms < min) return "<1m";
@@ -11766,7 +12137,7 @@ function heartbeatAgeBucket(ms) {
11766
12137
  return ">7d";
11767
12138
  }
11768
12139
  function isReaperProcessRunning(timeoutMs = 2e3) {
11769
- const win = platform5() === "win32";
12140
+ const win = platform7() === "win32";
11770
12141
  const [cmd, args] = win ? ["tasklist", ["/FI", "IMAGENAME eq reaper.exe", "/NH"]] : ["pgrep", ["-xi", "reaper"]];
11771
12142
  return new Promise((resolve4) => {
11772
12143
  execFile2(cmd, args, { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
@@ -11778,7 +12149,7 @@ function isReaperProcessRunning(timeoutMs = 2e3) {
11778
12149
  }
11779
12150
  function autostartInstalled(scriptsDir) {
11780
12151
  try {
11781
- return readFileSync13(join20(scriptsDir, "__startup.lua"), "utf-8").includes(AUTOSTART_MARKER);
12152
+ return readFileSync14(join22(scriptsDir, "__startup.lua"), "utf-8").includes(AUTOSTART_MARKER);
11782
12153
  } catch {
11783
12154
  return false;
11784
12155
  }
@@ -11793,13 +12164,13 @@ function setupHealthAttributes(h) {
11793
12164
  }
11794
12165
 
11795
12166
  // apps/reaper-mcp-server/src/install-info.ts
11796
- import { readFileSync as readFileSync14, realpathSync } from "node:fs";
12167
+ import { readFileSync as readFileSync15, realpathSync as realpathSync2 } from "node:fs";
11797
12168
  import { posix, win32 } from "node:path";
11798
- function pathApi(platform7) {
11799
- return platform7 === "win32" ? win32 : posix;
12169
+ function pathApi(platform9) {
12170
+ return platform9 === "win32" ? win32 : posix;
11800
12171
  }
11801
- function npxRoot(dir, platform7) {
11802
- const p = pathApi(platform7);
12172
+ function npxRoot(dir, platform9) {
12173
+ const p = pathApi(platform9);
11803
12174
  const parts = dir.split(p.sep);
11804
12175
  const i = parts.lastIndexOf("_npx");
11805
12176
  return i >= 0 && i + 1 < parts.length ? parts.slice(0, i + 2).join(p.sep) : void 0;
@@ -11830,7 +12201,7 @@ function classifySpec(spec) {
11830
12201
  if (/^[\^~<>=*xX\d]/.test(version) || version.includes("||") || / - /.test(version)) return "range";
11831
12202
  return "tag";
11832
12203
  }
11833
- function installPin(ctx, method, readFile6 = (path) => readFileSync14(path, "utf-8")) {
12204
+ function installPin(ctx, method, readFile6 = (path) => readFileSync15(path, "utf-8")) {
11834
12205
  if (method !== "npx") return "none";
11835
12206
  const specs = [];
11836
12207
  const root = npxRoot(ctx.dir, ctx.platform);
@@ -11859,7 +12230,7 @@ function installAttributes(info) {
11859
12230
  function readInstallInfo(codeDir, current, env = process.env, paths = { statePath: defaultUpdateStatePath(), markerPath: defaultUpdateMarkerPath() }) {
11860
12231
  let dir = codeDir;
11861
12232
  try {
11862
- dir = realpathSync(codeDir);
12233
+ dir = realpathSync2(codeDir);
11863
12234
  } catch {
11864
12235
  }
11865
12236
  const ctx = { dir, isClone: findCloneRoot(dir) !== null, env, execPath: process.execPath, platform: process.platform };
@@ -11876,125 +12247,126 @@ function readInstallInfo(codeDir, current, env = process.env, paths = { statePat
11876
12247
 
11877
12248
  // apps/reaper-mcp-server/src/main.ts
11878
12249
  var execAsync = promisifyUtil(execCb);
11879
- var ui = createUi();
12250
+ var ui2 = createUi();
11880
12251
  var __dirname2 = dirname13(fileURLToPath6(import.meta.url));
11881
12252
  async function setup() {
11882
12253
  const verbose = process.argv.includes("--verbose");
11883
12254
  const installedLine = (what, files) => {
11884
- if (verbose) for (const f of files) console.log(ui.item("ok", `Installed: ${f}`));
11885
- else if (files.length) console.log(ui.item("ok", `${files.length} ${what} installed`));
12255
+ if (verbose) for (const f of files) console.log(ui2.item("ok", `Installed: ${f}`));
12256
+ else if (files.length) console.log(ui2.item("ok", `${files.length} ${what} installed`));
11886
12257
  };
11887
- console.log(ui.banner("Setup", readServiceVersion()));
12258
+ console.log(ui2.banner("Setup", readServiceVersion()));
11888
12259
  const bridgeDir = await ensureBridgeDir();
11889
- console.log(`Bridge directory: ${ui.dim(bridgeDir)}
12260
+ console.log(`Bridge directory: ${ui2.dim(bridgeDir)}
11890
12261
  `);
11891
12262
  const scriptsDir = getReaperScriptsPath();
11892
- mkdirSync13(scriptsDir, { recursive: true });
12263
+ mkdirSync14(scriptsDir, { recursive: true });
11893
12264
  const reaperDir = resolveAssetDir(__dirname2, "reaper");
11894
- const filesPlan = setupFilesPlan(existsSync13(join21(scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua")), findCloneRoot(__dirname2) !== null);
12265
+ const filesPlan = setupFilesPlan(existsSync15(join23(scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua")), findCloneRoot(__dirname2) !== null);
11895
12266
  if (filesPlan === "leave") {
11896
- console.log(`${ui.mark("info")} The bridge is installed by ReaPack: leaving its scripts, JSFX and status page to ReaPack.`);
11897
- console.log(`${ui.dim("Setup only turns on starting with REAPER and the web interface.")}
12267
+ console.log(`${ui2.mark("info")} The bridge is installed by ReaPack: leaving its scripts, JSFX and status page to ReaPack.`);
12268
+ console.log(`${ui2.dim("Setup only turns on starting with REAPER and the web interface.")}
11898
12269
  `);
11899
12270
  installBridgeAutostart(scriptsDir);
11900
12271
  writeBridgeVersion(scriptsDir, readServiceVersion());
11901
12272
  const port = await enableWebInterface();
11902
12273
  console.log(`
11903
- ${ui.mark("ok")} ${ui.bold("Setup complete!")}`);
11904
- if (await chainAfterSetup(port, join21(scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua"))) return;
12274
+ ${ui2.mark("ok")} ${ui2.bold("Setup complete!")}`);
12275
+ if (await chainAfterSetup(port, join23(scriptsDir, "reaper-mcp", "MCP Bridge", "mcp_bridge.lua"))) return;
11905
12276
  console.log(`
11906
- Restart REAPER (or run the bridge once from the Action List) and add reaper-mcp to your harness: ${ui.cmd("reaper-mcp doctor")}`);
11907
- if (port) console.log(`The bridge opens its status window on start: ${ui.link(`http://localhost:${port}/${BRIDGE_UI_FILE}`)}`);
12277
+ Restart REAPER (or run the bridge once from the Action List) and add reaper-mcp to your harness: ${ui2.cmd("reaper-mcp doctor")}`);
12278
+ if (port) console.log(`The bridge opens its status window on start: ${ui2.link(`http://localhost:${port}/${BRIDGE_UI_FILE}`)}`);
11908
12279
  await offerSidecar();
11909
12280
  return;
11910
12281
  }
11911
12282
  if (filesPlan === "install-with-warning") {
11912
- console.log(`${ui.warn("WARNING:")} ReaPack has installed the bridge too, and REAPER prefers its copy (Scripts/reaper-mcp/MCP Bridge/ and`);
12283
+ console.log(`${ui2.warn("WARNING:")} ReaPack has installed the bridge too, and REAPER prefers its copy (Scripts/reaper-mcp/MCP Bridge/ and`);
11913
12284
  console.log("Effects/reaper-mcp/Meters/) over the files this checkout installs. Your local changes will not run until you");
11914
12285
  console.log("uninstall the reaper-mcp packages in ReaPack (Manage repositories > reaper-mcp > Uninstall packages),");
11915
12286
  console.log("then run setup again: this run also overwrote the status page ReaPack installed, which uninstalling removes.\n");
11916
12287
  }
11917
- console.log(`${ui.bold("Installing Lua scripts...")}`);
12288
+ console.log(`${ui2.bold("Installing Lua scripts...")}`);
11918
12289
  const luaInstalled = [];
11919
12290
  for (const asset of REAPER_ASSETS) {
11920
12291
  if (!asset.endsWith(".lua")) continue;
11921
- const src = join21(reaperDir, asset);
11922
- const dest = join21(scriptsDir, asset);
12292
+ const src = join23(reaperDir, asset);
12293
+ const dest = join23(scriptsDir, asset);
11923
12294
  if (installFile(src, dest)) luaInstalled.push(asset);
11924
- else console.log(ui.item("fail", `Not found: ${src}`));
12295
+ else console.log(ui2.item("fail", `Not found: ${src}`));
11925
12296
  }
11926
12297
  installedLine("scripts", luaInstalled);
11927
12298
  for (const asset of RETIRED_ASSETS) {
11928
- const dest = join21(scriptsDir, asset);
11929
- if (existsSync13(dest)) {
11930
- rmSync4(dest);
11931
- console.log(ui.item("info", `Removed: ${asset} (retired)`));
12299
+ const dest = join23(scriptsDir, asset);
12300
+ if (existsSync15(dest)) {
12301
+ rmSync5(dest);
12302
+ console.log(ui2.item("info", `Removed: ${asset} (retired)`));
11932
12303
  }
11933
12304
  }
11934
12305
  const cloneRoot = findCloneRoot(__dirname2);
11935
12306
  if (cloneRoot) {
11936
12307
  const dev = isDevClone(await cloneState(cloneRoot));
11937
- writeFileSync12(join21(scriptsDir, "mcp_update.conf"), updateConfigText(cloneRoot, process.execPath, dev));
11938
- console.log(ui.item("ok", `Installed: mcp_update.conf (${dev ? "developer clone: Rebuild & reload" : "one-click updates"} from the status page)`));
12308
+ writeFileSync13(join23(scriptsDir, "mcp_update.conf"), updateConfigText(cloneRoot, process.execPath, dev));
12309
+ console.log(ui2.item("ok", `Installed: mcp_update.conf (${dev ? "developer clone: Rebuild & reload" : "one-click updates"} from the status page)`));
11939
12310
  } else {
11940
- writeFileSync12(join21(scriptsDir, "mcp_update.conf"), npmUpdateConfigText(process.execPath, join21(__dirname2, "main.js")));
12311
+ writeFileSync13(join23(scriptsDir, "mcp_update.conf"), npmUpdateConfigText(process.execPath, join23(__dirname2, "main.js")));
11941
12312
  }
11942
- const effectsDir = join21(getReaperEffectsPath(), "reaper-mcp");
11943
- mkdirSync13(effectsDir, { recursive: true });
11944
- console.log(ui.section("Installing JSFX analyzers..."));
12313
+ const effectsDir = join23(getReaperEffectsPath(), "reaper-mcp");
12314
+ mkdirSync14(effectsDir, { recursive: true });
12315
+ console.log(ui2.section("Installing JSFX analyzers..."));
11945
12316
  const jsfxInstalled = [];
11946
12317
  for (const asset of REAPER_ASSETS) {
11947
12318
  if (asset.endsWith(".lua")) continue;
11948
- const src = join21(reaperDir, asset);
11949
- const dest = join21(effectsDir, asset);
12319
+ const src = join23(reaperDir, asset);
12320
+ const dest = join23(effectsDir, asset);
11950
12321
  if (installFile(src, dest)) jsfxInstalled.push(`reaper-mcp/${asset}`);
11951
- else console.log(ui.item("fail", `Not found: ${src}`));
12322
+ else console.log(ui2.item("fail", `Not found: ${src}`));
11952
12323
  }
11953
12324
  installedLine("JSFX files", jsfxInstalled);
11954
- console.log(ui.section("Installing example plugins..."));
11955
- const examplesDir = join21(resolveAssetDir(__dirname2, "claude"), "skills", "make-plugin", "examples");
11956
- const examples = installExamplePlugins(examplesDir, join21(generatedDir(), "examples"), loadToolkit(), presetsDir());
12325
+ console.log(ui2.section("Installing example plugins..."));
12326
+ const examplesDir = join23(resolveAssetDir(__dirname2, "claude"), "skills", "make-plugin", "examples");
12327
+ const examples = installExamplePlugins(examplesDir, join23(generatedDir(), "examples"), loadToolkit(), presetsDir());
11957
12328
  installedLine("example plugins", examples.installed.map((f) => `reaper-mcp-generated/examples/${f}`));
11958
- for (const f of examples.kept) console.log(ui.item("info", `Kept your edited copy: reaper-mcp-generated/examples/${f}`));
12329
+ for (const f of examples.kept) console.log(ui2.item("info", `Kept your edited copy: reaper-mcp-generated/examples/${f}`));
11959
12330
  if (verbose) {
11960
- for (const [f, names] of Object.entries(examples.presets)) if (names.length) console.log(ui.item("info", `Presets for ${f}: ${names.join(", ")}`));
12331
+ for (const [f, names] of Object.entries(examples.presets)) if (names.length) console.log(ui2.item("info", `Presets for ${f}: ${names.join(", ")}`));
11961
12332
  }
11962
- for (const e of examples.presetErrors) console.log(ui.item("warn", `Skipped presets (invalid): ${e}`));
11963
- if (!examples.installed.length && !examples.kept.length) console.log(ui.item("fail", `Not found: ${examplesDir}`));
12333
+ for (const e of examples.presetErrors) console.log(ui2.item("warn", `Skipped presets (invalid): ${e}`));
12334
+ if (!examples.installed.length && !examples.kept.length) console.log(ui2.item("fail", `Not found: ${examplesDir}`));
11964
12335
  const wwwSrc = resolveAssetDir(__dirname2, "bridge-ui");
11965
- console.log(ui.section("Installing bridge status UI..."));
11966
- if (existsSync13(join21(wwwSrc, BRIDGE_UI_FILE))) {
12336
+ console.log(ui2.section("Installing bridge status UI..."));
12337
+ if (existsSync15(join23(wwwSrc, BRIDGE_UI_FILE))) {
11967
12338
  const count = copyDirSync(wwwSrc, getReaperWwwPath());
11968
- console.log(ui.item("ok", verbose ? `Installed: reaper_www_root/${BRIDGE_UI_FILE} (+${count - 1} PWA files)` : "Status page installed"));
12339
+ console.log(ui2.item("ok", verbose ? `Installed: reaper_www_root/${BRIDGE_UI_FILE} (+${count - 1} PWA files)` : "Status page installed"));
11969
12340
  } else {
11970
- console.log(ui.item("fail", `Not found: ${join21(wwwSrc, BRIDGE_UI_FILE)} (build bridge-ui first)`));
12341
+ console.log(ui2.item("fail", `Not found: ${join23(wwwSrc, BRIDGE_UI_FILE)} (build bridge-ui first)`));
11971
12342
  }
11972
12343
  installBridgeAutostart(scriptsDir);
11973
12344
  writeBridgeVersion(scriptsDir, readServiceVersion());
11974
12345
  const webPort = await enableWebInterface();
11975
12346
  await registerSnapshotActions();
11976
12347
  console.log(`
11977
- ${ui.mark("ok")} ${ui.bold("Setup complete!")}`);
11978
- if (await chainAfterSetup(webPort, join21(scriptsDir, "mcp_bridge.lua"))) return;
12348
+ ${ui2.mark("ok")} ${ui2.bold("Setup complete!")}`);
12349
+ if (await chainAfterSetup(webPort, join23(scriptsDir, "mcp_bridge.lua"))) return;
11979
12350
  console.log("");
11980
- console.log(ui.heading("Next steps:"));
11981
- console.log(` ${ui.bold("1.")} Start REAPER: the bridge starts with it. If REAPER is already open, restart it,`);
12351
+ console.log(ui2.heading("Next steps:"));
12352
+ console.log(` ${ui2.bold("1.")} Start REAPER: the bridge starts with it. If REAPER is already open, restart it,`);
11982
12353
  console.log(" or run the bridge once by hand: Actions > Show action list > Load ReaScript,");
11983
- console.log(` select ${ui.dim(join21(scriptsDir, "mcp_bridge.lua"))} and click Run.`);
11984
- console.log(` ${ui.bold("2.")} Connect your AI harness: ${ui.cmd("reaper-mcp init")}, then check it with ${ui.cmd("reaper-mcp doctor")}`);
12354
+ console.log(` select ${ui2.dim(join23(scriptsDir, "mcp_bridge.lua"))} and click Run.`);
12355
+ console.log(` ${ui2.bold("2.")} Connect your AI harness: ${ui2.cmd("reaper-mcp init")}, then check it with ${ui2.cmd("reaper-mcp doctor")}`);
11985
12356
  if (webPort) {
11986
12357
  console.log(`
11987
- The bridge opens its status window on start: ${ui.link(`http://localhost:${webPort}/${BRIDGE_UI_FILE}`)}`);
12358
+ The bridge opens its status window on start: ${ui2.link(`http://localhost:${webPort}/${BRIDGE_UI_FILE}`)}`);
11988
12359
  }
11989
12360
  await offerSidecar();
11990
12361
  }
11991
12362
  async function offerSidecar() {
12363
+ if (process.env["REAPER_MCP_SKIP_SIDECAR_OFFER"]) return;
11992
12364
  const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !process.env["CI"];
11993
12365
  await offerSidecarSetup({ input: process.stdin, output: process.stdout, interactive }, getSidecarClient().isAvailable(), () => setupSidecar([]));
11994
12366
  }
11995
12367
  async function askYesNo(question, defaultYes = true) {
11996
12368
  process.stdout.write(`
11997
- ${ui.bold(question)} ${ui.dim(defaultYes ? "[Y/n]" : "[y/N]")} `);
12369
+ ${ui2.bold(question)} ${ui2.dim(defaultYes ? "[Y/n]" : "[y/N]")} `);
11998
12370
  let answer = "";
11999
12371
  if (!streamEnded(process.stdin)) {
12000
12372
  const rl = createInterface5({ input: process.stdin, output: process.stdout, terminal: false });
@@ -12007,6 +12379,7 @@ ${ui.bold(question)} ${ui.dim(defaultYes ? "[Y/n]" : "[y/N]")} `);
12007
12379
  return answer === "" ? defaultYes : answer === "y" || answer === "yes";
12008
12380
  }
12009
12381
  async function chainAfterSetup(port, bridgeScript) {
12382
+ if (process.argv.includes("--no-init")) return false;
12010
12383
  const yes = process.argv.includes("--yes") || process.argv.includes("-y");
12011
12384
  const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
12012
12385
  if (!yes && !interactive) return false;
@@ -12015,18 +12388,18 @@ async function chainAfterSetup(port, bridgeScript) {
12015
12388
  if (yes || await askYesNo("Check that everything is in place?")) {
12016
12389
  console.log("");
12017
12390
  await doctor();
12018
- console.log(ui.dim("The bridge shows as not detected until REAPER has started it: that is the one step left."));
12391
+ console.log(ui2.dim("The bridge shows as not detected until REAPER has started it: that is the one step left."));
12019
12392
  }
12020
12393
  } else {
12021
12394
  console.log(`
12022
- Whenever you are ready: ${ui.cmd("reaper-mcp init")}, then ${ui.cmd("reaper-mcp doctor")}`);
12395
+ Whenever you are ready: ${ui2.cmd("reaper-mcp init")}, then ${ui2.cmd("reaper-mcp doctor")}`);
12023
12396
  }
12024
12397
  await offerSidecar();
12025
12398
  console.log(`
12026
- ${ui.heading("One step left:")} start REAPER (restart it if it is open): the bridge starts with it.`);
12027
- console.log(` ${ui.dim("Rather not restart? Actions > Show action list > Load ReaScript, select")} ${ui.dim(bridgeScript)} ${ui.dim("and click Run.")}`);
12399
+ ${ui2.heading("One step left:")} start REAPER (restart it if it is open): the bridge starts with it.`);
12400
+ console.log(` ${ui2.dim("Rather not restart? Actions > Show action list > Load ReaScript, select")} ${ui2.dim(bridgeScript)} ${ui2.dim("and click Run.")}`);
12028
12401
  if (port) console.log(`
12029
- The bridge opens its status window on start: ${ui.link(`http://localhost:${port}/${BRIDGE_UI_FILE}`)}`);
12402
+ The bridge opens its status window on start: ${ui2.link(`http://localhost:${port}/${BRIDGE_UI_FILE}`)}`);
12030
12403
  return true;
12031
12404
  }
12032
12405
  async function cloneState(repo) {
@@ -12043,57 +12416,57 @@ async function isReaperRunning() {
12043
12416
  return await isReaperProcessRunning(1e4) ?? false;
12044
12417
  }
12045
12418
  async function enableWebInterface() {
12046
- console.log(ui.section("Enabling REAPER web interface..."));
12047
- const iniPath = join21(getReaperResourcePath(), "reaper.ini");
12048
- if (!existsSync13(iniPath)) {
12049
- console.log(ui.item("warn", `Skipped: ${iniPath} not found (start REAPER once, quit it, then re-run setup)`));
12419
+ console.log(ui2.section("Enabling REAPER web interface..."));
12420
+ const iniPath = join23(getReaperResourcePath(), "reaper.ini");
12421
+ if (!existsSync15(iniPath)) {
12422
+ console.log(ui2.item("warn", `Skipped: ${iniPath} not found (start REAPER once, quit it, then re-run setup)`));
12050
12423
  return null;
12051
12424
  }
12052
12425
  const requested = Number(process.env["REAPER_WEB_PORT"]) || DEFAULT_WEB_PORT;
12053
- const result = ensureWebInterface(readFileSync15(iniPath, "utf-8"), requested);
12426
+ const result = ensureWebInterface(readFileSync16(iniPath, "utf-8"), requested);
12054
12427
  if (!result.changed) {
12055
- console.log(ui.item("ok", `Already enabled on port ${result.port}`));
12428
+ console.log(ui2.item("ok", `Already enabled on port ${result.port}`));
12056
12429
  return result.port;
12057
12430
  }
12058
12431
  if (await isReaperRunning()) {
12059
12432
  if (!process.stdout.isTTY) {
12060
- console.log(ui.item("warn", "Skipped: REAPER is running and would overwrite reaper.ini on exit."));
12061
- console.log(` Quit REAPER and run ${ui.cmd("reaper-mcp setup")} again.`);
12433
+ console.log(ui2.item("warn", "Skipped: REAPER is running and would overwrite reaper.ini on exit."));
12434
+ console.log(` Quit REAPER and run ${ui2.cmd("reaper-mcp setup")} again.`);
12062
12435
  return null;
12063
12436
  }
12064
- console.log(ui.item("warn", "REAPER is running and would overwrite reaper.ini on exit."));
12437
+ console.log(ui2.item("warn", "REAPER is running and would overwrite reaper.ini on exit."));
12065
12438
  console.log(" Quit REAPER to finish (Ctrl+C to skip)...");
12066
12439
  while (await isReaperRunning()) await new Promise((r) => setTimeout(r, 1e3));
12067
12440
  }
12068
- writeFileSync12(iniPath, ensureWebInterface(readFileSync15(iniPath, "utf-8"), requested).ini, "utf-8");
12069
- console.log(ui.item("ok", `Enabled on port ${result.port} (override with REAPER_WEB_PORT)`));
12441
+ writeFileSync13(iniPath, ensureWebInterface(readFileSync16(iniPath, "utf-8"), requested).ini, "utf-8");
12442
+ console.log(ui2.item("ok", `Enabled on port ${result.port} (override with REAPER_WEB_PORT)`));
12070
12443
  return result.port;
12071
12444
  }
12072
12445
  function installBridgeAutostart(scriptsDir) {
12073
- console.log(ui.section("Starting the bridge with REAPER..."));
12074
- const path = join21(scriptsDir, "__startup.lua");
12075
- const { text: text9, changed } = ensureBridgeAutostart(existsSync13(path) ? readFileSync15(path, "utf-8") : "");
12076
- if (changed) writeFileSync12(path, text9, "utf-8");
12077
- console.log(ui.item("ok", changed ? "Added to Scripts/__startup.lua (REAPER runs it at launch)" : "Already in Scripts/__startup.lua"));
12078
- console.log(ui.dim(" Turn it off in the bridge window: Settings > Start with REAPER."));
12446
+ console.log(ui2.section("Starting the bridge with REAPER..."));
12447
+ const path = join23(scriptsDir, "__startup.lua");
12448
+ const { text: text9, changed } = ensureBridgeAutostart(existsSync15(path) ? readFileSync16(path, "utf-8") : "");
12449
+ if (changed) writeFileSync13(path, text9, "utf-8");
12450
+ console.log(ui2.item("ok", changed ? "Added to Scripts/__startup.lua (REAPER runs it at launch)" : "Already in Scripts/__startup.lua"));
12451
+ console.log(ui2.dim(" Turn it off in the bridge window: Settings > Start with REAPER."));
12079
12452
  }
12080
12453
  async function registerSnapshotActions() {
12081
- console.log(ui.section("Registering snapshot actions (quick save, next, previous)..."));
12082
- const kbPath = join21(getReaperResourcePath(), "reaper-kb.ini");
12083
- const kb = existsSync13(kbPath) ? readFileSync15(kbPath, "utf-8") : "";
12454
+ console.log(ui2.section("Registering snapshot actions (quick save, next, previous)..."));
12455
+ const kbPath = join23(getReaperResourcePath(), "reaper-kb.ini");
12456
+ const kb = existsSync15(kbPath) ? readFileSync16(kbPath, "utf-8") : "";
12084
12457
  const { added } = ensureSnapshotActions(kb);
12085
12458
  if (!added.length) {
12086
- console.log(ui.item("ok", "Already in the Action List"));
12459
+ console.log(ui2.item("ok", "Already in the Action List"));
12087
12460
  } else if (await isReaperRunning()) {
12088
- console.log(ui.item("info", "REAPER is running: the bridge adds them when it next starts (re-run mcp_bridge.lua)."));
12461
+ console.log(ui2.item("info", "REAPER is running: the bridge adds them when it next starts (re-run mcp_bridge.lua)."));
12089
12462
  } else {
12090
- writeFileSync12(kbPath, ensureSnapshotActions(kb).kb, "utf-8");
12091
- console.log(ui.item("ok", `Added: ${added.join(", ")}`));
12463
+ writeFileSync13(kbPath, ensureSnapshotActions(kb).kb, "utf-8");
12464
+ console.log(ui2.item("ok", `Added: ${added.join(", ")}`));
12092
12465
  }
12093
- console.log(`${ui.dim(" Bind keys in Actions > Show action list: search")} ${ui.cmd('"mcp_snapshot"')}${ui.dim(".")}`);
12466
+ console.log(`${ui2.dim(" Bind keys in Actions > Show action list: search")} ${ui2.cmd('"mcp_snapshot"')}${ui2.dim(".")}`);
12094
12467
  }
12095
- function installHint(ui2, hint) {
12096
- return /^https?:\/\/\S+$/.test(hint) ? ui2.link(hint) : hint;
12468
+ function installHint(ui3, hint) {
12469
+ return /^https?:\/\/\S+$/.test(hint) ? ui3.link(hint) : hint;
12097
12470
  }
12098
12471
  async function init(chained = false) {
12099
12472
  let chosen;
@@ -12103,66 +12476,66 @@ async function init(chained = false) {
12103
12476
  console.error(err.message);
12104
12477
  process.exit(1);
12105
12478
  }
12106
- console.log(ui.banner("Connect your AI harness", readServiceVersion()));
12479
+ console.log(ui2.banner("Connect your AI harness", readServiceVersion()));
12107
12480
  const env = realEnv();
12108
12481
  const found = detectHarnesses(env).map((h) => h.id);
12109
12482
  const ids = chosen ?? found;
12110
12483
  for (const h of HARNESSES) {
12111
- console.log(found.includes(h.id) ? ` ${ui.mark("ok")} ${ui.dim("found")} ${ui.bold(h.name)}` : ` ${ui.mark("info")} ${ui.dim("not found")} ${h.name}: ${ui.dim(installHint(ui, h.installHint))}`);
12484
+ console.log(found.includes(h.id) ? ` ${ui2.mark("ok")} ${ui2.dim("found")} ${ui2.bold(h.name)}` : ` ${ui2.mark("info")} ${ui2.dim("not found")} ${h.name}: ${ui2.dim(installHint(ui2, h.installHint))}`);
12112
12485
  }
12113
12486
  console.log("");
12114
12487
  if (ids.length === 0) {
12115
- console.log(`None of the supported harnesses is installed yet. Install one (see above), then run: ${ui.cmd("reaper-mcp init")}`);
12488
+ console.log(`None of the supported harnesses is installed yet. Install one (see above), then run: ${ui2.cmd("reaper-mcp init")}`);
12116
12489
  return;
12117
12490
  }
12118
- const mainJs = realpathSync2(process.argv[1]);
12491
+ const mainJs = realpathSync3(process.argv[1]);
12119
12492
  const inClone = findCloneRoot(__dirname2) !== null;
12120
12493
  for (const id of ids) {
12121
12494
  const h = HARNESSES.find((x) => x.id === id);
12122
12495
  if (id === "claude") {
12123
- const settingsPath = join21(homedir12(), ".claude", "settings.json");
12124
- mkdirSync13(dirname13(settingsPath), { recursive: true });
12125
- console.log(`${ui.mark("ok")} Claude settings (${MCP_TOOL_NAMES.length} REAPER tools allow-listed): ${ensureClaudeSettings(settingsPath)} \u2192 ${ui.dim(settingsPath.replace(homedir12(), "~"))}`);
12496
+ const settingsPath = join23(homedir14(), ".claude", "settings.json");
12497
+ mkdirSync14(dirname13(settingsPath), { recursive: true });
12498
+ console.log(`${ui2.mark("ok")} Claude settings (${MCP_TOOL_NAMES.length} REAPER tools allow-listed): ${ensureClaudeSettings(settingsPath)} \u2192 ${ui2.dim(settingsPath.replace(homedir14(), "~"))}`);
12126
12499
  if (inClone) {
12127
- const mcpJsonPath = join21(process.cwd(), ".mcp.json");
12128
- console.log(createMcpJson(mcpJsonPath, resolve3(process.argv[1])) ? `${ui.mark("ok")} Created: ${ui.dim(mcpJsonPath)}` : `${ui.mark("ok")} .mcp.json already exists \u2014 leaving it untouched.`);
12500
+ const mcpJsonPath = join23(process.cwd(), ".mcp.json");
12501
+ console.log(createMcpJson(mcpJsonPath, resolve3(process.argv[1])) ? `${ui2.mark("ok")} Created: ${ui2.dim(mcpJsonPath)}` : `${ui2.mark("ok")} .mcp.json already exists \u2014 leaving it untouched.`);
12129
12502
  continue;
12130
12503
  }
12131
12504
  }
12132
12505
  const r = connectHarness(id, process.execPath, mainJs, env);
12133
12506
  if (r.status === "failed") {
12134
- console.log(`${ui.mark("fail")} Could not connect ${ui.bold(h.name)}: ${r.detail}${found.includes(id) ? "" : ` ${ui.dim(`(not installed: ${installHint(ui, h.installHint)})`)}`}`);
12135
- console.log(` ${ui.dim("To connect it yourself:")} ${ui.cmd(r.manual ?? "")}`);
12507
+ console.log(`${ui2.mark("fail")} Could not connect ${ui2.bold(h.name)}: ${r.detail}${found.includes(id) ? "" : ` ${ui2.dim(`(not installed: ${installHint(ui2, h.installHint)})`)}`}`);
12508
+ console.log(` ${ui2.dim("To connect it yourself:")} ${ui2.cmd(r.manual ?? "")}`);
12136
12509
  } else {
12137
12510
  const what = { connected: "Connected", replaced: "Reconnected (the old entry pointed at files that no longer exist)", already: "Already connected" }[r.status];
12138
- console.log(`${ui.mark("ok")} ${what}: ${ui.bold(h.name)}${id === "claude" && inClone ? "" : ui.dim(" (works from any folder)")}`);
12511
+ console.log(`${ui2.mark("ok")} ${what}: ${ui2.bold(h.name)}${id === "claude" && inClone ? "" : ui2.dim(" (works from any folder)")}`);
12139
12512
  }
12140
12513
  }
12141
12514
  await askTelemetryOnce();
12142
12515
  if (inClone) {
12143
12516
  console.log("\nIf you haven't yet, symlink the skills + knowledge and install the bridge:");
12144
- console.log(` ${ui.cmd("scripts/sync-symlinks.sh")} ${ui.dim("# mix skills + knowledge \u2192 ~/.claude, skills + agents \u2192 ~/.agents")}`);
12517
+ console.log(` ${ui2.cmd("scripts/sync-symlinks.sh")} ${ui2.dim("# mix skills + knowledge \u2192 ~/.claude, skills + agents \u2192 ~/.agents")}`);
12145
12518
  } else {
12146
12519
  console.log("");
12147
12520
  installSkills(false, ids);
12148
12521
  if (!chained) console.log("\nIf you haven't yet, install the bridge:");
12149
12522
  }
12150
12523
  if (!chained) {
12151
- console.log(` ${ui.cmd("reaper-mcp setup")} ${ui.dim("# Lua bridge + JSFX \u2192 REAPER")}`);
12524
+ console.log(` ${ui2.cmd("reaper-mcp setup")} ${ui2.dim("# Lua bridge + JSFX \u2192 REAPER")}`);
12152
12525
  console.log("then start (or restart) REAPER: the bridge starts with it.");
12153
12526
  }
12154
12527
  if (!inClone) console.log(`
12155
- Want it to remember plugins and your corrections? Connect LoreKit (free, about five minutes): ${ui.link("https://reaper-mcp.vercel.app/docs/connect-lorekit")}`);
12528
+ Want it to remember plugins and your corrections? Connect LoreKit (free, about five minutes): ${ui2.link("https://reaper-mcp.vercel.app/docs/connect-lorekit")}`);
12156
12529
  console.log(`
12157
- Try: ${ui.cmd('/mixer "Please gain stage my tracks"')} \xB7 ${ui.cmd('/critique "Roast my mix"')}`);
12530
+ Try: ${ui2.cmd('/mixer "Please gain stage my tracks"')} \xB7 ${ui2.cmd('/critique "Roast my mix"')}`);
12158
12531
  }
12159
12532
  function installSkills(dryRun = false, ids) {
12160
12533
  if (findCloneRoot(__dirname2)) {
12161
12534
  console.log("Running from a clone: scripts/sync-symlinks.sh links the skills and knowledge into ~/.claude and ~/.agents.");
12162
12535
  return;
12163
12536
  }
12164
- const src = join21(resolveAssetDir(__dirname2, "claude"));
12165
- if (!existsSync13(src)) {
12537
+ const src = join23(resolveAssetDir(__dirname2, "claude"));
12538
+ if (!existsSync15(src)) {
12166
12539
  console.log(`Skills not found: ${src} (this build has no claude/ folder)`);
12167
12540
  process.exitCode = 1;
12168
12541
  return;
@@ -12180,21 +12553,21 @@ function installSkills(dryRun = false, ids) {
12180
12553
  const homes = skillsHomes(targets.length ? targets : ["claude"]);
12181
12554
  const verb = dryRun ? "Would install" : "Installed";
12182
12555
  const jobs = [];
12183
- if (homes.claude) jobs.push({ label: "~/.claude", dir: join21(homedir12(), ".claude"), what: "the mix skills, agents and knowledge" });
12184
- if (homes.agents) jobs.push({ label: "~/.agents", dir: join21(homedir12(), ".agents"), include: ["skills", "agents"], what: "the mix skills and agents" });
12185
- if (homes.agents && !homes.claude) jobs.push({ label: "~/.claude", dir: join21(homedir12(), ".claude"), include: ["knowledge"], what: "the knowledge base the skills read" });
12556
+ if (homes.claude) jobs.push({ label: "~/.claude", dir: join23(homedir14(), ".claude"), what: "the mix skills, agents and knowledge" });
12557
+ if (homes.agents) jobs.push({ label: "~/.agents", dir: join23(homedir14(), ".agents"), include: ["skills", "agents"], what: "the mix skills and agents" });
12558
+ if (homes.agents && !homes.claude) jobs.push({ label: "~/.claude", dir: join23(homedir14(), ".claude"), include: ["knowledge"], what: "the knowledge base the skills read" });
12186
12559
  for (const job of jobs) {
12187
12560
  const r = installClaudeAssets(src, job.dir, { dryRun, include: job.include });
12188
- console.log(`${ui.mark("ok")} ${verb} ${job.what} in ${job.label}: ${r.installed.length} new, ${r.updated.length} updated, ${r.unchanged} already current.`);
12561
+ console.log(`${ui2.mark("ok")} ${verb} ${job.what} in ${job.label}: ${r.installed.length} new, ${r.updated.length} updated, ${r.unchanged} already current.`);
12189
12562
  for (const s of r.skipped) {
12190
12563
  const why = { edited: "you changed it, left as is", "not-ours": "already exists and is yours, left as is", symlink: "linked elsewhere, left as is", "broken-symlink": "a link to a folder that no longer exists (a deleted clone?); remove it and run this again" }[s.reason];
12191
- console.log(ui.dim(` Skipped ${s.path}: ${why}`));
12564
+ console.log(ui2.dim(` Skipped ${s.path}: ${why}`));
12192
12565
  }
12193
12566
  }
12194
12567
  if (!dryRun) console.log("Try /mixer, /critique or /learn-plugin in your harness. (/learn-plugin saves what it learns to LoreKit, see the README.)");
12195
12568
  }
12196
12569
  function consoleConsentIO() {
12197
- return { input: process.stdin, output: process.stdout, interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY), ui };
12570
+ return { input: process.stdin, output: process.stdout, interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY), ui: ui2 };
12198
12571
  }
12199
12572
  var OPT_OUT_COUNTED = 'One anonymous "opted out" count was sent (no install id). Nothing is sent after this.';
12200
12573
  async function askTelemetryOnce() {
@@ -12205,29 +12578,29 @@ async function askTelemetryOnce() {
12205
12578
  }
12206
12579
  function describeTelemetry() {
12207
12580
  const { mode, reason } = resolveTelemetry();
12208
- const label = { default: ui.ok("On \u2014 pseudonymous usage data to the developer"), custom: ui.cmd("Custom \u2014 your own OTEL_* destination"), off: ui.dim("Off") }[mode];
12209
- return `${label} ${ui.dim(`(${reason})`)}`;
12581
+ const label = { default: ui2.ok("On \u2014 pseudonymous usage data to the developer"), custom: ui2.cmd("Custom \u2014 your own OTEL_* destination"), off: ui2.dim("Off") }[mode];
12582
+ return `${label} ${ui2.dim(`(${reason})`)}`;
12210
12583
  }
12211
12584
  async function telemetryCommand(sub = "status") {
12212
12585
  if (sub !== "on" && sub !== "off" && sub !== "setup" && sub !== "status") {
12213
- console.log(`Usage: ${ui.cmd("reaper-mcp telemetry")} [status|on|off]`);
12586
+ console.log(`Usage: ${ui2.cmd("reaper-mcp telemetry")} [status|on|off]`);
12214
12587
  process.exitCode = 1;
12215
12588
  return;
12216
12589
  }
12217
- if (ui.fancy && sub !== "setup") console.log(ui.banner("Telemetry", readServiceVersion()));
12590
+ if (ui2.fancy && sub !== "setup") console.log(ui2.banner("Telemetry", readServiceVersion()));
12218
12591
  if (sub === "off" && resolveTelemetry().mode === "default" && !await confirmOptOutPrompt(consoleConsentIO())) return;
12219
12592
  if (sub === "on" || sub === "off") {
12220
12593
  const change = saveTelemetryChoice(sub === "on");
12221
12594
  const counted = change ? await reportConsentChange(change) : false;
12222
- if (sub === "on") console.log(`${ui.mark("ok")} Pseudonymous usage telemetry turned ${ui.ok("on")} \u2014 thank you!`);
12223
- else console.log(`${ui.mark("ok")} Telemetry turned ${ui.bold("off")}. ${counted ? OPT_OUT_COUNTED : "Nothing will be sent."}`);
12224
- console.log(`${ui.dim("Restart Claude Code (or run")} ${ui.cmd("/mcp")}${ui.dim(") for the running server to pick it up.")}`);
12595
+ if (sub === "on") console.log(`${ui2.mark("ok")} Pseudonymous usage telemetry turned ${ui2.ok("on")} \u2014 thank you!`);
12596
+ else console.log(`${ui2.mark("ok")} Telemetry turned ${ui2.bold("off")}. ${counted ? OPT_OUT_COUNTED : "Nothing will be sent."}`);
12597
+ console.log(`${ui2.dim("Restart Claude Code (or run")} ${ui2.cmd("/mcp")}${ui2.dim(") for the running server to pick it up.")}`);
12225
12598
  } else if (sub === "setup") {
12226
- if (!await askTelemetryOnce()) console.log(`${ui.bold("Telemetry:")} ${describeTelemetry()}`);
12599
+ if (!await askTelemetryOnce()) console.log(`${ui2.bold("Telemetry:")} ${describeTelemetry()}`);
12227
12600
  return;
12228
12601
  }
12229
- console.log(`${ui.bold("Telemetry:")} ${describeTelemetry()}`);
12230
- console.log(`What is and isn't collected: ${ui.link(TELEMETRY_DOC_URL)}`);
12602
+ console.log(`${ui2.bold("Telemetry:")} ${describeTelemetry()}`);
12603
+ console.log(`What is and isn't collected: ${ui2.link(TELEMETRY_DOC_URL)}`);
12231
12604
  }
12232
12605
  async function doctor() {
12233
12606
  const core2 = [];
@@ -12235,27 +12608,27 @@ async function doctor() {
12235
12608
  core2.push(
12236
12609
  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" }
12237
12610
  );
12238
- const readIfExists = (path) => existsSync13(path) ? readFileSync15(path, "utf-8") : null;
12611
+ const readIfExists = (path) => existsSync15(path) ? readFileSync16(path, "utf-8") : null;
12239
12612
  core2.push(autostartCheck(
12240
- readIfExists(join21(getReaperScriptsPath(), "__startup.lua")),
12241
- readIfExists(join21(getReaperResourcePath(), "reaper-extstate.ini")),
12613
+ readIfExists(join23(getReaperScriptsPath(), "__startup.lua")),
12614
+ readIfExists(join23(getReaperResourcePath(), "reaper-extstate.ini")),
12242
12615
  await isReaperRunning()
12243
12616
  ));
12244
12617
  const forcedFlags = flagOverrideCheck();
12245
12618
  if (forcedFlags) core2.push(forcedFlags);
12246
- const globalClaudeDir = join21(homedir12(), ".claude");
12247
- const localSkills = existsSync13(join21(process.cwd(), ".claude", "skills", "mixer", "SKILL.md"));
12248
- const globalSkills = existsSync13(join21(globalClaudeDir, "skills", "mixer", "SKILL.md"));
12249
- const sharedSkills = existsSync13(join21(homedir12(), ".agents", "skills", "mixer", "SKILL.md"));
12619
+ const globalClaudeDir = join23(homedir14(), ".claude");
12620
+ const localSkills = existsSync15(join23(process.cwd(), ".claude", "skills", "mixer", "SKILL.md"));
12621
+ const globalSkills = existsSync15(join23(globalClaudeDir, "skills", "mixer", "SKILL.md"));
12622
+ const sharedSkills = existsSync15(join23(homedir14(), ".agents", "skills", "mixer", "SKILL.md"));
12250
12623
  core2.push(
12251
12624
  localSkills || globalSkills || sharedSkills ? { label: "Mix skills", status: "ok", detail: localSkills ? ".claude/skills" : globalSkills ? "~/.claude/skills" : "~/.agents/skills" } : { label: "Mix skills", status: "fail", detail: "Not linked", fix: findCloneRoot(__dirname2) ? "scripts/sync-symlinks.sh (from your clone)" : "reaper-mcp install-skills" }
12252
12625
  );
12253
- const localKnowledge = existsSync13(join21(process.cwd(), ".claude", "knowledge"));
12254
- const knowledgeLinked = localKnowledge || existsSync13(join21(globalClaudeDir, "knowledge"));
12626
+ const localKnowledge = existsSync15(join23(process.cwd(), ".claude", "knowledge"));
12627
+ const knowledgeLinked = localKnowledge || existsSync15(join23(globalClaudeDir, "knowledge"));
12255
12628
  core2.push(
12256
12629
  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" }
12257
12630
  );
12258
- const mcpJsonExists = existsSync13(join21(process.cwd(), ".mcp.json"));
12631
+ const mcpJsonExists = existsSync15(join23(process.cwd(), ".mcp.json"));
12259
12632
  const harnessEnv = realEnv();
12260
12633
  const installed = detectHarnesses(harnessEnv);
12261
12634
  const connected = installed.filter((h) => registeredServer(h.id, harnessEnv));
@@ -12278,11 +12651,11 @@ async function doctor() {
12278
12651
  status: "info",
12279
12652
  detail: { default: "On, pseudonymous \xB7 turn off: reaper-mcp telemetry off", custom: "Your own OTEL_* destination", off: "Off" }[telemetry]
12280
12653
  });
12281
- const sidecarVenvPath = join21(homedir12(), ".reaper-mcp", "sidecar-venv");
12282
- const venvBin = platform6() === "win32" ? "Scripts" : "bin";
12283
- const venvPythonName = platform6() === "win32" ? "python.exe" : "python";
12284
- const venvPython = join21(sidecarVenvPath, venvBin, venvPythonName);
12285
- const hfCachePath = join21(homedir12(), ".cache", "huggingface", "hub");
12654
+ const sidecarVenvPath = join23(homedir14(), ".reaper-mcp", "sidecar-venv");
12655
+ const venvBin = platform8() === "win32" ? "Scripts" : "bin";
12656
+ const venvPythonName = platform8() === "win32" ? "python.exe" : "python";
12657
+ const venvPython = join23(sidecarVenvPath, venvBin, venvPythonName);
12658
+ const hfCachePath = join23(homedir14(), ".cache", "huggingface", "hub");
12286
12659
  let pythonOk = false;
12287
12660
  let pythonDetail = "Not found";
12288
12661
  try {
@@ -12299,9 +12672,9 @@ async function doctor() {
12299
12672
  } catch {
12300
12673
  pythonDetail = "Not found";
12301
12674
  }
12302
- const venvExists = existsSync13(sidecarVenvPath);
12675
+ const venvExists = existsSync15(sidecarVenvPath);
12303
12676
  let depsOk = false;
12304
- if (venvExists && existsSync13(venvPython)) {
12677
+ if (venvExists && existsSync15(venvPython)) {
12305
12678
  try {
12306
12679
  await execAsync(`"${venvPython}" -c "import audiobox_aesthetics.infer"`);
12307
12680
  depsOk = true;
@@ -12315,14 +12688,14 @@ async function doctor() {
12315
12688
  addOns.demucs = found.separation;
12316
12689
  addOns.lv_chordia = found.chords;
12317
12690
  }
12318
- const weightsPath = join21(hfCachePath, "models--facebook--audiobox-aesthetics");
12319
- const weightsExist = existsSync13(weightsPath);
12691
+ const weightsPath = join23(hfCachePath, "models--facebook--audiobox-aesthetics");
12692
+ const weightsExist = existsSync15(weightsPath);
12320
12693
  const sidecarReady = venvExists && depsOk;
12321
12694
  const sidecarOptedIn = venvExists;
12322
12695
  const sidecarBroken = sidecarOptedIn && !sidecarReady;
12323
12696
  const missing = sidecarOptedIn ? "fail" : "info";
12324
12697
  const repair = "reaper-mcp setup-sidecar";
12325
- const home = (p) => p.replace(homedir12(), "~");
12698
+ const home = (p) => p.replace(homedir14(), "~");
12326
12699
  const sidecar = {
12327
12700
  title: "Python sidecar",
12328
12701
  note: "optional \xB7 lets Claude listen to the audio",
@@ -12357,8 +12730,8 @@ async function doctor() {
12357
12730
  const sections3 = [{ title: "Core", checks: core2 }, sidecar];
12358
12731
  if (extensionChecks.length > 0) sections3.push({ title: "Extensions", checks: extensionChecks });
12359
12732
  const extensionsBroken = extensionChecks.some((c) => c.status === "fail");
12360
- if (ui.fancy) console.log(ui.banner("Doctor", readServiceVersion()));
12361
- console.log(renderDoctor(sections3, { version: readServiceVersion(), color: useColor(), header: !ui.fancy }));
12733
+ if (ui2.fancy) console.log(ui2.banner("Doctor", readServiceVersion()));
12734
+ console.log(renderDoctor(sections3, { version: readServiceVersion(), color: useColor(), header: !ui2.fancy }));
12362
12735
  return bridgeRunning && knowledgeLinked && mcpRegistered && !sidecarBroken && !extensionsBroken ? 0 : 1;
12363
12736
  }
12364
12737
  function notifyNewerRelease(log) {
@@ -12477,12 +12850,12 @@ async function updateCommand(force, bridge) {
12477
12850
  const cloneRoot = findCloneRoot(__dirname2);
12478
12851
  if (cloneRoot) {
12479
12852
  return new Promise((resolveCode) => {
12480
- const child = spawn3("bash", ["./scripts/update.sh"], { cwd: cloneRoot, stdio: "inherit" });
12853
+ const child = spawn4("bash", ["./scripts/update.sh"], { cwd: cloneRoot, stdio: "inherit" });
12481
12854
  child.on("error", () => resolveCode(1));
12482
12855
  child.on("close", (code) => resolveCode(code ?? 1));
12483
12856
  });
12484
12857
  }
12485
- return runUpdate(realUpdateDeps(readServiceVersion(), join21(__dirname2, "main.js"), force, bridge));
12858
+ return runUpdate(realUpdateDeps(readServiceVersion(), join23(__dirname2, "main.js"), force, bridge));
12486
12859
  }
12487
12860
  var command = process.argv[2];
12488
12861
  switch (command) {
@@ -12528,6 +12901,15 @@ switch (command) {
12528
12901
  case "flags":
12529
12902
  process.exit(flagsCommand(process.argv.slice(3)));
12530
12903
  break;
12904
+ case "instance":
12905
+ instanceCommand(process.argv.slice(3)).then(
12906
+ (code) => process.exit(code),
12907
+ (err) => {
12908
+ console.error(err instanceof Error ? err.message : err);
12909
+ process.exit(1);
12910
+ }
12911
+ );
12912
+ break;
12531
12913
  case "extension":
12532
12914
  case "extensions":
12533
12915
  extensionCommand(process.argv.slice(3)).then(
@@ -12548,7 +12930,7 @@ switch (command) {
12548
12930
  (async () => {
12549
12931
  const status = await getBridgeState();
12550
12932
  const running = status.state === "connected";
12551
- console.log(`Bridge status: ${running ? ui.ok("CONNECTED") : ui.fail(`NOT DETECTED (${status.state})`)}`);
12933
+ console.log(`Bridge status: ${running ? ui2.ok("CONNECTED") : ui2.fail(`NOT DETECTED (${status.state})`)}`);
12552
12934
  if (!running) console.log(bridgeDownMessage(status));
12553
12935
  process.exit(running ? 0 : 1);
12554
12936
  })();
@@ -12575,6 +12957,8 @@ Usage:
12575
12957
  Agents/CI: --yes (core + aesthetics weights), --all, --with-separation (Demucs),
12576
12958
  --with-chords (chord model), --without-aesthetics, --list [--json] (what is installed)
12577
12959
  reaper-mcp extension Manage opt-in extensions: list | add <name|folder|git-url> | link <folder> | remove <name> | new <name>
12960
+ reaper-mcp instance A second REAPER for the agent to work in while you work in yours: create <name> | start <name> [project.rpp] |
12961
+ connect <name> | stop <name> | list | remove <name>
12578
12962
  reaper-mcp init Connect the harnesses you have installed (Claude Code, Codex CLI, Gemini CLI, Cursor) and suggest the ones you don't;
12579
12963
  --harness claude,codex or --all to pick by hand. From npm it also installs the skills
12580
12964
  reaper-mcp install-skills Copy the mix skills, agents and knowledge into ~/.claude, and skills + agents into ~/.agents for the