harness-sdk-python 0.29.2__tar.gz → 0.30.1__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 (44) hide show
  1. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/PKG-INFO +1 -1
  2. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/pyproject.toml +1 -1
  3. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/src/harness_sdk/__init__.py +2 -0
  4. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/src/harness_sdk/voice.py +228 -11
  5. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_voice.py +8 -3
  6. harness_sdk_python-0.30.1/tests/test_voice_delegation.py +224 -0
  7. harness_sdk_python-0.30.1/tests/test_voice_frontend_tools.py +109 -0
  8. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/voice_helpers.py +22 -3
  9. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/.gitignore +0 -0
  10. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/README.md +0 -0
  11. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/examples/__init__.py +0 -0
  12. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/examples/runs_app.py +0 -0
  13. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/src/harness_sdk/checkpoints.py +0 -0
  14. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/src/harness_sdk/deepagents.py +0 -0
  15. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/src/harness_sdk/fenced_postgres.py +0 -0
  16. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/src/harness_sdk/linear_thread.py +0 -0
  17. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/src/harness_sdk/run_manager.py +0 -0
  18. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/run_helpers.py +0 -0
  19. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_admit_steer.py +0 -0
  20. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_applied_visibility.py +0 -0
  21. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_batches.py +0 -0
  22. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_branch_anchor.py +0 -0
  23. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_checkpoints.py +0 -0
  24. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_deepagents_messages.py +0 -0
  25. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_dispatching.py +0 -0
  26. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_durability.py +0 -0
  27. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_edit_dispatched.py +0 -0
  28. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_edit_reload.py +0 -0
  29. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_enqueue.py +0 -0
  30. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_fenced_postgres.py +0 -0
  31. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_input_required.py +0 -0
  32. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_linear_thread.py +0 -0
  33. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_meta.py +0 -0
  34. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_mint_concurrency.py +0 -0
  35. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_outcomes.py +0 -0
  36. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_placement.py +0 -0
  37. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_prepare_hooks.py +0 -0
  38. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_restore.py +0 -0
  39. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_rewind_during_run.py +0 -0
  40. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_run_crash_sweep.py +0 -0
  41. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_settle.py +0 -0
  42. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_steer.py +0 -0
  43. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/tests/test_stop_continue.py +0 -0
  44. {harness_sdk_python-0.29.2 → harness_sdk_python-0.30.1}/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.29.2
3
+ Version: 0.30.1
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.29.2"
3
+ version = "0.30.1"
4
4
  description = "RunManager: the harness-sdk runs subsystem for Python Statewire hosts"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -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
  ]
@@ -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, activeTask}`` — 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,16 @@ 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). The running unit
37
+ projects as ``activeTask`` = ``{taskId, text}``, ``None`` at rest.
38
+
24
39
  Rejections: ``voice-active`` (a session is already live), ``no-voice``
25
40
  (no voice manager declared, or ``voice/end`` with no session),
26
41
  ``not-voice-owner`` (``voice/end`` from another client),
@@ -30,9 +45,10 @@ Rejections: ``voice-active`` (a session is already live), ``no-voice``
30
45
  import asyncio
31
46
  import functools
32
47
  import inspect
48
+ import json
33
49
  import logging
34
50
  from dataclasses import dataclass
35
- from typing import Any, Callable, Literal, Protocol, TypedDict
51
+ from typing import Any, Awaitable, Callable, Literal, Protocol, TypedDict
36
52
  from uuid import uuid4
37
53
 
38
54
  from pinned.trays import Tray, TrayDescriptor, TrayMapNamespace
@@ -49,6 +65,30 @@ def _reject(reason: str, message: str) -> StatewireReject:
49
65
  return StatewireReject(message, payload={"reason": reason})
50
66
 
51
67
 
68
+ def _validated_tools(tools: Any) -> "list[VoiceManager.ToolDef]":
69
+ if tools is None:
70
+ return []
71
+ if not isinstance(tools, list):
72
+ raise _reject("invalid-message", "tools must be a list")
73
+ names: set[str] = set()
74
+ for tool in tools:
75
+ if (
76
+ not isinstance(tool, dict)
77
+ or not isinstance(tool.get("name"), str)
78
+ or tool["name"] == ""
79
+ or not isinstance(tool.get("description"), str)
80
+ or not isinstance(tool.get("parameters"), dict)
81
+ ):
82
+ raise _reject(
83
+ "invalid-message",
84
+ f"tools entries must be {{name, description, parameters}}, got {tool!r}",
85
+ )
86
+ if tool["name"] in names:
87
+ raise _reject("invalid-message", f"duplicate tool name {tool['name']!r}")
88
+ names.add(tool["name"])
89
+ return tools
90
+
91
+
52
92
  def _capped_seed(seed: Any) -> "list[VoiceManager.SeedMessage]":
53
93
  if not isinstance(seed, list):
54
94
  raise TypeError(f"get_voice_seed must return a list, got {seed!r}")
@@ -71,11 +111,15 @@ class VoiceManager(Tray):
71
111
 
72
112
  clientId = observable(None)
73
113
  status = observable("connecting")
114
+ toolCalls = observable([])
115
+ activeTask = observable(None)
74
116
 
75
117
  state = observable(
76
118
  {
77
119
  "clientId": clientId,
78
120
  "status": status,
121
+ "toolCalls": toolCalls,
122
+ "activeTask": activeTask,
79
123
  }
80
124
  )
81
125
 
@@ -86,6 +130,11 @@ class VoiceManager(Tray):
86
130
  self._flushing = asyncio.Lock()
87
131
  self._ended = False
88
132
  self._watcher: "asyncio.Task[Any] | None" = None
133
+ self._handoff_pending: list[dict[str, str]] = []
134
+ self._seen_requests: set[str] = set()
135
+ self._delegating = asyncio.Lock()
136
+ self._tasks_run = 0
137
+ self._client_tools: set[str] = set()
89
138
 
90
139
  def items(self):
91
140
  yield from ()
@@ -96,12 +145,41 @@ class VoiceManager(Tray):
96
145
  role: Literal["user", "assistant", "system"]
97
146
  text: str
98
147
 
148
+ class ToolDef(TypedDict):
149
+ """One frontend function tool the client declares at ``voice/start``."""
150
+
151
+ name: str
152
+ description: str
153
+ parameters: dict[str, Any]
154
+
99
155
  @dataclass(frozen=True)
100
156
  class ToolRequest:
101
157
  call_id: str
102
158
  name: str
103
159
  arguments: str
104
160
 
161
+ @dataclass(frozen=True)
162
+ class TaskRequest:
163
+ """One delegated free-text work unit plus its transcript delta."""
164
+
165
+ task_id: str
166
+ text: str
167
+ transcript: str
168
+ follow_up: bool
169
+
170
+ def handoff(self) -> str:
171
+ """Render the task and its transcript delta as one delegate-facing prompt."""
172
+ window = (
173
+ "the voice conversation since the previous delegated task"
174
+ if self.follow_up
175
+ else "the voice conversation so far"
176
+ )
177
+ transcript = self.transcript or "(No new conversation was captured.)"
178
+ return (
179
+ f"This is the transcript of {window}:\n\n{transcript}\n\n"
180
+ f"The voice model delegated this task:\n{self.text}"
181
+ )
182
+
105
183
  @dataclass(frozen=True)
106
184
  class SessionContext:
107
185
  """The provider factory's per-session context."""
@@ -119,6 +197,8 @@ class VoiceManager(Tray):
119
197
 
120
198
  def tool_requested(self, request: "VoiceManager.ToolRequest") -> None: ...
121
199
 
200
+ def task_requested(self, task_id: str, text: str) -> None: ...
201
+
122
202
  def rollover_approaching(self, rollover_id: str, deadline: float) -> None: ...
123
203
 
124
204
  def closed(self, reason: str) -> None: ...
@@ -142,18 +222,29 @@ class VoiceManager(Tray):
142
222
  """Remove an in-flight turn from the ``state["messages"]`` projection."""
143
223
  ...
144
224
 
225
+ async def handle_voice_task(
226
+ self,
227
+ task: "VoiceManager.TaskRequest | VoiceManager.ToolRequest",
228
+ *,
229
+ speak: Callable[[str], Awaitable[None]],
230
+ ) -> str:
231
+ """Fulfill one delegated work unit; ``speak`` streams interim spoken updates and the return value is the result."""
232
+ ...
233
+
145
234
  # ─── Session lifecycle ──────────────────────────────────
146
235
 
147
236
  async def _begin(
148
- self, offer: str, seed: "list[VoiceManager.SeedMessage]", caller: Any,
237
+ self, offer: str, seed: "list[VoiceManager.SeedMessage]",
238
+ tools: "list[VoiceManager.ToolDef]", caller: Any,
149
239
  applied: Callable[[], None],
150
240
  ) -> Any:
151
241
  self.clientId.value = caller.client_id
242
+ self._client_tools = {tool["name"] for tool in tools}
152
243
  try:
153
244
  provider = await self.handler(
154
245
  VoiceManager.SessionContext(client_id=caller.client_id)
155
246
  )
156
- answer = await provider.start(offer, seed=seed, events=self)
247
+ answer = await provider.start(offer, seed=seed, tools=tools, events=self)
157
248
  if not isinstance(answer, str) or answer == "":
158
249
  raise TypeError(f"provider.start must return an SDP answer, got {answer!r}")
159
250
  except Exception as exc:
@@ -258,11 +349,107 @@ class VoiceManager(Tray):
258
349
  turn = self._turn(turn_id)
259
350
  turn["text"] = text
260
351
  turn["done"] = True
352
+ self._handoff_pending.append({"role": turn["role"], "text": text})
261
353
  self._render(turn)
262
354
  self._spawn(self._flush())
263
355
 
356
+ def _claim(self, request_id: str) -> bool:
357
+ if request_id in self._seen_requests:
358
+ return False
359
+ self._seen_requests.add(request_id)
360
+ return True
361
+
362
+ async def _append(
363
+ self, text: str, *, channel: Literal["speakable", "commentary"]
364
+ ) -> None:
365
+ provider = self._provider
366
+ if provider is not None:
367
+ await provider.append_context(text, channel=channel)
368
+
369
+ async def _speak(self, text: str) -> None:
370
+ await self._append(text, channel="speakable")
371
+
372
+ def task_requested(self, task_id: str, text: str) -> None:
373
+ if self._ended or not self._claim(task_id):
374
+ return
375
+ self._spawn(self._run_delegated_task(task_id, text))
376
+
377
+ async def _run_delegated_task(self, task_id: str, text: str) -> None:
378
+ # the lock orders transcript drains and keeps one delegation in flight
379
+ async with self._delegating:
380
+ pending, self._handoff_pending = self._handoff_pending, []
381
+ task = VoiceManager.TaskRequest(
382
+ task_id=task_id,
383
+ text=text,
384
+ transcript="\n".join(f"[{t['role']}] {t['text']}" for t in pending),
385
+ follow_up=self._tasks_run > 0,
386
+ )
387
+ self._tasks_run += 1
388
+ self.activeTask.value = {"taskId": task_id, "text": text}
389
+ try:
390
+ answer = await self._host.handle_voice_task(task, speak=self._speak)
391
+ if not isinstance(answer, str) or answer == "":
392
+ raise TypeError(
393
+ f"handle_voice_task must return the result text, got {answer!r}"
394
+ )
395
+ except Exception as exc:
396
+ logger.exception("voice session %r task %r failed", self.id, task_id)
397
+ await self._append(
398
+ f"The delegated work could not be completed: {exc}",
399
+ channel="commentary",
400
+ )
401
+ return
402
+ finally:
403
+ self.activeTask.value = None
404
+ await self._append(answer, channel="speakable")
405
+
264
406
  def tool_requested(self, request: "VoiceManager.ToolRequest") -> None:
265
- logger.info("voice session %r tool request ignored: %r", self.id, request)
407
+ if self._ended or not self._claim(request.call_id):
408
+ return
409
+ if request.name in self._client_tools:
410
+ self.toolCalls.value = [
411
+ *self.toolCalls.value,
412
+ {
413
+ "callId": request.call_id,
414
+ "name": request.name,
415
+ "arguments": request.arguments,
416
+ },
417
+ ]
418
+ return
419
+ self._spawn(self._run_tool_call(request))
420
+
421
+ async def _answer_client_call(self, call_id: str, output: str) -> None:
422
+ pending = self.toolCalls.value
423
+ if not any(call["callId"] == call_id for call in pending):
424
+ raise _reject(
425
+ "unknown-tool-call", f"no pending frontend tool call {call_id!r}"
426
+ )
427
+ provider = self._provider
428
+ if provider is None:
429
+ raise _reject("no-voice", "the voice session is not live")
430
+ await provider.return_tool_result(call_id, output)
431
+ self.toolCalls.value = [
432
+ call for call in pending if call["callId"] != call_id
433
+ ]
434
+
435
+ async def _run_tool_call(self, request: "VoiceManager.ToolRequest") -> None:
436
+ self.activeTask.value = {"taskId": request.call_id, "text": request.name}
437
+ try:
438
+ output = await self._host.handle_voice_task(request, speak=self._speak)
439
+ if not isinstance(output, str):
440
+ raise TypeError(
441
+ f"handle_voice_task must return the result text, got {output!r}"
442
+ )
443
+ except Exception as exc:
444
+ logger.exception(
445
+ "voice session %r tool call %r failed", self.id, request.call_id
446
+ )
447
+ output = json.dumps({"error": f"{type(exc).__name__}: {exc}"})
448
+ finally:
449
+ self.activeTask.value = None
450
+ provider = self._provider
451
+ if provider is not None:
452
+ await provider.return_tool_result(request.call_id, output)
266
453
 
267
454
  def rollover_approaching(self, rollover_id: str, deadline: float) -> None:
268
455
  logger.info(
@@ -282,6 +469,7 @@ class VoiceProvider(Protocol):
282
469
  async def start(
283
470
  self, offer: str, *,
284
471
  seed: "list[VoiceManager.SeedMessage]",
472
+ tools: "list[VoiceManager.ToolDef]",
285
473
  events: "VoiceManager.Events",
286
474
  ) -> str:
287
475
  """Open the session from an SDP offer and return the SDP answer; events flow into the sink."""
@@ -311,6 +499,7 @@ class VoiceManagerNamespace(TrayMapNamespace):
311
499
  "commit_voice_turns",
312
500
  "upsert_ephemeral_message",
313
501
  "drop_ephemeral_message",
502
+ "handle_voice_task",
314
503
  ):
315
504
  if not callable(getattr(api, name, None)):
316
505
  raise TypeError(
@@ -343,6 +532,7 @@ class VoiceManagerNamespace(TrayMapNamespace):
343
532
  offer = params.get("offer")
344
533
  if not isinstance(offer, str) or offer == "":
345
534
  raise _reject("invalid-message", "offer must be a non-empty SDP string")
535
+ tools = _validated_tools(params.get("tools"))
346
536
  if self._starting or self.live() is not None:
347
537
  raise _reject("voice-active", "a voice session is already live")
348
538
  self._starting = True
@@ -350,19 +540,38 @@ class VoiceManagerNamespace(TrayMapNamespace):
350
540
  seed = _capped_seed(await self._api.get_voice_seed())
351
541
  tray = await self.get_or_create(uuid4().hex)
352
542
  assert isinstance(tray, VoiceManager)
353
- return await tray._begin(offer, seed, ctx.caller, ctx.applied)
543
+ return await tray._begin(offer, seed, tools, ctx.caller, ctx.applied)
354
544
  finally:
355
545
  self._starting = False
356
546
 
357
- async def end(self, *, ctx: Any) -> None:
547
+ def _owned_session(self, ctx: Any, command: str) -> VoiceManager:
358
548
  session = self.live()
359
549
  if session is None:
360
550
  raise _reject("no-voice", "no voice session is live")
361
551
  if session.clientId.value != ctx.caller.client_id:
362
- raise _reject("not-voice-owner", "voice/end must come from the session owner")
552
+ raise _reject(
553
+ "not-voice-owner", f"{command} must come from the session owner"
554
+ )
555
+ return session
556
+
557
+ async def end(self, *, ctx: Any) -> None:
558
+ session = self._owned_session(ctx, "voice/end")
363
559
  await session._end("client")
364
560
  ctx.applied()
365
561
 
562
+ async def temp_frontend_tool_result(self, params: Any, *, ctx: Any) -> None:
563
+ session = self._owned_session(ctx, "voice/temp-frontend-tool-result")
564
+ if not isinstance(params, dict):
565
+ raise _reject("invalid-message", "params must be an object")
566
+ call_id = params.get("call_id")
567
+ output = params.get("output")
568
+ if not isinstance(call_id, str) or call_id == "" or not isinstance(output, str):
569
+ raise _reject(
570
+ "invalid-message", "call_id and output must be non-empty strings"
571
+ )
572
+ await session._answer_client_call(call_id, output)
573
+ ctx.applied()
574
+
366
575
 
367
576
  class VoiceManagerDescriptor(TrayDescriptor):
368
577
  namespace_cls = VoiceManagerNamespace
@@ -419,3 +628,11 @@ async def end_voice(host: Any, *, ctx: Any) -> None:
419
628
  if namespace is None:
420
629
  raise _reject("no-voice", "this host declares no voice manager")
421
630
  return await namespace.end(ctx=ctx)
631
+
632
+
633
+ async def temp_frontend_tool_result(host: Any, params: Any, *, ctx: Any) -> None:
634
+ """The ``voice/temp-frontend-tool-result`` command body: routes to the host's declared voice manager."""
635
+ namespace = _voice_of(host)
636
+ if namespace is None:
637
+ raise _reject("no-voice", "this host declares no voice manager")
638
+ return await namespace.temp_frontend_tool_result(params, ctx=ctx)
@@ -36,10 +36,15 @@ async def test_start_seeds_provider_and_projects_session():
36
36
  rsp = await drv.command("voice/start", {"offer": OFFER})
37
37
  assert rsp["type"] == "accepted", rsp
38
38
  assert rsp["payload"] == {"answer": ANSWER}
39
- assert bench.provider.calls == [("start", OFFER, bench.transcript)]
39
+ assert bench.provider.calls == [("start", OFFER, bench.transcript, [])]
40
40
  await drv.wait(lambda s: (voice_of(s) or {}).get("status") == "live")
41
41
  voice = voice_of(drv.replica)
42
- assert voice == {"clientId": drv.client_id, "status": "live"}
42
+ assert voice == {
43
+ "clientId": drv.client_id,
44
+ "status": "live",
45
+ "toolCalls": [],
46
+ "activeTask": None,
47
+ }
43
48
  assert bench.contexts[0].client_id == drv.client_id
44
49
 
45
50
 
@@ -298,7 +303,7 @@ async def test_seed_takes_the_128_tail():
298
303
  bench = Bench(transcript=[seed_message(i) for i in range(130)])
299
304
  async with voice_host(bench) as (drv, _app):
300
305
  await drv.command("voice/start", {"offer": OFFER})
301
- _, _, seed = bench.provider.calls[0]
306
+ _, _, seed, _tools = bench.provider.calls[0]
302
307
  assert len(seed) == 128
303
308
  assert seed == bench.transcript[-128:]
304
309
 
@@ -0,0 +1,224 @@
1
+ """Voice delegation contract: work units route to ``Host.handle_voice_task``,
2
+ handoffs drain the transcript incrementally, results flow back as speakable
3
+ context appends, named calls answer via ``return_tool_result``, repeated
4
+ request ids run once, and the running unit projects as ``activeTask``."""
5
+
6
+ import asyncio
7
+ import json
8
+
9
+ from voice_helpers import OFFER, Bench, voice_host, voice_of
10
+
11
+ from harness_sdk import VoiceManager
12
+
13
+
14
+ async def until(predicate, timeout: float = 5) -> None:
15
+ deadline = asyncio.get_running_loop().time() + timeout
16
+ while not predicate():
17
+ assert asyncio.get_running_loop().time() < deadline, "condition never held"
18
+ await asyncio.sleep(0.01)
19
+
20
+
21
+ def appends(bench: Bench):
22
+ return [call for call in bench.provider.calls if call[0] == "append_context"]
23
+
24
+
25
+ async def test_task_routes_to_handler_and_result_appends_speakable():
26
+ bench = Bench()
27
+ async with voice_host(bench) as (drv, _app):
28
+ await drv.command("voice/start", {"offer": OFFER})
29
+ bench.events().task_requested("d1", "check the weather")
30
+ await until(
31
+ lambda: ("append_context", "done:d1", "speakable") in bench.provider.calls
32
+ )
33
+ assert bench.tasks == [
34
+ VoiceManager.TaskRequest(
35
+ task_id="d1", text="check the weather", transcript="", follow_up=False
36
+ )
37
+ ]
38
+
39
+
40
+ async def test_handoff_carries_first_full_then_delta_transcript():
41
+ bench = Bench()
42
+ async with voice_host(bench) as (drv, _app):
43
+ await drv.command("voice/start", {"offer": OFFER})
44
+ events = bench.events()
45
+ events.turn_started("t1", "user")
46
+ events.turn_done("t1", "hello")
47
+ events.turn_started("t2", "assistant")
48
+ events.turn_done("t2", "hi!")
49
+ events.task_requested("d1", "first task")
50
+ await until(lambda: len(bench.tasks) == 1)
51
+ first = bench.tasks[0]
52
+ assert first.transcript == "[user] hello\n[assistant] hi!"
53
+ assert first.follow_up is False
54
+ assert "the voice conversation so far" in first.handoff()
55
+ assert first.handoff().endswith(
56
+ "The voice model delegated this task:\nfirst task"
57
+ )
58
+ events.turn_started("t3", "user")
59
+ events.turn_done("t3", "and now?")
60
+ events.task_requested("d2", "second task")
61
+ await until(lambda: len(bench.tasks) == 2)
62
+ second = bench.tasks[1]
63
+ assert second.transcript == "[user] and now?"
64
+ assert second.follow_up is True
65
+ assert "since the previous delegated task" in second.handoff()
66
+
67
+
68
+ async def test_empty_handoff_renders_a_placeholder():
69
+ task = VoiceManager.TaskRequest(
70
+ task_id="d1", text="go", transcript="", follow_up=False
71
+ )
72
+ assert "(No new conversation was captured.)" in task.handoff()
73
+
74
+
75
+ async def test_speak_streams_interim_updates_before_the_result():
76
+ bench = Bench()
77
+
78
+ async def handler(task, speak):
79
+ await speak("working on it")
80
+ return "all done"
81
+
82
+ bench.task_handler = handler
83
+ async with voice_host(bench) as (drv, _app):
84
+ await drv.command("voice/start", {"offer": OFFER})
85
+ bench.events().task_requested("d1", "dig in")
86
+ await until(
87
+ lambda: ("append_context", "all done", "speakable") in bench.provider.calls
88
+ )
89
+ assert appends(bench) == [
90
+ ("append_context", "working on it", "speakable"),
91
+ ("append_context", "all done", "speakable"),
92
+ ]
93
+
94
+
95
+ async def test_named_call_answers_via_return_tool_result():
96
+ bench = Bench()
97
+ async with voice_host(bench) as (drv, _app):
98
+ await drv.command("voice/start", {"offer": OFFER})
99
+ request = VoiceManager.ToolRequest(call_id="c1", name="get_time", arguments="{}")
100
+ bench.events().tool_requested(request)
101
+ await until(
102
+ lambda: ("return_tool_result", "c1", "done:c1") in bench.provider.calls
103
+ )
104
+ assert bench.tasks == [request]
105
+ assert appends(bench) == []
106
+
107
+
108
+ async def test_repeated_request_ids_run_once():
109
+ bench = Bench()
110
+ async with voice_host(bench) as (drv, _app):
111
+ await drv.command("voice/start", {"offer": OFFER})
112
+ events = bench.events()
113
+ events.task_requested("d1", "one")
114
+ events.task_requested("d1", "one")
115
+ request = VoiceManager.ToolRequest(call_id="c1", name="get_time", arguments="{}")
116
+ events.tool_requested(request)
117
+ events.tool_requested(request)
118
+ await until(
119
+ lambda: ("append_context", "done:d1", "speakable") in bench.provider.calls
120
+ and ("return_tool_result", "c1", "done:c1") in bench.provider.calls
121
+ )
122
+ assert len(bench.tasks) == 2
123
+
124
+
125
+ async def test_task_failure_surfaces_as_commentary():
126
+ bench = Bench()
127
+
128
+ async def handler(task, speak):
129
+ raise RuntimeError("boom")
130
+
131
+ bench.task_handler = handler
132
+ async with voice_host(bench) as (drv, _app):
133
+ await drv.command("voice/start", {"offer": OFFER})
134
+ bench.events().task_requested("d1", "dig in")
135
+ await until(lambda: appends(bench) != [])
136
+ assert appends(bench) == [
137
+ (
138
+ "append_context",
139
+ "The delegated work could not be completed: boom",
140
+ "commentary",
141
+ )
142
+ ]
143
+
144
+
145
+ async def test_active_task_projects_while_a_task_runs_and_clears_after():
146
+ bench = Bench()
147
+ gate = asyncio.Event()
148
+
149
+ async def handler(task, speak):
150
+ await gate.wait()
151
+ return "all done"
152
+
153
+ bench.task_handler = handler
154
+ async with voice_host(bench) as (drv, _app):
155
+ await drv.command("voice/start", {"offer": OFFER})
156
+ bench.events().task_requested("d1", "check the weather")
157
+ await drv.wait(
158
+ lambda s: (voice_of(s) or {}).get("activeTask")
159
+ == {"taskId": "d1", "text": "check the weather"}
160
+ )
161
+ gate.set()
162
+ await drv.wait(lambda s: (voice_of(s) or {}).get("activeTask") is None)
163
+
164
+
165
+ async def test_active_task_projects_a_named_call_and_clears_after():
166
+ bench = Bench()
167
+ gate = asyncio.Event()
168
+
169
+ async def handler(task, speak):
170
+ await gate.wait()
171
+ return "{}"
172
+
173
+ bench.task_handler = handler
174
+ async with voice_host(bench) as (drv, _app):
175
+ await drv.command("voice/start", {"offer": OFFER})
176
+ bench.events().tool_requested(
177
+ VoiceManager.ToolRequest(call_id="c1", name="get_time", arguments="{}")
178
+ )
179
+ await drv.wait(
180
+ lambda s: (voice_of(s) or {}).get("activeTask")
181
+ == {"taskId": "c1", "text": "get_time"}
182
+ )
183
+ gate.set()
184
+ await drv.wait(lambda s: (voice_of(s) or {}).get("activeTask") is None)
185
+
186
+
187
+ async def test_active_task_clears_when_the_handler_fails():
188
+ bench = Bench()
189
+ gate = asyncio.Event()
190
+
191
+ async def handler(task, speak):
192
+ await gate.wait()
193
+ raise RuntimeError("boom")
194
+
195
+ bench.task_handler = handler
196
+ async with voice_host(bench) as (drv, _app):
197
+ await drv.command("voice/start", {"offer": OFFER})
198
+ bench.events().task_requested("d1", "dig in")
199
+ await drv.wait(lambda s: (voice_of(s) or {}).get("activeTask") is not None)
200
+ gate.set()
201
+ await drv.wait(lambda s: (voice_of(s) or {}).get("activeTask") is None)
202
+ assert (voice_of(drv.replica) or {}).get("status") == "live"
203
+
204
+
205
+ async def test_tool_failure_returns_an_error_output():
206
+ bench = Bench()
207
+
208
+ async def handler(task, speak):
209
+ raise RuntimeError("boom")
210
+
211
+ bench.task_handler = handler
212
+ async with voice_host(bench) as (drv, _app):
213
+ await drv.command("voice/start", {"offer": OFFER})
214
+ bench.events().tool_requested(
215
+ VoiceManager.ToolRequest(call_id="c1", name="get_time", arguments="{}")
216
+ )
217
+ await until(
218
+ lambda: any(c[0] == "return_tool_result" for c in bench.provider.calls)
219
+ )
220
+ [(_, call_id, output)] = [
221
+ c for c in bench.provider.calls if c[0] == "return_tool_result"
222
+ ]
223
+ assert call_id == "c1"
224
+ assert json.loads(output) == {"error": "RuntimeError: boom"}
@@ -0,0 +1,109 @@
1
+ """Frontend function tools contract: ``voice/start {tools}`` reaches the
2
+ provider, matching calls project into ``state["voice"]["toolCalls"]``, and
3
+ ``voice/temp-frontend-tool-result`` answers them."""
4
+
5
+ from run_helpers import assert_rejected
6
+ from voice_helpers import (
7
+ OFFER,
8
+ Bench,
9
+ side_command,
10
+ voice_host,
11
+ voice_of,
12
+ )
13
+
14
+ from harness_sdk import VoiceManager
15
+
16
+ TOOL = {
17
+ "name": "get_local_time",
18
+ "description": "Read the user's local date and time.",
19
+ "parameters": {"type": "object", "properties": {}},
20
+ }
21
+
22
+
23
+ def call_of(events, call_id: str = "call-1") -> None:
24
+ events.tool_requested(
25
+ VoiceManager.ToolRequest(
26
+ call_id=call_id, name="get_local_time", arguments="{}"
27
+ )
28
+ )
29
+
30
+
31
+ async def test_start_passes_tools_to_the_provider():
32
+ bench = Bench()
33
+ async with voice_host(bench) as (drv, _app):
34
+ rsp = await drv.command("voice/start", {"offer": OFFER, "tools": [TOOL]})
35
+ assert rsp["type"] == "accepted", rsp
36
+ assert bench.provider.calls[0] == ("start", OFFER, [], [TOOL])
37
+
38
+
39
+ async def test_malformed_tools_reject_invalid_message():
40
+ bench = Bench()
41
+ async with voice_host(bench) as (drv, _app):
42
+ for tools in (
43
+ "not-a-list",
44
+ [{"name": "", "description": "", "parameters": {}}],
45
+ [{"name": "a", "description": "d"}],
46
+ [TOOL, TOOL],
47
+ ):
48
+ assert_rejected(
49
+ await drv.command("voice/start", {"offer": OFFER, "tools": tools}),
50
+ "invalid-message",
51
+ )
52
+ assert bench.provider.calls == []
53
+
54
+
55
+ async def test_client_tool_call_projects_into_state():
56
+ bench = Bench()
57
+ async with voice_host(bench) as (drv, _app):
58
+ await drv.command("voice/start", {"offer": OFFER, "tools": [TOOL]})
59
+ call_of(bench.events())
60
+ await drv.wait(
61
+ lambda s: (voice_of(s) or {}).get("toolCalls")
62
+ == [{"callId": "call-1", "name": "get_local_time", "arguments": "{}"}]
63
+ )
64
+ # the call surfaced to the client instead of the host handler
65
+ assert bench.tasks == []
66
+
67
+
68
+ async def test_tool_result_forwards_and_clears_the_pending_call():
69
+ bench = Bench()
70
+ async with voice_host(bench) as (drv, _app):
71
+ await drv.command("voice/start", {"offer": OFFER, "tools": [TOOL]})
72
+ call_of(bench.events())
73
+ await drv.wait(lambda s: (voice_of(s) or {}).get("toolCalls") != [])
74
+ rsp = await drv.command(
75
+ "voice/temp-frontend-tool-result",
76
+ {"call_id": "call-1", "output": "12:30"},
77
+ )
78
+ assert rsp["type"] == "accepted", rsp
79
+ assert ("return_tool_result", "call-1", "12:30") in bench.provider.calls
80
+ await drv.wait(lambda s: (voice_of(s) or {}).get("toolCalls") == [])
81
+
82
+
83
+ async def test_unknown_call_id_rejects_unknown_tool_call():
84
+ bench = Bench()
85
+ async with voice_host(bench) as (drv, _app):
86
+ await drv.command("voice/start", {"offer": OFFER, "tools": [TOOL]})
87
+ assert_rejected(
88
+ await drv.command(
89
+ "voice/temp-frontend-tool-result",
90
+ {"call_id": "call-9", "output": "x"},
91
+ ),
92
+ "unknown-tool-call",
93
+ )
94
+
95
+
96
+ async def test_tool_result_from_other_client_rejects_not_voice_owner():
97
+ bench = Bench()
98
+ async with voice_host(bench) as (drv, app):
99
+ await drv.command("voice/start", {"offer": OFFER, "tools": [TOOL]})
100
+ call_of(bench.events())
101
+ await drv.wait(lambda s: (voice_of(s) or {}).get("toolCalls") != [])
102
+ rsp = await side_command(
103
+ app,
104
+ drv._client,
105
+ "voice/temp-frontend-tool-result",
106
+ {"call_id": "call-1", "output": "x"},
107
+ )
108
+ assert_rejected(rsp, "not-voice-owner")
109
+ assert ("return_tool_result", "call-1", "x") not in bench.provider.calls
@@ -11,7 +11,13 @@ from run_helpers import RunDriver, _statement
11
11
  from statewire import Statewire, command
12
12
  from statewire_helpers import apply_ops, post_frame, statewire_client, stream_of
13
13
 
14
- from harness_sdk import VoiceManager, end_voice, start_voice, voice_manager
14
+ from harness_sdk import (
15
+ VoiceManager,
16
+ end_voice,
17
+ start_voice,
18
+ temp_frontend_tool_result,
19
+ voice_manager,
20
+ )
15
21
 
16
22
  OFFER = "v=0 fake-offer"
17
23
  ANSWER = "v=0 fake-answer"
@@ -27,8 +33,8 @@ class FakeVoiceProvider:
27
33
  self.events: VoiceManager.Events | None = None
28
34
  self.closed = False
29
35
 
30
- async def start(self, offer, *, seed, events):
31
- self.calls.append(("start", offer, list(seed)))
36
+ async def start(self, offer, *, seed, tools, events):
37
+ self.calls.append(("start", offer, list(seed), list(tools)))
32
38
  if self.fail is not None:
33
39
  raise self.fail
34
40
  self.events = events
@@ -64,6 +70,8 @@ class Bench:
64
70
  commits: list[list[dict[str, Any]]] = field(default_factory=list)
65
71
  commit_failures: list[Exception] = field(default_factory=list)
66
72
  contexts: list[VoiceManager.SessionContext] = field(default_factory=list)
73
+ tasks: list[Any] = field(default_factory=list)
74
+ task_handler: Any = None
67
75
 
68
76
  def events(self) -> VoiceManager.Events:
69
77
  assert self.provider.events is not None, "provider.start never ran"
@@ -108,6 +116,13 @@ def make_voice_host(bench: Bench, *, declare: bool = True):
108
116
  del self._ephemeral[message_id]
109
117
  self._project_messages()
110
118
 
119
+ async def handle_voice_task(self, task, *, speak):
120
+ bench.tasks.append(task)
121
+ if bench.task_handler is not None:
122
+ return await bench.task_handler(task, speak)
123
+ request_id = getattr(task, "task_id", None) or task.call_id
124
+ return f"done:{request_id}"
125
+
111
126
  @command("voice/start")
112
127
  async def voice_start(self, params, *, ctx):
113
128
  return await start_voice(self, params, ctx=ctx)
@@ -116,6 +131,10 @@ def make_voice_host(bench: Bench, *, declare: bool = True):
116
131
  async def voice_end(self, params=None, *, ctx):
117
132
  return await end_voice(self, ctx=ctx)
118
133
 
134
+ @command("voice/temp-frontend-tool-result")
135
+ async def voice_tool_result(self, params, *, ctx):
136
+ return await temp_frontend_tool_result(self, params, ctx=ctx)
137
+
119
138
  if not declare:
120
139
  return Host
121
140