harness-sdk-python 0.36.4__py3-none-any.whl → 0.36.6__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.
harness_sdk/deepagents.py CHANGED
@@ -148,6 +148,8 @@ class DeepagentsMessages:
148
148
  self._captured: dict[str, Any] | None = None
149
149
  self._admission: Any | None = None
150
150
  self._input_checkpoint_seen = False
151
+ self._handle: Any = None
152
+ self._output_seen = False
151
153
  self._ephemeral: dict[str, dict[str, Any]] = {}
152
154
  self._write_lock = asyncio.Lock()
153
155
 
@@ -208,6 +210,8 @@ class DeepagentsMessages:
208
210
  for message in ctx.messages:
209
211
  turn.append(self._append_user(message))
210
212
  self.admit(ctx.applied())
213
+ if plan.fork or ctx.input_outcomes:
214
+ self._handle = None
211
215
  if plan.fork:
212
216
  if plan.checkpoint_id is not None:
213
217
  config["configurable"]["checkpoint_id"] = plan.checkpoint_id
@@ -223,6 +227,34 @@ class DeepagentsMessages:
223
227
  if self._admission is not None:
224
228
  raise RuntimeError("previous input admission is still pending")
225
229
  self._admission = admission
230
+ self._handle = admission
231
+ self._output_seen = False
232
+
233
+ @property
234
+ def retractable(self) -> bool:
235
+ """Whether the current turn can still be retracted: a tip dispatch's admitted batch before any graph output."""
236
+ return self._handle is not None and not self._output_seen
237
+
238
+ async def retract_turn(self) -> None:
239
+ """Retract the current turn: ``undo().dur()`` its batch, drop it from the wire, and fork the checkpointer tip back to the pre-turn checkpoint."""
240
+ if not self.retractable:
241
+ raise RuntimeError("the turn is not retractable")
242
+ handle = self._handle
243
+ self.abandon_turn()
244
+ handle.undo().dur()
245
+ self._restamp()
246
+ async with self._write_lock:
247
+ latest = await self._store.get(None)
248
+ if (
249
+ latest is not None
250
+ and latest.checkpoint_id != self._thread.checkpoint_id
251
+ ):
252
+ checkpoint_id = await self._clone_tip(self._thread.checkpoint_id)
253
+ await self._thread.ingest(
254
+ Snapshot(
255
+ checkpoint_id, self._thread.transcript, self._thread.lineage
256
+ )
257
+ )
226
258
 
227
259
  def checkpoint_saved(self, config: Any, checkpoint: Any, metadata: Any) -> None:
228
260
  """Confirm this turn's input from a FrontierCheckpointer checkpoint callback."""
@@ -246,7 +278,10 @@ class DeepagentsMessages:
246
278
  self._captured = event
247
279
  if event["metadata"]["source"] in ("input", "loop"):
248
280
  self._input_checkpoint_seen = True
281
+ if event["metadata"]["source"] == "loop":
282
+ self._output_seen = True
249
283
  return
284
+ self._output_seen = True
250
285
  from statewire.langgraph import append_langgraph_event
251
286
 
252
287
  append_langgraph_event(self._state, namespace, mode, event)
@@ -263,6 +298,7 @@ class DeepagentsMessages:
263
298
  """Discard a stream capture and any fork planned for the abandoned turn."""
264
299
  self._captured = None
265
300
  self._admission = None
301
+ self._handle = None
266
302
  self._input_checkpoint_seen = False
267
303
  self._thread.abandon_plan()
268
304
 
@@ -329,21 +365,20 @@ class DeepagentsMessages:
329
365
  await self._thread.ingest(Snapshot(checkpoint_id, transcript, lineage))
330
366
  self._restamp()
331
367
 
332
- async def _clone_tip(self, checkpoint_id: str) -> str:
368
+ async def _clone_tip(self, checkpoint_id: str | None) -> str:
369
+ from langgraph.checkpoint.base import empty_checkpoint
333
370
  from langgraph.checkpoint.base.id import uuid6
334
371
 
335
- parent = {
336
- "configurable": {
337
- "thread_id": self._thread_id,
338
- "checkpoint_ns": "",
339
- "checkpoint_id": checkpoint_id,
340
- }
341
- }
342
- saved = await self._checkpointer.aget_tuple(parent)
343
- if saved is None:
344
- raise LookupError(f"checkpoint {checkpoint_id!r} is not in the checkpointer")
372
+ parent = {"configurable": {"thread_id": self._thread_id, "checkpoint_ns": ""}}
373
+ if checkpoint_id is None:
374
+ saved = None
375
+ else:
376
+ parent["configurable"]["checkpoint_id"] = checkpoint_id
377
+ saved = await self._checkpointer.aget_tuple(parent)
378
+ if saved is None:
379
+ raise LookupError(f"checkpoint {checkpoint_id!r} is not in the checkpointer")
345
380
  clone = {
346
- **saved.checkpoint,
381
+ **(empty_checkpoint() if saved is None else saved.checkpoint),
347
382
  "id": str(uuid6(clock_seq=-2)),
348
383
  "ts": datetime.now(timezone.utc).isoformat(),
349
384
  }
@@ -36,7 +36,12 @@ durably confirmed redelivers in resume mode instead (``ctx.resume``): the
36
36
  input batch must not be re-dispatched (``messages`` and the rollback surface
37
37
  raise; meta and input outcomes stay readable) and the run continues from its
38
38
  own continuation state (``ctx.state`` or an external checkpointer).
39
- ``Complete`` with an unconfirmed batch settles as an error.
39
+ ``Complete`` with an unconfirmed batch settles as an error. ``undo()`` on an
40
+ admission handle retracts its batch and every later one (newest first);
41
+ ``dur()`` then publishes the retraction. Retracted items re-present as
42
+ ``dispatching`` and return to their lane fronts at settle, the ``run/stop``
43
+ verdict carries them, and the run must end ``Stop``/``Error`` with
44
+ ``dispatch_queue=False``.
40
45
 
41
46
  ``epoch`` counts the entry's dispatches (not redeliveries); a ``run/stop``
42
47
  carrying an ``epoch`` other than the live one rejects. A mid-run stop or
@@ -399,6 +404,7 @@ class RunManager(Tray):
399
404
  self._batch: list[tuple[str, dict[str, Any]]] = []
400
405
  self._pending_takes = 0
401
406
  self._admissions: list[RunManager.Admission] = []
407
+ self._retracted: list[dict[str, Any]] = []
402
408
  self._input_requests: list[dict[str, Any]] = []
403
409
  self._input_answers: dict[str, Any] = {}
404
410
  self._run_live: "RunManager.RunContext | None" = None
@@ -455,6 +461,12 @@ class RunManager(Tray):
455
461
  self._replay_settle()
456
462
  self._outcome = settled
457
463
  recorded = self.outbox.value
464
+ if recorded is not None and not recorded["item"].get("durableAdmission", False):
465
+ self.steerQueue.untake(self.confirmedTakes.value)
466
+ self.confirmedTakes.value = 0
467
+ self.batchApplied.value = False
468
+ recorded = {**recorded, "item": {**recorded["item"], "durableAdmission": True}}
469
+ self.outbox.value = recorded
458
470
  if recorded is not None and not self.batchApplied.value:
459
471
  record = recorded["item"]["record"]
460
472
  lanes = recorded["item"]["lanes"]
@@ -611,9 +623,10 @@ class RunManager(Tray):
611
623
 
612
624
  def _resolve_stop_waiters(self) -> None:
613
625
  waiters, self._stop_waiters = self._stop_waiters, []
626
+ retracted, self._retracted = self._retracted, []
614
627
  for future in waiters:
615
628
  if not future.done():
616
- future.set_result(None)
629
+ future.set_result(retracted)
617
630
 
618
631
  def _settle_applied(self, fx: _Effects) -> None:
619
632
  for future, applied, result in fx.staged_sends:
@@ -681,7 +694,7 @@ class RunManager(Tray):
681
694
  self._stop_staged = True
682
695
  self._stop_waiters.append(entry.future) # the verdict waits for the settle
683
696
  elif not entry.future.done():
684
- entry.future.set_result(None)
697
+ entry.future.set_result([])
685
698
  return
686
699
  if isinstance(entry, _Continue):
687
700
  if not fx.continue_requested:
@@ -801,7 +814,11 @@ class RunManager(Tray):
801
814
  root_meta=root_meta,
802
815
  input_outcomes=input_outcomes,
803
816
  )
804
- item = {"record": record, "lanes": [lane for lane, _ in self._batch]}
817
+ item = {
818
+ "record": record,
819
+ "lanes": [lane for lane, _ in self._batch],
820
+ "durableAdmission": True,
821
+ }
805
822
  self.kick()
806
823
  self.stopReason.value = None
807
824
  self.epoch.value = self.epoch.value + 1
@@ -918,9 +935,17 @@ class RunManager(Tray):
918
935
  f"{type(outcome).__name__}"
919
936
  )
920
937
  if isinstance(outcome, RunManager.Complete) and (
921
- self.dispatching.value is not None or self._admissions
938
+ self.dispatching.value is not None or self._unconsumed()
922
939
  ):
923
940
  raise RuntimeError("run returned Complete with an unconfirmed batch")
941
+ if (
942
+ isinstance(outcome, (RunManager.Stop, RunManager.Error))
943
+ and outcome.dispatch_queue
944
+ and self._undone()
945
+ ):
946
+ raise RuntimeError(
947
+ "dispatch_queue=True would redispatch an undone batch"
948
+ )
924
949
  except EvictionRequested:
925
950
  self._advance()
926
951
  if self._stop_staged or ctx._tray_ctx.consumed:
@@ -1033,12 +1058,19 @@ class RunManager(Tray):
1033
1058
  def _settle(self, ctx: "RunManager.RunContext") -> None:
1034
1059
  if self._run_live is ctx:
1035
1060
  self._run_live = None
1036
- takes = self._pending_takes + sum(a._takes for a in self._admissions)
1061
+ unconsumed = self._unconsumed()
1062
+ self._retracted = [
1063
+ _public(message)
1064
+ for admission in self._admissions
1065
+ if admission._undone
1066
+ for _, message in admission._batch
1067
+ ]
1068
+ takes = self._pending_takes + sum(a._takes for a in unconsumed)
1037
1069
  if takes:
1038
1070
  self.steerQueue.untake(takes)
1039
1071
  self._drop_dispatched(
1040
1072
  message["id"]
1041
- for admission in self._admissions
1073
+ for admission in unconsumed
1042
1074
  if admission._takes
1043
1075
  for _, message in admission._batch
1044
1076
  )
@@ -1046,6 +1078,8 @@ class RunManager(Tray):
1046
1078
  self._drop_dispatched(message["id"] for _, message in self._batch)
1047
1079
  self._batch = []
1048
1080
  self._pending_takes = 0
1081
+ if any(not a._takes for a in unconsumed):
1082
+ self.batchApplied.value = False # an undone dispatch settles unapplied
1049
1083
  self._admissions.clear()
1050
1084
  recorded = self.outbox.value
1051
1085
  if recorded is not None and not self.batchApplied.value:
@@ -1095,7 +1129,15 @@ class RunManager(Tray):
1095
1129
  self.dispatching.value = None
1096
1130
  self._finish_settle()
1097
1131
 
1132
+ def _unconsumed(self) -> list["RunManager.Admission"]:
1133
+ return [a for a in self._admissions if not a._published or a._undone]
1134
+
1135
+ def _undone(self) -> bool:
1136
+ return any(a._undone for a in self._admissions)
1137
+
1098
1138
  def _applied(self, ctx: "RunManager.RunContext") -> "RunManager.Admission":
1139
+ if self._undone():
1140
+ raise RuntimeError("applied() after undo()")
1099
1141
  if self.dispatching.value is None:
1100
1142
  raise RuntimeError("applied() with no unapplied batch")
1101
1143
  admission = RunManager.Admission(ctx, list(self._batch), self._pending_takes)
@@ -1413,7 +1455,8 @@ class RunManager(Tray):
1413
1455
  lane = self._lane_of(e.message_id)
1414
1456
  if lane is None:
1415
1457
  raise _reject("unknown-id", f"message {e.message_id} is not queued")
1416
- self._check_author(e.message_id, e.principal)
1458
+ if e.principal != self.principal.value or self.principal.value is None:
1459
+ self._check_author(e.message_id, e.principal)
1417
1460
  self._lane(lane).value = [
1418
1461
  item for item in self._lane_items(lane) if item["id"] != e.message_id
1419
1462
  ]
@@ -1603,6 +1646,8 @@ class RunManager(Tray):
1603
1646
  """Drain the steer lane into a fresh dispatch record (deferred durable pops); requires the current batch to be applied."""
1604
1647
  self._ctx._ensure_active()
1605
1648
  manager = self._ctx._manager
1649
+ if manager._undone():
1650
+ raise RuntimeError("take() after undo()")
1606
1651
  if manager.dispatching.value is not None:
1607
1652
  raise RuntimeError("take before the current batch is applied")
1608
1653
  items = manager.steerQueue.take_now()
@@ -1628,26 +1673,72 @@ class RunManager(Tray):
1628
1673
 
1629
1674
  @dataclass(eq=False)
1630
1675
  class Admission:
1631
- """One visibly applied batch; ``dur()`` orders its consumption behind enlisted checkpoint writes."""
1676
+ """One visibly applied batch; ``dur()`` publishes its intent (consumed, or unconsumed after ``undo()``) behind enlisted checkpoint writes."""
1632
1677
 
1633
1678
  _ctx: "RunManager.RunContext"
1634
1679
  _batch: list[tuple[str, dict[str, Any]]]
1635
1680
  _takes: int
1636
1681
  _confirmed: bool = False
1682
+ _published: bool = False
1683
+ _undone: bool = False
1637
1684
 
1638
1685
  def dur(self) -> None:
1639
- """Enlist this batch's durable consumption; idempotent until the dispatch settles."""
1686
+ """Publish the current intent durably; idempotent until the dispatch settles."""
1640
1687
  self._ctx._ensure_active()
1641
- if self._confirmed:
1688
+ manager = self._ctx._manager
1689
+ if self._undone:
1690
+ for admission in reversed(manager._admissions):
1691
+ if admission._undone and admission._published:
1692
+ admission._publish(False)
1642
1693
  return
1643
1694
  self._confirmed = True
1695
+ for admission in manager._admissions:
1696
+ if admission._published:
1697
+ continue
1698
+ if not admission._confirmed or admission._undone:
1699
+ break
1700
+ admission._publish(True)
1701
+
1702
+ def undo(self) -> "RunManager.Admission":
1703
+ """Retract this batch and every later one, newest first; ``dur()`` then publishes the retraction. The record re-presents as ``dispatching`` until settle."""
1704
+ self._ctx._ensure_active()
1644
1705
  manager = self._ctx._manager
1645
- while manager._admissions and manager._admissions[0]._confirmed:
1646
- admission = manager._admissions.pop(0)
1647
- if admission._takes:
1648
- manager.confirmedTakes.value += admission._takes
1649
- else:
1650
- manager.batchApplied.value = True
1706
+ if not self._takes:
1707
+ record = manager.outbox.value["item"]["record"]
1708
+ if "rollbackTo" in record or "inputOutcomes" in record:
1709
+ raise RuntimeError(
1710
+ "undo() of a rewind or input-carrying dispatch is not supported"
1711
+ )
1712
+ for admission in reversed(manager._admissions):
1713
+ admission._undone = True
1714
+ if admission is self:
1715
+ break
1716
+ first = next(a for a in manager._admissions if a._undone)
1717
+ retracted = [
1718
+ item
1719
+ for admission in manager._admissions
1720
+ if admission._undone
1721
+ for _, item in admission._batch
1722
+ ] + [item for _, item in manager._batch]
1723
+ trigger = (
1724
+ "steer"
1725
+ if first._takes
1726
+ else manager.outbox.value["item"]["record"]["trigger"]
1727
+ )
1728
+ manager.dispatching.value = _public_record(
1729
+ manager._record_of(trigger, retracted)
1730
+ )
1731
+ return self
1732
+
1733
+ def _publish(self, consumed: bool) -> None:
1734
+ manager = self._ctx._manager
1735
+ self._published = consumed
1736
+ if self._takes:
1737
+ manager.confirmedTakes.value += (
1738
+ self._takes if consumed else -self._takes
1739
+ )
1740
+ else:
1741
+ manager.batchApplied.value = consumed
1651
1742
 
1652
1743
  @dataclass(frozen=True, eq=False)
1653
1744
  class RunContext:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: harness-sdk-python
3
- Version: 0.36.4
3
+ Version: 0.36.6
4
4
  Summary: RunManager: the harness-sdk runs subsystem for Python Statewire hosts
5
5
  Project-URL: Repository, https://github.com/assistant-ui/harness-sdk
6
6
  License-Expression: MIT
@@ -1,12 +1,12 @@
1
1
  harness_sdk/__init__.py,sha256=zoABjY3ixYzh5YyWtHQKs3MjphMJrwklzV0LOacDA5c,1740
2
2
  harness_sdk/checkpoints.py,sha256=4Jv0eyjGoUv9lC6ZZSOpHmZ4j_vMFkFPSxFcrpJ-NTQ,28195
3
- harness_sdk/deepagents.py,sha256=ilrz32oEhvoiKkKGPGbmsTmjZvWomhg1roxPMMxSCXk,15745
3
+ harness_sdk/deepagents.py,sha256=60awGXccJFtVHZyAt3SXLjs6BOt_Y4gszgy2fxVMzaU,17410
4
4
  harness_sdk/fenced_postgres.py,sha256=hbbrMR1WaqrHTNgd4wFrXfRrzQFGnyim-c8nZXgwWp4,13235
5
5
  harness_sdk/langgraph.py,sha256=0yT3l7wWrxjG4SOMQQAjre-EK2JBndryAmBg-k8NESg,2680
6
6
  harness_sdk/linear_thread.py,sha256=laDRXKLFsMlyWS4snqNAM6t38wO26gevLWXRNivhHSM,1810
7
7
  harness_sdk/protocol.py,sha256=4diqaWeYIVEKRjyKkqzeMMHJb7zrOQCvPkjQzkeIku8,140
8
- harness_sdk/run_manager.py,sha256=wKhMHscBUtAT4qddHC6_mftGO3u9T3HivlUgwfmJCAk,88062
8
+ harness_sdk/run_manager.py,sha256=O-6cAaRxJhx8vZPHTf_Xe9oCxcJzMjmlfF5ANXdu9e0,92085
9
9
  harness_sdk/voice.py,sha256=bRloaKSS1d0mFvfIM4Bhp50ADBK_7GpdarGvmDBubjg,32370
10
- harness_sdk_python-0.36.4.dist-info/METADATA,sha256=s8ACi-pVJMePCNS9BK75tFL7umZJxu0YYo7B7sI3sCA,2488
11
- harness_sdk_python-0.36.4.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
12
- harness_sdk_python-0.36.4.dist-info/RECORD,,
10
+ harness_sdk_python-0.36.6.dist-info/METADATA,sha256=6LJ8oq1t-ltAyG-9piyhLxzDaZViCGFq99ckAOls3kM,2488
11
+ harness_sdk_python-0.36.6.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
12
+ harness_sdk_python-0.36.6.dist-info/RECORD,,