@nodetool-ai/timeline 0.8.19 → 0.8.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/autoCrossfade.d.ts +30 -0
  3. package/dist/autoCrossfade.d.ts.map +1 -0
  4. package/dist/autoCrossfade.js +130 -0
  5. package/dist/autoCrossfade.js.map +1 -0
  6. package/dist/automation.d.ts +32 -1
  7. package/dist/automation.d.ts.map +1 -1
  8. package/dist/automation.js +78 -1
  9. package/dist/automation.js.map +1 -1
  10. package/dist/automationRanges.d.ts +375 -0
  11. package/dist/automationRanges.d.ts.map +1 -0
  12. package/dist/automationRanges.js +375 -0
  13. package/dist/automationRanges.js.map +1 -0
  14. package/dist/clipAudio.d.ts +3 -1
  15. package/dist/clipAudio.d.ts.map +1 -1
  16. package/dist/clipAudio.js.map +1 -1
  17. package/dist/clipLoop.d.ts +67 -0
  18. package/dist/clipLoop.d.ts.map +1 -0
  19. package/dist/clipLoop.js +339 -0
  20. package/dist/clipLoop.js.map +1 -0
  21. package/dist/clipSpeed.d.ts.map +1 -1
  22. package/dist/clipSpeed.js +7 -0
  23. package/dist/clipSpeed.js.map +1 -1
  24. package/dist/defaults.d.ts.map +1 -1
  25. package/dist/defaults.js +9 -0
  26. package/dist/defaults.js.map +1 -1
  27. package/dist/dropResolve.d.ts.map +1 -1
  28. package/dist/dropResolve.js +56 -17
  29. package/dist/dropResolve.js.map +1 -1
  30. package/dist/harmony/chordChart.d.ts +25 -0
  31. package/dist/harmony/chordChart.d.ts.map +1 -0
  32. package/dist/harmony/chordChart.js +99 -0
  33. package/dist/harmony/chordChart.js.map +1 -0
  34. package/dist/harmony/chordRange.d.ts +9 -0
  35. package/dist/harmony/chordRange.d.ts.map +1 -0
  36. package/dist/harmony/chordRange.js +32 -0
  37. package/dist/harmony/chordRange.js.map +1 -0
  38. package/dist/harmony/chordSymbols.d.ts +28 -0
  39. package/dist/harmony/chordSymbols.d.ts.map +1 -0
  40. package/dist/harmony/chordSymbols.js +147 -0
  41. package/dist/harmony/chordSymbols.js.map +1 -0
  42. package/dist/harmony/chordTrack.d.ts +13 -0
  43. package/dist/harmony/chordTrack.d.ts.map +1 -0
  44. package/dist/harmony/chordTrack.js +11 -0
  45. package/dist/harmony/chordTrack.js.map +1 -0
  46. package/dist/harmony/detect.d.ts +35 -0
  47. package/dist/harmony/detect.d.ts.map +1 -0
  48. package/dist/harmony/detect.js +138 -0
  49. package/dist/harmony/detect.js.map +1 -0
  50. package/dist/harmony/detectAudio.d.ts +62 -0
  51. package/dist/harmony/detectAudio.d.ts.map +1 -0
  52. package/dist/harmony/detectAudio.js +226 -0
  53. package/dist/harmony/detectAudio.js.map +1 -0
  54. package/dist/harmony/expand.d.ts +7 -12
  55. package/dist/harmony/expand.d.ts.map +1 -1
  56. package/dist/harmony/expand.js +63 -11
  57. package/dist/harmony/expand.js.map +1 -1
  58. package/dist/harmony/index.d.ts +7 -0
  59. package/dist/harmony/index.d.ts.map +1 -1
  60. package/dist/harmony/index.js +7 -0
  61. package/dist/harmony/index.js.map +1 -1
  62. package/dist/harmony/progressionLibrary.d.ts +33 -0
  63. package/dist/harmony/progressionLibrary.d.ts.map +1 -0
  64. package/dist/harmony/progressionLibrary.js +71 -0
  65. package/dist/harmony/progressionLibrary.js.map +1 -0
  66. package/dist/harmony/summary.d.ts +4 -0
  67. package/dist/harmony/summary.d.ts.map +1 -0
  68. package/dist/harmony/summary.js +22 -0
  69. package/dist/harmony/summary.js.map +1 -0
  70. package/dist/index.d.ts +3 -0
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +3 -0
  73. package/dist/index.js.map +1 -1
  74. package/dist/interchange.d.ts.map +1 -1
  75. package/dist/interchange.js +72 -12
  76. package/dist/interchange.js.map +1 -1
  77. package/dist/loopWindow.d.ts +17 -0
  78. package/dist/loopWindow.d.ts.map +1 -0
  79. package/dist/loopWindow.js +34 -0
  80. package/dist/loopWindow.js.map +1 -0
  81. package/dist/midi/cacheKey.d.ts +11 -2
  82. package/dist/midi/cacheKey.d.ts.map +1 -1
  83. package/dist/midi/cacheKey.js +69 -9
  84. package/dist/midi/cacheKey.js.map +1 -1
  85. package/dist/midi/controllerEdit.d.ts +35 -0
  86. package/dist/midi/controllerEdit.d.ts.map +1 -0
  87. package/dist/midi/controllerEdit.js +94 -0
  88. package/dist/midi/controllerEdit.js.map +1 -0
  89. package/dist/midi/controllerRange.d.ts +13 -0
  90. package/dist/midi/controllerRange.d.ts.map +1 -0
  91. package/dist/midi/controllerRange.js +13 -0
  92. package/dist/midi/controllerRange.js.map +1 -0
  93. package/dist/midi/controllers.d.ts +95 -0
  94. package/dist/midi/controllers.d.ts.map +1 -0
  95. package/dist/midi/controllers.js +421 -0
  96. package/dist/midi/controllers.js.map +1 -0
  97. package/dist/midi/curveCut.d.ts +17 -0
  98. package/dist/midi/curveCut.d.ts.map +1 -0
  99. package/dist/midi/curveCut.js +45 -0
  100. package/dist/midi/curveCut.js.map +1 -0
  101. package/dist/midi/edit.d.ts +13 -1
  102. package/dist/midi/edit.d.ts.map +1 -1
  103. package/dist/midi/edit.js +19 -3
  104. package/dist/midi/edit.js.map +1 -1
  105. package/dist/midi/engines/bl1.d.ts +10 -1
  106. package/dist/midi/engines/bl1.d.ts.map +1 -1
  107. package/dist/midi/engines/bl1.js +26 -6
  108. package/dist/midi/engines/bl1.js.map +1 -1
  109. package/dist/midi/engines/dr1.d.ts +11 -1
  110. package/dist/midi/engines/dr1.d.ts.map +1 -1
  111. package/dist/midi/engines/dr1.js +21 -3
  112. package/dist/midi/engines/dr1.js.map +1 -1
  113. package/dist/midi/engines/dsp.d.ts +1 -1
  114. package/dist/midi/engines/dsp.d.ts.map +1 -1
  115. package/dist/midi/engines/dsp.js +10 -2
  116. package/dist/midi/engines/dsp.js.map +1 -1
  117. package/dist/midi/engines/wt1.d.ts +10 -1
  118. package/dist/midi/engines/wt1.d.ts.map +1 -1
  119. package/dist/midi/engines/wt1.js +28 -5
  120. package/dist/midi/engines/wt1.js.map +1 -1
  121. package/dist/midi/events.d.ts +13 -4
  122. package/dist/midi/events.d.ts.map +1 -1
  123. package/dist/midi/events.js +33 -6
  124. package/dist/midi/events.js.map +1 -1
  125. package/dist/midi/expression.d.ts +25 -0
  126. package/dist/midi/expression.d.ts.map +1 -0
  127. package/dist/midi/expression.js +69 -0
  128. package/dist/midi/expression.js.map +1 -0
  129. package/dist/midi/index.d.ts +8 -0
  130. package/dist/midi/index.d.ts.map +1 -1
  131. package/dist/midi/index.js +8 -0
  132. package/dist/midi/index.js.map +1 -1
  133. package/dist/midi/instrument.d.ts.map +1 -1
  134. package/dist/midi/instrument.js +4 -0
  135. package/dist/midi/instrument.js.map +1 -1
  136. package/dist/midi/noteFunctions.d.ts +29 -0
  137. package/dist/midi/noteFunctions.d.ts.map +1 -0
  138. package/dist/midi/noteFunctions.js +213 -0
  139. package/dist/midi/noteFunctions.js.map +1 -0
  140. package/dist/midi/notes.d.ts +7 -1
  141. package/dist/midi/notes.d.ts.map +1 -1
  142. package/dist/midi/notes.js +43 -1
  143. package/dist/midi/notes.js.map +1 -1
  144. package/dist/midi/notesEdit.d.ts +13 -0
  145. package/dist/midi/notesEdit.d.ts.map +1 -1
  146. package/dist/midi/notesEdit.js +73 -2
  147. package/dist/midi/notesEdit.js.map +1 -1
  148. package/dist/midi/presets.d.ts +1 -1
  149. package/dist/midi/regionParams.d.ts +41 -0
  150. package/dist/midi/regionParams.d.ts.map +1 -0
  151. package/dist/midi/regionParams.js +164 -0
  152. package/dist/midi/regionParams.js.map +1 -0
  153. package/dist/midi/sampler.d.ts +2 -2
  154. package/dist/midi/sampler.d.ts.map +1 -1
  155. package/dist/midi/sampler.js +99 -21
  156. package/dist/midi/sampler.js.map +1 -1
  157. package/dist/midi/stepEditor.d.ts +50 -0
  158. package/dist/midi/stepEditor.d.ts.map +1 -0
  159. package/dist/midi/stepEditor.js +118 -0
  160. package/dist/midi/stepEditor.js.map +1 -0
  161. package/dist/midi/stepPattern.d.ts +173 -0
  162. package/dist/midi/stepPattern.d.ts.map +1 -0
  163. package/dist/midi/stepPattern.js +1390 -0
  164. package/dist/midi/stepPattern.js.map +1 -0
  165. package/dist/midi/stepPatternExpand.d.ts +149 -0
  166. package/dist/midi/stepPatternExpand.d.ts.map +1 -0
  167. package/dist/midi/stepPatternExpand.js +1068 -0
  168. package/dist/midi/stepPatternExpand.js.map +1 -0
  169. package/dist/midi/stepPatternLibrary.d.ts +65 -0
  170. package/dist/midi/stepPatternLibrary.d.ts.map +1 -0
  171. package/dist/midi/stepPatternLibrary.js +640 -0
  172. package/dist/midi/stepPatternLibrary.js.map +1 -0
  173. package/dist/midi/tempo.d.ts.map +1 -1
  174. package/dist/midi/tempo.js +3 -0
  175. package/dist/midi/tempo.js.map +1 -1
  176. package/dist/midi/voice.d.ts +51 -5
  177. package/dist/midi/voice.d.ts.map +1 -1
  178. package/dist/midi/voice.js +191 -21
  179. package/dist/midi/voice.js.map +1 -1
  180. package/dist/model3dBake.d.ts +13 -0
  181. package/dist/model3dBake.d.ts.map +1 -1
  182. package/dist/model3dBake.js +25 -0
  183. package/dist/model3dBake.js.map +1 -1
  184. package/dist/model3dCameraDescription.d.ts +11 -6
  185. package/dist/model3dCameraDescription.d.ts.map +1 -1
  186. package/dist/model3dCameraDescription.js +112 -30
  187. package/dist/model3dCameraDescription.js.map +1 -1
  188. package/dist/model3dReference.d.ts +25 -4
  189. package/dist/model3dReference.d.ts.map +1 -1
  190. package/dist/model3dReference.js +19 -6
  191. package/dist/model3dReference.js.map +1 -1
  192. package/dist/music/align.d.ts +111 -0
  193. package/dist/music/align.d.ts.map +1 -0
  194. package/dist/music/align.js +282 -0
  195. package/dist/music/align.js.map +1 -0
  196. package/dist/music/cut.d.ts +33 -0
  197. package/dist/music/cut.d.ts.map +1 -0
  198. package/dist/music/cut.js +50 -0
  199. package/dist/music/cut.js.map +1 -0
  200. package/dist/music/frames.d.ts +51 -0
  201. package/dist/music/frames.d.ts.map +1 -0
  202. package/dist/music/frames.js +110 -0
  203. package/dist/music/frames.js.map +1 -0
  204. package/dist/music/gain.d.ts +24 -0
  205. package/dist/music/gain.d.ts.map +1 -0
  206. package/dist/music/gain.js +38 -0
  207. package/dist/music/gain.js.map +1 -0
  208. package/dist/music/index.d.ts +9 -0
  209. package/dist/music/index.d.ts.map +1 -0
  210. package/dist/music/index.js +9 -0
  211. package/dist/music/index.js.map +1 -0
  212. package/dist/music/plan.d.ts +104 -0
  213. package/dist/music/plan.d.ts.map +1 -0
  214. package/dist/music/plan.js +300 -0
  215. package/dist/music/plan.js.map +1 -0
  216. package/dist/music/process.d.ts +9 -0
  217. package/dist/music/process.d.ts.map +1 -0
  218. package/dist/music/process.js +9 -0
  219. package/dist/music/process.js.map +1 -0
  220. package/dist/music/roles.d.ts +14 -0
  221. package/dist/music/roles.d.ts.map +1 -0
  222. package/dist/music/roles.js +30 -0
  223. package/dist/music/roles.js.map +1 -0
  224. package/dist/music/splice.d.ts +37 -0
  225. package/dist/music/splice.d.ts.map +1 -0
  226. package/dist/music/splice.js +67 -0
  227. package/dist/music/splice.js.map +1 -0
  228. package/dist/music/tempoRules.d.ts +41 -0
  229. package/dist/music/tempoRules.d.ts.map +1 -0
  230. package/dist/music/tempoRules.js +59 -0
  231. package/dist/music/tempoRules.js.map +1 -0
  232. package/dist/ops/apply.d.ts.map +1 -1
  233. package/dist/ops/apply.js +856 -234
  234. package/dist/ops/apply.js.map +1 -1
  235. package/dist/ops/automation.d.ts +6 -0
  236. package/dist/ops/automation.d.ts.map +1 -0
  237. package/dist/ops/automation.js +217 -0
  238. package/dist/ops/automation.js.map +1 -0
  239. package/dist/ops/barTime.d.ts +14 -0
  240. package/dist/ops/barTime.d.ts.map +1 -0
  241. package/dist/ops/barTime.js +33 -0
  242. package/dist/ops/barTime.js.map +1 -0
  243. package/dist/ops/chords.d.ts +43 -0
  244. package/dist/ops/chords.d.ts.map +1 -0
  245. package/dist/ops/chords.js +691 -0
  246. package/dist/ops/chords.js.map +1 -0
  247. package/dist/ops/groupBake.d.ts +24 -0
  248. package/dist/ops/groupBake.d.ts.map +1 -0
  249. package/dist/ops/groupBake.js +81 -0
  250. package/dist/ops/groupBake.js.map +1 -0
  251. package/dist/ops/index.d.ts +7 -0
  252. package/dist/ops/index.d.ts.map +1 -1
  253. package/dist/ops/index.js +5 -0
  254. package/dist/ops/index.js.map +1 -1
  255. package/dist/ops/join.d.ts +20 -0
  256. package/dist/ops/join.d.ts.map +1 -0
  257. package/dist/ops/join.js +265 -0
  258. package/dist/ops/join.js.map +1 -0
  259. package/dist/ops/loop.d.ts +29 -0
  260. package/dist/ops/loop.d.ts.map +1 -0
  261. package/dist/ops/loop.js +107 -0
  262. package/dist/ops/loop.js.map +1 -0
  263. package/dist/ops/midiMix.d.ts +41 -0
  264. package/dist/ops/midiMix.d.ts.map +1 -0
  265. package/dist/ops/midiMix.js +522 -0
  266. package/dist/ops/midiMix.js.map +1 -0
  267. package/dist/ops/op.d.ts +61 -11
  268. package/dist/ops/op.d.ts.map +1 -1
  269. package/dist/ops/op.js +60 -1
  270. package/dist/ops/op.js.map +1 -1
  271. package/dist/ops/parse.d.ts.map +1 -1
  272. package/dist/ops/parse.js +308 -4
  273. package/dist/ops/parse.js.map +1 -1
  274. package/dist/ops/pasteRange.d.ts +46 -0
  275. package/dist/ops/pasteRange.d.ts.map +1 -0
  276. package/dist/ops/pasteRange.js +276 -0
  277. package/dist/ops/pasteRange.js.map +1 -0
  278. package/dist/ops/plugin.d.ts +57 -0
  279. package/dist/ops/plugin.d.ts.map +1 -0
  280. package/dist/ops/plugin.js +875 -0
  281. package/dist/ops/plugin.js.map +1 -0
  282. package/dist/ops/sections.d.ts +98 -0
  283. package/dist/ops/sections.d.ts.map +1 -0
  284. package/dist/ops/sections.js +930 -0
  285. package/dist/ops/sections.js.map +1 -0
  286. package/dist/ops/serialize.d.ts +79 -1
  287. package/dist/ops/serialize.d.ts.map +1 -1
  288. package/dist/ops/serialize.js +85 -3
  289. package/dist/ops/serialize.js.map +1 -1
  290. package/dist/ops/stepPattern.d.ts +44 -0
  291. package/dist/ops/stepPattern.d.ts.map +1 -0
  292. package/dist/ops/stepPattern.js +2106 -0
  293. package/dist/ops/stepPattern.js.map +1 -0
  294. package/dist/ops/stepPatternFolders.d.ts +54 -0
  295. package/dist/ops/stepPatternFolders.d.ts.map +1 -0
  296. package/dist/ops/stepPatternFolders.js +299 -0
  297. package/dist/ops/stepPatternFolders.js.map +1 -0
  298. package/dist/ops/types.d.ts +238 -2
  299. package/dist/ops/types.d.ts.map +1 -1
  300. package/dist/rippleEdit.d.ts +5 -1
  301. package/dist/rippleEdit.d.ts.map +1 -1
  302. package/dist/rippleEdit.js +24 -9
  303. package/dist/rippleEdit.js.map +1 -1
  304. package/dist/script.d.ts +2 -1
  305. package/dist/script.d.ts.map +1 -1
  306. package/dist/script.js +3 -2
  307. package/dist/script.js.map +1 -1
  308. package/dist/splitClip.d.ts +29 -1
  309. package/dist/splitClip.d.ts.map +1 -1
  310. package/dist/splitClip.js +231 -1
  311. package/dist/splitClip.js.map +1 -1
  312. package/dist/storyboard.d.ts +14 -0
  313. package/dist/storyboard.d.ts.map +1 -1
  314. package/dist/storyboard.js +31 -0
  315. package/dist/storyboard.js.map +1 -1
  316. package/dist/testing/host-ops.js +3 -3
  317. package/dist/testing/host-ops.js.map +1 -1
  318. package/dist/testing/ops.d.ts +6 -1
  319. package/dist/testing/ops.d.ts.map +1 -1
  320. package/dist/testing/ops.js +823 -11
  321. package/dist/testing/ops.js.map +1 -1
  322. package/dist/timeRemap.d.ts +2 -2
  323. package/dist/timeRemap.d.ts.map +1 -1
  324. package/dist/timeRemap.js +18 -0
  325. package/dist/timeRemap.js.map +1 -1
  326. package/dist/trimClip.d.ts +1 -1
  327. package/dist/trimClip.d.ts.map +1 -1
  328. package/dist/trimClip.js +41 -7
  329. package/dist/trimClip.js.map +1 -1
  330. package/dist/types.d.ts +307 -16
  331. package/dist/types.d.ts.map +1 -1
  332. package/dist/types.js.map +1 -1
  333. package/package.json +11 -5
  334. package/dist/render/curveFitting.d.ts +0 -28
  335. package/dist/render/curveFitting.d.ts.map +0 -1
  336. package/dist/render/curveFitting.js +0 -94
  337. package/dist/render/curveFitting.js.map +0 -1
@@ -0,0 +1,2106 @@
1
+ /**
2
+ * Step Sequencer timeline ops (SQ20–SQ22, SQ42, SQ45, SQ47–SQ54).
3
+ *
4
+ * All 27 ops share one pure implementation invoked by `applyTimelineOp` across
5
+ * both the headless bridge and browser editor. Steps and loop bounds in tool
6
+ * input/output are 1-based (D97); stored `StepRow.steps` and `loopStart` are
7
+ * 0-based with exclusive `loopEnd`.
8
+ */
9
+ import { isFullResourceId, isShortResourceId } from "@nodetool-ai/protocol";
10
+ import { activeLoopMs } from "../clipLoop.js";
11
+ import { makeClip, makeTrack } from "../defaults.js";
12
+ import { barDurationMs } from "../midi/grid.js";
13
+ import { DEFAULT_MIDI_INSTRUMENT, instrumentSignature } from "../midi/instrument.js";
14
+ import { findInstrumentPreset, presetIdForInstrument } from "../midi/presets.js";
15
+ import { STEP_DEGREES, STEP_PATTERN_MAX_ROWS, STEP_PATTERN_MAX_STEPS, addPatternRow, applyMonoAtSteps, applyPatternRowSort, assignmentFromRowName, clearRowSteps, compactStep, defaultSubrowsForAssignment, isNoteRow, midiToPattern, normalizePattern, normalizeRow, normalizeStep, nudgeRowValues, parsePatternTextLines, parseStepNoteName, parseStepSelection, patternFromText, patternToText, randomizePatternSteps, resizePatternLength, resizeRowLength, rotateRowSteps, rowLabel, setPatternAutomationMode, setPatternKey, setPatternLoop, setPatternMidiChannel, setPatternPlayback, setPatternStepRate, setStepValue, sortPatternRows, stripPatternSteps, tieRowSteps, transposeRowSteps } from "../midi/stepPattern.js";
16
+ import { deriveTrackAutomationFromPatterns, expandPattern, fnv1a32Uints, kitPadPitch, rowKeyHash, stepRateTicks } from "../midi/stepPatternExpand.js";
17
+ import { FACTORY_STEP_PATTERNS, FACTORY_STEP_TEMPLATES, STEP_PATTERN_ASSET_CONTENT_TYPE, extractStepPatternTemplate, findFactoryStepPattern, isWithinStepPatternFolder, listFactoryStepPatterns, normalizeStepPatternFolderPath, parentStepPatternFolder, remapStepPatternFolderPath, stepPatternRootFolder } from "../midi/stepPatternLibrary.js";
18
+ import { DEFAULT_TEMPO, resolveTempo } from "../midi/tempo.js";
19
+ import { msToTicks } from "../midi/ticks.js";
20
+ import { resolveBarTime } from "./barTime.js";
21
+ import { collectStepPatternFolders, resolveCreateStepPatternFolderTarget, resolveMoveDestinationFolder, resolveRenameStepPatternFolderTarget, resolveStepPatternFolderRef, resolveUserStepPatternRef } from "./stepPatternFolders.js";
22
+ const clampInt = (v, lo, hi) => Math.max(lo, Math.min(hi, Math.round(v)));
23
+ /** Deterministic non-zero uint32 seed derived from a clip id. */
24
+ function seedForClipId(clipId) {
25
+ const h = rowKeyHash(clipId);
26
+ return h === 0 ? 1 : h;
27
+ }
28
+ /** Deterministic next uint32 seed distinct from `currentSeed`. */
29
+ function nextPatternSeed(clipId, currentSeed) {
30
+ const cur = currentSeed >>> 0;
31
+ let next = fnv1a32Uints(rowKeyHash(clipId), cur, 0x9e3779b9, 1) >>> 0;
32
+ if (next === 0 || next === cur) {
33
+ next = ((cur + 1) >>> 0) || 1;
34
+ }
35
+ return next;
36
+ }
37
+ /** Mint a unique deterministic row id within `pattern`. */
38
+ function mintRowId(pattern) {
39
+ const used = new Set(pattern.rows.map((r) => r.id));
40
+ let k = 1;
41
+ while (used.has(`r${k}`))
42
+ k += 1;
43
+ return `r${k}`;
44
+ }
45
+ function trackInstrumentOf(scope, clip) {
46
+ return scope.tracks.find((t) => t.id === clip.trackId)?.instrument;
47
+ }
48
+ function chordsOf(scope) {
49
+ return scope.tracks.find((t) => t.type === "chord")?.chords;
50
+ }
51
+ function resolvePatternClip(scope, clipId) {
52
+ const clip = scope.resolveMidiClip(clipId);
53
+ if (!clip.pattern) {
54
+ throw new Error(`Clip "${clip.name}" is a regular MIDI clip, not a step sequencer pattern region. Convert it with convert_midi_to_pattern or create one with create_pattern_region.`);
55
+ }
56
+ return {
57
+ clip,
58
+ pattern: clip.pattern,
59
+ instrument: trackInstrumentOf(scope, clip)
60
+ };
61
+ }
62
+ function formatValidRows(pattern, instrument) {
63
+ if (pattern.rows.length === 0) {
64
+ return "This pattern has no rows yet.";
65
+ }
66
+ const names = pattern.rows
67
+ .slice(0, 16)
68
+ .map((r) => `${r.id} ("${rowLabel(r, instrument)}")`)
69
+ .join(", ");
70
+ const more = pattern.rows.length > 16 ? `, and ${pattern.rows.length - 16} more` : "";
71
+ return `Valid rows: ${names}${more}.`;
72
+ }
73
+ /** Resolve a row by exact id, unique 12-char id prefix, or unique case-insensitive name/label. */
74
+ function resolveRow(pattern, target, instrument) {
75
+ const byIdIdx = pattern.rows.findIndex((r) => r.id === target);
76
+ if (byIdIdx >= 0) {
77
+ return { row: pattern.rows[byIdIdx], index: byIdIdx };
78
+ }
79
+ if (isShortResourceId(target)) {
80
+ const prefixMatches = [];
81
+ pattern.rows.forEach((row, index) => {
82
+ if (row.id.startsWith(target))
83
+ prefixMatches.push({ row, index });
84
+ });
85
+ if (prefixMatches.length > 1) {
86
+ throw new Error(`Row prefix "${target}" matches ${prefixMatches.length} rows (${prefixMatches
87
+ .map((m) => m.row.id)
88
+ .join(", ")}); use a full row id.`);
89
+ }
90
+ if (prefixMatches.length === 1) {
91
+ return prefixMatches[0];
92
+ }
93
+ }
94
+ const lower = target.trim().toLowerCase();
95
+ const matches = [];
96
+ pattern.rows.forEach((row, index) => {
97
+ const label = rowLabel(row, instrument).toLowerCase();
98
+ const explicit = row.name?.trim().toLowerCase();
99
+ if (label === lower || explicit === lower) {
100
+ matches.push({ row, index });
101
+ }
102
+ });
103
+ if (matches.length === 1) {
104
+ return matches[0];
105
+ }
106
+ if (matches.length > 1) {
107
+ throw new Error(`Row name "${target}" matches ${matches.length} rows (${matches
108
+ .map((m) => m.row.id)
109
+ .join(", ")}); address one by rowId.`);
110
+ }
111
+ throw new Error(`No row found matching "${target}". ${formatValidRows(pattern, instrument)}`);
112
+ }
113
+ export function patternSummary(pattern) {
114
+ return `${pattern.rows.length} rows x ${pattern.lengthSteps} @${pattern.stepRate}`;
115
+ }
116
+ function modeValueAtStep(row, stepIndex, mode, instrument) {
117
+ const raw = row.steps[stepIndex] ?? {};
118
+ const n = normalizeStep(raw);
119
+ switch (mode) {
120
+ case "onOff":
121
+ return n.on;
122
+ case "velocity":
123
+ return raw.velocity !== undefined ? n.velocity : n.on ? 100 : 0;
124
+ case "value":
125
+ return raw.value !== undefined ? n.value : n.on ? 64 : 0;
126
+ case "gate":
127
+ return n.gate;
128
+ case "tie":
129
+ return n.tie;
130
+ case "note":
131
+ return n.note;
132
+ case "octave":
133
+ return (n.octave ??
134
+ (row.assignment.type === "degree"
135
+ ? row.assignment.octave
136
+ : row.assignment.type === "kit"
137
+ ? Math.floor(kitPadPitch(row.assignment.pad, instrument) / 12) - 2
138
+ : row.assignment.type === "note" || row.assignment.type === "melodic"
139
+ ? Math.floor(row.assignment.pitch / 12) - 2
140
+ : 3));
141
+ case "repeat":
142
+ return n.repeat;
143
+ case "chance":
144
+ return n.chance;
145
+ case "offset":
146
+ return n.offset;
147
+ case "stepRate":
148
+ return n.stepRate ?? row.stepRate;
149
+ case "skip":
150
+ return n.skip;
151
+ case "loop":
152
+ return stepIndex >= row.loopStart && stepIndex < row.loopEnd;
153
+ }
154
+ }
155
+ function serializePatternRow(row, instrument, modes) {
156
+ const out = {
157
+ id: row.id,
158
+ name: rowLabel(row, instrument),
159
+ assignment: structuredClone(row.assignment),
160
+ stepRate: row.stepRate,
161
+ lengthSteps: row.lengthSteps,
162
+ playback: row.playback,
163
+ mute: row.mute,
164
+ solo: row.solo,
165
+ // 1-based inclusive loop range for agent output (D97).
166
+ loopStart: row.loopStart + 1,
167
+ loopEnd: row.loopEnd,
168
+ midiChannel: row.midiChannel,
169
+ automationMode: row.automationMode,
170
+ subrows: [...row.subrows]
171
+ };
172
+ if (row.color !== undefined)
173
+ out.color = row.color;
174
+ if (row.subrowsExpanded !== undefined)
175
+ out.subrowsExpanded = row.subrowsExpanded;
176
+ if (modes && modes.length > 0) {
177
+ const values = {};
178
+ for (const mode of modes) {
179
+ values[mode] = Array.from({ length: row.lengthSteps }, (_, i) => modeValueAtStep(row, i, mode, instrument));
180
+ }
181
+ out.values = values;
182
+ }
183
+ return out;
184
+ }
185
+ function serializePatternSettings(pattern) {
186
+ const out = {
187
+ name: pattern.name,
188
+ lengthSteps: pattern.lengthSteps,
189
+ stepRate: pattern.stepRate,
190
+ playback: pattern.playback,
191
+ swing: pattern.swing,
192
+ swingDivision: pattern.swingDivision,
193
+ legato: pattern.legato,
194
+ mono: pattern.mono,
195
+ midiChannel: pattern.midiChannel,
196
+ pitchSource: pattern.pitchSource,
197
+ key: pattern.key ? { ...pattern.key } : undefined,
198
+ scale: pattern.scale,
199
+ noTranspose: pattern.noTranspose,
200
+ scaleQuantize: pattern.scaleQuantize,
201
+ automationMode: pattern.automationMode,
202
+ seed: pattern.seed
203
+ };
204
+ if (pattern.rowSort !== undefined)
205
+ out.rowSort = pattern.rowSort;
206
+ return out;
207
+ }
208
+ /** Build default kit rows for a DR-1 or Sampler kit track (SQ42). */
209
+ function defaultRowsForTrack(track) {
210
+ const defaults = {
211
+ lengthSteps: 16,
212
+ stepRate: "1/16",
213
+ playback: "forward",
214
+ midiChannel: 1,
215
+ automationMode: "latch"
216
+ };
217
+ const inst = track.instrument;
218
+ if (inst?.type === "drum" && inst.pads.length > 0) {
219
+ return inst.pads.map((pad, idx) => normalizeRow({
220
+ id: `r${idx + 1}`,
221
+ name: pad.name,
222
+ assignment: { type: "kit", pad: idx }
223
+ }, defaults));
224
+ }
225
+ if (inst?.type === "sampler" && inst.zones.length > 0) {
226
+ return inst.zones.slice(0, 16).map((zone, idx) => normalizeRow({
227
+ id: `r${idx + 1}`,
228
+ name: zone.name,
229
+ assignment: { type: "kit", pad: idx }
230
+ }, defaults));
231
+ }
232
+ if (track.musicRole === "drums") {
233
+ const drumRows = [
234
+ { name: "Kick", pitch: 36 },
235
+ { name: "Snare", pitch: 38 },
236
+ { name: "Closed Hat", pitch: 42 },
237
+ { name: "Clap", pitch: 39 }
238
+ ];
239
+ return drumRows.map((d, idx) => normalizeRow({
240
+ id: `r${idx + 1}`,
241
+ name: d.name,
242
+ assignment: { type: "note", pitch: d.pitch }
243
+ }, defaults));
244
+ }
245
+ return [
246
+ normalizeRow({
247
+ id: "r1",
248
+ name: "C3",
249
+ assignment: { type: "melodic", pitch: 60 }
250
+ }, defaults)
251
+ ];
252
+ }
253
+ function projectKeyToStepKey(tempo) {
254
+ if (!tempo.key)
255
+ return undefined;
256
+ const tonicNames = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
257
+ const flatMap = {
258
+ C: 0, "C#": 1, Db: 1, D: 2, "D#": 3, Eb: 3, E: 4, F: 5,
259
+ "F#": 6, Gb: 6, G: 7, "G#": 8, Ab: 8, A: 9, "A#": 10, Bb: 10, B: 11
260
+ };
261
+ const idx = flatMap[tempo.key.tonic] ?? tonicNames.indexOf(tempo.key.tonic);
262
+ if (idx < 0)
263
+ return undefined;
264
+ return {
265
+ tonic: idx,
266
+ mode: tempo.key.mode === "minor" ? "minor" : "major"
267
+ };
268
+ }
269
+ const DEFAULT_MIDI_INSTRUMENT_SIG = instrumentSignature(DEFAULT_MIDI_INSTRUMENT);
270
+ function isDefaultOrUnsetTrackInstrument(instrument, hostDefault) {
271
+ if (!instrument)
272
+ return true;
273
+ const sig = instrumentSignature(instrument);
274
+ if (sig === DEFAULT_MIDI_INSTRUMENT_SIG)
275
+ return true;
276
+ if (hostDefault && sig === instrumentSignature(hostDefault))
277
+ return true;
278
+ return false;
279
+ }
280
+ function resolveSavedPatternInstrument(entry) {
281
+ if (entry.instrument) {
282
+ const instrument = structuredClone(entry.instrument);
283
+ const presetId = presetIdForInstrument(instrument);
284
+ return presetId ? { instrument, presetId } : { instrument };
285
+ }
286
+ if (entry.instrumentPreset) {
287
+ const preset = findInstrumentPreset(entry.instrumentPreset);
288
+ if (preset) {
289
+ return {
290
+ instrument: structuredClone(preset.instrument),
291
+ presetId: preset.id
292
+ };
293
+ }
294
+ }
295
+ return null;
296
+ }
297
+ function resolvedLibraryPattern(entry, source) {
298
+ const resolved = {
299
+ id: entry.id,
300
+ name: entry.name,
301
+ kind: entry.kind,
302
+ source,
303
+ pattern: normalizePattern(structuredClone(entry.pattern))
304
+ };
305
+ if (entry.instrument)
306
+ resolved.instrument = structuredClone(entry.instrument);
307
+ if (entry.instrumentPreset)
308
+ resolved.instrumentPreset = entry.instrumentPreset;
309
+ return resolved;
310
+ }
311
+ async function resolveLibraryPattern(scope, ref) {
312
+ const trimmed = ref.trim();
313
+ const needle = trimmed.toLowerCase();
314
+ if (scope.ctx.stepPatternLibrary) {
315
+ const userEntries = await scope.ctx.stepPatternLibrary.list();
316
+ let userMatch = userEntries.find((e) => e.id.toLowerCase() === needle || e.name.toLowerCase() === needle);
317
+ if (!userMatch && isShortResourceId(trimmed)) {
318
+ const prefixMatches = userEntries.filter((e) => e.id.startsWith(trimmed));
319
+ if (prefixMatches.length > 1) {
320
+ throw new Error(`Step pattern prefix "${trimmed}" matches ${prefixMatches.length} user patterns; use a full id.`);
321
+ }
322
+ userMatch = prefixMatches[0];
323
+ }
324
+ if (userMatch)
325
+ return resolvedLibraryPattern(userMatch, "user");
326
+ }
327
+ const factory = findFactoryStepPattern(ref);
328
+ if (factory)
329
+ return resolvedLibraryPattern(factory, "factory");
330
+ const sampleNames = [...FACTORY_STEP_PATTERNS, ...FACTORY_STEP_TEMPLATES]
331
+ .slice(0, 10)
332
+ .map((e) => `"${e.name}"`)
333
+ .join(", ");
334
+ throw new Error(`No step pattern or template found matching "${ref}". Examples: ${sampleNames} — call list_step_patterns for the full list.`);
335
+ }
336
+ /** Resolve a 12-char effect id prefix against `track.effects` (Resource ID Principles). */
337
+ function resolveDeviceId(deviceId, track) {
338
+ if (!deviceId || deviceId === "instrument")
339
+ return "instrument";
340
+ const effects = track?.effects ?? [];
341
+ const exact = effects.find((e) => e.id === deviceId);
342
+ if (exact)
343
+ return exact.id;
344
+ if (isShortResourceId(deviceId)) {
345
+ const matches = effects.filter((e) => e.id.startsWith(deviceId)); // key-boundary-ok: deviceId is an exact 12-char short id and more than one match is refused below.
346
+ if (matches.length > 1) {
347
+ throw new Error(`Device prefix "${deviceId}" matches ${matches.length} effects on track "${track?.name ?? ""}"; use a full effect id.`);
348
+ }
349
+ if (matches.length === 1)
350
+ return matches[0].id;
351
+ }
352
+ return deviceId;
353
+ }
354
+ /** Enforce SQ4 / SQ19 row assignment restrictions. */
355
+ function assertAssignmentAllowed(assignment, pattern, instrument) {
356
+ if (assignment.type === "degree" && pattern.pitchSource !== "chords") {
357
+ throw new Error('Degree rows require pattern pitchSource "chords" (call set_pattern with pitchSource: "chords" first).');
358
+ }
359
+ if (assignment.type === "kit" &&
360
+ instrument?.type !== "drum" &&
361
+ instrument?.type !== "sampler") {
362
+ throw new Error(`Kit rows require a DR-1 drum or Sampler track (this track uses ${instrument?.type ?? "no"} instrument).`);
363
+ }
364
+ }
365
+ function resolveRowAssignmentInput(input, instrument, track) {
366
+ if (input.assignment) {
367
+ const cloned = structuredClone(input.assignment);
368
+ if (cloned.type === "automation" && cloned.target.kind === "device") {
369
+ cloned.target.deviceId = resolveDeviceId(cloned.target.deviceId, track);
370
+ }
371
+ return { assignment: cloned };
372
+ }
373
+ if (input.pad !== undefined) {
374
+ if (typeof input.pad === "number") {
375
+ return { assignment: { type: "kit", pad: clampInt(input.pad, 0, 15) } };
376
+ }
377
+ const lower = input.pad.trim().toLowerCase();
378
+ if (instrument?.type === "drum") {
379
+ const idx = instrument.pads.findIndex((p) => p.name.toLowerCase() === lower);
380
+ if (idx >= 0) {
381
+ return {
382
+ assignment: { type: "kit", pad: idx },
383
+ defaultName: instrument.pads[idx].name
384
+ };
385
+ }
386
+ throw new Error(`No drum pad named "${input.pad}". Valid pads: ${instrument.pads
387
+ .map((p, i) => `${i} ("${p.name}")`)
388
+ .join(", ")}.`);
389
+ }
390
+ if (instrument?.type === "sampler") {
391
+ const idx = instrument.zones.findIndex((z) => z.name.toLowerCase() === lower);
392
+ if (idx >= 0 && idx < 16) {
393
+ return {
394
+ assignment: { type: "kit", pad: idx },
395
+ defaultName: instrument.zones[idx].name
396
+ };
397
+ }
398
+ }
399
+ const inferred = assignmentFromRowName(input.pad, instrument);
400
+ return { assignment: inferred.assignment, defaultName: inferred.customName ?? input.pad };
401
+ }
402
+ if (input.pitch !== undefined) {
403
+ const pitch = typeof input.pitch === "number"
404
+ ? clampInt(input.pitch, 0, 127)
405
+ : parseStepNoteName(input.pitch);
406
+ if (pitch === undefined) {
407
+ throw new Error(`Invalid pitch "${String(input.pitch)}". Pass an integer 0..127 or a note name like "C3".`);
408
+ }
409
+ return { assignment: { type: "note", pitch } };
410
+ }
411
+ if (input.degree !== undefined) {
412
+ const degree = typeof input.degree === "number"
413
+ ? STEP_DEGREES[clampInt(input.degree, 0, STEP_DEGREES.length - 1)]
414
+ : input.degree;
415
+ const octave = input.octave !== undefined ? clampInt(input.octave, -2, 8) : 3;
416
+ return { assignment: { type: "degree", degree, octave } };
417
+ }
418
+ if (input.cc !== undefined) {
419
+ return {
420
+ assignment: {
421
+ type: "automation",
422
+ target: { kind: "cc", cc: clampInt(input.cc, 0, 127) }
423
+ }
424
+ };
425
+ }
426
+ if (input.param !== undefined) {
427
+ const lower = input.param.trim().toLowerCase();
428
+ if (lower === "pitchbend" || lower === "pitch bend") {
429
+ return { assignment: { type: "automation", target: { kind: "pitchBend" } } };
430
+ }
431
+ if (lower === "channelpressure" || lower === "channel pressure") {
432
+ return {
433
+ assignment: { type: "automation", target: { kind: "channelPressure" } }
434
+ };
435
+ }
436
+ return {
437
+ assignment: {
438
+ type: "automation",
439
+ target: {
440
+ kind: "device",
441
+ deviceId: resolveDeviceId(input.deviceId, track),
442
+ param: input.param
443
+ }
444
+ }
445
+ };
446
+ }
447
+ if (input.name) {
448
+ const inferred = assignmentFromRowName(input.name, instrument);
449
+ return { assignment: inferred.assignment, defaultName: input.name };
450
+ }
451
+ throw new Error("Each row in add_pattern_rows needs one of: assignment, pitch, pad, degree, cc, param, or name.");
452
+ }
453
+ function advanceAssignment(assignment, instrument) {
454
+ switch (assignment.type) {
455
+ case "note":
456
+ return { type: "note", pitch: Math.min(127, assignment.pitch + 1) };
457
+ case "melodic":
458
+ return { type: "melodic", pitch: Math.min(127, assignment.pitch + 1) };
459
+ case "kit": {
460
+ const maxPad = instrument?.type === "drum"
461
+ ? Math.max(0, instrument.pads.length - 1)
462
+ : instrument?.type === "sampler"
463
+ ? Math.max(0, Math.min(15, instrument.zones.length - 1))
464
+ : 15;
465
+ return { type: "kit", pad: Math.min(maxPad, assignment.pad + 1) };
466
+ }
467
+ case "degree": {
468
+ const idx = STEP_DEGREES.indexOf(assignment.degree);
469
+ const nextIdx = (idx + 1) % STEP_DEGREES.length;
470
+ const nextOct = nextIdx === 0 ? Math.min(8, assignment.octave + 1) : assignment.octave;
471
+ return { type: "degree", degree: STEP_DEGREES[nextIdx], octave: nextOct };
472
+ }
473
+ case "automation":
474
+ if (assignment.target.kind === "cc") {
475
+ return {
476
+ type: "automation",
477
+ target: { kind: "cc", cc: Math.min(127, assignment.target.cc + 1) }
478
+ };
479
+ }
480
+ return structuredClone(assignment);
481
+ }
482
+ }
483
+ function assertUniqueSubrows(subrows) {
484
+ if (!subrows)
485
+ return;
486
+ const seen = new Set();
487
+ for (const mode of subrows) {
488
+ if (seen.has(mode)) {
489
+ throw new Error(`Duplicate subrow mode "${mode}". Two subrows on the same row cannot share an edit mode.`);
490
+ }
491
+ seen.add(mode);
492
+ }
493
+ }
494
+ function validateLoopBounds1Based(loopStart1, loopEnd1, lengthSteps, currentStart0, currentEndExcl) {
495
+ const nextStart0 = loopStart1 !== undefined ? loopStart1 - 1 : currentStart0;
496
+ const nextEndExcl = loopEnd1 !== undefined ? loopEnd1 : currentEndExcl;
497
+ if (nextStart0 < 0 || nextStart0 >= lengthSteps) {
498
+ throw new Error(`loopStart must be between 1 and ${lengthSteps}.`);
499
+ }
500
+ if (nextEndExcl < 1 || nextEndExcl > lengthSteps) {
501
+ throw new Error(`loopEnd must be between 1 and ${lengthSteps}.`);
502
+ }
503
+ if (nextStart0 >= nextEndExcl) {
504
+ throw new Error(`loopStart (${nextStart0 + 1}) must be <= loopEnd (${nextEndExcl}).`);
505
+ }
506
+ return { loopStart: nextStart0, loopEnd: nextEndExcl };
507
+ }
508
+ function applyPatternTextToPattern(base, text, mode, instrument) {
509
+ const lines = parsePatternTextLines(text);
510
+ if (lines.length === 0) {
511
+ throw new Error('Pattern text contained no rows. Format each line as "<Row> [| rate] : <steps>", e.g. "Kick: x... x... x... x...".');
512
+ }
513
+ if (mode === "replace") {
514
+ const parsed = patternFromText(text, {
515
+ name: base.name,
516
+ seed: base.seed,
517
+ stepRate: base.stepRate,
518
+ instrument
519
+ });
520
+ return normalizePattern({
521
+ ...base,
522
+ lengthSteps: parsed.lengthSteps,
523
+ rows: parsed.rows
524
+ });
525
+ }
526
+ let pattern = structuredClone(base);
527
+ const maxLineLen = Math.max(...lines.map((l) => l.steps.length));
528
+ if (maxLineLen > pattern.lengthSteps) {
529
+ pattern = resizePatternLength(pattern, Math.min(STEP_PATTERN_MAX_STEPS, maxLineLen));
530
+ }
531
+ for (const line of lines) {
532
+ const lower = line.name.trim().toLowerCase();
533
+ const existingIdx = pattern.rows.findIndex((r) => rowLabel(r, instrument).toLowerCase() === lower ||
534
+ r.name?.trim().toLowerCase() === lower);
535
+ if (existingIdx >= 0) {
536
+ const existing = pattern.rows[existingIdx];
537
+ const nextLen = line.steps.length;
538
+ const updatedRow = normalizeRow({
539
+ ...existing,
540
+ lengthSteps: nextLen,
541
+ loopStart: Math.min(existing.loopStart, nextLen - 1),
542
+ loopEnd: existing.loopEnd === existing.lengthSteps ? nextLen : Math.min(existing.loopEnd, nextLen),
543
+ stepRate: line.stepRate ?? existing.stepRate,
544
+ steps: line.steps
545
+ }, pattern);
546
+ pattern.rows[existingIdx] = updatedRow;
547
+ if (pattern.mono && isNoteRow(updatedRow)) {
548
+ const turnedOn = updatedRow.steps
549
+ .map((s, i) => (s.on ? i : -1))
550
+ .filter((i) => i >= 0);
551
+ pattern = applyMonoAtSteps(pattern, updatedRow.id, turnedOn);
552
+ }
553
+ }
554
+ else {
555
+ if (pattern.rows.length >= STEP_PATTERN_MAX_ROWS) {
556
+ throw new Error(`Cannot add row "${line.name}": a pattern holds at most ${STEP_PATTERN_MAX_ROWS} rows.`);
557
+ }
558
+ const inferred = assignmentFromRowName(line.name, instrument);
559
+ const id = mintRowId(pattern);
560
+ pattern = addPatternRow(pattern, {
561
+ id,
562
+ name: inferred.customName ?? line.name,
563
+ assignment: inferred.assignment,
564
+ lengthSteps: line.steps.length,
565
+ loopStart: 0,
566
+ loopEnd: line.steps.length,
567
+ stepRate: line.stepRate ?? pattern.stepRate,
568
+ steps: line.steps
569
+ }, instrument);
570
+ const added = pattern.rows.find((r) => r.id === id);
571
+ if (pattern.mono && added && isNoteRow(added)) {
572
+ const turnedOn = added.steps
573
+ .map((s, i) => (s.on ? i : -1))
574
+ .filter((i) => i >= 0);
575
+ pattern = applyMonoAtSteps(pattern, added.id, turnedOn);
576
+ }
577
+ }
578
+ }
579
+ return pattern;
580
+ }
581
+ /** All 27 Step Sequencer op handlers, keyed by op name. */
582
+ export const STEP_PATTERN_OP_HANDLERS = {
583
+ // ── SQ48: Read ────────────────────────────────────────────────────────────
584
+ get_pattern: (scope, op) => {
585
+ const { clip, pattern, instrument } = resolvePatternClip(scope, op.clipId);
586
+ return {
587
+ ok: true,
588
+ clipId: clip.id,
589
+ name: clip.name,
590
+ summary: patternSummary(pattern),
591
+ settings: serializePatternSettings(pattern),
592
+ text: patternToText(pattern, instrument),
593
+ rows: pattern.rows.map((row) => serializePatternRow(row, instrument, op.modes))
594
+ };
595
+ },
596
+ // ── SQ49: Create & convert ────────────────────────────────────────────────
597
+ create_pattern_region: async (scope, op) => {
598
+ const track = scope.resolveMidiTrack(op.trackId);
599
+ scope.assertWritable([], track.id);
600
+ scope.state.tempo ??= structuredClone(DEFAULT_TEMPO);
601
+ const tempo = resolveTempo(scope.state);
602
+ const startMs = resolveBarTime(scope.state, op, op.atMs, "atMs") ??
603
+ scope.trackEndMs(track.id);
604
+ const bars = op.bars ?? 1;
605
+ const durationMs = Math.max(1, Math.round(bars * barDurationMs(tempo)));
606
+ const clipId = scope.ctx.newId("clip");
607
+ const seed = seedForClipId(clipId);
608
+ let pattern;
609
+ if (op.template !== undefined) {
610
+ if (op.template.trim().toLowerCase() === "track default") {
611
+ pattern = track.stepTemplate
612
+ ? normalizePattern({ ...structuredClone(track.stepTemplate), seed })
613
+ : normalizePattern({
614
+ name: op.name ?? "Pattern",
615
+ seed,
616
+ rows: defaultRowsForTrack(track)
617
+ });
618
+ }
619
+ else {
620
+ const entry = await resolveLibraryPattern(scope, op.template);
621
+ pattern = normalizePattern({
622
+ ...entry.pattern,
623
+ seed
624
+ });
625
+ }
626
+ if (op.text !== undefined) {
627
+ pattern = applyPatternTextToPattern(pattern, op.text, "merge", track.instrument);
628
+ }
629
+ }
630
+ else if (op.text !== undefined) {
631
+ pattern = patternFromText(op.text, {
632
+ name: op.name ?? "Pattern",
633
+ seed,
634
+ instrument: track.instrument
635
+ });
636
+ }
637
+ else if (track.stepTemplate) {
638
+ pattern = normalizePattern({
639
+ ...structuredClone(track.stepTemplate),
640
+ name: op.name || track.stepTemplate.name,
641
+ seed
642
+ });
643
+ }
644
+ else {
645
+ pattern = normalizePattern({
646
+ name: op.name ?? "Pattern",
647
+ seed,
648
+ rows: defaultRowsForTrack(track)
649
+ });
650
+ }
651
+ if (op.name) {
652
+ pattern.name = op.name;
653
+ }
654
+ const clip = makeClip({
655
+ id: clipId,
656
+ trackId: track.id,
657
+ name: op.name ?? pattern.name,
658
+ startMs,
659
+ durationMs,
660
+ mediaType: "midi",
661
+ sourceType: "imported",
662
+ status: "generated",
663
+ pattern
664
+ });
665
+ scope.clips.push(clip);
666
+ scope.state.selectedClipIds = [clip.id];
667
+ scope.touch(clip.id);
668
+ return {
669
+ ok: true,
670
+ clip: scope.clipOut(clip),
671
+ pattern: patternSummary(pattern),
672
+ text: patternToText(pattern, track.instrument)
673
+ };
674
+ },
675
+ convert_pattern_to_midi: (scope, op) => {
676
+ const tempo = resolveTempo(scope.state);
677
+ const chords = chordsOf(scope);
678
+ const targets = op.clipIds.map((id) => resolvePatternClip(scope, id));
679
+ scope.assertWritable(targets.map((t) => t.clip));
680
+ const converted = [];
681
+ for (const { clip, pattern, instrument } of targets) {
682
+ const loopMs = activeLoopMs(clip);
683
+ const inPointTicks = Math.max(0, Math.round(msToTicks(clip.inPointMs ?? 0, tempo.bpm)));
684
+ const phaseTicks = (clip.patternPhaseTicks ?? 0) + inPointTicks;
685
+ const repeatVaries = loopMs !== undefined &&
686
+ (phaseTicks > 0 ||
687
+ pattern.pitchSource === "chords" ||
688
+ pattern.rows.some((r) => r.playback === "shuffle" ||
689
+ r.playback === "random" ||
690
+ r.playback === "wander" ||
691
+ r.steps.some((s) => (s.chance !== undefined && s.chance < 100) ||
692
+ (s.condition !== undefined && s.condition.type !== "always"))));
693
+ const expandDurMs = repeatVaries ? clip.durationMs : (loopMs ?? clip.durationMs);
694
+ const clipLengthTicks = Math.max(1, Math.round(msToTicks(expandDurMs, tempo.bpm)));
695
+ const loopLengthTicks = repeatVaries && loopMs !== undefined
696
+ ? Math.max(1, Math.round(msToTicks(loopMs, tempo.bpm)))
697
+ : undefined;
698
+ const expanded = expandPattern(pattern, {
699
+ clipLengthTicks,
700
+ loopLengthTicks,
701
+ patternPhaseTicks: phaseTicks,
702
+ rowCycles: clip.patternRowCycles,
703
+ instrument,
704
+ chords,
705
+ key: projectKeyToStepKey(tempo),
706
+ clipStartDocTick: Math.round(msToTicks(clip.startMs - tempo.offsetMs, tempo.bpm))
707
+ });
708
+ if (expanded.deviceAutomation.length > 0) {
709
+ const track = scope.tracks.find((t) => t.id === clip.trackId);
710
+ if (track) {
711
+ track.automation = deriveTrackAutomationFromPatterns(track, [clip], {
712
+ tracks: scope.tracks,
713
+ tempo
714
+ });
715
+ }
716
+ }
717
+ delete clip.pattern;
718
+ delete clip.patternPhaseTicks;
719
+ delete clip.patternRowCycles;
720
+ if (repeatVaries) {
721
+ delete clip.loopLengthMs;
722
+ }
723
+ clip.inPointMs = 0;
724
+ if (clip.outPointMs !== undefined) {
725
+ clip.outPointMs = repeatVaries ? clip.durationMs : (loopMs ?? clip.durationMs);
726
+ }
727
+ clip.notes = expanded.notes;
728
+ if (expanded.controllers.length > 0) {
729
+ clip.controllers = expanded.controllers;
730
+ }
731
+ else {
732
+ delete clip.controllers;
733
+ }
734
+ scope.touch(clip.id);
735
+ converted.push(scope.clipOut(clip));
736
+ }
737
+ return {
738
+ ok: true,
739
+ clips: converted
740
+ };
741
+ },
742
+ convert_midi_to_pattern: (scope, op) => {
743
+ const tempo = resolveTempo(scope.state);
744
+ const clips = op.clipIds.map((id) => scope.resolveMidiClip(id));
745
+ scope.assertWritable(clips);
746
+ for (const clip of clips) {
747
+ if (clip.pattern) {
748
+ throw new Error(`Clip "${clip.name}" is already a step sequencer pattern region.`);
749
+ }
750
+ }
751
+ let droppedNotes = 0;
752
+ let collisions = 0;
753
+ const conversions = [];
754
+ for (const clip of clips) {
755
+ const instrument = trackInstrumentOf(scope, clip);
756
+ const windowStartTick = Math.max(0, Math.round(msToTicks(clip.inPointMs ?? 0, tempo.bpm)));
757
+ const clipLengthTicks = Math.max(1, Math.round(msToTicks(activeLoopMs(clip) ?? clip.durationMs, tempo.bpm)));
758
+ const res = midiToPattern(clip.notes ?? [], clip.controllers ?? [], {
759
+ clipLengthTicks,
760
+ windowStartTick,
761
+ stepRate: op.stepRate,
762
+ instrument,
763
+ seed: seedForClipId(clip.id),
764
+ name: clip.name
765
+ });
766
+ delete clip.notes;
767
+ delete clip.controllers;
768
+ delete clip.patternPhaseTicks;
769
+ clip.inPointMs = 0;
770
+ clip.pattern = res.pattern;
771
+ scope.touch(clip.id);
772
+ droppedNotes += res.droppedNotes;
773
+ collisions += res.mergedCollisions;
774
+ conversions.push({
775
+ clipId: clip.id,
776
+ droppedNotes: res.droppedNotes,
777
+ collisions: res.mergedCollisions,
778
+ stepRate: res.pattern.stepRate,
779
+ lengthSteps: res.pattern.lengthSteps,
780
+ rowCount: res.pattern.rows.length
781
+ });
782
+ }
783
+ return {
784
+ ok: true,
785
+ droppedNotes,
786
+ collisions,
787
+ conversions,
788
+ clips: clips.map((c) => scope.clipOut(c))
789
+ };
790
+ },
791
+ separate_pattern_rows: (scope, op) => {
792
+ const { clip, pattern, instrument } = resolvePatternClip(scope, op.clipId);
793
+ scope.assertWritable([clip]);
794
+ if (pattern.rows.length === 0) {
795
+ throw new Error(`Pattern "${clip.name}" has no rows to separate.`);
796
+ }
797
+ const srcTrackIdx = scope.tracks.findIndex((t) => t.id === clip.trackId);
798
+ const srcTrack = scope.tracks[srcTrackIdx];
799
+ if (!srcTrack) {
800
+ throw new Error(`Source track "${clip.trackId}" not found.`);
801
+ }
802
+ const anySolo = pattern.rows.some((r) => r.solo);
803
+ const newTracks = [];
804
+ const newClips = [];
805
+ for (const row of pattern.rows) {
806
+ const name = rowLabel(row, instrument);
807
+ const trackId = scope.ctx.newId("track");
808
+ const newTrack = makeTrack({
809
+ id: trackId,
810
+ type: "midi",
811
+ name,
812
+ index: 0,
813
+ instrument: srcTrack.instrument
814
+ ? structuredClone(srcTrack.instrument)
815
+ : undefined,
816
+ volumeDb: srcTrack.volumeDb,
817
+ pan: srcTrack.pan,
818
+ effects: srcTrack.effects ? structuredClone(srcTrack.effects) : undefined,
819
+ folderId: srcTrack.folderId,
820
+ musicRole: srcTrack.musicRole
821
+ });
822
+ const clonedRow = structuredClone(row);
823
+ // Preserve mix when solo was active on the source pattern (SQ22).
824
+ if (anySolo) {
825
+ clonedRow.mute = !row.solo;
826
+ clonedRow.solo = false;
827
+ }
828
+ const oneRowPattern = {
829
+ ...structuredClone(pattern),
830
+ name,
831
+ rows: [clonedRow]
832
+ };
833
+ const newClip = makeClip({
834
+ id: scope.ctx.newId("clip"),
835
+ trackId,
836
+ name,
837
+ startMs: clip.startMs,
838
+ durationMs: clip.durationMs,
839
+ mediaType: "midi",
840
+ sourceType: clip.sourceType,
841
+ status: clip.status,
842
+ loopLengthMs: clip.loopLengthMs,
843
+ transpose: clip.transpose,
844
+ velocityOffset: clip.velocityOffset,
845
+ quantize: clip.quantize ? structuredClone(clip.quantize) : undefined,
846
+ harmony: clip.harmony ? structuredClone(clip.harmony) : undefined,
847
+ pattern: oneRowPattern,
848
+ patternPhaseTicks: clip.patternPhaseTicks,
849
+ patternRowCycles: clip.patternRowCycles?.[row.id]
850
+ ? { [row.id]: structuredClone(clip.patternRowCycles[row.id]) }
851
+ : undefined
852
+ });
853
+ newTracks.push(newTrack);
854
+ newClips.push(newClip);
855
+ }
856
+ // Insert new tracks immediately beneath the source track and re-index.
857
+ scope.tracks.splice(srcTrackIdx + 1, 0, ...newTracks);
858
+ scope.tracks.forEach((t, i) => {
859
+ t.index = i;
860
+ });
861
+ // Replace source clip with the separated clips.
862
+ scope.clips = scope.clips.filter((c) => c.id !== clip.id);
863
+ scope.clips.push(...newClips);
864
+ scope.state.selectedClipIds = newClips.map((c) => c.id);
865
+ scope.touch(clip.id, ...newClips.map((c) => c.id));
866
+ return {
867
+ ok: true,
868
+ removedClipId: clip.id,
869
+ tracks: newTracks.map((t) => scope.trackOut(t)),
870
+ clips: newClips.map((c) => scope.clipOut(c))
871
+ };
872
+ },
873
+ // ── SQ50: Pattern settings ────────────────────────────────────────────────
874
+ set_pattern: (scope, op) => {
875
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
876
+ scope.assertWritable([clip]);
877
+ let pattern = structuredClone(clip.pattern);
878
+ if (op.name !== undefined)
879
+ pattern.name = op.name;
880
+ if (op.lengthSteps !== undefined) {
881
+ pattern = resizePatternLength(pattern, op.lengthSteps);
882
+ }
883
+ if (op.stepRate !== undefined) {
884
+ pattern = setPatternStepRate(pattern, op.stepRate);
885
+ }
886
+ if (op.playback !== undefined) {
887
+ pattern = setPatternPlayback(pattern, op.playback);
888
+ }
889
+ if (op.swing !== undefined)
890
+ pattern.swing = clampInt(op.swing, 0, 100);
891
+ if (op.swingDivision !== undefined)
892
+ pattern.swingDivision = op.swingDivision;
893
+ if (op.legato !== undefined)
894
+ pattern.legato = op.legato;
895
+ if (op.mono !== undefined)
896
+ pattern.mono = op.mono;
897
+ if (op.midiChannel !== undefined) {
898
+ pattern = setPatternMidiChannel(pattern, op.midiChannel);
899
+ }
900
+ if (op.pitchSource !== undefined)
901
+ pattern.pitchSource = op.pitchSource;
902
+ if (op.scale !== undefined)
903
+ pattern.scale = op.scale;
904
+ if (op.scaleQuantize !== undefined)
905
+ pattern.scaleQuantize = op.scaleQuantize;
906
+ if (op.noTranspose !== undefined)
907
+ pattern.noTranspose = op.noTranspose;
908
+ if (op.key !== undefined) {
909
+ if (op.key === null) {
910
+ delete pattern.key;
911
+ }
912
+ else {
913
+ pattern = setPatternKey(pattern, op.key);
914
+ }
915
+ }
916
+ if (op.automationMode !== undefined) {
917
+ pattern = setPatternAutomationMode(pattern, op.automationMode);
918
+ }
919
+ if (op.loopStart !== undefined || op.loopEnd !== undefined) {
920
+ const start0 = op.loopStart !== undefined ? op.loopStart - 1 : undefined;
921
+ const endExcl = op.loopEnd !== undefined ? op.loopEnd : undefined;
922
+ if (start0 !== undefined && endExcl !== undefined && start0 >= endExcl) {
923
+ throw new Error(`loopStart (${op.loopStart}) must be <= loopEnd (${op.loopEnd}).`);
924
+ }
925
+ pattern = setPatternLoop(pattern, start0, endExcl);
926
+ }
927
+ clip.pattern = pattern;
928
+ scope.touch(clip.id);
929
+ return {
930
+ ok: true,
931
+ clip: scope.clipOut(clip),
932
+ settings: serializePatternSettings(pattern),
933
+ text: patternToText(pattern, instrument)
934
+ };
935
+ },
936
+ set_pattern_seed: (scope, op) => {
937
+ const { clip } = resolvePatternClip(scope, op.clipId);
938
+ scope.assertWritable([clip]);
939
+ const seed = op.seed !== undefined
940
+ ? op.seed >>> 0
941
+ : nextPatternSeed(clip.id, clip.pattern.seed);
942
+ clip.pattern.seed = seed;
943
+ scope.touch(clip.id);
944
+ return {
945
+ ok: true,
946
+ clipId: clip.id,
947
+ seed
948
+ };
949
+ },
950
+ // ── SQ51: Rows ────────────────────────────────────────────────────────────
951
+ add_pattern_rows: (scope, op) => {
952
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
953
+ scope.assertWritable([clip]);
954
+ const track = scope.tracks.find((t) => t.id === clip.trackId);
955
+ let pattern = structuredClone(clip.pattern);
956
+ if (pattern.rows.length + op.rows.length > STEP_PATTERN_MAX_ROWS) {
957
+ throw new Error(`Cannot add ${op.rows.length} row(s): pattern already has ${pattern.rows.length} rows and supports at most ${STEP_PATTERN_MAX_ROWS}.`);
958
+ }
959
+ const addedIds = [];
960
+ for (const rowInput of op.rows) {
961
+ assertUniqueSubrows(rowInput.subrows);
962
+ const resolved = resolveRowAssignmentInput(rowInput, instrument, track);
963
+ assertAssignmentAllowed(resolved.assignment, pattern, instrument);
964
+ const id = mintRowId(pattern);
965
+ let steps;
966
+ let lengthSteps = rowInput.lengthSteps ?? pattern.lengthSteps;
967
+ let stepRate = rowInput.stepRate ?? pattern.stepRate;
968
+ if (rowInput.text !== undefined) {
969
+ const lineText = rowInput.text.includes(":")
970
+ ? rowInput.text
971
+ : `${rowInput.name ?? resolved.defaultName ?? "Row"}: ${rowInput.text}`;
972
+ const parsed = parsePatternTextLines(lineText);
973
+ if (parsed[0]) {
974
+ steps = parsed[0].steps;
975
+ if (rowInput.lengthSteps === undefined) {
976
+ lengthSteps = parsed[0].steps.length;
977
+ }
978
+ if (rowInput.stepRate === undefined && parsed[0].stepRate) {
979
+ stepRate = parsed[0].stepRate;
980
+ }
981
+ }
982
+ }
983
+ if (lengthSteps > pattern.lengthSteps) {
984
+ throw new Error(`Row lengthSteps (${lengthSteps}) cannot exceed pattern lengthSteps (${pattern.lengthSteps}). Resize the pattern length first.`);
985
+ }
986
+ const loopBounds = validateLoopBounds1Based(rowInput.loopStart, rowInput.loopEnd, lengthSteps, 0, lengthSteps);
987
+ pattern = addPatternRow(pattern, {
988
+ id,
989
+ assignment: resolved.assignment,
990
+ name: rowInput.name ?? resolved.defaultName,
991
+ // normalizeRow leaves undefined color and subrowsExpanded off the row.
992
+ color: rowInput.color,
993
+ stepRate,
994
+ lengthSteps,
995
+ playback: rowInput.playback ?? pattern.playback,
996
+ mute: rowInput.mute ?? false,
997
+ solo: rowInput.solo ?? false,
998
+ loopStart: loopBounds.loopStart,
999
+ loopEnd: loopBounds.loopEnd,
1000
+ midiChannel: rowInput.midiChannel ?? pattern.midiChannel,
1001
+ automationMode: rowInput.automationMode ?? pattern.automationMode,
1002
+ subrowsExpanded: rowInput.subrowsExpanded,
1003
+ subrows: rowInput.subrows ?? defaultSubrowsForAssignment(resolved.assignment),
1004
+ steps
1005
+ }, instrument);
1006
+ addedIds.push(id);
1007
+ }
1008
+ clip.pattern = pattern;
1009
+ scope.touch(clip.id);
1010
+ return {
1011
+ ok: true,
1012
+ clipId: clip.id,
1013
+ addedRowIds: addedIds,
1014
+ rows: pattern.rows.map((r) => serializePatternRow(r, instrument))
1015
+ };
1016
+ },
1017
+ set_pattern_row: (scope, op) => {
1018
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1019
+ scope.assertWritable([clip]);
1020
+ const track = scope.tracks.find((t) => t.id === clip.trackId);
1021
+ const pattern = structuredClone(clip.pattern);
1022
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1023
+ assertUniqueSubrows(op.subrows);
1024
+ let next = structuredClone(row);
1025
+ if (op.lengthSteps !== undefined) {
1026
+ if (op.lengthSteps > pattern.lengthSteps) {
1027
+ throw new Error(`Row lengthSteps (${op.lengthSteps}) cannot exceed pattern lengthSteps (${pattern.lengthSteps}). Resize the pattern length first.`);
1028
+ }
1029
+ if (op.lengthSteps !== next.lengthSteps) {
1030
+ next = resizeRowLength(next, op.lengthSteps);
1031
+ }
1032
+ }
1033
+ if (op.name !== undefined)
1034
+ next.name = op.name;
1035
+ if (op.assignment !== undefined) {
1036
+ const nextAssign = structuredClone(op.assignment);
1037
+ if (nextAssign.type === "automation" && nextAssign.target.kind === "device") {
1038
+ nextAssign.target.deviceId = resolveDeviceId(nextAssign.target.deviceId, track);
1039
+ }
1040
+ assertAssignmentAllowed(nextAssign, pattern, instrument);
1041
+ next.assignment = nextAssign;
1042
+ }
1043
+ if (op.stepRate !== undefined) {
1044
+ stepRateTicks(op.stepRate);
1045
+ next.stepRate = op.stepRate;
1046
+ }
1047
+ if (op.playback !== undefined)
1048
+ next.playback = op.playback;
1049
+ if (op.mute !== undefined)
1050
+ next.mute = op.mute;
1051
+ if (op.solo !== undefined)
1052
+ next.solo = op.solo;
1053
+ if (op.midiChannel !== undefined) {
1054
+ next.midiChannel = clampInt(op.midiChannel, 1, 16);
1055
+ }
1056
+ if (op.automationMode !== undefined) {
1057
+ next.automationMode = op.automationMode;
1058
+ }
1059
+ if (op.color !== undefined) {
1060
+ if (op.color === null)
1061
+ delete next.color;
1062
+ else
1063
+ next.color = op.color;
1064
+ }
1065
+ if (op.subrowsExpanded !== undefined) {
1066
+ next.subrowsExpanded = op.subrowsExpanded;
1067
+ }
1068
+ if (op.subrows !== undefined) {
1069
+ next.subrows = [...op.subrows];
1070
+ }
1071
+ if (op.loopStart !== undefined || op.loopEnd !== undefined) {
1072
+ const bounds = validateLoopBounds1Based(op.loopStart, op.loopEnd, next.lengthSteps, next.loopStart, next.loopEnd);
1073
+ next.loopStart = bounds.loopStart;
1074
+ next.loopEnd = bounds.loopEnd;
1075
+ }
1076
+ pattern.rows[index] = next;
1077
+ clip.pattern = pattern;
1078
+ scope.touch(clip.id);
1079
+ return {
1080
+ ok: true,
1081
+ clipId: clip.id,
1082
+ row: serializePatternRow(next, instrument)
1083
+ };
1084
+ },
1085
+ remove_pattern_rows: (scope, op) => {
1086
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1087
+ scope.assertWritable([clip]);
1088
+ if (!op.unused && (!op.rows || op.rows.length === 0)) {
1089
+ throw new Error("remove_pattern_rows requires `rows` (row ids or names) or `unused: true`.");
1090
+ }
1091
+ const pattern = structuredClone(clip.pattern);
1092
+ const removeIds = new Set();
1093
+ if (op.rows) {
1094
+ for (const ref of op.rows) {
1095
+ removeIds.add(resolveRow(pattern, ref, instrument).row.id);
1096
+ }
1097
+ }
1098
+ if (op.unused) {
1099
+ for (const r of pattern.rows) {
1100
+ if (!r.steps.some((s) => s.on)) {
1101
+ removeIds.add(r.id);
1102
+ }
1103
+ }
1104
+ }
1105
+ const removedRowIds = pattern.rows
1106
+ .filter((r) => removeIds.has(r.id))
1107
+ .map((r) => r.id);
1108
+ pattern.rows = pattern.rows.filter((r) => !removeIds.has(r.id));
1109
+ clip.pattern = pattern;
1110
+ scope.touch(clip.id);
1111
+ return {
1112
+ ok: true,
1113
+ clipId: clip.id,
1114
+ removedRowIds,
1115
+ rows: pattern.rows.map((r) => serializePatternRow(r, instrument))
1116
+ };
1117
+ },
1118
+ move_pattern_row: (scope, op) => {
1119
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1120
+ scope.assertWritable([clip]);
1121
+ const pattern = structuredClone(clip.pattern);
1122
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1123
+ if (op.toIndex < 0 || op.toIndex >= pattern.rows.length) {
1124
+ throw new Error(`toIndex ${op.toIndex} is out of range. Valid indices are 0..${Math.max(0, pattern.rows.length - 1)}.`);
1125
+ }
1126
+ pattern.rows.splice(index, 1);
1127
+ pattern.rows.splice(op.toIndex, 0, row);
1128
+ delete pattern.rowSort;
1129
+ clip.pattern = pattern;
1130
+ scope.touch(clip.id);
1131
+ return {
1132
+ ok: true,
1133
+ clipId: clip.id,
1134
+ rows: pattern.rows.map((r) => serializePatternRow(r, instrument))
1135
+ };
1136
+ },
1137
+ sort_pattern_rows: (scope, op) => {
1138
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1139
+ scope.assertWritable([clip]);
1140
+ const sorted = sortPatternRows(clip.pattern, op.by, op.descending ?? false, instrument);
1141
+ clip.pattern = sorted;
1142
+ scope.touch(clip.id);
1143
+ return {
1144
+ ok: true,
1145
+ clipId: clip.id,
1146
+ rows: sorted.rows.map((r) => serializePatternRow(r, instrument))
1147
+ };
1148
+ },
1149
+ set_pattern_row_sort: (scope, op) => {
1150
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1151
+ scope.assertWritable([clip]);
1152
+ let pattern = structuredClone(clip.pattern);
1153
+ if (op.rowSort === "none") {
1154
+ delete pattern.rowSort;
1155
+ }
1156
+ else {
1157
+ pattern.rowSort = op.rowSort;
1158
+ pattern = applyPatternRowSort(pattern, instrument);
1159
+ }
1160
+ clip.pattern = pattern;
1161
+ scope.touch(clip.id);
1162
+ return {
1163
+ ok: true,
1164
+ clipId: clip.id,
1165
+ rowSort: pattern.rowSort ?? "none",
1166
+ rows: pattern.rows.map((r) => serializePatternRow(r, instrument))
1167
+ };
1168
+ },
1169
+ copy_pattern_row: (scope, op) => {
1170
+ const src = resolvePatternClip(scope, op.clipId);
1171
+ const dst = op.toClipId
1172
+ ? resolvePatternClip(scope, op.toClipId)
1173
+ : src;
1174
+ scope.assertWritable([dst.clip]);
1175
+ const { row: srcRow, index: srcIndex } = resolveRow(src.pattern, op.row, src.instrument);
1176
+ const dstPattern = structuredClone(dst.pattern);
1177
+ if (op.toRow !== undefined && !op.asNew && !op.nextAssignment) {
1178
+ const { row: dstRow, index: dstIndex } = resolveRow(dstPattern, op.toRow, dst.instrument);
1179
+ if (isNoteRow(srcRow) !== isNoteRow(dstRow)) {
1180
+ throw new Error(`Cannot copy ${srcRow.assignment.type} row "${rowLabel(srcRow, src.instrument)}" onto ${dstRow.assignment.type} row "${rowLabel(dstRow, dst.instrument)}": row types must match (note vs automation).`);
1181
+ }
1182
+ if (op.settingsOnly) {
1183
+ const targetLen = Math.min(srcRow.lengthSteps, dstPattern.lengthSteps);
1184
+ const loopEnd = Math.min(srcRow.loopEnd, targetLen);
1185
+ const loopStart = Math.min(srcRow.loopStart, loopEnd - 1);
1186
+ let updated = resizeRowLength(dstRow, targetLen);
1187
+ updated = {
1188
+ ...updated,
1189
+ stepRate: srcRow.stepRate,
1190
+ playback: srcRow.playback,
1191
+ mute: srcRow.mute,
1192
+ solo: srcRow.solo,
1193
+ loopStart,
1194
+ loopEnd,
1195
+ midiChannel: srcRow.midiChannel,
1196
+ automationMode: srcRow.automationMode,
1197
+ subrows: [...srcRow.subrows]
1198
+ };
1199
+ dstPattern.rows[dstIndex] = updated;
1200
+ }
1201
+ else {
1202
+ // SQ4 / SQ35 / SQ51: preserve target assignment & name when copying
1203
+ // onto an existing row, promoting a fixed `note` target to `melodic`
1204
+ // if melodic steps are copied into it, and clamping row length to
1205
+ // destination pattern length (SQ7).
1206
+ const fitted = srcRow.lengthSteps > dstPattern.lengthSteps
1207
+ ? resizeRowLength(srcRow, dstPattern.lengthSteps)
1208
+ : structuredClone(srcRow);
1209
+ const hasMelodicOffsets = fitted.steps.some((s) => s.note !== undefined || s.octave !== undefined);
1210
+ const nextAssignment = dstRow.assignment.type === "note" &&
1211
+ (srcRow.assignment.type === "melodic" || hasMelodicOffsets)
1212
+ ? { type: "melodic", pitch: dstRow.assignment.pitch }
1213
+ : structuredClone(dstRow.assignment);
1214
+ dstPattern.rows[dstIndex] = {
1215
+ ...fitted,
1216
+ id: dstRow.id,
1217
+ name: dstRow.name,
1218
+ assignment: nextAssignment
1219
+ };
1220
+ }
1221
+ dst.clip.pattern = dstPattern;
1222
+ scope.touch(dst.clip.id);
1223
+ return {
1224
+ ok: true,
1225
+ clipId: dst.clip.id,
1226
+ row: serializePatternRow(dstPattern.rows[dstIndex], dst.instrument)
1227
+ };
1228
+ }
1229
+ // Paste as a new row (asNew / nextAssignment / toRow omitted).
1230
+ if (dstPattern.rows.length >= STEP_PATTERN_MAX_ROWS) {
1231
+ throw new Error(`Cannot copy row: destination pattern already has ${STEP_PATTERN_MAX_ROWS} rows.`);
1232
+ }
1233
+ const newId = mintRowId(dstPattern);
1234
+ const cloned = srcRow.lengthSteps > dstPattern.lengthSteps
1235
+ ? resizeRowLength(srcRow, dstPattern.lengthSteps)
1236
+ : structuredClone(srcRow);
1237
+ cloned.id = newId;
1238
+ if (op.settingsOnly) {
1239
+ cloned.steps = Array.from({ length: cloned.lengthSteps }, () => ({}));
1240
+ }
1241
+ if (op.nextAssignment) {
1242
+ cloned.assignment = advanceAssignment(srcRow.assignment, dst.instrument);
1243
+ delete cloned.name;
1244
+ }
1245
+ assertAssignmentAllowed(cloned.assignment, dstPattern, dst.instrument);
1246
+ const insertAt = dst.clip.id === src.clip.id ? srcIndex + 1 : dstPattern.rows.length;
1247
+ dstPattern.rows.splice(insertAt, 0, cloned);
1248
+ dst.clip.pattern = dstPattern;
1249
+ scope.touch(dst.clip.id);
1250
+ return {
1251
+ ok: true,
1252
+ clipId: dst.clip.id,
1253
+ row: serializePatternRow(cloned, dst.instrument)
1254
+ };
1255
+ },
1256
+ // ── SQ52: Steps ───────────────────────────────────────────────────────────
1257
+ set_steps: (scope, op) => {
1258
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1259
+ scope.assertWritable([clip]);
1260
+ if (!op.values && !op.ramp) {
1261
+ throw new Error("set_steps requires `values` and/or `ramp`.");
1262
+ }
1263
+ let pattern = structuredClone(clip.pattern);
1264
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1265
+ const stepIndices = parseStepSelection(op.steps, row.lengthSteps);
1266
+ let updated = row;
1267
+ const turnedOn = [];
1268
+ stepIndices.forEach((stepIdx, pos) => {
1269
+ const patch = {};
1270
+ if (op.values) {
1271
+ for (const [k, v] of Object.entries(op.values)) {
1272
+ if (k === "stepRate" && v === null) {
1273
+ patch.stepRate = undefined;
1274
+ }
1275
+ else if (v !== undefined) {
1276
+ patch[k] = v;
1277
+ }
1278
+ }
1279
+ }
1280
+ if (op.ramp) {
1281
+ const isDeviceValue = op.ramp.field === "value" &&
1282
+ updated.assignment.type === "automation" &&
1283
+ updated.assignment.target.kind === "device";
1284
+ const raw = stepIndices.length <= 1
1285
+ ? op.ramp.from
1286
+ : op.ramp.from +
1287
+ ((op.ramp.to - op.ramp.from) * pos) / (stepIndices.length - 1);
1288
+ const val = isDeviceValue ? raw : Math.round(raw);
1289
+ patch[op.ramp.field] = val;
1290
+ }
1291
+ const keepOff = op.ramp?.leaveOff === true && op.values?.on !== true;
1292
+ // Handle explicit stepRate: null clearing inherited rate.
1293
+ if (op.values && op.values.stepRate === null) {
1294
+ const clearedSteps = [...updated.steps];
1295
+ const copy = { ...(clearedSteps[stepIdx] ?? {}) };
1296
+ delete copy.stepRate;
1297
+ clearedSteps[stepIdx] = compactStep(copy);
1298
+ updated = { ...updated, steps: clearedSteps };
1299
+ }
1300
+ updated = setStepValue(updated, stepIdx, patch, { keepOff });
1301
+ if (updated.steps[stepIdx]?.on) {
1302
+ turnedOn.push(stepIdx);
1303
+ }
1304
+ });
1305
+ pattern.rows[index] = updated;
1306
+ if (pattern.mono && turnedOn.length > 0) {
1307
+ pattern = applyMonoAtSteps(pattern, updated.id, turnedOn);
1308
+ }
1309
+ clip.pattern = pattern;
1310
+ scope.touch(clip.id);
1311
+ return {
1312
+ ok: true,
1313
+ clipId: clip.id,
1314
+ row: serializePatternRow(pattern.rows[index], instrument),
1315
+ editedSteps: stepIndices.map((i) => i + 1),
1316
+ text: patternToText(pattern, instrument)
1317
+ };
1318
+ },
1319
+ set_pattern_text: (scope, op) => {
1320
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1321
+ scope.assertWritable([clip]);
1322
+ const next = applyPatternTextToPattern(clip.pattern, op.text, op.mode ?? "merge", instrument);
1323
+ clip.pattern = next;
1324
+ scope.touch(clip.id);
1325
+ return {
1326
+ ok: true,
1327
+ clip: scope.clipOut(clip),
1328
+ pattern: patternSummary(next),
1329
+ text: patternToText(next, instrument)
1330
+ };
1331
+ },
1332
+ clear_pattern: (scope, op) => {
1333
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1334
+ scope.assertWritable([clip]);
1335
+ const pattern = structuredClone(clip.pattern);
1336
+ if (op.scope === "steps") {
1337
+ if (!op.row || op.steps === undefined) {
1338
+ throw new Error('clear_pattern with scope "steps" requires `row` and `steps`.');
1339
+ }
1340
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1341
+ const indices = parseStepSelection(op.steps, row.lengthSteps);
1342
+ pattern.rows[index] = clearRowSteps(row, indices, op.mode);
1343
+ }
1344
+ else if (op.scope === "row") {
1345
+ if (!op.row) {
1346
+ throw new Error('clear_pattern with scope "row" requires `row`.');
1347
+ }
1348
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1349
+ pattern.rows[index] = clearRowSteps(row, undefined, op.mode);
1350
+ }
1351
+ else {
1352
+ pattern.rows = pattern.rows.map((r) => {
1353
+ if (op.rowType === "note" && !isNoteRow(r))
1354
+ return r;
1355
+ if (op.rowType === "automation" && isNoteRow(r))
1356
+ return r;
1357
+ return clearRowSteps(r, undefined, op.mode);
1358
+ });
1359
+ }
1360
+ clip.pattern = pattern;
1361
+ scope.touch(clip.id);
1362
+ return {
1363
+ ok: true,
1364
+ clipId: clip.id,
1365
+ text: patternToText(pattern, instrument)
1366
+ };
1367
+ },
1368
+ copy_steps: (scope, op) => {
1369
+ const src = resolvePatternClip(scope, op.clipId);
1370
+ const dst = op.toClipId ? resolvePatternClip(scope, op.toClipId) : src;
1371
+ scope.assertWritable(op.cut && dst.clip.id !== src.clip.id ? [src.clip, dst.clip] : [dst.clip]);
1372
+ const srcPattern = structuredClone(src.pattern);
1373
+ const dstPattern = dst.clip.id === src.clip.id ? srcPattern : structuredClone(dst.pattern);
1374
+ const { row: srcRow, index: srcIdx } = resolveRow(srcPattern, op.row, src.instrument);
1375
+ const { row: dstRow, index: dstIdx } = resolveRow(dstPattern, op.toRow, dst.instrument);
1376
+ if (isNoteRow(srcRow) !== isNoteRow(dstRow)) {
1377
+ throw new Error(`Cannot paste steps from ${srcRow.assignment.type} row "${rowLabel(srcRow, src.instrument)}" to ${dstRow.assignment.type} row "${rowLabel(dstRow, dst.instrument)}": row types must match (note vs automation).`);
1378
+ }
1379
+ const srcIndices = parseStepSelection(op.steps, srcRow.lengthSteps);
1380
+ const dstStart = op.toStep - 1;
1381
+ if (dstStart < 0 || dstStart >= dstRow.lengthSteps) {
1382
+ throw new Error(`toStep ${op.toStep} is out of range. Valid steps are 1..${dstRow.lengthSteps}.`);
1383
+ }
1384
+ const base = srcIndices[0];
1385
+ const copied = srcIndices.map((idx) => structuredClone(srcRow.steps[idx] ?? {}));
1386
+ const prevTargetRates = srcIndices.map((idx) => {
1387
+ const targetIdx = dstStart + (idx - base);
1388
+ return targetIdx >= 0 && targetIdx < dstRow.lengthSteps
1389
+ ? dstRow.steps[targetIdx]?.stepRate
1390
+ : undefined;
1391
+ });
1392
+ // Clear source before writing destination so overlapping same-row cut+paste
1393
+ // does not erase the freshly pasted steps.
1394
+ if (op.cut) {
1395
+ srcPattern.rows[srcIdx] = clearRowSteps(srcPattern.rows[srcIdx], srcIndices);
1396
+ src.clip.pattern = srcPattern;
1397
+ scope.touch(src.clip.id);
1398
+ }
1399
+ const activeDstRow = dstPattern.rows[dstIdx];
1400
+ const nextDstSteps = [...activeDstRow.steps];
1401
+ const pastedOn = [];
1402
+ const pastedSteps1 = [];
1403
+ let pastedMelodic = false;
1404
+ srcIndices.forEach((idx, k) => {
1405
+ const targetIdx = dstStart + (idx - base);
1406
+ if (targetIdx < 0 || targetIdx >= activeDstRow.lengthSteps)
1407
+ return;
1408
+ const incoming = copied[k];
1409
+ if (incoming.note !== undefined || incoming.octave !== undefined) {
1410
+ pastedMelodic = true;
1411
+ }
1412
+ // SQ35 / D81: explicit source stepRate stays; unset source stepRate takes
1413
+ // the replaced step's explicit rate if any (else inherits target row rate).
1414
+ const prevTargetRate = prevTargetRates[k];
1415
+ if (incoming.stepRate === undefined && prevTargetRate !== undefined) {
1416
+ incoming.stepRate = prevTargetRate;
1417
+ }
1418
+ nextDstSteps[targetIdx] = compactStep(incoming);
1419
+ pastedSteps1.push(targetIdx + 1);
1420
+ if (nextDstSteps[targetIdx].on)
1421
+ pastedOn.push(targetIdx);
1422
+ });
1423
+ const nextDstAssignment = pastedMelodic && activeDstRow.assignment.type === "note"
1424
+ ? { type: "melodic", pitch: activeDstRow.assignment.pitch }
1425
+ : activeDstRow.assignment;
1426
+ dstPattern.rows[dstIdx] = {
1427
+ ...activeDstRow,
1428
+ assignment: nextDstAssignment,
1429
+ steps: nextDstSteps
1430
+ };
1431
+ let finalDst = dstPattern;
1432
+ if (finalDst.mono && pastedOn.length > 0) {
1433
+ finalDst = applyMonoAtSteps(finalDst, activeDstRow.id, pastedOn);
1434
+ }
1435
+ dst.clip.pattern = finalDst;
1436
+ scope.touch(dst.clip.id);
1437
+ return {
1438
+ ok: true,
1439
+ clipId: dst.clip.id,
1440
+ pastedSteps: pastedSteps1,
1441
+ text: patternToText(finalDst, dst.instrument)
1442
+ };
1443
+ },
1444
+ repeat_step: (scope, op) => {
1445
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1446
+ scope.assertWritable([clip]);
1447
+ let pattern = structuredClone(clip.pattern);
1448
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1449
+ const idx = op.step - 1;
1450
+ if (idx < 0 || idx >= row.lengthSteps) {
1451
+ throw new Error(`Step ${op.step} is out of range. Valid steps are 1..${row.lengthSteps}.`);
1452
+ }
1453
+ if (idx + 1 >= row.lengthSteps) {
1454
+ throw new Error(`Step ${op.step} is the last step of row "${rowLabel(row, instrument)}" (length ${row.lengthSteps}); there is no following step to repeat into.`);
1455
+ }
1456
+ const nextSteps = [...row.steps];
1457
+ nextSteps[idx + 1] = compactStep(structuredClone(row.steps[idx] ?? {}));
1458
+ pattern.rows[index] = { ...row, steps: nextSteps };
1459
+ if (pattern.mono && nextSteps[idx + 1].on) {
1460
+ pattern = applyMonoAtSteps(pattern, row.id, [idx + 1]);
1461
+ }
1462
+ clip.pattern = pattern;
1463
+ scope.touch(clip.id);
1464
+ return {
1465
+ ok: true,
1466
+ clipId: clip.id,
1467
+ repeatedToStep: op.step + 1,
1468
+ text: patternToText(pattern, instrument)
1469
+ };
1470
+ },
1471
+ // ── SQ53: Transforms ──────────────────────────────────────────────────────
1472
+ rotate_pattern: (scope, op) => {
1473
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1474
+ scope.assertWritable([clip]);
1475
+ const pattern = structuredClone(clip.pattern);
1476
+ if (op.row !== undefined) {
1477
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1478
+ pattern.rows[index] = rotateRowSteps(row, op.by, op.mode);
1479
+ }
1480
+ else {
1481
+ pattern.rows = pattern.rows.map((r) => rotateRowSteps(r, op.by, op.mode));
1482
+ }
1483
+ clip.pattern = pattern;
1484
+ scope.touch(clip.id);
1485
+ return {
1486
+ ok: true,
1487
+ clipId: clip.id,
1488
+ text: patternToText(pattern, instrument)
1489
+ };
1490
+ },
1491
+ transpose_pattern: (scope, op) => {
1492
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1493
+ scope.assertWritable([clip]);
1494
+ const pattern = structuredClone(clip.pattern);
1495
+ if (op.row !== undefined) {
1496
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1497
+ const stepIndices = op.steps !== undefined
1498
+ ? parseStepSelection(op.steps, row.lengthSteps)
1499
+ : undefined;
1500
+ pattern.rows[index] = transposeRowSteps(row, op.semitones, stepIndices, instrument);
1501
+ }
1502
+ else {
1503
+ pattern.rows = pattern.rows.map((r) => {
1504
+ const stepIndices = op.steps !== undefined
1505
+ ? parseStepSelection(op.steps, r.lengthSteps)
1506
+ : undefined;
1507
+ return transposeRowSteps(r, op.semitones, stepIndices, instrument);
1508
+ });
1509
+ }
1510
+ clip.pattern = pattern;
1511
+ scope.touch(clip.id);
1512
+ return {
1513
+ ok: true,
1514
+ clipId: clip.id,
1515
+ rows: pattern.rows.map((r) => serializePatternRow(r, instrument))
1516
+ };
1517
+ },
1518
+ randomize_pattern: (scope, op) => {
1519
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1520
+ scope.assertWritable([clip]);
1521
+ const pattern = structuredClone(clip.pattern);
1522
+ let rowIds;
1523
+ if (op.rows && op.rows.length > 0) {
1524
+ rowIds = new Set(op.rows.map((r) => resolveRow(pattern, r, instrument).row.id));
1525
+ }
1526
+ const maxLen = pattern.rows.length > 0
1527
+ ? Math.max(...pattern.rows.map((r) => r.lengthSteps))
1528
+ : pattern.lengthSteps;
1529
+ const stepIndices = op.steps !== undefined ? parseStepSelection(op.steps, maxLen) : undefined;
1530
+ const usedSeed = op.seed !== undefined
1531
+ ? op.seed >>> 0
1532
+ : fnv1a32Uints(pattern.seed >>> 0, rowKeyHash(clip.id), rowKeyHash(op.mode), Math.round(op.density ?? 50)) || 1;
1533
+ const next = randomizePatternSteps(pattern, op.mode, {
1534
+ rowIds,
1535
+ stepIndices,
1536
+ seed: usedSeed,
1537
+ density: op.density
1538
+ });
1539
+ clip.pattern = next;
1540
+ scope.touch(clip.id);
1541
+ return {
1542
+ ok: true,
1543
+ clipId: clip.id,
1544
+ seed: usedSeed,
1545
+ text: patternToText(next, instrument)
1546
+ };
1547
+ },
1548
+ nudge_pattern_values: (scope, op) => {
1549
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1550
+ scope.assertWritable([clip]);
1551
+ const pattern = structuredClone(clip.pattern);
1552
+ if (op.row !== undefined) {
1553
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1554
+ pattern.rows[index] = nudgeRowValues(row, op.mode, op.delta, instrument);
1555
+ }
1556
+ else {
1557
+ pattern.rows = pattern.rows.map((r) => nudgeRowValues(r, op.mode, op.delta, instrument));
1558
+ }
1559
+ clip.pattern = pattern;
1560
+ scope.touch(clip.id);
1561
+ return {
1562
+ ok: true,
1563
+ clipId: clip.id,
1564
+ text: patternToText(pattern, instrument)
1565
+ };
1566
+ },
1567
+ tie_steps: (scope, op) => {
1568
+ const { clip, instrument } = resolvePatternClip(scope, op.clipId);
1569
+ scope.assertWritable([clip]);
1570
+ const pattern = structuredClone(clip.pattern);
1571
+ const { row, index } = resolveRow(pattern, op.row, instrument);
1572
+ if (op.from < 1 || op.from > row.lengthSteps || op.to < 1 || op.to > row.lengthSteps) {
1573
+ throw new Error(`tie_steps range [${op.from}, ${op.to}] is outside 1..${row.lengthSteps}.`);
1574
+ }
1575
+ pattern.rows[index] = tieRowSteps(row, op.from - 1, op.to - 1, op.tie);
1576
+ clip.pattern = pattern;
1577
+ scope.touch(clip.id);
1578
+ return {
1579
+ ok: true,
1580
+ clipId: clip.id,
1581
+ text: patternToText(pattern, instrument)
1582
+ };
1583
+ },
1584
+ // ── SQ54, SQ43 & SQ45: Library, Folders & Track Template ──────────────────
1585
+ list_step_patterns: async (scope, op) => {
1586
+ const q = op.query?.trim().toLowerCase();
1587
+ const cat = op.category?.trim().toLowerCase();
1588
+ const rawUser = scope.ctx.stepPatternLibrary
1589
+ ? await scope.ctx.stepPatternLibrary.list()
1590
+ : [];
1591
+ const rawFolders = scope.ctx.stepPatternLibrary
1592
+ ?.listFolders
1593
+ ? await scope.ctx.stepPatternLibrary.listFolders()
1594
+ : collectStepPatternFolders([], rawUser);
1595
+ let folderFilter = null;
1596
+ if (op.folder !== undefined && op.folder.trim() !== "") {
1597
+ const trimmedFolder = op.folder.trim();
1598
+ const rootPattern = stepPatternRootFolder("pattern");
1599
+ const rootTemplate = stepPatternRootFolder("template");
1600
+ if (trimmedFolder.toLowerCase() === rootPattern.toLowerCase()) {
1601
+ folderFilter = { folder: rootPattern, kind: "pattern" };
1602
+ }
1603
+ else if (trimmedFolder.toLowerCase() === rootTemplate.toLowerCase()) {
1604
+ folderFilter = { folder: rootTemplate, kind: "template" };
1605
+ }
1606
+ else if (isShortResourceId(trimmedFolder) ||
1607
+ isFullResourceId(trimmedFolder)) {
1608
+ const resolved = resolveStepPatternFolderRef(rawFolders, trimmedFolder, op.kind);
1609
+ folderFilter = { folder: resolved.folder, kind: resolved.kind };
1610
+ }
1611
+ else {
1612
+ const existing = rawFolders.find((f) => (!op.kind || f.kind === op.kind) &&
1613
+ (f.folder.toLowerCase() === trimmedFolder.toLowerCase() ||
1614
+ f.folder.toLowerCase() ===
1615
+ normalizeStepPatternFolderPath(f.kind, trimmedFolder).toLowerCase()));
1616
+ if (existing) {
1617
+ folderFilter = { folder: existing.folder, kind: existing.kind };
1618
+ }
1619
+ else {
1620
+ const fallbackKind = op.kind ?? "pattern";
1621
+ folderFilter = {
1622
+ folder: normalizeStepPatternFolderPath(fallbackKind, trimmedFolder),
1623
+ kind: op.kind
1624
+ };
1625
+ }
1626
+ }
1627
+ }
1628
+ const factory = folderFilter
1629
+ ? []
1630
+ : listFactoryStepPatterns({
1631
+ query: op.query,
1632
+ kind: op.kind,
1633
+ category: op.category
1634
+ }).map((e) => {
1635
+ const item = {
1636
+ id: e.id,
1637
+ name: e.name,
1638
+ kind: e.kind,
1639
+ category: e.category,
1640
+ tags: [...e.tags],
1641
+ source: "factory"
1642
+ };
1643
+ return e.instrumentPreset ? { ...item, instrumentPreset: e.instrumentPreset } : item;
1644
+ });
1645
+ const user = rawUser
1646
+ .filter((e) => {
1647
+ if (op.kind && e.kind !== op.kind)
1648
+ return false;
1649
+ if (folderFilter) {
1650
+ if (folderFilter.kind && e.kind !== folderFilter.kind)
1651
+ return false;
1652
+ const entryFolder = normalizeStepPatternFolderPath(e.kind, e.folder);
1653
+ if (!isWithinStepPatternFolder(entryFolder, folderFilter.folder)) {
1654
+ return false;
1655
+ }
1656
+ }
1657
+ if (cat && (e.category ?? "user").toLowerCase() !== cat)
1658
+ return false;
1659
+ if (q) {
1660
+ const hay = [e.id, e.name, e.folder ?? "", ...(e.tags ?? [])]
1661
+ .join(" ")
1662
+ .toLowerCase();
1663
+ if (!hay.includes(q))
1664
+ return false;
1665
+ }
1666
+ return true;
1667
+ })
1668
+ .map((e) => {
1669
+ const item = {
1670
+ id: e.id,
1671
+ name: e.name,
1672
+ kind: e.kind,
1673
+ category: e.category ?? "user",
1674
+ tags: [...(e.tags ?? [])],
1675
+ folder: e.folder,
1676
+ source: "user"
1677
+ };
1678
+ return e.instrumentPreset ? { ...item, instrumentPreset: e.instrumentPreset } : item;
1679
+ });
1680
+ const folders = rawFolders
1681
+ .filter((f) => {
1682
+ if (op.kind && f.kind !== op.kind)
1683
+ return false;
1684
+ if (folderFilter) {
1685
+ if (folderFilter.kind && f.kind !== folderFilter.kind)
1686
+ return false;
1687
+ if (!isWithinStepPatternFolder(f.folder, folderFilter.folder)) {
1688
+ return false;
1689
+ }
1690
+ }
1691
+ if (q) {
1692
+ const hay = `${f.name} ${f.folder}`.toLowerCase();
1693
+ if (!hay.includes(q))
1694
+ return false;
1695
+ }
1696
+ return true;
1697
+ })
1698
+ .map((f) => {
1699
+ const listed = {
1700
+ name: f.name,
1701
+ kind: f.kind,
1702
+ folder: f.folder,
1703
+ parentFolder: f.parentFolder
1704
+ };
1705
+ return f.id !== undefined ? { id: f.id, ...listed } : listed;
1706
+ });
1707
+ return {
1708
+ ok: true,
1709
+ entries: [...user, ...factory],
1710
+ folders
1711
+ };
1712
+ },
1713
+ apply_step_pattern: async (scope, op) => {
1714
+ if (!op.clipId && !op.trackId) {
1715
+ throw new Error("apply_step_pattern requires either `clipId` (existing clip) or `trackId` (create a new pattern region).");
1716
+ }
1717
+ const entry = await resolveLibraryPattern(scope, op.pattern);
1718
+ const tempo = resolveTempo(scope.state);
1719
+ let loaded = normalizePattern(structuredClone(entry.pattern));
1720
+ if (op.useProjectKey) {
1721
+ const projKey = projectKeyToStepKey(tempo);
1722
+ if (projKey) {
1723
+ loaded = setPatternKey(loaded, projKey);
1724
+ }
1725
+ }
1726
+ if (op.clipId) {
1727
+ const clip = scope.resolveMidiClip(op.clipId);
1728
+ scope.assertWritable([clip]);
1729
+ if (!clip.pattern && (clip.notes?.length ?? 0) > 0) {
1730
+ throw new Error(`Clip "${clip.name}" already holds MIDI notes. Convert it with convert_midi_to_pattern or pass trackId to create a new pattern region.`);
1731
+ }
1732
+ loaded.seed = clip.pattern?.seed ?? seedForClipId(clip.id);
1733
+ delete clip.notes;
1734
+ delete clip.controllers;
1735
+ clip.pattern = loaded;
1736
+ scope.touch(clip.id);
1737
+ const instrument = trackInstrumentOf(scope, clip);
1738
+ return {
1739
+ ok: true,
1740
+ clip: scope.clipOut(clip),
1741
+ appliedPattern: entry.name,
1742
+ source: entry.source,
1743
+ text: patternToText(loaded, instrument)
1744
+ };
1745
+ }
1746
+ const track = scope.resolveMidiTrack(op.trackId);
1747
+ scope.assertWritable([], track.id);
1748
+ scope.state.tempo ??= structuredClone(DEFAULT_TEMPO);
1749
+ const hadClips = scope.clips.some((c) => c.trackId === track.id);
1750
+ let instrumentApplied = false;
1751
+ let appliedInstrumentPreset;
1752
+ if (!hadClips &&
1753
+ isDefaultOrUnsetTrackInstrument(track.instrument, scope.ctx.defaultMidiInstrument)) {
1754
+ const savedInstrument = resolveSavedPatternInstrument(entry);
1755
+ if (savedInstrument) {
1756
+ track.instrument = savedInstrument.instrument;
1757
+ instrumentApplied = true;
1758
+ appliedInstrumentPreset = savedInstrument.presetId;
1759
+ }
1760
+ }
1761
+ const startMs = resolveBarTime(scope.state, op, op.atMs, "atMs") ??
1762
+ scope.trackEndMs(track.id);
1763
+ const durationMs = Math.max(1, Math.round((op.bars ?? 1) * barDurationMs(resolveTempo(scope.state))));
1764
+ const clipId = scope.ctx.newId("clip");
1765
+ loaded.seed = seedForClipId(clipId);
1766
+ const clip = makeClip({
1767
+ id: clipId,
1768
+ trackId: track.id,
1769
+ name: entry.name,
1770
+ startMs,
1771
+ durationMs,
1772
+ mediaType: "midi",
1773
+ sourceType: "imported",
1774
+ status: "generated",
1775
+ pattern: loaded
1776
+ });
1777
+ scope.clips.push(clip);
1778
+ scope.state.selectedClipIds = [clip.id];
1779
+ scope.touch(clip.id);
1780
+ const result = {
1781
+ ok: true,
1782
+ clip: scope.clipOut(clip),
1783
+ appliedPattern: entry.name,
1784
+ source: entry.source,
1785
+ text: patternToText(loaded, track.instrument)
1786
+ };
1787
+ if (instrumentApplied) {
1788
+ result.track = scope.trackOut(track);
1789
+ result.instrumentApplied = true;
1790
+ if (appliedInstrumentPreset)
1791
+ result.instrumentPreset = appliedInstrumentPreset;
1792
+ }
1793
+ return result;
1794
+ },
1795
+ save_step_pattern: async (scope, op) => {
1796
+ const { clip, pattern, instrument } = resolvePatternClip(scope, op.clipId);
1797
+ const savedInstrument = instrument ? structuredClone(instrument) : undefined;
1798
+ const savedInstrumentPreset = savedInstrument
1799
+ ? presetIdForInstrument(savedInstrument)
1800
+ : undefined;
1801
+ const savedPattern = op.kind === "template"
1802
+ ? normalizePattern({ ...extractStepPatternTemplate(pattern), name: op.name })
1803
+ : normalizePattern({ ...structuredClone(pattern), name: op.name });
1804
+ let resolvedFolderArg = op.folder?.trim();
1805
+ if (resolvedFolderArg &&
1806
+ (isShortResourceId(resolvedFolderArg) || isFullResourceId(resolvedFolderArg)) &&
1807
+ scope.ctx.stepPatternLibrary?.listFolders) {
1808
+ const existingFolders = await scope.ctx.stepPatternLibrary.listFolders();
1809
+ resolvedFolderArg = resolveMoveDestinationFolder(existingFolders, op.kind, resolvedFolderArg);
1810
+ }
1811
+ const folder = normalizeStepPatternFolderPath(op.kind, resolvedFolderArg);
1812
+ if (scope.ctx.stepPatternLibrary) {
1813
+ const rootFolder = stepPatternRootFolder(op.kind);
1814
+ const sub = folder.length > rootFolder.length
1815
+ ? folder.slice(rootFolder.length + 1)
1816
+ : undefined;
1817
+ const entry = {
1818
+ name: op.name,
1819
+ kind: op.kind,
1820
+ folder: sub,
1821
+ pattern: savedPattern
1822
+ };
1823
+ if (savedInstrument)
1824
+ entry.instrument = savedInstrument;
1825
+ if (savedInstrumentPreset)
1826
+ entry.instrumentPreset = savedInstrumentPreset;
1827
+ const stored = await scope.ctx.stepPatternLibrary.save(entry);
1828
+ const saved = {
1829
+ ok: true,
1830
+ id: stored.id,
1831
+ name: op.name,
1832
+ kind: op.kind,
1833
+ folder: stored.folder || folder,
1834
+ assetId: stored.assetId,
1835
+ contentType: STEP_PATTERN_ASSET_CONTENT_TYPE,
1836
+ clipId: clip.id
1837
+ };
1838
+ if (savedInstrumentPreset)
1839
+ saved.instrumentPreset = savedInstrumentPreset;
1840
+ return saved;
1841
+ }
1842
+ const slug = op.name
1843
+ .toLowerCase()
1844
+ .replace(/[^a-z0-9]+/g, "-")
1845
+ .replace(/^-|-$/g, "");
1846
+ const result = {
1847
+ ok: true,
1848
+ id: `user:${op.kind}:${slug || "pattern"}`,
1849
+ name: op.name,
1850
+ kind: op.kind,
1851
+ folder,
1852
+ contentType: STEP_PATTERN_ASSET_CONTENT_TYPE,
1853
+ clipId: clip.id,
1854
+ pattern: savedPattern
1855
+ };
1856
+ if (savedInstrument)
1857
+ result.instrument = savedInstrument;
1858
+ if (savedInstrumentPreset)
1859
+ result.instrumentPreset = savedInstrumentPreset;
1860
+ return result;
1861
+ },
1862
+ set_track_step_template: (scope, op) => {
1863
+ const track = scope.resolveMidiTrack(op.trackId);
1864
+ scope.assertWritable([], track.id);
1865
+ if (op.clear) {
1866
+ delete track.stepTemplate;
1867
+ return {
1868
+ ok: true,
1869
+ track: scope.trackOut(track),
1870
+ cleared: true
1871
+ };
1872
+ }
1873
+ if (!op.fromClipId) {
1874
+ throw new Error("set_track_step_template requires `fromClipId` or `clear: true`.");
1875
+ }
1876
+ const { pattern } = resolvePatternClip(scope, op.fromClipId);
1877
+ const template = stripPatternSteps(pattern);
1878
+ track.stepTemplate = template;
1879
+ return {
1880
+ ok: true,
1881
+ track: scope.trackOut(track),
1882
+ rowCount: template.rows.length
1883
+ };
1884
+ },
1885
+ create_step_pattern_folder: async (scope, op) => {
1886
+ const library = scope.ctx.stepPatternLibrary;
1887
+ if (!library?.createFolder) {
1888
+ throw new Error("This session's step pattern library does not support folder operations.");
1889
+ }
1890
+ const created = await library.createFolder({
1891
+ name: op.name,
1892
+ kind: op.kind,
1893
+ parentFolder: op.parentFolder
1894
+ });
1895
+ return {
1896
+ ok: true,
1897
+ ...created
1898
+ };
1899
+ },
1900
+ rename_step_pattern_folder: async (scope, op) => {
1901
+ const library = scope.ctx.stepPatternLibrary;
1902
+ if (!library?.renameFolder) {
1903
+ throw new Error("This session's step pattern library does not support folder operations.");
1904
+ }
1905
+ const renamed = await library.renameFolder({
1906
+ folder: op.folder,
1907
+ newName: op.newName,
1908
+ kind: op.kind
1909
+ });
1910
+ return {
1911
+ ok: true,
1912
+ ...renamed
1913
+ };
1914
+ },
1915
+ delete_step_pattern_folder: async (scope, op) => {
1916
+ const library = scope.ctx.stepPatternLibrary;
1917
+ if (!library?.deleteFolder) {
1918
+ throw new Error("This session's step pattern library does not support folder operations.");
1919
+ }
1920
+ const deleted = await library.deleteFolder({
1921
+ folder: op.folder,
1922
+ kind: op.kind
1923
+ });
1924
+ return {
1925
+ ok: true,
1926
+ ...deleted
1927
+ };
1928
+ },
1929
+ move_step_pattern: async (scope, op) => {
1930
+ const library = scope.ctx.stepPatternLibrary;
1931
+ if (!library?.movePattern) {
1932
+ throw new Error("This session's step pattern library does not support moving patterns between folders.");
1933
+ }
1934
+ const moved = await library.movePattern({
1935
+ pattern: op.pattern,
1936
+ folder: op.folder
1937
+ });
1938
+ return {
1939
+ ok: true,
1940
+ ...moved
1941
+ };
1942
+ }
1943
+ };
1944
+ /** Create an in-memory user step pattern library (for tests and headless bridge parity). */
1945
+ export function createMemoryStepPatternLibrary(seed) {
1946
+ const entries = (seed?.entries ?? []).map((e) => structuredClone(e));
1947
+ const folderMarkers = (seed?.folders ?? []).map((f) => ({ ...f }));
1948
+ let patternSeq = 0;
1949
+ let folderSeq = 0;
1950
+ const mintPatternId = () => {
1951
+ for (;;) {
1952
+ const candidate = `${(++patternSeq).toString(16).padStart(8, "0")}a0a000000000000000000000`;
1953
+ if (!entries.some((e) => e.id === candidate))
1954
+ return candidate;
1955
+ }
1956
+ };
1957
+ const mintFolderId = () => {
1958
+ for (;;) {
1959
+ const candidate = `${(++folderSeq).toString(16).padStart(8, "0")}f01d00000000000000000000`;
1960
+ if (!folderMarkers.some((f) => f.id === candidate))
1961
+ return candidate;
1962
+ }
1963
+ };
1964
+ const currentFolders = () => collectStepPatternFolders(folderMarkers, entries);
1965
+ return {
1966
+ async list() {
1967
+ return entries.map((e) => structuredClone(e));
1968
+ },
1969
+ async listFolders() {
1970
+ return currentFolders().map((f) => ({ ...f }));
1971
+ },
1972
+ async save({ name, kind, folder, pattern, instrument, instrumentPreset }) {
1973
+ const fullFolder = normalizeStepPatternFolderPath(kind, folder);
1974
+ const existing = entries.find((e) => e.kind === kind && e.name.toLowerCase() === name.toLowerCase());
1975
+ if (existing) {
1976
+ existing.folder = fullFolder;
1977
+ existing.pattern = structuredClone(pattern);
1978
+ if (instrument) {
1979
+ existing.instrument = structuredClone(instrument);
1980
+ }
1981
+ else {
1982
+ delete existing.instrument;
1983
+ }
1984
+ if (instrumentPreset) {
1985
+ existing.instrumentPreset = instrumentPreset;
1986
+ }
1987
+ else {
1988
+ delete existing.instrumentPreset;
1989
+ }
1990
+ return { id: existing.id, folder: fullFolder };
1991
+ }
1992
+ const id = mintPatternId();
1993
+ const created = {
1994
+ id,
1995
+ name,
1996
+ kind,
1997
+ category: kind === "template" ? "templates" : "user",
1998
+ tags: [kind, "user"],
1999
+ folder: fullFolder,
2000
+ pattern: structuredClone(pattern)
2001
+ };
2002
+ if (instrument)
2003
+ created.instrument = structuredClone(instrument);
2004
+ if (instrumentPreset)
2005
+ created.instrumentPreset = instrumentPreset;
2006
+ entries.push(created);
2007
+ return { id, folder: fullFolder };
2008
+ },
2009
+ async createFolder({ kind, name, parentFolder }) {
2010
+ const target = resolveCreateStepPatternFolderTarget(currentFolders(), {
2011
+ kind,
2012
+ name,
2013
+ parentFolder
2014
+ });
2015
+ const id = mintFolderId();
2016
+ folderMarkers.push({ id, kind: target.kind, folder: target.folder });
2017
+ return {
2018
+ id,
2019
+ name: target.name,
2020
+ kind: target.kind,
2021
+ folder: target.folder,
2022
+ parentFolder: target.parentFolder
2023
+ };
2024
+ },
2025
+ async renameFolder({ folder, newName, kind }) {
2026
+ const plan = resolveRenameStepPatternFolderTarget(currentFolders(), {
2027
+ folder,
2028
+ newName,
2029
+ kind
2030
+ });
2031
+ for (const marker of folderMarkers) {
2032
+ if (marker.kind === plan.kind &&
2033
+ isWithinStepPatternFolder(marker.folder, plan.previousFolder)) {
2034
+ marker.folder = remapStepPatternFolderPath(marker.folder, plan.previousFolder, plan.folder);
2035
+ }
2036
+ }
2037
+ const movedPatterns = [];
2038
+ for (const entry of entries) {
2039
+ if (entry.kind === plan.kind &&
2040
+ isWithinStepPatternFolder(entry.folder, plan.previousFolder)) {
2041
+ const nextFolder = remapStepPatternFolderPath(entry.folder, plan.previousFolder, plan.folder);
2042
+ entry.folder = nextFolder;
2043
+ movedPatterns.push({
2044
+ id: entry.id,
2045
+ name: entry.name,
2046
+ folder: nextFolder
2047
+ });
2048
+ }
2049
+ }
2050
+ const renamed = {
2051
+ name: plan.name,
2052
+ kind: plan.kind,
2053
+ previousFolder: plan.previousFolder,
2054
+ folder: plan.folder,
2055
+ parentFolder: plan.parentFolder,
2056
+ movedPatternCount: movedPatterns.length,
2057
+ movedPatterns
2058
+ };
2059
+ return plan.current.id !== undefined ? { id: plan.current.id, ...renamed } : renamed;
2060
+ },
2061
+ async deleteFolder({ folder, kind }) {
2062
+ const target = resolveStepPatternFolderRef(currentFolders(), folder, kind);
2063
+ const parentFolder = parentStepPatternFolder(target.kind, target.folder);
2064
+ const movedPatterns = [];
2065
+ for (const entry of entries) {
2066
+ if (entry.kind === target.kind &&
2067
+ isWithinStepPatternFolder(entry.folder, target.folder)) {
2068
+ entry.folder = parentFolder;
2069
+ movedPatterns.push({
2070
+ id: entry.id,
2071
+ name: entry.name,
2072
+ folder: parentFolder
2073
+ });
2074
+ }
2075
+ }
2076
+ for (let i = folderMarkers.length - 1; i >= 0; i -= 1) {
2077
+ const marker = folderMarkers[i];
2078
+ if (marker.kind === target.kind &&
2079
+ isWithinStepPatternFolder(marker.folder, target.folder)) {
2080
+ folderMarkers.splice(i, 1);
2081
+ }
2082
+ }
2083
+ return {
2084
+ kind: target.kind,
2085
+ deletedFolder: target.folder,
2086
+ parentFolder,
2087
+ movedPatternCount: movedPatterns.length,
2088
+ movedPatterns
2089
+ };
2090
+ },
2091
+ async movePattern({ pattern, folder }) {
2092
+ const match = resolveUserStepPatternRef(entries, pattern);
2093
+ const targetFolder = resolveMoveDestinationFolder(currentFolders(), match.kind, folder);
2094
+ const previousFolder = match.folder ?? stepPatternRootFolder(match.kind);
2095
+ match.folder = targetFolder;
2096
+ return {
2097
+ id: match.id,
2098
+ name: match.name,
2099
+ kind: match.kind,
2100
+ previousFolder,
2101
+ folder: targetFolder
2102
+ };
2103
+ }
2104
+ };
2105
+ }
2106
+ //# sourceMappingURL=stepPattern.js.map