harness-sdk-python 0.25.2__tar.gz → 0.27.0__tar.gz

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 (42) hide show
  1. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/PKG-INFO +1 -1
  2. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/pyproject.toml +1 -1
  3. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/src/harness_sdk/__init__.py +16 -0
  4. harness_sdk_python-0.27.0/src/harness_sdk/deepagents.py +260 -0
  5. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/src/harness_sdk/run_manager.py +19 -6
  6. harness_sdk_python-0.27.0/src/harness_sdk/voice.py +382 -0
  7. harness_sdk_python-0.27.0/tests/test_deepagents_messages.py +238 -0
  8. harness_sdk_python-0.27.0/tests/test_mint_concurrency.py +59 -0
  9. harness_sdk_python-0.27.0/tests/test_voice.py +192 -0
  10. harness_sdk_python-0.27.0/tests/voice_helpers.py +145 -0
  11. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/.gitignore +0 -0
  12. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/README.md +0 -0
  13. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/examples/__init__.py +0 -0
  14. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/examples/runs_app.py +0 -0
  15. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/src/harness_sdk/checkpoints.py +0 -0
  16. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/src/harness_sdk/fenced_postgres.py +0 -0
  17. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/src/harness_sdk/linear_thread.py +0 -0
  18. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/run_helpers.py +0 -0
  19. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_admit_steer.py +0 -0
  20. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_applied_visibility.py +0 -0
  21. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_batches.py +0 -0
  22. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_branch_anchor.py +0 -0
  23. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_checkpoints.py +0 -0
  24. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_dispatching.py +0 -0
  25. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_durability.py +0 -0
  26. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_edit_dispatched.py +0 -0
  27. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_edit_reload.py +0 -0
  28. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_enqueue.py +0 -0
  29. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_fenced_postgres.py +0 -0
  30. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_input_required.py +0 -0
  31. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_linear_thread.py +0 -0
  32. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_meta.py +0 -0
  33. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_outcomes.py +0 -0
  34. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_placement.py +0 -0
  35. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_prepare_hooks.py +0 -0
  36. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_restore.py +0 -0
  37. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_rewind_during_run.py +0 -0
  38. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_run_crash_sweep.py +0 -0
  39. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_settle.py +0 -0
  40. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_steer.py +0 -0
  41. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_stop_continue.py +0 -0
  42. {harness_sdk_python-0.25.2 → harness_sdk_python-0.27.0}/tests/test_stopping_window.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: harness-sdk-python
3
- Version: 0.25.2
3
+ Version: 0.27.0
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,6 +1,6 @@
1
1
  [project]
2
2
  name = "harness-sdk-python"
3
- version = "0.25.2"
3
+ version = "0.27.0"
4
4
  description = "RunManager: the harness-sdk runs subsystem for Python Statewire hosts"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -11,23 +11,39 @@ from .checkpoints import (
11
11
  langgraph_snapshot,
12
12
  langgraph_switch_values,
13
13
  )
14
+ from .deepagents import DeepagentsMessages
14
15
  from .linear_thread import linear_thread
15
16
  from .run_manager import RunManager, RunManagerDescriptor, run_manager
17
+ from .voice import (
18
+ VoiceManager,
19
+ VoiceManagerDescriptor,
20
+ VoiceProvider,
21
+ end_voice,
22
+ start_voice,
23
+ voice_manager,
24
+ )
16
25
 
17
26
  __all__ = [
18
27
  "CheckpointIndex",
19
28
  "CheckpointStore",
20
29
  "CheckpointThread",
30
+ "DeepagentsMessages",
21
31
  "MemoryCheckpointIndex",
22
32
  "Plan",
23
33
  "PostgresCheckpointIndex",
24
34
  "RunManager",
25
35
  "RunManagerDescriptor",
26
36
  "Snapshot",
37
+ "VoiceManager",
38
+ "VoiceManagerDescriptor",
39
+ "VoiceProvider",
27
40
  "checkpoint_thread",
41
+ "end_voice",
28
42
  "langgraph_checkpoints",
29
43
  "langgraph_snapshot",
30
44
  "langgraph_switch_values",
31
45
  "linear_thread",
32
46
  "run_manager",
47
+ "start_voice",
48
+ "voice_manager",
33
49
  ]
@@ -0,0 +1,260 @@
1
+ """DeepagentsMessages: the ``messages`` slice of a Statewire host, projected
2
+ from a langgraph checkpointer in the deepagents dialect. The checkpointer is
3
+ the source of truth and the wire state is its projection, restamped with
4
+ ``branch: {id, siblings}`` metadata after every ingest. A rewind restores the
5
+ projection from the target message's anchor checkpoint; a branch switch clones
6
+ the target branch's tip as the checkpointer's latest checkpoint, so resumption
7
+ and reboot both land on the switched world.
8
+ """
9
+
10
+ from datetime import datetime, timezone
11
+ from typing import Any
12
+
13
+ from statepatch import plain
14
+
15
+ from .checkpoints import (
16
+ CheckpointIndex,
17
+ CheckpointStore,
18
+ Snapshot,
19
+ _values_snapshot,
20
+ checkpoint_thread,
21
+ langgraph_snapshot,
22
+ )
23
+
24
+
25
+ def _role(message: dict[str, Any]) -> str:
26
+ return "user" if message["type"] == "human" else "assistant"
27
+
28
+
29
+ def _user_text(message: dict[str, Any]) -> str:
30
+ return "\n\n".join(
31
+ part["text"] for part in message["parts"] if part["type"] == "text"
32
+ )
33
+
34
+
35
+ def _checkpointer_store(
36
+ checkpointer: Any, thread_id: str, checkpoint_ns: str
37
+ ) -> CheckpointStore:
38
+ class _Store:
39
+ async def get(self, checkpoint_id: str | None) -> Snapshot | None:
40
+ configurable: dict[str, Any] = {
41
+ "thread_id": thread_id,
42
+ "checkpoint_ns": checkpoint_ns,
43
+ }
44
+ if checkpoint_id is not None:
45
+ configurable["checkpoint_id"] = checkpoint_id
46
+ saved = await checkpointer.aget_tuple({"configurable": configurable})
47
+ if saved is None:
48
+ return None
49
+ return _values_snapshot(
50
+ saved.checkpoint["id"],
51
+ saved.checkpoint["channel_values"],
52
+ "messages",
53
+ "lineage",
54
+ )
55
+
56
+ return _Store()
57
+
58
+
59
+ class DeepagentsMessages:
60
+ """A host's ``state["messages"]`` over a langgraph checkpointer: boot, turn streaming, rewind, and branch switching for the deepagents dialect."""
61
+
62
+ def __init__(self, checkpointer: Any) -> None:
63
+ if not hasattr(checkpointer, "aget_tuple") or not hasattr(checkpointer, "aput"):
64
+ raise TypeError(
65
+ f"checkpointer must be a langgraph checkpoint saver, got {checkpointer!r}"
66
+ )
67
+ self._checkpointer = checkpointer
68
+ self._captured: dict[str, Any] | None = None
69
+
70
+ async def boot(
71
+ self, state: Any, *, index: CheckpointIndex, thread_id: str
72
+ ) -> None:
73
+ """Adopt ``state["messages"]`` and load the thread's history into it with branch stamps."""
74
+ self._state = state
75
+ self._thread_id = thread_id
76
+ self._store = _checkpointer_store(self._checkpointer, thread_id, "")
77
+ self._thread = await checkpoint_thread(
78
+ store=self._store, index=index, thread_id=thread_id, role=_role
79
+ )
80
+ if self._thread.transcript:
81
+ # the graph carries no lineage channel: re-derive the world path from the tail row
82
+ row = await index.get_message(
83
+ thread_id, "", self._thread.transcript[-1]["id"]
84
+ )
85
+ if row is not None and row["branch_id"] != 0:
86
+ await self._thread.switch_state(row["branch_id"])
87
+ self._restamp()
88
+
89
+ async def get_message_meta(self, message_id: str | None) -> dict[str, Any] | None:
90
+ """The thread projection's message meta, for RunManager."""
91
+ return await self._thread.get_message_meta(message_id)
92
+
93
+ async def get_message_child_id(self, parent_id: str) -> str | None:
94
+ """The thread projection's child id, for RunManager."""
95
+ return await self._thread.get_message_child_id(parent_id)
96
+
97
+ def config(self) -> dict[str, Any]:
98
+ """The langgraph config addressing this thread."""
99
+ return {"configurable": {"thread_id": self._thread_id}}
100
+
101
+ async def plan_turn(
102
+ self, ctx: Any
103
+ ) -> tuple[dict[str, Any] | None, dict[str, Any]]:
104
+ """The dispatch's langgraph (payload, config): plans the resumption, restores a rewind's window, appends the batch to the wire state, and confirms it applied."""
105
+ config = self.config()
106
+ if ctx.resume:
107
+ return None, config
108
+ plan = await self._thread.plan_run(ctx)
109
+ if ctx.has_rollback:
110
+ base = (
111
+ (await self._snapshot(plan.checkpoint_id)).messages
112
+ if plan.checkpoint_id is not None
113
+ else []
114
+ )
115
+ self._replace([*base, *plan.replay])
116
+ turn: list[Any] = [*plan.replay]
117
+ for message in ctx.messages:
118
+ turn.append(self._append_user(message))
119
+ ctx.applied()
120
+ if plan.fork:
121
+ if plan.checkpoint_id is not None:
122
+ config["configurable"]["checkpoint_id"] = plan.checkpoint_id
123
+ else:
124
+ from langchain_core.messages import RemoveMessage
125
+ from langgraph.graph.message import REMOVE_ALL_MESSAGES
126
+
127
+ turn = [RemoveMessage(id=REMOVE_ALL_MESSAGES), *turn]
128
+ return ({"messages": turn} if turn else None), config
129
+
130
+ def append_event(self, namespace: tuple, mode: str, event: Any) -> None:
131
+ """Fold one ``astream`` event into the wire state; the root checkpoint stream is captured for the turn's ingest."""
132
+ if mode == "checkpoints":
133
+ if namespace == ():
134
+ self._captured = event
135
+ return
136
+ from statewire.langgraph import append_langgraph_event
137
+
138
+ append_langgraph_event(self._state, namespace, mode, event)
139
+
140
+ async def ingest_turn(self, *, refetch: bool = False) -> None:
141
+ """Ingest the turn's captured checkpoint and restamp; ``refetch`` discards the capture and reads the checkpointer's latest instead."""
142
+ captured, self._captured = self._captured, None
143
+ if refetch or captured is None:
144
+ await self._thread.ingest_latest()
145
+ else:
146
+ await self._thread.ingest(langgraph_snapshot(captured))
147
+ self._restamp()
148
+
149
+ def append_users(self, messages: Any) -> list[dict[str, Any]]:
150
+ """Append harness user messages to the wire state as human entries, deduplicated by id; returns the langgraph turn entries."""
151
+ return [self._append_user(message) for message in messages]
152
+
153
+ async def append_messages(self, messages: list[dict[str, Any]]) -> None:
154
+ """Append ``{id, role, text}`` entries as a new checkpoint on the current tip and restamp; the voice commit path."""
155
+ from langchain_core.messages import AIMessage, HumanMessage
156
+ from langgraph.checkpoint.base import empty_checkpoint
157
+ from langgraph.checkpoint.base.id import uuid6
158
+
159
+ if not messages:
160
+ raise ValueError("messages must be non-empty")
161
+ for message in messages:
162
+ if message["role"] not in ("user", "assistant"):
163
+ raise ValueError(f"unsupported message role: {message['role']!r}")
164
+ entries = [
165
+ (HumanMessage if m["role"] == "user" else AIMessage)(
166
+ id=m["id"], content=m["text"]
167
+ )
168
+ for m in messages
169
+ ]
170
+ parent = {"configurable": {"thread_id": self._thread_id, "checkpoint_ns": ""}}
171
+ saved = await self._checkpointer.aget_tuple(parent)
172
+ if saved is None:
173
+ checkpoint = empty_checkpoint()
174
+ step = -1
175
+ else:
176
+ checkpoint = {**saved.checkpoint}
177
+ step = (saved.metadata or {}).get("step", -1)
178
+ parent["configurable"]["checkpoint_id"] = saved.checkpoint["id"]
179
+ version = self._checkpointer.get_next_version(
180
+ checkpoint["channel_versions"].get("messages"), None
181
+ )
182
+ checkpoint = {
183
+ **checkpoint,
184
+ "id": str(uuid6(clock_seq=-2)),
185
+ "ts": datetime.now(timezone.utc).isoformat(),
186
+ "channel_values": {
187
+ **checkpoint["channel_values"],
188
+ "messages": [
189
+ *checkpoint["channel_values"].get("messages", []),
190
+ *entries,
191
+ ],
192
+ },
193
+ "channel_versions": {
194
+ **checkpoint["channel_versions"],
195
+ "messages": version,
196
+ },
197
+ }
198
+ metadata = {"source": "update", "step": step + 1, "parents": {}}
199
+ await self._checkpointer.aput(parent, checkpoint, metadata, {"messages": version})
200
+ await self._thread.ingest_latest()
201
+ self._restamp()
202
+
203
+ async def switch_branch(self, branch_id: int) -> None:
204
+ """Switch to ``branch_id``: its tip becomes the checkpointer's latest checkpoint and the wire state rebaselines."""
205
+ transcript, lineage = await self._thread.switch_state(branch_id)
206
+ checkpoint_id = await self._clone_tip(self._thread.checkpoint_id)
207
+ await self._thread.ingest(Snapshot(checkpoint_id, transcript, lineage))
208
+ self._restamp()
209
+
210
+ async def _clone_tip(self, checkpoint_id: str) -> str:
211
+ from langgraph.checkpoint.base.id import uuid6
212
+
213
+ parent = {
214
+ "configurable": {
215
+ "thread_id": self._thread_id,
216
+ "checkpoint_ns": "",
217
+ "checkpoint_id": checkpoint_id,
218
+ }
219
+ }
220
+ saved = await self._checkpointer.aget_tuple(parent)
221
+ if saved is None:
222
+ raise LookupError(f"checkpoint {checkpoint_id!r} is not in the checkpointer")
223
+ clone = {
224
+ **saved.checkpoint,
225
+ "id": str(uuid6(clock_seq=-2)),
226
+ "ts": datetime.now(timezone.utc).isoformat(),
227
+ }
228
+ metadata = {
229
+ "source": "update",
230
+ "step": (saved.metadata or {}).get("step", -1) + 1,
231
+ "parents": {},
232
+ }
233
+ written = await self._checkpointer.aput(parent, clone, metadata, {})
234
+ return written["configurable"]["checkpoint_id"]
235
+
236
+ async def _snapshot(self, checkpoint_id: str) -> Snapshot:
237
+ snapshot = await self._store.get(checkpoint_id)
238
+ if snapshot is None:
239
+ raise LookupError(
240
+ f"checkpoint {checkpoint_id!r} is not in the checkpointer"
241
+ )
242
+ return snapshot
243
+
244
+ def _append_user(self, message: dict[str, Any]) -> dict[str, Any]:
245
+ entry = {"id": message["id"], "type": "human", "content": _user_text(message)}
246
+ if not any(m["id"] == entry["id"] for m in plain(self._state["messages"])):
247
+ self._state["messages"].append(entry)
248
+ return entry
249
+
250
+ def _replace(self, messages: list[dict[str, Any]]) -> None:
251
+ from statewire.langgraph import replace_messages
252
+
253
+ replace_messages(self._state, messages)
254
+
255
+ def _restamp(self) -> None:
256
+ stamped = []
257
+ for message in self._thread.transcript:
258
+ branch, siblings = self._thread.sibling_info(message["id"])
259
+ stamped.append({**message, "branch": {"id": branch, "siblings": siblings}})
260
+ self._replace(stamped)
@@ -48,6 +48,7 @@ window.
48
48
  """
49
49
 
50
50
  import asyncio
51
+ import contextlib
51
52
  import logging
52
53
  from dataclasses import dataclass, field
53
54
  from typing import Any, AsyncIterator, Callable, Coroutine, Iterable, Protocol
@@ -1610,7 +1611,7 @@ class RunManagerNamespace(TrayMapNamespace):
1610
1611
  f"{type(api).__name__} must implement get_message_meta "
1611
1612
  "(RunManager.Thread) to host @run_manager"
1612
1613
  )
1613
- self._mint_lock = asyncio.Lock()
1614
+ self._mint: "asyncio.Task[Any] | None" = None
1614
1615
  self._mounted: list[RunManager] = []
1615
1616
  api.state["runs"] = []
1616
1617
  api.state["status"] = "ready"
@@ -1628,14 +1629,26 @@ class RunManagerNamespace(TrayMapNamespace):
1628
1629
  return tray
1629
1630
 
1630
1631
  async def _machine(self, run_id: str) -> tuple[RunManager, bool]:
1631
- tray = self.live()
1632
- if tray is not None:
1633
- return tray, False
1634
- async with self._mint_lock:
1632
+ # No await between the live() check and the mint's publication, and no
1633
+ # lock held across storage I/O: same-tick callers await the shared mint
1634
+ # task and merge into the machine it mounts; the creator raises its
1635
+ # mint's failure while followers re-mint and progress.
1636
+ while True:
1635
1637
  tray = self.live()
1636
1638
  if tray is not None:
1637
1639
  return tray, False
1638
- return await self.get_or_create(run_id), True # type: ignore[return-value]
1640
+ pending = self._mint
1641
+ if pending is None:
1642
+ pending = self._api.create_task(self.get_or_create(run_id))
1643
+ self._mint = pending
1644
+ pending.add_done_callback(self._mint_settled)
1645
+ return await pending, True
1646
+ with contextlib.suppress(Exception):
1647
+ await pending
1648
+
1649
+ def _mint_settled(self, task: "asyncio.Task[Any]") -> None:
1650
+ if self._mint is task:
1651
+ self._mint = None
1639
1652
 
1640
1653
  # ─── Mounted view ───────────────────────────────────────
1641
1654