phosphor-harness 0.4.5 → 0.4.6

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.
package/README.md CHANGED
@@ -113,6 +113,8 @@ Duplex mode uses the pinned acoustic session's draft and commit controls. Speech
113
113
 
114
114
  Set `"episodic_memory": true` in the duplex profile and run the local tool portal with `--episodic-memory`. Use `--episodic-memory-root` to point at the existing adapter's private owner store. The portal retains committed transcripts, spoken replies, and tool receipt summaries through the adapter's episode recorder. Natural recall requests search that store. An optional `--episodic-embeddings-cpu` mode uses the configured local Ollama embedding model on CPU for semantic retrieval.
115
115
 
116
+ With duplex enabled, say “Let me hear your thoughts” or “Enable the thinking voice” to turn on progress cues. Say “Turn the thinking voice off” to disable them. The `speak-thinking` tool saves the setting across restarts. During reasoning, the same Talker and configured voice stream one short public progress cue. The harness plays frames as they arrive, lowers their bandwidth and gain, and scales tempo and pitch with the measured reasoning token rate. The cue uses timing metadata only. Speech interruption or a ready answer stops the cue. Enabled mode adds reasoning and cue generation, which can delay the final response. The acoustic bridge retries a setting command only when its first decode includes an extra sentence.
117
+
116
118
  With the 9B profile, add `--image /path/to/image.png` to attach the current contents of a JPEG or PNG file at commit. The vision projector receives the image pixels alongside the transcribed request. The backplane carries the resulting visual evidence through that turn's structured tool calls. Keep the image at or below 8 MiB.
117
119
 
118
120
  ## Inspect and use tools
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "phosphor-harness",
3
- "version": "0.4.5",
3
+ "version": "0.4.6",
4
4
  "description": "Local multimodal voice, vision and tool harness for Phosphor",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sophon-standalone-harness"
7
- version = "0.4.4"
7
+ version = "0.4.6"
8
8
  description = "Phosphor voice, vision and tool harness"
9
9
  requires-python = ">=3.10"
10
10
  license = {text = "Apache-2.0"}
@@ -7,8 +7,10 @@ import os
7
7
  import select
8
8
  import signal
9
9
  import subprocess
10
+ from threading import Event
10
11
  import time
11
12
 
13
+ import httpx
12
14
  import numpy as np
13
15
  from training_suite.models.native_turn import NativeAssistantTurn
14
16
  from training_suite.sophon_acoustic_session import (
@@ -19,6 +21,7 @@ from training_suite.sophon_vad import SophonVoiceBoundaries
19
21
 
20
22
  from .episode_recording import EpisodeRecorder
21
23
  from .pulse_audio import AudioRouteChanged, _inventory, echo_cancel, restore_capture, select_devices
24
+ from .speak_thinking import LiveProgressCue, TOOL_NAME as THINKING_TOOL
22
25
  from .terminal_input import PASSWORD_REQUEST, TERMINAL_HANDLE
23
26
 
24
27
 
@@ -76,6 +79,9 @@ class _Turn:
76
79
  first_pcm: bool = False
77
80
  ended: bool = False
78
81
  failed: bool = False
82
+ reasoning: tuple[float, float] | None = None
83
+ progress_cancelled: Event = field(default_factory=Event)
84
+ progress_cue: LiveProgressCue | None = None
79
85
 
80
86
  def close_segment(self):
81
87
  if self.speech and self.speech[-1].end is None:
@@ -112,7 +118,7 @@ class DuplexVoice:
112
118
  """Keep a single generation lane while input and speaker output remain independent."""
113
119
 
114
120
  def __init__(self, profile, runtime, embed, tools, boundary, player, password_reply, log, *,
115
- history=None, recorder=None):
121
+ history=None, recorder=None, progress_enabled=False):
116
122
  self.profile, self.runtime, self.embed, self.tools = profile, runtime, embed, tools
117
123
  self.boundary, self.start_player, self.password_reply, self.log = boundary, player, password_reply, log
118
124
  self.history = history if history is not None else deque(maxlen=6)
@@ -124,6 +130,9 @@ class DuplexVoice:
124
130
  raise ValueError("playback_prebuffer_ms must be an integer between 0 and 1000")
125
131
  self.prebuffer_bytes = prebuffer_ms * PLAYBACK_BYTES_PER_SECOND // 1_000
126
132
  self.player = None
133
+ self.progress_enabled = progress_enabled
134
+ self.progress_player = None
135
+ self.progress_audio = bytearray()
127
136
  self.prefix = b""
128
137
  self.speaking = False
129
138
  self.number = 0
@@ -140,7 +149,12 @@ class DuplexVoice:
140
149
  if turn is None or turn.number != messages[-1].get("voice_turn"):
141
150
  return
142
151
  turn.pcm = (turn.prefix + media)[-960_000:]
143
- with self.runtime.backplane.interruptible(cancelled):
152
+ def progress(rate):
153
+ if turn.committed_at is not None and not cancelled.is_set():
154
+ turn.reasoning = (time.monotonic(), rate)
155
+
156
+ options = {"progress": progress} if self.progress_enabled else {}
157
+ with self.runtime.backplane.interruptible(cancelled, **options):
144
158
  if turn.password is not None:
145
159
  if await_commit() and not cancelled.is_set():
146
160
  reply = self.password_reply(turn.pcm, turn.password)
@@ -156,8 +170,13 @@ class DuplexVoice:
156
170
  max_tool_rounds=self.runtime.backplane.tool_rounds, language=self.profile["language"],
157
171
  ):
158
172
  turn.heard = model_audio.user_text or ""
159
- if isinstance(event, NativeAssistantTurn) and event.calls:
160
- turn.launched_tools = True
173
+ if isinstance(event, NativeAssistantTurn):
174
+ if event.text:
175
+ turn.progress_cancelled.set()
176
+ if turn.progress_cue is not None:
177
+ turn.progress_cue.thread.join(timeout=0.10)
178
+ if event.calls:
179
+ turn.launched_tools = True
161
180
  yield event
162
181
  finally:
163
182
  turn.heard = model_audio.user_text or ""
@@ -173,6 +192,7 @@ class DuplexVoice:
173
192
  self.log(event="draft_started", generation=turn.generation)
174
193
 
175
194
  def _stop_player(self):
195
+ self._stop_progress()
176
196
  self.pending_audio.clear()
177
197
  if self.player is None:
178
198
  return
@@ -182,6 +202,58 @@ class DuplexVoice:
182
202
  player.stdin.close()
183
203
  player.wait(timeout=3)
184
204
 
205
+ def _stop_progress(self):
206
+ if self.turn is not None:
207
+ self.turn.progress_cancelled.set()
208
+ self.progress_audio.clear()
209
+ if self.progress_player is not None:
210
+ player, self.progress_player = self.progress_player, None
211
+ if player.poll() is None:
212
+ player.kill()
213
+ player.stdin.close()
214
+ player.wait(timeout=3)
215
+
216
+ def _play_progress(self, turn):
217
+ if turn.progress_cancelled.is_set() or turn.ended:
218
+ self._stop_progress()
219
+ return
220
+ if turn.progress_cue is None:
221
+ if turn.reasoning is None or time.monotonic() - turn.reasoning[0] >= 0.45:
222
+ return
223
+ turn.progress_cue = LiveProgressCue(self.runtime.speech, self.profile["language"],
224
+ turn.reasoning[1], turn.progress_cancelled)
225
+ cue = turn.progress_cue
226
+ if not self.progress_audio:
227
+ self.progress_audio.extend(cue.next_frame())
228
+ if not self.progress_audio:
229
+ if not cue.thread.is_alive():
230
+ if cue.failed:
231
+ self.log(event="progress_voice_unavailable", generation=turn.generation)
232
+ if self.progress_player is not None and not self.progress_player.stdin.closed:
233
+ self.progress_player.stdin.close()
234
+ if self.progress_player is None or self.progress_player.poll() is not None:
235
+ self._stop_progress()
236
+ return
237
+ if self.progress_player is None:
238
+ try:
239
+ self.progress_player = self.start_player()
240
+ os.set_blocking(self.progress_player.stdin.fileno(), False)
241
+ except OSError:
242
+ self._stop_progress()
243
+ self.log(event="progress_voice_unavailable", generation=turn.generation)
244
+ return
245
+ self.log(event="progress_voice", generation=turn.generation, reasoning_tokens_per_second=round(cue.rate, 2),
246
+ speed=round(cue.speed, 2), gain_db=-5,
247
+ first_frame_s=round(time.monotonic() - cue.started, 3))
248
+ try:
249
+ written = os.write(self.progress_player.stdin.fileno(), self.progress_audio)
250
+ except BlockingIOError:
251
+ return
252
+ except BrokenPipeError:
253
+ self._stop_progress()
254
+ return
255
+ del self.progress_audio[:written]
256
+
185
257
  def _speech_started(self, resumed):
186
258
  old = self.turn
187
259
  self.session.speech_started()
@@ -189,6 +261,7 @@ class DuplexVoice:
189
261
  self.speaking = True
190
262
  if old is None:
191
263
  return
264
+ old.progress_cancelled.set()
192
265
  if old.committed_at is None:
193
266
  self.log(event="draft_revised", generation=old.generation)
194
267
  return
@@ -253,6 +326,8 @@ class DuplexVoice:
253
326
  elif isinstance(event, NativeToolResult):
254
327
  turn.messages.append(event.as_message())
255
328
  self.log(event="tool_result", name=event.call.name, status=event.status, generation=turn.generation)
329
+ if event.call.name == THINKING_TOOL and event.status == "ok" and isinstance(event.data, dict):
330
+ self.progress_enabled = event.data.get("enabled") is True
256
331
  if event.call.name == "terminal_session" and event.status == "ok" and isinstance(event.data, dict):
257
332
  handle = event.data.get("terminal_password_prompt")
258
333
  if isinstance(handle, str) and TERMINAL_HANDLE.fullmatch(handle):
@@ -278,6 +353,7 @@ class DuplexVoice:
278
353
  if self.pending_audio and (self.player is not None or turn.ended or waited
279
354
  or len(self.pending_audio) >= self.prebuffer_bytes):
280
355
  if self.player is None:
356
+ self._stop_progress()
281
357
  self.player = self.start_player()
282
358
  os.set_blocking(self.player.stdin.fileno(), False)
283
359
  turn.playback_started = time.monotonic()
@@ -298,9 +374,12 @@ class DuplexVoice:
298
374
  after_turn_commit_s=round(time.monotonic() - turn.committed_at, 3))
299
375
  turn.submitted += written
300
376
  del self.pending_audio[:written]
377
+ elif self.player is None:
378
+ self._play_progress(turn)
301
379
  if turn.ended and self.player is not None and not self.pending_audio and not self.player.stdin.closed:
302
380
  self.player.stdin.close()
303
381
  if turn.ended and (self.player is None or self.player.poll() is not None):
382
+ self._stop_progress()
304
383
  if not turn.failed and turn.first_pcm and (self.player is None or self.player.returncode == 0):
305
384
  self._retain(turn.history())
306
385
  if len(turn.prompts) == 1 and turn.messages and turn.messages[-1]["content"] == PASSWORD_REQUEST:
@@ -366,8 +445,13 @@ def run_microphone(source, sink, channels, channel, vad, profile, runtime, embed
366
445
  with echo_cancel(*physical, with_aec) as (microphone, speaker):
367
446
  vad.reset()
368
447
  detector = SophonVoiceBoundaries(vad.stream_probabilities, start_ms=128)
448
+ try:
449
+ progress_enabled = tools.thinking_status()
450
+ except (httpx.HTTPError, ValueError):
451
+ progress_enabled = False
369
452
  loop = DuplexVoice(profile, runtime, embed, tools, detector, lambda: player(speaker),
370
- password_reply, log, history=history, recorder=recorder)
453
+ password_reply, log, history=history, recorder=recorder,
454
+ progress_enabled=progress_enabled)
371
455
 
372
456
  def verify_route(pid):
373
457
  sources = _inventory("sources")
@@ -13,6 +13,7 @@ from io import BytesIO
13
13
  import json
14
14
  import logging
15
15
  import re
16
+ import time
16
17
  from urllib.parse import urlsplit
17
18
  import wave
18
19
  from uuid import uuid4
@@ -26,6 +27,7 @@ from training_suite.sophon_speech import validate_speech_text
26
27
  from training_suite.training.audio_bridge_training import MEDIA_INSTRUCTION, MEDIA_SYSTEM_PROMPT
27
28
 
28
29
  from .regex_tools import tighten_quoted_escapes
30
+ from .speak_thinking import ProgressChatStream, TOOL_NAME as THINKING_TOOL, requested_setting
29
31
  from .tools import FILE_TOOL_ROUNDS, VOICE_TOOL_ROUNDS, active_tools, current_turn, requested_tools
30
32
  from .terminal_input import PASSWORD_REQUEST, TERMINAL_HANDLE
31
33
 
@@ -284,6 +286,17 @@ def _current_date_turn(receipts):
284
286
  return NativeAssistantTurn("", (NativeToolCall(uuid4().hex, "get_current_time", {}),))
285
287
 
286
288
 
289
+ def _thinking_setting_turn(receipts, enabled):
290
+ for entry in reversed(receipts):
291
+ if entry["role"] == "tool" and entry.get("name") == THINKING_TOOL:
292
+ envelope = json.loads(entry["content"])
293
+ result = envelope.get("data") or {}
294
+ if envelope.get("status") == "ok" and result.get("enabled") is enabled and result.get("durable") is True:
295
+ return NativeAssistantTurn("The progress voice is " + ("on." if enabled else "off."), ())
296
+ return NativeAssistantTurn("I couldn't confirm the progress voice setting.", ())
297
+ return NativeAssistantTurn("", (NativeToolCall(uuid4().hex, THINKING_TOOL, {"enabled": enabled}),))
298
+
299
+
287
300
  @dataclass(frozen=True)
288
301
  class _ReplacementPrecondition:
289
302
  old: str
@@ -399,6 +412,7 @@ class OrnithBackplane:
399
412
  self.client = httpx.Client(base_url=url, timeout=90, trust_env=False, transport=transport)
400
413
  self.transport = transport
401
414
  self._cancel = ContextVar("ornith_cancel", default=None)
415
+ self._progress = ContextVar("ornith_progress", default=None)
402
416
 
403
417
  def __enter__(self):
404
418
  return self
@@ -407,12 +421,26 @@ class OrnithBackplane:
407
421
  self.client.close()
408
422
 
409
423
  @contextmanager
410
- def interruptible(self, cancelled):
424
+ def interruptible(self, cancelled, *, progress=None):
411
425
  token = self._cancel.set(cancelled)
426
+ progress_token = self._progress.set(progress)
412
427
  try:
413
428
  yield
414
429
  finally:
415
430
  self._cancel.reset(token)
431
+ self._progress.reset(progress_token)
432
+
433
+ @staticmethod
434
+ async def _wait_connection(awaitable, cancelled):
435
+ request = asyncio.create_task(awaitable)
436
+ while not request.done() and not cancelled.is_set():
437
+ await asyncio.wait((request,), timeout=0.025)
438
+ if cancelled.is_set():
439
+ request.cancel()
440
+ with suppress(asyncio.CancelledError, httpx.HTTPError):
441
+ await request
442
+ raise OrnithTurnInterrupted()
443
+ return request.result()
416
444
 
417
445
  def _post(self, path, **options):
418
446
  cancelled = self._cancel.get()
@@ -424,25 +452,55 @@ class OrnithBackplane:
424
452
  trust_env=False, transport=self.transport) as client:
425
453
  if cancelled.is_set():
426
454
  raise OrnithTurnInterrupted()
427
- request = asyncio.create_task(client.post(path, **options))
428
- while not request.done() and not cancelled.is_set():
429
- await asyncio.wait((request,), timeout=0.025)
430
- if cancelled.is_set():
431
- request.cancel()
432
- with suppress(asyncio.CancelledError, httpx.HTTPError):
433
- await request
434
- raise OrnithTurnInterrupted()
435
- return request.result()
455
+ return await self._wait_connection(client.post(path, **options), cancelled)
436
456
 
437
457
  return asyncio.run(post())
438
458
 
439
- def _chat(self, messages, *, max_tokens, **options):
459
+ def _stream_chat(self, payload, progress):
460
+ cancelled = self._cancel.get()
461
+
462
+ async def decode():
463
+ async with httpx.AsyncClient(base_url=self.client.base_url, timeout=self.client.timeout,
464
+ trust_env=False, transport=self.transport) as client:
465
+ request = client.build_request("POST", "/v1/chat/completions", json={
466
+ **payload, "stream": True, "timings_per_token": True,
467
+ })
468
+ response = await self._wait_connection(client.send(request, stream=True), cancelled)
469
+ try:
470
+ if not response.is_success:
471
+ await self._wait_connection(response.aread(), cancelled)
472
+ return response
473
+ stream = ProgressChatStream(progress)
474
+ lines = response.aiter_lines()
475
+ while True:
476
+ try:
477
+ line = await self._wait_connection(lines.__anext__(), cancelled)
478
+ except StopAsyncIteration:
479
+ break
480
+ if line == "data: [DONE]":
481
+ break
482
+ if line.startswith("data: "):
483
+ stream.feed(json.loads(line[6:]))
484
+ return httpx.Response(response.status_code, json=stream.response(), request=request)
485
+ finally:
486
+ await response.aclose()
487
+
488
+ return asyncio.run(decode())
489
+
490
+ def _chat(self, messages, *, max_tokens, narrate_progress=False, request_timeout=None, **options):
491
+ progress = self._progress.get() if narrate_progress else None
492
+ if progress is not None:
493
+ options["chat_template_kwargs"] = {**options.get("chat_template_kwargs", {}), "enable_thinking": True}
494
+ options.setdefault("reasoning_budget_tokens", 64)
440
495
  try:
441
496
  while True:
442
- response = self._post("/v1/chat/completions", json={
497
+ payload = {
443
498
  "model": self.model, "messages": messages, "max_tokens": max_tokens,
444
499
  "chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, **options,
445
- })
500
+ }
501
+ request_options = {} if request_timeout is None else {"timeout": request_timeout}
502
+ response = (self._stream_chat(payload, progress) if progress is not None else
503
+ self._post("/v1/chat/completions", json=payload, **request_options))
446
504
  if not _context_rejected(response):
447
505
  response.raise_for_status()
448
506
  break
@@ -504,6 +562,30 @@ class OrnithBackplane:
504
562
  return {"valid": False}
505
563
  return parse_tagged_audio_evidence("".join(f"<{name}>{result[name]}</{name}>" for name in properties))
506
564
 
565
+ def _confirm_spoken_setting(self, audio, command):
566
+ started = time.monotonic()
567
+ agreed = False
568
+ try:
569
+ message = self._chat([
570
+ {"role": "system", "content": "Check the entire audio. Set exact to true only if the spoken words "
571
+ "match the supplied command and there is no additional spoken sentence."},
572
+ {"role": "user", "content": [audio, {"type": "text", "text": command}]},
573
+ ], max_tokens=20, request_timeout=2.5, cache_prompt=False, response_format={
574
+ "type": "json_schema", "json_schema": {"name": "spoken_command", "strict": True, "schema": {
575
+ "type": "object", "properties": {"exact": {"type": "boolean"}},
576
+ "required": ["exact"], "additionalProperties": False,
577
+ }},
578
+ })
579
+ agreed = _arguments(message.get("content")).get("exact") is True
580
+ except RuntimeError as error:
581
+ if not isinstance(error.__cause__, httpx.TimeoutException):
582
+ raise
583
+ except ValueError:
584
+ pass
585
+ logging.getLogger(__name__).info("Voice setting verification took %.3fs (confirmed=%s)",
586
+ time.monotonic() - started, agreed)
587
+ return agreed
588
+
507
589
  def recognize_password(self, pcm):
508
590
  return self._recognize(pcm)["speech_transcript"]
509
591
 
@@ -525,7 +607,12 @@ class OrnithBackplane:
525
607
  turn.pcm = b""
526
608
  return
527
609
  evidence = self._recognize(turn.pcm)
528
- turn.user_text = _spoken_extensions(evidence["speech_transcript"])
610
+ transcript = evidence["speech_transcript"]
611
+ parts = re.split(r"(?<=[.!?])\s+", transcript, maxsplit=1)
612
+ if (len(parts) == 2 and requested_setting(parts[0]) is not None
613
+ and self._confirm_spoken_setting(_audio_part(turn.pcm), parts[0])):
614
+ transcript = parts[0]
615
+ turn.user_text = _spoken_extensions(transcript)
529
616
  if observation := evidence["audio_observation"]:
530
617
  turn.user_text += f"\n\nBackground sounds: {observation}"
531
618
  turn.pcm = b""
@@ -609,7 +696,7 @@ class OrnithBackplane:
609
696
  if cancelled.is_set():
610
697
  return None
611
698
  try:
612
- message = self._chat(rendered, max_tokens=max_new_tokens, **options)
699
+ message = self._chat(rendered, max_tokens=max_new_tokens, narrate_progress=True, **options)
613
700
  if cancelled.is_set():
614
701
  return None
615
702
  turn = validate_visible_turn(self._decode(message, tools))
@@ -685,10 +772,13 @@ class OrnithBackplane:
685
772
  rounds = [entry["tool_calls"] for entry in current if entry.get("tool_calls")]
686
773
  requests = [message["content"] for message in rendered if message["role"] == "user"]
687
774
  request = requests[-1] if requests else None
688
- date_query = request.partition("\n\nBackground sounds:")[0] if request and media and not media.visual_evidence else request
689
- if (date_query and _DIRECT_DATE.fullmatch(date_query.strip().replace("’", "'").rstrip(" .?!"))
775
+ spoken_request = request.partition("\n\nBackground sounds:")[0] if request and media and not media.visual_evidence else request
776
+ if (spoken_request and _DIRECT_DATE.fullmatch(spoken_request.strip().replace("’", "'").rstrip(" .?!"))
690
777
  and any(tool["function"]["name"] == "get_current_time" for tool in tools or ())):
691
778
  return _current_date_turn(current)
779
+ thinking_setting = requested_setting(spoken_request)
780
+ if thinking_setting is not None and any(tool["function"]["name"] == THINKING_TOOL for tool in tools or ()):
781
+ return _thinking_setting_turn(current, thinking_setting)
692
782
  named_tools = requested_tools(tools or [], request)
693
783
  recall_requested = bool(request and _RECALL_REQUEST.search(request) and not rounds
694
784
  and any(tool["function"]["name"] == "episodic_search" for tool in tools or ()))
@@ -13,6 +13,7 @@ import sys
13
13
  from unittest.mock import patch
14
14
  from uuid import UUID
15
15
 
16
+ from .speak_thinking import read_setting, write_setting
16
17
  from .terminal_input import terminal_with_spoken_input
17
18
 
18
19
 
@@ -140,7 +141,7 @@ def make_app(checkout: Path, state: Path, workspace: Path, *, enable_camera: boo
140
141
  path = request.path
141
142
  if path not in {"/api/tools", "/api/status", "/api/voice/camera-qr",
142
143
  "/api/harness/attachments", "/api/harness/location", "/api/harness/camera",
143
- "/api/harness/terminal-password", "/api/harness/memory"} and not path.startswith(
144
+ "/api/harness/terminal-password", "/api/harness/memory", "/api/harness/speak-thinking"} and not path.startswith(
144
145
  ("/api/tools/", "/api/mcp/servers", "/api/files/")
145
146
  ):
146
147
  abort(404)
@@ -192,6 +193,22 @@ def make_app(checkout: Path, state: Path, workspace: Path, *, enable_camera: boo
192
193
  if not hmac.compare_digest(request.cookies.get("omni_portal_session", ""), owner):
193
194
  abort(403)
194
195
 
196
+ @app.route("/api/harness/speak-thinking", methods=["GET", "POST"])
197
+ def speak_thinking():
198
+ require_voice_session()
199
+ settings = state / "speak-thinking.json"
200
+ if request.method == "POST":
201
+ if not request.content_length or request.content_length > 1024:
202
+ abort(400)
203
+ data = request.get_json(silent=True)
204
+ if not isinstance(data, dict) or set(data) - {"enabled"}:
205
+ abort(400)
206
+ if "enabled" in data:
207
+ if type(data["enabled"]) is not bool:
208
+ abort(400)
209
+ write_setting(settings, data["enabled"])
210
+ return jsonify({"enabled": read_setting(settings), "durable": True})
211
+
195
212
  @app.get("/api/harness/memory")
196
213
  def voice_memory_status():
197
214
  require_voice_session()
@@ -0,0 +1,183 @@
1
+ """Persist the optional progress voice and render its local, low-volume cues."""
2
+
3
+ from collections import deque
4
+ from contextlib import closing
5
+ import json
6
+ import os
7
+ from queue import Empty, SimpleQueue
8
+ import re
9
+ from tempfile import NamedTemporaryFile
10
+ from threading import Thread
11
+ import time
12
+
13
+ TOOL_NAME = "speak-thinking"
14
+ SPEAK_THINKING_TOOL = {"type": "function", "function": {
15
+ "name": TOOL_NAME,
16
+ "description": "Turn the audible progress voice on or off, or read its durable setting.",
17
+ "parameters": {"type": "object", "properties": {"enabled": {"type": "boolean"}},
18
+ "additionalProperties": False},
19
+ }}
20
+
21
+ _ENABLE = re.compile(
22
+ r"(?:please )?(?:(?:let me|can i) hear (?:your thoughts|you think|your thinking|what you're thinking)|think out loud|"
23
+ r"(?:speak|say) (?:your )?(?:thoughts|thinking)(?: out loud| aloud)?|"
24
+ r"(?:turn on|enable) (?:the )?(?:speak[- ]thinking(?: tool)?|thinking voice|progress voice)|"
25
+ r"turn (?:the )?(?:thinking voice|speak[- ]thinking) on)(?: please)?", re.I,
26
+ )
27
+ _DISABLE = re.compile(
28
+ r"(?:please )?(?:stop (?:speaking|saying) (?:your )?(?:thoughts|thinking)|keep your (?:thoughts|thinking) quiet|"
29
+ r"(?:turn off|disable|mute|stop) (?:the )?(?:speak[- ]thinking(?: tool)?|thinking voice|progress voice)|"
30
+ r"turn (?:the )?(?:thinking voice|speak[- ]thinking) off)(?: please)?", re.I,
31
+ )
32
+
33
+
34
+ def requested_setting(text):
35
+ if not isinstance(text, str):
36
+ return None
37
+ clean = " ".join(text.strip().replace("’", "'").rstrip(".!?").split())
38
+ if _ENABLE.fullmatch(clean):
39
+ return True
40
+ if _DISABLE.fullmatch(clean):
41
+ return False
42
+ return None
43
+
44
+
45
+ def read_setting(path):
46
+ try:
47
+ return json.loads(path.read_text()).get("enabled") is True
48
+ except FileNotFoundError:
49
+ return False
50
+
51
+
52
+ def write_setting(path, enabled):
53
+ with NamedTemporaryFile(dir=path.parent, mode="w", prefix=".speak-thinking.", delete=False) as file:
54
+ json.dump({"enabled": enabled}, file)
55
+ file.write("\n")
56
+ os.replace(file.name, path)
57
+
58
+
59
+ class ReasoningRate:
60
+ """Smooth the time between reasoning outputs without retaining their text."""
61
+
62
+ def __init__(self):
63
+ self.samples = deque()
64
+
65
+ def observe(self, count, now=None):
66
+ stamp = time.monotonic() if now is None else now
67
+ self.samples.append((stamp, count))
68
+ while len(self.samples) > 1 and self.samples[0][0] < stamp - 1.25:
69
+ self.samples.popleft()
70
+ elapsed = stamp - self.samples[0][0]
71
+ if elapsed < 0.35:
72
+ return None
73
+ return sum(count for _, count in list(self.samples)[1:]) / elapsed
74
+
75
+
76
+ class ProgressChatStream:
77
+ """Assemble public chat fields and count private reasoning tokens without storing them."""
78
+
79
+ def __init__(self, on_rate):
80
+ self.on_rate = on_rate
81
+ self.rate = ReasoningRate()
82
+ self.predicted = 0
83
+ self.parts = []
84
+ self.calls = {}
85
+ self.finish_reason = None
86
+
87
+ def feed(self, frame):
88
+ choices = frame.get("choices") or ()
89
+ if not choices:
90
+ return
91
+ choice = choices[0]
92
+ delta = choice.get("delta") or {}
93
+ predicted = (frame.get("timings") or {}).get("predicted_n")
94
+ if type(predicted) is int and predicted > self.predicted:
95
+ if delta.get("reasoning_content"):
96
+ rate = self.rate.observe(predicted - self.predicted)
97
+ if rate is not None:
98
+ self.on_rate(rate)
99
+ self.predicted = predicted
100
+ if delta.get("content"):
101
+ self.parts.append(delta["content"])
102
+ for fragment in delta.get("tool_calls") or ():
103
+ call = self.calls.setdefault(fragment["index"], {"type": "function", "function": {"name": "", "arguments": ""}})
104
+ if fragment.get("id"):
105
+ call["id"] = fragment["id"]
106
+ for key, value in (fragment.get("function") or {}).items():
107
+ if key in call["function"] and isinstance(value, str):
108
+ call["function"][key] += value
109
+ if choice.get("finish_reason"):
110
+ self.finish_reason = choice["finish_reason"]
111
+
112
+ def response(self):
113
+ message = {"role": "assistant", "content": "".join(self.parts) or None}
114
+ if self.calls:
115
+ message["tool_calls"] = [self.calls[index] for index in sorted(self.calls)]
116
+ return {"choices": [{"finish_reason": self.finish_reason, "message": message}]}
117
+
118
+
119
+ def playback_speed(tokens_per_second):
120
+ return min(2.1, max(1.12, 1 + tokens_per_second / 32))
121
+
122
+
123
+ class ProgressPCM:
124
+ """Lower the cue bandwidth and raise pitch and tempo as frames arrive."""
125
+
126
+ gain = 10 ** (-5 / 20)
127
+
128
+ def __init__(self, speed):
129
+ self.step = speed / 2 # Pair 24 kHz source samples, then resample to 24 kHz.
130
+ self.position = 0.0
131
+ self.carry = b""
132
+
133
+ def convert(self, pcm):
134
+ import numpy as np
135
+
136
+ pcm = self.carry + pcm
137
+ end = len(pcm) & ~3
138
+ self.carry = pcm[end:]
139
+ samples = np.frombuffer(pcm[:end], dtype="<i2").reshape(-1, 2).mean(axis=1)
140
+ if not len(samples):
141
+ return b""
142
+ positions = np.arange(self.position, len(samples), self.step)
143
+ self.position += len(positions) * self.step - len(samples)
144
+ return (np.interp(positions, np.arange(len(samples)), samples) * self.gain).astype("<i2").tobytes()
145
+
146
+
147
+ class LiveProgressCue:
148
+ """Receive a short cue from the same resident Talker as the spoken answer."""
149
+
150
+ def __init__(self, speech, language, rate, cancelled):
151
+ self.rate = rate
152
+ self.speed = playback_speed(rate)
153
+ self.cancelled = cancelled
154
+ self.audio = SimpleQueue()
155
+ self.failed = False
156
+ self.started = time.monotonic()
157
+ self.thread = Thread(target=self._synthesize, args=(speech, language), daemon=True)
158
+ self.thread.start()
159
+
160
+ def _synthesize(self, speech, language):
161
+ from training_suite.sophon_speech import SophonSpeechError
162
+
163
+ converter = ProgressPCM(self.speed)
164
+ remaining = 72_000 # At most 1.5 seconds of original Talker audio per turn.
165
+ text = {"zh": "请稍等。", "ja": "少々お待ちください。"}.get(language.lower().split("-")[0], "One moment.")
166
+ try:
167
+ with closing(speech.frames(text, language, cancelled=self.cancelled)) as frames:
168
+ for pcm in frames:
169
+ if self.cancelled.is_set():
170
+ return
171
+ clip = pcm[:remaining]
172
+ remaining -= len(clip)
173
+ self.audio.put(converter.convert(clip))
174
+ if not remaining:
175
+ return
176
+ except (OSError, SophonSpeechError, ValueError):
177
+ self.failed = not self.cancelled.is_set()
178
+
179
+ def next_frame(self):
180
+ try:
181
+ return self.audio.get_nowait()
182
+ except Empty:
183
+ return b""
@@ -12,6 +12,7 @@ from urllib.parse import quote, urlsplit
12
12
 
13
13
  import httpx
14
14
 
15
+ from .speak_thinking import SPEAK_THINKING_TOOL, TOOL_NAME as THINKING_TOOL
15
16
  from .news import NEWS_TOOL, get_headlines
16
17
  from .portal_server import read_token
17
18
  from .regex_tools import REGEX_BUILD_TOOL, REGEX_EXAMPLE_TOOL, REGEX_FIELDS_TOOL, build_regex, infer_workspace_field_regex, read_regex_example
@@ -180,6 +181,7 @@ class PortalTools:
180
181
  if "tool_search" not in tools:
181
182
  raise ValueError("the tool API does not expose typed tool discovery")
182
183
  tools.setdefault("get_news_headlines", NEWS_TOOL)
184
+ tools.setdefault(THINKING_TOOL, SPEAK_THINKING_TOOL)
183
185
  tools.setdefault("regex_build", REGEX_BUILD_TOOL)
184
186
  if "workspace_file" in tools:
185
187
  tools.setdefault("regex_example", REGEX_EXAMPLE_TOOL)
@@ -208,6 +210,9 @@ class PortalTools:
208
210
  def memory_status(self) -> dict:
209
211
  return self._request("GET", "/api/harness/memory", timeout=4)
210
212
 
213
+ def thinking_status(self) -> bool:
214
+ return self._request("GET", "/api/harness/speak-thinking", timeout=4).get("enabled") is True
215
+
211
216
  def remember_episode(self, episode: dict) -> dict:
212
217
  return self._request("POST", "/api/harness/memory", json=episode, timeout=4)
213
218
 
@@ -259,6 +264,11 @@ class PortalTools:
259
264
  return {"ok": False, "error": "unknown_tool"}
260
265
  if name == "get_news_headlines":
261
266
  return get_headlines(arguments)
267
+ if name == THINKING_TOOL:
268
+ try:
269
+ return self._request("POST", "/api/harness/speak-thinking", json=arguments, timeout=4)
270
+ except (httpx.HTTPError, ValueError):
271
+ return {"ok": False, "error": "progress_voice_setting_unavailable"}
262
272
  if name == "regex_build":
263
273
  return build_regex(arguments)
264
274
  if name == "regex_example":