trackwright 0.3.0__py3-none-any.whl

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 (46) hide show
  1. trackwright/__init__.py +13 -0
  2. trackwright/__main__.py +7 -0
  3. trackwright/bridge.py +323 -0
  4. trackwright/cli.py +203 -0
  5. trackwright/commands.py +397 -0
  6. trackwright/config.py +149 -0
  7. trackwright/core/__init__.py +1 -0
  8. trackwright/core/automation.py +410 -0
  9. trackwright/core/base.py +313 -0
  10. trackwright/core/commanding.py +300 -0
  11. trackwright/core/exporting.py +143 -0
  12. trackwright/core/importing.py +127 -0
  13. trackwright/core/lifecycle.py +74 -0
  14. trackwright/core/models.py +467 -0
  15. trackwright/core/policy.py +58 -0
  16. trackwright/core/presets.py +88 -0
  17. trackwright/core/project.py +221 -0
  18. trackwright/core/ranges.py +355 -0
  19. trackwright/core/reading.py +229 -0
  20. trackwright/core/refs.py +88 -0
  21. trackwright/core/saving.py +72 -0
  22. trackwright/core/service.py +27 -0
  23. trackwright/core/settings.py +80 -0
  24. trackwright/core/writing.py +390 -0
  25. trackwright/coremidi.py +307 -0
  26. trackwright/cubase/Trackwright_Bridge.js +1130 -0
  27. trackwright/cubase/__init__.py +83 -0
  28. trackwright/doctor.py +69 -0
  29. trackwright/errors.py +120 -0
  30. trackwright/exports.py +54 -0
  31. trackwright/fake.py +1112 -0
  32. trackwright/host.py +238 -0
  33. trackwright/hostport.py +74 -0
  34. trackwright/installer.py +305 -0
  35. trackwright/launcher.py +150 -0
  36. trackwright/logs.py +50 -0
  37. trackwright/ops.py +46 -0
  38. trackwright/protocol.py +182 -0
  39. trackwright/py.typed +0 -0
  40. trackwright/server.py +472 -0
  41. trackwright/transport.py +130 -0
  42. trackwright-0.3.0.dist-info/METADATA +190 -0
  43. trackwright-0.3.0.dist-info/RECORD +46 -0
  44. trackwright-0.3.0.dist-info/WHEEL +4 -0
  45. trackwright-0.3.0.dist-info/entry_points.txt +3 -0
  46. trackwright-0.3.0.dist-info/licenses/LICENSE +661 -0
trackwright/server.py ADDED
@@ -0,0 +1,472 @@
1
+ """The Trackwright MCP server: tool registration on top of :class:`~trackwright.core.service.CubaseService`.
2
+
3
+ Every tool is a thin async wrapper: it runs the blocking service call in a worker thread and turns
4
+ :class:`~trackwright.errors.TrackwrightError` into an MCP tool error ``"CODE: message"`` so the
5
+ model can read it and correct itself.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Callable
12
+ from typing import Annotated, Literal
13
+
14
+ import anyio.to_thread
15
+ from loguru import logger
16
+ from mcp.server.mcpserver import MCPServer
17
+ from mcp.server.mcpserver.exceptions import ToolError
18
+ from mcp_types import ToolAnnotations
19
+ from pydantic import Field
20
+
21
+ from trackwright import SERVER_NAME, __version__
22
+ from trackwright.core.models import (
23
+ AutomationPoint,
24
+ AutomationRecordOut,
25
+ AutomationTargetsOut,
26
+ ChangesOut,
27
+ CommandOut,
28
+ ConvertOut,
29
+ ExportOut,
30
+ ImportOut,
31
+ InsertPluginOut,
32
+ InsertsOut,
33
+ LaunchOut,
34
+ ParameterOut,
35
+ ParametersOut,
36
+ PluginCatalogOut,
37
+ PositionOut,
38
+ PresetStepOut,
39
+ ProjectOut,
40
+ ProjectSettingsOut,
41
+ RangeEditOut,
42
+ SaveOut,
43
+ SelectedChannelOut,
44
+ SelectOut,
45
+ StatusOut,
46
+ TempoOut,
47
+ TrackListOut,
48
+ TransportOut,
49
+ WriteOut,
50
+ )
51
+ from trackwright.core.service import CubaseService
52
+ from trackwright.errors import TrackwrightError
53
+
54
+ INSTRUCTIONS = """\
55
+ Trackwright controls a running Cubase through its MIDI Remote API.
56
+
57
+ Rules for using these tools:
58
+ - Designate tracks with the `track` selector: "selected", "uid:<UID>" (stable, preferred) or an exact name.
59
+ Take uids from cubase_list_tracks. Object `ref`s are only valid until Cubase reloads the script.
60
+ - Every tool that modifies the project has `dry_run` (default true). First call it with dry_run=true,
61
+ show the plan to the user, and only after the user agrees call it again with dry_run=false.
62
+ - Writes are never retried automatically. After a TIMEOUT the outcome is unknown: read the value back.
63
+ - Commands report a `command_class`. "dialog" means Cubase opened a dialog that the user must complete:
64
+ never claim it is done. "ui_selection" commands act on the Cubase window selection, which these tools
65
+ cannot see: ask the user to check the result.
66
+ - Routing (inputs, outputs, send destinations) cannot be changed through this API.
67
+ - Podcast-style editing: cubase_edit_range works in seconds and acts on every track in the range.
68
+ - Never save on your own initiative: cubase_save_project only when the user asks to save, after a dry run.
69
+ - Automation: list the parameters with cubase_list_automation_targets, then record a curve with
70
+ cubase_record_automation. Recording plays the project (audible) and writes the track's automation.
71
+ Give points in real units ("plain": -20 for -20 dB, 1000 for 1 kHz, pan -100 left..0..+100 right):
72
+ Cubase converts them exactly. Never guess
73
+ normalized values; use cubase_convert_value when you need one.
74
+ - If a tool fails with WRITES_DISABLED, writes are disabled in the user's Trackwright configuration.
75
+ """
76
+
77
+ TrackArg = Annotated[str, Field(description='"selected", "uid:<UID>" (from cubase_list_tracks) or an exact track name')]
78
+ TargetArg = Annotated[
79
+ str, Field(description="'channel' (track parameters), 'insert:N' (plugin in slot N) or 'strip:eq'")
80
+ ]
81
+ DryRunArg = Annotated[bool, Field(description="true (default): only return the plan; false: apply it")]
82
+ TimeArg = Annotated[str, Field(description="'3. 1. 1. 0' (bar. beat. 16th. tick) or, with unit=seconds, '0:00:02.000'")]
83
+
84
+ READ = ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=False)
85
+ NAVIGATE = ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=True, open_world_hint=False)
86
+ WRITE = ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=False, open_world_hint=False)
87
+ DESTRUCTIVE = ToolAnnotations(read_only_hint=False, destructive_hint=True, idempotent_hint=False, open_world_hint=False)
88
+
89
+
90
+ def tool_error(exc: TrackwrightError) -> ToolError:
91
+ text = f"{exc.code}: {exc.message}"
92
+ if exc.details:
93
+ text += f" | details: {json.dumps(exc.details, ensure_ascii=False, default=str)}"
94
+ return ToolError(text)
95
+
96
+
97
+ async def run[T](fn: Callable[[], T]) -> T:
98
+ """Run a blocking service call off the event loop and map domain errors to tool errors."""
99
+ try:
100
+ return await anyio.to_thread.run_sync(fn)
101
+ except TrackwrightError as exc:
102
+ logger.info("tool error {}", exc)
103
+ raise tool_error(exc) from exc
104
+
105
+
106
+ def build_server(service: CubaseService) -> MCPServer:
107
+ server: MCPServer = MCPServer(name=SERVER_NAME, version=__version__, instructions=INSTRUCTIONS)
108
+
109
+ # ------------------------------------------------------------------ read tools (E05)
110
+ @server.tool(annotations=READ, description="Connection, script version, capabilities and write policy.")
111
+ async def cubase_status() -> StatusOut:
112
+ return await run(service.status)
113
+
114
+ @server.tool(annotations=READ, description="All mixer channels with name, uid, volume, mute, solo and routing.")
115
+ async def cubase_list_tracks(
116
+ offset: Annotated[int, Field(ge=0)] = 0, limit: Annotated[int, Field(ge=1, le=128)] = 32
117
+ ) -> TrackListOut:
118
+ return await run(lambda: service.list_tracks(offset, limit))
119
+
120
+ @server.tool(annotations=READ, description="The selected track and its sections (Inserts, Strips, Sends...).")
121
+ async def cubase_get_selected_channel() -> SelectedChannelOut:
122
+ return await run(service.get_selected_channel)
123
+
124
+ @server.tool(annotations=READ, description="The 8 insert slots of a track and the plugin loaded in each.")
125
+ async def cubase_list_inserts(track: TrackArg = "selected") -> InsertsOut:
126
+ return await run(lambda: service.list_inserts(track))
127
+
128
+ @server.tool(annotations=READ, description="Plugins that can be loaded in an insert slot (name, vendor, uid).")
129
+ async def cubase_list_available_plugins(
130
+ track: TrackArg = "selected",
131
+ slot: Annotated[int, Field(ge=1, le=16)] = 1,
132
+ filter: Annotated[str | None, Field(description="text to match in name, vendor or category")] = None, # noqa: A002
133
+ offset: Annotated[int, Field(ge=0)] = 0,
134
+ limit: Annotated[int, Field(ge=1, le=40)] = 20,
135
+ ) -> PluginCatalogOut:
136
+ return await run(lambda: service.list_available_plugins(track, slot, filter, offset, limit))
137
+
138
+ @server.tool(annotations=READ, description="Parameters of the channel, of a plugin or of the strip EQ.")
139
+ async def cubase_list_parameters(
140
+ target: TargetArg,
141
+ track: TrackArg = "selected",
142
+ offset: Annotated[int, Field(ge=0, description="use next_offset from the previous page")] = 0,
143
+ limit: Annotated[int, Field(ge=1, le=25)] = 25,
144
+ filter: Annotated[str | None, Field(description="text to match in the parameter title")] = None, # noqa: A002
145
+ ) -> ParametersOut:
146
+ return await run(lambda: service.list_parameters(track, target, offset, limit, filter))
147
+
148
+ @server.tool(annotations=READ, description="One parameter, by tag, with its display value and units.")
149
+ async def cubase_get_parameter(target: TargetArg, tag: int, track: TrackArg = "selected") -> ParameterOut:
150
+ return await run(lambda: service.get_parameter(track, target, tag))
151
+
152
+ @server.tool(
153
+ annotations=READ,
154
+ description="Properties of the open project: tempo, time signature at the cursor, cycle, punch, pre/post-roll, "
155
+ "metronome, precount, transport state, record modes and the project folder. Says which properties the "
156
+ "Cubase API does not expose (sample rate, length, name).",
157
+ )
158
+ async def cubase_get_project(
159
+ include_folders: Annotated[
160
+ bool, Field(description="find the project folder from the files Cubase has open (lsof)")
161
+ ] = True,
162
+ ) -> ProjectOut:
163
+ return await run(lambda: service.get_project(include_folders=include_folders))
164
+
165
+ @server.tool(annotations=READ, description="Cursor position, cycle locators and tempo.")
166
+ async def cubase_get_transport() -> TransportOut:
167
+ return await run(service.get_transport)
168
+
169
+ @server.tool(
170
+ annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=False),
171
+ description="Changes Cubase reported since the last call (hints to re-read objects). Empties the buffer.",
172
+ )
173
+ async def cubase_poll_changes() -> ChangesOut:
174
+ return await run(service.poll_changes)
175
+
176
+ # ------------------------------------------------------------------ write and navigation tools (E06)
177
+ @server.tool(annotations=WRITE, description="Set a parameter (process 0..1 or plain units) and verify it.")
178
+ async def cubase_set_parameter(
179
+ target: TargetArg,
180
+ tag: int,
181
+ value: float,
182
+ track: TrackArg = "selected",
183
+ unit: Literal["process", "plain"] = "process",
184
+ expect_title: Annotated[str | None, Field(description="refuse if the parameter title differs")] = None,
185
+ dry_run: DryRunArg = True,
186
+ ) -> WriteOut:
187
+ return await run(
188
+ lambda: service.set_parameter(
189
+ track, target, tag, value, unit=unit, dry_run=dry_run, expect_title=expect_title
190
+ )
191
+ )
192
+
193
+ @server.tool(annotations=WRITE, description="Load a plugin (by uid) into an empty insert slot and verify it.")
194
+ async def cubase_insert_plugin(
195
+ slot: Annotated[int, Field(ge=1, le=16)],
196
+ plugin_uid: Annotated[str, Field(description="uid from cubase_list_available_plugins")],
197
+ track: TrackArg = "selected",
198
+ dry_run: DryRunArg = True,
199
+ ) -> InsertPluginOut:
200
+ return await run(lambda: service.insert_plugin(track, slot, plugin_uid, dry_run=dry_run))
201
+
202
+ @server.tool(annotations=WRITE, description="Volume (normalized 0..1), mute, solo or record arm of any track.")
203
+ async def cubase_set_track_mix(
204
+ track: TrackArg,
205
+ volume: Annotated[float | None, Field(ge=0, le=1, description="normalized fader value")] = None,
206
+ mute: bool | None = None,
207
+ solo: bool | None = None,
208
+ record_arm: bool | None = None,
209
+ dry_run: DryRunArg = True,
210
+ ) -> WriteOut:
211
+ return await run(
212
+ lambda: service.set_track_mix(
213
+ track, volume=volume, mute=mute, solo=solo, record_arm=record_arm, dry_run=dry_run
214
+ )
215
+ )
216
+
217
+ @server.tool(annotations=WRITE, description="Rename a track (refuses names used by another track).")
218
+ async def cubase_rename_track(
219
+ track: TrackArg, new_name: Annotated[str, Field(min_length=1, max_length=64)], dry_run: DryRunArg = True
220
+ ) -> WriteOut:
221
+ return await run(lambda: service.rename_track(track, new_name, dry_run=dry_run))
222
+
223
+ @server.tool(annotations=NAVIGATE, description="Select a track, or the next/previous one. Single selection.")
224
+ async def cubase_select_track(
225
+ track: Annotated[str | None, Field(description="track selector; omit when using step")] = None,
226
+ step: Literal["next", "prev"] | None = None,
227
+ ) -> SelectOut:
228
+ return await run(lambda: service.select_track(track, step))
229
+
230
+ @server.tool(annotations=NAVIGATE, description="Move the cursor or a cycle locator (transport stopped).")
231
+ async def cubase_set_position(
232
+ which: Literal["cursor", "cycle_left", "cycle_right"],
233
+ time: TimeArg,
234
+ unit: Literal["bars", "seconds"] = "bars",
235
+ dry_run: Annotated[bool, Field(description="true: only show the current and requested positions")] = False,
236
+ ) -> PositionOut:
237
+ return await run(lambda: service.set_position(which, time, unit=unit, dry_run=dry_run))
238
+
239
+ @server.tool(annotations=WRITE, description="Set the project tempo in BPM (20..300).")
240
+ async def cubase_set_tempo(bpm: Annotated[float, Field(ge=20, le=300)], dry_run: DryRunArg = True) -> TempoOut:
241
+ return await run(lambda: service.set_tempo(bpm, dry_run=dry_run))
242
+
243
+ # ------------------------------------------------------------------ command tools (E07)
244
+ @server.tool(annotations=WRITE, description="Marker track, insert a marker at the cursor, or jump between markers.")
245
+ async def cubase_markers(
246
+ action: Literal["add_marker_track", "insert_at_cursor", "locate_prev", "locate_next"],
247
+ dry_run: DryRunArg = True,
248
+ ) -> CommandOut:
249
+ return await run(lambda: service.markers(action, dry_run=dry_run))
250
+
251
+ @server.tool(
252
+ annotations=DESTRUCTIVE,
253
+ description="Remove the selected track. expect_selected must match the current selection exactly.",
254
+ )
255
+ async def cubase_remove_selected_tracks(expect_selected: TrackArg, dry_run: DryRunArg = True) -> CommandOut:
256
+ return await run(lambda: service.remove_selected_tracks(expect_selected, dry_run=dry_run))
257
+
258
+ @server.tool(annotations=DESTRUCTIVE, description="Split every event crossing the given locators (all tracks).")
259
+ async def cubase_split_at_locators(left: TimeArg, right: TimeArg, dry_run: DryRunArg = True) -> CommandOut:
260
+ return await run(lambda: service.split_at_locators(left, right, dry_run=dry_run))
261
+
262
+ @server.tool(
263
+ annotations=WRITE,
264
+ description="Create an audio/group/folder track with the user's help: 'start' opens Cubase's dialog, "
265
+ "'confirm' checks that the track exists.",
266
+ )
267
+ async def cubase_add_track_interactive(
268
+ phase: Literal["start", "confirm"],
269
+ kind: Literal["audio", "group", "folder"],
270
+ suggested_name: Annotated[str, Field(min_length=1, max_length=64)],
271
+ ) -> CommandOut:
272
+ return await run(lambda: service.add_track_interactive(phase, kind, suggested_name))
273
+
274
+ @server.tool(
275
+ annotations=DESTRUCTIVE,
276
+ description="Run a Cubase command from the allow-list (see the tools reference). Advanced: prefer the "
277
+ "dedicated tools. Reports the observed command class.",
278
+ )
279
+ async def cubase_run_command(
280
+ key: Annotated[str, Field(description="command key, e.g. 'edit.undo' or 'zoom.in'")],
281
+ dry_run: DryRunArg = True,
282
+ force: Annotated[bool, Field(description="fire even if Cubase says it cannot be performed")] = False,
283
+ ) -> CommandOut:
284
+ return await run(lambda: service.run_command(key, dry_run=dry_run, force=force))
285
+
286
+ # ------------------------------------------------------------------ range editing (TW-1211)
287
+ @server.tool(
288
+ annotations=DESTRUCTIVE,
289
+ description="Edit a time range of the project, in seconds (or bars), on EVERY track with events in it "
290
+ "(or, with track and action 'delete', on that track only): "
291
+ "delete (leave a gap), delete_time or cut_time (remove and close the gap), insert_silence, crop. "
292
+ "With verify_track (a track with audio), checks the result by probing its event edges before and after. "
293
+ "Undo in Cubase reverts it. Dry run by default.",
294
+ )
295
+ async def cubase_edit_range(
296
+ start: Annotated[str, Field(description="range start: seconds ('2', '1:30', '0:01:30.250') or bars")],
297
+ end: Annotated[str, Field(description="range end, same unit")],
298
+ action: Annotated[
299
+ Literal["delete", "delete_time", "cut_time", "insert_silence", "crop"],
300
+ Field(description="what to do with the range"),
301
+ ],
302
+ unit: Annotated[Literal["seconds", "bars"], Field(description="unit of start and end")] = "seconds",
303
+ verify_track: Annotated[
304
+ str | None, Field(description="track whose audio edges are probed to verify (recommended)")
305
+ ] = None,
306
+ track: Annotated[
307
+ str | None,
308
+ Field(description="edit ONLY this track (action 'delete' only, e.g. a cough on one microphone)"),
309
+ ] = None,
310
+ dry_run: DryRunArg = True,
311
+ ) -> RangeEditOut:
312
+ return await run(
313
+ lambda: service.edit_range(
314
+ start, end, action, unit=unit, verify_track=verify_track, track=track, dry_run=dry_run
315
+ )
316
+ )
317
+
318
+ # ------------------------------------------------------------------ plugin presets (TW-1205)
319
+ @server.tool(
320
+ annotations=WRITE,
321
+ description="Step to the next or previous preset of the plugin in an insert slot (opens its editor for the "
322
+ "command). Verified by comparing the plugin's parameters. Presets cannot be chosen or read by name, and a "
323
+ "preset must already be loaded in the plugin. Dry run by default.",
324
+ )
325
+ async def cubase_plugin_preset(
326
+ track: TrackArg,
327
+ slot: Annotated[int, Field(ge=1, le=16, description="insert slot number")],
328
+ direction: Literal["next", "previous"],
329
+ dry_run: DryRunArg = True,
330
+ ) -> PresetStepOut:
331
+ return await run(lambda: service.plugin_preset(track, slot, direction, dry_run=dry_run))
332
+
333
+ # ------------------------------------------------------------------ project settings (TW-1210)
334
+ @server.tool(
335
+ annotations=WRITE,
336
+ description="Change project/transport settings: cycle, metronome, precount, punch in/out, use of pre/post-"
337
+ "roll, click in playback/record (true/false) and click level (0-127). Each one is read back. Dry run by "
338
+ "default. Time signature, tempo track and project setup are not settable here (use cubase_set_tempo).",
339
+ )
340
+ async def cubase_set_project(
341
+ cycle: bool | None = None,
342
+ metronome: bool | None = None,
343
+ precount: bool | None = None,
344
+ punch_in: bool | None = None,
345
+ punch_out: bool | None = None,
346
+ pre_roll: bool | None = None,
347
+ post_roll: bool | None = None,
348
+ click_in_playback: bool | None = None,
349
+ click_in_record: bool | None = None,
350
+ click_level: Annotated[int | None, Field(ge=0, le=127)] = None,
351
+ dry_run: DryRunArg = True,
352
+ ) -> ProjectSettingsOut:
353
+ given = {k: v for k, v in {
354
+ "cycle": cycle, "metronome": metronome, "precount": precount, "punch_in": punch_in,
355
+ "punch_out": punch_out, "pre_roll": pre_roll, "post_roll": post_roll,
356
+ "click_in_playback": click_in_playback, "click_in_record": click_in_record, "click_level": click_level,
357
+ }.items() if v is not None} # fmt: skip
358
+ return await run(lambda: service.set_project(given, dry_run=dry_run))
359
+
360
+ # ------------------------------------------------------------------ save (TW-1202)
361
+ @server.tool(
362
+ annotations=DESTRUCTIVE,
363
+ description="Save the project file, ONLY when the user explicitly asks to save. mode 'save' overwrites "
364
+ "the open .cpr; 'new_version' writes <name>-NN.cpr and Cubase continues on it. Needs [writes] save = "
365
+ "true. Dry run by default: show the plan and ask for confirmation. Verified by the .cpr file dates.",
366
+ )
367
+ async def cubase_save_project(
368
+ mode: Annotated[Literal["save", "new_version"], Field(description="overwrite or save a new version")] = "save",
369
+ dry_run: DryRunArg = True,
370
+ ) -> SaveOut:
371
+ return await run(lambda: service.save_project(mode, dry_run=dry_run))
372
+
373
+ # ------------------------------------------------------------------ import (TW-1203)
374
+ @server.tool(
375
+ annotations=WRITE,
376
+ description="Import an audio file with the user, in two phases. 'start' selects the track, puts the "
377
+ "cursor at the position (seconds or bars) and opens Cubase's file selector: the user picks the file "
378
+ "(Cubase does not answer until the selector is closed). 'confirm' (same track, position and file, plus "
379
+ "since) probes the track for the new event edges and lists the copy in the project's Audio folder.",
380
+ )
381
+ async def cubase_import_audio(
382
+ phase: Literal["start", "confirm"],
383
+ track: TrackArg,
384
+ position: Annotated[str, Field(description="where the audio starts: seconds ('0', '1:30') or bars")],
385
+ unit: Annotated[Literal["seconds", "bars"], Field(description="unit of position")] = "seconds",
386
+ file: Annotated[
387
+ str | None, Field(description="path of the file the user will pick (to tell them and check duration)")
388
+ ] = None,
389
+ since: Annotated[float | None, Field(description="confirm: the 'since' returned by start")] = None,
390
+ dry_run: DryRunArg = True,
391
+ ) -> ImportOut:
392
+ return await run(
393
+ lambda: service.import_audio(phase, track, position, unit=unit, file=file, since=since, dry_run=dry_run)
394
+ )
395
+
396
+ # ------------------------------------------------------------------ export (TW-1204)
397
+ @server.tool(
398
+ annotations=WRITE,
399
+ description="Export the mix with the user, in two phases. 'start' puts the locators on the range "
400
+ "(seconds or bars; omit start/end for all the audio) and opens Cubase's Export Audio Mixdown dialog: "
401
+ "the user picks the format and exports. 'confirm' (with since and expected_seconds from 'start') finds "
402
+ "the new file in the export folder and checks its duration. Trackwright never exports by itself.",
403
+ )
404
+ async def cubase_export_mix(
405
+ phase: Literal["start", "confirm"],
406
+ start: Annotated[str | None, Field(description="range start; omit with end for the whole project")] = None,
407
+ end: Annotated[str | None, Field(description="range end")] = None,
408
+ unit: Annotated[Literal["seconds", "bars"], Field(description="unit of start and end")] = "seconds",
409
+ since: Annotated[float | None, Field(description="confirm: the 'since' returned by start")] = None,
410
+ expected_seconds: Annotated[float | None, Field(description="confirm: the expected duration")] = None,
411
+ folder: Annotated[str | None, Field(description="confirm: export folder if not the proposed one")] = None,
412
+ dry_run: DryRunArg = True,
413
+ ) -> ExportOut:
414
+ return await run(
415
+ lambda: service.export_mix(
416
+ phase, start=start, end=end, unit=unit, since=since, expected_seconds=expected_seconds,
417
+ folder=folder, dry_run=dry_run,
418
+ )
419
+ ) # fmt: skip
420
+
421
+ # ------------------------------------------------------------------ lifecycle (TW-1201)
422
+ @server.tool(
423
+ annotations=WRITE,
424
+ description="Open Cubase (optionally with a .cpr project) when it is closed, and wait until the "
425
+ "Trackwright script answers. Never opens a second instance and never closes Cubase. Returns "
426
+ "awaiting_user when Cubase shows a dialog (Steinberg Hub, project choice) that the user must answer.",
427
+ )
428
+ async def cubase_launch(
429
+ project: Annotated[str | None, Field(description="path of a .cpr project to open (optional)")] = None,
430
+ dry_run: DryRunArg = True,
431
+ ) -> LaunchOut:
432
+ return await run(lambda: service.launch_cubase(project, dry_run=dry_run))
433
+
434
+ # ------------------------------------------------------------------ automation tools (TW-1207)
435
+ @server.tool(
436
+ annotations=NAVIGATE,
437
+ description="Parameters of a track that can be automated (volume, pan, sends, channel EQ, pre-filter, "
438
+ "quick controls, insert plugin parameters), with the Cubase parameter bound to each. Selects the track.",
439
+ )
440
+ async def cubase_list_automation_targets(track: TrackArg) -> AutomationTargetsOut:
441
+ return await run(lambda: service.list_automation_targets(track))
442
+
443
+ @server.tool(
444
+ annotations=NAVIGATE,
445
+ description="Exact conversion done by Cubase between a parameter's real units (dB, Hz...) and its "
446
+ "normalized 0..1 value, in either direction. Give plain or value. Changes nothing (selects the track).",
447
+ )
448
+ async def cubase_convert_value(
449
+ track: TrackArg,
450
+ parameter: Annotated[str, Field(description="key from cubase_list_automation_targets, e.g. 'volume'")],
451
+ plain: Annotated[float | None, Field(description="value in real units, e.g. -20 (dB)")] = None,
452
+ value: Annotated[float | None, Field(description="normalized value 0..1")] = None,
453
+ ) -> ConvertOut:
454
+ return await run(lambda: service.convert_value(track, parameter, plain=plain, value=value))
455
+
456
+ @server.tool(
457
+ annotations=WRITE,
458
+ description="Record an automation curve on a track parameter: plays the project from just before the "
459
+ "first point and moves the parameter through the points (linear in between). Audible. Optionally "
460
+ "verifies with a read-back pass. Positions assume 4/4. Give each point as plain (real units, preferred) "
461
+ "or value.",
462
+ )
463
+ async def cubase_record_automation(
464
+ track: TrackArg,
465
+ parameter: Annotated[str, Field(description="key from cubase_list_automation_targets, e.g. 'volume'")],
466
+ points: Annotated[list[AutomationPoint], Field(min_length=1, max_length=64)],
467
+ verify: Annotated[bool, Field(description="play again with read automation to check the curve")] = True,
468
+ dry_run: DryRunArg = True,
469
+ ) -> AutomationRecordOut:
470
+ return await run(lambda: service.record_automation(track, parameter, points, dry_run=dry_run, verify=verify))
471
+
472
+ return server
@@ -0,0 +1,130 @@
1
+ """MIDI transport: two CoreMIDI virtual ports created with mido + python-rtmidi.
2
+
3
+ Port names are written from Cubase's point of view:
4
+
5
+ - ``to_cubase`` ("Trackwright To Cubase") is a Python *virtual output*. CoreMIDI publishes it as a
6
+ source, so Cubase sees it as a MIDI **input**: the script reads from it.
7
+ - ``from_cubase`` ("Trackwright From Cubase") is a Python *virtual input*. CoreMIDI publishes it as
8
+ a destination, so Cubase sees it as a MIDI **output**: the script writes to it.
9
+
10
+ The ports exist only while the process that created them is alive. Cubase reconnects by itself
11
+ when they reappear (verified in the POC, milestone H).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import threading
17
+ from collections.abc import Callable, Sequence
18
+ from dataclasses import dataclass
19
+ from typing import Any, Protocol
20
+
21
+ from loguru import logger
22
+
23
+ from trackwright.errors import TransportError
24
+ from trackwright.protocol import is_ours
25
+
26
+ Receiver = Callable[[list[int]], None]
27
+
28
+
29
+ class Transport(Protocol):
30
+ """What the host client needs from a transport."""
31
+
32
+ name: str
33
+
34
+ def open(self, receiver: Receiver) -> None: ...
35
+
36
+ def send_sysex(self, data: Sequence[int]) -> None: ...
37
+
38
+ def close(self) -> None: ...
39
+
40
+ def stats(self) -> dict[str, int]: ...
41
+
42
+
43
+ @dataclass
44
+ class TransportStats:
45
+ sent_frames: int = 0
46
+ received_frames: int = 0
47
+ foreign_frames: int = 0
48
+ non_sysex_messages: int = 0
49
+
50
+
51
+ class MidiTransport:
52
+ """Real transport. ``backend`` is the ``mido`` module (injectable for tests)."""
53
+
54
+ name = "coremidi-virtual"
55
+
56
+ def __init__(self, to_cubase: str, from_cubase: str, *, backend: Any | None = None) -> None:
57
+ self.to_cubase = to_cubase
58
+ self.from_cubase = from_cubase
59
+ self._backend = backend
60
+ self._out: Any = None
61
+ self._in: Any = None
62
+ self._send_lock = threading.Lock()
63
+ self._stats = TransportStats()
64
+
65
+ def _mido(self) -> Any:
66
+ if self._backend is None:
67
+ import mido # noqa: PLC0415 - imported lazily: loading rtmidi is slow and not needed by --help
68
+
69
+ mido.set_backend("mido.backends.rtmidi")
70
+ self._backend = mido
71
+ return self._backend
72
+
73
+ def open(self, receiver: Receiver) -> None:
74
+ mido = self._mido()
75
+ existing_in = set(mido.get_input_names())
76
+ existing_out = set(mido.get_output_names())
77
+ if self.to_cubase in existing_in or self.from_cubase in existing_out:
78
+ raise TransportError(
79
+ "virtual ports with these names already exist: is another bridge running?",
80
+ details={"to_cubase": self.to_cubase, "from_cubase": self.from_cubase},
81
+ )
82
+
83
+ def on_message(message: Any) -> None:
84
+ if message.type != "sysex":
85
+ self._stats.non_sysex_messages += 1
86
+ return
87
+ data = list(message.data)
88
+ if not is_ours(data):
89
+ self._stats.foreign_frames += 1
90
+ logger.trace("ignoring foreign SysEx {}", data[:8])
91
+ return
92
+ self._stats.received_frames += 1
93
+ try:
94
+ receiver(data)
95
+ except Exception:
96
+ logger.exception("receiver failed")
97
+
98
+ try:
99
+ self._out = mido.open_output(self.to_cubase, virtual=True)
100
+ self._in = mido.open_input(self.from_cubase, virtual=True, callback=on_message)
101
+ except Exception as exc:
102
+ self.close()
103
+ raise TransportError(f"cannot create virtual ports: {exc}") from exc
104
+ logger.info("virtual MIDI ports open: '{}' (to Cubase), '{}' (from Cubase)", self.to_cubase, self.from_cubase)
105
+
106
+ def send_sysex(self, data: Sequence[int]) -> None:
107
+ if self._out is None:
108
+ raise TransportError("transport is not open")
109
+ message = self._mido().Message("sysex", data=list(data))
110
+ with self._send_lock:
111
+ self._out.send(message)
112
+ self._stats.sent_frames += 1
113
+
114
+ def close(self) -> None:
115
+ for port in (self._in, self._out):
116
+ if port is None:
117
+ continue
118
+ try:
119
+ port.close()
120
+ except Exception:
121
+ logger.exception("error closing MIDI port")
122
+ self._in = self._out = None
123
+
124
+ def stats(self) -> dict[str, int]:
125
+ return {
126
+ "sent_frames": self._stats.sent_frames,
127
+ "received_frames": self._stats.received_frames,
128
+ "foreign_frames": self._stats.foreign_frames,
129
+ "non_sysex_messages": self._stats.non_sysex_messages,
130
+ }