harness-sdk-python 0.29.2__py3-none-any.whl → 0.30.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/__init__.py CHANGED
@@ -20,6 +20,7 @@ from .voice import (
20
20
  VoiceProvider,
21
21
  end_voice,
22
22
  start_voice,
23
+ temp_frontend_tool_result,
23
24
  voice_manager,
24
25
  )
25
26
 
@@ -45,5 +46,6 @@ __all__ = [
45
46
  "linear_thread",
46
47
  "run_manager",
47
48
  "start_voice",
49
+ "temp_frontend_tool_result",
48
50
  "voice_manager",
49
51
  ]
harness_sdk/voice.py CHANGED
@@ -7,10 +7,15 @@ lives in its own ephemeral tray, minted by ``voice/start`` and deleted when
7
7
  the session ends. The host implements ``VoiceManager.Host``: the seed read
8
8
  and the turn commit both stay host-owned.
9
9
 
10
- ``voice/start {offer}`` seeds the provider from the thread transcript (at
11
- most 128 messages, tail taken) and projects ``state["voice"] = {clientId,
12
- status}`` — the SDP answer rides only the command's result payload
13
- ``{answer}``. The session is bound to the issuing client's connection: ``voice/end`` from the owner, a
10
+ ``voice/start {offer, tools?}`` seeds the provider from the thread
11
+ transcript (at most 128 messages, tail taken), hands the client's frontend
12
+ function tool definitions to the provider, and projects ``state["voice"] =
13
+ {clientId, status, toolCalls}`` — the SDP answer rides only the command's
14
+ result payload ``{answer}``. A named call matching a client-declared tool
15
+ projects into ``toolCalls`` as ``{callId, name, arguments}``; the owning
16
+ client answers it with ``voice/temp-frontend-tool-result {call_id,
17
+ output}``, which forwards through ``provider.return_tool_result`` and
18
+ clears the entry. The session is bound to the issuing client's connection: ``voice/end`` from the owner, a
14
19
  provider ``closed`` event, or a connection drop ends it. Provider turn
15
20
  events render live in ``state["messages"]`` through
16
21
  ``Host.upsert_ephemeral_message`` (message id = turn id), tagged
@@ -21,6 +26,15 @@ same id, a failed commit keeps its turns for the next flush; session end
21
26
  flushes the remaining done turns, then commits in-progress turns with
22
27
  their partial text; in-progress turns with no text yet are dropped.
23
28
 
29
+ Delegated work: provider ``task_requested`` (free-text unit) and
30
+ ``tool_requested`` (named call) events route to ``Host.handle_voice_task``,
31
+ deduped by id. Tasks run one at a time and each carries an incremental
32
+ transcript handoff — the first task the conversation so far, follow-ups the
33
+ turns since the previous task. Interim ``speak`` text and the returned
34
+ result flow back as speakable context appends; a named call's result
35
+ returns via ``provider.return_tool_result``; a failed handler surfaces to
36
+ the model as commentary (task) or an error output (call).
37
+
24
38
  Rejections: ``voice-active`` (a session is already live), ``no-voice``
25
39
  (no voice manager declared, or ``voice/end`` with no session),
26
40
  ``not-voice-owner`` (``voice/end`` from another client),
@@ -30,9 +44,10 @@ Rejections: ``voice-active`` (a session is already live), ``no-voice``
30
44
  import asyncio
31
45
  import functools
32
46
  import inspect
47
+ import json
33
48
  import logging
34
49
  from dataclasses import dataclass
35
- from typing import Any, Callable, Literal, Protocol, TypedDict
50
+ from typing import Any, Awaitable, Callable, Literal, Protocol, TypedDict
36
51
  from uuid import uuid4
37
52
 
38
53
  from pinned.trays import Tray, TrayDescriptor, TrayMapNamespace
@@ -49,6 +64,30 @@ def _reject(reason: str, message: str) -> StatewireReject:
49
64
  return StatewireReject(message, payload={"reason": reason})
50
65
 
51
66
 
67
+ def _validated_tools(tools: Any) -> "list[VoiceManager.ToolDef]":
68
+ if tools is None:
69
+ return []
70
+ if not isinstance(tools, list):
71
+ raise _reject("invalid-message", "tools must be a list")
72
+ names: set[str] = set()
73
+ for tool in tools:
74
+ if (
75
+ not isinstance(tool, dict)
76
+ or not isinstance(tool.get("name"), str)
77
+ or tool["name"] == ""
78
+ or not isinstance(tool.get("description"), str)
79
+ or not isinstance(tool.get("parameters"), dict)
80
+ ):
81
+ raise _reject(
82
+ "invalid-message",
83
+ f"tools entries must be {{name, description, parameters}}, got {tool!r}",
84
+ )
85
+ if tool["name"] in names:
86
+ raise _reject("invalid-message", f"duplicate tool name {tool['name']!r}")
87
+ names.add(tool["name"])
88
+ return tools
89
+
90
+
52
91
  def _capped_seed(seed: Any) -> "list[VoiceManager.SeedMessage]":
53
92
  if not isinstance(seed, list):
54
93
  raise TypeError(f"get_voice_seed must return a list, got {seed!r}")
@@ -71,11 +110,13 @@ class VoiceManager(Tray):
71
110
 
72
111
  clientId = observable(None)
73
112
  status = observable("connecting")
113
+ toolCalls = observable([])
74
114
 
75
115
  state = observable(
76
116
  {
77
117
  "clientId": clientId,
78
118
  "status": status,
119
+ "toolCalls": toolCalls,
79
120
  }
80
121
  )
81
122
 
@@ -86,6 +127,11 @@ class VoiceManager(Tray):
86
127
  self._flushing = asyncio.Lock()
87
128
  self._ended = False
88
129
  self._watcher: "asyncio.Task[Any] | None" = None
130
+ self._handoff_pending: list[dict[str, str]] = []
131
+ self._seen_requests: set[str] = set()
132
+ self._delegating = asyncio.Lock()
133
+ self._tasks_run = 0
134
+ self._client_tools: set[str] = set()
89
135
 
90
136
  def items(self):
91
137
  yield from ()
@@ -96,12 +142,41 @@ class VoiceManager(Tray):
96
142
  role: Literal["user", "assistant", "system"]
97
143
  text: str
98
144
 
145
+ class ToolDef(TypedDict):
146
+ """One frontend function tool the client declares at ``voice/start``."""
147
+
148
+ name: str
149
+ description: str
150
+ parameters: dict[str, Any]
151
+
99
152
  @dataclass(frozen=True)
100
153
  class ToolRequest:
101
154
  call_id: str
102
155
  name: str
103
156
  arguments: str
104
157
 
158
+ @dataclass(frozen=True)
159
+ class TaskRequest:
160
+ """One delegated free-text work unit plus its transcript delta."""
161
+
162
+ task_id: str
163
+ text: str
164
+ transcript: str
165
+ follow_up: bool
166
+
167
+ def handoff(self) -> str:
168
+ """Render the task and its transcript delta as one delegate-facing prompt."""
169
+ window = (
170
+ "the voice conversation since the previous delegated task"
171
+ if self.follow_up
172
+ else "the voice conversation so far"
173
+ )
174
+ transcript = self.transcript or "(No new conversation was captured.)"
175
+ return (
176
+ f"This is the transcript of {window}:\n\n{transcript}\n\n"
177
+ f"The voice model delegated this task:\n{self.text}"
178
+ )
179
+
105
180
  @dataclass(frozen=True)
106
181
  class SessionContext:
107
182
  """The provider factory's per-session context."""
@@ -119,6 +194,8 @@ class VoiceManager(Tray):
119
194
 
120
195
  def tool_requested(self, request: "VoiceManager.ToolRequest") -> None: ...
121
196
 
197
+ def task_requested(self, task_id: str, text: str) -> None: ...
198
+
122
199
  def rollover_approaching(self, rollover_id: str, deadline: float) -> None: ...
123
200
 
124
201
  def closed(self, reason: str) -> None: ...
@@ -142,18 +219,29 @@ class VoiceManager(Tray):
142
219
  """Remove an in-flight turn from the ``state["messages"]`` projection."""
143
220
  ...
144
221
 
222
+ async def handle_voice_task(
223
+ self,
224
+ task: "VoiceManager.TaskRequest | VoiceManager.ToolRequest",
225
+ *,
226
+ speak: Callable[[str], Awaitable[None]],
227
+ ) -> str:
228
+ """Fulfill one delegated work unit; ``speak`` streams interim spoken updates and the return value is the result."""
229
+ ...
230
+
145
231
  # ─── Session lifecycle ──────────────────────────────────
146
232
 
147
233
  async def _begin(
148
- self, offer: str, seed: "list[VoiceManager.SeedMessage]", caller: Any,
234
+ self, offer: str, seed: "list[VoiceManager.SeedMessage]",
235
+ tools: "list[VoiceManager.ToolDef]", caller: Any,
149
236
  applied: Callable[[], None],
150
237
  ) -> Any:
151
238
  self.clientId.value = caller.client_id
239
+ self._client_tools = {tool["name"] for tool in tools}
152
240
  try:
153
241
  provider = await self.handler(
154
242
  VoiceManager.SessionContext(client_id=caller.client_id)
155
243
  )
156
- answer = await provider.start(offer, seed=seed, events=self)
244
+ answer = await provider.start(offer, seed=seed, tools=tools, events=self)
157
245
  if not isinstance(answer, str) or answer == "":
158
246
  raise TypeError(f"provider.start must return an SDP answer, got {answer!r}")
159
247
  except Exception as exc:
@@ -258,11 +346,101 @@ class VoiceManager(Tray):
258
346
  turn = self._turn(turn_id)
259
347
  turn["text"] = text
260
348
  turn["done"] = True
349
+ self._handoff_pending.append({"role": turn["role"], "text": text})
261
350
  self._render(turn)
262
351
  self._spawn(self._flush())
263
352
 
353
+ def _claim(self, request_id: str) -> bool:
354
+ if request_id in self._seen_requests:
355
+ return False
356
+ self._seen_requests.add(request_id)
357
+ return True
358
+
359
+ async def _append(
360
+ self, text: str, *, channel: Literal["speakable", "commentary"]
361
+ ) -> None:
362
+ provider = self._provider
363
+ if provider is not None:
364
+ await provider.append_context(text, channel=channel)
365
+
366
+ async def _speak(self, text: str) -> None:
367
+ await self._append(text, channel="speakable")
368
+
369
+ def task_requested(self, task_id: str, text: str) -> None:
370
+ if self._ended or not self._claim(task_id):
371
+ return
372
+ self._spawn(self._run_delegated_task(task_id, text))
373
+
374
+ async def _run_delegated_task(self, task_id: str, text: str) -> None:
375
+ # the lock orders transcript drains and keeps one delegation in flight
376
+ async with self._delegating:
377
+ pending, self._handoff_pending = self._handoff_pending, []
378
+ task = VoiceManager.TaskRequest(
379
+ task_id=task_id,
380
+ text=text,
381
+ transcript="\n".join(f"[{t['role']}] {t['text']}" for t in pending),
382
+ follow_up=self._tasks_run > 0,
383
+ )
384
+ self._tasks_run += 1
385
+ try:
386
+ answer = await self._host.handle_voice_task(task, speak=self._speak)
387
+ if not isinstance(answer, str) or answer == "":
388
+ raise TypeError(
389
+ f"handle_voice_task must return the result text, got {answer!r}"
390
+ )
391
+ except Exception as exc:
392
+ logger.exception("voice session %r task %r failed", self.id, task_id)
393
+ await self._append(
394
+ f"The delegated work could not be completed: {exc}",
395
+ channel="commentary",
396
+ )
397
+ return
398
+ await self._append(answer, channel="speakable")
399
+
264
400
  def tool_requested(self, request: "VoiceManager.ToolRequest") -> None:
265
- logger.info("voice session %r tool request ignored: %r", self.id, request)
401
+ if self._ended or not self._claim(request.call_id):
402
+ return
403
+ if request.name in self._client_tools:
404
+ self.toolCalls.value = [
405
+ *self.toolCalls.value,
406
+ {
407
+ "callId": request.call_id,
408
+ "name": request.name,
409
+ "arguments": request.arguments,
410
+ },
411
+ ]
412
+ return
413
+ self._spawn(self._run_tool_call(request))
414
+
415
+ async def _answer_client_call(self, call_id: str, output: str) -> None:
416
+ pending = self.toolCalls.value
417
+ if not any(call["callId"] == call_id for call in pending):
418
+ raise _reject(
419
+ "unknown-tool-call", f"no pending frontend tool call {call_id!r}"
420
+ )
421
+ provider = self._provider
422
+ if provider is None:
423
+ raise _reject("no-voice", "the voice session is not live")
424
+ await provider.return_tool_result(call_id, output)
425
+ self.toolCalls.value = [
426
+ call for call in pending if call["callId"] != call_id
427
+ ]
428
+
429
+ async def _run_tool_call(self, request: "VoiceManager.ToolRequest") -> None:
430
+ try:
431
+ output = await self._host.handle_voice_task(request, speak=self._speak)
432
+ if not isinstance(output, str):
433
+ raise TypeError(
434
+ f"handle_voice_task must return the result text, got {output!r}"
435
+ )
436
+ except Exception as exc:
437
+ logger.exception(
438
+ "voice session %r tool call %r failed", self.id, request.call_id
439
+ )
440
+ output = json.dumps({"error": f"{type(exc).__name__}: {exc}"})
441
+ provider = self._provider
442
+ if provider is not None:
443
+ await provider.return_tool_result(request.call_id, output)
266
444
 
267
445
  def rollover_approaching(self, rollover_id: str, deadline: float) -> None:
268
446
  logger.info(
@@ -282,6 +460,7 @@ class VoiceProvider(Protocol):
282
460
  async def start(
283
461
  self, offer: str, *,
284
462
  seed: "list[VoiceManager.SeedMessage]",
463
+ tools: "list[VoiceManager.ToolDef]",
285
464
  events: "VoiceManager.Events",
286
465
  ) -> str:
287
466
  """Open the session from an SDP offer and return the SDP answer; events flow into the sink."""
@@ -311,6 +490,7 @@ class VoiceManagerNamespace(TrayMapNamespace):
311
490
  "commit_voice_turns",
312
491
  "upsert_ephemeral_message",
313
492
  "drop_ephemeral_message",
493
+ "handle_voice_task",
314
494
  ):
315
495
  if not callable(getattr(api, name, None)):
316
496
  raise TypeError(
@@ -343,6 +523,7 @@ class VoiceManagerNamespace(TrayMapNamespace):
343
523
  offer = params.get("offer")
344
524
  if not isinstance(offer, str) or offer == "":
345
525
  raise _reject("invalid-message", "offer must be a non-empty SDP string")
526
+ tools = _validated_tools(params.get("tools"))
346
527
  if self._starting or self.live() is not None:
347
528
  raise _reject("voice-active", "a voice session is already live")
348
529
  self._starting = True
@@ -350,19 +531,38 @@ class VoiceManagerNamespace(TrayMapNamespace):
350
531
  seed = _capped_seed(await self._api.get_voice_seed())
351
532
  tray = await self.get_or_create(uuid4().hex)
352
533
  assert isinstance(tray, VoiceManager)
353
- return await tray._begin(offer, seed, ctx.caller, ctx.applied)
534
+ return await tray._begin(offer, seed, tools, ctx.caller, ctx.applied)
354
535
  finally:
355
536
  self._starting = False
356
537
 
357
- async def end(self, *, ctx: Any) -> None:
538
+ def _owned_session(self, ctx: Any, command: str) -> VoiceManager:
358
539
  session = self.live()
359
540
  if session is None:
360
541
  raise _reject("no-voice", "no voice session is live")
361
542
  if session.clientId.value != ctx.caller.client_id:
362
- raise _reject("not-voice-owner", "voice/end must come from the session owner")
543
+ raise _reject(
544
+ "not-voice-owner", f"{command} must come from the session owner"
545
+ )
546
+ return session
547
+
548
+ async def end(self, *, ctx: Any) -> None:
549
+ session = self._owned_session(ctx, "voice/end")
363
550
  await session._end("client")
364
551
  ctx.applied()
365
552
 
553
+ async def temp_frontend_tool_result(self, params: Any, *, ctx: Any) -> None:
554
+ session = self._owned_session(ctx, "voice/temp-frontend-tool-result")
555
+ if not isinstance(params, dict):
556
+ raise _reject("invalid-message", "params must be an object")
557
+ call_id = params.get("call_id")
558
+ output = params.get("output")
559
+ if not isinstance(call_id, str) or call_id == "" or not isinstance(output, str):
560
+ raise _reject(
561
+ "invalid-message", "call_id and output must be non-empty strings"
562
+ )
563
+ await session._answer_client_call(call_id, output)
564
+ ctx.applied()
565
+
366
566
 
367
567
  class VoiceManagerDescriptor(TrayDescriptor):
368
568
  namespace_cls = VoiceManagerNamespace
@@ -419,3 +619,11 @@ async def end_voice(host: Any, *, ctx: Any) -> None:
419
619
  if namespace is None:
420
620
  raise _reject("no-voice", "this host declares no voice manager")
421
621
  return await namespace.end(ctx=ctx)
622
+
623
+
624
+ async def temp_frontend_tool_result(host: Any, params: Any, *, ctx: Any) -> None:
625
+ """The ``voice/temp-frontend-tool-result`` command body: routes to the host's declared voice manager."""
626
+ namespace = _voice_of(host)
627
+ if namespace is None:
628
+ raise _reject("no-voice", "this host declares no voice manager")
629
+ return await namespace.temp_frontend_tool_result(params, ctx=ctx)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: harness-sdk-python
3
- Version: 0.29.2
3
+ Version: 0.30.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
- harness_sdk/__init__.py,sha256=N9gOUKqe0_eM7cIA9sfA_lH1FBw1MN8U-zerwGAPVHE,1094
1
+ harness_sdk/__init__.py,sha256=EO0rTCg1NmWPNlnip81KjkvKYoc0dGLULKv2ton3tG8,1158
2
2
  harness_sdk/checkpoints.py,sha256=L02l1IyLDj2b-GD7_HGrck7uenALeI4kg8yJSzoNVmc,25999
3
3
  harness_sdk/deepagents.py,sha256=cMipZ9ndZ3zUR3-VqOMf5CiPVMmym74ytIeguQAjYZo,12280
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=oVmfxltjyV9ylATIpAszaM6MOS9TC3Haksgf6I7c4v8,15863
8
- harness_sdk_python-0.29.2.dist-info/METADATA,sha256=-4c6JdBIpkP6td3WlIcpnbUOX9ntoTM5dG6vcwoD55k,2200
9
- harness_sdk_python-0.29.2.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
10
- harness_sdk_python-0.29.2.dist-info/RECORD,,
7
+ harness_sdk/voice.py,sha256=ng2w22tk8aaC1h_x0K4ng7mbaTNXPQwCwFllErhkMOM,24616
8
+ harness_sdk_python-0.30.0.dist-info/METADATA,sha256=JNDcDwcIICNMqvUvczSqIk1SDUjsWBpA1ROrs6L95HM,2200
9
+ harness_sdk_python-0.30.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
10
+ harness_sdk_python-0.30.0.dist-info/RECORD,,