coder-eval 0.8.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. coder_eval/.gitattributes +2 -0
  2. coder_eval/__init__.py +3 -0
  3. coder_eval/agent.py +302 -0
  4. coder_eval/agents/__init__.py +41 -0
  5. coder_eval/agents/_logging.py +89 -0
  6. coder_eval/agents/antigravity_agent.py +811 -0
  7. coder_eval/agents/claude_code_agent.py +1701 -0
  8. coder_eval/agents/codex_agent.py +2055 -0
  9. coder_eval/agents/noop_agent.py +100 -0
  10. coder_eval/agents/registry.py +163 -0
  11. coder_eval/agents/watchdog.py +116 -0
  12. coder_eval/analysis.py +88 -0
  13. coder_eval/cli/__init__.py +87 -0
  14. coder_eval/cli/aggregate_command.py +153 -0
  15. coder_eval/cli/console.py +7 -0
  16. coder_eval/cli/evaluate_command.py +164 -0
  17. coder_eval/cli/plan_command.py +152 -0
  18. coder_eval/cli/report_command.py +121 -0
  19. coder_eval/cli/run_command.py +686 -0
  20. coder_eval/cli/run_helpers.py +137 -0
  21. coder_eval/cli/run_task_internal_command.py +210 -0
  22. coder_eval/cli/utils.py +37 -0
  23. coder_eval/config.py +212 -0
  24. coder_eval/criteria/__init__.py +163 -0
  25. coder_eval/criteria/_classification_aggregate.py +106 -0
  26. coder_eval/criteria/agent_judge.py +425 -0
  27. coder_eval/criteria/base.py +248 -0
  28. coder_eval/criteria/classification_match.py +107 -0
  29. coder_eval/criteria/command_executed.py +181 -0
  30. coder_eval/criteria/commands_efficiency.py +73 -0
  31. coder_eval/criteria/file_check.py +119 -0
  32. coder_eval/criteria/file_contains.py +85 -0
  33. coder_eval/criteria/file_exists.py +45 -0
  34. coder_eval/criteria/file_matches_regex.py +86 -0
  35. coder_eval/criteria/json_check.py +184 -0
  36. coder_eval/criteria/llm_judge.py +260 -0
  37. coder_eval/criteria/reference_comparison.py +130 -0
  38. coder_eval/criteria/run_command.py +220 -0
  39. coder_eval/criteria/skill_triggered.py +111 -0
  40. coder_eval/criteria/uipath_eval.py +223 -0
  41. coder_eval/errors/__init__.py +26 -0
  42. coder_eval/errors/agent.py +26 -0
  43. coder_eval/errors/budget.py +28 -0
  44. coder_eval/errors/categories.py +205 -0
  45. coder_eval/errors/categorization.py +240 -0
  46. coder_eval/errors/executor.py +124 -0
  47. coder_eval/errors/judge.py +12 -0
  48. coder_eval/errors/retry.py +211 -0
  49. coder_eval/errors/timeout.py +63 -0
  50. coder_eval/evaluation/__init__.py +10 -0
  51. coder_eval/evaluation/checker.py +260 -0
  52. coder_eval/evaluation/judge_anthropic.py +55 -0
  53. coder_eval/evaluation/judge_bedrock.py +114 -0
  54. coder_eval/evaluation/judge_context.py +497 -0
  55. coder_eval/evaluation/judge_models.py +53 -0
  56. coder_eval/evaluation/judge_persistence.py +291 -0
  57. coder_eval/evaluation/judge_usage.py +50 -0
  58. coder_eval/evaluation/sub_agent.py +231 -0
  59. coder_eval/evaluation/summaries.py +48 -0
  60. coder_eval/evaluation/verdict_tool.py +213 -0
  61. coder_eval/formatting.py +191 -0
  62. coder_eval/isolation/__init__.py +15 -0
  63. coder_eval/isolation/docker_runner.py +1253 -0
  64. coder_eval/logging_config.py +399 -0
  65. coder_eval/models/__init__.py +337 -0
  66. coder_eval/models/agent_config.py +373 -0
  67. coder_eval/models/container_paths.py +26 -0
  68. coder_eval/models/criteria.py +942 -0
  69. coder_eval/models/enums.py +121 -0
  70. coder_eval/models/experiment.py +314 -0
  71. coder_eval/models/judge.py +90 -0
  72. coder_eval/models/judge_defaults.py +11 -0
  73. coder_eval/models/limits.py +89 -0
  74. coder_eval/models/merge_strategy.py +132 -0
  75. coder_eval/models/mutations.py +95 -0
  76. coder_eval/models/results.py +787 -0
  77. coder_eval/models/routing.py +160 -0
  78. coder_eval/models/sandbox.py +371 -0
  79. coder_eval/models/tasks.py +631 -0
  80. coder_eval/models/telemetry.py +454 -0
  81. coder_eval/models/templates.py +108 -0
  82. coder_eval/orchestration/__init__.py +13 -0
  83. coder_eval/orchestration/batch.py +690 -0
  84. coder_eval/orchestration/config.py +111 -0
  85. coder_eval/orchestration/config_merge.py +431 -0
  86. coder_eval/orchestration/evaluation.py +94 -0
  87. coder_eval/orchestration/experiment.py +837 -0
  88. coder_eval/orchestration/overrides.py +206 -0
  89. coder_eval/orchestration/task_loader.py +437 -0
  90. coder_eval/orchestrator.py +2078 -0
  91. coder_eval/path_utils.py +79 -0
  92. coder_eval/plugins.py +81 -0
  93. coder_eval/pricing.py +169 -0
  94. coder_eval/py.typed +0 -0
  95. coder_eval/reports.py +1066 -0
  96. coder_eval/reports_experiment.py +761 -0
  97. coder_eval/reports_html.py +1659 -0
  98. coder_eval/reports_stats.py +250 -0
  99. coder_eval/resources/__init__.py +137 -0
  100. coder_eval/resources/default_experiment.yaml +85 -0
  101. coder_eval/resources/default_ignore_patterns.yaml +60 -0
  102. coder_eval/resources/tags.yaml +55 -0
  103. coder_eval/sandbox.py +1127 -0
  104. coder_eval/scoring/__init__.py +11 -0
  105. coder_eval/scoring/ast_similarity.py +38 -0
  106. coder_eval/scoring/complexity.py +115 -0
  107. coder_eval/scoring/quality.py +154 -0
  108. coder_eval/scoring/signature_similarity.py +57 -0
  109. coder_eval/scoring/similarity.py +103 -0
  110. coder_eval/scoring/token_similarity.py +44 -0
  111. coder_eval/simulation/__init__.py +27 -0
  112. coder_eval/simulation/termination.py +88 -0
  113. coder_eval/simulation/user_simulator.py +324 -0
  114. coder_eval/streaming/__init__.py +44 -0
  115. coder_eval/streaming/callbacks.py +57 -0
  116. coder_eval/streaming/collector.py +193 -0
  117. coder_eval/streaming/events.py +198 -0
  118. coder_eval/streaming/renderers.py +248 -0
  119. coder_eval/streaming/wire.py +115 -0
  120. coder_eval/telemetry.py +407 -0
  121. coder_eval/utils.py +517 -0
  122. coder_eval-0.8.2.dist-info/METADATA +242 -0
  123. coder_eval-0.8.2.dist-info/RECORD +127 -0
  124. coder_eval-0.8.2.dist-info/WHEEL +4 -0
  125. coder_eval-0.8.2.dist-info/entry_points.txt +5 -0
  126. coder_eval-0.8.2.dist-info/licenses/LICENSE +201 -0
  127. coder_eval-0.8.2.dist-info/licenses/NOTICE +18 -0
coder_eval/utils.py ADDED
@@ -0,0 +1,517 @@
1
+ """General-purpose utilities.
2
+
3
+ Groups several concerns that are deliberately agent-agnostic so any agent or
4
+ subsystem can reuse them:
5
+
6
+ * JSON-safe serialization of arbitrary values / dataclasses (``serialize_value``,
7
+ ``dump_dataclass``).
8
+ * Environment handling: ``$VAR`` expansion (``expand_env_vars``) and secret
9
+ redaction (``redact_env``).
10
+ * Plugin path processing (``process_plugins``).
11
+ * Version / reproducibility capture (``get_version_info`` and the ``uip``
12
+ helpers).
13
+ """
14
+
15
+ import dataclasses
16
+ import json
17
+ import logging
18
+ import os
19
+ import re
20
+ import shutil
21
+ import subprocess
22
+ from collections.abc import Collection
23
+ from pathlib import Path
24
+ from typing import Any, TypeGuard
25
+
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # Matches $VAR or ${VAR} env-var references in a path string.
30
+ _ENV_VAR_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
31
+
32
+
33
+ def expand_env_vars(text: str) -> str:
34
+ """Expand ``$VAR`` and ``${VAR}`` references in ``text`` from ``os.environ``.
35
+
36
+ Undefined references are left untouched (matching ``os.path.expandvars``
37
+ semantics), so callers can detect and warn about them afterwards.
38
+ """
39
+ return _ENV_VAR_PATTERN.sub(lambda m: os.environ.get(m.group(1) or m.group(2), m.group(0)), text)
40
+
41
+
42
+ def process_plugins(
43
+ plugins: list[dict[str, Any]],
44
+ *,
45
+ log: logging.Logger | logging.LoggerAdapter[Any] = logger,
46
+ ) -> list[dict[str, Any]]:
47
+ """Process plugins by expanding environment variable placeholders in paths.
48
+
49
+ Expands any $VAR or ${VAR} patterns in plugin paths using environment variables.
50
+ Logs a warning if a path contains an env var reference that is not set.
51
+
52
+ Args:
53
+ plugins: List of plugin configuration dictionaries (with optional 'path' keys)
54
+ log: Logger (or adapter) for the undefined-env-var warning; defaults to
55
+ this module's logger.
56
+
57
+ Returns:
58
+ List of processed plugin configurations with env vars expanded
59
+ """
60
+ if not plugins:
61
+ return []
62
+
63
+ processed = []
64
+
65
+ for plugin in plugins:
66
+ # Create a copy to avoid modifying the original
67
+ processed_plugin = dict(plugin)
68
+
69
+ # Expand env vars in path if present
70
+ if "path" in processed_plugin:
71
+ path = processed_plugin["path"]
72
+ # Check for unset env vars before expansion (for better error messages)
73
+ for match in _ENV_VAR_PATTERN.finditer(path):
74
+ # group(1) is ${VAR}, group(2) is $VAR
75
+ var_name = match.group(1) or match.group(2)
76
+ if var_name not in os.environ:
77
+ log.warning(f"Plugin path contains undefined environment variable ${var_name}: {path}")
78
+
79
+ # Expand all env vars in the path, then resolve relative paths
80
+ # against the process cwd (not the sandbox cwd) so plugins are found
81
+ expanded = expand_env_vars(path)
82
+ processed_plugin["path"] = str(Path(expanded).resolve())
83
+
84
+ processed.append(processed_plugin)
85
+
86
+ return processed
87
+
88
+
89
+ SKIP = object() # Sentinel marking values that serialize_value should drop from the result.
90
+
91
+
92
+ def serialize_value(
93
+ value: Any,
94
+ *,
95
+ skip: Any = SKIP,
96
+ skip_if_has_attrs: Collection[str] = frozenset({"write", "read"}),
97
+ ) -> Any:
98
+ """Recursively serialize a value to JSON-safe types.
99
+
100
+ Traverses dataclasses, dicts, lists, and tuples, converting ``Path`` to
101
+ ``str`` and falling back to ``str(value)`` for unknown types.
102
+
103
+ Returns the ``skip`` sentinel for values that should be excluded from the
104
+ result: callables, and any object exposing *all* of ``skip_if_has_attrs``
105
+ (file-like objects — those with both ``write`` and ``read`` — by default).
106
+ Callers drop any field/item that comes back as ``skip``.
107
+
108
+ Args:
109
+ value: The value to serialize.
110
+ skip: Sentinel returned for non-serializable values; callers compare
111
+ results against this same object with ``is`` to filter them out.
112
+ skip_if_has_attrs: Attribute names that, when all present on a value,
113
+ mark it as non-serializable. Defaults to file-like detection
114
+ (``{"write", "read"}``); pass an empty collection to disable.
115
+ """
116
+ if value is None or isinstance(value, (str, int, float, bool)):
117
+ return value
118
+ if callable(value):
119
+ return skip
120
+ if skip_if_has_attrs and all(hasattr(value, attr) for attr in skip_if_has_attrs):
121
+ return skip
122
+ if isinstance(value, Path):
123
+ return str(value)
124
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
125
+ serialized: dict[str, Any] = {}
126
+ for field in dataclasses.fields(value):
127
+ field_value = serialize_value(getattr(value, field.name), skip=skip, skip_if_has_attrs=skip_if_has_attrs)
128
+ if field_value is not skip:
129
+ serialized[field.name] = field_value
130
+ return serialized
131
+ if isinstance(value, dict):
132
+ serialized_dict: dict[str, Any] = {}
133
+ for k, v in value.items():
134
+ v_serialized = serialize_value(v, skip=skip, skip_if_has_attrs=skip_if_has_attrs)
135
+ if v_serialized is not skip:
136
+ serialized_dict[str(k)] = v_serialized
137
+ return serialized_dict
138
+ if isinstance(value, (list, tuple)):
139
+ serialized_list: list[Any] = []
140
+ for item in value:
141
+ item_serialized = serialize_value(item, skip=skip, skip_if_has_attrs=skip_if_has_attrs)
142
+ if item_serialized is not skip:
143
+ serialized_list.append(item_serialized)
144
+ return serialized_list
145
+ # Fallback: convert unknown types to string representation
146
+ return str(value)
147
+
148
+
149
+ SENSITIVE_ENV_KEYWORDS = {"TOKEN", "KEY", "SECRET"}
150
+
151
+
152
+ def redact_env(env: dict[str, str]) -> dict[str, str]:
153
+ """Redact sensitive values from an environment variable dict.
154
+
155
+ Keys containing TOKEN, KEY, or SECRET (case-insensitive) are replaced with ***REDACTED***.
156
+ """
157
+ return {k: "***REDACTED***" if any(kw in k.upper() for kw in SENSITIVE_ENV_KEYWORDS) else v for k, v in env.items()}
158
+
159
+
160
+ def dump_dataclass(obj: Any, *, skip: Any = SKIP) -> dict[str, Any]:
161
+ """Dump a dataclass instance to a plain JSON-serializable dict.
162
+
163
+ Recursively serializes each field via :func:`serialize_value`, skipping
164
+ non-serializable values (callables, file-like objects). A field named
165
+ ``env`` holding a dict is passed through :func:`redact_env` so secrets
166
+ (tokens, keys) never reach the dump.
167
+
168
+ Args:
169
+ obj: A dataclass instance.
170
+ skip: Sentinel forwarded to :func:`serialize_value` to mark dropped values.
171
+
172
+ Returns:
173
+ Dictionary of field names to JSON-serializable values.
174
+ """
175
+ result: dict[str, Any] = {}
176
+ for field in dataclasses.fields(obj):
177
+ value = serialize_value(getattr(obj, field.name), skip=skip)
178
+ if value is not skip:
179
+ if field.name == "env" and isinstance(value, dict):
180
+ value = redact_env(value)
181
+ result[field.name] = value
182
+ return result
183
+
184
+
185
+ def get_default_docker_image_tag() -> str:
186
+ """Return the default coder-eval-agent image tag for this package version.
187
+
188
+ Returns 'coder-eval-agent:<version>' if installed, or 'coder-eval-agent:latest'
189
+ if running from source without -e installation.
190
+ """
191
+ from importlib.metadata import PackageNotFoundError, version
192
+
193
+ try:
194
+ return f"coder-eval-agent:{version('coder-eval')}"
195
+ except PackageNotFoundError:
196
+ logger.debug("coder-eval package not installed; defaulting image tag to :latest")
197
+ return "coder-eval-agent:latest"
198
+
199
+
200
+ def _git_short_sha(repo_path: Path) -> str:
201
+ """Return short HEAD SHA for a git repo, or 'unknown' if not a git repo / git missing."""
202
+ if not repo_path.exists():
203
+ return "unknown"
204
+ try:
205
+ result = subprocess.run(
206
+ ["git", "rev-parse", "--short", "HEAD"],
207
+ capture_output=True,
208
+ text=True,
209
+ encoding="utf-8",
210
+ errors="replace",
211
+ timeout=5,
212
+ cwd=repo_path,
213
+ )
214
+ if result.returncode == 0:
215
+ return result.stdout.strip()
216
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
217
+ # Best-effort metadata lookup: treat git/process/filesystem issues as unavailable.
218
+ return "unknown"
219
+ return "unknown"
220
+
221
+
222
+ # A semver-ish version token: major.minor.patch with an optional leading `v`
223
+ # and any prerelease/build tail (e.g. `1.196.0-alpha.20260605.7426`). Anchored
224
+ # at the start of a line so it rejects non-version `uip --version` output.
225
+ _VERSION_TOKEN = re.compile(r"^v?\d+\.\d+\.\d+\S*$")
226
+
227
+
228
+ def looks_like_version(value: object) -> TypeGuard[str]:
229
+ """True when ``value`` is a string that parses as a ``major.minor.patch`` version.
230
+
231
+ Guards every version-capture sink against non-version ``uip --version``
232
+ output: newer CLI builds can print a JSON envelope (e.g.
233
+ ``{"Result": "Success"}``) or an auto-update/sync line instead of a bare
234
+ version, and a raw ``stdout.strip()`` would otherwise record that verbatim.
235
+ """
236
+ return isinstance(value, str) and bool(_VERSION_TOKEN.match(value.strip()))
237
+
238
+
239
+ def _uip_version(search_path: str | None = None) -> str:
240
+ """Return the ``uip --version`` version string, or 'unknown'.
241
+
242
+ ``search_path`` overrides the PATH used to resolve ``uip``; pass the
243
+ agent-aligned PATH to report the binary the agent actually executed
244
+ instead of whichever ``uip`` this process happens to see first.
245
+
246
+ The output is validated against :func:`looks_like_version` and the first
247
+ version-shaped line is returned — so a CLI that prefixes the version with
248
+ an auto-update/sync envelope (newer builds do) still yields the version,
249
+ and one that prints only a non-version envelope yields ``"unknown"``
250
+ rather than polluting ``cli_version`` with ``{"Result": "Success"}``.
251
+ """
252
+ uip = "uip"
253
+ if search_path is not None:
254
+ resolved = shutil.which("uip", path=search_path)
255
+ if not resolved:
256
+ return "unknown"
257
+ uip = resolved
258
+ try:
259
+ result = subprocess.run([uip, "--version"], capture_output=True, text=True, encoding="utf-8", timeout=5)
260
+ if result.returncode == 0:
261
+ for line in result.stdout.splitlines():
262
+ stripped = line.strip()
263
+ if looks_like_version(stripped):
264
+ return stripped
265
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
266
+ return "unknown"
267
+ return "unknown"
268
+
269
+
270
+ def resolve_uipath_plugin_dir(search_path: str | None = None) -> Path | None:
271
+ """Resolve the canonical ``node_modules/@uipath`` plugin-tools directory.
272
+
273
+ Shared core of ``Sandbox._refresh_plugin_tools_dir`` and
274
+ :func:`_resolve_plugin_tools_dir` (MST-9795). Resolve ``uip`` on
275
+ ``search_path`` (``None`` → process PATH), follow symlinks (Bun installs
276
+ ``uip`` as a symlink into the package dist), and walk up to the first
277
+ ``@uipath`` directory whose parent is ``node_modules``.
278
+
279
+ ``search_path`` is forwarded to :func:`shutil.which`; pass the
280
+ agent-aligned PATH (``Sandbox.uip_search_path``) to resolve the binary the
281
+ agent actually executed, or ``None`` to use this process's PATH.
282
+
283
+ Returns ``None`` when no usable ``uip`` is on PATH or the resolved binary
284
+ does not live inside a recognizable ``node_modules/@uipath`` tree (e.g.
285
+ development monorepo runs). Logs at debug on every non-resolving branch.
286
+ """
287
+ resolved = shutil.which("uip", path=search_path)
288
+ if not resolved:
289
+ return None
290
+ try:
291
+ real = Path(resolved).resolve(strict=True)
292
+ except (OSError, RuntimeError) as exc:
293
+ logger.debug("Failed to resolve `uip` symlink %s: %s", resolved, exc)
294
+ return None
295
+ # Walk up looking for `.../node_modules/@uipath`. We accept the first
296
+ # @uipath dir whose parent is named `node_modules` — the cli is always
297
+ # inside one, e.g. `~/.bun/.../node_modules/@uipath/cli/dist/index.js`.
298
+ for ancestor in real.parents:
299
+ if ancestor.name == "@uipath" and ancestor.parent.name == "node_modules":
300
+ logger.debug("Resolved @uipath plugin-tools dir=%s from `uip` at %s", ancestor, real)
301
+ return ancestor
302
+ logger.debug("`uip` at %s is not inside a recognizable node_modules/@uipath tree", real)
303
+ return None
304
+
305
+
306
+ def _resolve_plugin_tools_dir() -> Path | None:
307
+ """Resolve the canonical ``node_modules/@uipath`` plugin-tools directory.
308
+
309
+ An external ``PLUGIN_TOOLS_DIR`` pin wins; otherwise delegates to
310
+ :func:`resolve_uipath_plugin_dir` against this process's PATH.
311
+ """
312
+ if pinned := os.environ.get("PLUGIN_TOOLS_DIR"):
313
+ pinned_path = Path(pinned)
314
+ return pinned_path if pinned_path.is_dir() else None
315
+
316
+ return resolve_uipath_plugin_dir()
317
+
318
+
319
+ def _tool_plugin_versions(tools_dir: Path | None = None) -> dict[str, str]:
320
+ """Return ``{plugin_name: version}`` for installed ``@uipath/*-tool`` plugins.
321
+
322
+ The UiPath CLI shell (``@uipath/cli``, reported as ``cli_version``) and its
323
+ tool plugins (e.g. ``@uipath/maestro-tool``) are versioned independently, so
324
+ the shell version alone can mislead regression timelines. Enumerates the
325
+ ``@uipath`` plugin-tools dir for packages whose ``package.json`` name ends in
326
+ ``-tool`` and records their ``version``.
327
+
328
+ ``tools_dir`` overrides the directory to enumerate (e.g. the sandbox's
329
+ agent-aligned ``plugin_tools_dir``); when ``None``, resolve from this
330
+ process's own environment via :func:`_resolve_plugin_tools_dir`.
331
+
332
+ Best-effort: a missing dir or unreadable/unparseable ``package.json`` is
333
+ skipped, never raised — capturing reproducibility metadata must not fail a run.
334
+ """
335
+ if tools_dir is None:
336
+ tools_dir = _resolve_plugin_tools_dir()
337
+ if tools_dir is None or not tools_dir.is_dir():
338
+ return {}
339
+
340
+ plugins: dict[str, str] = {}
341
+ # npm installs ``@uipath/<pkg>`` into ``@uipath/<pkg>/``, so a ``-tool`` plugin
342
+ # dir is always named ``<pkg>-tool``. Mirror the manifest-name contract
343
+ # (``name.endswith("-tool")`` below) in the glob to avoid statting unrelated dirs.
344
+ for pkg_json in sorted(tools_dir.glob("*-tool/package.json")):
345
+ try:
346
+ data = json.loads(pkg_json.read_text(encoding="utf-8"))
347
+ except (json.JSONDecodeError, OSError) as exc:
348
+ logger.debug("Failed to read or parse tool-plugin package.json at %s: %s", pkg_json, exc)
349
+ continue
350
+ name = data.get("name")
351
+ if not isinstance(name, str) or not name.endswith("-tool"):
352
+ continue
353
+ # Key on the short package name (drop the @uipath scope) for readability.
354
+ short_name = name.rsplit("/", 1)[-1]
355
+ version = data.get("version")
356
+ plugins[short_name] = version if isinstance(version, str) else "unknown"
357
+ return plugins
358
+
359
+
360
+ def _cli_version_from_manifest(tools_dir: Path | None) -> str | None:
361
+ """Read ``@uipath/cli``'s version straight from its installed ``package.json``.
362
+
363
+ This is the same source of truth :func:`_tool_plugin_versions` reads for the
364
+ tool plugins — the published package's ``package.json`` carries the full
365
+ ``-alpha.<date>.<run>`` version (CI stamps it at publish time), and
366
+ ``uip --version`` merely prints that field. Reading the manifest avoids
367
+ parsing ``uip --version`` stdout, which newer CLI builds can pollute with a
368
+ JSON envelope / auto-update line. The CLI lives at ``<tools_dir>/cli`` (the
369
+ plugin-tools dir is derived by walking up from the resolved ``uip`` binary).
370
+
371
+ Returns ``None`` (so callers fall back to the validated stdout path) when the
372
+ dir/manifest is absent or the version isn't version-shaped — e.g. in-process
373
+ dev runs where ``uip`` isn't inside a ``node_modules/@uipath`` tree.
374
+ """
375
+ if tools_dir is None:
376
+ return None
377
+ try:
378
+ data = json.loads((tools_dir / "cli" / "package.json").read_text(encoding="utf-8"))
379
+ except (json.JSONDecodeError, OSError) as exc:
380
+ logger.debug("Failed to read @uipath/cli package.json under %s: %s", tools_dir, exc)
381
+ return None
382
+ version = data.get("version")
383
+ return version if looks_like_version(version) else None
384
+
385
+
386
+ def _resolve_cli_version(tools_dir: Path | None, search_path: str | None) -> str:
387
+ """The CLI shell version: prefer its ``package.json`` manifest, fall back to ``uip --version``.
388
+
389
+ Symmetric with ``tool_plugins`` (manifest-first); the validated stdout path
390
+ (:func:`_uip_version`) covers installs not under ``node_modules/@uipath``.
391
+ """
392
+ return _cli_version_from_manifest(tools_dir) or _uip_version(search_path)
393
+
394
+
395
+ def runtime_uip_versions(plugin_tools_dir: str | Path | None, search_path: str | None = None) -> dict[str, Any]:
396
+ """Capture uip shell + tool-plugin versions as resolved at task runtime.
397
+
398
+ :func:`get_version_info` resolves ``uip`` from this process's own
399
+ environment, which describes the *pre-task* state: under ``--driver
400
+ docker`` the CLI auto-installs/upgrades its ``@uipath/*-tool`` plugins on
401
+ first use inside the task, so versions captured at setup time are the
402
+ image-baked ones, not what the agent and criteria actually executed
403
+ (coder_eval#366 follow-up). Call this AFTER the task with the sandbox's
404
+ agent-aligned ``plugin_tools_dir``/PATH to record the real runtime state.
405
+
406
+ Strict about its inputs, unlike :func:`get_version_info`: a ``None``
407
+ ``plugin_tools_dir`` yields ``tool_plugins == {}`` rather than falling
408
+ back to process-env discovery — on an in-process (non-docker) run that
409
+ fallback would reach into the host's installs, re-introducing exactly the
410
+ host-pollution this function exists to remove. Callers keep their
411
+ setup-time values on empty results instead.
412
+
413
+ Returns a partial env-info dict (``cli_version`` + ``tool_plugins``)
414
+ suitable for ``environment_info.update(...)``. Best-effort like the rest
415
+ of the version capture: never raises.
416
+ """
417
+ tools_dir = Path(plugin_tools_dir) if plugin_tools_dir else None
418
+ return {
419
+ "cli_version": _resolve_cli_version(tools_dir, search_path),
420
+ "tool_plugins": _tool_plugin_versions(tools_dir) if tools_dir else {},
421
+ }
422
+
423
+
424
+ def get_version_info(sandbox_path: Path | None = None) -> dict[str, Any]:
425
+ """Captures versions of key dependencies for reproducibility.
426
+
427
+ Args:
428
+ sandbox_path: Optional path to sandbox directory. When provided,
429
+ CLAUDE.md in the sandbox will be hashed for reproducibility tracking.
430
+
431
+ Returns:
432
+ Dictionary containing version information for critical dependencies.
433
+ """
434
+ version_info = {}
435
+
436
+ # Get git commit hash (pinned to project root, not CWD which may be a sandbox)
437
+ project_root = Path(__file__).resolve().parent.parent
438
+ version_info["git_commit"] = _git_short_sha(project_root)
439
+
440
+ # Sibling repos that contribute to the agent's runtime context.
441
+ # Path resolution: env var first (CODER_EVAL_SKILLS_DIR), then sibling-of-coder_eval default.
442
+ # A downstream runner can set this env var to its configured path so custom layouts get the right SHA.
443
+ sibling_root = project_root.parent.parent
444
+ skills_override = os.environ.get("CODER_EVAL_SKILLS_DIR")
445
+ skills_path = Path(skills_override) if skills_override else sibling_root / "skills"
446
+ version_info["skills_git_commit"] = _git_short_sha(skills_path)
447
+
448
+ # uip CLI is installed via npm; read its version from @uipath/cli's
449
+ # package.json (same source tool_plugins uses), falling back to a validated
450
+ # `uip --version`. Consumed by downstream run-summary tooling.
451
+ tools_dir = resolve_uipath_plugin_dir()
452
+ version_info["cli_version"] = _resolve_cli_version(tools_dir, None)
453
+
454
+ # The CLI shell (cli_version) and its `@uipath/*-tool` plugins (e.g.
455
+ # maestro-tool) version independently, so the shell version alone can
456
+ # mislead regression timelines. Record the installed plugin versions too.
457
+ version_info["tool_plugins"] = _tool_plugin_versions(tools_dir)
458
+
459
+ # Get coder_eval version
460
+ from importlib.metadata import PackageNotFoundError, version
461
+
462
+ try:
463
+ version_info["coder_eval"] = version("coder_eval")
464
+ except PackageNotFoundError:
465
+ version_info["coder_eval"] = "unknown"
466
+
467
+ # Try to get Claude CLI version
468
+ try:
469
+ result = subprocess.run(
470
+ ["claude", "-v"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5
471
+ )
472
+ version_info["claude_code_cli"] = result.stdout.strip()
473
+ except (FileNotFoundError, subprocess.SubprocessError):
474
+ version_info["claude_code_cli"] = "Not Found"
475
+
476
+ # Try to get uv version
477
+ try:
478
+ result = subprocess.run(
479
+ ["uv", "--version"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5
480
+ )
481
+ version_info["uv"] = result.stdout.strip()
482
+ except (FileNotFoundError, subprocess.SubprocessError):
483
+ version_info["uv"] = "Not Found"
484
+
485
+ # Get Python packages
486
+ try:
487
+ import anthropic
488
+
489
+ version_info["anthropic"] = anthropic.__version__
490
+ except (ImportError, AttributeError):
491
+ version_info["anthropic"] = "Not Installed"
492
+
493
+ try:
494
+ import openai # pyright: ignore[reportMissingImports]
495
+
496
+ version_info["openai"] = openai.__version__
497
+ except (ImportError, AttributeError):
498
+ version_info["openai"] = "Not Installed"
499
+
500
+ try:
501
+ import pydantic
502
+
503
+ version_info["pydantic"] = pydantic.__version__
504
+ except (ImportError, AttributeError):
505
+ version_info["pydantic"] = "Not Installed"
506
+
507
+ # Hash CLAUDE.md if sandbox path provided
508
+ if sandbox_path:
509
+ claude_md = sandbox_path / "CLAUDE.md"
510
+ if claude_md.is_file():
511
+ import hashlib
512
+
513
+ content = claude_md.read_bytes()
514
+ version_info["claude_md_sha256"] = hashlib.sha256(content).hexdigest()
515
+ version_info["claude_md_size_bytes"] = str(len(content))
516
+
517
+ return version_info