phosphor-harness 0.4.3 → 0.4.5

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
@@ -24,7 +24,7 @@ phosphor --manual --microphone alsa_input.example --speaker alsa_output.example
24
24
 
25
25
  ## Capabilities
26
26
 
27
- The pinned adapter exposes 47 tools in 20 families. The harness adds headlines and a direct Wi-Fi scan. The model starts with clock, approximate current location, system information, arithmetic, web access, and typed tool discovery. Discovery makes the complete catalog available by family and retains each selected family's exact schemas throughout the turn. The catalog includes session memory, shell execution, dedicated terminal sessions, workspace files, web, documents, notes and tasks, MCP, file delivery, browser, desktop, camera, and peripheral tools.
27
+ The pinned adapter exposes 47 tools in 20 families. The harness adds headlines, direct Wi-Fi scanning, and regex compilation. The model starts with clock, approximate current location, system information, arithmetic, web access, and typed tool discovery. Discovery makes the adapter's catalog available by family and retains each selected family's exact schemas throughout the turn. The catalog includes session memory, shell execution, dedicated terminal sessions, workspace files, web, documents, notes and tasks, MCP, file delivery, browser, desktop, camera, and peripheral tools.
28
28
 
29
29
  The harness preserves typed argument validation, native tool-result messages, and tool execution after the microphone turn commits. The tool server executes under the service user account, listens on loopback, and stores its bearer token in a private file.
30
30
 
@@ -105,6 +105,14 @@ sophon-harness --token-file runtime/state/portal.token \
105
105
 
106
106
  Speak into the microphone and pause for a response. Capture rearms after a short quiet interval following playback to reject the speaker's tail. Add `--probe /path/to/input.wav --probe-only` for an offline audio replay. Repeat `--probe` with `--probe-history` to replay a multi-turn conversation.
107
107
 
108
+ The 9B profile accepts `"duplex": true` or `--duplex` for spoken interruptions. The microphone remains open through generation and playback. The harness uses a private PulseAudio echo-cancelled source and sink and keeps the configured system defaults. Use `--echo-cancelled-input` when an external echo canceller or isolated audio route already supplies the input.
109
+
110
+ Automatic capture prefers a connected ReSpeaker and checks the actual PulseAudio stream route. The harness reconnects when the device disappears and rebinds a diverted capture stream. Use `--source` to select a specific device. Duplex playback buffers 500 ms of PCM by default. Set `playback_prebuffer_ms` in the profile to tune the startup buffer. An interruption clears buffered speech.
111
+
112
+ Duplex mode uses the pinned acoustic session's draft and commit controls. Speech that resumes before commit revises the draft with the retained audio. A barge-in cancels the active response, clears queued playback, and captures the new speech. An early interruption can merge the utterances before any tool starts. Tools and audible output wait for the committed turn. This profile uses Silero speech boundaries with the current backplane. The original speech model's learned turn and backchannel classification requires separate qualification.
113
+
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
+
108
116
  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.
109
117
 
110
118
  ## Inspect and use tools
@@ -119,18 +127,33 @@ Use `attach /path/to/document.pdf` with the same CLI options to index an operato
119
127
 
120
128
  Use `location --file /path/to/location.json` with the same CLI options to provide approximate location to the current session. A location object can contain a city, region, and country. Use `location --clear` to remove it. The tool reports unavailable when the session has no location.
121
129
 
122
- Tool failures retain the executor's reason, exit code, or approved alternatives. The model can correct invalid arguments or choose an indicated capability. A transient read can repeat the exact request once. A rejected schema is repaired before dispatch.
130
+ Tool failures retain the executor's reason, exit code, or approved alternatives. The model can correct invalid arguments or choose an indicated capability. A transient read can repeat the exact request once. A failed shell verification can be repeated once per verified file change. When the request explicitly calls for a recheck, the harness offers the exact verifier as the next native call. An explicit request for the shell's `stdin` field makes that field required. A redundant leading literal `printf` is removed when it supplies the same input. A rejected schema is repaired before dispatch.
131
+
132
+ For literal file replacements with a stated count, the harness preserves that precondition and constrains an authorized retry to the count reported by the executor. Regex requests can read a positive fixture through `regex_example` and use `regex_build` to assemble a Python pattern. For consistent `key=value` records, `regex_infer_fields` can infer the pattern from positive fixtures and capture declarations in the workspace specification. The model chooses the destination and the workspace tool saves the exact compiled pattern. The shell runs the requested validator.
133
+
134
+ Explicit requests naming registered tools expose those schemas for the current turn. A clear request to use a single supported read-only tool requires a native call with validated arguments. When that tool returns a capability error, the harness presents its suggested alternatives and typed discovery for the remainder of the recovery.
123
135
 
124
- An explicit request naming a registered tool exposes that tool for the current turn. Clear requests to use a supported read-only tool require a native call with validated arguments. When that tool returns a capability error, the harness presents its suggested alternatives and typed discovery for the remainder of the recovery.
136
+ Direct requests for today's date use the local clock tool and speak the calendar date from its receipt.
137
+
138
+ The automatic installer chooses an Orin context budget from available unified memory before loading the voice models. `--manual --context TOKENS` sets a fixed window. Other platforms default to 8,192 tokens unless a size is supplied.
125
139
 
126
140
  The voice profile accepts `tool_timeout_s` for longer calls. A transport timeout may leave the outcome unknown, so verify command effects before requesting another execution.
127
141
 
142
+ If the model server rejects a request at the context limit, the 9B backplane retries with a shorter conversation history. It keeps the system prompt, current request, and current tool receipts. Older tool transcripts are removed before older messages.
143
+
144
+ The 9B profile can set `transcription_url` to a loopback `/v1/audio/transcriptions` endpoint for ordinary user utterances. The bundled worker accepts a local Faster Whisper model path and requires an explicit device and compute type. This profile uses the selected worker's transcript for language and tool routing. The native acoustic bridge handles spoken terminal credentials.
145
+
146
+ ```bash
147
+ python scripts/run_transcription_worker.py --weights /path/to/local/whisper-checkpoint \
148
+ --device cpu --compute-type int8
149
+ ```
150
+
128
151
  ## Verification on Jetson AGX Orin
129
152
 
130
153
  - Ornith 9B answered six of seven recorded conversation turns correctly. It called the clock and calculator, returned 56 for eight times seven, and repeated a phrase only when asked to do so in this replay. It gave a wrong answer to the cow question. The earlier 4B replay answered two of the seven correctly and used a generation-only harness.
131
154
  - The separate spoken news replay called the headlines tool and produced a spoken answer. The documents replay discovered the typed search tool and reported the empty result. These tests exercised four paths through the 48-schema catalog. Other tools may require their own service setup and validation.
132
155
  - First non-silent PCM for the seven 9B replays ranged from 5.561 to 8.627 seconds after turn commit, with a median of 5.789 seconds. The live device uses the ReSpeaker microphone and its configured speaker output with the operator's existing voice profile.
133
- - The runtime captures a committed audio turn, runs the acoustic bridge, and then sends the transcript through Ornith's native chat template. This profile is turn-based. The microphone rearms after playback completes, so verbal barge-in is unavailable. Its 9B audio bridge results are separate from the original Sophon's full-duplex benchmark.
156
+ - The 9B results above use the turn-based capture path. The runtime sends the transcript through the backplane's native chat template. Duplex evaluation measures spoken interruption and draft revision separately.
134
157
 
135
158
  ## Source and attribution
136
159
 
package/package.json CHANGED
@@ -1,18 +1,41 @@
1
1
  {
2
2
  "name": "phosphor-harness",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "description": "Local multimodal voice, vision and tool harness for Phosphor",
5
5
  "license": "Apache-2.0",
6
- "repository": {"type": "git", "url": "git+https://github.com/robit-man/phosphor-harness.git"},
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/robit-man/phosphor-harness.git"
9
+ },
7
10
  "homepage": "https://github.com/robit-man/phosphor-harness",
8
- "bin": {"phosphor": "./bin/phosphor.cjs"},
9
- "engines": {"node": ">=18"},
10
- "os": ["linux"],
11
- "cpu": ["x64", "arm64"],
11
+ "bin": {
12
+ "phosphor": "./bin/phosphor.cjs"
13
+ },
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "os": [
18
+ "linux"
19
+ ],
20
+ "cpu": [
21
+ "x64",
22
+ "arm64"
23
+ ],
12
24
  "files": [
13
- "bin/phosphor.cjs", "quickstart.sh", "scripts/*.sh", "scripts/*.py", "scripts/phosphor-weights.sha256",
14
- "sophon_harness/*.py", "pyproject.toml", "sources.lock.json", "requirements-orin-voice.txt",
15
- "ornith-profile.example.json", "profile.example.json"
25
+ "bin/phosphor.cjs",
26
+ "quickstart.sh",
27
+ "scripts/*.sh",
28
+ "scripts/*.py",
29
+ "scripts/phosphor-weights.sha256",
30
+ "sophon_harness/*.py",
31
+ "pyproject.toml",
32
+ "sources.lock.json",
33
+ "requirements-orin-voice.txt",
34
+ "ornith-profile.example.json",
35
+ "profile.example.json"
16
36
  ],
17
- "publishConfig": {"access": "public", "registry": "https://registry.npmjs.org/"}
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "registry": "https://registry.npmjs.org/"
40
+ }
18
41
  }
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.3"
7
+ version = "0.4.4"
8
8
  description = "Phosphor voice, vision and tool harness"
9
9
  requires-python = ">=3.10"
10
10
  license = {text = "Apache-2.0"}
package/quickstart.sh CHANGED
@@ -22,7 +22,7 @@ microphone and speaker, and start the Phosphor user service.
22
22
  --root DIR --microphone NAME --speaker NAME --channels COUNT --channel INDEX
23
23
  --gpu UUID --python PATH --voice-python PATH --talker-python PATH
24
24
  --tools-python PATH --llama-server PATH --weights DIR --profile FILE
25
- --camera-device /dev/videoN (repeatable) --no-camera --context TOKENS
25
+ --camera-device /dev/videoN (repeatable) --no-camera --context auto|TOKENS
26
26
  USAGE
27
27
  }
28
28
  fail() { printf 'Phosphor: %s\n' "$*" >&2; exit 1; }
@@ -40,7 +40,7 @@ esac
40
40
 
41
41
  python=python3
42
42
  voice_python='' talker_python='' tools_python='' llama='' weights='' profile=''
43
- microphone='' speaker='' channels='' channel=0 gpu='' context=8192
43
+ microphone='' speaker='' channels='' channel=0 gpu='' context=auto
44
44
  overrides=no
45
45
  while (($#)); do
46
46
  case "$1" in
@@ -94,7 +94,7 @@ if [[ "$inspect" == yes ]]; then
94
94
  fi
95
95
  exit 0
96
96
  fi
97
- [[ "$context" =~ ^[1-9][0-9]{3,5}$ ]] || fail "provide a context size from 1000 to 999999 tokens"
97
+ [[ "$context" == auto || "$context" =~ ^[1-9][0-9]{3,5}$ ]] || fail "provide auto or a context size from 1000 to 999999 tokens"
98
98
  if [[ ${#jetson_args[@]} -gt 0 ]]; then
99
99
  ((ram_mib >= 22528)) || fail "the Orin profile needs at least 24 GB of unified memory"
100
100
  gpu=${gpu:-0}
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env python3
2
+ """Select a qualified Phosphor context budget before loading the Orin models."""
3
+
4
+ import argparse
5
+ from pathlib import Path
6
+
7
+
8
+ def select_orin_context(available_kib):
9
+ if available_kib >= 23_500_000:
10
+ return 32_768
11
+ if available_kib >= 21_500_000:
12
+ return 16_384
13
+ return 8_192
14
+
15
+
16
+ def read_available_kib(meminfo):
17
+ for line in meminfo.read_text().splitlines():
18
+ name, _, value = line.partition(":")
19
+ if name == "MemAvailable":
20
+ return int(value.split()[0])
21
+ raise ValueError("the kernel did not report available system memory")
22
+
23
+
24
+ if __name__ == "__main__":
25
+ parser = argparse.ArgumentParser(description=__doc__)
26
+ parser.add_argument("--meminfo", type=Path, default=Path("/proc/meminfo"))
27
+ args = parser.parse_args()
28
+ print(select_orin_context(read_available_kib(args.meminfo)))
@@ -15,6 +15,14 @@ fi
15
15
 
16
16
  export PYTHONPATH="$code${PYTHONPATH:+:$PYTHONPATH}"
17
17
  export PYTHONUNBUFFERED=1
18
+ if [[ "$context" == auto ]]; then
19
+ if (( ${#jetson_args[@]} )); then
20
+ context=$("$voice_python" "$(dirname "$0")/context_size.py")
21
+ else
22
+ context=8192
23
+ fi
24
+ fi
25
+ printf 'Phosphor context size: %s tokens\n' "$context"
18
26
  pids=()
19
27
  cleanup() {
20
28
  unlink "$state/voice.ready" 2>/dev/null || :
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env python3
2
+ """Serve a locally pinned Faster Whisper model to the harness on loopback."""
3
+
4
+ from argparse import ArgumentParser
5
+ from email import policy
6
+ from email.parser import BytesParser
7
+ from http.server import BaseHTTPRequestHandler, HTTPServer
8
+ from io import BytesIO
9
+ import json
10
+ from pathlib import Path
11
+ import wave
12
+
13
+ import numpy as np
14
+ from faster_whisper import WhisperModel
15
+
16
+
17
+ MAX_REQUEST = 4 * 1024 * 1024
18
+
19
+
20
+ def decode_request(content_type, data):
21
+ message = BytesParser(policy=policy.default).parsebytes(
22
+ f"Content-Type: {content_type}\r\nMIME-Version: 1.0\r\n\r\n".encode("ascii") + data
23
+ )
24
+ if not message.is_multipart():
25
+ raise ValueError("expected a multipart audio upload")
26
+ files = [part for part in message.iter_parts()
27
+ if part.get_param("name", header="content-disposition") == "file"]
28
+ if len(files) != 1:
29
+ raise ValueError("expected one audio upload")
30
+ with wave.open(BytesIO(files[0].get_payload(decode=True)), "rb") as audio:
31
+ if (audio.getframerate(), audio.getsampwidth(), audio.getnchannels()) != (16_000, 2, 1):
32
+ raise ValueError("expected 16 kHz mono PCM16 audio")
33
+ return np.frombuffer(audio.readframes(audio.getnframes()), dtype="<i2").astype(np.float32) / 32768
34
+
35
+
36
+ def main():
37
+ parser = ArgumentParser(description=__doc__)
38
+ parser.add_argument("--weights", type=Path, required=True)
39
+ parser.add_argument("--device", choices=("cpu", "cuda"), required=True)
40
+ parser.add_argument("--compute-type", required=True)
41
+ parser.add_argument("--language", default="en")
42
+ parser.add_argument("--initial-prompt")
43
+ parser.add_argument("--hotwords")
44
+ parser.add_argument("--cpu-threads", type=int, default=4)
45
+ parser.add_argument("--port", type=int, default=18216)
46
+ args = parser.parse_args()
47
+ model = WhisperModel(str(args.weights.resolve(strict=True)), device=args.device,
48
+ compute_type=args.compute_type, cpu_threads=args.cpu_threads, local_files_only=True)
49
+
50
+ class TranscriptionHandler(BaseHTTPRequestHandler):
51
+ def setup(self):
52
+ self.request.settimeout(30)
53
+ super().setup()
54
+
55
+ def do_GET(self):
56
+ if self.path != "/health":
57
+ self.send_error(404)
58
+ return
59
+ self.reply({"ready": True, "device": args.device})
60
+
61
+ def do_POST(self):
62
+ if self.path != "/v1/audio/transcriptions":
63
+ self.send_error(404)
64
+ return
65
+ try:
66
+ length = int(self.headers.get("Content-Length", "0"))
67
+ if not 0 < length <= MAX_REQUEST:
68
+ raise ValueError("invalid audio upload size")
69
+ audio = decode_request(self.headers.get("Content-Type", ""), self.rfile.read(length))
70
+ except (ValueError, TypeError, EOFError, wave.Error):
71
+ self.send_error(400, "Invalid audio upload")
72
+ return
73
+ segments, _ = model.transcribe(audio, language=args.language, beam_size=5,
74
+ condition_on_previous_text=False, initial_prompt=args.initial_prompt,
75
+ hotwords=args.hotwords)
76
+ self.reply({"text": "".join(segment.text for segment in segments).strip()})
77
+
78
+ def reply(self, result):
79
+ payload = json.dumps(result).encode()
80
+ self.send_response(200)
81
+ self.send_header("Content-Type", "application/json")
82
+ self.send_header("Content-Length", str(len(payload)))
83
+ self.end_headers()
84
+ self.wfile.write(payload)
85
+
86
+ with HTTPServer(("127.0.0.1", args.port), TranscriptionHandler) as server:
87
+ server.serve_forever()
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()
@@ -36,6 +36,8 @@ def main() -> None:
36
36
  run.add_argument("--channel", type=int, default=0)
37
37
  run.add_argument("--source")
38
38
  run.add_argument("--sink")
39
+ run.add_argument("--duplex", action="store_true", help="Keep the microphone open and cancel replies on spoken interruptions")
40
+ run.add_argument("--echo-cancelled-input", action="store_true", help="Duplex input already uses an echo canceller or isolated audio route")
39
41
  run.add_argument("--ready-file", type=Path, help=argparse.SUPPRESS)
40
42
  run.add_argument("--probe", type=Path, action="append", default=[])
41
43
  run.add_argument("--probe-only", action="store_true")
@@ -51,6 +53,8 @@ def main() -> None:
51
53
  parser.error("supply --memory-mib for Qwen 4B or --ornith-url for Ornith 9B")
52
54
  if args.image is not None and args.ornith_url is None:
53
55
  parser.error("--image requires the 9B backplane")
56
+ if (args.duplex or args.echo_cancelled_input) and args.ornith_url is None:
57
+ parser.error("local duplex audio requires the 9B backplane")
54
58
  sys.path.insert(0, str(args.suite.resolve(strict=True)))
55
59
  from .voice import start
56
60
  start(args)