codev-mcp 0.1.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.
codev_mcp/engine.py ADDED
@@ -0,0 +1,693 @@
1
+ """Thin, thread-safe wrapper around the CODE V COM object.
2
+
3
+ All COM calls run on one dedicated worker thread, because the MCP server
4
+ dispatches tool calls from a thread pool and a COM proxy should stay on the
5
+ thread that created it.
6
+
7
+ Every public method returns a plain dict "envelope":
8
+
9
+ {"ok": bool, ..., "errors": [...], "warnings": [...], "plots": [...]}
10
+
11
+ ``errors`` and ``warnings`` are the messages CODE V raised while the call ran
12
+ (collected from the COM events), so a caller can tell a command that ran from
13
+ a command that ran cleanly. Nothing here raises for an engine-side failure.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import gc
19
+ import os
20
+ import sys
21
+ import threading
22
+ import time
23
+ from concurrent.futures import ThreadPoolExecutor
24
+ from typing import Any, Callable
25
+
26
+ from codev_mcp import procs, settings # noqa: E402
27
+ from codev_mcp.paths import LEGACY_START_DIR, default_start_dir # noqa: E402,F401
28
+
29
+ DEFAULT_PROGID = "CodeV.Application"
30
+ MAX_OUTPUT_CHARS = 20_000
31
+
32
+
33
+ class _EventLog:
34
+ """Collects messages delivered through the ICVApplicationEvents interface."""
35
+
36
+ def __init__(self) -> None:
37
+ self._lock = threading.Lock()
38
+ self.errors: list[str] = []
39
+ self.warnings: list[str] = []
40
+ self.plots: list[str] = []
41
+
42
+ def add(self, kind: str, text: str) -> None:
43
+ with self._lock:
44
+ getattr(self, kind).append(str(text).strip())
45
+
46
+ def discard_warnings(self, start: int, needle: str) -> int:
47
+ """Drop warnings at index >= start that contain ``needle``; return how many."""
48
+ with self._lock:
49
+ kept = [w for w in self.warnings[start:] if needle not in w]
50
+ dropped = len(self.warnings) - start - len(kept)
51
+ self.warnings[start:] = kept
52
+ return dropped
53
+
54
+ def take_since(self, e0: int, w0: int) -> tuple[list[str], list[str]]:
55
+ """Remove and return the errors and warnings added after these indices."""
56
+ with self._lock:
57
+ errors, warnings = self.errors[e0:], self.warnings[w0:]
58
+ del self.errors[e0:]
59
+ del self.warnings[w0:]
60
+ return errors, warnings
61
+
62
+ def drain(self) -> dict[str, list[str]]:
63
+ with self._lock:
64
+ out = {
65
+ "errors": self.errors,
66
+ "warnings": self.warnings,
67
+ "plots": self.plots,
68
+ }
69
+ self.errors, self.warnings, self.plots = [], [], []
70
+ return out
71
+
72
+
73
+ def _make_handler(log: _EventLog) -> type:
74
+ class Handler:
75
+ def OnLicenseError(self, error): # noqa: N802 (COM event name)
76
+ log.add("errors", f"License error: {error}")
77
+
78
+ def OnCodeVError(self, error): # noqa: N802
79
+ log.add("errors", error)
80
+
81
+ def OnCodeVWarning(self, warning): # noqa: N802
82
+ log.add("warnings", warning)
83
+
84
+ def OnPlotReady(self, filename, plotwindow): # noqa: N802
85
+ log.add("plots", filename)
86
+
87
+ return Handler
88
+
89
+
90
+ def _clip(text: Any) -> tuple[str, bool]:
91
+ text = "" if text is None else str(text)
92
+ if len(text) <= MAX_OUTPUT_CHARS:
93
+ return text, False
94
+ return text[:MAX_OUTPUT_CHARS], True
95
+
96
+
97
+ DEFAULT_IDLE_MINUTES = settings.DEFAULT_IDLE_MINUTES
98
+
99
+
100
+ def _idle_seconds_from_env() -> float | None:
101
+ """CODEV_IDLE_MINUTES (default 20); 0 or less turns the timeout off."""
102
+ minutes, _ = settings.idle_minutes()
103
+ return minutes * 60.0 if minutes > 0 else None
104
+
105
+
106
+ class CodeVEngine:
107
+ def __init__(
108
+ self,
109
+ progid: str | None = None,
110
+ start_dir: str | None = None,
111
+ idle_seconds: float | None | str = "env",
112
+ com_factory: Callable[[type], Any] | None = None,
113
+ locator_factory: Callable[[int, type], Any] | None = None,
114
+ ) -> None:
115
+ # com_factory replaces win32com in tests: it is called with the event
116
+ # handler class and returns an object that behaves like CodeV.Application.
117
+ # locator_factory does the same for attaching to an open window: called
118
+ # with the window's PID UI (0 = first window) and the handler class.
119
+ self._com_factory = com_factory
120
+ self._locator_factory = locator_factory
121
+ # "background": a hidden session this server starts and stops.
122
+ # "attached": the user's own CODE V window, reached through CVLocator.
123
+ self.mode = "background"
124
+ self.attached_window: dict | None = None
125
+ self._sink: Any = None
126
+ self.progid = progid or settings.env("CODEV_PROGID") or DEFAULT_PROGID
127
+ self.start_dir = start_dir or str(settings.start_dir())
128
+ self._cv: Any = None
129
+ self._events_attached = False
130
+ self._last_output: str | None = None # see command_output()
131
+ self._log = _EventLog()
132
+ self._pool = ThreadPoolExecutor(
133
+ max_workers=1, thread_name_prefix="codev-com", initializer=self._init_thread
134
+ )
135
+ # Idle timeout: release the licence seat when unused, and bring the
136
+ # lens back on the next call. None disables it.
137
+ self.idle_seconds: float | None = _idle_seconds_from_env() if idle_seconds == "env" else idle_seconds
138
+ self.on_idle_stop: Callable[[Ops], str | None] | None = None # returns a snapshot label
139
+ self.on_restart: Callable[[Ops, str], dict] | None = None # restores that label
140
+ self._last_activity = time.monotonic()
141
+ self._idle_label: str | None = None
142
+ self._notice: dict | None = None
143
+ self.last_idle_stop: dict | None = None
144
+ self._watch_stop = threading.Event()
145
+ self._watchdog: threading.Thread | None = None
146
+
147
+ # -- worker-thread plumbing -------------------------------------------
148
+
149
+ @staticmethod
150
+ def _init_thread() -> None:
151
+ import pythoncom
152
+
153
+ pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
154
+
155
+ def _flush_events(self) -> None:
156
+ """Make CODE V deliver events still queued from the call that just ran.
157
+
158
+ CODE V hands over a call's last event only when the next request
159
+ arrives, so without this it would land in the next tool's result. A
160
+ cheap EvaluateExpression is such a request (property reads are not).
161
+ Skipped while a long command runs: it would wait for it.
162
+ """
163
+ cv = self._cv
164
+ if cv is None:
165
+ return
166
+ try:
167
+ if not cv.IsExecutingCommand:
168
+ # The request clears CommandOutput, where a finished long command's
169
+ # listing waits to be read; keep it for command_output(). Empty means
170
+ # an earlier flush (or evaluation) cleared it: keep the copy we have.
171
+ output = str(cv.CommandOutput or "")
172
+ if output:
173
+ self._last_output = output
174
+ cv.EvaluateExpression("(NUM S)")
175
+ except Exception: # the session may be gone; the call's own result says so
176
+ pass
177
+
178
+ def command_output(self) -> str:
179
+ """CommandOutput as the last command left it (the full listing of a finished
180
+ long command). Call on the COM thread, inside ``with_ops``/``with_cv``.
181
+
182
+ Live output wins: it is newer than any copy. Empty live output means a
183
+ flush cleared it, so the copy taken just before is the answer.
184
+ """
185
+ live = str(self._cv.CommandOutput or "") if self._cv is not None else ""
186
+ return live or self._last_output or ""
187
+
188
+ def _run(self, fn: Callable[[], dict]) -> dict:
189
+ """Run ``fn`` on the COM thread and attach the events it produced."""
190
+
191
+ def call() -> dict:
192
+ self._log.drain()
193
+ try:
194
+ result = fn()
195
+ except Exception as exc: # com_error or anything else
196
+ result = {"ok": False, "exception": _describe(exc)}
197
+ self._flush_events()
198
+ events = self._log.drain()
199
+ if events["errors"] or "exception" in result:
200
+ result["ok"] = False
201
+ result.setdefault("ok", True)
202
+ result.update(events)
203
+ if self._notice:
204
+ result["session_notice"] = self._notice
205
+ self._notice = None
206
+ if self.mode == "attached" and "exception" in result and _looks_disconnected(result["exception"]):
207
+ # The user closed the window (or CODE V went away): say so plainly.
208
+ self._cv = None
209
+ self._last_output = None
210
+ result["error_detail"] = ("The attached CODE V window has closed or stopped responding. "
211
+ "Call attach_to_window again, or detach_from_window to go back to a "
212
+ "background session.")
213
+ self._last_activity = time.monotonic()
214
+ return result
215
+
216
+ return self._pool.submit(call).result()
217
+
218
+ # -- idle timeout ------------------------------------------------------
219
+
220
+ def _start_watchdog(self) -> None:
221
+ if self.idle_seconds is None or (self._watchdog and self._watchdog.is_alive()):
222
+ return
223
+ self._watchdog = threading.Thread(target=self._watch, name="codev-idle", daemon=True)
224
+ self._watchdog.start()
225
+
226
+ def _watch(self) -> None:
227
+ interval = max(0.5, min(30.0, self.idle_seconds / 4))
228
+ while not self._watch_stop.wait(interval):
229
+ if self._cv is not None and time.monotonic() - self._last_activity >= self.idle_seconds:
230
+ try:
231
+ self._pool.submit(self._idle_stop).result()
232
+ except Exception:
233
+ pass # try again on the next tick
234
+
235
+ def _idle_stop(self) -> None:
236
+ """Runs on the COM thread, so it cannot overlap a tool call."""
237
+ if self.mode == "attached":
238
+ return # the seat belongs to the user's window, not to this server
239
+ idle = time.monotonic() - self._last_activity
240
+ if self._cv is None or self.idle_seconds is None or idle < self.idle_seconds:
241
+ return
242
+ try:
243
+ if self._cv.IsExecutingCommand:
244
+ return # never interrupt an optimization or other long run
245
+ except Exception:
246
+ pass
247
+ self._log.drain()
248
+ label = None
249
+ if self.on_idle_stop is not None:
250
+ try:
251
+ label = self.on_idle_stop(Ops(self._cv, self._log))
252
+ except Exception:
253
+ label = None
254
+ if not label:
255
+ self._log.drain()
256
+ return # keep the seat rather than lose the lens
257
+ try:
258
+ self._cv.StopCodeV()
259
+ except Exception:
260
+ pass
261
+ finally:
262
+ self._cv = None
263
+ self._last_output = None
264
+ self._idle_label = label
265
+ self.last_idle_stop = {
266
+ "at": time.strftime("%Y-%m-%d %H:%M:%S"),
267
+ "idle_minutes": round(idle / 60.0, 1),
268
+ "snapshot": label,
269
+ }
270
+ self._log.drain()
271
+
272
+ def idle_status(self) -> dict:
273
+ out: dict[str, Any] = {
274
+ "idle_timeout_minutes": None if self.idle_seconds is None else round(self.idle_seconds / 60.0, 2),
275
+ "last_idle_stop": self.last_idle_stop,
276
+ }
277
+ if self._cv is not None and self.idle_seconds is not None:
278
+ idle = time.monotonic() - self._last_activity
279
+ out["idle_minutes"] = round(idle / 60.0, 1)
280
+ out["releases_in_minutes"] = round(max(0.0, self.idle_seconds - idle) / 60.0, 1)
281
+ if self._idle_label:
282
+ out["will_restore_on_next_call"] = self._idle_label
283
+ return out
284
+
285
+ def shutdown(self) -> None:
286
+ self._watch_stop.set()
287
+
288
+ def _ensure_started(self) -> None:
289
+ """Start CODE V if needed. Call only from the COM thread."""
290
+ if self._cv is not None:
291
+ return
292
+ if self.mode == "attached":
293
+ # Never start a hidden session behind the user's back while they
294
+ # expect their window to be driven.
295
+ raise RuntimeError("The attached CODE V window is no longer connected. Call attach_to_window "
296
+ "again, or detach_from_window to go back to a background session.")
297
+ os.makedirs(self.start_dir, exist_ok=True)
298
+ before = procs.pids("cvgui.exe") if self._com_factory is None else set()
299
+ cv = None
300
+ try:
301
+ if self._com_factory is not None:
302
+ cv = self._com_factory(_make_handler(self._log))
303
+ self._events_attached = True
304
+ else:
305
+ import win32com.client as wc
306
+
307
+ try:
308
+ cv = wc.DispatchWithEvents(self.progid, _make_handler(self._log))
309
+ self._events_attached = True
310
+ except Exception:
311
+ # Events need a generated type-library wrapper; fall back without them.
312
+ cv = wc.Dispatch(self.progid)
313
+ self._events_attached = False
314
+ # CODE V checks the folder here, before StartCodeV.
315
+ cv.StartingDirectory = self.start_dir
316
+ # Default is 256 KB; a full LIS of a large lens can exceed it.
317
+ cv.MaxTextBufferSize = 4_000_000
318
+ cv.StartCodeV()
319
+ # StartCodeV returns even when the licence checkout failed, leaving a
320
+ # session that silently ignores commands. Probe it before trusting it.
321
+ try:
322
+ cv.EvaluateExpression("(CVV)")
323
+ healthy = not self._log.errors
324
+ except Exception:
325
+ healthy = False
326
+ if not healthy:
327
+ raise RuntimeError(
328
+ "CODE V started but is not usable (see errors; usually a licence problem)."
329
+ )
330
+ except Exception:
331
+ self._abandon_start(cv, before)
332
+ raise
333
+ self._cv = cv
334
+ self._start_watchdog()
335
+ if self._idle_label and self.on_restart is not None:
336
+ label, self._idle_label = self._idle_label, None
337
+ try:
338
+ restored = self.on_restart(Ops(cv, self._log), label)
339
+ ok = restored.get("ok", True) and "label" in restored
340
+ except Exception as exc:
341
+ restored, ok = {"error": _describe(exc)}, False
342
+ self._notice = {
343
+ "event": "CODE V was stopped after "
344
+ f"{self.last_idle_stop['idle_minutes'] if self.last_idle_stop else '?'} minutes idle "
345
+ "to free the licence seat, and started again for this call.",
346
+ "lens": f"Restored from snapshot {label!r}." if ok else
347
+ f"Could not restore snapshot {label!r}; the lens is not the one you had. "
348
+ "Use restore_snapshot or open_lens.",
349
+ "restore": restored,
350
+ }
351
+
352
+ def _abandon_start(self, cv: Any, before: set[int]) -> None:
353
+ """Undo a failed start so it leaves no cvgui/codevm running (see procs.py).
354
+
355
+ Only cvgui.exe processes that appeared during this start are ended. A
356
+ CODE V started by another program in the same few seconds would also
357
+ match; that window is short and only matters when a start fails.
358
+ """
359
+ if cv is not None:
360
+ for close in (getattr(cv, "StopCodeV", None), getattr(cv, "close", None)):
361
+ try:
362
+ if close:
363
+ close()
364
+ except Exception:
365
+ pass
366
+ del cv
367
+ if self._com_factory is not None:
368
+ return
369
+ gc.collect()
370
+ time.sleep(1.0)
371
+ for pid in procs.pids("cvgui.exe") - before:
372
+ procs.terminate_tree(pid)
373
+
374
+ # -- session -----------------------------------------------------------
375
+
376
+ @property
377
+ def running(self) -> bool:
378
+ return self._cv is not None
379
+
380
+ def start(self) -> dict:
381
+ def fn() -> dict:
382
+ self._ensure_started()
383
+ return {
384
+ "version": str(self._cv.CodeVVersion),
385
+ "progid": self.progid,
386
+ "starting_directory": self.start_dir,
387
+ "events_attached": self._events_attached,
388
+ }
389
+
390
+ return self._run(fn)
391
+
392
+ def stop(self) -> dict:
393
+ def fn() -> dict:
394
+ self._idle_label = None # an explicit stop means "do not bring it back"
395
+ if self.mode == "attached":
396
+ return self._detach()
397
+ if self._cv is None:
398
+ return {"stopped": False, "note": "No session was running."}
399
+ try:
400
+ self._cv.StopCodeV()
401
+ finally:
402
+ self._cv = None
403
+ self._last_output = None
404
+ return {"stopped": True}
405
+
406
+ return self._run(fn)
407
+
408
+ # -- attaching to the user's CODE V window -------------------------------
409
+
410
+ def attach(self, pid: int = 0) -> dict:
411
+ """Connect to an open CODE V window (PID UI; 0 = the first window).
412
+
413
+ All tools then act on that window, so the user sees each command run.
414
+ Ending the connection (detach) leaves the window open: in this mode
415
+ StopCodeV only ends the COM connection, as CODE V's interactive-COM
416
+ examples rely on.
417
+ """
418
+
419
+ def fn() -> dict:
420
+ if self.mode == "background" and self._cv is not None:
421
+ return {"ok": False, "error_detail": "A background CODE V session is running. Its lens would be "
422
+ "lost; save_snapshot if needed, then stop_session, then attach."}
423
+ if self.mode == "attached" and self._cv is not None:
424
+ if pid in (0, (self.attached_window or {}).get("pid")):
425
+ return {"attached": True, "already": True, "window": self.attached_window}
426
+ self._detach()
427
+ cv = None
428
+ try:
429
+ if self._locator_factory is not None:
430
+ cv = self._locator_factory(int(pid), _make_handler(self._log))
431
+ else:
432
+ import win32com.client as wc
433
+
434
+ cv = wc.Dispatch("CVLocator.Locator").GETCVAPI(int(pid))
435
+ if cv is None:
436
+ return {"ok": False, "error_detail": "No CODE V window found" + (f" with PID UI {pid}" if pid else "")
437
+ + ". Open CODE V, or check the PID UI with 'eva (pid ui)' in its command window."}
438
+ cv.MaxTextBufferSize = 4_000_000
439
+ cv.StartCodeV()
440
+ if self._locator_factory is None:
441
+ import win32com.client as wc
442
+
443
+ self._sink = wc.WithEvents(cv, _make_handler(self._log))
444
+ self._events_attached = True
445
+ window = {"pid": int(cv.EvaluateExpression("(PID UI)")), "version": str(cv.EvaluateExpression("(CVV)")),
446
+ "lens": str(cv.EvaluateExpression("(TIT)"))}
447
+ except Exception:
448
+ if cv is not None:
449
+ try:
450
+ cv.StopCodeV() # ends the connection only; the window stays open
451
+ except Exception:
452
+ pass
453
+ self._sink = None
454
+ raise
455
+ self._cv = cv
456
+ self.mode = "attached"
457
+ self.attached_window = window
458
+ return {"attached": True, "window": window,
459
+ "note": "Tools now act on this CODE V window; detach_from_window ends the connection and leaves "
460
+ "the window open. The idle timeout does not apply while attached."}
461
+
462
+ return self._run(fn)
463
+
464
+ def _detach(self) -> dict:
465
+ """End the connection to the attached window (COM thread). The window stays open."""
466
+ window = self.attached_window
467
+ try:
468
+ if self._cv is not None:
469
+ self._cv.StopCodeV()
470
+ except Exception:
471
+ pass
472
+ finally:
473
+ self._cv = None
474
+ self._last_output = None
475
+ self._sink = None
476
+ self.mode = "background"
477
+ self.attached_window = None
478
+ return {"detached": True, "window": window, "note": "The CODE V window stays open."}
479
+
480
+ def detach(self) -> dict:
481
+ def fn() -> dict:
482
+ if self.mode != "attached":
483
+ return {"detached": False, "note": "Not attached to a CODE V window."}
484
+ return self._detach()
485
+
486
+ return self._run(fn)
487
+
488
+ # -- commands and expressions -------------------------------------------
489
+
490
+ def command(self, command: str, timeout_s: float | None = None) -> dict:
491
+ def fn() -> dict:
492
+ self._ensure_started()
493
+ if timeout_s:
494
+ self._cv.CommandTimeout = int(timeout_s * 1000)
495
+ output, clipped = _clip(self._cv.Command(command))
496
+ return {"command": command, "output": output, "output_truncated": clipped}
497
+
498
+ return self._run(fn)
499
+
500
+ def evaluate(self, expression: str) -> dict:
501
+ def fn() -> dict:
502
+ self._ensure_started()
503
+ value = _coerce(self._cv.EvaluateExpression(expression))
504
+ if self._log.errors: # stale value from a failed evaluation
505
+ return {"expression": expression}
506
+ return {"expression": expression, "value": value}
507
+
508
+ return self._run(fn)
509
+
510
+ def evaluate_many(self, expressions: dict[str, str]) -> dict:
511
+ """Evaluate several named expressions in one round trip to the COM thread."""
512
+
513
+ def fn() -> dict:
514
+ self._ensure_started()
515
+ values: dict[str, Any] = {}
516
+ failed: list[str] = []
517
+ for name, expr in expressions.items():
518
+ seen = len(self._log.errors)
519
+ try:
520
+ value = _coerce(self._cv.EvaluateExpression(expr))
521
+ except Exception as exc:
522
+ values[name] = {"error": _describe(exc)}
523
+ failed.append(name)
524
+ continue
525
+ # A bad database item does not raise: CODE V reports an error
526
+ # event and hands back a stale value. Never pass that value on.
527
+ new_errors = self._log.errors[seen:]
528
+ if new_errors:
529
+ values[name] = {"error": "; ".join(new_errors), "expression": expr}
530
+ failed.append(name)
531
+ else:
532
+ values[name] = value
533
+ result: dict[str, Any] = {"values": values}
534
+ if failed:
535
+ result["ok"] = False
536
+ result["failed"] = failed
537
+ return result
538
+
539
+ return self._run(fn)
540
+
541
+ def counts(self) -> dict:
542
+ def fn() -> dict:
543
+ self._ensure_started()
544
+ cv = self._cv
545
+ return {
546
+ "surfaces": int(cv.SurfaceCount),
547
+ "fields": int(cv.FieldCount),
548
+ "wavelengths": int(cv.WavelengthCount),
549
+ "zooms": int(cv.ZoomCount),
550
+ "stop_surface": int(cv.StopSurface),
551
+ }
552
+
553
+ return self._run(fn)
554
+
555
+ def with_ops(self, fn: Callable[["Ops"], dict]) -> dict:
556
+ """Run ``fn(ops)`` on the COM thread; see ``Ops`` for the helpers."""
557
+
558
+ def call() -> dict:
559
+ self._ensure_started()
560
+ return fn(Ops(self._cv, self._log))
561
+
562
+ return self._run(call)
563
+
564
+ def with_cv(self, fn: Callable[[Any], dict]) -> dict:
565
+ """Run ``fn(cv)`` on the COM thread with the live COM object.
566
+
567
+ For typed API calls (MTF_1FLD and friends). ``fn`` returns the body of
568
+ the envelope; events raised while it ran are attached as usual.
569
+ """
570
+
571
+ def call() -> dict:
572
+ self._ensure_started()
573
+ return fn(self._cv)
574
+
575
+ return self._run(call)
576
+
577
+ # -- long-running commands ---------------------------------------------
578
+
579
+ def async_start(self, command: str) -> dict:
580
+ def fn() -> dict:
581
+ self._ensure_started()
582
+ if self._cv.IsExecutingCommand:
583
+ return {"ok": False, "note": "A command is already executing."}
584
+ self._cv.AsyncCommand(command)
585
+ return {"command": command, "started": True}
586
+
587
+ return self._run(fn)
588
+
589
+ def async_poll(self, wait_ms: int = 1000) -> dict:
590
+ def fn() -> dict:
591
+ self._ensure_started()
592
+ if self._cv.IsExecutingCommand:
593
+ self._cv.Wait(int(wait_ms))
594
+ if self._cv.IsExecutingCommand:
595
+ return {"executing": True}
596
+ output, clipped = _clip(self.command_output())
597
+ return {"executing": False, "output": output, "output_truncated": clipped}
598
+
599
+ return self._run(fn)
600
+
601
+ def async_stop(self) -> dict:
602
+ def fn() -> dict:
603
+ self._ensure_started()
604
+ self._cv.StopCommand()
605
+ return {"stop_requested": True}
606
+
607
+ return self._run(fn)
608
+
609
+
610
+ class CodeVError(Exception):
611
+ """CODE V reported an error while evaluating something."""
612
+
613
+
614
+ class Ops:
615
+ """Helpers for multi-step work on the COM thread.
616
+
617
+ Each call reports only the errors and warnings it caused, so a caller can
618
+ attribute a failure to the step that produced it.
619
+ """
620
+
621
+ def __init__(self, cv: Any, log: _EventLog) -> None:
622
+ self.cv = cv
623
+ self._log = log
624
+
625
+ def cmd(self, text: str) -> dict:
626
+ e0, w0 = len(self._log.errors), len(self._log.warnings)
627
+ output = str(self.cv.Command(text) or "")
628
+ return {
629
+ "output": output,
630
+ "errors": self._log.errors[e0:],
631
+ "warnings": self._log.warnings[w0:],
632
+ }
633
+
634
+ def eva(self, expression: str) -> Any:
635
+ """Evaluate, raising CodeVError instead of returning a stale value."""
636
+ e0 = len(self._log.errors)
637
+ value = _coerce(self.cv.EvaluateExpression(expression))
638
+ new = self._log.errors[e0:]
639
+ if new:
640
+ raise CodeVError(f"{expression}: {'; '.join(new)}")
641
+ return value
642
+
643
+ def soft(self, fn: Callable[[], Any]) -> tuple[Any, list[str], list[str]]:
644
+ """Run an optional step; its CODE V errors and warnings are returned, not
645
+ added to the call's envelope. For values that may legitimately be
646
+ unavailable (a semi-diameter that needs a ray trace, a PSF on a system
647
+ it does not support) without failing a result that is otherwise valid.
648
+ Returns (result or None if it raised, errors, warnings).
649
+ """
650
+ e0, w0 = len(self._log.errors), len(self._log.warnings)
651
+ try:
652
+ result = fn()
653
+ except Exception as exc:
654
+ result = None
655
+ self._log.add("errors", _describe(exc))
656
+ errors, warnings = self._log.take_since(e0, w0)
657
+ return result, errors, warnings
658
+
659
+ def eva_expecting(self, expression: str, warning: str) -> tuple[Any, bool]:
660
+ """Evaluate a read that may raise one known, harmless warning.
661
+
662
+ The warning is removed from the call's envelope (it was caused by our
663
+ own read-back, not by anything the caller asked for). Returns the value
664
+ and whether the warning occurred.
665
+ """
666
+ w0 = len(self._log.warnings)
667
+ value = self.eva(expression)
668
+ return value, self._log.discard_warnings(w0, warning) > 0
669
+
670
+
671
+ def _looks_disconnected(text: str) -> bool:
672
+ """COM errors that mean the server process is gone (RPC unavailable, call failed)."""
673
+ return any(code in text for code in ("-2147023174", "-2147023170", "-2147417848", "RPC server is unavailable",
674
+ "remote procedure call failed", "object invoked has disconnected"))
675
+
676
+
677
+ def _coerce(value: Any) -> Any:
678
+ """EvaluateExpression returns text; hand back a number when it is one."""
679
+ if isinstance(value, (int, float)):
680
+ return value
681
+ text = str(value).strip()
682
+ try:
683
+ return float(text)
684
+ except ValueError:
685
+ return text
686
+
687
+
688
+ def _describe(exc: Exception) -> str:
689
+ return f"{type(exc).__name__}: {exc}"
690
+
691
+
692
+ if sys.platform != "win32": # pragma: no cover
693
+ raise ImportError("codev_mcp.engine needs Windows: CODE V's API is COM-only.")