phosphor-harness 0.4.4 → 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.
@@ -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,8 +12,10 @@ 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
18
+ from .regex_tools import REGEX_BUILD_TOOL, REGEX_EXAMPLE_TOOL, REGEX_FIELDS_TOOL, build_regex, infer_workspace_field_regex, read_regex_example
17
19
  from .wifi import WIFI_SCAN_TOOL, wifi_observation
18
20
 
19
21
  CORE_TOOLS = (
@@ -21,6 +23,7 @@ CORE_TOOLS = (
21
23
  "safe_math_eval", "scan_wifi_networks", "get_news_headlines", "web_search", "web_fetch", "request_camera_view",
22
24
  )
23
25
  VOICE_TOOL_ROUNDS = 6
26
+ FILE_TOOL_ROUNDS = 8
24
27
  REPEATABLE_READS = frozenset({
25
28
  "get_current_time", "get_system_snapshot", "get_user_location", "get_portal_capabilities",
26
29
  "safe_math_eval", "memory_read", "memory_search", "document_search", "session_search",
@@ -30,7 +33,10 @@ MAX_RESPONSE = 24 * 1024 * 1024
30
33
  MAX_RECEIPT = 12_000
31
34
  _NAME = re.compile(r"[A-Za-z0-9_.-]{1,128}\Z")
32
35
  _DEVICE_TOOLS = {"serial": "serial_io", "bluetooth_controllers": "bluetooth_io", "network": "network_io"}
33
- _TOOL_DIRECTIVE = re.compile(r"^\s*(?:please\s+)?(?:use|call|invoke|run)\s+(?:(?:your|the)\s+)?", re.I)
36
+ _TOOL_DIRECTIVE = re.compile(
37
+ r"(?:^|[.!?,;]\s+|\b(?:and|then)\s+)\s*(?:please\s+)?(?:use|call|invoke|run)\s+(?:(?:your|the)\s+)?`?",
38
+ re.I,
39
+ )
34
40
  _TOOL_ALIASES = {"safe_math_eval": "calculator"}
35
41
 
36
42
 
@@ -41,24 +47,26 @@ def current_turn(messages, audio_index):
41
47
  return messages[user_index + 1:]
42
48
 
43
49
 
44
- def requested_tool(definitions, request_text):
45
- """Match an explicit request to use a tool at the start of the user's turn."""
46
- if not isinstance(request_text, str) or not (directive := _TOOL_DIRECTIVE.match(request_text)):
47
- return None
48
- phrase = request_text[directive.end():].casefold().replace("_", " ")
50
+ def requested_tools(definitions, request_text):
51
+ """Match registered tool names explicitly invoked in the user's current turn."""
52
+ if not isinstance(request_text, str):
53
+ return set()
54
+ phrases = [request_text[match.end():].casefold().replace("_", " ")
55
+ for match in _TOOL_DIRECTIVE.finditer(request_text)]
56
+ names = set()
49
57
  for item in definitions:
50
58
  name = item["function"]["name"]
51
59
  labels = (name.casefold().replace("_", " "), _TOOL_ALIASES.get(name))
52
- if any(label and re.match(rf"{re.escape(label)}\b", phrase) for label in labels):
53
- return name
54
- return None
60
+ if any(re.match(rf"{re.escape(label)}\b", phrase)
61
+ for label in labels if label for phrase in phrases):
62
+ names.add(name)
63
+ return names
55
64
 
56
65
 
57
- def active_tools(definitions, messages, audio_index, *, explicitly_requested=None):
66
+ def active_tools(definitions, messages, audio_index, *, explicitly_requested=()):
58
67
  """Retain exact typed schemas revealed during the current committed turn."""
59
68
  chosen = set(CORE_TOOLS)
60
- if explicitly_requested:
61
- chosen.add(explicitly_requested)
69
+ chosen.update(explicitly_requested)
62
70
  for message in current_turn(messages, audio_index):
63
71
  if message.get("role") != "tool":
64
72
  continue
@@ -102,6 +110,21 @@ def _text_receipt(value, token: str):
102
110
  return value
103
111
 
104
112
 
113
+ def _compact_episodic_receipt(receipt):
114
+ if not isinstance(receipt.get("results"), list):
115
+ return receipt
116
+ fields = ("event_id", "episode", "modality", "actor", "authority", "occurred_at", "channels")
117
+ results = [{**{key: row[key] for key in fields if key in row}, "text": str(row.get("text", ""))[:1300]}
118
+ for row in receipt["results"] if isinstance(row, dict)]
119
+ facts = list(receipt.get("facts", ()))
120
+ compact = {**receipt, "results": results, "facts": facts}
121
+ while len(_json(compact)) > MAX_RECEIPT and facts:
122
+ facts.pop()
123
+ while len(_json(compact)) > MAX_RECEIPT and len(results) > 1:
124
+ results.pop()
125
+ return compact
126
+
127
+
105
128
  class PortalTools:
106
129
  """Use the authenticated tool API, independent of its language endpoint."""
107
130
 
@@ -158,6 +181,11 @@ class PortalTools:
158
181
  if "tool_search" not in tools:
159
182
  raise ValueError("the tool API does not expose typed tool discovery")
160
183
  tools.setdefault("get_news_headlines", NEWS_TOOL)
184
+ tools.setdefault(THINKING_TOOL, SPEAK_THINKING_TOOL)
185
+ tools.setdefault("regex_build", REGEX_BUILD_TOOL)
186
+ if "workspace_file" in tools:
187
+ tools.setdefault("regex_example", REGEX_EXAMPLE_TOOL)
188
+ tools.setdefault("regex_infer_fields", REGEX_FIELDS_TOOL)
161
189
  if "network_io" in tools:
162
190
  tools.setdefault("scan_wifi_networks", WIFI_SCAN_TOOL)
163
191
  return tools
@@ -179,6 +207,15 @@ class PortalTools:
179
207
  return self._request("DELETE", "/api/harness/location")
180
208
  return self._request("POST", "/api/harness/location", json=location)
181
209
 
210
+ def memory_status(self) -> dict:
211
+ return self._request("GET", "/api/harness/memory", timeout=4)
212
+
213
+ def thinking_status(self) -> bool:
214
+ return self._request("GET", "/api/harness/speak-thinking", timeout=4).get("enabled") is True
215
+
216
+ def remember_episode(self, episode: dict) -> dict:
217
+ return self._request("POST", "/api/harness/memory", json=episode, timeout=4)
218
+
182
219
  def submit_password(self, handle: str, password: str) -> bool:
183
220
  try:
184
221
  value = self._request("POST", "/api/harness/terminal-password",
@@ -227,6 +264,17 @@ class PortalTools:
227
264
  return {"ok": False, "error": "unknown_tool"}
228
265
  if name == "get_news_headlines":
229
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"}
272
+ if name == "regex_build":
273
+ return build_regex(arguments)
274
+ if name == "regex_example":
275
+ return read_regex_example(self.invoke)
276
+ if name == "regex_infer_fields":
277
+ return infer_workspace_field_regex(arguments, self.invoke)
230
278
  if name == "request_camera_view":
231
279
  return {"ok": False, "error": "camera_requires_visual_session",
232
280
  "message": "This camera request needs an active backplane with image input."}
@@ -243,6 +291,8 @@ class PortalTools:
243
291
  if standalone_wifi:
244
292
  value = wifi_observation(value)
245
293
  receipt = _text_receipt(value, self.token)
294
+ if name == "episodic_search":
295
+ receipt = _compact_episodic_receipt(receipt)
246
296
  serialized = _json(receipt)
247
297
  if len(serialized) > MAX_RECEIPT:
248
298
  # Keep executor status and routing information even when output is large.
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from collections import deque
6
+ import hashlib
6
7
  import inspect
7
8
  import json
8
9
  from pathlib import Path
@@ -31,6 +32,7 @@ from .tools import VOICE_TOOL_ROUNDS, PortalTools, active_tools
31
32
 
32
33
  RATE = 16_000
33
34
  FRAME = 512
35
+ SOPHON_VAD_SHA256 = "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3"
34
36
  _MARKER = re.compile(r"\ufdd0([0-9]+)\ufdd1")
35
37
 
36
38
 
@@ -48,6 +50,7 @@ class SpeechDetector:
48
50
  def reset(self):
49
51
  self.state = np.zeros((2, 1, 128), dtype=np.float32)
50
52
  self.context = np.zeros(64, dtype=np.float32)
53
+ self.pending = bytearray()
51
54
 
52
55
  def probability(self, audio) -> float:
53
56
  signal = np.concatenate((self.context, audio))[None, :]
@@ -57,6 +60,15 @@ class SpeechDetector:
57
60
  self.context = audio[-64:].copy()
58
61
  return float(score[0, 0])
59
62
 
63
+ def stream_probabilities(self, pcm: bytes) -> list[float]:
64
+ self.pending.extend(pcm)
65
+ values = []
66
+ while len(self.pending) >= FRAME * 2:
67
+ frame = np.frombuffer(self.pending[:FRAME * 2], dtype="<i2").astype(np.float32) / 32768
68
+ del self.pending[:FRAME * 2]
69
+ values.append(self.probability(frame))
70
+ return values
71
+
60
72
 
61
73
  def capture_turn(source: str, vad: SpeechDetector, channels: int, channel: int, *, after_playback=False,
62
74
  ready=None):
@@ -199,13 +211,13 @@ def start_player(sink):
199
211
  )
200
212
 
201
213
 
202
- def respond_to_password(audio, pending, runtime, tools, language, sink):
214
+ def password_status(pcm, pending, runtime, tools):
203
215
  handle, deadline = pending
204
216
  if time.monotonic() > deadline:
205
217
  status = "The password input expired. Ask me to check the terminal again."
206
218
  else:
207
219
  try:
208
- password = spoken_password(runtime.backplane.recognize_password(pcm16(audio)))
220
+ password = spoken_password(runtime.backplane.recognize_password(pcm))
209
221
  if password is None:
210
222
  status = "Password entry cancelled."
211
223
  elif tools.submit_password(handle, password):
@@ -214,6 +226,11 @@ def respond_to_password(audio, pending, runtime, tools, language, sink):
214
226
  status = "I couldn't confirm password submission. Ask me to check the terminal."
215
227
  except (RuntimeError, OSError, ValueError):
216
228
  status = "I couldn't transcribe the password. Ask me to check the terminal again."
229
+ return status
230
+
231
+
232
+ def respond_to_password(audio, pending, runtime, tools, language, sink):
233
+ status = password_status(pcm16(audio), pending, runtime, tools)
217
234
  player = start_player(sink)
218
235
  try:
219
236
  for frame in runtime.speech.frames(status, language):
@@ -245,7 +262,8 @@ def conduct_turn(audio, history, profile, runtime, embed, tools, *, sink=None, f
245
262
  try:
246
263
  for event in tools.run_committed_turn(
247
264
  runtime, messages, media=media, cancelled=cancel,
248
- max_new_tokens=profile["max_new_tokens"], max_tool_rounds=VOICE_TOOL_ROUNDS,
265
+ max_new_tokens=profile["max_new_tokens"],
266
+ max_tool_rounds=getattr(runtime.backplane, "tool_rounds", VOICE_TOOL_ROUNDS),
249
267
  language=profile["language"],
250
268
  ):
251
269
  if isinstance(event, NativeAssistantTurn):
@@ -302,9 +320,11 @@ def start(args):
302
320
  def embed(pcm, _cancel):
303
321
  return AudioTurn(pcm, image=image_part(args.image) if args.image is not None else None)
304
322
 
305
- with OrnithBackplane(args.ornith_url, args.ornith_model) as backplane:
323
+ transcription_url = profile.get("transcription_url")
324
+ with OrnithBackplane(args.ornith_url, args.ornith_model, transcription_url=transcription_url) as backplane:
306
325
  run_voice(args, profile, backplane, embed, {
307
- "backplane": args.ornith_model, "audio_path": "trained_transcript_bridge",
326
+ "backplane": args.ornith_model,
327
+ "audio_path": "configured_transcription_worker" if transcription_url else "trained_transcript_bridge",
308
328
  "image_attached": args.image is not None,
309
329
  })
310
330
  return
@@ -336,24 +356,34 @@ def run_voice(args, profile, backplane, embed, metadata):
336
356
  log(event="fixture_complete", fixture=path.name, reply=reply, tools=results)
337
357
  if args.probe_only:
338
358
  return
359
+ ready_file = getattr(args, "ready_file", None)
360
+
361
+ def listening(capture_source, playback_sink):
362
+ log(event="listening", source=capture_source, sink=playback_sink)
363
+ if ready_file is not None:
364
+ ready_file.touch()
365
+
366
+ if args.ornith_url and (args.duplex or profile.get("duplex", False)):
367
+ from .duplex_voice import run_microphone
368
+
369
+ if hashlib.sha256(args.vad.read_bytes()).hexdigest() != SOPHON_VAD_SHA256:
370
+ raise ValueError("duplex capture requires the pinned Sophon Silero model")
371
+ vad = SpeechDetector(args.vad)
372
+ run_microphone(args.source, args.sink, args.channels, args.channel, vad, profile, runtime, embed, tools,
373
+ start_player, lambda pcm, pending: password_status(pcm, pending, runtime, tools),
374
+ log, listening, with_aec=not args.echo_cancelled_input)
375
+ return
339
376
  source = args.source or subprocess.check_output(["pactl", "get-default-source"], text=True).strip()
340
377
  sink = args.sink or subprocess.check_output(["pactl", "get-default-sink"], text=True).strip()
341
- vad = SpeechDetector(args.vad)
342
- history = deque(maxlen=6)
343
- after_playback = False
344
- ready_file = getattr(args, "ready_file", None)
345
378
  if ready_file is not None:
346
379
  with start_player(sink) as player:
347
380
  player.communicate(input=bytes(960), timeout=10)
348
381
  if player.returncode:
349
382
  raise RuntimeError("speaker playback could not start")
350
-
351
- def listening():
352
- log(event="listening", source=source, sink=sink)
353
- if ready_file is not None:
354
- ready_file.touch()
355
-
356
- first_capture = listening
383
+ vad = SpeechDetector(args.vad)
384
+ history = deque(maxlen=6)
385
+ after_playback = False
386
+ first_capture = lambda: listening(source, sink)
357
387
  while True:
358
388
  audio = capture_turn(source, vad, args.channels, args.channel, after_playback=after_playback,
359
389
  ready=first_capture)