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
@@ -0,0 +1,83 @@
1
+ """The Trackwright MIDI Remote script shipped inside the package, and its installer.
2
+
3
+ Cubase loads user scripts from
4
+ ``~/Documents/Steinberg/Cubase/MIDI Remote/Driver Scripts/Local/<vendor>/<device>/<Vendor>_<Device>.js``.
5
+ Cubase does **not** reload a changed script by itself: restart Cubase (or use "Reload Scripts")
6
+ after installing a new version.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import re
13
+ import shutil
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import Literal
17
+
18
+ from loguru import logger
19
+
20
+ from trackwright.errors import PreconditionFailedError
21
+
22
+ SCRIPT_NAME = "Trackwright_Bridge.js"
23
+ SCRIPT_PATH = Path(__file__).with_name(SCRIPT_NAME)
24
+
25
+ InstallState = Literal["missing", "up_to_date", "different"]
26
+
27
+
28
+ def _version_of(path: Path) -> str | None:
29
+ match = re.search(r"var SCRIPT_VERSION = '([^']+)'", path.read_text(encoding="utf-8"))
30
+ return match.group(1) if match else None
31
+
32
+
33
+ def _digest(path: Path) -> str:
34
+ return hashlib.sha256(path.read_bytes()).hexdigest()
35
+
36
+
37
+ SCRIPT_VERSION = _version_of(SCRIPT_PATH)
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class ScriptStatus:
42
+ destination: Path
43
+ state: InstallState
44
+ packaged_version: str | None
45
+ installed_version: str | None
46
+
47
+ def to_dict(self) -> dict[str, str | None]:
48
+ return {
49
+ "destination": str(self.destination),
50
+ "state": self.state,
51
+ "packaged_version": self.packaged_version,
52
+ "installed_version": self.installed_version,
53
+ }
54
+
55
+
56
+ def script_status(install_dir: Path, source: Path = SCRIPT_PATH) -> ScriptStatus:
57
+ """Compare the installed script with ``source`` (the packaged script by default)."""
58
+ destination = install_dir / SCRIPT_NAME
59
+ if not destination.exists():
60
+ return ScriptStatus(destination, "missing", _version_of(source), None)
61
+ state: InstallState = "up_to_date" if _digest(destination) == _digest(source) else "different"
62
+ return ScriptStatus(destination, state, _version_of(source), _version_of(destination))
63
+
64
+
65
+ def install_script(install_dir: Path, *, apply: bool, source: Path = SCRIPT_PATH) -> tuple[ScriptStatus, bool]:
66
+ """Copy ``source`` (the packaged script by default) to ``install_dir``. Without ``apply`` only report.
67
+
68
+ ``source`` lets developers install an experiment build (for example ``experiments/tw1101``).
69
+ Returns the status *after* the call and whether a file was written.
70
+ """
71
+ if not install_dir.is_absolute():
72
+ raise PreconditionFailedError(f"the install directory must be an absolute path: {install_dir}")
73
+ if not source.is_file() or _version_of(source) is None:
74
+ raise PreconditionFailedError(f"{source} is not a Trackwright MIDI Remote script")
75
+ status = script_status(install_dir, source)
76
+ if not apply or status.state == "up_to_date":
77
+ return status, False
78
+ if status.destination.is_symlink():
79
+ raise PreconditionFailedError(f"refusing to overwrite a symbolic link: {status.destination}")
80
+ install_dir.mkdir(parents=True, exist_ok=True)
81
+ shutil.copyfile(source, status.destination)
82
+ logger.info("installed {} {} at {}", SCRIPT_NAME, _version_of(source), status.destination)
83
+ return script_status(install_dir, source), True
trackwright/doctor.py ADDED
@@ -0,0 +1,69 @@
1
+ """``trackwright doctor``: check every link of the chain and say what to do next.
2
+
3
+ Used by the ``doctor`` command and as the last step of ``trackwright setup``. Read-only: it never starts
4
+ the bridge nor writes anything.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from trackwright.bridge import BridgeClient
12
+ from trackwright.config import Settings
13
+ from trackwright.cubase import script_status
14
+ from trackwright.errors import TrackwrightError
15
+
16
+ JsonObject = dict[str, Any]
17
+
18
+
19
+ def run_doctor(settings: Settings) -> JsonObject:
20
+ """Return ``{"ok": bool, "checks": [{"check", "ok", "detail", "fix"?}, ...]}``."""
21
+ checks: list[JsonObject] = []
22
+
23
+ def check(name: str, ok: bool, detail: Any, fix: str | None = None) -> bool:
24
+ checks.append({"check": name, "ok": ok, "detail": detail, **({"fix": fix} if fix and not ok else {})})
25
+ return ok
26
+
27
+ check("configuration", True, str(settings.source or "built-in defaults"))
28
+ status = script_status(settings.script.install_dir)
29
+ check(
30
+ "script installed",
31
+ status.state == "up_to_date",
32
+ status.to_dict(),
33
+ "run 'trackwright setup' (or 'trackwright script install --apply') and restart Cubase",
34
+ )
35
+ client = BridgeClient(settings.bridge.socket_path)
36
+ bridge_fix = (
37
+ "it starts by itself with the MCP server ([bridge] autostart); to start it by hand: 'trackwright bridge'"
38
+ if settings.bridge.autostart
39
+ else "start it in a terminal: 'trackwright bridge'"
40
+ )
41
+ try:
42
+ bridge = client.call("bridge.status", timeout=settings.bridge.request_timeout)
43
+ bridge_ok = check(
44
+ "bridge running", True, {"socket": str(settings.bridge.socket_path), "pid": bridge.get("pid")}
45
+ )
46
+ except TrackwrightError as exc:
47
+ bridge_ok = check("bridge running", False, exc.to_dict(), bridge_fix)
48
+ if bridge_ok:
49
+ try:
50
+ hello = client.call("hello", timeout=settings.bridge.request_timeout)
51
+ check("Cubase answers", True, {"script": hello.get("scriptVersion"), "host": hello.get("host")})
52
+ except TrackwrightError as exc:
53
+ check(
54
+ "Cubase answers",
55
+ False,
56
+ exc.to_dict(),
57
+ "open Cubase; in the MIDI Remote tab of the lower zone the 'Trackwright - Bridge' surface "
58
+ "must be active (see docs/manual/01-installation.md, step 6)",
59
+ )
60
+ check(
61
+ "writes",
62
+ True,
63
+ {
64
+ "enabled": settings.writes.enabled,
65
+ "save": settings.writes.save,
66
+ "allowed_tracks": list(settings.writes.allowed_tracks),
67
+ },
68
+ )
69
+ return {"ok": all(c["ok"] for c in checks), "checks": checks}
trackwright/errors.py ADDED
@@ -0,0 +1,120 @@
1
+ """Error hierarchy shared by every layer.
2
+
3
+ Every error carries a stable machine-readable ``code`` (also used as the MCP tool error prefix),
4
+ a human message and optional ``details``. Codes reported by the Cubase script (``HostError``) are
5
+ passed through unchanged so that the evidence in the POC documentation maps directly to them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, ClassVar
11
+
12
+
13
+ class TrackwrightError(Exception):
14
+ """Base class. ``code`` is stable and documented in the tools reference."""
15
+
16
+ default_code: ClassVar[str] = "TRACKWRIGHT_ERROR"
17
+
18
+ def __init__(self, message: str, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
19
+ super().__init__(message)
20
+ self.code = code or self.default_code
21
+ self.message = message
22
+ self.details: dict[str, Any] = dict(details or {})
23
+
24
+ def to_dict(self) -> dict[str, Any]:
25
+ """Serializable form used by the bridge IPC and in logs."""
26
+ out: dict[str, Any] = {"code": self.code, "message": self.message}
27
+ if self.details:
28
+ out["details"] = self.details
29
+ return out
30
+
31
+ def __str__(self) -> str:
32
+ return f"{self.code}: {self.message}"
33
+
34
+
35
+ class ConfigError(TrackwrightError):
36
+ """The configuration file or environment is invalid."""
37
+
38
+ default_code = "CONFIG_ERROR"
39
+
40
+
41
+ class TransportError(TrackwrightError):
42
+ """The MIDI transport could not be opened or used."""
43
+
44
+ default_code = "TRANSPORT_ERROR"
45
+
46
+
47
+ class ProtocolError(TrackwrightError):
48
+ """A frame or envelope does not follow the protocol."""
49
+
50
+ default_code = "PROTOCOL_ERROR"
51
+
52
+
53
+ class RequestTimeoutError(TrackwrightError):
54
+ """No response in time. For writes the outcome is unknown: never retry, read back instead."""
55
+
56
+ default_code = "TIMEOUT"
57
+
58
+ def __init__(self, message: str, *, outcome_unknown: bool, details: dict[str, Any] | None = None) -> None:
59
+ merged = {"outcome": "unknown" if outcome_unknown else "not_executed_or_lost", **(details or {})}
60
+ super().__init__(message, details=merged)
61
+ self.outcome_unknown = outcome_unknown
62
+
63
+
64
+ class StaleSessionError(TrackwrightError):
65
+ """The script was reloaded: its session id changed and runtime ids are no longer valid."""
66
+
67
+ default_code = "STALE_SESSION"
68
+
69
+
70
+ class HostError(TrackwrightError):
71
+ """An error reported by the Cubase script; ``code`` is the script's code (for example ``INVALID_OBJECT``)."""
72
+
73
+ default_code = "HOST_ERROR"
74
+
75
+
76
+ class BridgeUnavailableError(TrackwrightError):
77
+ """The bridge daemon is not running or its socket is not usable."""
78
+
79
+ default_code = "BRIDGE_UNAVAILABLE"
80
+
81
+
82
+ class PolicyError(TrackwrightError):
83
+ """The configured write policy forbids the operation (``WRITES_DISABLED`` or ``NOT_ALLOWED``)."""
84
+
85
+ default_code = "NOT_ALLOWED"
86
+
87
+
88
+ class NotFoundError(TrackwrightError):
89
+ """A track, slot, parameter or command does not exist."""
90
+
91
+ default_code = "NOT_FOUND"
92
+
93
+
94
+ class StaleReferenceError(TrackwrightError):
95
+ """An opaque object reference belongs to another session or now points at a different object."""
96
+
97
+ default_code = "STALE_REF"
98
+
99
+
100
+ class PreconditionFailedError(TrackwrightError):
101
+ """The current state does not allow the operation (slot occupied, selection mismatch...)."""
102
+
103
+ default_code = "PRECONDITION_FAILED"
104
+
105
+
106
+ class VerificationFailedError(TrackwrightError):
107
+ """The operation ran but reading the state back does not show the requested result."""
108
+
109
+ default_code = "VERIFY_FAILED"
110
+
111
+
112
+ _HOST_CODE_CLASSES: dict[str, type[TrackwrightError]] = {
113
+ "STALE_SESSION": StaleSessionError,
114
+ }
115
+
116
+
117
+ def host_error(code: str, message: str, details: dict[str, Any] | None = None) -> TrackwrightError:
118
+ """Build the error for a code returned by the Cubase script."""
119
+ cls = _HOST_CODE_CLASSES.get(code, HostError)
120
+ return cls(message, code=code, details=details)
trackwright/exports.py ADDED
@@ -0,0 +1,54 @@
1
+ """Find the audio files Cubase exported (TW-1204). Only metadata is read: name, size, time and duration.
2
+
3
+ The duration comes from macOS ``afinfo`` ("estimated duration: 27.991125 sec"), which reads the file header.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import subprocess
10
+ from collections.abc import Callable, Sequence
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ AUDIO_SUFFIXES = frozenset({".wav", ".mp3", ".aif", ".aiff", ".flac", ".ogg", ".m4a", ".wv"})
15
+ PROJECT_SUFFIXES = frozenset({".cpr"})
16
+ DURATION = re.compile(r"estimated duration:\s*([0-9.]+)\s*sec")
17
+ Output = Callable[[Sequence[str]], str]
18
+
19
+
20
+ def _afinfo(argv: Sequence[str]) -> str:
21
+ result = subprocess.run(list(argv), capture_output=True, check=False, text=True, timeout=15) # noqa: S603
22
+ return result.stdout
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ExportedFile:
27
+ path: str
28
+ size_bytes: int
29
+ modified: float
30
+ duration_seconds: float | None
31
+
32
+
33
+ class ExportInspector:
34
+ def __init__(self, *, output: Output = _afinfo) -> None:
35
+ self._output = output
36
+
37
+ def duration(self, path: Path) -> float | None:
38
+ match = DURATION.search(self._output(["/usr/bin/afinfo", str(path)]))
39
+ return float(match.group(1)) if match else None
40
+
41
+ def find(self, folder: Path, since: float, suffixes: frozenset[str] = AUDIO_SUFFIXES) -> list[ExportedFile]:
42
+ """Files with ``suffixes`` directly in ``folder`` modified at or after ``since`` (epoch seconds), newest
43
+ first. Audio files also get their duration; nothing else is read."""
44
+ if not folder.is_dir():
45
+ return []
46
+ found = []
47
+ for entry in folder.iterdir():
48
+ if entry.suffix.lower() not in suffixes or not entry.is_file():
49
+ continue
50
+ info = entry.stat()
51
+ if info.st_mtime >= since - 1.0:
52
+ duration = self.duration(entry) if entry.suffix.lower() in AUDIO_SUFFIXES else None
53
+ found.append(ExportedFile(str(entry), info.st_size, info.st_mtime, duration))
54
+ return sorted(found, key=lambda f: f.modified, reverse=True)