flmcp-studio 0.4.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.
- fl_studio_mcp/__init__.py +2 -0
- fl_studio_mcp/__main__.py +6 -0
- fl_studio_mcp/audio_analysis.py +220 -0
- fl_studio_mcp/bridge_client.py +373 -0
- fl_studio_mcp/cli.py +588 -0
- fl_studio_mcp/file_bridge.py +172 -0
- fl_studio_mcp/fl_bridge/device_FLStudioMCP.py +2236 -0
- fl_studio_mcp/fl_bridge/piano_roll/ComposeWithLLM.pyscript +222 -0
- fl_studio_mcp/fl_windows.py +311 -0
- fl_studio_mcp/gui_voice.py +472 -0
- fl_studio_mcp/keystroke.py +127 -0
- fl_studio_mcp/midi_wake.py +73 -0
- fl_studio_mcp/paths.py +32 -0
- fl_studio_mcp/prompts.py +136 -0
- fl_studio_mcp/protocol.py +32 -0
- fl_studio_mcp/resources/__init__.py +1 -0
- fl_studio_mcp/resources/project.py +81 -0
- fl_studio_mcp/server.py +81 -0
- fl_studio_mcp/tools/__init__.py +5 -0
- fl_studio_mcp/tools/_meta.py +67 -0
- fl_studio_mcp/tools/_toolsets.py +117 -0
- fl_studio_mcp/tools/arrangement.py +35 -0
- fl_studio_mcp/tools/audio.py +323 -0
- fl_studio_mcp/tools/automation.py +67 -0
- fl_studio_mcp/tools/channels.py +127 -0
- fl_studio_mcp/tools/generators.py +422 -0
- fl_studio_mcp/tools/meta.py +132 -0
- fl_studio_mcp/tools/mixer.py +101 -0
- fl_studio_mcp/tools/patterns.py +111 -0
- fl_studio_mcp/tools/piano_roll.py +195 -0
- fl_studio_mcp/tools/playlist.py +83 -0
- fl_studio_mcp/tools/plugins.py +93 -0
- fl_studio_mcp/tools/project.py +67 -0
- fl_studio_mcp/tools/transport.py +103 -0
- fl_studio_mcp/tools/ui.py +55 -0
- fl_studio_mcp/tools/voice.py +314 -0
- fl_studio_mcp/voice_to_midi.py +559 -0
- flmcp_studio-0.4.0.dist-info/METADATA +341 -0
- flmcp_studio-0.4.0.dist-info/RECORD +42 -0
- flmcp_studio-0.4.0.dist-info/WHEEL +4 -0
- flmcp_studio-0.4.0.dist-info/entry_points.txt +4 -0
- flmcp_studio-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Audio file analysis: tempo + key + onsets + melody extraction.
|
|
3
|
+
|
|
4
|
+
Works on any soundfile-readable format (WAV / FLAC / MP3 / OGG / AIFF).
|
|
5
|
+
Uses librosa for beat tracking, chroma-based key detection, onset detection
|
|
6
|
+
and melody extraction (pyin on the whole mix — best guess for the most
|
|
7
|
+
prominent monophonic line).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
import tempfile
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
# numpy / librosa / soundfile are heavy optional deps (the `audio` extra) and are
|
|
21
|
+
# imported lazily inside the functions that need them, so importing this module
|
|
22
|
+
# (e.g. when the MCP server registers the audio tools) does not require them.
|
|
23
|
+
|
|
24
|
+
from .voice_to_midi import Note, transcribe_monophonic, transcribe_polyphonic
|
|
25
|
+
|
|
26
|
+
log = logging.getLogger("fl_studio_mcp.audio_analysis")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# Key profiles (Krumhansl-Schmuckler) for major/minor key detection. Kept as
|
|
30
|
+
# plain Python tuples so this module imports without numpy; converted to arrays
|
|
31
|
+
# lazily inside `_estimate_key`.
|
|
32
|
+
_KEY_PROFILE_MAJOR = (6.35, 2.23, 3.48, 2.33, 4.38, 4.09,
|
|
33
|
+
2.52, 5.19, 2.39, 3.66, 2.29, 2.88)
|
|
34
|
+
_KEY_PROFILE_MINOR = (6.33, 2.68, 3.52, 5.38, 2.60, 3.53,
|
|
35
|
+
2.54, 4.75, 3.98, 2.69, 3.34, 3.17)
|
|
36
|
+
_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class AudioAnalysis:
|
|
41
|
+
path: str
|
|
42
|
+
duration_sec: float
|
|
43
|
+
samplerate: int
|
|
44
|
+
tempo_bpm: float
|
|
45
|
+
beats_sec: list[float]
|
|
46
|
+
onsets_sec: list[float]
|
|
47
|
+
key_root: str
|
|
48
|
+
key_scale: str # "major" | "minor"
|
|
49
|
+
key_confidence: float # 0..1
|
|
50
|
+
loudness_db: float
|
|
51
|
+
energy_rms: float
|
|
52
|
+
notes: list[Note] = field(default_factory=list)
|
|
53
|
+
|
|
54
|
+
def as_dict(self) -> dict:
|
|
55
|
+
return {
|
|
56
|
+
"path": self.path,
|
|
57
|
+
"duration_sec": round(self.duration_sec, 2),
|
|
58
|
+
"samplerate": self.samplerate,
|
|
59
|
+
"tempo_bpm": round(self.tempo_bpm, 1),
|
|
60
|
+
"beats_count": len(self.beats_sec),
|
|
61
|
+
"onsets_count": len(self.onsets_sec),
|
|
62
|
+
"key": f"{self.key_root} {self.key_scale}",
|
|
63
|
+
"key_root": self.key_root,
|
|
64
|
+
"key_scale": self.key_scale,
|
|
65
|
+
"key_confidence": round(self.key_confidence, 3),
|
|
66
|
+
"loudness_db": round(self.loudness_db, 1),
|
|
67
|
+
"energy_rms": round(self.energy_rms, 4),
|
|
68
|
+
"beats_sec": [round(b, 3) for b in self.beats_sec[:32]],
|
|
69
|
+
"onsets_sec": [round(o, 3) for o in self.onsets_sec[:32]],
|
|
70
|
+
"notes_count": len(self.notes),
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def load_audio(path: str | Path, target_sr: int = 22050) -> tuple[Any, int]:
|
|
75
|
+
"""Load any audio file (WAV/MP3/FLAC/OGG) as mono float32 (numpy array)."""
|
|
76
|
+
import librosa
|
|
77
|
+
y, sr = librosa.load(str(path), sr=target_sr, mono=True)
|
|
78
|
+
return y, sr
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def analyze_audio(path: str | Path,
|
|
82
|
+
extract_melody: bool = False,
|
|
83
|
+
target_sr: int = 22050,
|
|
84
|
+
polyphonic: bool = False) -> AudioAnalysis:
|
|
85
|
+
"""Full analysis: tempo, key, onsets, loudness, (optional) melody/notes.
|
|
86
|
+
|
|
87
|
+
When `extract_melody` is set, `polyphonic=True` runs Spotify Basic Pitch to
|
|
88
|
+
capture chords / all notes; otherwise the monophonic pyin engine extracts a
|
|
89
|
+
single dominant line.
|
|
90
|
+
"""
|
|
91
|
+
import librosa
|
|
92
|
+
import numpy as np
|
|
93
|
+
|
|
94
|
+
path = str(path)
|
|
95
|
+
if not os.path.exists(path):
|
|
96
|
+
raise FileNotFoundError(path)
|
|
97
|
+
|
|
98
|
+
y, sr = load_audio(path, target_sr=target_sr)
|
|
99
|
+
duration = len(y) / sr
|
|
100
|
+
|
|
101
|
+
# Tempo & beats
|
|
102
|
+
try:
|
|
103
|
+
tempo_arr, beats = librosa.beat.beat_track(y=y, sr=sr)
|
|
104
|
+
tempo = float(tempo_arr.item() if hasattr(tempo_arr, "item") else tempo_arr)
|
|
105
|
+
beats_sec = librosa.frames_to_time(beats, sr=sr).tolist()
|
|
106
|
+
except Exception as e:
|
|
107
|
+
log.warning("beat tracking failed: %s", e)
|
|
108
|
+
tempo = 0.0
|
|
109
|
+
beats_sec = []
|
|
110
|
+
|
|
111
|
+
# Onsets
|
|
112
|
+
try:
|
|
113
|
+
onsets = librosa.onset.onset_detect(y=y, sr=sr, units="time")
|
|
114
|
+
onsets_sec = [float(o) for o in onsets]
|
|
115
|
+
except Exception as e:
|
|
116
|
+
log.warning("onset detection failed: %s", e)
|
|
117
|
+
onsets_sec = []
|
|
118
|
+
|
|
119
|
+
# Key via chroma + Krumhansl-Schmuckler
|
|
120
|
+
try:
|
|
121
|
+
chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
|
|
122
|
+
pc_mean = chroma.mean(axis=1)
|
|
123
|
+
key_root, key_scale, key_conf = _estimate_key(pc_mean)
|
|
124
|
+
except Exception as e:
|
|
125
|
+
log.warning("key estimation failed: %s", e)
|
|
126
|
+
key_root, key_scale, key_conf = "C", "major", 0.0
|
|
127
|
+
|
|
128
|
+
# Loudness + RMS
|
|
129
|
+
rms = float(np.sqrt(np.mean(y * y))) if y.size else 0.0
|
|
130
|
+
loudness_db = 20.0 * math.log10(max(rms, 1e-9))
|
|
131
|
+
|
|
132
|
+
a = AudioAnalysis(
|
|
133
|
+
path=path,
|
|
134
|
+
duration_sec=duration,
|
|
135
|
+
samplerate=sr,
|
|
136
|
+
tempo_bpm=tempo,
|
|
137
|
+
beats_sec=beats_sec,
|
|
138
|
+
onsets_sec=onsets_sec,
|
|
139
|
+
key_root=key_root,
|
|
140
|
+
key_scale=key_scale,
|
|
141
|
+
key_confidence=key_conf,
|
|
142
|
+
loudness_db=loudness_db,
|
|
143
|
+
energy_rms=rms,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
if extract_melody:
|
|
147
|
+
if polyphonic:
|
|
148
|
+
# Basic Pitch: polyphonic, captures chords / all notes in the mix.
|
|
149
|
+
a.notes = transcribe_polyphonic(path, min_note_sec=0.1)
|
|
150
|
+
else:
|
|
151
|
+
# pyin on the full mix — best-effort monophonic extraction.
|
|
152
|
+
# Works well on vocals / lead lines, less so on dense mixes.
|
|
153
|
+
a.notes = transcribe_monophonic(path, min_note_sec=0.1,
|
|
154
|
+
merge_gap_sec=0.15,
|
|
155
|
+
semitone_tolerance=1.2,
|
|
156
|
+
hysteresis_sec=0.08)
|
|
157
|
+
|
|
158
|
+
return a
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _estimate_key(pc_mean) -> tuple[str, str, float]:
|
|
162
|
+
"""Krumhansl-Schmuckler key profile correlation."""
|
|
163
|
+
import numpy as np
|
|
164
|
+
|
|
165
|
+
profile_major = np.array(_KEY_PROFILE_MAJOR)
|
|
166
|
+
profile_minor = np.array(_KEY_PROFILE_MINOR)
|
|
167
|
+
pc_mean = np.asarray(pc_mean, dtype=float)
|
|
168
|
+
pc = pc_mean / (pc_mean.sum() + 1e-9)
|
|
169
|
+
best_name, best_scale, best_corr = "C", "major", -2.0
|
|
170
|
+
for i in range(12):
|
|
171
|
+
maj_shifted = np.roll(profile_major, i)
|
|
172
|
+
min_shifted = np.roll(profile_minor, i)
|
|
173
|
+
corr_maj = float(np.corrcoef(pc, maj_shifted)[0, 1])
|
|
174
|
+
corr_min = float(np.corrcoef(pc, min_shifted)[0, 1])
|
|
175
|
+
if corr_maj > best_corr:
|
|
176
|
+
best_corr = corr_maj
|
|
177
|
+
best_name = _NAMES[i]
|
|
178
|
+
best_scale = "major"
|
|
179
|
+
if corr_min > best_corr:
|
|
180
|
+
best_corr = corr_min
|
|
181
|
+
best_name = _NAMES[i]
|
|
182
|
+
best_scale = "minor"
|
|
183
|
+
confidence = max(0.0, min(1.0, (best_corr + 1.0) / 2.0))
|
|
184
|
+
return best_name, best_scale, confidence
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def slice_at_onsets(path: str | Path,
|
|
188
|
+
output_dir: str | Path | None = None,
|
|
189
|
+
max_slices: int = 32,
|
|
190
|
+
min_slice_sec: float = 0.25,
|
|
191
|
+
pad_before_sec: float = 0.01,
|
|
192
|
+
pad_after_sec: float = 0.05) -> list[str]:
|
|
193
|
+
"""Slice the input audio at detected onsets. Writes WAV files to disk."""
|
|
194
|
+
import librosa
|
|
195
|
+
import soundfile as sf
|
|
196
|
+
|
|
197
|
+
y, sr = load_audio(path)
|
|
198
|
+
onsets = librosa.onset.onset_detect(y=y, sr=sr, units="samples")
|
|
199
|
+
if len(onsets) == 0:
|
|
200
|
+
return []
|
|
201
|
+
|
|
202
|
+
out_dir = Path(output_dir) if output_dir else Path(tempfile.gettempdir()) / "fLMCP_slices"
|
|
203
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
204
|
+
|
|
205
|
+
src_stem = Path(path).stem
|
|
206
|
+
written: list[str] = []
|
|
207
|
+
total = len(y)
|
|
208
|
+
for i in range(min(len(onsets), max_slices)):
|
|
209
|
+
start = int(max(0, onsets[i] - pad_before_sec * sr))
|
|
210
|
+
end = int(min(total,
|
|
211
|
+
onsets[i + 1] + pad_after_sec * sr if i + 1 < len(onsets)
|
|
212
|
+
else total))
|
|
213
|
+
if (end - start) / sr < min_slice_sec:
|
|
214
|
+
continue
|
|
215
|
+
slice_wav = y[start:end]
|
|
216
|
+
dest = out_dir / f"{src_stem}_slice_{i:03d}.wav"
|
|
217
|
+
sf.write(str(dest), slice_wav, sr, subtype="PCM_16")
|
|
218
|
+
written.append(str(dest))
|
|
219
|
+
|
|
220
|
+
return written
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""Synchronous file client for the fLMCP controller."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import errno
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Callable, Iterator
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
from functools import cached_property
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from tempfile import NamedTemporaryFile
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from . import paths
|
|
21
|
+
from .midi_wake import find_wake_sender
|
|
22
|
+
from .protocol import (
|
|
23
|
+
COMMAND_NAME,
|
|
24
|
+
HEARTBEAT_NAME,
|
|
25
|
+
LOCK_NAME,
|
|
26
|
+
MAX_BATCH_ACTIONS,
|
|
27
|
+
PROTOCOL,
|
|
28
|
+
RESPONSE_NAME,
|
|
29
|
+
RPCError,
|
|
30
|
+
encode_command,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger("fl_studio_mcp.bridge")
|
|
34
|
+
|
|
35
|
+
POLL_INTERVAL = 0.008
|
|
36
|
+
HEARTBEAT_MAX_AGE = 5.0
|
|
37
|
+
WAKE_PROBE_TIMEOUT = 0.20
|
|
38
|
+
WAKE_RETRY_INTERVAL = 0.10
|
|
39
|
+
AUTOMATION_WAKE_INTERVAL = 0.02
|
|
40
|
+
AUTOMATION_START_GRACE = 1.0 # arming settle time plus one heartbeat interval
|
|
41
|
+
IDLE_OBSERVATION_WINDOW = 1.25
|
|
42
|
+
UNAVAILABLE = (
|
|
43
|
+
"bridge unavailable: FL Studio not running or fLMCP Bridge script not enabled"
|
|
44
|
+
" — see fl_ping / docs"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
_request_lock = threading.Lock()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _read_object(path: Path) -> dict[str, Any]:
|
|
51
|
+
try:
|
|
52
|
+
value = json.loads(path.read_bytes().decode("utf-8"))
|
|
53
|
+
except (OSError, ValueError, RecursionError):
|
|
54
|
+
return {}
|
|
55
|
+
return value if isinstance(value, dict) else {}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _explain(error: str) -> str:
|
|
59
|
+
"""Add the likely cause to FL's terse "Operation unsafe at current time"."""
|
|
60
|
+
if "unsafe" not in error.lower():
|
|
61
|
+
return error
|
|
62
|
+
from .fl_windows import open_dialogs
|
|
63
|
+
|
|
64
|
+
dialogs = open_dialogs()
|
|
65
|
+
if dialogs:
|
|
66
|
+
names = ", ".join(f"'{title}'" for title in dialogs)
|
|
67
|
+
return f"{error} (FL is showing a dialog: {names}. Answer or close it in FL, then retry.)"
|
|
68
|
+
return f"{error} (FL is busy, e.g. a dialog is open or a plugin is loading. Retry shortly.)"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _finite_non_negative(value: Any) -> bool:
|
|
72
|
+
return type(value) in (int, float) and math.isfinite(value) and value >= 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _sleep_until(deadline: float, interval: float = POLL_INTERVAL) -> None:
|
|
76
|
+
time.sleep(max(0.0, min(interval, deadline - time.monotonic())))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@contextmanager
|
|
80
|
+
def _process_lock(path: Path, deadline: float) -> Iterator[None]:
|
|
81
|
+
# Never delete the lock file: waiters must lock the same file even if a
|
|
82
|
+
# holder exits. Windows permits byte-range locking past end of file.
|
|
83
|
+
with path.open("a+b") as lock_file:
|
|
84
|
+
fd = lock_file.fileno()
|
|
85
|
+
if sys.platform == "win32":
|
|
86
|
+
import msvcrt
|
|
87
|
+
|
|
88
|
+
def acquire() -> None:
|
|
89
|
+
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
|
|
90
|
+
|
|
91
|
+
def release() -> None:
|
|
92
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
|
|
93
|
+
else:
|
|
94
|
+
import fcntl
|
|
95
|
+
|
|
96
|
+
def acquire() -> None:
|
|
97
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
98
|
+
|
|
99
|
+
def release() -> None:
|
|
100
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
101
|
+
|
|
102
|
+
while True:
|
|
103
|
+
try:
|
|
104
|
+
acquire()
|
|
105
|
+
break
|
|
106
|
+
except OSError as error:
|
|
107
|
+
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
|
108
|
+
raise
|
|
109
|
+
if time.monotonic() >= deadline:
|
|
110
|
+
raise TimeoutError("timed out waiting for the bridge lock") from error
|
|
111
|
+
_sleep_until(deadline)
|
|
112
|
+
try:
|
|
113
|
+
yield
|
|
114
|
+
finally:
|
|
115
|
+
release()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _try_wake(sender: Callable[[], bool] | None) -> None:
|
|
119
|
+
if sender is not None:
|
|
120
|
+
try:
|
|
121
|
+
sender()
|
|
122
|
+
except OSError:
|
|
123
|
+
log.debug("MIDI wake failed", exc_info=True)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class BridgeClient:
|
|
127
|
+
def __init__(self, timeout: float | None = None, *, bridge_dir: str | Path | None = None):
|
|
128
|
+
self.timeout = float(os.environ.get("FLMCP_TIMEOUT", "10") if timeout is None else timeout)
|
|
129
|
+
if not math.isfinite(self.timeout) or self.timeout <= 0:
|
|
130
|
+
raise ValueError("FLMCP_TIMEOUT must be a positive, finite number of seconds")
|
|
131
|
+
self.bridge_dir = Path(bridge_dir) if bridge_dir is not None else paths.bridge_dir()
|
|
132
|
+
self.command_file = self.bridge_dir / COMMAND_NAME
|
|
133
|
+
self.response_file = self.bridge_dir / RESPONSE_NAME
|
|
134
|
+
self.heartbeat_file = self.bridge_dir / HEARTBEAT_NAME
|
|
135
|
+
self._last_id = 0
|
|
136
|
+
self._pump_lock = threading.Lock()
|
|
137
|
+
self._pump_until = 0.0
|
|
138
|
+
self._pump_limit = 0.0
|
|
139
|
+
self._pumping = False
|
|
140
|
+
|
|
141
|
+
@cached_property
|
|
142
|
+
def _wake_sender(self) -> Callable[[], bool] | None:
|
|
143
|
+
return find_wake_sender()
|
|
144
|
+
|
|
145
|
+
def close(self) -> None:
|
|
146
|
+
"""Reset MIDI output discovery. The file transport has no connection to close."""
|
|
147
|
+
with _request_lock:
|
|
148
|
+
self.__dict__.pop("_wake_sender", None)
|
|
149
|
+
|
|
150
|
+
def _fresh_heartbeat(self) -> dict[str, Any]:
|
|
151
|
+
heartbeat = _read_object(self.heartbeat_file)
|
|
152
|
+
ts = heartbeat.get("ts")
|
|
153
|
+
now = time.time()
|
|
154
|
+
if (
|
|
155
|
+
heartbeat.get("protocol") == PROTOCOL
|
|
156
|
+
and type(ts) in (int, float)
|
|
157
|
+
and ts > 0
|
|
158
|
+
and now - HEARTBEAT_MAX_AGE <= ts <= now + HEARTBEAT_MAX_AGE
|
|
159
|
+
):
|
|
160
|
+
return heartbeat
|
|
161
|
+
return {}
|
|
162
|
+
|
|
163
|
+
def is_connected(self) -> bool:
|
|
164
|
+
return bool(self._fresh_heartbeat())
|
|
165
|
+
|
|
166
|
+
def _require_heartbeat(self, action: str, deadline: float) -> dict[str, Any]:
|
|
167
|
+
heartbeat = self._fresh_heartbeat()
|
|
168
|
+
if heartbeat:
|
|
169
|
+
return heartbeat
|
|
170
|
+
|
|
171
|
+
# A wake-only controller cannot refresh its heartbeat between calls.
|
|
172
|
+
# Probe before writing anything so a dead controller leaves no queued edit.
|
|
173
|
+
sender = self._wake_sender
|
|
174
|
+
if sender is not None:
|
|
175
|
+
probe_deadline = min(deadline, time.monotonic() + WAKE_PROBE_TIMEOUT)
|
|
176
|
+
next_wake = 0.0
|
|
177
|
+
while time.monotonic() < probe_deadline:
|
|
178
|
+
now = time.monotonic()
|
|
179
|
+
if now >= next_wake:
|
|
180
|
+
_try_wake(sender)
|
|
181
|
+
next_wake = now + WAKE_RETRY_INTERVAL
|
|
182
|
+
heartbeat = self._fresh_heartbeat()
|
|
183
|
+
if heartbeat:
|
|
184
|
+
return heartbeat
|
|
185
|
+
_sleep_until(probe_deadline)
|
|
186
|
+
raise RPCError(action, UNAVAILABLE)
|
|
187
|
+
|
|
188
|
+
def _next_id(self, heartbeat: dict[str, Any]) -> int:
|
|
189
|
+
# Read the shared high-water marks under the cross-process lock. This
|
|
190
|
+
# also handles clock rollback between calls or MCP process restarts.
|
|
191
|
+
seen_ids = (
|
|
192
|
+
heartbeat.get("last_id"),
|
|
193
|
+
_read_object(self.command_file).get("id"),
|
|
194
|
+
_read_object(self.response_file).get("id"),
|
|
195
|
+
self._last_id,
|
|
196
|
+
)
|
|
197
|
+
self._last_id = max(time.time_ns(), max(i for i in seen_ids if type(i) is int) + 1)
|
|
198
|
+
return self._last_id
|
|
199
|
+
|
|
200
|
+
def _write_command(self, body: bytes, deadline: float) -> None:
|
|
201
|
+
deadline = min(deadline, time.monotonic() + 0.25)
|
|
202
|
+
temporary = None
|
|
203
|
+
try:
|
|
204
|
+
with NamedTemporaryFile(dir=self.bridge_dir, prefix="mcp_command.", suffix=".tmp",
|
|
205
|
+
delete=False) as output:
|
|
206
|
+
temporary = Path(output.name)
|
|
207
|
+
output.write(body)
|
|
208
|
+
while True:
|
|
209
|
+
try:
|
|
210
|
+
os.replace(temporary, self.command_file)
|
|
211
|
+
return
|
|
212
|
+
except PermissionError:
|
|
213
|
+
# Windows can deny replace while the controller has the file open.
|
|
214
|
+
if time.monotonic() >= deadline:
|
|
215
|
+
raise
|
|
216
|
+
_sleep_until(deadline)
|
|
217
|
+
finally:
|
|
218
|
+
if temporary is not None:
|
|
219
|
+
try:
|
|
220
|
+
temporary.unlink(missing_ok=True)
|
|
221
|
+
except OSError:
|
|
222
|
+
log.debug("could not remove bridge temporary file", exc_info=True)
|
|
223
|
+
|
|
224
|
+
def _wait_for_response(self, action: str, request_id: int, deadline: float) -> dict[str, Any]:
|
|
225
|
+
sender = self._wake_sender
|
|
226
|
+
next_wake = 0.0
|
|
227
|
+
next_health_check = time.monotonic() + 0.25
|
|
228
|
+
while time.monotonic() < deadline:
|
|
229
|
+
now = time.monotonic()
|
|
230
|
+
if now >= next_wake:
|
|
231
|
+
_try_wake(sender)
|
|
232
|
+
next_wake = now + WAKE_RETRY_INTERVAL
|
|
233
|
+
response = _read_object(self.response_file)
|
|
234
|
+
response_id = response.get("id")
|
|
235
|
+
if type(response_id) is int and response_id == request_id and type(response.get("ok")) is bool:
|
|
236
|
+
return response
|
|
237
|
+
if now >= next_health_check:
|
|
238
|
+
try:
|
|
239
|
+
self._require_heartbeat(action, deadline)
|
|
240
|
+
except RPCError as error:
|
|
241
|
+
raise RPCError(action, f"{error.message}; execution status unknown") from error
|
|
242
|
+
next_health_check = now + 0.25
|
|
243
|
+
_sleep_until(deadline)
|
|
244
|
+
raise RPCError(action, f"no response within {self.timeout:g}s; execution status unknown")
|
|
245
|
+
|
|
246
|
+
def _start_async_wake_pump(self, results: list[Any], idle_calls: int) -> None:
|
|
247
|
+
sender = self._wake_sender
|
|
248
|
+
if sender is None:
|
|
249
|
+
return
|
|
250
|
+
durations, limits = [], []
|
|
251
|
+
for result in results:
|
|
252
|
+
if not isinstance(result, dict) or result.get("mode") != "async":
|
|
253
|
+
continue
|
|
254
|
+
duration = result.get("approx_duration_sec")
|
|
255
|
+
if _finite_non_negative(duration):
|
|
256
|
+
durations.append(duration)
|
|
257
|
+
start_timeout = result.get("start_timeout_sec")
|
|
258
|
+
limits.append(duration + (start_timeout if _finite_non_negative(start_timeout) else 0))
|
|
259
|
+
if not durations:
|
|
260
|
+
return
|
|
261
|
+
|
|
262
|
+
with self._pump_lock:
|
|
263
|
+
now = time.monotonic()
|
|
264
|
+
self._pump_until = max(self._pump_until, now + max(durations) + AUTOMATION_START_GRACE)
|
|
265
|
+
# Keep waking past that while the bridge reports a recording in progress
|
|
266
|
+
# (e.g. waiting for FL's record prompt), up to the bridge's start timeout.
|
|
267
|
+
self._pump_limit = max(self._pump_limit, now + max(limits) + AUTOMATION_START_GRACE)
|
|
268
|
+
if self._pumping:
|
|
269
|
+
return
|
|
270
|
+
self._pumping = True
|
|
271
|
+
pump = threading.Thread(target=self._pump_wakes, args=(sender, idle_calls),
|
|
272
|
+
name="flmcp-automation-wake", daemon=True)
|
|
273
|
+
try:
|
|
274
|
+
pump.start()
|
|
275
|
+
except RuntimeError:
|
|
276
|
+
self._pumping = False
|
|
277
|
+
log.warning("could not start automation wake pump", exc_info=True)
|
|
278
|
+
|
|
279
|
+
def _pump_wakes(self, sender: Callable[[], bool], idle_calls: int) -> None:
|
|
280
|
+
idle_active_until = 0.0
|
|
281
|
+
while True:
|
|
282
|
+
now = time.monotonic()
|
|
283
|
+
heartbeat = self._fresh_heartbeat()
|
|
284
|
+
with self._pump_lock:
|
|
285
|
+
recording = bool(heartbeat.get("automation")) and now < self._pump_limit
|
|
286
|
+
if now >= self._pump_until and not recording:
|
|
287
|
+
self._pumping = False
|
|
288
|
+
return
|
|
289
|
+
observed = heartbeat.get("idle_calls", idle_calls)
|
|
290
|
+
if type(observed) is int and observed != idle_calls:
|
|
291
|
+
if observed > idle_calls:
|
|
292
|
+
idle_active_until = now + IDLE_OBSERVATION_WINDOW
|
|
293
|
+
else:
|
|
294
|
+
idle_active_until = 0.0 # Controller reloaded since the previous sample.
|
|
295
|
+
idle_calls = observed
|
|
296
|
+
if now >= idle_active_until:
|
|
297
|
+
_try_wake(sender)
|
|
298
|
+
time.sleep(AUTOMATION_WAKE_INTERVAL)
|
|
299
|
+
|
|
300
|
+
def _exchange(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
301
|
+
deadline = time.monotonic() + self.timeout
|
|
302
|
+
if not _request_lock.acquire(timeout=self.timeout):
|
|
303
|
+
raise RPCError(action, "timed out waiting for the in-process bridge lock")
|
|
304
|
+
try:
|
|
305
|
+
self._require_heartbeat(action, deadline)
|
|
306
|
+
with _process_lock(self.bridge_dir / LOCK_NAME, deadline):
|
|
307
|
+
heartbeat = self._require_heartbeat(action, deadline)
|
|
308
|
+
if time.monotonic() >= deadline:
|
|
309
|
+
raise TimeoutError("timed out before dispatch")
|
|
310
|
+
request_id = self._next_id(heartbeat)
|
|
311
|
+
self._write_command(encode_command(request_id, payload), deadline)
|
|
312
|
+
try:
|
|
313
|
+
response = self._wait_for_response(action, request_id, deadline)
|
|
314
|
+
except RPCError:
|
|
315
|
+
# Replace any unread command with a no-op while preserving the ID.
|
|
316
|
+
# A handler that already started may still finish.
|
|
317
|
+
try:
|
|
318
|
+
self._write_command(encode_command(request_id, {"batch": []}),
|
|
319
|
+
time.monotonic() + 0.05)
|
|
320
|
+
except OSError:
|
|
321
|
+
log.warning("could not clear timed-out bridge command %s", request_id)
|
|
322
|
+
raise
|
|
323
|
+
if not response["ok"]:
|
|
324
|
+
raise RPCError(action, _explain(str(response.get("error") or "unknown error")))
|
|
325
|
+
|
|
326
|
+
if "batch" in payload:
|
|
327
|
+
records = response.get("results")
|
|
328
|
+
if (
|
|
329
|
+
not isinstance(records, list)
|
|
330
|
+
or len(records) != len(payload["batch"])
|
|
331
|
+
or any(not isinstance(item, dict) for item in records)
|
|
332
|
+
):
|
|
333
|
+
raise RPCError(action, "invalid batch response")
|
|
334
|
+
results = [item.get("result") for item in records if item.get("ok")]
|
|
335
|
+
else:
|
|
336
|
+
if "result" not in response:
|
|
337
|
+
raise RPCError(action, "missing result in response")
|
|
338
|
+
results = [response["result"]]
|
|
339
|
+
|
|
340
|
+
idle_calls = heartbeat.get("idle_calls")
|
|
341
|
+
self._start_async_wake_pump(results, idle_calls if type(idle_calls) is int else 0)
|
|
342
|
+
return response
|
|
343
|
+
except TimeoutError as error:
|
|
344
|
+
raise RPCError(action, str(error)) from error
|
|
345
|
+
except OSError as error:
|
|
346
|
+
raise RPCError(action, f"{UNAVAILABLE} ({error})") from error
|
|
347
|
+
finally:
|
|
348
|
+
_request_lock.release()
|
|
349
|
+
|
|
350
|
+
def call(self, action: str, **params: Any) -> Any:
|
|
351
|
+
return self._exchange(action, {"action": action, "params": params}).get("result")
|
|
352
|
+
|
|
353
|
+
def call_batch(self, actions: list[tuple[str, dict]]) -> list[dict[str, Any]]:
|
|
354
|
+
"""Run up to 32 actions in order, returning one success/error record per action."""
|
|
355
|
+
if len(actions) > MAX_BATCH_ACTIONS:
|
|
356
|
+
raise RPCError("batch", f"expected at most {MAX_BATCH_ACTIONS} actions")
|
|
357
|
+
payload = {"batch": [{"action": action, "params": params} for action, params in actions]}
|
|
358
|
+
return self._exchange("batch", payload)["results"]
|
|
359
|
+
|
|
360
|
+
def ping(self) -> dict:
|
|
361
|
+
return self.call("meta.ping")
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
_singleton: BridgeClient | None = None
|
|
365
|
+
_singleton_lock = threading.Lock()
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def get_client() -> BridgeClient:
|
|
369
|
+
global _singleton
|
|
370
|
+
with _singleton_lock:
|
|
371
|
+
if _singleton is None:
|
|
372
|
+
_singleton = BridgeClient()
|
|
373
|
+
return _singleton
|