harness-sdk-python 0.27.0__py3-none-any.whl → 0.28.0__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
@@ -66,6 +66,7 @@ class DeepagentsMessages:
66
66
  )
67
67
  self._checkpointer = checkpointer
68
68
  self._captured: dict[str, Any] | None = None
69
+ self._ephemeral: dict[str, dict[str, Any]] = {}
69
70
 
70
71
  async def boot(
71
72
  self, state: Any, *, index: CheckpointIndex, thread_id: str
@@ -241,6 +242,26 @@ class DeepagentsMessages:
241
242
  )
242
243
  return snapshot
243
244
 
245
+ def upsert_ephemeral_message(self, message: dict[str, Any]) -> None:
246
+ """Render an in-flight ``{id, role, text}`` entry in ``state["messages"]``; an ``append_messages`` of the same id replaces it durably."""
247
+ if message["role"] not in ("user", "assistant"):
248
+ raise ValueError(f"unsupported message role: {message['role']!r}")
249
+ if message["id"] not in self._ephemeral and any(
250
+ m["id"] == message["id"] for m in self._thread.transcript
251
+ ):
252
+ raise ValueError(f"message {message['id']!r} is already durable")
253
+ self._ephemeral[message["id"]] = {
254
+ "id": message["id"],
255
+ "type": "human" if message["role"] == "user" else "ai",
256
+ "content": message["text"],
257
+ }
258
+ self._restamp()
259
+
260
+ def drop_ephemeral_message(self, message_id: str) -> None:
261
+ """Remove an in-flight entry from the ``state["messages"]`` projection."""
262
+ del self._ephemeral[message_id]
263
+ self._restamp()
264
+
244
265
  def _append_user(self, message: dict[str, Any]) -> dict[str, Any]:
245
266
  entry = {"id": message["id"], "type": "human", "content": _user_text(message)}
246
267
  if not any(m["id"] == entry["id"] for m in plain(self._state["messages"])):
@@ -257,4 +278,8 @@ class DeepagentsMessages:
257
278
  for message in self._thread.transcript:
258
279
  branch, siblings = self._thread.sibling_info(message["id"])
259
280
  stamped.append({**message, "branch": {"id": branch, "siblings": siblings}})
281
+ durable = {message["id"] for message in stamped}
282
+ stamped.extend(
283
+ entry for id_, entry in self._ephemeral.items() if id_ not in durable
284
+ )
260
285
  self._replace(stamped)
harness_sdk/voice.py CHANGED
@@ -9,12 +9,15 @@ and the turn commit both stay host-owned.
9
9
 
10
10
  ``voice/start {offer}`` seeds the provider from the thread transcript (at
11
11
  most 128 messages, tail taken) and projects ``state["voice"] = {clientId,
12
- status, answer, turns}`` — the SDP answer rides the applied state. The
13
- session is bound to the issuing client's connection: ``voice/end`` from the
14
- owner, a provider ``closed`` event, or a connection drop ends it. Provider
15
- turn events accumulate in the in-memory turn buffer projected as
16
- ``state["voice"]["turns"]``; at session end the completed turns commit
17
- through ``Host.commit_voice_turns`` and in-progress turns drop.
12
+ status, answer}`` — the SDP answer rides the applied state. The session is
13
+ bound to the issuing client's connection: ``voice/end`` from the owner, a
14
+ provider ``closed`` event, or a connection drop ends it. Provider turn
15
+ events render live in ``state["messages"]`` through
16
+ ``Host.upsert_ephemeral_message`` (message id = turn id); each completed
17
+ turn commits through ``Host.commit_voice_turns`` (serialized, in
18
+ done-order) and the durable entry replaces the ephemeral one under the
19
+ same id, a failed commit keeps its turns for the next flush; session end
20
+ flushes the remaining done turns and drops in-progress turns.
18
21
 
19
22
  Rejections: ``voice-active`` (a session is already live), ``no-voice``
20
23
  (no voice manager declared, or ``voice/end`` with no session),
@@ -58,22 +61,21 @@ def _capped_seed(seed: Any) -> "list[VoiceManager.SeedMessage]":
58
61
 
59
62
 
60
63
  class VoiceManager(Tray):
61
- """One live voice session: the provider handle, the in-memory turn
62
- buffer, and its wire projection; ended sessions commit and self-delete."""
64
+ """One live voice session: the provider handle and the in-memory turn
65
+ buffer rendered live in ``state["messages"]``; completed turns commit
66
+ per turn and ended sessions flush and self-delete."""
63
67
 
64
68
  connection_poll = 0.5
65
69
 
66
70
  clientId = observable(None)
67
71
  status = observable("connecting")
68
72
  answer = observable(None)
69
- turns = observable([])
70
73
 
71
74
  state = observable(
72
75
  {
73
76
  "clientId": clientId,
74
77
  "status": status,
75
78
  "answer": answer,
76
- "turns": turns,
77
79
  }
78
80
  )
79
81
 
@@ -81,6 +83,7 @@ class VoiceManager(Tray):
81
83
  super().__init__(**kwargs)
82
84
  self._provider: "VoiceProvider | None" = None
83
85
  self._turns: list[dict[str, Any]] = []
86
+ self._flushing = asyncio.Lock()
84
87
  self._ended = False
85
88
  self._watcher: "asyncio.Task[Any] | None" = None
86
89
 
@@ -121,7 +124,7 @@ class VoiceManager(Tray):
121
124
  def closed(self, reason: str) -> None: ...
122
125
 
123
126
  class Host(Protocol):
124
- """The host seam: the thread transcript in, committed turns out."""
127
+ """The host seam: the thread transcript in, live and committed turns out."""
125
128
 
126
129
  async def get_voice_seed(self) -> "list[VoiceManager.SeedMessage]":
127
130
  """The transcript as ``{role, text}`` seed messages, tool/system noise skipped."""
@@ -131,6 +134,14 @@ class VoiceManager(Tray):
131
134
  """Write completed ``{id, role, text}`` turns to the thread's durable transcript."""
132
135
  ...
133
136
 
137
+ def upsert_ephemeral_message(self, message: dict[str, Any]) -> None:
138
+ """Render an in-flight ``{id, role, text}`` turn in ``state["messages"]``; same id updates in place."""
139
+ ...
140
+
141
+ def drop_ephemeral_message(self, message_id: str) -> None:
142
+ """Remove an in-flight turn from the ``state["messages"]`` projection."""
143
+ ...
144
+
134
145
  # ─── Session lifecycle ──────────────────────────────────
135
146
 
136
147
  async def _begin(
@@ -180,19 +191,12 @@ class VoiceManager(Tray):
180
191
  await provider.close()
181
192
  except Exception:
182
193
  logger.exception("voice provider close failed for session %r", self.id)
183
- done = [
184
- {"id": t["id"], "role": t["role"], "text": t["text"]}
185
- for t in self._turns
186
- if t["done"]
187
- ]
188
- self._turns = []
189
- self.turns.value = []
194
+ await self._flush()
195
+ turns, self._turns = self._turns, []
196
+ for turn in turns:
197
+ self._host.drop_ephemeral_message(turn["id"])
190
198
  self.status.value = "closed"
191
- try:
192
- if done:
193
- await self.handler.__self__.commit_voice_turns(done)
194
- finally:
195
- self.delete()
199
+ self.delete()
196
200
 
197
201
  # ─── Events sink ────────────────────────────────────────
198
202
 
@@ -202,22 +206,48 @@ class VoiceManager(Tray):
202
206
  return turn
203
207
  raise ValueError(f"turn {turn_id!r} was never started")
204
208
 
205
- def _project_turns(self) -> None:
206
- self.turns.value = [dict(turn) for turn in self._turns]
209
+ @property
210
+ def _host(self) -> Any:
211
+ return self.handler.__self__
212
+
213
+ def _render(self, turn: dict[str, Any]) -> None:
214
+ self._host.upsert_ephemeral_message(
215
+ {"id": turn["id"], "role": turn["role"], "text": turn["text"]}
216
+ )
217
+
218
+ async def _flush(self) -> None:
219
+ # the lock serializes commits in done-order across turn-done and end
220
+ async with self._flushing:
221
+ done = [t for t in self._turns if t["done"]]
222
+ if not done:
223
+ return
224
+ try:
225
+ await self._host.commit_voice_turns(
226
+ [{"id": t["id"], "role": t["role"], "text": t["text"]} for t in done]
227
+ )
228
+ except Exception:
229
+ logger.exception("voice session %r turn commit failed", self.id)
230
+ return
231
+ committed = {t["id"] for t in done}
232
+ self._turns = [t for t in self._turns if t["id"] not in committed]
233
+ for turn_id in committed:
234
+ self._host.drop_ephemeral_message(turn_id)
207
235
 
208
236
  def turn_started(self, turn_id: str, role: str) -> None:
209
237
  if self._ended:
210
238
  return
211
239
  if any(turn["id"] == turn_id for turn in self._turns):
212
240
  raise ValueError(f"turn {turn_id!r} already started")
213
- self._turns.append({"id": turn_id, "role": role, "text": "", "done": False})
214
- self._project_turns()
241
+ turn = {"id": turn_id, "role": role, "text": "", "done": False}
242
+ self._turns.append(turn)
243
+ self._render(turn)
215
244
 
216
245
  def turn_delta(self, turn_id: str, text: str) -> None:
217
246
  if self._ended:
218
247
  return
219
- self._turn(turn_id)["text"] += text
220
- self._project_turns()
248
+ turn = self._turn(turn_id)
249
+ turn["text"] += text
250
+ self._render(turn)
221
251
 
222
252
  def turn_done(self, turn_id: str, text: str) -> None:
223
253
  if self._ended:
@@ -225,7 +255,8 @@ class VoiceManager(Tray):
225
255
  turn = self._turn(turn_id)
226
256
  turn["text"] = text
227
257
  turn["done"] = True
228
- self._project_turns()
258
+ self._render(turn)
259
+ self._spawn(self._flush())
229
260
 
230
261
  def tool_requested(self, request: "VoiceManager.ToolRequest") -> None:
231
262
  logger.info("voice session %r tool request ignored: %r", self.id, request)
@@ -272,7 +303,12 @@ class VoiceManagerNamespace(TrayMapNamespace):
272
303
 
273
304
  def __init__(self, api: Any, spec: TrayDescriptor) -> None:
274
305
  super().__init__(api, spec)
275
- for name in ("get_voice_seed", "commit_voice_turns"):
306
+ for name in (
307
+ "get_voice_seed",
308
+ "commit_voice_turns",
309
+ "upsert_ephemeral_message",
310
+ "drop_ephemeral_message",
311
+ ):
276
312
  if not callable(getattr(api, name, None)):
277
313
  raise TypeError(
278
314
  f"{type(api).__name__} must implement {name} "
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: harness-sdk-python
3
- Version: 0.27.0
3
+ Version: 0.28.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,10 +1,10 @@
1
1
  harness_sdk/__init__.py,sha256=N9gOUKqe0_eM7cIA9sfA_lH1FBw1MN8U-zerwGAPVHE,1094
2
2
  harness_sdk/checkpoints.py,sha256=L02l1IyLDj2b-GD7_HGrck7uenALeI4kg8yJSzoNVmc,25999
3
- harness_sdk/deepagents.py,sha256=d7Vb1MhwU-UKSvsvuAKEEROxXf8mukEzqfEfCIlcxM4,10915
3
+ harness_sdk/deepagents.py,sha256=nnpJ65NeVXcpZNoFOSq6brVYrKdEqSjWgf6wz_WlHiw,12145
4
4
  harness_sdk/fenced_postgres.py,sha256=hbbrMR1WaqrHTNgd4wFrXfRrzQFGnyim-c8nZXgwWp4,13235
5
5
  harness_sdk/linear_thread.py,sha256=laDRXKLFsMlyWS4snqNAM6t38wO26gevLWXRNivhHSM,1810
6
6
  harness_sdk/run_manager.py,sha256=CbY_4dpFeqGx3kJNI1ffsu3uIvzVc-Tc1UB6Nr9SiHY,77654
7
- harness_sdk/voice.py,sha256=LbFO8lpd3jzPuaj2RuxEHckP5TiVjKpQeMsxxaefDPg,14081
8
- harness_sdk_python-0.27.0.dist-info/METADATA,sha256=sA94429xkLoOYG23eysErRAPt00YaQemCcfnIgTPuYM,2200
9
- harness_sdk_python-0.27.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
10
- harness_sdk_python-0.27.0.dist-info/RECORD,,
7
+ harness_sdk/voice.py,sha256=e9aw3hwgOq9l34VSyySxhfK3RY1WErPtZ_kVlBHtuHE,15663
8
+ harness_sdk_python-0.28.0.dist-info/METADATA,sha256=Vut2SI_mn0FFCWh8n_cLh4lJp_ICPIbkUgoxjPEg3pU,2200
9
+ harness_sdk_python-0.28.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
10
+ harness_sdk_python-0.28.0.dist-info/RECORD,,