managed-deepagents 0.9.1.dev1__py3-none-win_amd64.whl → 0.9.1.dev2__py3-none-win_amd64.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.
Binary file
@@ -10,6 +10,7 @@ import json
10
10
  import os
11
11
  from collections.abc import Coroutine, Mapping
12
12
  from concurrent.futures import ThreadPoolExecutor
13
+ from http import HTTPStatus
13
14
  from importlib import import_module
14
15
  from typing import TYPE_CHECKING, cast
15
16
  from urllib.parse import quote
@@ -145,6 +146,8 @@ def run_sync(coroutine: Coroutine[object, object, None]) -> None:
145
146
  def patch_sandbox_proxy_config(
146
147
  sandbox: SandboxDefinition, name: str, config: dict[str, object]
147
148
  ) -> None:
149
+ from langsmith.sandbox import ResourceNotFoundError # noqa: PLC0415
150
+
148
151
  from managed_deepagents.runtime import _sandbox_client_kwargs # noqa: PLC0415
149
152
 
150
153
  kwargs = _sandbox_client_kwargs(sandbox)
@@ -167,6 +170,10 @@ def patch_sandbox_proxy_config(
167
170
  )
168
171
  except Exception: # noqa: BLE001 — omit secret-bearing transport causes
169
172
  raise RuntimeError("Could not update sandbox proxy credentials.") from None
173
+ if response.status_code == HTTPStatus.NOT_FOUND:
174
+ raise ResourceNotFoundError(
175
+ "Could not update sandbox proxy credentials.", "sandbox"
176
+ ) from None
170
177
  if not response.is_success:
171
178
  raise RuntimeError("Could not update sandbox proxy credentials.")
172
179
 
@@ -187,6 +194,8 @@ class SandboxProxyConfigSync:
187
194
  async def sync(
188
195
  self, sandbox: SandboxDefinition, name: str | None, config: Mapping[str, object] | None
189
196
  ) -> None:
197
+ from langsmith.sandbox import ResourceNotFoundError # noqa: PLC0415
198
+
190
199
  template = sandbox.options.get("proxy_config")
191
200
  if template is None:
192
201
  return
@@ -198,6 +207,10 @@ class SandboxProxyConfigSync:
198
207
  return
199
208
  try:
200
209
  await asyncio.to_thread(patch_sandbox_proxy_config, sandbox, name, wire)
210
+ except ResourceNotFoundError:
211
+ raise ResourceNotFoundError(
212
+ "Could not update sandbox proxy credentials.", "sandbox"
213
+ ) from None
201
214
  except Exception: # noqa: BLE001 — omit secret-bearing transport causes
202
215
  raise RuntimeError("Could not update sandbox proxy credentials.") from None
203
216
  self._hashes[name] = digest
@@ -22,6 +22,7 @@ import threading
22
22
  import time
23
23
  from collections.abc import Callable, Iterable, Mapping
24
24
  from functools import partial
25
+ from http import HTTPStatus
25
26
  from typing import TYPE_CHECKING, Any, Literal, Protocol, TypedDict, cast
26
27
 
27
28
  from deepagents import FilesystemPermission, create_deep_agent
@@ -127,18 +128,6 @@ class _Omitted:
127
128
 
128
129
  _OMITTED = _Omitted()
129
130
 
130
- # Cold-box race: command stream died before the sandbox accepted the command.
131
- _STREAM_NEVER_STARTED_RE = re.compile(
132
- r"Command stream ended before ['\"]started['\"] message",
133
- flags=re.IGNORECASE,
134
- )
135
- _STREAM_NEVER_STARTED_TYPES = frozenset(
136
- {
137
- "_StreamEndedBeforeStarted",
138
- "StreamEndedBeforeStarted",
139
- }
140
- )
141
-
142
131
  if TYPE_CHECKING:
143
132
  from deepagents.backends.protocol import BackendProtocol as DeepAgentsBackend
144
133
  from deepagents.backends.protocol import FileDownloadResponse, FileUploadResponse
@@ -309,13 +298,16 @@ _SANDBOX_NAME_CONFLICT_RE = re.compile(
309
298
  class _ManagedSandboxEntry:
310
299
  """Cached sandbox plus per-thread connector sandbox sync state."""
311
300
 
312
- __slots__ = ("backend", "host_name", "synced_threads")
301
+ __slots__ = ("backend", "host_name", "sandbox_id", "synced_threads")
313
302
 
314
- def __init__(self, backend: object, host_name: str | None = None) -> None:
303
+ def __init__(
304
+ self, backend: object, host_name: str | None = None, sandbox_id: str | None = None
305
+ ) -> None:
315
306
  self.backend = backend
316
307
  self.synced_threads: set[str] = set()
317
308
  #: LangSmith box name for this entry (deterministic or unique-suffixed).
318
309
  self.host_name = host_name
310
+ self.sandbox_id = sandbox_id
319
311
 
320
312
 
321
313
  #: Created sandboxes, keyed by thread and any explicit dynamic selection,
@@ -384,22 +376,6 @@ def _sandbox_create_kwargs(
384
376
  return create_kwargs
385
377
 
386
378
 
387
- def _host_sandbox_names_for(
388
- sandbox: SandboxDefinition,
389
- config: ManagedRunConfig | Mapping[str, object] | None,
390
- selection_fingerprint: str | None = None,
391
- ) -> list[str]:
392
- """Deterministic Host box names to adopt or invalidate for this thread."""
393
- deployment = _managed_deployment_name()
394
- if deployment is None:
395
- return []
396
- return _managed_sandbox_lookup_names(
397
- deployment,
398
- _thread_scope_key(config, selection_fingerprint),
399
- sandbox,
400
- )
401
-
402
-
403
379
  def _sandbox_client_kwargs(sandbox: SandboxDefinition) -> dict[str, object]:
404
380
  """Client kwargs pinning the API key and the workspace holding the recipe."""
405
381
  kwargs: dict[str, object] = {}
@@ -422,29 +398,6 @@ def _sandbox_client_for(sandbox: SandboxDefinition) -> object:
422
398
  return sandbox_client_cls(**_sandbox_client_kwargs(sandbox))
423
399
 
424
400
 
425
- def _delete_host_sandbox(sandbox: SandboxDefinition, name: str) -> None:
426
- """Best-effort Host delete so the next resolve cannot adopt a broken box."""
427
- try:
428
- client = _sandbox_client_for(sandbox)
429
- delete_sandbox = getattr(client, "delete_sandbox", None)
430
- if not callable(delete_sandbox):
431
- return
432
- _await_if_needed(delete_sandbox(name))
433
- _LOG.info("[mda] sandbox invalidate: deleted name=%r", name)
434
- except Exception as error: # noqa: BLE001 — recreate must proceed anyway
435
- _LOG.warning(
436
- "[mda] sandbox invalidate: delete failed name=%r err=%s: %s",
437
- name,
438
- type(error).__name__,
439
- error,
440
- )
441
-
442
-
443
- def _block_sandbox_names(names: Iterable[str]) -> None:
444
- with _managed_sandbox_lock:
445
- _invalidated_sandbox_names.update(names)
446
-
447
-
448
401
  def _sandbox_name_blocked(name: str) -> bool:
449
402
  with _managed_sandbox_lock:
450
403
  return name in _invalidated_sandbox_names
@@ -455,16 +408,6 @@ def _unblock_sandbox_name(name: str) -> None:
455
408
  _invalidated_sandbox_names.discard(name)
456
409
 
457
410
 
458
- def _backend_id(backend: object | None) -> str | None:
459
- if backend is None:
460
- return None
461
- value = getattr(backend, "id", None)
462
- if value is None:
463
- return None
464
- text = str(value).strip()
465
- return text or None
466
-
467
-
468
411
  def _sandbox_handle_name(handle: object) -> str | None:
469
412
  """Read ``name`` from an SDK sandbox handle (object or mapping)."""
470
413
  name = _string_option(getattr(handle, "name", None))
@@ -486,115 +429,6 @@ def _sandbox_handle_id(handle: object) -> str | None:
486
429
  return text or None
487
430
 
488
431
 
489
- def _cache_entry_matches_expected(
490
- entry: _ManagedSandboxEntry,
491
- *,
492
- expected_backend_id: str | None,
493
- expected_host_name: str | None,
494
- ) -> bool:
495
- """True when ``entry`` is still the sandbox the caller failed on."""
496
- if expected_backend_id is not None:
497
- return _backend_id(entry.backend) == expected_backend_id
498
- return expected_host_name is not None and entry.host_name == expected_host_name
499
-
500
-
501
- def _invalidate_managed_sandbox( # noqa: C901
502
- sandbox: SandboxDefinition,
503
- config: ManagedRunConfig | Mapping[str, object] | None,
504
- *,
505
- expected_backend_id: str | None = None,
506
- expected_host_name: str | None = None,
507
- selection_fingerprint: str | None = None,
508
- ) -> None:
509
- """Drop a cached sandbox and delete its Host box so recreate cannot adopt it.
510
-
511
- Process-cache clear alone is not enough under deploy: names are deterministic
512
- per scope, so the next resolve would re-adopt the same broken box. Mark the
513
- name blocked (delete can lag) and best-effort ``delete_sandbox``.
514
-
515
- When ``expected_backend_id`` / ``expected_host_name`` are set, only pop the
516
- cache entry if it still refers to that failing sandbox. A concurrent sibling
517
- may already have replaced it — deleting the replacement would strand the
518
- healthy recreate.
519
- """
520
- key = _thread_scope_key(config, selection_fingerprint)
521
- names: list[str] = []
522
- has_expected = expected_backend_id is not None or expected_host_name is not None
523
- # Take the per-key lock so we do not race an in-flight provisioner that
524
- # would otherwise re-insert a box we just invalidated.
525
- with _sandbox_key_lock(key), _managed_sandbox_lock:
526
- entry = _managed_sandboxes.get(key)
527
- if entry is not None and has_expected:
528
- if _cache_entry_matches_expected(
529
- entry,
530
- expected_backend_id=expected_backend_id,
531
- expected_host_name=expected_host_name,
532
- ):
533
- entry = _managed_sandboxes.pop(key, None)
534
- else:
535
- # Safe to delete the failing box only when the replacement uses
536
- # a different Host name (unique-suffix path).
537
- if expected_host_name and entry.host_name and expected_host_name != entry.host_name:
538
- names.append(expected_host_name)
539
- entry = None
540
- elif entry is not None:
541
- entry = _managed_sandboxes.pop(key, None)
542
-
543
- popped = entry is not None
544
- if entry is not None and entry.host_name:
545
- names.append(entry.host_name)
546
- if expected_host_name and (popped or not has_expected):
547
- names.append(expected_host_name)
548
- if not has_expected:
549
- # Failed before a resolved identity was captured (e.g. cold provision):
550
- # delete the deterministic name so the next resolve cannot re-adopt it.
551
- try:
552
- extra = _host_sandbox_names_for(sandbox, config, selection_fingerprint)
553
- except Exception: # noqa: BLE001 — still clear cache even if naming fails
554
- extra = []
555
- names.extend(extra)
556
- unique_names = list(dict.fromkeys(names))
557
- if not unique_names:
558
- return
559
-
560
- _block_sandbox_names(unique_names)
561
- for name in unique_names:
562
- _delete_host_sandbox(sandbox, name)
563
-
564
-
565
- def _is_sandbox_stream_error(error: object) -> bool:
566
- """True when execute failed before the sandbox accepted the command.
567
-
568
- Matches only the cold-box readiness race (named error or message). Ambiguous
569
- stream/transport errors may have already started a command — those belong on
570
- other recreate matchers, not this classifier.
571
- """
572
- if type(error).__name__ in _STREAM_NEVER_STARTED_TYPES:
573
- return True
574
- message = f"{type(error).__name__}: {error}"
575
- return bool(_STREAM_NEVER_STARTED_RE.search(message))
576
-
577
-
578
- def _is_transient_sandbox_error(error: object) -> bool:
579
- """True when a sandbox API error is worth invalidating + recreating once."""
580
- # Never-started stream race is recreate-safe. Truncated HTTP bodies and
581
- # peer-closed errors are recreate-only as well.
582
- if _is_sandbox_stream_error(error):
583
- return True
584
- message = f"{type(error).__name__}: {error}"
585
- return bool(
586
- re.search(
587
- r"LangSmithSandboxError|HTTP 502|Bad Gateway|HTTP 503|HTTP 504|"
588
- r"ECONNRESET|ETIMEDOUT|"
589
- r"peer closed connection without sending complete message body|"
590
- r"incomplete chunked read|"
591
- r"sandbox.*(not found|gone|unavailable|terminated)",
592
- message,
593
- flags=re.IGNORECASE,
594
- )
595
- )
596
-
597
-
598
432
  (SandboxClient,) = _optional_runtime_symbols("langsmith.sandbox", "SandboxClient")
599
433
 
600
434
 
@@ -1599,8 +1433,6 @@ def _managed_sandbox_backend( # noqa: C901
1599
1433
  def __init__(self, bound_configurable: Mapping[str, object] | None) -> None:
1600
1434
  self._bound_configurable = bound_configurable
1601
1435
  self._resolved_backend: ResolvedSandboxBackend | None = None
1602
- self._resolved_host_name: str | None = None
1603
- self._recreated_after_transient = False
1604
1436
 
1605
1437
  def bind_runtime(self, runtime: object) -> _LazyManagedSandboxBackend:
1606
1438
  """Capture this run's configuration without resolving the sandbox."""
@@ -1625,15 +1457,13 @@ def _managed_sandbox_backend( # noqa: C901
1625
1457
  return "pending:sandbox"
1626
1458
 
1627
1459
  def ls(self, path: str = "/") -> object:
1628
- return self._with_sandbox_retry(lambda: self._backend().ls(path))
1460
+ return self._call("ls", path)
1629
1461
 
1630
1462
  async def als(self, path: str = "/") -> object:
1631
1463
  return await self._acall("als", path)
1632
1464
 
1633
1465
  def read(self, file_path: str, offset: int = 0, limit: int = 2000) -> object:
1634
- return self._with_sandbox_retry(
1635
- lambda: self._backend().read(file_path, offset=offset, limit=limit)
1636
- )
1466
+ return self._call("read", file_path, offset=offset, limit=limit)
1637
1467
 
1638
1468
  async def aread(self, file_path: str, offset: int = 0, limit: int = 2000) -> object:
1639
1469
  return await self._acall("aread", file_path, offset, limit)
@@ -1647,10 +1477,8 @@ def _managed_sandbox_backend( # noqa: C901
1647
1477
  max_count: int | None = None,
1648
1478
  ) -> object:
1649
1479
  if max_count is not None:
1650
- return self._with_sandbox_retry(
1651
- lambda: self._backend().grep(pattern, path, glob, max_count=max_count)
1652
- )
1653
- return self._with_sandbox_retry(lambda: self._backend().grep(pattern, path, glob))
1480
+ return self._call("grep", pattern, path, glob, max_count=max_count)
1481
+ return self._call("grep", pattern, path, glob)
1654
1482
 
1655
1483
  async def agrep(
1656
1484
  self,
@@ -1668,7 +1496,7 @@ def _managed_sandbox_backend( # noqa: C901
1668
1496
  # Refuse before resolving: a root glob is never worth creating a sandbox for.
1669
1497
  if _is_filesystem_root(path):
1670
1498
  return _root_glob_refusal()
1671
- return self._with_sandbox_retry(lambda: self._backend().glob(pattern, path))
1499
+ return self._call("glob", pattern, path)
1672
1500
 
1673
1501
  async def aglob(self, pattern: str, path: str | None = None) -> object:
1674
1502
  if _is_filesystem_root(path):
@@ -1676,7 +1504,7 @@ def _managed_sandbox_backend( # noqa: C901
1676
1504
  return await self._acall("aglob", pattern, path)
1677
1505
 
1678
1506
  def write(self, file_path: str, content: str) -> object:
1679
- return self._with_sandbox_retry(lambda: self._backend().write(file_path, content))
1507
+ return self._call("write", file_path, content)
1680
1508
 
1681
1509
  async def awrite(self, file_path: str, content: str) -> object:
1682
1510
  return await self._acall("awrite", file_path, content)
@@ -1688,13 +1516,12 @@ def _managed_sandbox_backend( # noqa: C901
1688
1516
  new_string: str,
1689
1517
  replace_all: bool = False,
1690
1518
  ) -> object:
1691
- return self._with_sandbox_retry(
1692
- lambda: self._backend().edit(
1693
- file_path,
1694
- old_string,
1695
- new_string,
1696
- replace_all=replace_all,
1697
- )
1519
+ return self._call(
1520
+ "edit",
1521
+ file_path,
1522
+ old_string,
1523
+ new_string,
1524
+ replace_all=replace_all,
1698
1525
  )
1699
1526
 
1700
1527
  async def aedit(
@@ -1713,49 +1540,30 @@ def _managed_sandbox_backend( # noqa: C901
1713
1540
  )
1714
1541
 
1715
1542
  def delete(self, file_path: str) -> object:
1716
- return self._with_sandbox_retry(lambda: self._backend().delete(file_path))
1543
+ return self._call("delete", file_path)
1717
1544
 
1718
1545
  async def adelete(self, file_path: str) -> object:
1719
1546
  return await self._acall("adelete", file_path)
1720
1547
 
1721
1548
  def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
1722
- return cast(
1723
- "list[FileUploadResponse]",
1724
- self._with_sandbox_retry(lambda: self._backend().upload_files(files)),
1725
- )
1549
+ return cast("list[FileUploadResponse]", self._call("upload_files", files))
1726
1550
 
1727
1551
  async def aupload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
1728
1552
  return cast("list[FileUploadResponse]", await self._acall("aupload_files", files))
1729
1553
 
1730
1554
  def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
1731
- return cast(
1732
- "list[FileDownloadResponse]",
1733
- self._with_sandbox_retry(lambda: self._backend().download_files(paths)),
1734
- )
1555
+ return cast("list[FileDownloadResponse]", self._call("download_files", paths))
1735
1556
 
1736
1557
  async def adownload_files(self, paths: list[str]) -> list[FileDownloadResponse]:
1737
1558
  return cast("list[FileDownloadResponse]", await self._acall("adownload_files", paths))
1738
1559
 
1739
1560
  def execute(self, command: str, *, timeout: int | None = None) -> object:
1740
- is_syncing_sandbox_proxy_config = False
1741
-
1742
- def _run() -> object:
1743
- nonlocal is_syncing_sandbox_proxy_config
1744
- backend = self._backend()
1745
- if has_proxy_config:
1746
- is_syncing_sandbox_proxy_config = True
1747
- run_sync(self._sync_sandbox_proxy_config())
1748
- is_syncing_sandbox_proxy_config = False
1749
- if timeout is not None:
1750
- try:
1751
- return backend.execute(command, timeout=timeout)
1752
- except TypeError:
1753
- return backend.execute(command)
1754
- return backend.execute(command)
1755
-
1756
- return self._with_sandbox_retry(
1757
- _run, retry_allowed=lambda: not is_syncing_sandbox_proxy_config
1758
- )
1561
+ if timeout is not None:
1562
+ try:
1563
+ return self._call("execute", command, timeout=timeout)
1564
+ except TypeError:
1565
+ return self._call("execute", command)
1566
+ return self._call("execute", command)
1759
1567
 
1760
1568
  async def aexecute(
1761
1569
  self,
@@ -1779,20 +1587,12 @@ def _managed_sandbox_backend( # noqa: C901
1779
1587
  config,
1780
1588
  )
1781
1589
 
1782
- def _remember_resolved(
1783
- self, backend: ResolvedSandboxBackend, scope_key: str
1784
- ) -> ResolvedSandboxBackend:
1785
- self._resolved_backend = backend
1786
- self._resolved_host_name = _peek_managed_host_name(scope_key)
1787
- return backend
1788
-
1789
1590
  def _backend(self) -> ResolvedSandboxBackend:
1790
1591
  if self._resolved_backend is not None:
1791
1592
  return self._resolved_backend
1792
1593
  config = _effective_sandbox_run_config(
1793
1594
  run_config, bound_configurable=self._bound_configurable
1794
1595
  )
1795
- key = _thread_scope_key(config, selection_fingerprint)
1796
1596
  backend = cast(
1797
1597
  "ResolvedSandboxBackend",
1798
1598
  _resolve_managed_sandbox(
@@ -1803,7 +1603,8 @@ def _managed_sandbox_backend( # noqa: C901
1803
1603
  selection_fingerprint=selection_fingerprint,
1804
1604
  ),
1805
1605
  )
1806
- return self._remember_resolved(backend, key)
1606
+ self._resolved_backend = backend
1607
+ return backend
1807
1608
 
1808
1609
  async def _abackend(self) -> ResolvedSandboxBackend:
1809
1610
  if self._resolved_backend is not None:
@@ -1811,7 +1612,6 @@ def _managed_sandbox_backend( # noqa: C901
1811
1612
  config = _effective_sandbox_run_config(
1812
1613
  run_config, bound_configurable=self._bound_configurable
1813
1614
  )
1814
- key = _thread_scope_key(config, selection_fingerprint)
1815
1615
  backend = cast(
1816
1616
  "ResolvedSandboxBackend",
1817
1617
  await asyncio.to_thread(
@@ -1823,100 +1623,51 @@ def _managed_sandbox_backend( # noqa: C901
1823
1623
  selection_fingerprint,
1824
1624
  ),
1825
1625
  )
1826
- return self._remember_resolved(backend, key)
1626
+ self._resolved_backend = backend
1627
+ return backend
1827
1628
 
1828
- def _with_sandbox_retry(
1829
- self,
1830
- operation: Callable[[], object],
1831
- *,
1832
- retry_allowed: Callable[[], bool] | None = None,
1833
- ) -> object:
1629
+ def _recover(self, backend: ResolvedSandboxBackend, error: Exception) -> None:
1630
+ if not _is_sandbox_not_found_error(error):
1631
+ return
1834
1632
  config = _effective_sandbox_run_config(
1835
1633
  run_config, bound_configurable=self._bound_configurable
1836
1634
  )
1635
+ previous_name = _peek_managed_host_name(
1636
+ _thread_scope_key(config, selection_fingerprint)
1637
+ )
1837
1638
  try:
1838
- return operation()
1839
- except Exception as error:
1840
- if retry_allowed is not None and not retry_allowed():
1841
- raise
1842
- if self._recreated_after_transient or not _is_transient_sandbox_error(error):
1843
- raise
1844
- key = _thread_scope_key(config, selection_fingerprint)
1845
- failing_id = _backend_id(self._resolved_backend)
1846
- failing_name = self._resolved_host_name
1847
- _LOG.warning(
1848
- "[mda] sandbox op failed; invalidating and recreating once "
1849
- "scope=%r sandbox_id=%r err=%s: %s",
1850
- key,
1851
- failing_id,
1852
- type(error).__name__,
1853
- error,
1639
+ recovered = _recover_managed_sandbox(
1640
+ sandbox, config, backend, connectors, identity, selection_fingerprint
1854
1641
  )
1855
- self._recreated_after_transient = True
1856
- _invalidate_managed_sandbox(
1857
- sandbox,
1858
- config,
1859
- expected_backend_id=failing_id,
1860
- expected_host_name=failing_name,
1861
- selection_fingerprint=selection_fingerprint,
1862
- )
1863
- sandbox_proxy_config_sync.invalidate(failing_name)
1864
- self._resolved_backend = None
1865
- self._resolved_host_name = None
1866
- return operation()
1642
+ except Exception: # noqa: BLE001
1643
+ return
1644
+ if recovered is not backend:
1645
+ sandbox_proxy_config_sync.invalidate(previous_name)
1646
+ if self._resolved_backend is backend:
1647
+ self._resolved_backend = recovered
1648
+
1649
+ def _call(self, method: str, *args: object, **kwargs: object) -> object:
1650
+ backend = self._backend()
1651
+ try:
1652
+ if method == "execute" and has_proxy_config:
1653
+ run_sync(self._sync_sandbox_proxy_config())
1654
+ return getattr(backend, method)(*args, **kwargs)
1655
+ except Exception as error:
1656
+ self._recover(backend, error)
1657
+ raise
1867
1658
 
1868
1659
  async def _acall(self, method: str, *args: object, **kwargs: object) -> object:
1869
- config = _effective_sandbox_run_config(
1870
- run_config, bound_configurable=self._bound_configurable
1871
- )
1872
- failing_id: str | None = None
1873
- failing_name: str | None = None
1874
- is_syncing_sandbox_proxy_config = False
1660
+ backend = await self._abackend()
1875
1661
  try:
1876
- backend = await self._abackend()
1877
- failing_id = _backend_id(backend)
1878
- failing_name = self._resolved_host_name
1879
1662
  if method == "aexecute":
1880
- is_syncing_sandbox_proxy_config = True
1881
1663
  await self._sync_sandbox_proxy_config()
1882
- is_syncing_sandbox_proxy_config = False
1883
1664
  result = getattr(backend, method)(*args, **kwargs)
1884
1665
  if inspect.isawaitable(result):
1885
1666
  return await result
1886
1667
  return result
1887
1668
  except Exception as error:
1888
- if is_syncing_sandbox_proxy_config:
1889
- raise
1890
- if self._recreated_after_transient or not _is_transient_sandbox_error(error):
1891
- raise
1892
- key = _thread_scope_key(config, selection_fingerprint)
1893
- _LOG.warning(
1894
- "[mda] sandbox op failed; invalidating and recreating once "
1895
- "scope=%r method=%r sandbox_id=%r err=%s: %s",
1896
- key,
1897
- method,
1898
- failing_id,
1899
- type(error).__name__,
1900
- error,
1901
- )
1902
- self._recreated_after_transient = True
1903
- _invalidate_managed_sandbox(
1904
- sandbox,
1905
- config,
1906
- expected_backend_id=failing_id,
1907
- expected_host_name=failing_name,
1908
- selection_fingerprint=selection_fingerprint,
1909
- )
1910
- sandbox_proxy_config_sync.invalidate(failing_name)
1911
- self._resolved_backend = None
1912
- self._resolved_host_name = None
1913
- backend = await self._abackend()
1914
- if method == "aexecute":
1915
- await self._sync_sandbox_proxy_config()
1916
- result = getattr(backend, method)(*args, **kwargs)
1917
- if inspect.isawaitable(result):
1918
- return await result
1919
- return result
1669
+ await asyncio.to_thread(self._recover, backend, error)
1670
+ raise
1920
1671
 
1921
1672
  return _LazyManagedSandboxBackend(None)
1922
1673
 
@@ -2020,7 +1771,7 @@ def _resolve_managed_sandbox(
2020
1771
  # Cold create/provision while holding only the per-key lock. Do not hold
2021
1772
  # ``_managed_sandbox_lock`` here — websocket retries can take tens of
2022
1773
  # seconds and would wedge every other Host worker.
2023
- backend, host_name = _create_langsmith_sandbox(
1774
+ backend, host_name, sandbox_id = _create_langsmith_sandbox(
2024
1775
  sandbox,
2025
1776
  config=config,
2026
1777
  connectors=connectors,
@@ -2029,13 +1780,68 @@ def _resolve_managed_sandbox(
2029
1780
  scope_key=key,
2030
1781
  selection_fingerprint=selection_fingerprint,
2031
1782
  )
2032
- entry = _ManagedSandboxEntry(backend, host_name=host_name)
1783
+ entry = _ManagedSandboxEntry(backend, host_name=host_name, sandbox_id=sandbox_id)
2033
1784
  entry.synced_threads.add(thread_key)
2034
1785
  with _managed_sandbox_lock:
2035
1786
  _managed_sandboxes[key] = entry
2036
1787
  return entry.backend
2037
1788
 
2038
1789
 
1790
+ def _is_sandbox_not_found_error(error: Exception) -> bool:
1791
+ from langsmith.sandbox import ResourceNotFoundError, SandboxConnectionError # noqa: PLC0415
1792
+
1793
+ if isinstance(error, ResourceNotFoundError):
1794
+ return True
1795
+ if isinstance(error, SandboxConnectionError):
1796
+ response = getattr(error.__cause__, "response", None)
1797
+ return getattr(response, "status_code", None) == HTTPStatus.NOT_FOUND
1798
+ return False
1799
+
1800
+
1801
+ def _recover_managed_sandbox(
1802
+ sandbox: SandboxDefinition,
1803
+ config: ManagedRunConfig | Mapping[str, object] | None,
1804
+ failed_backend: ResolvedSandboxBackend,
1805
+ connectors: list[Connector] | None = None,
1806
+ identity: IdentityDefinitionLike | None = None,
1807
+ selection_fingerprint: str | None = None,
1808
+ ) -> ResolvedSandboxBackend:
1809
+ from langsmith.sandbox import ResourceNotFoundError # noqa: PLC0415
1810
+
1811
+ key = _thread_scope_key(config, selection_fingerprint)
1812
+ with _sandbox_key_lock(key):
1813
+ with _managed_sandbox_lock:
1814
+ entry = _managed_sandboxes.get(key)
1815
+ if entry is None:
1816
+ return failed_backend
1817
+ current = cast("ResolvedSandboxBackend", entry.backend)
1818
+ if current is not failed_backend or entry.host_name is None:
1819
+ return current
1820
+ client = _sandbox_client_for(sandbox)
1821
+ get_sandbox = cast("Callable[[str], object]", getattr(client, "get_sandbox")) # noqa: B009
1822
+ try:
1823
+ existing = _await_if_needed(get_sandbox(entry.host_name))
1824
+ except ResourceNotFoundError:
1825
+ existing = None
1826
+ if existing is not None and _sandbox_handle_id(existing) == entry.sandbox_id:
1827
+ return current
1828
+ backend, host_name, sandbox_id = _create_langsmith_sandbox(
1829
+ sandbox,
1830
+ config=config,
1831
+ connectors=connectors,
1832
+ identity=identity,
1833
+ scope_key=key,
1834
+ selection_fingerprint=selection_fingerprint,
1835
+ recovery_name=entry.host_name,
1836
+ existing_sandbox=existing,
1837
+ )
1838
+ replacement = _ManagedSandboxEntry(backend, host_name=host_name, sandbox_id=sandbox_id)
1839
+ replacement.synced_threads.add(_thread_sync_key(config))
1840
+ with _managed_sandbox_lock:
1841
+ _managed_sandboxes[key] = replacement
1842
+ return backend
1843
+
1844
+
2039
1845
  def _thread_sync_key(
2040
1846
  config: ManagedRunConfig | Mapping[str, object] | None,
2041
1847
  ) -> str:
@@ -2364,6 +2170,22 @@ def _resolve_sandbox_instance(
2364
2170
  return created, False
2365
2171
 
2366
2172
 
2173
+ def _create_replacement_sandbox(
2174
+ client: object, create_kwargs: dict[str, object], name: str
2175
+ ) -> tuple[object, bool]:
2176
+ from langsmith.sandbox import ( # noqa: PLC0415
2177
+ ResourceAlreadyExistsError,
2178
+ ResourceNameConflictError,
2179
+ )
2180
+
2181
+ create_sandbox = cast("Callable[..., object]", getattr(client, "create_sandbox")) # noqa: B009
2182
+ try:
2183
+ return _await_if_needed(create_sandbox(name=name, **create_kwargs)), False
2184
+ except (ResourceAlreadyExistsError, ResourceNameConflictError):
2185
+ get_sandbox = cast("Callable[[str], object]", getattr(client, "get_sandbox")) # noqa: B009
2186
+ return _await_if_needed(get_sandbox(name)), True
2187
+
2188
+
2367
2189
  def _create_langsmith_sandbox(
2368
2190
  sandbox: SandboxDefinition,
2369
2191
  *,
@@ -2373,7 +2195,9 @@ def _create_langsmith_sandbox(
2373
2195
  sandbox_mode: Literal["create", "reuse"] = "create",
2374
2196
  scope_key: str,
2375
2197
  selection_fingerprint: str | None = None,
2376
- ) -> tuple[ResolvedSandboxBackend, str | None]:
2198
+ recovery_name: str | None = None,
2199
+ existing_sandbox: object | None = None,
2200
+ ) -> tuple[ResolvedSandboxBackend, str | None, str | None]:
2377
2201
  """Build a LangSmith sandbox, optionally from the baked recipe, and wrap it."""
2378
2202
  create_kwargs = _sandbox_create_kwargs(sandbox, selection_fingerprint)
2379
2203
  client = _sandbox_client_for(sandbox)
@@ -2381,17 +2205,20 @@ def _create_langsmith_sandbox(
2381
2205
  lookup_names = (
2382
2206
  _managed_sandbox_lookup_names(deployment, scope_key, sandbox) if deployment else []
2383
2207
  )
2384
- sandbox_name = lookup_names[0] if lookup_names else None
2208
+ sandbox_name = recovery_name or (lookup_names[0] if lookup_names else None)
2385
2209
  fallback_name: Callable[[], str] | None = None
2386
2210
  if deployment:
2387
2211
  fallback_name = partial(_managed_sandbox_fallback_name, deployment, scope_key)
2388
- langsmith_sandbox, adopted = _resolve_sandbox_instance(
2389
- client,
2390
- create_kwargs,
2391
- sandbox_name,
2392
- fallback_name,
2393
- lookup_names[1:],
2394
- )
2212
+ if existing_sandbox is not None:
2213
+ langsmith_sandbox, adopted = existing_sandbox, True
2214
+ elif recovery_name:
2215
+ langsmith_sandbox, adopted = _create_replacement_sandbox(
2216
+ client, create_kwargs, recovery_name
2217
+ )
2218
+ else:
2219
+ langsmith_sandbox, adopted = _resolve_sandbox_instance(
2220
+ client, create_kwargs, sandbox_name, fallback_name, lookup_names[1:]
2221
+ )
2395
2222
  host_name = _sandbox_handle_name(langsmith_sandbox) or sandbox_name
2396
2223
  _LOG.info(
2397
2224
  "[mda] sandbox resolve: %s name=%r id=%r scope=%r",
@@ -2418,7 +2245,7 @@ def _create_langsmith_sandbox(
2418
2245
  identity=identity,
2419
2246
  )
2420
2247
 
2421
- return resolved, host_name
2248
+ return resolved, host_name, _sandbox_handle_id(langsmith_sandbox)
2422
2249
 
2423
2250
 
2424
2251
  def _string_option(value: object) -> str | None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: managed-deepagents
3
- Version: 0.9.1.dev1
3
+ Version: 0.9.1.dev2
4
4
  Summary: Managed Deep Agents — the define_deep_agent authoring interface plus the CLI that compiles and deploys a code-first Deep Agent repository to a managed LangGraph runtime.
5
5
  Author: LangChain
6
6
  License: MIT
@@ -25,7 +25,7 @@ managed_deepagents/_managed_tools.py,sha256=a_vtJdrWo0o9UXaKKZzgY1JCl84V0SCRAwhz
25
25
  managed_deepagents/_memory_instructions.py,sha256=s69Shu6vGCXbynozC-SRSJeZrpH5PNowh0sIRKH65XQ,6763
26
26
  managed_deepagents/_run_input.py,sha256=BoEozXHd2fC1lHRu5A548pZn4v9ZGlx7TgPePI5oZjc,4430
27
27
  managed_deepagents/_runtime_schedules.py,sha256=D_HVGD1tpZpi2QSJ9MOnkYY_EzmSUVWAlAwVYRf865U,22495
28
- managed_deepagents/_sandbox_proxy.py,sha256=X2pgx_09YGEOs3qzqtoYT2aVWtpOTVoom_l_PKilnUk,8519
28
+ managed_deepagents/_sandbox_proxy.py,sha256=Uce50nCI7MAO1TqRi9UAJQRBK6XzDU31PlH56s5TYjI,9054
29
29
  managed_deepagents/_schedule_auth.py,sha256=3w22m98Fsru4WC5KJo_Iw8intRGuh8RJskvMz7WloB0,8982
30
30
  managed_deepagents/_schedule_channel.py,sha256=2xOSy2UQcQ6z8r-JrnbOKQg1-daOu4oye7PnaNk0g-4,981
31
31
  managed_deepagents/_schedule_time.py,sha256=uNyULRjoD0HzPVvV-W772HPb3BYCt0fwEbbT9Ec__Jc,3710
@@ -37,10 +37,10 @@ managed_deepagents/define_memory.py,sha256=0DzI9jxr83YJ6mEhqXRbIYzgWpl259-PdAMoA
37
37
  managed_deepagents/namespaces.py,sha256=7jNvJ18p6xL4_FKCqW4QZ4sYVYlMd6Nuw9Zw8H_0Zb4,4896
38
38
  managed_deepagents/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
39
39
  managed_deepagents/run_context.py,sha256=9gzugZ5naNNQCJcXGRY_-7ZXxttY9w3jkxjR94JKgsk,3287
40
- managed_deepagents/runtime.py,sha256=euvDJOtkavX43RVdsBNBeKDz-VgZ7LzSI3aPF4EAigE,95079
40
+ managed_deepagents/runtime.py,sha256=atutnzqXJJPcydb3gaBAl_ZhxDlhQyWEbuCFEoIAi1k,88247
41
41
  managed_deepagents/sandbox.py,sha256=8qaswX6F2LYJX1uGq_7XwAGHZjGOD9VQ0WISqPK_ohs,4734
42
42
  managed_deepagents/schedules.py,sha256=qLXWdtvtv9tKyKhyULZIXUTqC8rZOxm2ZlMM7unjxZ8,5654
43
- managed_deepagents/_binaries/mda.exe,sha256=GfRY9VksVFvg4w8Hk28tjGbkZ7tDX9MIkkBSvvxKc0g,4412928
43
+ managed_deepagents/_binaries/mda.exe,sha256=dD1jwrJRrgXlYOhRbvrGXW0V5aJsXqBIc42ftPeiYiI,4412928
44
44
  managed_deepagents/_channels/__init__.py,sha256=tY94zltWKNw-FIzbGjrh0cSAc2JIHCEAvcY7hzoRED0,801
45
45
  managed_deepagents/_channels/assistant_text.py,sha256=ZLYAF1MQVE5_EN49MoPJdB8Ckf3vNPpXNBhkdA4egF0,3414
46
46
  managed_deepagents/_channels/binding.py,sha256=IAMVozOELxTN1vb36snmFba-EcYKdxH5gHbfLqPkKJo,5144
@@ -101,9 +101,9 @@ managed_deepagents/identity/__init__.py,sha256=YMB5p2DRyyY_82gGNVfGHjfjnUFRTtMne
101
101
  managed_deepagents/identity/claims.py,sha256=prby7r_8Lww3MmoBm8PX6PsSGE3GwSHkr8mVIz_08nU,1180
102
102
  managed_deepagents/identity/options.py,sha256=x_yMbXEFR7zXyehEjDHG2qjAlukXjrRBcQLcM6IndLM,2550
103
103
  managed_deepagents/identity/supabase.py,sha256=8uobl3WCrQL_ieSXG8KTLf1th7Qjim9liZT50HeaJE0,6026
104
- managed_deepagents-0.9.1.dev1.dist-info/licenses/LICENSE,sha256=WnPZQQ608ojZUkXl7BW6VbKloIAibZiGm1K6cjeZOL8,1066
105
- managed_deepagents-0.9.1.dev1.dist-info/METADATA,sha256=kcI-qD9RUjWkPKhelgd3Y_6b0NbK_DiPcD_3Y94iDPM,32563
106
- managed_deepagents-0.9.1.dev1.dist-info/WHEEL,sha256=3I5VVWZdsFlU417aCS2bMRuerS8wsfvBq99MyatBV3A,97
107
- managed_deepagents-0.9.1.dev1.dist-info/entry_points.txt,sha256=ziZqkKuaDO3qHCjKmBhrx9cm3ok8bZ9xcEDpUTj4unM,53
108
- managed_deepagents-0.9.1.dev1.dist-info/top_level.txt,sha256=fdBo4O0Hlol_w022tTLB5ftZpamb4yJoQ3MUvjgTGfA,19
109
- managed_deepagents-0.9.1.dev1.dist-info/RECORD,,
104
+ managed_deepagents-0.9.1.dev2.dist-info/licenses/LICENSE,sha256=WnPZQQ608ojZUkXl7BW6VbKloIAibZiGm1K6cjeZOL8,1066
105
+ managed_deepagents-0.9.1.dev2.dist-info/METADATA,sha256=nzOSdzLnqsDbXB6AXFLVjCZ-Hu3a2LVQzTTeLhcSf24,32563
106
+ managed_deepagents-0.9.1.dev2.dist-info/WHEEL,sha256=3I5VVWZdsFlU417aCS2bMRuerS8wsfvBq99MyatBV3A,97
107
+ managed_deepagents-0.9.1.dev2.dist-info/entry_points.txt,sha256=ziZqkKuaDO3qHCjKmBhrx9cm3ok8bZ9xcEDpUTj4unM,53
108
+ managed_deepagents-0.9.1.dev2.dist-info/top_level.txt,sha256=fdBo4O0Hlol_w022tTLB5ftZpamb4yJoQ3MUvjgTGfA,19
109
+ managed_deepagents-0.9.1.dev2.dist-info/RECORD,,