conformtools 0.6.5 → 0.6.7

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 (149) hide show
  1. package/README.md +18 -13
  2. package/dist/account-DJTD3KYK.js +3 -0
  3. package/dist/arriraw-YIJ3BYNN.js +525 -0
  4. package/dist/avid-panel/MANIFEST.json +11 -0
  5. package/dist/avid-panel/avid-manifest.json +46 -0
  6. package/dist/avid-panel/icon.svg +4 -0
  7. package/dist/avid-panel/icons/conformtools.svg +4 -0
  8. package/dist/avid-panel/index.html +26 -0
  9. package/dist/avid-panel/panel.css +12 -0
  10. package/dist/avid-panel/panel.js +7 -0
  11. package/dist/bridge-JQF4V3V2.js +3 -0
  12. package/dist/browser/timeline_core_bg.wasm +0 -0
  13. package/dist/chunk-2BPR6LK6.js +3 -0
  14. package/dist/chunk-3D3Z4TBR.js +3 -0
  15. package/dist/chunk-55BKURYP.js +378 -0
  16. package/dist/chunk-5WEZRGXG.js +39 -0
  17. package/dist/chunk-6V4OEOOX.js +3 -0
  18. package/dist/chunk-7D7H6VFW.js +3 -0
  19. package/dist/chunk-A7FNR3T5.js +3 -0
  20. package/dist/chunk-AACY2V3L.js +3 -0
  21. package/dist/chunk-AMRJXYL4.js +3 -0
  22. package/dist/chunk-C2ESM27Z.js +3 -0
  23. package/dist/chunk-D4WPRRBT.js +3 -0
  24. package/dist/chunk-D6YDLKSA.js +3 -0
  25. package/dist/chunk-DKGGJM6Z.js +3 -0
  26. package/dist/chunk-EUBXH67N.js +7 -0
  27. package/dist/chunk-GK4YYKJ6.js +19 -0
  28. package/dist/chunk-GM6QKY7W.js +3 -0
  29. package/dist/chunk-J2JXLEAI.js +3 -0
  30. package/dist/chunk-JV7TZDKJ.js +3 -0
  31. package/dist/chunk-NAFLOZER.js +9 -0
  32. package/dist/chunk-NFJHWZJX.js +3 -0
  33. package/dist/chunk-NU3X7P4N.js +3 -0
  34. package/dist/chunk-P2LL3JMC.js +20 -0
  35. package/dist/chunk-PFISREY4.js +3 -0
  36. package/dist/chunk-PFZVET7S.js +3 -0
  37. package/dist/chunk-PHAMF4JF.js +4 -0
  38. package/dist/chunk-PLRB2YXJ.js +3 -0
  39. package/dist/chunk-PSANHDZM.js +3 -0
  40. package/dist/chunk-RGMTLNMF.js +3 -0
  41. package/dist/chunk-RJ6JA2LZ.js +3 -0
  42. package/dist/chunk-S5JDS5PQ.js +5 -0
  43. package/dist/chunk-SGLQY53R.js +3 -0
  44. package/dist/chunk-SKFMOLUO.js +8 -0
  45. package/dist/chunk-SNTAZJ5A.js +6 -0
  46. package/dist/chunk-TK55FA56.js +3 -0
  47. package/dist/chunk-TXQR2HI2.js +4 -0
  48. package/dist/chunk-VIBEEWPC.js +10 -0
  49. package/dist/chunk-WN53ARHJ.js +3 -0
  50. package/dist/chunk-XLEINKFL.js +5 -0
  51. package/dist/claude-setup-IIWUB4CE.js +5 -0
  52. package/dist/cli.js +17 -0
  53. package/dist/clip-state-B6JOX3JE.js +3 -0
  54. package/dist/conformtools-analyze +0 -0
  55. package/dist/conformtools-decode +0 -0
  56. package/dist/cr3-wasm-HLJWEV2S.js +3 -0
  57. package/dist/dng-wasm-CQDLPM5V.js +3 -0
  58. package/dist/dpx-wasm-TLGMM7BO.js +3 -0
  59. package/dist/engine-P6H5P6HP.js +5 -0
  60. package/dist/esm-SFFBP7PS.js +3 -0
  61. package/dist/exr-wasm-2NPKPTVB.js +3 -0
  62. package/dist/flame/hook/conformtools_flame/__init__.py +10 -0
  63. package/dist/flame/hook/conformtools_flame/building.py +191 -0
  64. package/dist/flame/hook/conformtools_flame/hook.py +177 -0
  65. package/dist/flame/hook/conformtools_flame/render.py +622 -0
  66. package/dist/flame/hook/conformtools_flame/util.py +33 -0
  67. package/dist/flame/hook/conformtools_flame/verbs.py +1037 -0
  68. package/dist/flame/hook/conformtools_flame_hook.py +42 -0
  69. package/dist/fonts/gfx/BarlowCondensed-Bold.ttf +0 -0
  70. package/dist/fonts/gfx/BarlowCondensed-Regular.ttf +0 -0
  71. package/dist/fonts/gfx/InstrumentSerif-Regular.ttf +0 -0
  72. package/dist/fonts/gfx/Inter-Bold.ttf +0 -0
  73. package/dist/fonts/gfx/Inter-Regular.ttf +0 -0
  74. package/dist/fonts/gfx/JetBrainsMono-Bold.ttf +0 -0
  75. package/dist/fonts/gfx/JetBrainsMono-Regular.ttf +0 -0
  76. package/dist/fonts/gfx/OFL.txt +100 -0
  77. package/dist/framing-SWOD4CWB.js +3 -0
  78. package/dist/gfx-worker.js +3 -0
  79. package/dist/h264-JJMZSUWW.js +3 -0
  80. package/dist/h264-mxf-DCUOGLDU.js +3 -0
  81. package/dist/host-relink-TWAF6WIG.js +10 -0
  82. package/dist/hosts-Z666EF7V.js +3 -0
  83. package/dist/http.js +5 -0
  84. package/dist/i2o-transfer +0 -0
  85. package/dist/inspect-FJKYPEXL.js +68 -0
  86. package/dist/isobmff-VJOWP4MH.js +3 -0
  87. package/dist/mc-video-5MGGOQN4.js +3 -0
  88. package/dist/mcp.js +13 -0
  89. package/dist/media-NZYVREUF.js +3 -0
  90. package/dist/media_core-YZ3PABEG.js +9 -0
  91. package/dist/media_core_bg-FDL7GJZP.js +3 -0
  92. package/dist/media_core_bg-XRBVKQZH.js +3 -0
  93. package/dist/mxf-FJSRFLJC.js +3 -0
  94. package/dist/nuke/panel/python/Startup/conformtools_nuke_startup.py +44 -0
  95. package/dist/nuke/panel/python/conformtools_nuke/__init__.py +10 -0
  96. package/dist/nuke/panel/python/conformtools_nuke/panel.py +217 -0
  97. package/dist/nuke/panel/python/conformtools_nuke/verbs.py +837 -0
  98. package/dist/ops-X7NAREC4.js +3 -0
  99. package/dist/peer-kit/ctpeer/__init__.py +21 -0
  100. package/dist/peer-kit/ctpeer/client.py +247 -0
  101. package/dist/peer-kit/ctpeer/neutral.py +178 -0
  102. package/dist/peer-kit/ctpeer/pairing.py +139 -0
  103. package/dist/peer-kit/ctpeer/protocol.py +209 -0
  104. package/dist/peer-kit/ctpeer/websocket.py +289 -0
  105. package/dist/premiere-uxp/icons/panel.png +0 -0
  106. package/dist/premiere-uxp/icons/panel@2x.png +0 -0
  107. package/dist/premiere-uxp/icons/plugin.png +0 -0
  108. package/dist/premiere-uxp/icons/plugin@2x.png +0 -0
  109. package/dist/premiere-uxp/index.html +38 -0
  110. package/dist/premiere-uxp/index.js +93 -0
  111. package/dist/premiere-uxp/lib/clipmeta.js +170 -0
  112. package/dist/premiere-uxp/lib/ctx.js +68 -0
  113. package/dist/premiere-uxp/lib/edit.js +516 -0
  114. package/dist/premiere-uxp/lib/handles.js +57 -0
  115. package/dist/premiere-uxp/lib/markers.js +198 -0
  116. package/dist/premiere-uxp/lib/pairing.js +67 -0
  117. package/dist/premiere-uxp/lib/premiere.js +91 -0
  118. package/dist/premiere-uxp/lib/probe.js +452 -0
  119. package/dist/premiere-uxp/lib/protocol.js +165 -0
  120. package/dist/premiere-uxp/lib/render.js +45 -0
  121. package/dist/premiere-uxp/lib/session.js +85 -0
  122. package/dist/premiere-uxp/lib/sizing.js +325 -0
  123. package/dist/premiere-uxp/lib/time.js +88 -0
  124. package/dist/premiere-uxp/lib/timeline.js +336 -0
  125. package/dist/premiere-uxp/lib/verbs.js +21 -0
  126. package/dist/premiere-uxp/lib/write.js +97 -0
  127. package/dist/premiere-uxp/manifest.json +102 -0
  128. package/dist/probe-F7WQHMIA.js +3 -0
  129. package/dist/prores-RIG37OIH.js +526 -0
  130. package/dist/r3d-CXUNG6VS.js +1025 -0
  131. package/dist/r3d-T5O6IIZZ.js +3 -0
  132. package/dist/resolve-bridge.py +2286 -0
  133. package/dist/resolve-presets/conform.tools.xml +127 -0
  134. package/dist/source-QGWWLMME.js +3 -0
  135. package/dist/statusline-GMMCFMOA.js +4 -0
  136. package/dist/statusline.js +3 -0
  137. package/dist/still-P4JJNTEO.js +3 -0
  138. package/dist/still-wasm-DN5LPASS.js +3 -0
  139. package/dist/store-7IOEBOZY.js +3 -0
  140. package/dist/tiff-wasm-BPRDR6EB.js +3 -0
  141. package/dist/timeline-DQG6TVPF.js +3 -0
  142. package/dist/timeline_core-IOENXK4Z.js +3 -0
  143. package/dist/timeline_core_bg-JW42YM3G.js +3 -0
  144. package/dist/udf_bg-B37GKRIH.js +3 -0
  145. package/dist/wasm/media_core_bg.wasm +0 -0
  146. package/dist/wasm/udf_bg.wasm +0 -0
  147. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  148. package/dist/wav-64SC6P7U.js +3 -0
  149. package/package.json +6 -4
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
3
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-2BPR6LK6.js";import"./chunk-PSANHDZM.js";export{c as CoverageMissError,e as DeliveryCoverageMissError,a as INTENTS,f as asDeliveryCoverageMiss,h as extract,i as mediaOp,d as parseDeliveryCoverageMiss,g as resolveFormat,b as unpackFrame16};
@@ -0,0 +1,21 @@
1
+ """ctpeer - the CONFORM.TOOLS host-bridge peer kit for Python hosts.
2
+
3
+ Stdlib only (Python 3.9 - 3.13): Autodesk Flame and Foundry Nuke Studio /
4
+ Hiero ship their own interpreters and nothing may be pip-installed into them.
5
+ One copy lives in `mcp/hosts/peer-kit/ctpeer/`; each host package vendors
6
+ it at package time (`mcp/hosts/peer-kit/vendor.py`).
7
+
8
+ websocket.py RFC 6455 client (loopback ws:// only, masked, ping/pong, cap)
9
+ pairing.py finding pairing.json the way the app writes it
10
+ protocol.py handle table, the verb dispatcher, `idle_marshaller`
11
+ client.py connect / hello / request loop / reconnect / events
12
+ neutral.py timecode, marker colour names, the `[ct:...]` note token
13
+
14
+ Wire protocol and threat model: docs/INTERNAL_HOST_BRIDGE.md.
15
+ """
16
+
17
+ from .client import BridgeClient
18
+ from .protocol import PROTOCOL_VERSION, Dispatcher, Handles, PeerError, idle_marshaller, off_main
19
+
20
+ __version__ = "1.1.0"
21
+ __all__ = ["BridgeClient", "Dispatcher", "Handles", "PeerError", "PROTOCOL_VERSION", "idle_marshaller", "off_main", "__version__"]
@@ -0,0 +1,247 @@
1
+ """The bridge client: pairing -> connect -> hello -> answer requests, with
2
+ reconnect. Runs on its own daemon threads; every host call goes through the
3
+ host's `run_on_main` (Flame: `flame.schedule_idle_event`; Nuke:
4
+ `hiero.core.executeInMainThreadWithResult`), so the host API is only ever
5
+ touched on the host's main thread.
6
+
7
+ client = BridgeClient(host={"id": "flame", "name": "Flame", "version": "2026", "platform": "linux"},
8
+ capabilities=[...], optional_verbs=[...], verbs={"session.name": fn, ...},
9
+ run_on_main=run_on_main)
10
+ client.start() # returns at once; connects in the background
11
+ client.event("timeline_changed", {"name": "CUT_v2"})
12
+ client.stop()
13
+
14
+ Threads: the CONNECTOR (pairing, backoff, the read loop: pings, closes and
15
+ requests are read here, so a slow verb never stops a pong) and one WORKER that
16
+ runs requests in arrival order and sends each answer. A peer never sends a
17
+ request: `event` is the only unsolicited message, and the app treats it as
18
+ inert JSON.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import queue
25
+ import threading
26
+ from typing import Any, Callable, Dict, Iterable, Optional
27
+
28
+ from . import pairing as pairing_mod
29
+ from .protocol import PROTOCOL_VERSION, Dispatcher, hello
30
+ from .websocket import MAX_MESSAGE_BYTES, ConnectionClosed, WebSocket, WebSocketError
31
+
32
+ RECONNECT_S = (0.5, 1.0, 2.0, 4.0, 8.0, 15.0)
33
+
34
+ #: States `on_state` reports, in the order a good connection walks them.
35
+ STATES = ("idle", "unpaired", "connecting", "hello", "connected", "refused", "closed", "stopped")
36
+
37
+
38
+ class BridgeClient:
39
+ def __init__(self, host: Dict[str, Any], capabilities: Iterable[str], verbs: Dict[str, Callable[..., Any]],
40
+ optional_verbs: Iterable[str] = (), run_on_main: Optional[Callable[[Callable[[], Any]], Any]] = None,
41
+ read_pairing: Optional[Callable[[], Dict[str, Any]]] = None,
42
+ log: Optional[Callable[[str], None]] = None,
43
+ on_state: Optional[Callable[[str, str], None]] = None,
44
+ reconnect: Iterable[float] = RECONNECT_S, try_preferred_ports: bool = True,
45
+ max_message: int = MAX_MESSAGE_BYTES, connect_timeout: float = 5.0):
46
+ self.host = dict(host)
47
+ self.capabilities = list(capabilities)
48
+ self.optional_verbs = list(optional_verbs)
49
+ self.dispatcher = Dispatcher(verbs, self.capabilities, run_on_main, log)
50
+ self.read_pairing = read_pairing or pairing_mod.read
51
+ self._log = log or (lambda line: None)
52
+ self._on_state = on_state
53
+ self.reconnect = tuple(reconnect) or RECONNECT_S
54
+ self.try_preferred_ports = try_preferred_ports
55
+ self.max_message = max_message
56
+ self.connect_timeout = connect_timeout
57
+ self.state = "idle"
58
+ self.detail = ""
59
+ self.app: Dict[str, Any] = {}
60
+ self.attempt = 0
61
+ self._ws: Optional[WebSocket] = None
62
+ self._stop = threading.Event()
63
+ self._connected = threading.Event()
64
+ self._thread: Optional[threading.Thread] = None
65
+ self._jobs: "queue.Queue[Optional[Dict[str, Any]]]" = queue.Queue()
66
+ self._worker: Optional[threading.Thread] = None
67
+ self._lock = threading.Lock()
68
+
69
+ # -- state -----------------------------------------------------------
70
+ def log(self, line: str) -> None:
71
+ try:
72
+ self._log(line)
73
+ except Exception:
74
+ pass
75
+
76
+ def _set_state(self, state: str, detail: str = "") -> None:
77
+ self.state, self.detail = state, detail
78
+ if self._on_state:
79
+ try:
80
+ self._on_state(state, detail)
81
+ except Exception:
82
+ pass
83
+
84
+ @property
85
+ def connected(self) -> bool:
86
+ return self.state == "connected"
87
+
88
+ def wait_connected(self, timeout: float = 5.0) -> bool:
89
+ return self._connected.wait(timeout)
90
+
91
+ # -- lifecycle -------------------------------------------------------
92
+ def start(self) -> None:
93
+ with self._lock:
94
+ if self._thread and self._thread.is_alive():
95
+ return
96
+ self._stop.clear()
97
+ self.attempt = 0
98
+ self._worker = threading.Thread(target=self._work, name="ctpeer-worker", daemon=True)
99
+ self._worker.start()
100
+ self._thread = threading.Thread(target=self._run, name="ctpeer-connector", daemon=True)
101
+ self._thread.start()
102
+
103
+ def stop(self, join: float = 2.0) -> None:
104
+ self._stop.set()
105
+ ws = self._ws
106
+ if ws is not None:
107
+ try:
108
+ ws.close(1000, "plugin stopped")
109
+ except Exception:
110
+ pass
111
+ self._jobs.put(None)
112
+ for t in (self._thread, self._worker):
113
+ if t is not None and t is not threading.current_thread():
114
+ t.join(join)
115
+ self._connected.clear()
116
+ self._set_state("stopped")
117
+
118
+ # -- the connector ---------------------------------------------------
119
+ def _run(self) -> None:
120
+ while not self._stop.is_set():
121
+ fast = self._session()
122
+ if self._stop.is_set():
123
+ break
124
+ delay = self.reconnect[0] if fast else self.reconnect[min(self.attempt, len(self.reconnect) - 1)]
125
+ self.attempt += 1
126
+ self._stop.wait(delay)
127
+
128
+ def _session(self) -> bool:
129
+ """One connection attempt and, if admitted, its whole life. True when
130
+ a working connection dropped (reconnect fast)."""
131
+ try:
132
+ pairing = self.read_pairing()
133
+ except Exception as e:
134
+ self._set_state("unpaired", "no pairing file - turn on the host bridge in CONFORM.TOOLS")
135
+ self.log(f"pairing: {e}")
136
+ return False
137
+ urls = pairing_mod.fallback_urls(pairing["url"]) if self.try_preferred_ports else [pairing["url"]]
138
+ ws = None
139
+ for url in urls:
140
+ if self._stop.is_set():
141
+ return False
142
+ self._set_state("connecting", url)
143
+ try:
144
+ ws = WebSocket.connect(url, timeout=self.connect_timeout, max_message=self.max_message)
145
+ break
146
+ except WebSocketError as e:
147
+ self.log(f"connect {url}: {e}")
148
+ ws = None
149
+ if ws is None:
150
+ self._set_state("closed", "the app's bridge is not answering")
151
+ return False
152
+ self._ws = ws
153
+ try:
154
+ ws.send_text(json.dumps(hello(pairing["token"], self.host, self.capabilities, self.optional_verbs)))
155
+ self._set_state("hello")
156
+ first = json.loads(ws.recv())
157
+ if not isinstance(first, dict) or first.get("type") != "welcome":
158
+ code = first.get("code", "error") if isinstance(first, dict) else "error"
159
+ self._set_state("refused", str(code))
160
+ self.log(f"app refused: {code}")
161
+ if code in ("bad_token", "protocol_mismatch", "busy"):
162
+ self.attempt = max(self.attempt, 3) # a stale pairing / a twin: back off
163
+ return False
164
+ if first.get("protocol") not in (None, PROTOCOL_VERSION):
165
+ self._set_state("refused", "protocol_mismatch")
166
+ return False
167
+ self.app = first.get("app") or {}
168
+ self.attempt = 0
169
+ self._connected.set()
170
+ self._set_state("connected", f"{self.app.get('name', 'app')} {self.app.get('version', '')}".strip())
171
+ self._read_loop(ws)
172
+ return True
173
+ except ConnectionClosed as e:
174
+ self.log(f"bridge closed: {e}")
175
+ return self.state == "connected"
176
+ except (WebSocketError, ValueError) as e:
177
+ self.log(f"bridge: {e}")
178
+ return False
179
+ finally:
180
+ was = self._connected.is_set()
181
+ self._connected.clear()
182
+ self._ws = None
183
+ try:
184
+ ws.close()
185
+ except Exception:
186
+ pass
187
+ if not self._stop.is_set() and (was or self.state in ("hello", "connecting", "connected")):
188
+ self._set_state("closed", "")
189
+
190
+ def _read_loop(self, ws: WebSocket) -> None:
191
+ while not self._stop.is_set():
192
+ text = ws.recv()
193
+ try:
194
+ msg = json.loads(text)
195
+ except ValueError:
196
+ self.log("bad frame (not JSON)")
197
+ continue
198
+ if isinstance(msg, dict) and msg.get("type") == "request":
199
+ self._jobs.put(msg)
200
+ else:
201
+ self.log(f"unexpected frame type {msg.get('type') if isinstance(msg, dict) else type(msg).__name__}")
202
+
203
+ # -- the worker ------------------------------------------------------
204
+ def _work(self) -> None:
205
+ while True:
206
+ msg = self._jobs.get()
207
+ if msg is None:
208
+ if self._stop.is_set():
209
+ return
210
+ continue
211
+ response = self.dispatcher.handle(msg)
212
+ self._send(response)
213
+
214
+ def _send(self, obj: Dict[str, Any]) -> bool:
215
+ ws = self._ws
216
+ if ws is None:
217
+ return False
218
+ try:
219
+ text = json.dumps(obj, default=_jsonable)
220
+ except (TypeError, ValueError) as e:
221
+ text = json.dumps({"type": "response", "id": obj.get("id"), "ok": False,
222
+ "error": {"code": "bad_answer", "message": f"the answer is not JSON: {e}"}})
223
+ try:
224
+ ws.send_text(text)
225
+ return True
226
+ except WebSocketError as e:
227
+ if "exceeds" in str(e):
228
+ ws.send_text(json.dumps({"type": "response", "id": obj.get("id"), "ok": False,
229
+ "error": {"code": "too_large", "message": str(e)}}))
230
+ self.log(f"send: {e}")
231
+ return False
232
+
233
+ # -- events ----------------------------------------------------------
234
+ def event(self, name: str, data: Optional[Dict[str, Any]] = None) -> bool:
235
+ """Push `{"type":"event"}` - inert JSON on the app side. False when
236
+ not connected (events are not queued)."""
237
+ if not self.connected:
238
+ return False
239
+ return self._send({"type": "event", "name": str(name), "data": dict(data or {})})
240
+
241
+
242
+ def _jsonable(value: Any) -> Any:
243
+ """Last-resort JSON for host values a verb forgot to convert."""
244
+ if isinstance(value, (set, frozenset, tuple)):
245
+ return list(value)
246
+ return str(value)
247
+
@@ -0,0 +1,178 @@
1
+ """Host-neutral helpers both Python peers share: timecode, marker colours,
2
+ and the `[ct:<custom>]` note token.
3
+
4
+ * **Colours.** The app's marker vocabulary is DaVinci Resolve's sixteen names
5
+ (`Blue`, `Cyan`, ... `Cream`). A host that stores a marker colour as RGB
6
+ (Flame) maps a name to the RGB below on write and back to the NEAREST name
7
+ on read, so a name written reads back as itself.
8
+ * **Clip colours** (a segment's / clip's colour) use Resolve's sixteen clip
9
+ colour names the same way (`CLIP_HEX` = `hosts/base.py` NEUTRAL_CLIP_COLORS).
10
+ * **Custom data.** A host whose markers have no custom-data field carries it
11
+ as a trailing ` [ct:<custom>]` token in the note (plan decision D6), with
12
+ `hosts/base.py`'s exact escaping (`\\`, `[`, `]` backslash-escaped).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from typing import Dict, Optional, Tuple
19
+
20
+ #: Resolve's marker palette: the names are the neutral vocabulary, the hex is
21
+ #: `hosts/base.py` NEUTRAL_COLORS (what the app's UI draws); a test keeps the
22
+ #: two identical.
23
+ MARKER_HEX: Dict[str, str] = {
24
+ "Blue": "#007fe3", "Cyan": "#00ced0", "Green": "#00ad00", "Yellow": "#f09d00",
25
+ "Red": "#e12401", "Pink": "#ff44c8", "Purple": "#9013fe", "Fuchsia": "#c02e6f",
26
+ "Rose": "#ffa1b9", "Lavender": "#a193c8", "Sky": "#92e2fd", "Mint": "#72db00",
27
+ "Lemon": "#dce95a", "Sand": "#c4915e", "Cocoa": "#6e5143", "Cream": "#f5ebe1",
28
+ }
29
+ MARKER_RGB: Dict[str, Tuple[float, float, float]] = {
30
+ k: (int(v[1:3], 16) / 255.0, int(v[3:5], 16) / 255.0, int(v[5:7], 16) / 255.0) for k, v in MARKER_HEX.items()
31
+ }
32
+ _BY_LOWER = {k.lower(): k for k in MARKER_RGB}
33
+
34
+
35
+ def canonical_color(name: str) -> str:
36
+ """`"blue"` -> `"Blue"`; unknown names come back unchanged."""
37
+ return _BY_LOWER.get(str(name or "").strip().lower(), str(name or "").strip())
38
+
39
+
40
+ def color_rgb(name: str) -> Optional[Tuple[float, float, float]]:
41
+ """A neutral name (or `#RRGGBB`) as 0-1 RGB, None when unknown."""
42
+ s = str(name or "").strip()
43
+ if re.match(r"^#[0-9a-fA-F]{6}$", s):
44
+ return tuple(int(s[i:i + 2], 16) / 255.0 for i in (1, 3, 5)) # type: ignore[return-value]
45
+ key = _BY_LOWER.get(s.lower())
46
+ return MARKER_RGB[key] if key else None
47
+
48
+
49
+ def nearest_color(rgb) -> str:
50
+ """The neutral name closest to an RGB triple (0-1 floats or 0-255 ints)."""
51
+ return _nearest(rgb, MARKER_RGB)
52
+
53
+
54
+ def _nearest(rgb, palette: Dict[str, Tuple[float, float, float]]) -> str:
55
+ try:
56
+ r, g, b = (float(x) for x in list(rgb)[:3])
57
+ except Exception:
58
+ return ""
59
+ if max(r, g, b) > 1.0:
60
+ r, g, b = r / 255.0, g / 255.0, b / 255.0
61
+ best, dist = "", 1e9
62
+ for name, (cr, cg, cb) in palette.items():
63
+ d = (r - cr) ** 2 + (g - cg) ** 2 + (b - cb) ** 2
64
+ if d < dist:
65
+ best, dist = name, d
66
+ return best
67
+
68
+
69
+ # ── clip colours ──────────────────────────────────────────────────────────
70
+
71
+ #: Resolve's CLIP colour palette (`hosts/base.py` NEUTRAL_CLIP_COLORS): the
72
+ #: names a track item's / pool clip's colour crosses the wire by. A host that
73
+ #: stores RGB (a Flame segment) maps through it the same way as markers.
74
+ CLIP_HEX: Dict[str, str] = {
75
+ "Orange": "#eb6e01", "Apricot": "#ffa833", "Yellow": "#d4ad1f", "Lime": "#9fc615",
76
+ "Olive": "#5f9921", "Green": "#448f65", "Teal": "#019899", "Navy": "#005278",
77
+ "Blue": "#4376a1", "Purple": "#9972a0", "Violet": "#d0568d", "Pink": "#e98cb5",
78
+ "Tan": "#b9af97", "Beige": "#c4a07c", "Brown": "#996601", "Chocolate": "#8c5a3f",
79
+ }
80
+ CLIP_RGB: Dict[str, Tuple[float, float, float]] = {
81
+ k: (int(v[1:3], 16) / 255.0, int(v[3:5], 16) / 255.0, int(v[5:7], 16) / 255.0) for k, v in CLIP_HEX.items()
82
+ }
83
+ _CLIP_BY_LOWER = {k.lower(): k for k in CLIP_RGB}
84
+
85
+
86
+ def clip_color_rgb(name: str) -> Optional[Tuple[float, float, float]]:
87
+ """A clip-colour name (or `#RRGGBB`) as 0-1 RGB, None when unknown."""
88
+ s = str(name or "").strip()
89
+ if re.match(r"^#[0-9a-fA-F]{6}$", s):
90
+ return tuple(int(s[i:i + 2], 16) / 255.0 for i in (1, 3, 5)) # type: ignore[return-value]
91
+ key = _CLIP_BY_LOWER.get(s.lower())
92
+ return CLIP_RGB[key] if key else None
93
+
94
+
95
+ def nearest_clip_color(rgb) -> str:
96
+ """The clip-colour name closest to an RGB triple (0-1 or 0-255)."""
97
+ return _nearest(rgb, CLIP_RGB)
98
+
99
+
100
+ # ── custom data in the note ───────────────────────────────────────────────
101
+
102
+ #: Byte-for-byte the codec of `hosts/base.py` (`encode_custom_data` /
103
+ #: `decode_custom_data`, plan decision D6): `\\`, `[` and `]` are
104
+ #: backslash-escaped, only the LAST token is ours, and a note that already ends
105
+ #: in something token-shaped gets an empty token appended so the round trip is
106
+ #: exact. A test checks the two agree on every vector.
107
+ _TOKEN = re.compile(r"(?:^| )\[ct:((?:[^\[\]\\]|\\.)*)\]$", re.S)
108
+
109
+
110
+ def encode_note(note: str, custom_data: str = "") -> str:
111
+ note = str(note or "")
112
+ custom = str(custom_data or "")
113
+ if not custom and not _TOKEN.search(note):
114
+ return note
115
+ escaped = custom.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]")
116
+ return f"{note}{' ' if note else ''}[ct:{escaped}]"
117
+
118
+
119
+ def decode_note(note: str) -> Tuple[str, str]:
120
+ """`(note without the token, custom data)`."""
121
+ note = str(note or "")
122
+ m = _TOKEN.search(note)
123
+ if not m:
124
+ return note, ""
125
+ return note[: m.start()], re.sub(r"\\(.)", r"\1", m.group(1), flags=re.S)
126
+
127
+
128
+ # ── timecode ──────────────────────────────────────────────────────────────
129
+
130
+
131
+ def nominal_fps(fps: float) -> int:
132
+ """The integer frame count per timecode second (23.976 -> 24)."""
133
+ return max(1, int(round(float(fps or 0) or 24)))
134
+
135
+
136
+ def is_drop_rate(fps: float) -> bool:
137
+ f = float(fps or 0)
138
+ return abs(f - 29.97) < 0.01 or abs(f - 59.94) < 0.01
139
+
140
+
141
+ def tc_to_frames(tc: str, fps: float, drop: Optional[bool] = None) -> int:
142
+ """`HH:MM:SS:FF` (or `;`/`+`/`.` before the frames) -> absolute frames."""
143
+ s = str(tc or "").strip().strip("'")
144
+ m = re.match(r"^(-)?(\d+)[:;.](\d+)[:;.](\d+)[:;.+](\d+)$", s)
145
+ if not m:
146
+ raise ValueError(f"not a timecode: {tc!r}")
147
+ sign = -1 if m.group(1) else 1
148
+ h, mi, se, fr = (int(m.group(i)) for i in range(2, 6))
149
+ base = nominal_fps(fps)
150
+ if drop is None:
151
+ drop = (";" in s) and is_drop_rate(fps)
152
+ total = (h * 3600 + mi * 60 + se) * base + fr
153
+ if drop:
154
+ dropped = 2 if base == 30 else 4
155
+ minutes = h * 60 + mi
156
+ total -= dropped * (minutes - minutes // 10)
157
+ return sign * total
158
+
159
+
160
+ def frames_to_tc(frames: int, fps: float, drop: bool = False, frame_sep: Optional[str] = None) -> str:
161
+ base = nominal_fps(fps)
162
+ n = int(frames)
163
+ sign = "-" if n < 0 else ""
164
+ n = abs(n)
165
+ if drop and base in (30, 60):
166
+ dropped = 2 if base == 30 else 4
167
+ per10 = base * 600 - dropped * 9
168
+ d, m = divmod(n, per10)
169
+ if m > dropped:
170
+ n += dropped * 9 * d + dropped * ((m - dropped) // (base * 60 - dropped))
171
+ else:
172
+ n += dropped * 9 * d
173
+ ff = n % base
174
+ ss = (n // base) % 60
175
+ mm = (n // (base * 60)) % 60
176
+ hh = n // (base * 3600)
177
+ sep = frame_sep if frame_sep is not None else (";" if drop else ":")
178
+ return f"{sign}{hh:02d}:{mm:02d}:{ss:02d}{sep}{ff:02d}"
@@ -0,0 +1,139 @@
1
+ """Finding the host bridge: the pairing file.
2
+
3
+ Two apps host a bridge, and both may be installed: the conform.tools engine
4
+ (`mcp/hosts/bridge.ts`: the MCP / CLI / the in-repo desktop app) and the live
5
+ desktop app (`src-tauri/src/host_bridge.rs`). Each writes its own
6
+ `host-bridge/pairing.json` when its bridge starts (mode 0600, a new port and
7
+ token on every start, removed on stop):
8
+
9
+ {"protocol": 1, "url": "ws://127.0.0.1:48127/host-bridge", "port": 48127, "token": "<64 hex>"}
10
+
11
+ engine $CONFORM_MCP_HOME, else ~/.conform-mcp (mcp/host/runtime.ts home())
12
+ live app $CONFORM_TOOLS_DATA_ROOT, else dirs::data_dir()/app.conform.tools:
13
+ macOS ~/Library/Application Support/app.conform.tools
14
+ Windows %APPDATA%\\app.conform.tools
15
+ Linux $XDG_DATA_HOME/app.conform.tools (default ~/.local/share/...)
16
+
17
+ The NEWEST valid file wins (mtime; a tie goes to the engine): the peer follows
18
+ whichever app started its bridge last, and re-reads on every reconnect. The
19
+ same rule in every peer: the Premiere panel (`mcp/hosts/premiere/uxp-plugin/
20
+ lib/pairing.js`, same two places, no env overrides - UXP has no environment);
21
+ the Avid panel is a page the bridge itself serves on its own port and asks
22
+ that origin for the pairing (`mcp/hosts/avid/panel/lib/pairing.js`), so it
23
+ pairs with whichever app it was loaded from. The token is validated as 64 hex,
24
+ the url as the loopback bridge, and neither is ever logged in full.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import os
31
+ import re
32
+ import sys
33
+ from typing import Any, Dict, List, Optional
34
+
35
+ PROTOCOL_VERSION = 1
36
+ APP_IDENTIFIER = "app.conform.tools"
37
+ DATA_ROOT_ENV = "CONFORM_TOOLS_DATA_ROOT"
38
+ ENGINE_HOME_ENV = "CONFORM_MCP_HOME"
39
+ ENGINE_DIR = ".conform-mcp"
40
+ PAIRING_DIR = "host-bridge"
41
+ PAIRING_FILE = "pairing.json"
42
+ #: `host_bridge.rs::PREFERRED_PORTS` - tried when the pairing's own port is gone.
43
+ PREFERRED_PORTS = (48127, 48128, 48129, 48130, 48131, 48132, 48133, 48134)
44
+
45
+ _URL = re.compile(r"^ws://(127\.0\.0\.1|localhost):(\d+)/host-bridge$")
46
+ _TOKEN = re.compile(r"^[0-9a-f]{64}$")
47
+
48
+
49
+ class PairingError(Exception):
50
+ code = "unpaired"
51
+
52
+
53
+ def platform_data_dir(platform: Optional[str] = None, env: Optional[Dict[str, str]] = None, home: Optional[str] = None) -> str:
54
+ """`dirs::data_dir()` for this platform (what Tauri's app data dir sits in)."""
55
+ platform = platform or sys.platform
56
+ env = os.environ if env is None else env
57
+ home = home or os.path.expanduser("~")
58
+ if platform.startswith("win"):
59
+ return env.get("APPDATA") or os.path.join(home, "AppData", "Roaming")
60
+ if platform == "darwin":
61
+ return os.path.join(home, "Library", "Application Support")
62
+ xdg = (env.get("XDG_DATA_HOME") or "").strip()
63
+ return xdg if xdg and os.path.isabs(xdg) else os.path.join(home, ".local", "share")
64
+
65
+
66
+ def candidates(platform: Optional[str] = None, env: Optional[Dict[str, str]] = None, home: Optional[str] = None) -> List[str]:
67
+ """Where to look: the engine's file, then the live app's (its explicit
68
+ override, then the platform path). `read` takes the newest of these."""
69
+ env = os.environ if env is None else env
70
+ home = home or os.path.expanduser("~")
71
+ engine = (env.get(ENGINE_HOME_ENV) or "").strip() or os.path.join(home, ENGINE_DIR)
72
+ out: List[str] = [os.path.join(engine, PAIRING_DIR, PAIRING_FILE)]
73
+ override = (env.get(DATA_ROOT_ENV) or "").strip()
74
+ if override:
75
+ out.append(os.path.join(override, PAIRING_DIR, PAIRING_FILE))
76
+ out.append(os.path.join(platform_data_dir(platform, env, home), APP_IDENTIFIER, PAIRING_DIR, PAIRING_FILE))
77
+ return out
78
+
79
+
80
+ def parse(text: str) -> Dict[str, Any]:
81
+ try:
82
+ p = json.loads(text)
83
+ except ValueError as e:
84
+ raise PairingError(f"pairing is not JSON: {e}") from e
85
+ if not isinstance(p, dict):
86
+ raise PairingError("pairing is not an object")
87
+ if p.get("protocol") != PROTOCOL_VERSION:
88
+ raise PairingError(f"pairing protocol {p.get('protocol')!r}, this plugin speaks {PROTOCOL_VERSION}")
89
+ url = p.get("url")
90
+ m = _URL.match(url) if isinstance(url, str) else None
91
+ if not m:
92
+ raise PairingError("pairing url is not the loopback bridge")
93
+ token = p.get("token")
94
+ if not isinstance(token, str) or not _TOKEN.match(token):
95
+ raise PairingError("pairing token is malformed")
96
+ port = p.get("port")
97
+ port = int(port) if isinstance(port, int) and 0 < port < 65536 else int(m.group(2))
98
+ return {"url": url, "token": token, "port": port}
99
+
100
+
101
+ def read(paths: Optional[List[str]] = None) -> Dict[str, Any]:
102
+ """The newest valid pairing (by mtime; ties keep `paths` order),
103
+ `{url, token, port, source}`; `PairingError` naming every place tried when
104
+ there is none."""
105
+ errors, found = [], []
106
+ for path in paths if paths is not None else candidates():
107
+ try:
108
+ with open(path, "r", encoding="utf-8") as f:
109
+ text = f.read()
110
+ mtime = os.fstat(f.fileno()).st_mtime
111
+ except FileNotFoundError:
112
+ errors.append(f"{path}: not found")
113
+ continue
114
+ except OSError as e:
115
+ errors.append(f"{path}: {e}")
116
+ continue
117
+ try:
118
+ found.append((mtime, {**parse(text), "source": path}))
119
+ except PairingError as e:
120
+ errors.append(f"{path}: {e}")
121
+ if found:
122
+ return max(found, key=lambda f: f[0])[1] # max keeps the first of equal mtimes
123
+ raise PairingError(" | ".join(errors) or "no pairing found")
124
+
125
+
126
+ def mask_token(token: str) -> str:
127
+ return f"{token[:6]}...{token[-4:]}" if token else ""
128
+
129
+
130
+ def fallback_urls(pairing_url: str) -> List[str]:
131
+ """The pairing's url, then the other preferred ports on 127.0.0.1. Used
132
+ only when the pairing's port refuses: the token still decides admission,
133
+ so a wrong guess costs a refused handshake and nothing else."""
134
+ out = [pairing_url]
135
+ for port in PREFERRED_PORTS:
136
+ url = f"ws://127.0.0.1:{port}/host-bridge"
137
+ if url not in out:
138
+ out.append(url)
139
+ return out