Repository navigation
Expand file tree
/
Copy pathextras_info.py
More file actions
1630 lines (1365 loc) · 60.1 KB
/
Copy pathextras_info.py
File metadata and controls
1630 lines (1365 loc) · 60.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Inspect optional-dependency install status for the running distribution.
Reads `Requires-Dist` metadata to report which packages declared under
`[project.optional-dependencies]` are installed, and renders that status
in either plain text (for stdout) or markdown (for rich UI contexts).
"""
from __future__ import annotations
import ast
import importlib.util
import json
import logging
import re
import tomllib
from dataclasses import dataclass
from importlib.metadata import (
Distribution,
PackageNotFoundError,
distribution,
distributions,
version as pkg_version,
)
from pathlib import Path
from typing import Literal
from urllib.parse import urlparse
from urllib.request import url2pathname
from packaging.requirements import InvalidRequirement, Requirement
from packaging.utils import canonicalize_name
from packaging.version import InvalidVersion, Version
logger = logging.getLogger(__name__)
DistributionMetadataStatus = Literal["resolved", "not_installed", "error"]
"""Outcome of a distribution version lookup.
Used for any distribution (the `deepagents` SDK and the `deepagents-code`
CLI alike). `"not_installed"` means the package metadata is genuinely absent;
`"error"` means an unexpected failure occurred while reading it. Callers
that don't care which kind of failure happened can treat both the same.
"""
def _sdk_distribution_name(dist: Distribution) -> str:
"""Return `dist`'s lowercased, hyphenated name, or `""` when unavailable.
`Distribution.name` is a property that reads and parses `METADATA`, so it can
raise rather than return `None` — a distribution with non-UTF-8 `METADATA`
raises `UnicodeDecodeError`. Those failures are contained here so one
unreadable distribution cannot abort the caller's whole scan.
"""
try:
name = dist.name
except (AttributeError, KeyError, OSError, TypeError, ValueError):
# `KeyError` is future-proofing: on a metadata-less `*.dist-info`,
# `Distribution.name` returns `None` today but is documented to raise
# `KeyError` in a later Python (`DeprecationWarning` as of 3.14).
logger.debug("Could not read distribution name; skipping", exc_info=True)
return ""
if not isinstance(name, str):
# A partial install can leave a `*.dist-info` with no `METADATA`, for
# which `Distribution.name` is currently `None`.
return ""
return name.lower().replace("_", "-")
def _read_sdk_direct_url(dist: Distribution) -> dict[str, object] | None:
"""Return `dist`'s parsed PEP 610 payload, or `None` when it is unusable.
Unreadable or unparseable metadata reports `None` rather than raising, so one
bad distribution cannot abort the caller's scan.
"""
try:
raw = dist.read_text("direct_url.json")
except (OSError, TypeError, ValueError):
# `read_text` already suppresses the ordinary absent-file cases, so
# reaching here means the path exists but is unusable (`OSError`) or holds
# non-UTF-8 bytes (`UnicodeDecodeError`, a `ValueError`). `TypeError` is
# unreachable through the stdlib's `PathDistribution` and is kept only as
# insurance against third-party `Distribution` implementations.
logger.debug("Could not read direct_url.json", exc_info=True)
return None
if not raw:
# Normal and common: non-editable installs omit the file entirely, as
# does the source-tree `*.egg-info`. Deliberately not logged.
return None
try:
data = json.loads(raw)
except (RecursionError, ValueError):
# `ValueError` covers `json.JSONDecodeError`; pathologically nested
# input raises `RecursionError`, which is not a `ValueError`.
logger.debug("Malformed direct_url.json", exc_info=True)
return None
return data if isinstance(data, dict) else None
def _file_url_to_path(url: str) -> Path | None:
"""Convert a `file://` URL to a local path.
Returns:
The local path, or `None` when the URL is not a `file://` URL or cannot
be parsed.
"""
try:
parsed = urlparse(url)
except ValueError: # e.g. an invalid IPv6 host
logger.debug("Unparseable direct_url.json url", exc_info=True)
return None
if parsed.scheme != "file":
return None
path = url2pathname(parsed.path)
if parsed.netloc and parsed.netloc != "localhost":
# A UNC path such as `file://server/share/proj`.
path = f"//{parsed.netloc}{path}"
return Path(path)
def _sdk_editable_record_root(dist: Distribution) -> Path | None:
"""Return `dist`'s editable source root, or `None` when it is not editable.
`None` also covers an editable record whose source location cannot be
determined, since such a record cannot be correlated with the running module.
"""
data = _read_sdk_direct_url(dist)
if data is None:
return None
dir_info = data.get("dir_info")
if not isinstance(dir_info, dict) or dir_info.get("editable") is not True:
return None
url = data.get("url")
if not isinstance(url, str):
return None
return _file_url_to_path(url)
def _running_sdk_package_root() -> Path | None:
"""Return the directory of the `deepagents` package importable in this process.
Located with `importlib.util.find_spec` rather than an `import`, so the
probe does not execute the SDK — dcode resolves the SDK version for trace
metadata without importing the SDK package, and a findable-but-broken SDK
install must not fail here.
`None` when the package cannot be located or has no determinable origin —
some frozen and embedded interpreters report no `__file__`, and a namespace
package carries no `__init__.py`. Separate function so tests can substitute
a location without touching the real install layout.
"""
try:
spec = importlib.util.find_spec("deepagents")
except (ImportError, ValueError):
# `ValueError` covers `sys.modules["deepagents"]` being `None`, which
# `find_spec` rejects instead of searching.
logger.debug("Could not search for the deepagents package", exc_info=True)
return None
if spec is None or spec.origin is None:
return None
try:
return Path(spec.origin).resolve().parent
except (OSError, ValueError):
logger.debug("Could not locate the deepagents package", exc_info=True)
return None
def _is_under(root: Path, candidate: Path) -> bool:
"""Return whether `candidate` is `root` or lives inside it."""
try:
resolved = root.resolve()
except OSError:
logger.debug("Could not resolve editable source root", exc_info=True)
return False
return resolved == candidate or resolved in candidate.parents
def _editable_sdk_source_root() -> Path | None:
"""Return the editable `deepagents` source root from package metadata.
Scans every installed distribution named `deepagents` for PEP 610
`direct_url.json` with `dir_info.editable: true`, and credits a record only
when its source root actually contains the `deepagents` module imported into
this process.
Both halves are load-bearing, and they guard opposite errors:
- Scanning, rather than a single `importlib.metadata.distribution` lookup,
avoids a false negative. `setuptools` leaves a gitignored
`deepagents.egg-info/` in the source tree after any local build, and the cwd
is on `sys.path` for `-c`, `-m`, and the REPL, so that `*.egg-info` is found
*first* when running from the checkout. It carries no `direct_url.json`, so
the single-lookup form reports "not editable" and never consults the real
editable install in site-packages — disagreeing with the SDK's own
`lc_versions.deepagents` trace entry, which scans.
- Correlating against the located package avoids a false positive. An
environment can hold more than one `deepagents` record — a wheel earlier on
`sys.path` and an unrelated editable checkout later on it. Only the wheel's
code is actually importable, so reporting the other checkout's root would
attribute a workspace build to a published install.
Per-distribution metadata failures are contained by the helpers above, so one
unreadable distribution cannot end the scan early and mask a later editable
one. Missing or unparseable metadata reports no source root, keeping version
reporting best-effort rather than a source of diagnostic failures.
"""
package_root = _running_sdk_package_root()
if package_root is None:
# Without a location for the importable package, no editable record can
# be attributed to it, so report the plain metadata version.
return None
try:
for dist in distributions():
if _sdk_distribution_name(dist) != "deepagents":
continue
source_root = _sdk_editable_record_root(dist)
if source_root is not None and _is_under(source_root, package_root):
return source_root
except (OSError, TypeError, ValueError, RecursionError):
# Backstop for `distributions()` itself: it yields lazily, so a broken
# `sys.path` entry surfaces mid-iteration and cannot be contained
# per-distribution the way the two helpers above are. `RecursionError`
# is included so the helpers' containment of pathological metadata keeps
# the answer independent of iteration order when the outer loop is the
# only place such an error can surface from.
logger.debug(
"Stopped scanning installed distributions for PEP 610 metadata",
exc_info=True,
)
return None
def _sdk_version_from_source(root: Path) -> str | None:
"""Read `deepagents.__version__` from a source tree rooted at `root`.
Returns:
The source SDK version, or `None` when it cannot be read.
"""
version_file = root / "deepagents" / "_version.py"
try:
source = version_file.read_text(encoding="utf-8")
module = ast.parse(source, filename=str(version_file))
except (OSError, SyntaxError, ValueError):
# Reached only for editable installs, where the package is known to be
# present — so an unreadable or malformed version file is a broken local
# checkout, not an absent dependency. Warn (not debug): the source
# version is masked and the caller falls back to potentially stale
# metadata.
logger.warning("Failed to read deepagents SDK version file", exc_info=True)
return None
for node in module.body:
# Match only a plain `__version__ = "..."` assignment. release-please
# writes the SDK's `_version.py` that way, so annotated (`ast.AnnAssign`)
# or tuple-target forms are intentionally ignored.
if not isinstance(node, ast.Assign):
continue
if not any(
isinstance(target, ast.Name) and target.id == "__version__"
for target in node.targets
):
continue
try:
value = ast.literal_eval(node.value)
except (ValueError, TypeError):
# A non-literal `__version__` RHS masks the source version just like
# an unreadable file, so warn for parity with the read/parse failure
# above rather than falling back to stale metadata silently.
logger.warning(
"Failed to evaluate deepagents SDK __version__ literal",
exc_info=True,
)
return None
return value if isinstance(value, str) and value else None
return None
def _contract_home(path: Path) -> str:
"""Return `path` as text with a home-directory prefix contracted to `~`.
Args:
path: Filesystem path to render.
Returns:
The stringified path, with a leading home directory replaced by `~`
when applicable. The raw path is returned when the home directory
cannot be determined.
"""
text = str(path)
try:
home = str(Path.home())
except (OSError, RuntimeError):
return text
if text == home:
return "~"
prefix = home if home.endswith("/") else f"{home}/"
if text.startswith(prefix):
return f"~/{text[len(prefix) :]}"
return text
@dataclass(frozen=True)
class DistributionVersion:
"""Structured version facts for a single installed distribution.
Separates three facts that are easily conflated: the live version read from
the running source, whether imported or parsed (`source_version`), the
version recorded in the installed distribution metadata (`metadata_version`),
and whether the install is editable (with its `source_path`). `status`
records whether the metadata lookup succeeded so diagnostic callers can
distinguish a genuinely absent package from an unexpected lookup failure.
"""
name: str
"""Distribution name, such as `deepagents` or `deepagents-code`."""
source_version: str | None
"""Version read from the imported/source `_version.py`, when available."""
metadata_version: str | None
"""Version from `importlib.metadata`, when the distribution is installed."""
editable: bool
"""Whether the distribution is installed in editable mode."""
source_path: str | None
"""`~`-contracted editable source root, when known.
Available for callers that want to display the editable root; the
`--version`/`/version` surfaces render the CLI path from `config` instead,
so this is not rendered on every surface today.
"""
status: DistributionMetadataStatus
"""Outcome of the metadata lookup."""
@property
def primary_version(self) -> str | None:
"""Version to report as authoritative.
Editable installs prefer the live source version because their metadata
can lag the working tree after a local version change; every other
install uses the metadata version, falling back to the source version
when metadata is absent. This keeps the "a resolved lookup yields a
non-`None` version" contract intact even when a source version is the
only fact available.
"""
if self.editable and self.source_version:
return self.source_version
return self.metadata_version or self.source_version
@property
def has_drift(self) -> bool:
"""Whether the source and metadata versions are both known and differ."""
return (
self.source_version is not None
and self.metadata_version is not None
and self.source_version != self.metadata_version
)
@dataclass(frozen=True)
class VersionReport:
"""Network-free snapshot of the version facts diagnostics need.
Bundles the running CLI and installed SDK version facts with the result of
comparing the `deepagents` requirement that `deepagents-code` declares
against the effective SDK version for diagnostics.
"""
cli: DistributionVersion
"""Version facts for the running `deepagents-code` distribution."""
sdk: DistributionVersion
"""Version facts for the installed `deepagents` SDK distribution."""
sdk_requirement: Requirement | None
"""The `deepagents` requirement declared by `deepagents-code`, if found."""
sdk_requirement_satisfied: bool | None
"""Whether the effective SDK version satisfies `sdk_requirement`.
`None` when the comparison cannot be made (no declared requirement, the SDK
version cannot be resolved — genuinely not installed or an unexpected
metadata error — or an unparseable version).
"""
@property
def effective_sdk_version(self) -> str | None:
"""Published SDK baseline represented by the running client checkout."""
return _effective_sdk_version(self.cli, self.sdk, self.sdk_requirement)
@property
def sdk_is_workspace_head(self) -> bool:
"""Whether the SDK is the editable sibling workspace represented by its pin."""
return _uses_exact_requirement_as_effective_version(
self.cli, self.sdk, self.sdk_requirement
)
@property
def display_sdk_version(self) -> str | None:
"""SDK version string for user-facing diagnostics and trace metadata."""
return _display_sdk_version(self.cli, self.sdk, self.sdk_requirement)
@property
def sdk_source_version_invalid(self) -> bool:
"""Whether an editable SDK has no parseable live source version."""
return self.sdk.editable and _parse_version(self.sdk.source_version) is None
@property
def sdk_requirement_mismatch(self) -> bool:
"""Whether the effective SDK version violates the declared requirement."""
# `is False`, not `not`: an inconclusive comparison (`None`) is *not* a
# mismatch. Collapsing this to `not self.sdk_requirement_satisfied` would
# silently report every unknown as a mismatch and flag doctor unhealthy.
return self.sdk_requirement_satisfied is False
def _read_cli_source_version() -> str | None:
"""Return the running `deepagents-code` source version, or `None`.
Reads `deepagents_code._version.__version__`, which is always present for
the running package but is imported defensively so best-effort diagnostics
never crash on a broken checkout.
"""
try:
from deepagents_code._version import __version__
except Exception:
# `_version` is generated and always present for the running package, so
# a failure here means a broken checkout that masks the source version
# and forces a fall back to potentially stale metadata. Warn for parity
# with `_sdk_version_from_source`, which handles the same failure shape.
logger.warning("Could not read deepagents-code source version", exc_info=True)
return None
return __version__ if isinstance(__version__, str) and __version__ else None
def _cli_editable_info() -> tuple[bool, str | None]:
"""Return the editable status and source path for `deepagents-code`.
Reuses the cached PEP 610 detection in `config` rather than reimplementing
it, so both surfaces agree and stay patchable in tests.
"""
try:
from deepagents_code.config import (
_get_editable_install_path,
_is_editable_install,
)
return _is_editable_install(), _get_editable_install_path()
except Exception:
logger.debug(
"Could not determine deepagents-code editable status", exc_info=True
)
return False, None
def collect_cli_version_info() -> DistributionVersion:
"""Collect version facts for the running `deepagents-code` distribution.
Returns:
The structured CLI version facts. The status is `"resolved"` whenever a
source or metadata version is available, `"not_installed"` when the
metadata is genuinely missing (`PackageNotFoundError`) and no source
version is available, and `"error"` on an unexpected metadata failure
with no source fallback.
"""
source = _read_cli_source_version()
try:
metadata: str | None = pkg_version("deepagents-code")
status: DistributionMetadataStatus = "resolved"
except PackageNotFoundError:
logger.debug("deepagents-code package metadata not found in environment")
metadata = None
status = "resolved" if source else "not_installed"
except Exception: # Best-effort lookup; never propagate to the caller
logger.warning(
"Unexpected error looking up deepagents-code metadata version",
exc_info=True,
)
metadata = None
status = "resolved" if source else "error"
editable, path = _cli_editable_info()
return DistributionVersion(
name="deepagents-code",
source_version=source,
metadata_version=metadata,
editable=editable,
source_path=path,
status=status,
)
def collect_sdk_version_info() -> DistributionVersion:
"""Collect version facts for the installed `deepagents` SDK distribution.
Editable SDK installs prefer the source tree's `_version.py`; everything
else reports the installed metadata version. Distinguishes a genuinely
missing package from an unexpected metadata error.
Returns:
The structured SDK version facts.
"""
try:
metadata = pkg_version("deepagents")
except PackageNotFoundError:
logger.debug("deepagents SDK package not found in environment")
return DistributionVersion(
name="deepagents",
source_version=None,
metadata_version=None,
editable=False,
source_path=None,
status="not_installed",
)
except Exception: # Best-effort lookup; never propagate to the caller
logger.warning(
"Unexpected error looking up deepagents SDK version", exc_info=True
)
return DistributionVersion(
name="deepagents",
source_version=None,
metadata_version=None,
editable=False,
source_path=None,
status="error",
)
source_root = _editable_sdk_source_root()
editable = source_root is not None
source_version = _sdk_version_from_source(source_root) if source_root else None
source_path = _contract_home(source_root) if source_root else None
return DistributionVersion(
name="deepagents",
source_version=source_version,
metadata_version=metadata,
editable=editable,
source_path=source_path,
status="resolved",
)
def sdk_requirement_from_cli(
distribution_name: str = "deepagents-code",
) -> Requirement | None:
"""Return the base `deepagents` requirement declared by `deepagents-code`.
Reads the installed distribution's `Requires-Dist` metadata and parses each
entry with `packaging.Requirement`, returning the applicable base
`deepagents` dependency. Extras-gated or environment-conditional variants
whose marker does not apply to the current environment are skipped.
Args:
distribution_name: Name of the installed distribution to inspect.
Returns:
The parsed `deepagents` requirement, or `None` when the distribution or
requirement cannot be read.
"""
try:
dist = distribution(distribution_name)
except PackageNotFoundError:
logger.debug(
"Distribution %s not found; cannot read deepagents requirement",
distribution_name,
)
return None
except Exception: # Best-effort lookup; never propagate to the caller
logger.warning(
"Unexpected error reading %s requirements", distribution_name, exc_info=True
)
return None
try:
requirements = dist.requires or []
except Exception: # Best-effort lookup; malformed metadata must not be fatal
logger.warning(
"Unexpected error reading %s requirements", distribution_name, exc_info=True
)
return None
return _sdk_requirement_from_entries(requirements)
def _sdk_requirement_from_entries(requirements: list[str]) -> Requirement | None:
"""Return the applicable base SDK requirement from dependency entries."""
target = canonicalize_name("deepagents")
for raw in requirements:
try:
req = Requirement(raw)
except InvalidRequirement:
logger.warning("Could not parse Requires-Dist entry: %s", raw)
continue
if canonicalize_name(req.name) != target:
continue
if req.marker is not None:
# Skip extras-gated (`extra == "..."`) or environment-conditional
# variants that do not apply; only the base runtime dependency is
# meaningful for a straight installed-version comparison.
try:
applicable = req.marker.evaluate()
except Exception:
# An unexpected marker-evaluation failure must not silently drop
# the base requirement — that would hide the very SDK mismatch
# this check exists to surface. Warn and treat it as applicable
# so a genuine mismatch is still flagged rather than masked.
logger.warning(
"Could not evaluate marker for Requires-Dist entry %s; "
"treating the requirement as applicable",
raw,
exc_info=True,
)
else:
if not applicable:
continue
return req
return None
def _sdk_requirement_from_cli_source(source_path: str | None) -> Requirement | None:
"""Read the SDK requirement from an editable dcode source checkout.
Editable installation metadata can lag the working tree after an update, so
workspace diagnostics must use the live `pyproject.toml` dependency instead.
Returns:
The current source requirement, or `None` when it cannot be read safely.
"""
root = _resolve_source_path(source_path)
if root is None:
return None
pyproject = root / "pyproject.toml"
try:
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
project = data.get("project")
if not isinstance(project, dict):
return None
dependencies = project.get("dependencies")
if not isinstance(dependencies, list) or not all(
isinstance(entry, str) for entry in dependencies
):
return None
except (OSError, TypeError, tomllib.TOMLDecodeError):
logger.warning(
"Could not read deepagents requirement from editable dcode source",
exc_info=True,
)
return None
return _sdk_requirement_from_entries(dependencies)
def _exact_pin(requirement: Requirement | None) -> str | None:
"""Return the single `==` pin from `requirement`, if it has one."""
if requirement is None:
return None
specs = list(requirement.specifier)
if len(specs) == 1 and specs[0].operator == "==":
return specs[0].version
return None
def _parse_version(value: str | None) -> Version | None:
"""Parse a version string for best-effort diagnostic comparisons.
Returns:
The parsed version, or `None` when the input is absent or unparseable.
"""
if value is None:
return None
try:
return Version(value)
except InvalidVersion:
logger.debug("Could not parse version %r", value, exc_info=True)
return None
def _with_editable_local_version(value: str) -> str:
"""Return `value` with an `editable` PEP 440 local segment appended.
Mirrors `deepagents._version._with_editable_local_version`, which stamps
`lc_versions["deepagents"]` the same way, so both entries in a trace share
one encoding. Kept local because the SDK helper only exists in releases
newer than the exact `deepagents` pin.
The base version is re-emitted in canonical PEP 440 form, so the result can
differ from `value` beyond the added segment (`1.0.0-alpha1` becomes
`1.0.0a1+editable`). An existing local segment is preserved and extended
rather than clobbered (`1.0+build` becomes `1.0+build.editable`), which makes
this non-idempotent. Unparseable input is returned unchanged.
"""
parsed = _parse_version(value)
if parsed is None:
return value
local = f"{parsed.local}.editable" if parsed.local else "editable"
return f"{parsed.public}+{local}"
def _resolve_source_path(path: str | None) -> Path | None:
"""Resolve an editable source path for workspace-shape comparisons.
Returns:
The resolved path, or `None` when the path is absent or unusable.
"""
if path is None:
return None
try:
normalized = path
if re.match(r"^/?[A-Za-z]:[/\\]", normalized):
# PEP 610 paths can arrive as `/C:/repo` while `url2pathname`
# returns `C:\repo`. Normalize both before asking `Path` to resolve
# them so Windows workspace siblings share the same anchor.
normalized = normalized.removeprefix("/")
normalized = f"{normalized[0].upper()}{normalized[1:]}"
normalized = normalized.replace("\\", "/")
return Path(normalized).expanduser().resolve(strict=False)
except (OSError, RuntimeError, ValueError):
logger.debug("Could not resolve editable source path %r", path, exc_info=True)
return None
def _editable_sdk_is_cli_workspace_sibling(
cli: DistributionVersion, sdk: DistributionVersion
) -> bool:
"""Whether editable SDK and dcode installs are sibling monorepo packages.
Returns:
`True` for the known `<repo>/libs/code` and `<repo>/libs/deepagents`
checkout shape.
"""
if not cli.editable or not sdk.editable:
return False
cli_path = _resolve_source_path(cli.source_path)
sdk_path = _resolve_source_path(sdk.source_path)
if cli_path is None or sdk_path is None:
return False
return (
cli_path.name == "code"
and sdk_path.name == "deepagents"
and cli_path.parent == sdk_path.parent
and cli_path.parent.name == "libs"
)
def _uses_exact_requirement_as_effective_version(
cli: DistributionVersion, sdk: DistributionVersion, requirement: Requirement | None
) -> bool:
"""Whether an exact `deepagents-code` pin represents sibling workspace HEAD.
Main does not track every SDK alpha release in `libs/deepagents`, so the
sibling SDK package in the same monorepo checkout can carry the previous
stable marker while `deepagents-code` intentionally declares a newer exact
alpha requirement. In that case the pin is the nearest published SDK baseline
represented by the running workspace. Ranged requirements and unrelated
editable SDK checkouts are never inferred this way.
Returns:
`True` when the exact pin is newer than every known editable SDK marker
and the SDK checkout is the monorepo sibling of the dcode checkout.
"""
if not _editable_sdk_is_cli_workspace_sibling(cli, sdk):
return False
pinned = _parse_version(_exact_pin(requirement))
if pinned is None:
return False
parsed_source = _parse_version(sdk.source_version)
if parsed_source is None:
return False
parsed_metadata = _parse_version(sdk.metadata_version)
markers = [parsed_source]
if parsed_metadata is not None:
markers.append(parsed_metadata)
return pinned > max(markers)
def _sdk_requirement_for_cli(cli: DistributionVersion) -> Requirement | None:
"""Return the live SDK requirement appropriate for the CLI install type."""
if cli.editable:
return _sdk_requirement_from_cli_source(cli.source_path)
return sdk_requirement_from_cli()
def _effective_sdk_version(
cli: DistributionVersion, sdk: DistributionVersion, requirement: Requirement | None
) -> str | None:
"""Return the SDK version diagnostics should treat as effective."""
pinned = _exact_pin(requirement)
if _uses_exact_requirement_as_effective_version(cli, sdk, requirement):
return pinned
return sdk.primary_version
def _display_sdk_version(
cli: DistributionVersion, sdk: DistributionVersion, requirement: Requirement | None
) -> str | None:
"""Return the SDK version string for diagnostics and trace metadata."""
version = _effective_sdk_version(cli, sdk, requirement)
if version is None or not _uses_exact_requirement_as_effective_version(
cli, sdk, requirement
):
return version
return _with_editable_local_version(version)
def _trace_sdk_version(
cli: DistributionVersion, sdk: DistributionVersion, requirement: Requirement | None
) -> str | None:
"""Return the SDK version string for LangSmith trace metadata.
Every editable SDK install gets the `editable` local segment, not just the
sibling workspace HEAD case that `_display_sdk_version` marks. A trace
carries the version string alone, with no room for the `(editable)`
annotation the human-facing surfaces render alongside it, and the SDK stamps
`lc_versions["deepagents"]` for any editable install — so suffixing only the
workspace HEAD case left the two entries in a single trace disagreeing.
Returns:
The version string, or `None` when it cannot be resolved.
"""
version = _effective_sdk_version(cli, sdk, requirement)
if version is None or not sdk.editable:
return version
return _with_editable_local_version(version)
def _sdk_requirement_comparison_version(
cli: DistributionVersion, sdk: DistributionVersion, requirement: Requirement | None
) -> str | None:
"""Return the SDK version to compare against the declared requirement."""
if sdk.status != "resolved":
return None
if sdk.editable:
return _effective_sdk_version(cli, sdk, requirement)
return sdk.metadata_version
def _requirement_satisfied(
requirement: Requirement | None, version: str | None
) -> bool | None:
"""Return whether `version` satisfies `requirement`.
Args:
requirement: The declared requirement, or `None`.
version: The SDK version to compare, or `None`.
Returns:
`True`/`False` when the comparison can be made, or `None` when either
input is absent or the version cannot be parsed. Prereleases are
allowed so a prerelease pin (e.g. `==0.7.0a7`) is evaluated
correctly.
"""
if requirement is None or version is None:
return None
try:
parsed = Version(version)
except InvalidVersion:
logger.debug(
"Could not parse SDK version %r for requirement comparison",
version,
exc_info=True,
)
return None
return requirement.specifier.contains(parsed, prereleases=True)
def collect_version_report() -> VersionReport:
"""Collect the offline version report used by `--version`, `/version`, and doctor.
Returns:
A `VersionReport` bundling CLI and SDK version facts with the declared
`deepagents` requirement and whether the effective SDK version
satisfies it. Performs no network or subprocess calls.
"""
cli = collect_cli_version_info()
sdk = collect_sdk_version_info()
requirement = _sdk_requirement_for_cli(cli)
satisfied = _requirement_satisfied(
requirement, _sdk_requirement_comparison_version(cli, sdk, requirement)
)
return VersionReport(
cli=cli,
sdk=sdk,
sdk_requirement=requirement,
sdk_requirement_satisfied=satisfied,
)
def _format_requirement_display(requirement: Requirement) -> str:
"""Render a requirement's version constraint for display.
A single exact pin (`==X`) is shown as the bare version for readability;
any other constraint keeps its full specifier form.
Returns:
The display form of the requirement's version constraint.
"""
specs = list(requirement.specifier)
if len(specs) == 1 and specs[0].operator == "==":
return specs[0].version
return str(requirement.specifier) or "any"
def _join_annotation_parts(parts: list[str]) -> str:
"""Join annotation parts into a trailing ` (...)` suffix.
Returns:
The parts joined as ` (a; b)`, or an empty string when `parts` is empty.
"""
return f" ({'; '.join(parts)})" if parts else ""
def format_cli_version_annotation(info: DistributionVersion) -> str:
"""Return the source/metadata drift annotation for the CLI version line.
Editable status is surfaced separately by every caller (the dedicated
`Editable install:` line on `--version`/`/version`, and the `Install method`
item in `doctor`), so it is intentionally *not* repeated inline here — that
kept the CLI reading "editable" twice on those surfaces.
Args:
info: The CLI version facts.
Returns:
A trailing ` (...)` suffix flagging any drift between the source and
installed metadata versions, or an empty string when they agree (so
normal installs stay unchanged).
"""
parts: list[str] = []
if info.has_drift and info.metadata_version is not None:
parts.append(f"installed metadata: {info.metadata_version}")
return _join_annotation_parts(parts)
def format_sdk_version_annotation(report: VersionReport) -> str:
"""Return the workspace/editable/drift/mismatch SDK version annotation.
Args:
report: The collected version report.
Returns:
A trailing ` (...)` suffix identifying sibling workspace HEAD or a
general editable install, preserving raw source/metadata facts when
useful, and flagging an actionable requirement mismatch. Empty when
none applies.
"""
info = report.sdk
workspace_head = report.sdk_is_workspace_head
parts: list[str] = []
if workspace_head:
parts.append("workspace HEAD")
elif info.editable:
parts.append("editable")
if workspace_head and info.source_version is not None:
parts.append(f"source marker: {info.source_version}")
elif report.sdk_source_version_invalid:
marker = info.source_version or "unavailable"
parts.append(f"invalid source marker: {marker}")
metadata_needs_annotation = info.has_drift or (
info.editable
and info.source_version is None
and info.metadata_version != report.effective_sdk_version
)
if metadata_needs_annotation and info.metadata_version is not None:
parts.append(f"installed metadata: {info.metadata_version}")
if (
not workspace_head
and report.sdk_requirement_mismatch
and report.sdk_requirement is not None
):
required = _format_requirement_display(report.sdk_requirement)
parts.append(f"required by deepagents-code: {required} — mismatch")
return _join_annotation_parts(parts)
def resolve_sdk_version() -> tuple[str | None, DistributionMetadataStatus]:
"""Resolve the diagnostic `deepagents` SDK version.
Compatibility wrapper for callers that only need one SDK version string and
lookup status. Every editable install carries an `+editable` local segment,
matching how the SDK stamps `lc_versions["deepagents"]`. For sibling monorepo
packages whose stable source marker trails dcode's exact SDK pin, the pin
identifies the nearest published baseline the workspace HEAD represents.
Returns:
`(version, status)`. `version` is the resolved version string when
`status` is `"resolved"`, otherwise `None`.
"""
cli = collect_cli_version_info()
sdk = collect_sdk_version_info()
if sdk.status != "resolved":
return None, sdk.status
requirement = _sdk_requirement_for_cli(cli)
return _trace_sdk_version(cli, sdk, requirement), "resolved"
_EXTRA_MARKER_RE = re.compile(r"""extra\s*==\s*["']([^"']+)["']""")
class ExtrasIntrospectionError(RuntimeError):
"""Raised when installed extras cannot be determined safely."""
MODEL_PROVIDER_EXTRAS: frozenset[str] = frozenset(
{