phosphor-harness 0.0.0-stage → 0.4.0

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,229 @@
1
+ """Run the pinned Qwen Omni Adapters tool API without a model daemon."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import base64
7
+ import hashlib
8
+ import hmac
9
+ import os
10
+ from pathlib import Path
11
+ import secrets
12
+ import sys
13
+ from unittest.mock import patch
14
+
15
+ from .terminal_input import terminal_with_spoken_input
16
+
17
+
18
+ def read_token(path: Path, *, create: bool = False) -> str:
19
+ if create:
20
+ try:
21
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
22
+ except FileExistsError:
23
+ pass
24
+ else:
25
+ with os.fdopen(descriptor, "w") as handle:
26
+ handle.write(secrets.token_urlsafe(32) + "\n")
27
+ if path.stat().st_mode & 0o077:
28
+ raise ValueError("the tool token file must be private to its owner")
29
+ token = path.read_text().strip()
30
+ if len(token) < 24:
31
+ raise ValueError("the tool token is too short")
32
+ return token
33
+
34
+
35
+ def make_app(checkout: Path, state: Path, workspace: Path, *, enable_camera: bool,
36
+ camera_devices: tuple[str, ...] = (), helper_url: str | None = None,
37
+ episodic_memory: bool = False, host_cameras=None):
38
+ sys.path.insert(0, str(checkout))
39
+ sys.path.insert(0, str(checkout / "src"))
40
+ from flask import abort, jsonify, request
41
+ from portal.app import PortalConfig, create_app
42
+ from portal.documents import DocumentError, MAX_DOCUMENT_BYTES, SessionDocumentStore
43
+ from portal.terminals import TerminalError, TerminalStore
44
+ from portal.tools import SessionLocationStore, SessionWorkspaceStore, ToolInputError
45
+
46
+ token = read_token(state / "portal.token", create=True)
47
+ profile = PortalConfig(
48
+ adapter_url=helper_url or "http://127.0.0.1:9/api/chat",
49
+ adapter_health_url="", comprehension_health_url="", tts_health_url="",
50
+ ollama_health_url="", model="sophon-4b", access_token=token,
51
+ remote_camera_enabled=enable_camera, remote_camera_devices=camera_devices,
52
+ background_task_path=state / "tasks.json",
53
+ tool_workspace_root=workspace, file_delivery_roots=(workspace,),
54
+ file_delivery_root=state / "deliveries", mcp_enabled=True, mcp_root=state / "mcp",
55
+ session_log_dir=state / "diagnostics", episodic_memory_enabled=episodic_memory,
56
+ )
57
+ documents = SessionDocumentStore(ttl_s=profile.session_log_ttl_s)
58
+ session_workspace = SessionWorkspaceStore(ttl_s=profile.session_log_ttl_s)
59
+ terminals = terminal_with_spoken_input(TerminalStore, TerminalError)
60
+ class ReportedLocations(SessionLocationStore):
61
+ @staticmethod
62
+ def describe(location):
63
+ if not location["available"]:
64
+ return {
65
+ **location, "reason": "No approximate location has been supplied for this voice session.",
66
+ "next_action": "Ask the user to supply their approximate current location.",
67
+ }
68
+ return {
69
+ **location, "source": "operator_supplied", "precision": "approximate",
70
+ "scope": "voice_session", "caveat": "This is the approximate area supplied for the voice session.",
71
+ "provenance": {
72
+ **location["provenance"], "source_type": "operator_supplied", "authority": "user_provided_area",
73
+ },
74
+ }
75
+
76
+ def set(self, session_id, payload):
77
+ return self.describe(super().set(session_id, payload))
78
+
79
+ def get(self, session_id):
80
+ return self.describe(super().get(session_id))
81
+
82
+ locations = ReportedLocations()
83
+ # The pinned portal constructs this store during app initialization. Share
84
+ # it with the standalone attachment endpoint and the original tool executor.
85
+ if enable_camera and host_cameras is None:
86
+ from harness.camera import CameraSet
87
+
88
+ host_cameras = CameraSet(_candidates=list(camera_devices)) if camera_devices else CameraSet.discover()
89
+ with (
90
+ patch("portal.app.SessionDocumentStore", return_value=documents),
91
+ patch("portal.tools.SessionLocationStore", return_value=locations),
92
+ patch("portal.tools.SessionWorkspaceStore", return_value=session_workspace),
93
+ patch("portal.tools.TerminalStore", return_value=terminals),
94
+ ):
95
+ app = create_app(profile, host_cameras=host_cameras)
96
+ owner = hashlib.sha256(b"omni-voice-session\0" + token.encode()).hexdigest()
97
+
98
+ @app.before_request
99
+ def only_tool_routes():
100
+ path = request.path
101
+ if path not in {"/api/tools", "/api/status", "/api/voice/camera-qr",
102
+ "/api/harness/attachments", "/api/harness/location", "/api/harness/camera",
103
+ "/api/harness/terminal-password"} and not path.startswith(
104
+ ("/api/tools/", "/api/mcp/servers", "/api/files/")
105
+ ):
106
+ abort(404)
107
+
108
+ @app.post("/api/harness/attachments")
109
+ def attach_document():
110
+ if not hmac.compare_digest(request.headers.get("Authorization", ""), f"Bearer {token}"):
111
+ abort(401)
112
+ upload = request.files.get("file")
113
+ if upload is None or not upload.filename:
114
+ return jsonify({"error": "send one document in the file field"}), 400
115
+ raw = upload.stream.read(MAX_DOCUMENT_BYTES + 1)
116
+ if len(raw) > MAX_DOCUMENT_BYTES:
117
+ abort(413)
118
+ attachment = {"name": upload.filename, "mime_type": upload.content_type,
119
+ "data": base64.b64encode(raw).decode()}
120
+ mime_type = str(upload.mimetype).lower()
121
+ media_key = "audios" if mime_type.startswith("audio/") else "videos" if (
122
+ mime_type.startswith("video/") or mime_type == "image/gif"
123
+ ) else None
124
+ try:
125
+ if media_key is not None:
126
+ media = session_workspace.observe_media(owner, [{"role": "user", media_key: [attachment]}])
127
+ return jsonify({"media_ids": media})
128
+ _, accepted = documents.prepare(owner, [attachment], "")
129
+ except (DocumentError, ToolInputError) as error:
130
+ return jsonify({"error": str(error)}), 400
131
+ return jsonify({"attachments": accepted})
132
+
133
+ @app.route("/api/harness/location", methods=["POST", "DELETE"])
134
+ def update_location():
135
+ if not hmac.compare_digest(request.headers.get("Authorization", ""), f"Bearer {token}"):
136
+ abort(401)
137
+ if request.method == "DELETE":
138
+ locations.clear(owner)
139
+ return jsonify({"available": False})
140
+ if request.content_length is None or request.content_length > 8192:
141
+ abort(413)
142
+ data = request.get_json(silent=True)
143
+ try:
144
+ value = locations.set(owner, data)
145
+ except ToolInputError as error:
146
+ return jsonify({"error": str(error)}), 400
147
+ return jsonify(value)
148
+
149
+ def require_voice_session():
150
+ if not hmac.compare_digest(request.headers.get("Authorization", ""), f"Bearer {token}"):
151
+ abort(401)
152
+ if not hmac.compare_digest(request.cookies.get("omni_portal_session", ""), owner):
153
+ abort(403)
154
+
155
+ @app.post("/api/harness/terminal-password")
156
+ def send_terminal_password():
157
+ require_voice_session()
158
+ if not request.content_length or request.content_length > 32_768:
159
+ abort(400)
160
+ data = request.get_json(silent=True)
161
+ if not isinstance(data, dict) or set(data) != {"handle", "password"}:
162
+ abort(400)
163
+ try:
164
+ submitted = terminals.send_password(owner, data["handle"], data["password"])
165
+ except (TerminalError, OSError, ValueError):
166
+ submitted = False
167
+ return jsonify({"submitted": submitted})
168
+
169
+ @app.post("/api/harness/camera")
170
+ def capture_camera():
171
+ require_voice_session()
172
+ if not request.content_length or request.content_length > 4096:
173
+ abort(400)
174
+ data = request.get_json(silent=True)
175
+ if not isinstance(data, dict) or set(data) != {"mode"}:
176
+ abort(400)
177
+ if not enable_camera or host_cameras is None:
178
+ return jsonify({"ok": False, "error": "camera_disabled",
179
+ "message": "Camera capture is disabled in the local tool service."})
180
+ if data["mode"] != "still":
181
+ return jsonify({"ok": False, "error": "camera_motion_unsupported",
182
+ "message": "This voice profile can capture a current still image."})
183
+ try:
184
+ frame = host_cameras.snapshot()
185
+ except (OSError, RuntimeError, ValueError):
186
+ frame = None
187
+ if not frame:
188
+ return jsonify({"ok": False, "error": "camera_unavailable",
189
+ "message": "No configured camera returned a fresh frame."})
190
+ encoded = frame.get("data")
191
+ if (frame.get("mime_type") != "image/jpeg" or frame.get("encoding") != "base64"
192
+ or not isinstance(encoded, str) or len(encoded) > 12 * 1024 * 1024):
193
+ return jsonify({"ok": False, "error": "camera_frame_invalid",
194
+ "message": "The camera returned an invalid or oversized frame."})
195
+ return jsonify({"ok": True, "frame": {
196
+ "data": encoded, "mime_type": "image/jpeg",
197
+ }, "camera_count": len(frame.get("camera_orientation", ())) or 1})
198
+
199
+ return app
200
+
201
+
202
+ def main() -> None:
203
+ from waitress import serve
204
+
205
+ parser = argparse.ArgumentParser(description=__doc__)
206
+ parser.add_argument("--adapters", required=True, type=Path)
207
+ parser.add_argument("--state", required=True, type=Path)
208
+ parser.add_argument("--workspace", required=True, type=Path)
209
+ parser.add_argument("--port", type=int, default=18214)
210
+ parser.add_argument("--camera", action="store_true", help="Enable on-demand local camera stills")
211
+ parser.add_argument("--camera-device", action="append", default=[], help="Restrict capture to the given device")
212
+ parser.add_argument("--episodic-memory", action="store_true", help="Enable the adapter's configured memory service")
213
+ parser.add_argument("--helper-url", help="Optional operator-configured Ollama-style text endpoint")
214
+ args = parser.parse_args()
215
+ if args.camera_device and not args.camera:
216
+ parser.error("--camera-device requires --camera")
217
+ os.umask(0o077)
218
+ state = args.state.resolve()
219
+ state.mkdir(parents=True, exist_ok=True, mode=0o700)
220
+ workspace = args.workspace.resolve(strict=True)
221
+ app = make_app(args.adapters.resolve(strict=True), state, workspace,
222
+ enable_camera=args.camera, camera_devices=tuple(args.camera_device),
223
+ helper_url=args.helper_url, episodic_memory=args.episodic_memory)
224
+ print(f"Qwen Omni tool API listening at 127.0.0.1:{args.port}", flush=True)
225
+ serve(app, host="127.0.0.1", port=args.port, threads=4)
226
+
227
+
228
+ if __name__ == "__main__":
229
+ main()
@@ -0,0 +1,57 @@
1
+ """Launch the original Sophon streaming Talker on the local interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import gc
7
+ import os
8
+ from pathlib import Path
9
+ import runpy
10
+ import sys
11
+
12
+ from aiohttp import web
13
+ import torch
14
+
15
+
16
+ def main() -> None:
17
+ parser = argparse.ArgumentParser(description=__doc__)
18
+ parser.add_argument("--source", type=Path, required=True, help="Pinned Sophon Realtime source")
19
+ parser.add_argument("--speech-weights", type=Path, required=True)
20
+ parser.add_argument("--port", type=int, default=18213)
21
+ parser.add_argument("--memory-mib", type=int)
22
+ parser.add_argument("--orin", action="store_true")
23
+ args = parser.parse_args()
24
+ if torch.cuda.device_count() != 1:
25
+ raise RuntimeError("the Talker needs one scoped CUDA device")
26
+ if args.orin and torch.cuda.get_device_capability(0) != (8, 7):
27
+ raise RuntimeError("the Orin profile needs an SM87 CUDA device")
28
+ if args.memory_mib:
29
+ device_bytes = torch.cuda.get_device_properties(0).total_memory
30
+ torch.cuda.set_per_process_memory_fraction(min(1, args.memory_mib * 1024**2 / device_bytes))
31
+
32
+ os.environ["SOPHON_MODEL_DIR"] = str(args.speech_weights.resolve(strict=True))
33
+ if args.orin:
34
+ os.environ.update(
35
+ S220_SLOTS="1", S220_PREP_WARM="0", S220_KVC_WARM="0", S220_AD_GRAPH="0",
36
+ S220_HIFT_GRAPH="0", S220_E2B_ALL="0", E2V2_KVCG="0",
37
+ )
38
+ args.source = args.source.resolve(strict=True)
39
+ entry = args.source / "sophon_expressive/talker220_server.py"
40
+ entry.resolve(strict=True)
41
+ sys.path.insert(0, str(args.source))
42
+ run_app = web.run_app
43
+
44
+ def start_on_loopback(*app_args, **app_kwargs):
45
+ gc.collect()
46
+ torch.cuda.synchronize()
47
+ torch.cuda.empty_cache()
48
+ app_kwargs["host"] = "127.0.0.1"
49
+ return run_app(*app_args, **app_kwargs)
50
+
51
+ web.run_app = start_on_loopback
52
+ sys.argv = [str(entry), "--port", str(args.port)]
53
+ runpy.run_path(str(entry), run_name="__main__")
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
@@ -0,0 +1,124 @@
1
+ """Private spoken input for a terminal's actual hidden password prompt."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import tempfile
8
+ import termios
9
+
10
+ PASSWORD_REQUEST = "The terminal is waiting for a password. Say password is followed by the password, spell it, or say cancel."
11
+ PASSWORD_PROMPT = re.compile(
12
+ r"[^\r\n]{0,180}\b(?:password|passphrase)\b[^\r\n:]{0,100}:\s*\Z", re.IGNORECASE,
13
+ )
14
+ TERMINAL_HANDLE = re.compile(r"term-[a-f0-9]{24}\Z")
15
+
16
+ _DIGITS = dict(zip(("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"), "0123456789"))
17
+ _PHONETIC = dict(zip(
18
+ "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november "
19
+ "oscar papa quebec romeo sierra tango uniform victor whiskey xray yankee zulu".split(),
20
+ "abcdefghijklmnopqrstuvwxyz",
21
+ ))
22
+ _SYMBOLS = {
23
+ "at": "@", "dash": "-", "dot": ".", "exclamation": "!", "hash": "#", "percent": "%",
24
+ "plus": "+", "slash": "/", "space": " ", "underscore": "_", "dollar": "$",
25
+ }
26
+
27
+
28
+ def spoken_password(transcript: str) -> str | None:
29
+ """Accept a literal password or exact character spelling for mixed case."""
30
+ text = transcript.strip()
31
+ normalized = text.casefold().rstrip(".!?").strip()
32
+ if normalized in {"cancel", "cancel password", "cancel the password"}:
33
+ return None
34
+ if match := re.match(r"password is\b[,:]?\s+(.+)", text, re.IGNORECASE):
35
+ return match.group(1).rstrip(".!?")
36
+ if not normalized.startswith("spell "):
37
+ raise ValueError("unrecognized password dictation")
38
+ words = iter(normalized[6:].replace("x-ray", "xray").replace("x ray", "xray").replace(",", " ").split())
39
+ output = []
40
+ for word in words:
41
+ if word in {"uppercase", "lowercase", "upper", "lower", "digit"}:
42
+ value = next(words, "")
43
+ if word == "digit":
44
+ value = _DIGITS.get(value, value) if value else ""
45
+ if value not in "0123456789" or len(value) != 1:
46
+ raise ValueError("unrecognized password digit")
47
+ else:
48
+ value = _PHONETIC.get(value, value)
49
+ if not re.fullmatch(r"[a-z]", value):
50
+ raise ValueError("unrecognized password letter")
51
+ if word in {"upper", "uppercase"}:
52
+ value = value.upper()
53
+ output.append(value)
54
+ elif word in _SYMBOLS:
55
+ output.append(_SYMBOLS[word])
56
+ elif word in _PHONETIC:
57
+ output.append(_PHONETIC[word])
58
+ elif re.fullmatch(r"[a-z0-9]", word):
59
+ output.append(word)
60
+ else:
61
+ raise ValueError("unrecognized password spelling")
62
+ if not output:
63
+ raise ValueError("empty password spelling")
64
+ return "".join(output)
65
+
66
+
67
+ def hidden_password_prompt(receipt: dict) -> bool:
68
+ """Require a password label at the cursor and a terminal with echo disabled."""
69
+ if not PASSWORD_PROMPT.search(receipt.get("text", "")):
70
+ return False
71
+ tty = receipt.get("session", {}).get("tty")
72
+ if not tty:
73
+ return False
74
+ try:
75
+ descriptor = os.open(tty, os.O_RDONLY | os.O_NOCTTY | os.O_NONBLOCK)
76
+ try:
77
+ flags = termios.tcgetattr(descriptor)[3]
78
+ finally:
79
+ os.close(descriptor)
80
+ except (OSError, termios.error):
81
+ return False
82
+ return bool(flags & termios.ICANON) and not bool(flags & termios.ECHO)
83
+
84
+
85
+ def terminal_with_spoken_input(base, terminal_error):
86
+ """Extend the adapter's terminal store using its echo-checked secret input."""
87
+ class SpokenTerminal(base):
88
+ def execute(self, owner, arguments):
89
+ if "secret_file" in arguments:
90
+ raise terminal_error("Wait for the terminal password prompt and speak the credential to the voice session.")
91
+ receipt = super().execute(owner, arguments)
92
+ if arguments.get("action") in {"read", "create", "send", "key"}:
93
+ handle = receipt.get("handle") or receipt.get("session", {}).get("handle")
94
+ if handle:
95
+ try:
96
+ snapshot = receipt if arguments["action"] == "read" else super().execute(
97
+ owner, {"action": "read", "handle": handle, "lines": 8},
98
+ )
99
+ except terminal_error:
100
+ snapshot = {}
101
+ if hidden_password_prompt(snapshot):
102
+ receipt["terminal_password_prompt"] = handle
103
+ return receipt
104
+
105
+ def send_password(self, owner, handle, password):
106
+ if not isinstance(handle, str) or not TERMINAL_HANDLE.fullmatch(handle):
107
+ raise ValueError("invalid terminal handle")
108
+ if not isinstance(password, str) or not password or any(char in password for char in "\r\n\0"):
109
+ raise ValueError("invalid terminal password")
110
+ encoded = password.encode("utf-8")
111
+ if len(encoded) > 4096:
112
+ raise ValueError("terminal password exceeds the input limit")
113
+ snapshot = super().execute(owner, {"action": "read", "handle": handle, "lines": 8})
114
+ if not hidden_password_prompt(snapshot):
115
+ return False
116
+ with tempfile.NamedTemporaryFile(prefix="phosphor-terminal-") as secret:
117
+ secret.write(encoded)
118
+ secret.flush()
119
+ receipt = super().execute(owner, {
120
+ "action": "send", "handle": handle, "secret_file": secret.name, "submit": True,
121
+ })
122
+ return bool(receipt.get("input_delivered") and receipt.get("secret_input"))
123
+
124
+ return SpokenTerminal()