sim-cli-core 0.2.4__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.
- sim/__init__.py +11 -0
- sim/__main__.py +24 -0
- sim/_plugin_install.py +451 -0
- sim/_timeout.py +115 -0
- sim/cli.py +1353 -0
- sim/compat.py +411 -0
- sim/config.py +380 -0
- sim/describe.py +346 -0
- sim/driver.py +190 -0
- sim/drivers/__init__.py +161 -0
- sim/drivers/coolprop/__init__.py +3 -0
- sim/drivers/coolprop/driver.py +183 -0
- sim/drivers/openfoam/__init__.py +4 -0
- sim/drivers/openfoam/compatibility.yaml +37 -0
- sim/drivers/openfoam/driver.py +432 -0
- sim/gui/LICENSES/ATTRIBUTION.md +24 -0
- sim/gui/__init__.py +230 -0
- sim/gui/_pywinauto_tools.py +452 -0
- sim/gui/_win32_dialog.py +148 -0
- sim/history.py +170 -0
- sim/inspect.py +1088 -0
- sim/plugins.py +468 -0
- sim/runner.py +195 -0
- sim/server.py +547 -0
- sim/session.py +224 -0
- sim/testing/__init__.py +30 -0
- sim/testing/protocol_conformance.py +264 -0
- sim_cli_core-0.2.4.dist-info/METADATA +309 -0
- sim_cli_core-0.2.4.dist-info/RECORD +33 -0
- sim_cli_core-0.2.4.dist-info/WHEEL +4 -0
- sim_cli_core-0.2.4.dist-info/entry_points.txt +2 -0
- sim_cli_core-0.2.4.dist-info/licenses/LICENSE +190 -0
- sim_cli_core-0.2.4.dist-info/licenses/NOTICE +72 -0
sim/inspect.py
ADDED
|
@@ -0,0 +1,1088 @@
|
|
|
1
|
+
"""Inspect probe framework + core probes.
|
|
2
|
+
|
|
3
|
+
═══════════════════════════════════════════════════════════════════════════
|
|
4
|
+
Why this module exists (read this before touching a probe)
|
|
5
|
+
═══════════════════════════════════════════════════════════════════════════
|
|
6
|
+
|
|
7
|
+
The inspect layer is the **agent decision-support layer**. It does NOT act;
|
|
8
|
+
acting is the job of `run` / `exec` / external automation scripts. What it
|
|
9
|
+
does is answer two questions after every `run / connect / exec`:
|
|
10
|
+
|
|
11
|
+
1. "Did what I just do achieve my goal?" → yes → next step; no → question 2
|
|
12
|
+
2. "Where should I look to find out why?" → the channels, in cost order
|
|
13
|
+
|
|
14
|
+
Channels are structured so an agent queries them cheap-first:
|
|
15
|
+
|
|
16
|
+
cheapest ────────────────────────────────────────────────► most expensive
|
|
17
|
+
#1 Process meta pure stdlib, always on
|
|
18
|
+
#3 StdoutJsonTail parse a JSON line — free
|
|
19
|
+
#3+ PythonTraceback read traceback string — free
|
|
20
|
+
#4 SdkAttribute read session.attr — cheap unless SDK is slow
|
|
21
|
+
#5 DomainExceptionMap regex post-processor — free
|
|
22
|
+
#2 stderr regex read text stream — cheap
|
|
23
|
+
#6 TUI echo ditto, driver-specific
|
|
24
|
+
#7 Log file open a file — cheap
|
|
25
|
+
#9 WorkdirDiff os.walk + stat — I/O but fast
|
|
26
|
+
#8a GUI dialog enum pywinauto UIA walk — seconds
|
|
27
|
+
#8b Screenshot PIL bbox capture — seconds + disk
|
|
28
|
+
|
|
29
|
+
Constraints this design places on every probe implementation:
|
|
30
|
+
|
|
31
|
+
• `Diagnostic.code` MUST be machine-switchable (e.g.
|
|
32
|
+
"fluent.sdk.attr_not_found", "python.NameError", "sim.runtime.snippet_timeout")
|
|
33
|
+
— never free-form text. Agents switch on it without NLP.
|
|
34
|
+
• `Diagnostic.severity` IS the agent threshold signal:
|
|
35
|
+
info = "I noticed it, don't panic"
|
|
36
|
+
warning = "look if you care"
|
|
37
|
+
error = "you must act"
|
|
38
|
+
A modal dialog that blocks agent progress MUST be severity=error,
|
|
39
|
+
not info — otherwise the decision tree in the agent skips it.
|
|
40
|
+
• A probe NEVER acts. If you want to dismiss a dialog, automate a key
|
|
41
|
+
press, or re-start a crashed session, that's `run`/`exec`/`driver.launch`
|
|
42
|
+
territory (see e.g. dialog-watcher pattern in comsol driver launch),
|
|
43
|
+
not a probe.
|
|
44
|
+
• Driver-side probe lists are declarative: driver says "I need these
|
|
45
|
+
channels with these rule tables / these reader closures" — probe
|
|
46
|
+
classes themselves stay driver-agnostic.
|
|
47
|
+
|
|
48
|
+
See `sim-proj/inspect-probes-PLAN.md §二·六` and
|
|
49
|
+
`sim-proj/inspect-probes-PLAN-phase2.md "Raison d'être"` for the full
|
|
50
|
+
rationale and the agent decision tree.
|
|
51
|
+
|
|
52
|
+
═══════════════════════════════════════════════════════════════════════════
|
|
53
|
+
Implementation notes
|
|
54
|
+
═══════════════════════════════════════════════════════════════════════════
|
|
55
|
+
|
|
56
|
+
Implements §三 (根本思路) "第 1 档 通用观察契约":
|
|
57
|
+
ok / wall_time_s / started_at / diagnostics[{severity, message, source, code}]
|
|
58
|
+
/ artifacts[{path, size, mtime, role}]
|
|
59
|
+
|
|
60
|
+
Single-file Phase 1-2 design. Expand into a package only when we cross any of:
|
|
61
|
+
- file > ~500 lines
|
|
62
|
+
- add a platform-specific probe that needs its own helper files
|
|
63
|
+
- we hit real maintenance friction from co-location
|
|
64
|
+
|
|
65
|
+
Two `Diagnostic` classes coexist and should NEVER be merged:
|
|
66
|
+
- `sim.driver.Diagnostic` — lint-time ({level, message, line}), pre-existing
|
|
67
|
+
- `sim.inspect.Diagnostic` — run-time ({severity, message, source, code, extra})
|
|
68
|
+
"""
|
|
69
|
+
from __future__ import annotations
|
|
70
|
+
|
|
71
|
+
import re
|
|
72
|
+
from dataclasses import dataclass, field
|
|
73
|
+
from typing import Any, Callable, Protocol, runtime_checkable
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ── schema dataclasses ─────────────────────────────────────────────────────────
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Diagnostic:
|
|
81
|
+
"""Run-time observation diagnostic. Fields align with 根本思路.md §三.
|
|
82
|
+
|
|
83
|
+
- severity: "error" | "warning" | "info"
|
|
84
|
+
- message: human-readable text
|
|
85
|
+
- source: channel identifier, e.g. "stderr" / "stdout" / "log:<path>"
|
|
86
|
+
/ "sdk:<ExcClass>" / "gui:<dialog-title>" / "process" / "traceback"
|
|
87
|
+
- code: opaque, driver-specific machine identifier (e.g.
|
|
88
|
+
"openfoam.bc.missing", "fluent.rpc.timeout", "python.NameError")
|
|
89
|
+
- extra: escape hatch for per-channel metadata (line numbers, window
|
|
90
|
+
handles, exception type, etc.) — never auto-promoted to top level
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
severity: str
|
|
94
|
+
message: str
|
|
95
|
+
source: str
|
|
96
|
+
code: str = ""
|
|
97
|
+
extra: dict = field(default_factory=dict)
|
|
98
|
+
|
|
99
|
+
def to_dict(self) -> dict:
|
|
100
|
+
return {
|
|
101
|
+
"severity": self.severity,
|
|
102
|
+
"message": self.message,
|
|
103
|
+
"source": self.source,
|
|
104
|
+
"code": self.code,
|
|
105
|
+
"extra": dict(self.extra),
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class Artifact:
|
|
111
|
+
"""Run-time output artifact. Fields align with 根本思路.md §三."""
|
|
112
|
+
|
|
113
|
+
path: str
|
|
114
|
+
size: int | None = None
|
|
115
|
+
mtime: str | None = None # ISO 8601 UTC string
|
|
116
|
+
role: str = "" # e.g. "solver-log" / "case" / "data" / "screenshot"
|
|
117
|
+
|
|
118
|
+
def to_dict(self) -> dict:
|
|
119
|
+
return {
|
|
120
|
+
"path": self.path,
|
|
121
|
+
"size": self.size,
|
|
122
|
+
"mtime": self.mtime,
|
|
123
|
+
"role": self.role,
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class ProbeResult:
|
|
129
|
+
"""What a single probe returns."""
|
|
130
|
+
|
|
131
|
+
diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
132
|
+
artifacts: list[Artifact] = field(default_factory=list)
|
|
133
|
+
raw: dict = field(default_factory=dict)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class InspectCtx:
|
|
138
|
+
"""Input bundle handed to every probe.
|
|
139
|
+
|
|
140
|
+
Contains every observable the runner/session has collected. Probes MUST
|
|
141
|
+
NOT mutate it.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
stdout: str
|
|
145
|
+
stderr: str
|
|
146
|
+
workdir: str
|
|
147
|
+
wall_time_s: float
|
|
148
|
+
exit_code: int
|
|
149
|
+
driver_name: str
|
|
150
|
+
session_ns: dict[str, Any] # live session namespace; {} for one-shot
|
|
151
|
+
workdir_before: list[str] | None = None
|
|
152
|
+
extras: dict[str, Any] = field(default_factory=dict)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# ── Protocol + collect loop ────────────────────────────────────────────────────
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@runtime_checkable
|
|
159
|
+
class InspectProbe(Protocol):
|
|
160
|
+
"""Structural type for anything the probe pipeline will call."""
|
|
161
|
+
|
|
162
|
+
name: str
|
|
163
|
+
|
|
164
|
+
def applies(self, ctx: InspectCtx) -> bool: ...
|
|
165
|
+
|
|
166
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult: ...
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def collect_diagnostics(
|
|
170
|
+
probes: list[InspectProbe], ctx: InspectCtx
|
|
171
|
+
) -> tuple[list[Diagnostic], list[Artifact]]:
|
|
172
|
+
"""Run every probe, concatenate results, isolate per-probe exceptions.
|
|
173
|
+
|
|
174
|
+
Before each probe runs, `ctx.extras["prior_diagnostics"]` is populated
|
|
175
|
+
with the accumulated diagnostics collected so far. Post-processor probes
|
|
176
|
+
like `DomainExceptionMapProbe` use this to upgrade/augment earlier
|
|
177
|
+
outputs without mutating them.
|
|
178
|
+
|
|
179
|
+
A crashing probe emits a synthetic `Diagnostic(severity="warning",
|
|
180
|
+
code="sim.inspect.probe_crashed", ...)` so the pipeline never becomes
|
|
181
|
+
load-bearing on probe correctness.
|
|
182
|
+
"""
|
|
183
|
+
diagnostics: list[Diagnostic] = []
|
|
184
|
+
artifacts: list[Artifact] = []
|
|
185
|
+
for p in probes:
|
|
186
|
+
# Make already-collected diagnostics visible to this probe
|
|
187
|
+
if ctx.extras is None:
|
|
188
|
+
ctx.extras = {}
|
|
189
|
+
ctx.extras["prior_diagnostics"] = list(diagnostics)
|
|
190
|
+
try:
|
|
191
|
+
if not p.applies(ctx):
|
|
192
|
+
continue
|
|
193
|
+
result = p.probe(ctx)
|
|
194
|
+
except Exception as exc:
|
|
195
|
+
diagnostics.append(Diagnostic(
|
|
196
|
+
severity="warning",
|
|
197
|
+
message=f"probe {p.name!r} crashed: {type(exc).__name__}: {exc}",
|
|
198
|
+
source=f"sim.inspect:{p.name}",
|
|
199
|
+
code="sim.inspect.probe_crashed",
|
|
200
|
+
))
|
|
201
|
+
continue
|
|
202
|
+
diagnostics.extend(result.diagnostics)
|
|
203
|
+
artifacts.extend(result.artifacts)
|
|
204
|
+
return diagnostics, artifacts
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ── probes ─────────────────────────────────────────────────────────────────────
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class ProcessMetaProbe:
|
|
211
|
+
"""Channel #1 — process meta. Turns exit_code + wall_time into one Diagnostic.
|
|
212
|
+
|
|
213
|
+
Always applies. Info-level when exit_code == 0; error when non-zero.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
name = "process-meta"
|
|
217
|
+
|
|
218
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
219
|
+
return True
|
|
220
|
+
|
|
221
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
222
|
+
if ctx.exit_code == 0:
|
|
223
|
+
diag = Diagnostic(
|
|
224
|
+
severity="info",
|
|
225
|
+
message=f"exit 0 in {ctx.wall_time_s:.2f}s",
|
|
226
|
+
source="process",
|
|
227
|
+
code="sim.process.exit_zero",
|
|
228
|
+
extra={"exit_code": 0, "wall_time_s": ctx.wall_time_s},
|
|
229
|
+
)
|
|
230
|
+
else:
|
|
231
|
+
diag = Diagnostic(
|
|
232
|
+
severity="error",
|
|
233
|
+
message=f"exit {ctx.exit_code} after {ctx.wall_time_s:.2f}s",
|
|
234
|
+
source="process",
|
|
235
|
+
code="sim.process.exit_nonzero",
|
|
236
|
+
extra={"exit_code": ctx.exit_code, "wall_time_s": ctx.wall_time_s},
|
|
237
|
+
)
|
|
238
|
+
return ProbeResult(diagnostics=[diag])
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class TextStreamRulesProbe:
|
|
242
|
+
"""Channel #2 / #7 — regex rules over any text stream.
|
|
243
|
+
|
|
244
|
+
One probe class, many instances. Driver declares `source` (channel id
|
|
245
|
+
like "stderr" / "log:log.simpleFoam") + `text_selector` (closure over
|
|
246
|
+
InspectCtx that returns the text to scan) + `rules` (list of
|
|
247
|
+
{pattern, severity, code, message_template?}).
|
|
248
|
+
|
|
249
|
+
Each rule match emits one Diagnostic. `extra.line` = 1-based line
|
|
250
|
+
number of the match; `extra.match` = first matching group if any.
|
|
251
|
+
`message_template` substitution: `{match}` / `{group1}` / `{group2}` / ...
|
|
252
|
+
If no template given, use the matched line (trimmed).
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
name = "text-stream-rules"
|
|
256
|
+
|
|
257
|
+
def __init__(
|
|
258
|
+
self,
|
|
259
|
+
source: str,
|
|
260
|
+
text_selector: Callable[[InspectCtx], str],
|
|
261
|
+
rules: list[dict],
|
|
262
|
+
):
|
|
263
|
+
self.source = source
|
|
264
|
+
self.text_selector = text_selector
|
|
265
|
+
self.rules = rules
|
|
266
|
+
# Pre-compile for perf + fail-fast on bad regex
|
|
267
|
+
self._compiled = [(re.compile(r["pattern"]), r) for r in rules]
|
|
268
|
+
|
|
269
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
270
|
+
try:
|
|
271
|
+
text = self.text_selector(ctx)
|
|
272
|
+
except Exception:
|
|
273
|
+
return False
|
|
274
|
+
return bool(text and text.strip())
|
|
275
|
+
|
|
276
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
277
|
+
text = self.text_selector(ctx)
|
|
278
|
+
diags: list[Diagnostic] = []
|
|
279
|
+
for lineno, line in enumerate(text.splitlines(), start=1):
|
|
280
|
+
for regex, rule in self._compiled:
|
|
281
|
+
m = regex.search(line)
|
|
282
|
+
if not m:
|
|
283
|
+
continue
|
|
284
|
+
template = rule.get("message_template")
|
|
285
|
+
if template:
|
|
286
|
+
subs: dict[str, str] = {"match": m.group(0)}
|
|
287
|
+
for i, g in enumerate(m.groups(), start=1):
|
|
288
|
+
subs[f"group{i}"] = g or ""
|
|
289
|
+
try:
|
|
290
|
+
message = template.format(**subs)
|
|
291
|
+
except (KeyError, IndexError):
|
|
292
|
+
message = template
|
|
293
|
+
else:
|
|
294
|
+
message = line.strip()
|
|
295
|
+
diags.append(Diagnostic(
|
|
296
|
+
severity=rule["severity"],
|
|
297
|
+
message=message,
|
|
298
|
+
source=self.source,
|
|
299
|
+
code=rule["code"],
|
|
300
|
+
extra={"line": lineno, "match": m.group(0)},
|
|
301
|
+
))
|
|
302
|
+
return ProbeResult(diagnostics=diags)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
_TRACEBACK_HEADER = "Traceback (most recent call last):"
|
|
306
|
+
# Match final "ExcClass: message" line after a traceback block
|
|
307
|
+
_EXC_LINE_RE = re.compile(r"^(\w+(?:\.\w+)*):\s*(.*)$")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class PythonTracebackProbe:
|
|
311
|
+
"""Channel #3 extension — detect + parse Python tracebacks.
|
|
312
|
+
|
|
313
|
+
Looks at `ctx.stderr` first, then `ctx.session_ns.get("_session_error")`
|
|
314
|
+
(convention used by session runtimes that capture exc via
|
|
315
|
+
`traceback.format_exc()`).
|
|
316
|
+
|
|
317
|
+
Emits one Diagnostic per distinct traceback found, with
|
|
318
|
+
`code = "python.<ExcClass>"`, `source = "traceback"`, `message` = the
|
|
319
|
+
final exception line (e.g. "name 'x' is not defined").
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
name = "python-traceback"
|
|
323
|
+
|
|
324
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
325
|
+
sources = (
|
|
326
|
+
ctx.stderr or "",
|
|
327
|
+
ctx.session_ns.get("_session_error", "") if ctx.session_ns else "",
|
|
328
|
+
)
|
|
329
|
+
return any(_TRACEBACK_HEADER in s for s in sources)
|
|
330
|
+
|
|
331
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
332
|
+
diags: list[Diagnostic] = []
|
|
333
|
+
seen: set[tuple[str, str]] = set()
|
|
334
|
+
for text in (
|
|
335
|
+
ctx.stderr or "",
|
|
336
|
+
ctx.session_ns.get("_session_error", "") if ctx.session_ns else "",
|
|
337
|
+
):
|
|
338
|
+
for d in self._parse_tracebacks(text):
|
|
339
|
+
key = (d.code, d.message)
|
|
340
|
+
if key in seen:
|
|
341
|
+
continue
|
|
342
|
+
seen.add(key)
|
|
343
|
+
diags.append(d)
|
|
344
|
+
return ProbeResult(diagnostics=diags)
|
|
345
|
+
|
|
346
|
+
def _parse_tracebacks(self, text: str) -> list[Diagnostic]:
|
|
347
|
+
if not text or _TRACEBACK_HEADER not in text:
|
|
348
|
+
return []
|
|
349
|
+
out: list[Diagnostic] = []
|
|
350
|
+
lines = text.splitlines()
|
|
351
|
+
i = 0
|
|
352
|
+
while i < len(lines):
|
|
353
|
+
if lines[i].strip() == _TRACEBACK_HEADER:
|
|
354
|
+
# Scan down for the final "ExcClass: message" line
|
|
355
|
+
j = i + 1
|
|
356
|
+
exc_class = None
|
|
357
|
+
exc_msg = ""
|
|
358
|
+
last_file_line = None
|
|
359
|
+
while j < len(lines):
|
|
360
|
+
stripped = lines[j].strip()
|
|
361
|
+
if not stripped:
|
|
362
|
+
j += 1
|
|
363
|
+
continue
|
|
364
|
+
if stripped.startswith("File "):
|
|
365
|
+
last_file_line = stripped
|
|
366
|
+
j += 1
|
|
367
|
+
continue
|
|
368
|
+
if stripped.startswith(_TRACEBACK_HEADER):
|
|
369
|
+
# another traceback begins — stop
|
|
370
|
+
break
|
|
371
|
+
if lines[j].startswith(" "):
|
|
372
|
+
# indented continuation (code line or caret)
|
|
373
|
+
j += 1
|
|
374
|
+
continue
|
|
375
|
+
m = _EXC_LINE_RE.match(stripped)
|
|
376
|
+
if m:
|
|
377
|
+
exc_class, exc_msg = m.group(1), m.group(2)
|
|
378
|
+
j += 1
|
|
379
|
+
break
|
|
380
|
+
j += 1
|
|
381
|
+
if exc_class:
|
|
382
|
+
extra: dict = {}
|
|
383
|
+
if last_file_line:
|
|
384
|
+
extra["last_frame"] = last_file_line
|
|
385
|
+
out.append(Diagnostic(
|
|
386
|
+
severity="error",
|
|
387
|
+
message=exc_msg or exc_class,
|
|
388
|
+
source="traceback",
|
|
389
|
+
code=f"python.{exc_class}",
|
|
390
|
+
extra=extra,
|
|
391
|
+
))
|
|
392
|
+
i = j
|
|
393
|
+
else:
|
|
394
|
+
i += 1
|
|
395
|
+
return out
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
class RuntimeTimeoutProbe:
|
|
399
|
+
"""Synthetic — emits a structured diagnostic when a session exec was
|
|
400
|
+
interrupted by per-snippet timeout.
|
|
401
|
+
|
|
402
|
+
Looks at `ctx.extras["timeout_hit"]` (bool) + `ctx.extras["timeout_s"]`
|
|
403
|
+
(float) populated by the driver's `run()` when `call_with_timeout` came
|
|
404
|
+
back with `hung=True`.
|
|
405
|
+
|
|
406
|
+
Without this, a timeout would only show up as a free-text
|
|
407
|
+
`record.error` string — nothing to switch on.
|
|
408
|
+
"""
|
|
409
|
+
|
|
410
|
+
name = "runtime-timeout"
|
|
411
|
+
|
|
412
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
413
|
+
return bool((ctx.extras or {}).get("timeout_hit"))
|
|
414
|
+
|
|
415
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
416
|
+
extras = ctx.extras or {}
|
|
417
|
+
t = extras.get("timeout_s", 0.0)
|
|
418
|
+
elapsed = extras.get("timeout_elapsed_s", t)
|
|
419
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
420
|
+
severity="error",
|
|
421
|
+
source="sim.runtime",
|
|
422
|
+
code="sim.runtime.snippet_timeout",
|
|
423
|
+
message=(f"snippet exceeded timeout_s={t} (elapsed {elapsed:.1f}s); "
|
|
424
|
+
f"session is likely unusable — disconnect + re-launch"),
|
|
425
|
+
extra={"timeout_s": t, "elapsed_s": elapsed},
|
|
426
|
+
)])
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
class StdoutJsonTailProbe:
|
|
430
|
+
"""Channel #3 — stdout JSON-tail convention.
|
|
431
|
+
|
|
432
|
+
Scans stdout in reverse for the last line that parses as a JSON object,
|
|
433
|
+
and emits one info Diagnostic with source="stdout:json" and the parsed
|
|
434
|
+
dict in `extra.value`. Also falls back to `session_ns.get("_result")`
|
|
435
|
+
if that is a dict/list and no stdout JSON line is found.
|
|
436
|
+
|
|
437
|
+
This makes the existing "print(json.dumps(...))" pattern — used by ~30
|
|
438
|
+
of our drivers' parse_output() — inspectable from the probe layer too,
|
|
439
|
+
without each driver having to duplicate the scan.
|
|
440
|
+
"""
|
|
441
|
+
|
|
442
|
+
name = "stdout-json-tail"
|
|
443
|
+
|
|
444
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
445
|
+
if ctx.stdout and ctx.stdout.strip():
|
|
446
|
+
return True
|
|
447
|
+
res = (ctx.session_ns or {}).get("_result")
|
|
448
|
+
return isinstance(res, (dict, list))
|
|
449
|
+
|
|
450
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
451
|
+
import json # noqa: PLC0415
|
|
452
|
+
|
|
453
|
+
parsed: Any = None
|
|
454
|
+
found_from = None
|
|
455
|
+
line_no = None
|
|
456
|
+
for candidate in reversed((ctx.stdout or "").splitlines()):
|
|
457
|
+
s = candidate.strip()
|
|
458
|
+
if not s or s[:1] not in "{[":
|
|
459
|
+
continue
|
|
460
|
+
try:
|
|
461
|
+
parsed = json.loads(s)
|
|
462
|
+
found_from = "stdout"
|
|
463
|
+
line_no = len((ctx.stdout or "").splitlines()) - list(
|
|
464
|
+
reversed((ctx.stdout or "").splitlines())
|
|
465
|
+
).index(candidate)
|
|
466
|
+
break
|
|
467
|
+
except json.JSONDecodeError:
|
|
468
|
+
continue
|
|
469
|
+
|
|
470
|
+
if parsed is None:
|
|
471
|
+
res = (ctx.session_ns or {}).get("_result")
|
|
472
|
+
if isinstance(res, (dict, list)):
|
|
473
|
+
parsed = res
|
|
474
|
+
found_from = "session_result"
|
|
475
|
+
|
|
476
|
+
if parsed is None:
|
|
477
|
+
return ProbeResult()
|
|
478
|
+
|
|
479
|
+
try:
|
|
480
|
+
preview = json.dumps(parsed, ensure_ascii=False, default=str)
|
|
481
|
+
except Exception:
|
|
482
|
+
preview = repr(parsed)
|
|
483
|
+
if len(preview) > 300:
|
|
484
|
+
preview = preview[:297] + "..."
|
|
485
|
+
|
|
486
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
487
|
+
severity="info",
|
|
488
|
+
message=f"parsed {found_from}: {preview}",
|
|
489
|
+
source=f"stdout:json",
|
|
490
|
+
code="sim.stdout.json_tail",
|
|
491
|
+
extra={
|
|
492
|
+
"source_kind": found_from,
|
|
493
|
+
"line": line_no,
|
|
494
|
+
"value": parsed,
|
|
495
|
+
},
|
|
496
|
+
)])
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
class SdkAttributeProbe:
|
|
500
|
+
"""Channel #4 — SDK object attribute reader.
|
|
501
|
+
|
|
502
|
+
Two construction modes (mutually exclusive):
|
|
503
|
+
|
|
504
|
+
1. `attr_paths=["setup.models.viscous.model", ...]` — walks `getattr` chain
|
|
505
|
+
on `ctx.session_ns["session"]`; if the final attribute is callable
|
|
506
|
+
(pyfluent wraps many properties as SettingsObject() callables), calls
|
|
507
|
+
it with no args. Used by Phase 1 Fluent driver.
|
|
508
|
+
|
|
509
|
+
2. `readers=[(label, callable(session) -> value), ...]` — the caller
|
|
510
|
+
provides arbitrary extractors. Used by COMSOL driver, whose Java API
|
|
511
|
+
(`model.feature('stat1').getString('type')`) does not fit a
|
|
512
|
+
getattr-chain. Label appears in `source=<prefix>:<label>` and
|
|
513
|
+
`code=<code_prefix>.<label>`.
|
|
514
|
+
|
|
515
|
+
Successful read → info Diagnostic. Raised exception → warning
|
|
516
|
+
Diagnostic with `code="sim.sdk.attr_read_failed"`, probe continues
|
|
517
|
+
past it to the next path/reader.
|
|
518
|
+
"""
|
|
519
|
+
|
|
520
|
+
name = "sdk-attribute"
|
|
521
|
+
|
|
522
|
+
def __init__(
|
|
523
|
+
self,
|
|
524
|
+
attr_paths: list[str] | None = None,
|
|
525
|
+
readers: list[tuple[str, Callable[[Any], Any]]] | None = None,
|
|
526
|
+
call_callables: bool = True,
|
|
527
|
+
source_prefix: str = "sdk:attr",
|
|
528
|
+
code_prefix: str = "fluent.sdk.attr",
|
|
529
|
+
):
|
|
530
|
+
if attr_paths is not None and readers is not None:
|
|
531
|
+
raise ValueError(
|
|
532
|
+
"SdkAttributeProbe: pass EITHER attr_paths OR readers, not both"
|
|
533
|
+
)
|
|
534
|
+
if attr_paths is None and readers is None:
|
|
535
|
+
raise ValueError(
|
|
536
|
+
"SdkAttributeProbe: must pass attr_paths or readers"
|
|
537
|
+
)
|
|
538
|
+
self.call_callables = call_callables
|
|
539
|
+
self.source_prefix = source_prefix
|
|
540
|
+
self.code_prefix = code_prefix
|
|
541
|
+
if readers is not None:
|
|
542
|
+
# Readers mode: caller supplies (label, callable) pairs
|
|
543
|
+
self._readers: list[tuple[str, Callable[[Any], Any]]] = list(readers)
|
|
544
|
+
else:
|
|
545
|
+
# attr_paths mode: synthesize readers from getattr chains
|
|
546
|
+
self._readers = [
|
|
547
|
+
(path, self._make_getattr_reader(path))
|
|
548
|
+
for path in attr_paths
|
|
549
|
+
]
|
|
550
|
+
|
|
551
|
+
def _make_getattr_reader(self, path: str) -> Callable[[Any], Any]:
|
|
552
|
+
parts = path.split(".")
|
|
553
|
+
|
|
554
|
+
def _reader(root):
|
|
555
|
+
obj = root
|
|
556
|
+
for part in parts:
|
|
557
|
+
obj = getattr(obj, part)
|
|
558
|
+
if self.call_callables and callable(obj):
|
|
559
|
+
try:
|
|
560
|
+
return obj()
|
|
561
|
+
except TypeError:
|
|
562
|
+
return obj
|
|
563
|
+
return obj
|
|
564
|
+
|
|
565
|
+
return _reader
|
|
566
|
+
|
|
567
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
568
|
+
return bool((ctx.session_ns or {}).get("session"))
|
|
569
|
+
|
|
570
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
571
|
+
session = (ctx.session_ns or {}).get("session")
|
|
572
|
+
diags: list[Diagnostic] = []
|
|
573
|
+
for label, reader in self._readers:
|
|
574
|
+
source = f"{self.source_prefix}:{label}"
|
|
575
|
+
code = f"{self.code_prefix}.{label}"
|
|
576
|
+
try:
|
|
577
|
+
value = reader(session)
|
|
578
|
+
except Exception as exc:
|
|
579
|
+
diags.append(Diagnostic(
|
|
580
|
+
severity="warning",
|
|
581
|
+
source=source,
|
|
582
|
+
code="sim.sdk.attr_read_failed",
|
|
583
|
+
message=f"{label}: {type(exc).__name__}: {exc}",
|
|
584
|
+
extra={"label": label, "exception": type(exc).__name__},
|
|
585
|
+
))
|
|
586
|
+
continue
|
|
587
|
+
try:
|
|
588
|
+
value_repr = repr(value)
|
|
589
|
+
except Exception:
|
|
590
|
+
value_repr = f"<unreprable {type(value).__name__}>"
|
|
591
|
+
if len(value_repr) > 300:
|
|
592
|
+
value_repr = value_repr[:297] + "..."
|
|
593
|
+
diags.append(Diagnostic(
|
|
594
|
+
severity="info",
|
|
595
|
+
source=source,
|
|
596
|
+
code=code,
|
|
597
|
+
message=f"{label} = {value_repr}",
|
|
598
|
+
extra={"label": label, "value_repr": value_repr},
|
|
599
|
+
))
|
|
600
|
+
return ProbeResult(diagnostics=diags)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
# Default exception-map rules for DomainExceptionMapProbe.
|
|
604
|
+
#
|
|
605
|
+
# Deliberately empty — solver-specific exception→domain-code mapping is a
|
|
606
|
+
# semantic judgement ("this Python exception means a Fluent RPC timeout")
|
|
607
|
+
# and that belongs to the agent / sim-skills layer, not the driver layer.
|
|
608
|
+
# The class remains available so a skill or agent can pass its own rules
|
|
609
|
+
# explicitly via DomainExceptionMapProbe(rules=[...]).
|
|
610
|
+
_EXC_MAP_RULES: list[dict] = []
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
class DomainExceptionMapProbe:
|
|
614
|
+
"""Channel #5 — Fluent-specific exception → domain code upgrader.
|
|
615
|
+
|
|
616
|
+
Post-processor. Reads `ctx.extras["prior_diagnostics"]` (populated by
|
|
617
|
+
`collect_diagnostics` between probe invocations) and, for each prior
|
|
618
|
+
diag whose code matches a python.* pattern AND message matches a domain
|
|
619
|
+
signature, emits a NEW diag with an upgraded `fluent.*` code. The
|
|
620
|
+
original python.* diag is preserved (never mutated); agents see both
|
|
621
|
+
and can prefer the domain code when available.
|
|
622
|
+
"""
|
|
623
|
+
|
|
624
|
+
name = "domain-exception-map"
|
|
625
|
+
|
|
626
|
+
def __init__(self, rules: list[dict] | None = None):
|
|
627
|
+
self.rules = rules or _EXC_MAP_RULES
|
|
628
|
+
self._compiled = [(re.compile(r["regex"]), r) for r in self.rules]
|
|
629
|
+
|
|
630
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
631
|
+
priors = (ctx.extras or {}).get("prior_diagnostics") or []
|
|
632
|
+
return bool(priors)
|
|
633
|
+
|
|
634
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
635
|
+
priors = (ctx.extras or {}).get("prior_diagnostics") or []
|
|
636
|
+
diags: list[Diagnostic] = []
|
|
637
|
+
for prior in priors:
|
|
638
|
+
# prior is a Diagnostic instance
|
|
639
|
+
code_in = getattr(prior, "code", "") or ""
|
|
640
|
+
msg_in = getattr(prior, "message", "") or ""
|
|
641
|
+
for regex, rule in self._compiled:
|
|
642
|
+
if rule["code_in"] and code_in not in rule["code_in"]:
|
|
643
|
+
continue
|
|
644
|
+
m = regex.search(msg_in)
|
|
645
|
+
if not m:
|
|
646
|
+
continue
|
|
647
|
+
# Build the new message
|
|
648
|
+
subs: dict[str, str] = {"match": m.group(0), "orig": msg_in}
|
|
649
|
+
for i, g in enumerate(m.groups(), start=1):
|
|
650
|
+
subs[f"group{i}"] = g or ""
|
|
651
|
+
try:
|
|
652
|
+
new_msg = rule["message_template"].format(**subs)
|
|
653
|
+
except (KeyError, IndexError):
|
|
654
|
+
new_msg = rule["message_template"]
|
|
655
|
+
# If the original had a helpful hint, preserve a ref to it
|
|
656
|
+
if "most similar names are" in msg_in:
|
|
657
|
+
new_msg = new_msg + " | pyfluent hint: " + msg_in.split(
|
|
658
|
+
"most similar names are", 1)[1].strip()
|
|
659
|
+
diags.append(Diagnostic(
|
|
660
|
+
severity="error",
|
|
661
|
+
source=getattr(prior, "source", "traceback"),
|
|
662
|
+
code=rule["upgrade_code"],
|
|
663
|
+
message=new_msg,
|
|
664
|
+
extra={
|
|
665
|
+
"upgraded_from": code_in,
|
|
666
|
+
"original_message": msg_in[:500],
|
|
667
|
+
"match": m.group(0),
|
|
668
|
+
},
|
|
669
|
+
))
|
|
670
|
+
break
|
|
671
|
+
return ProbeResult(diagnostics=diags)
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
_WORKDIR_ROLE_RULES: list[tuple[str, str]] = [
|
|
675
|
+
# Fluent
|
|
676
|
+
(".cas.h5", "case"),
|
|
677
|
+
(".cas", "case"),
|
|
678
|
+
(".dat.h5", "data"),
|
|
679
|
+
(".dat", "data"),
|
|
680
|
+
(".msh.h5", "mesh"),
|
|
681
|
+
(".msh", "mesh"),
|
|
682
|
+
(".trn", "transcript"),
|
|
683
|
+
# COMSOL (Phase 2)
|
|
684
|
+
(".mph", "comsol-model"),
|
|
685
|
+
(".class", "jvm-class"),
|
|
686
|
+
(".java", "java-source"),
|
|
687
|
+
# Generic solver output
|
|
688
|
+
(".out", "solver-log"),
|
|
689
|
+
(".log", "solver-log"),
|
|
690
|
+
(".png", "screenshot"),
|
|
691
|
+
(".jpg", "image"),
|
|
692
|
+
(".csv", "result-csv"),
|
|
693
|
+
]
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _pick_role(filename: str) -> str:
|
|
697
|
+
low = filename.lower()
|
|
698
|
+
for ext, role in _WORKDIR_ROLE_RULES:
|
|
699
|
+
if low.endswith(ext):
|
|
700
|
+
return role
|
|
701
|
+
return "output"
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
class WorkdirDiffProbe:
|
|
705
|
+
"""Channel #9 — workdir before/after diff → Artifact list.
|
|
706
|
+
|
|
707
|
+
Needs `ctx.workdir_before` (list of relative paths) populated by the
|
|
708
|
+
driver/runner BEFORE exec. Probes the workdir after exec, emits one
|
|
709
|
+
Artifact per newly-introduced file, with role inferred from extension.
|
|
710
|
+
|
|
711
|
+
For persistent sessions, the 'before' list is the driver's
|
|
712
|
+
responsibility (take a snapshot inside `run()`). For one-shot
|
|
713
|
+
`execute_script`, Phase 2 will wire this in similarly.
|
|
714
|
+
"""
|
|
715
|
+
|
|
716
|
+
name = "workdir-diff"
|
|
717
|
+
|
|
718
|
+
def __init__(self, workdir_getter=None):
|
|
719
|
+
self.workdir_getter = workdir_getter or (lambda ctx: ctx.workdir)
|
|
720
|
+
|
|
721
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
722
|
+
return ctx.workdir_before is not None
|
|
723
|
+
|
|
724
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
725
|
+
import time as _time # noqa: PLC0415
|
|
726
|
+
from pathlib import Path as _Path # noqa: PLC0415
|
|
727
|
+
|
|
728
|
+
workdir = _Path(self.workdir_getter(ctx))
|
|
729
|
+
if not workdir.is_dir():
|
|
730
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
731
|
+
severity="warning",
|
|
732
|
+
source="workdir",
|
|
733
|
+
code="sim.workdir.missing",
|
|
734
|
+
message=f"workdir not accessible: {workdir}",
|
|
735
|
+
)])
|
|
736
|
+
before = set(ctx.workdir_before or [])
|
|
737
|
+
arts: list[Artifact] = []
|
|
738
|
+
try:
|
|
739
|
+
now_files = [p for p in workdir.rglob("*") if p.is_file()]
|
|
740
|
+
except Exception as exc:
|
|
741
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
742
|
+
severity="warning", source="workdir",
|
|
743
|
+
code="sim.workdir.scan_failed",
|
|
744
|
+
message=f"{type(exc).__name__}: {exc}",
|
|
745
|
+
)])
|
|
746
|
+
for p in sorted(now_files):
|
|
747
|
+
try:
|
|
748
|
+
rel = str(p.relative_to(workdir)).replace("\\", "/")
|
|
749
|
+
except Exception:
|
|
750
|
+
rel = str(p)
|
|
751
|
+
if rel in before:
|
|
752
|
+
continue
|
|
753
|
+
try:
|
|
754
|
+
st = p.stat()
|
|
755
|
+
size = st.st_size
|
|
756
|
+
mtime = _time.strftime(
|
|
757
|
+
"%Y-%m-%dT%H:%M:%SZ", _time.gmtime(st.st_mtime))
|
|
758
|
+
except Exception:
|
|
759
|
+
size, mtime = None, None
|
|
760
|
+
role = _pick_role(p.name)
|
|
761
|
+
arts.append(Artifact(
|
|
762
|
+
path=str(p), size=size, mtime=mtime, role=role,
|
|
763
|
+
))
|
|
764
|
+
return ProbeResult(artifacts=arts)
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
def generic_probes() -> list:
|
|
768
|
+
"""任何 session driver 都可以免费使用的 5 个通用 probe。
|
|
769
|
+
|
|
770
|
+
#1 ProcessMetaProbe exit_code + wall_time
|
|
771
|
+
#1+ RuntimeTimeoutProbe hung-snippet 检测
|
|
772
|
+
#3 StdoutJsonTailProbe 最后一行 JSON / _result fallback
|
|
773
|
+
#3+ PythonTracebackProbe 结构化 traceback 解析
|
|
774
|
+
#9 WorkdirDiffProbe 新增文件 → Artifacts
|
|
775
|
+
|
|
776
|
+
需要 SDK 状态查询(#4)、日志扫描(#6/#7)、GUI 观察(#8a/#8b)的 driver
|
|
777
|
+
在此基础上追加 solver 专用 probe。
|
|
778
|
+
"""
|
|
779
|
+
return [
|
|
780
|
+
ProcessMetaProbe(),
|
|
781
|
+
RuntimeTimeoutProbe(),
|
|
782
|
+
StdoutJsonTailProbe(),
|
|
783
|
+
PythonTracebackProbe(),
|
|
784
|
+
WorkdirDiffProbe(),
|
|
785
|
+
]
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _find_matching_windows(
|
|
789
|
+
process_name_substrings: tuple[str, ...],
|
|
790
|
+
) -> tuple[list[dict], int, list[str]]:
|
|
791
|
+
"""Shared helper: enumerate top-level windows owned by any process whose
|
|
792
|
+
name contains one of the given substrings. Returns (matches, total_scanned,
|
|
793
|
+
errors). Each match dict: {window, pid, proc_name, title, rect}.
|
|
794
|
+
|
|
795
|
+
`rect` is (left, top, right, bottom) int tuple, or None if rect-fetch
|
|
796
|
+
failed. `window` is the raw pywinauto wrapper (use it for capture).
|
|
797
|
+
|
|
798
|
+
Lazy-imports pywinauto + psutil so this module stays importable on Linux
|
|
799
|
+
/ in headless environments.
|
|
800
|
+
"""
|
|
801
|
+
errors: list[str] = []
|
|
802
|
+
try:
|
|
803
|
+
from pywinauto import Desktop # noqa: PLC0415
|
|
804
|
+
import psutil # noqa: PLC0415
|
|
805
|
+
except Exception as exc:
|
|
806
|
+
errors.append(f"{type(exc).__name__}: {exc}")
|
|
807
|
+
return [], 0, errors
|
|
808
|
+
|
|
809
|
+
try:
|
|
810
|
+
windows = Desktop(backend="uia").windows()
|
|
811
|
+
except Exception as exc:
|
|
812
|
+
errors.append(f"Desktop enumeration: {type(exc).__name__}: {exc}")
|
|
813
|
+
return [], 0, errors
|
|
814
|
+
|
|
815
|
+
subs = tuple(s.lower() for s in process_name_substrings)
|
|
816
|
+
matches: list[dict] = []
|
|
817
|
+
total = 0
|
|
818
|
+
for w in windows:
|
|
819
|
+
total += 1
|
|
820
|
+
try:
|
|
821
|
+
pid = w.process_id()
|
|
822
|
+
try:
|
|
823
|
+
proc_name = psutil.Process(pid).name().lower()
|
|
824
|
+
except Exception:
|
|
825
|
+
proc_name = ""
|
|
826
|
+
if not any(sub in proc_name for sub in subs):
|
|
827
|
+
continue
|
|
828
|
+
title = w.window_text() or ""
|
|
829
|
+
try:
|
|
830
|
+
r = w.rectangle()
|
|
831
|
+
rect = (int(r.left), int(r.top), int(r.right), int(r.bottom))
|
|
832
|
+
except Exception:
|
|
833
|
+
rect = None
|
|
834
|
+
matches.append({
|
|
835
|
+
"window": w, "pid": pid, "proc_name": proc_name,
|
|
836
|
+
"title": title, "rect": rect,
|
|
837
|
+
})
|
|
838
|
+
except Exception:
|
|
839
|
+
continue
|
|
840
|
+
return matches, total, errors
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
class GuiDialogProbe:
|
|
844
|
+
"""Channel #8a — GUI dialog enumeration via pywinauto (Windows only).
|
|
845
|
+
|
|
846
|
+
Walks top-level windows belonging to the matched process(es) and emits
|
|
847
|
+
one Diagnostic per window. If the title contains a dialog-hint keyword
|
|
848
|
+
("Error" / "Warning" / "Confirm" / ...) severity is escalated to
|
|
849
|
+
"error" with `code=fluent.gui.dialog_detected`.
|
|
850
|
+
|
|
851
|
+
Always emits a final `sim.inspect.gui_scan_summary` info diag so probe
|
|
852
|
+
activity is observable even when nothing matches.
|
|
853
|
+
|
|
854
|
+
`process_name_substrings` default matches Fluent's frontend: `cx####.exe`
|
|
855
|
+
(Cortex for Fluent 2024 R1 = cx2410.exe, 2025 R1 = cx2510.exe, ...)
|
|
856
|
+
plus `fluent` / `ansys` for completeness.
|
|
857
|
+
|
|
858
|
+
Lazy-imports pywinauto so sim-cli stays importable on Linux.
|
|
859
|
+
"""
|
|
860
|
+
|
|
861
|
+
name = "gui-dialog"
|
|
862
|
+
# ── Severity-classification hints (Plan C, 2026-04-22) ─────────────────
|
|
863
|
+
#
|
|
864
|
+
# Boss's first-principles challenge: "agent 自己能读懂各种语言,为啥还要
|
|
865
|
+
# probe 做文字匹配?" — correct. Maintaining a multilingual keyword table
|
|
866
|
+
# is a hopeless arms race and delegates work the agent does cheaply with
|
|
867
|
+
# its LLM. Plan C: we ONLY pre-escalate on **English strong-signal** words
|
|
868
|
+
# that are de-facto programming convention for "hard failure" — these
|
|
869
|
+
# appear in 95%+ of CAE dialogs regardless of the UI's primary language
|
|
870
|
+
# (because developers write error messages in English first). Anything
|
|
871
|
+
# else stays severity=info with the full title + screenshot — the agent's
|
|
872
|
+
# LLM reads Chinese/French/Japanese/... natively and decides for itself.
|
|
873
|
+
#
|
|
874
|
+
# Rationale lives in sim-proj/inspect-probes-PLAN.md §二·六.
|
|
875
|
+
_ERROR_SIGNAL_HINTS = (
|
|
876
|
+
"error", "fatal", "abort", "failed", "crash", "exception",
|
|
877
|
+
)
|
|
878
|
+
_WARNING_SIGNAL_HINTS = ("warning",)
|
|
879
|
+
|
|
880
|
+
def __init__(
|
|
881
|
+
self,
|
|
882
|
+
process_name_substrings: tuple[str, ...] = ("fluent", "ansys", "cx", "cortex"),
|
|
883
|
+
code_prefix: str = "fluent.gui",
|
|
884
|
+
):
|
|
885
|
+
self.process_name_substrings = tuple(s.lower() for s in process_name_substrings)
|
|
886
|
+
self.code_prefix = code_prefix
|
|
887
|
+
|
|
888
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
889
|
+
try:
|
|
890
|
+
import pywinauto # noqa: F401, PLC0415
|
|
891
|
+
return True
|
|
892
|
+
except Exception:
|
|
893
|
+
return False
|
|
894
|
+
|
|
895
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
896
|
+
matches, total, errors = _find_matching_windows(self.process_name_substrings)
|
|
897
|
+
diags: list[Diagnostic] = []
|
|
898
|
+
if errors:
|
|
899
|
+
for msg in errors:
|
|
900
|
+
diags.append(Diagnostic(
|
|
901
|
+
severity="warning",
|
|
902
|
+
message=msg,
|
|
903
|
+
source="gui:dialog",
|
|
904
|
+
code="sim.inspect.gui_enum_failed",
|
|
905
|
+
))
|
|
906
|
+
return ProbeResult(diagnostics=diags)
|
|
907
|
+
|
|
908
|
+
for m in matches:
|
|
909
|
+
proc_name, pid, title = m["proc_name"], m["pid"], m["title"]
|
|
910
|
+
if not title.strip():
|
|
911
|
+
diags.append(Diagnostic(
|
|
912
|
+
severity="info",
|
|
913
|
+
message=f"(untitled window on {proc_name}, pid={pid})",
|
|
914
|
+
source=f"gui:dialog:{proc_name}",
|
|
915
|
+
code=f"{self.code_prefix}.window_observed_untitled",
|
|
916
|
+
extra={"pid": pid, "process": proc_name, "rect": m["rect"]},
|
|
917
|
+
))
|
|
918
|
+
continue
|
|
919
|
+
low = title.lower()
|
|
920
|
+
if any(h in low for h in self._ERROR_SIGNAL_HINTS):
|
|
921
|
+
severity = "error"
|
|
922
|
+
code = f"{self.code_prefix}.dialog_with_error_signal"
|
|
923
|
+
elif any(h in low for h in self._WARNING_SIGNAL_HINTS):
|
|
924
|
+
severity = "warning"
|
|
925
|
+
code = f"{self.code_prefix}.dialog_with_warning_signal"
|
|
926
|
+
else:
|
|
927
|
+
# Plan C: every other observed window is neutral info.
|
|
928
|
+
# Agent reads the title (+ any paired screenshot artifact
|
|
929
|
+
# via #8b) and decides with its LLM whether this is a
|
|
930
|
+
# blocker. Probe intentionally does NOT guess based on
|
|
931
|
+
# localized keywords — that's the agent's job.
|
|
932
|
+
severity = "info"
|
|
933
|
+
code = f"{self.code_prefix}.window_observed"
|
|
934
|
+
diags.append(Diagnostic(
|
|
935
|
+
severity=severity,
|
|
936
|
+
message=title[:300],
|
|
937
|
+
source=f"gui:dialog:{proc_name}",
|
|
938
|
+
code=code,
|
|
939
|
+
extra={"pid": pid, "process": proc_name, "title": title,
|
|
940
|
+
"rect": m["rect"]},
|
|
941
|
+
))
|
|
942
|
+
matched_procs = sorted({m["proc_name"] for m in matches})
|
|
943
|
+
diags.append(Diagnostic(
|
|
944
|
+
severity="info",
|
|
945
|
+
message=(f"scanned {total} top-level windows; matched {len(matches)} "
|
|
946
|
+
f"on processes: {matched_procs or 'none'}"),
|
|
947
|
+
source="gui:dialog",
|
|
948
|
+
code="sim.inspect.gui_scan_summary",
|
|
949
|
+
extra={"total_windows": total,
|
|
950
|
+
"matched_processes": matched_procs,
|
|
951
|
+
"match_count": len(matches)},
|
|
952
|
+
))
|
|
953
|
+
return ProbeResult(diagnostics=diags)
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
class ScreenshotProbe:
|
|
957
|
+
"""Channel #8b — per-window screenshot capture via PIL.ImageGrab bbox.
|
|
958
|
+
|
|
959
|
+
IMPORTANT: this probe captures ONLY the bounding box of each matched
|
|
960
|
+
Fluent window, NOT the whole desktop. If no Fluent window is found,
|
|
961
|
+
emits a single warning diag and nothing else — we never fall back to
|
|
962
|
+
full-screen capture (that creates noisy / PII-risky artifacts).
|
|
963
|
+
|
|
964
|
+
Every matched window produces:
|
|
965
|
+
- one Artifact (role="screenshot", path=<png>)
|
|
966
|
+
- one info Diag (source=gui:screenshot, code=sim.screenshot.captured)
|
|
967
|
+
|
|
968
|
+
PNGs land in `ctx.workdir/screenshots/<prefix>_<pid>_<ts>.png`.
|
|
969
|
+
"""
|
|
970
|
+
|
|
971
|
+
name = "screenshot"
|
|
972
|
+
|
|
973
|
+
def __init__(
|
|
974
|
+
self,
|
|
975
|
+
filename_prefix: str = "shot",
|
|
976
|
+
process_name_substrings: tuple[str, ...] = ("fluent", "ansys", "cx", "cortex"),
|
|
977
|
+
):
|
|
978
|
+
self.filename_prefix = filename_prefix
|
|
979
|
+
self.process_name_substrings = tuple(s.lower() for s in process_name_substrings)
|
|
980
|
+
|
|
981
|
+
def applies(self, ctx: InspectCtx) -> bool:
|
|
982
|
+
try:
|
|
983
|
+
from PIL import ImageGrab # noqa: F401, PLC0415
|
|
984
|
+
import pywinauto # noqa: F401, PLC0415
|
|
985
|
+
return True
|
|
986
|
+
except Exception:
|
|
987
|
+
return False
|
|
988
|
+
|
|
989
|
+
def probe(self, ctx: InspectCtx) -> ProbeResult:
|
|
990
|
+
import time as _time # noqa: PLC0415
|
|
991
|
+
from pathlib import Path as _Path # noqa: PLC0415
|
|
992
|
+
|
|
993
|
+
try:
|
|
994
|
+
from PIL import ImageGrab # noqa: PLC0415
|
|
995
|
+
except Exception as exc:
|
|
996
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
997
|
+
severity="warning", source="gui:screenshot",
|
|
998
|
+
code="sim.inspect.screenshot_unavailable",
|
|
999
|
+
message=f"PIL.ImageGrab unavailable: {exc}",
|
|
1000
|
+
)])
|
|
1001
|
+
|
|
1002
|
+
matches, _, errors = _find_matching_windows(self.process_name_substrings)
|
|
1003
|
+
if errors:
|
|
1004
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
1005
|
+
severity="warning", source="gui:screenshot",
|
|
1006
|
+
code="sim.inspect.screenshot_enum_failed",
|
|
1007
|
+
message="; ".join(errors),
|
|
1008
|
+
)])
|
|
1009
|
+
|
|
1010
|
+
if not matches:
|
|
1011
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
1012
|
+
severity="info", source="gui:screenshot",
|
|
1013
|
+
code="sim.screenshot.no_window",
|
|
1014
|
+
message=(f"no window matched {self.process_name_substrings}; "
|
|
1015
|
+
f"no screenshot taken (full-screen fallback disabled)"),
|
|
1016
|
+
)])
|
|
1017
|
+
|
|
1018
|
+
try:
|
|
1019
|
+
shots_dir = _Path(ctx.workdir) / "screenshots"
|
|
1020
|
+
shots_dir.mkdir(parents=True, exist_ok=True)
|
|
1021
|
+
except Exception as exc:
|
|
1022
|
+
return ProbeResult(diagnostics=[Diagnostic(
|
|
1023
|
+
severity="warning", source="gui:screenshot",
|
|
1024
|
+
code="sim.inspect.screenshot_workdir_failed",
|
|
1025
|
+
message=f"{type(exc).__name__}: {exc}",
|
|
1026
|
+
)])
|
|
1027
|
+
|
|
1028
|
+
diags: list[Diagnostic] = []
|
|
1029
|
+
arts: list[Artifact] = []
|
|
1030
|
+
ts = int(_time.time() * 1000)
|
|
1031
|
+
for m in matches:
|
|
1032
|
+
rect = m["rect"]
|
|
1033
|
+
pid = m["pid"]
|
|
1034
|
+
title = m["title"] or "(untitled)"
|
|
1035
|
+
if rect is None or rect[2] <= rect[0] or rect[3] <= rect[1]:
|
|
1036
|
+
diags.append(Diagnostic(
|
|
1037
|
+
severity="warning", source="gui:screenshot",
|
|
1038
|
+
code="sim.inspect.screenshot_bad_rect",
|
|
1039
|
+
message=f"skipped pid={pid} ({m['proc_name']}): invalid rect {rect}",
|
|
1040
|
+
extra={"pid": pid, "process": m["proc_name"], "rect": rect},
|
|
1041
|
+
))
|
|
1042
|
+
continue
|
|
1043
|
+
# Windows places minimized windows far offscreen (~(-32000,-32000)).
|
|
1044
|
+
# Capturing would produce a black PNG — skip with an info diag so
|
|
1045
|
+
# the agent / human understands why there's no screenshot.
|
|
1046
|
+
if rect[0] < -10000 or rect[1] < -10000:
|
|
1047
|
+
diags.append(Diagnostic(
|
|
1048
|
+
severity="info", source="gui:screenshot",
|
|
1049
|
+
code="sim.screenshot.window_minimized",
|
|
1050
|
+
message=(f"skipped pid={pid} ({m['proc_name']}): "
|
|
1051
|
+
f"window is minimized (rect={rect})"),
|
|
1052
|
+
extra={"pid": pid, "process": m["proc_name"], "rect": rect,
|
|
1053
|
+
"title": title},
|
|
1054
|
+
))
|
|
1055
|
+
continue
|
|
1056
|
+
out_path = shots_dir / f"{self.filename_prefix}_{pid}_{ts}.png"
|
|
1057
|
+
try:
|
|
1058
|
+
img = ImageGrab.grab(bbox=rect, all_screens=True)
|
|
1059
|
+
img.save(out_path, "PNG")
|
|
1060
|
+
except Exception as exc:
|
|
1061
|
+
diags.append(Diagnostic(
|
|
1062
|
+
severity="warning", source="gui:screenshot",
|
|
1063
|
+
code="sim.inspect.screenshot_failed",
|
|
1064
|
+
message=f"{type(exc).__name__}: {exc}",
|
|
1065
|
+
extra={"pid": pid, "rect": rect},
|
|
1066
|
+
))
|
|
1067
|
+
continue
|
|
1068
|
+
try:
|
|
1069
|
+
st = out_path.stat()
|
|
1070
|
+
arts.append(Artifact(
|
|
1071
|
+
path=str(out_path), size=st.st_size,
|
|
1072
|
+
mtime=_time.strftime("%Y-%m-%dT%H:%M:%SZ",
|
|
1073
|
+
_time.gmtime(st.st_mtime)),
|
|
1074
|
+
role="screenshot",
|
|
1075
|
+
))
|
|
1076
|
+
except Exception:
|
|
1077
|
+
arts.append(Artifact(path=str(out_path), role="screenshot"))
|
|
1078
|
+
diags.append(Diagnostic(
|
|
1079
|
+
severity="info", source="gui:screenshot",
|
|
1080
|
+
code="sim.screenshot.captured",
|
|
1081
|
+
message=(f"captured {m['proc_name']} pid={pid} "
|
|
1082
|
+
f"{(rect[2]-rect[0])}x{(rect[3]-rect[1])} → "
|
|
1083
|
+
f"{out_path.name}"),
|
|
1084
|
+
extra={"path": str(out_path), "pid": pid,
|
|
1085
|
+
"process": m["proc_name"], "rect": rect,
|
|
1086
|
+
"title": title},
|
|
1087
|
+
))
|
|
1088
|
+
return ProbeResult(diagnostics=diags, artifacts=arts)
|