@syengup/fridaynext-hermes-channel 0.1.0-beta.2 → 0.1.0-beta.3
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 +1 -1
- package/install-runtime.js +1 -4
- package/package.json +1 -1
- package/plugin/README.md +1 -1
- package/plugin/fridaynext_plugin/adapter.py +11 -1
- package/plugin/fridaynext_plugin/compat_v0225.py +73 -0
- package/plugin/fridaynext_plugin/message_speech.py +143 -0
- package/plugin/runtime/dist/hosted-backend.js +43 -0
- package/plugin/runtime/dist/service-host.js +14 -3
- package/plugin/runtime/dist/speech-routes.js +111 -0
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
运行本包默认命令即可安装并配对;可选--profile指定已有配置,--hermes指定CLI路径。只使用Hermes公开插件、配置和网关命令;不使用旧独立canonical客户端。官方在途任务及监督器保护保持,不带--all、--force或--yes重启网关。
|
|
12
12
|
|
|
13
|
-
已有模型配置、允许用户、Node路径、数据目录和服务身份保留。已有允许用户不含owner时先明确修复授权。全新服务准备LAN
|
|
13
|
+
已有模型配置、允许用户、Node路径、数据目录和服务身份保留。已有允许用户不含owner时先明确修复授权。全新服务准备LAN监听,并沿标准插件默认准备FridayTunnel网关待机;已有监听、显式公网开关和私有配置不重置。旧安装器写入但没有来源标记的false保守保留,需要用户明确配置选择后才启用。网关待机不代表用户权益、grant、隧道在线或模型就绪。安装记录与私有备份保留在当前Hermes配置目录的.fridaynext-installer下。失败会标为未完成,保留备份供修复;不会声称已回滚运行中的服务,也不取消任务或清除数据。安装器更新时重新运行发行命令;Hermes登记本机包来源,不声称官方catalog自动更新。
|
|
14
14
|
|
|
15
15
|
## 配对与手动连接
|
|
16
16
|
|
package/install-runtime.js
CHANGED
|
@@ -108,7 +108,6 @@ export function installAndPair(options) {
|
|
|
108
108
|
throw new InstallationError('OWNER_AUTHORIZATION_REQUIRED', '现有允许用户配置未授权owner,请在Hermes确认授权后重试。');
|
|
109
109
|
}
|
|
110
110
|
const node = get('platforms.fridaynext.node_bin');
|
|
111
|
-
const publicAccess = get('platforms.fridaynext.public_access');
|
|
112
111
|
const validation = JSON.parse(cli(['plugins', 'validate', source, '--json']));
|
|
113
112
|
for (const warning of validation.warnings ?? []) {
|
|
114
113
|
if (typeof warning !== 'string' || !warning.startsWith('private core imports')
|
|
@@ -151,9 +150,7 @@ export function installAndPair(options) {
|
|
|
151
150
|
command(process.execPath, ['--input-type=module', '-e', script, service, home]);
|
|
152
151
|
receipt.newServicePrepared = true;
|
|
153
152
|
}
|
|
154
|
-
|
|
155
|
-
cli(['config', 'set', 'platforms.fridaynext.public_access', 'false'], false);
|
|
156
|
-
}
|
|
153
|
+
// 全新服务沿标准插件的Kit公网待机默认值;已有显式选择和私有配置保持,不代开用户权益。
|
|
157
154
|
// 官方安装器接收Git源;保留包内源码的本地Git来源,供Hermes登记和后续检查,不临时伪造远端地址。
|
|
158
155
|
const release = path.join(installer, 'releases', receipt.contentHash);
|
|
159
156
|
if (!fs.existsSync(path.join(release, '.git'))) {
|
package/package.json
CHANGED
package/plugin/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
运行本包默认命令即可安装并配对;可选--profile指定已有配置,--hermes指定CLI路径。只使用Hermes公开插件、配置和网关命令;不使用旧独立canonical客户端。官方在途任务及监督器保护保持,不带--all、--force或--yes重启网关。
|
|
12
12
|
|
|
13
|
-
已有模型配置、允许用户、Node路径、数据目录和服务身份保留。已有允许用户不含owner时先明确修复授权。全新服务准备LAN
|
|
13
|
+
已有模型配置、允许用户、Node路径、数据目录和服务身份保留。已有允许用户不含owner时先明确修复授权。全新服务准备LAN监听,并沿标准插件默认准备FridayTunnel网关待机;已有监听、显式公网开关和私有配置不重置。旧安装器写入但没有来源标记的false保守保留,需要用户明确配置选择后才启用。网关待机不代表用户权益、grant、隧道在线或模型就绪。安装记录与私有备份保留在当前Hermes配置目录的.fridaynext-installer下。失败会标为未完成,保留备份供修复;不会声称已回滚运行中的服务,也不取消任务或清除数据。安装器更新时重新运行发行命令;Hermes登记本机包来源,不声称官方catalog自动更新。
|
|
14
14
|
|
|
15
15
|
## 配对与手动连接
|
|
16
16
|
|
|
@@ -33,6 +33,7 @@ from . import media_input
|
|
|
33
33
|
from . import media_output
|
|
34
34
|
from . import inline_media
|
|
35
35
|
from . import compat_v0225
|
|
36
|
+
from .message_speech import MessageSpeechPort
|
|
36
37
|
from .compat_v0225 import MediaDeliveryBoundary
|
|
37
38
|
from .delivery_context import owned_delivery, current_delivery, check_delivery
|
|
38
39
|
from .controls import ControlCoordinator
|
|
@@ -648,6 +649,14 @@ class FridayNextAdapter(MediaDeliveryBoundary, BasePlatformAdapter):
|
|
|
648
649
|
await media_output.media_observations.reconcile(self, record)
|
|
649
650
|
|
|
650
651
|
async def host_request(self, method, params):
|
|
652
|
+
if method in ("speech.config", "speech.speak"):
|
|
653
|
+
if params.get("serviceInstanceId") != self.service_id:
|
|
654
|
+
raise NativeControlError("SERVICE_MISMATCH")
|
|
655
|
+
if getattr(self, "message_speech_port", None) is None:
|
|
656
|
+
self.message_speech_port = MessageSpeechPort(self)
|
|
657
|
+
if method == "speech.config":
|
|
658
|
+
return await self.message_speech_port.config()
|
|
659
|
+
return await self.message_speech_port.speak(params.get("text"))
|
|
651
660
|
if method == "media.check":
|
|
652
661
|
if self.host is None:
|
|
653
662
|
raise NativeControlError("MEDIA_CALL_RETIRED")
|
|
@@ -710,7 +719,7 @@ class FridayNextAdapter(MediaDeliveryBoundary, BasePlatformAdapter):
|
|
|
710
719
|
"sessions.title", "sessions.pin", "history.message-detail",
|
|
711
720
|
"sessions.settings", "sessions.settings.versioned-v1",
|
|
712
721
|
*(["agents.defaults.versioned-v1"] if defaults_writable else []),
|
|
713
|
-
"runs.resolve-unknown-v1", "approval", "question",
|
|
722
|
+
"runs.resolve-unknown-v1", "approval", "question", "tts",
|
|
714
723
|
]
|
|
715
724
|
details = {
|
|
716
725
|
"runs.resolve-unknown-v1": {"scope": "service", "options": ["acknowledge-unknown"], "permission": "allowed"},
|
|
@@ -742,6 +751,7 @@ class FridayNextAdapter(MediaDeliveryBoundary, BasePlatformAdapter):
|
|
|
742
751
|
"model-display-names-v0.22.5",
|
|
743
752
|
"profile-defaults-v0.22.5",
|
|
744
753
|
"reasoning-identity-v0.22.5",
|
|
754
|
+
"message-speech-v0.22.5",
|
|
745
755
|
],
|
|
746
756
|
},
|
|
747
757
|
"backend": {
|
|
@@ -17,6 +17,79 @@ logger = logging.getLogger(__name__)
|
|
|
17
17
|
_resolved_default_warning_emitted = False
|
|
18
18
|
_model_names_warning_emitted = False
|
|
19
19
|
_profile_defaults_warning_emitted = False
|
|
20
|
+
_message_speech_warning_emitted = False
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _warn_message_speech_compat():
|
|
24
|
+
"""固定版消息朗读只发一次告警;不记录文本、音频或profile路径。"""
|
|
25
|
+
global _message_speech_warning_emitted
|
|
26
|
+
if _message_speech_warning_emitted:
|
|
27
|
+
return
|
|
28
|
+
_message_speech_warning_emitted = True
|
|
29
|
+
logger.warning(
|
|
30
|
+
"hermes.compat.message_speech_v0_22_5:消息朗读依赖固定版TTS内部函数"
|
|
31
|
+
"(check_tts_requirements/_load_tts_config/_get_provider/text_to_speech_tool/"
|
|
32
|
+
"_resolve_max_text_length);公开TTS接口可用后替换"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def message_speech_config(profile):
|
|
37
|
+
"""固定版消息朗读配置:在profile作用域读取provider可用性、名称和输入上限。"""
|
|
38
|
+
_warn_message_speech_compat()
|
|
39
|
+
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
|
|
40
|
+
from tools import tts_tool
|
|
41
|
+
from tools.tts_tool_delivery import _resolve_max_text_length
|
|
42
|
+
|
|
43
|
+
token = set_hermes_home_override(profile)
|
|
44
|
+
try:
|
|
45
|
+
tts_config = tts_tool._load_tts_config()
|
|
46
|
+
provider = tts_tool._get_provider(tts_config)
|
|
47
|
+
return {
|
|
48
|
+
"available": bool(tts_tool.check_tts_requirements()),
|
|
49
|
+
"provider": provider,
|
|
50
|
+
"maxTextLength": _resolve_max_text_length(provider, tts_config),
|
|
51
|
+
}
|
|
52
|
+
finally:
|
|
53
|
+
reset_hermes_home_override(token)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class _DropCurrentThreadLogs(logging.Filter):
|
|
57
|
+
"""只丢弃本合成线程的宿主TTS日志,避免私有临时路径进入生产日志。"""
|
|
58
|
+
|
|
59
|
+
def __init__(self):
|
|
60
|
+
super().__init__()
|
|
61
|
+
self.thread = threading.get_ident()
|
|
62
|
+
|
|
63
|
+
def filter(self, record):
|
|
64
|
+
return record.thread != self.thread
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def message_speech_synthesize(profile, text, output_path):
|
|
68
|
+
"""固定版TTS合成:调用原text_to_speech_tool,返回其JSON envelope。
|
|
69
|
+
|
|
70
|
+
同步函数;调用方负责放到线程中执行并清理output_path所在私有临时目录。
|
|
71
|
+
宿主TTS会在INFO/错误日志中打印输出路径;这里仅在本线程合成期间过滤这两个固定版logger,
|
|
72
|
+
不改Hermes core,也不影响其他线程的原生日志。
|
|
73
|
+
"""
|
|
74
|
+
_warn_message_speech_compat()
|
|
75
|
+
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
|
|
76
|
+
from tools import tts_tool, tts_command_provider # noqa: F401(固定版logger存在性由导入证明)
|
|
77
|
+
|
|
78
|
+
filters = []
|
|
79
|
+
for name in ("tools.tts_tool", "tools.tts_command_provider"):
|
|
80
|
+
target = logging.getLogger(name)
|
|
81
|
+
current = _DropCurrentThreadLogs()
|
|
82
|
+
target.addFilter(current)
|
|
83
|
+
filters.append((target, current))
|
|
84
|
+
token = set_hermes_home_override(profile)
|
|
85
|
+
try:
|
|
86
|
+
if not tts_tool.check_tts_requirements():
|
|
87
|
+
raise RuntimeError("TTS_UNAVAILABLE")
|
|
88
|
+
return tts_tool.text_to_speech_tool(text, output_path=str(output_path))
|
|
89
|
+
finally:
|
|
90
|
+
reset_hermes_home_override(token)
|
|
91
|
+
for target, current in filters:
|
|
92
|
+
target.removeFilter(current)
|
|
20
93
|
|
|
21
94
|
|
|
22
95
|
def profile_default_config(profile, *, expected_version=None, update=None, prepare=None):
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""消息朗读端口:经固定版Hermes TTS合成单条正文,返回受控音频字段。
|
|
2
|
+
|
|
3
|
+
只做本地语音合成:不提交模型请求、不创建消息/运行、不写历史、不投递平台消息。
|
|
4
|
+
音频写入0700私有临时目录,读取后随目录删除;不长期缓存,不记录正文或路径。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import base64
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import tempfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import compat_v0225
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
MAX_TEXT_LENGTH = 1200
|
|
19
|
+
MAX_AUDIO_BYTES = 2_500_000
|
|
20
|
+
CONFIG_TIMEOUT_SECONDS = 15
|
|
21
|
+
SYNTHESIS_TIMEOUT_SECONDS = 100
|
|
22
|
+
TEMP_PREFIX = "fridaynext-speech-"
|
|
23
|
+
_MIME_TYPES = {
|
|
24
|
+
"mp3": "audio/mpeg",
|
|
25
|
+
"wav": "audio/wav",
|
|
26
|
+
"ogg": "audio/ogg",
|
|
27
|
+
"opus": "audio/ogg",
|
|
28
|
+
"flac": "audio/flac",
|
|
29
|
+
"m4a": "audio/mp4",
|
|
30
|
+
"aac": "audio/aac",
|
|
31
|
+
"amr": "audio/amr",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _SpeechFailure(Exception):
|
|
36
|
+
def __init__(self, code):
|
|
37
|
+
self.code = code
|
|
38
|
+
super().__init__(code)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _token(value):
|
|
42
|
+
return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,63}", value) is not None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class MessageSpeechPort:
|
|
46
|
+
def __init__(self, adapter):
|
|
47
|
+
self.adapter = adapter
|
|
48
|
+
|
|
49
|
+
def _config_sync(self):
|
|
50
|
+
return compat_v0225.message_speech_config(self.adapter.profile)
|
|
51
|
+
|
|
52
|
+
async def config(self):
|
|
53
|
+
try:
|
|
54
|
+
value = await asyncio.wait_for(asyncio.to_thread(self._config_sync), CONFIG_TIMEOUT_SECONDS)
|
|
55
|
+
except Exception:
|
|
56
|
+
return {"error": "TTS_UNAVAILABLE"}
|
|
57
|
+
if not isinstance(value, dict):
|
|
58
|
+
return {"error": "TTS_UNAVAILABLE"}
|
|
59
|
+
limit = value.get("maxTextLength")
|
|
60
|
+
if value.get("available") is not True or type(limit) is not int or limit <= 0:
|
|
61
|
+
return {"error": "TTS_UNAVAILABLE"}
|
|
62
|
+
return {"maxTextLength": min(limit, MAX_TEXT_LENGTH)}
|
|
63
|
+
|
|
64
|
+
def _speak_sync(self, text):
|
|
65
|
+
try:
|
|
66
|
+
value = compat_v0225.message_speech_config(self.adapter.profile)
|
|
67
|
+
except Exception:
|
|
68
|
+
raise _SpeechFailure("TTS_UNAVAILABLE") from None
|
|
69
|
+
if not isinstance(value, dict):
|
|
70
|
+
raise _SpeechFailure("TTS_UNAVAILABLE")
|
|
71
|
+
limit = value.get("maxTextLength")
|
|
72
|
+
if value.get("available") is not True:
|
|
73
|
+
raise _SpeechFailure("TTS_UNAVAILABLE")
|
|
74
|
+
if type(limit) is not int or limit <= 0:
|
|
75
|
+
raise _SpeechFailure("TTS_UNAVAILABLE")
|
|
76
|
+
if len(text) > min(limit, MAX_TEXT_LENGTH):
|
|
77
|
+
raise _SpeechFailure("TTS_INPUT_TOO_LONG")
|
|
78
|
+
with tempfile.TemporaryDirectory(prefix=TEMP_PREFIX) as directory:
|
|
79
|
+
root = Path(directory).resolve()
|
|
80
|
+
os.chmod(root, 0o700)
|
|
81
|
+
output = root / "speech.mp3"
|
|
82
|
+
try:
|
|
83
|
+
raw = compat_v0225.message_speech_synthesize(self.adapter.profile, text, output)
|
|
84
|
+
except Exception as error:
|
|
85
|
+
if isinstance(error, RuntimeError) and str(error) == "TTS_UNAVAILABLE":
|
|
86
|
+
raise _SpeechFailure("TTS_UNAVAILABLE") from None
|
|
87
|
+
raise _SpeechFailure("TTS_FAILED") from None
|
|
88
|
+
try:
|
|
89
|
+
envelope = json.loads(raw)
|
|
90
|
+
except (TypeError, ValueError):
|
|
91
|
+
raise _SpeechFailure("TTS_FAILED") from None
|
|
92
|
+
if not isinstance(envelope, dict) or envelope.get("success") is not True:
|
|
93
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
94
|
+
file_path = envelope.get("file_path")
|
|
95
|
+
if not isinstance(file_path, str) or not file_path:
|
|
96
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
97
|
+
paths = envelope.get("file_paths")
|
|
98
|
+
if isinstance(paths, list) and len(paths) != 1:
|
|
99
|
+
# 正常单条正文不应分块;缺ffmpeg时Hermes会保留多个片段,不能只返回第一段冒充完整音频。
|
|
100
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
101
|
+
audio = Path(file_path)
|
|
102
|
+
if audio.is_symlink() or audio.resolve().parent != root:
|
|
103
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
104
|
+
suffix = audio.suffix.lower().lstrip(".")
|
|
105
|
+
mime_type = _MIME_TYPES.get(suffix)
|
|
106
|
+
if not mime_type:
|
|
107
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
108
|
+
try:
|
|
109
|
+
size = audio.stat().st_size
|
|
110
|
+
except OSError:
|
|
111
|
+
raise _SpeechFailure("TTS_FAILED") from None
|
|
112
|
+
if size <= 0:
|
|
113
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
114
|
+
if size > MAX_AUDIO_BYTES:
|
|
115
|
+
raise _SpeechFailure("TTS_AUDIO_TOO_LARGE")
|
|
116
|
+
try:
|
|
117
|
+
data = audio.read_bytes()
|
|
118
|
+
except OSError:
|
|
119
|
+
raise _SpeechFailure("TTS_FAILED") from None
|
|
120
|
+
if len(data) != size or not data:
|
|
121
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
122
|
+
provider = envelope.get("provider") or value.get("provider")
|
|
123
|
+
if not _token(provider):
|
|
124
|
+
raise _SpeechFailure("TTS_FAILED")
|
|
125
|
+
return {
|
|
126
|
+
"audioBase64": base64.b64encode(data).decode("ascii"),
|
|
127
|
+
"provider": provider,
|
|
128
|
+
"outputFormat": suffix,
|
|
129
|
+
"mimeType": mime_type,
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async def speak(self, text):
|
|
133
|
+
if not isinstance(text, str) or not text.strip():
|
|
134
|
+
return {"error": "TTS_INPUT_INVALID"}
|
|
135
|
+
text = text.strip()
|
|
136
|
+
if len(text) > MAX_TEXT_LENGTH:
|
|
137
|
+
return {"error": "TTS_INPUT_TOO_LONG"}
|
|
138
|
+
try:
|
|
139
|
+
return await asyncio.wait_for(asyncio.to_thread(self._speak_sync, text), SYNTHESIS_TIMEOUT_SECONDS)
|
|
140
|
+
except _SpeechFailure as error:
|
|
141
|
+
return {"error": error.code}
|
|
142
|
+
except Exception:
|
|
143
|
+
return {"error": "TTS_FAILED"}
|
|
@@ -6,6 +6,16 @@ import { HostedRecoveryPort } from "./hosted-recovery.js";
|
|
|
6
6
|
import { HostedMediaInput } from "./hosted-media.js";
|
|
7
7
|
import { HostedArtifacts } from "./hosted-artifacts.js";
|
|
8
8
|
import { HostedDeliveryObservations } from "./hosted-delivery-observations.js";
|
|
9
|
+
import { MAX_SPEECH_AUDIO_BASE64_LENGTH, MAX_SPEECH_TEXT_LENGTH, SPEECH_ERROR_CODES } from "./speech-routes.js";
|
|
10
|
+
function speechToken(value) {
|
|
11
|
+
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(value);
|
|
12
|
+
}
|
|
13
|
+
function speechBase64(value) {
|
|
14
|
+
return value.length % 4 === 0 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
|
|
15
|
+
}
|
|
16
|
+
function speechMime(value) {
|
|
17
|
+
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9.+-]{0,63}\/[A-Za-z0-9][A-Za-z0-9.+-]{0,63}$/.test(value);
|
|
18
|
+
}
|
|
9
19
|
export class HostedBackendAdapter {
|
|
10
20
|
rpc;
|
|
11
21
|
store;
|
|
@@ -164,5 +174,38 @@ export class HostedBackendAdapter {
|
|
|
164
174
|
async mutateAgentDefaults(agentId, change) { return new HostedSettings(this.rpc, this.store?.serverInstanceId).mutateDefaults(agentId, change); }
|
|
165
175
|
async inspectAgentDefaultsMutation(agentId, commandId) { return new HostedSettings(this.rpc, this.store?.serverInstanceId).inspectDefaults(agentId, commandId); }
|
|
166
176
|
async healthDetails() { return { hostMode: "platform-plugin", runtimeInterface: this.runtimeInterface, facilities: this.facilities, diagnostics: await new HostedSettings(this.rpc, this.store?.serverInstanceId).diagnostics() }; }
|
|
177
|
+
// 消息朗读只读宿主TTS配置并做本地合成;Node只保留受控字段,不转发host异常或音频路径。
|
|
178
|
+
async speechConfig() {
|
|
179
|
+
let reply;
|
|
180
|
+
try {
|
|
181
|
+
reply = await this.rpc.call("speech.config", { serviceInstanceId: this.store?.serverInstanceId }, 15000);
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
185
|
+
}
|
|
186
|
+
if (reply.error !== undefined)
|
|
187
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
188
|
+
const value = reply.maxTextLength;
|
|
189
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
|
|
190
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
191
|
+
return { maxTextLength: Math.min(value, MAX_SPEECH_TEXT_LENGTH) };
|
|
192
|
+
}
|
|
193
|
+
async speak(text) {
|
|
194
|
+
let reply;
|
|
195
|
+
try {
|
|
196
|
+
reply = await this.rpc.call("speech.speak", { serviceInstanceId: this.store?.serverInstanceId, text }, 110000);
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
200
|
+
}
|
|
201
|
+
if (reply.error !== undefined)
|
|
202
|
+
throw new HermesError(typeof reply.error === "string" && SPEECH_ERROR_CODES.has(reply.error) ? reply.error : "TTS_FAILED");
|
|
203
|
+
const { audioBase64, provider, outputFormat, mimeType } = reply;
|
|
204
|
+
if (typeof audioBase64 !== "string" || !audioBase64 || audioBase64.length > MAX_SPEECH_AUDIO_BASE64_LENGTH
|
|
205
|
+
|| !speechBase64(audioBase64) || !speechToken(provider) || !speechToken(outputFormat) || !speechMime(mimeType)) {
|
|
206
|
+
throw new HermesError("TTS_FAILED");
|
|
207
|
+
}
|
|
208
|
+
return { audioBase64, provider, outputFormat, mimeType };
|
|
209
|
+
}
|
|
167
210
|
async close() { this.closed = true; this.runChanged = undefined; this.runChanges.clear(); this.publisher?.close(); this.delivery?.close(); this.rpc.close?.(); }
|
|
168
211
|
}
|
|
@@ -12,6 +12,7 @@ import { loadOrCreateIdentity, saveListenCoordinates } from "./identity.js";
|
|
|
12
12
|
import { validatePublicConfig } from "./public-config.js";
|
|
13
13
|
import { atomicPrivateJSON } from "./private-files.js";
|
|
14
14
|
import { OwnedMediaTransport } from "./media-transport.js";
|
|
15
|
+
import { createSpeechRoutes } from "./speech-routes.js";
|
|
15
16
|
export class FridayServiceHost {
|
|
16
17
|
options;
|
|
17
18
|
service;
|
|
@@ -84,9 +85,18 @@ export class FridayServiceHost {
|
|
|
84
85
|
const facilities = { pairing: "assembled", attest: "assembled", files: "assembled", capsules: "assembled", names: "assembled", preview: "assembled", push: "assembled-unverified", publicAccess: publicConfig ? "assembled-unverified" : "not-configured" };
|
|
85
86
|
const adapter = this.adapter = await this.options.createBackend({ store, profileId, facilities,
|
|
86
87
|
isCurrent: () => this.mediaLease === mediaLease, mediaSignal: mediaAbort.signal, attachmentTransfer, outputTransport });
|
|
87
|
-
|
|
88
|
+
// 公网管理属于本进程装配的Kit设施,不继承宿主声明;可管理不等于隧道已在线。
|
|
89
|
+
adapter.descriptor.capabilities = [...new Set([
|
|
90
|
+
...adapter.descriptor.capabilities.filter(capability => capability !== "public-access.manage"),
|
|
91
|
+
"prompt-capsules", "server-name", "link-preview", "push-v1",
|
|
92
|
+
...(publicConfig?.enabled ? ["public-access.manage"] : []),
|
|
93
|
+
])];
|
|
88
94
|
let lanUrl = () => "", proxyPort = 0;
|
|
89
|
-
|
|
95
|
+
let service;
|
|
96
|
+
// 扩展路由只挂本插件自己的消息朗读;Kit继续负责公共路由、attest与身份门禁,Bearer在扩展内显式校验。
|
|
97
|
+
const speechRoutes = createSpeechRoutes({ authenticate: request => service.authenticate(request), backend: adapter });
|
|
98
|
+
service = this.service = new ChannelService({ dataDir: root, authToken: identity.token, store, adapter,
|
|
99
|
+
extensions: speechRoutes,
|
|
90
100
|
// 正常终态由宿主完成事件即时唤醒;漏提示或重连只按固定节奏对账,不随时长退避。
|
|
91
101
|
reconciliation: { initialDelayMs: 1000, maxDelayMs: 1000 },
|
|
92
102
|
gate: { required: () => true, isPublic },
|
|
@@ -106,7 +116,8 @@ export class FridayServiceHost {
|
|
|
106
116
|
if (!active)
|
|
107
117
|
return null;
|
|
108
118
|
const shared = publicConfig?.enabled ? service.infrastructure.publicAccess?.getPairingInfo() : undefined;
|
|
109
|
-
|
|
119
|
+
// 待机控制面尚未恢复时先生成真实LAN资料;已返回的公网资料必须仍匹配当前TLS身份。
|
|
120
|
+
if (shared && shared.fingerprint !== active.fingerprint)
|
|
110
121
|
return null;
|
|
111
122
|
return { ...shared, v: 2, backendId: "hermes", lanUrl: lanUrl(), fingerprint: active.fingerprint, token: identity.token };
|
|
112
123
|
} } },
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { HermesError } from "./service-errors.js";
|
|
2
|
+
// 传输上界:1200字符按Mac mini真实edge采样约1.7MB音频,base64约2.3MB,留在UDS 4MB单帧内。
|
|
3
|
+
// Node与Python各自校验一次,不能只信客户端。
|
|
4
|
+
export const MAX_SPEECH_TEXT_LENGTH = 1200;
|
|
5
|
+
// Python音频硬上界2,500,000字节;base64膨胀约4/3,Node只接受其对应的最大帧。
|
|
6
|
+
export const MAX_SPEECH_AUDIO_BASE64_LENGTH = 3_500_000;
|
|
7
|
+
export const SPEECH_ERROR_CODES = new Set([
|
|
8
|
+
"TTS_INPUT_INVALID",
|
|
9
|
+
"TTS_INPUT_TOO_LONG",
|
|
10
|
+
"TTS_UNAVAILABLE",
|
|
11
|
+
"TTS_FAILED",
|
|
12
|
+
"TTS_AUDIO_TOO_LARGE",
|
|
13
|
+
]);
|
|
14
|
+
const BODY_LIMIT_BYTES = 1024 * 1024;
|
|
15
|
+
const ERROR_STATUS = {
|
|
16
|
+
TTS_INPUT_INVALID: 400,
|
|
17
|
+
TTS_INPUT_TOO_LONG: 400,
|
|
18
|
+
TTS_AUDIO_TOO_LARGE: 502,
|
|
19
|
+
TTS_UNAVAILABLE: 503,
|
|
20
|
+
TTS_FAILED: 503,
|
|
21
|
+
};
|
|
22
|
+
function json(res, status, body) {
|
|
23
|
+
res.statusCode = status;
|
|
24
|
+
res.setHeader("Cache-Control", "no-store");
|
|
25
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
26
|
+
res.end(JSON.stringify(body));
|
|
27
|
+
}
|
|
28
|
+
function token(value) {
|
|
29
|
+
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(value);
|
|
30
|
+
}
|
|
31
|
+
function mime(value) {
|
|
32
|
+
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9.+-]{0,63}\/[A-Za-z0-9][A-Za-z0-9.+-]{0,63}$/.test(value);
|
|
33
|
+
}
|
|
34
|
+
function base64(value) {
|
|
35
|
+
return value.length % 4 === 0 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
|
|
36
|
+
}
|
|
37
|
+
async function readJSON(req) {
|
|
38
|
+
const chunks = [];
|
|
39
|
+
let size = 0;
|
|
40
|
+
for await (const chunk of req) {
|
|
41
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
42
|
+
size += bytes.length;
|
|
43
|
+
if (size > BODY_LIMIT_BYTES)
|
|
44
|
+
throw new Error("body too large");
|
|
45
|
+
chunks.push(bytes);
|
|
46
|
+
}
|
|
47
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
48
|
+
}
|
|
49
|
+
// 扩展路由位于Kit既有attest/身份门禁之后,但ChannelService不会自动校验Bearer;这里显式补上。
|
|
50
|
+
// 只投影受控字段,任何宿主原始异常、路径、凭据或朗读原文都不进入响应。
|
|
51
|
+
export function createSpeechRoutes(options) {
|
|
52
|
+
return async (req, res) => {
|
|
53
|
+
const pathname = new URL(req.url ?? "/", "http://localhost").pathname.replace(/\/+$/, "");
|
|
54
|
+
const isConfig = pathname === "/friday-next/tts/config";
|
|
55
|
+
if (!isConfig && pathname !== "/friday-next/tts/speak")
|
|
56
|
+
return false;
|
|
57
|
+
if (!options.authenticate(req)) {
|
|
58
|
+
json(res, 401, { ok: false, code: "UNAUTHORIZED" });
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
if (req.method !== (isConfig ? "GET" : "POST")) {
|
|
62
|
+
json(res, 405, { ok: false, code: "METHOD_NOT_ALLOWED" });
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
if (isConfig) {
|
|
66
|
+
try {
|
|
67
|
+
const value = (await options.backend.speechConfig())?.maxTextLength;
|
|
68
|
+
if (!Number.isSafeInteger(value) || value < 1)
|
|
69
|
+
throw new HermesError("TTS_UNAVAILABLE");
|
|
70
|
+
json(res, 200, { ok: true, maxTextLength: Math.min(value, MAX_SPEECH_TEXT_LENGTH) });
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
json(res, 503, { ok: false, code: "TTS_UNAVAILABLE", error: "Hermes TTS is unavailable" });
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
let body;
|
|
78
|
+
try {
|
|
79
|
+
body = await readJSON(req);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
body = null;
|
|
83
|
+
}
|
|
84
|
+
const keys = body && typeof body === "object" && !Array.isArray(body) ? Object.keys(body) : [];
|
|
85
|
+
const text = keys.length === 1 && keys[0] === "text" && typeof body.text === "string"
|
|
86
|
+
? body.text.trim() : "";
|
|
87
|
+
if (!text) {
|
|
88
|
+
json(res, 400, { ok: false, code: "TTS_INPUT_INVALID" });
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
if ([...text].length > MAX_SPEECH_TEXT_LENGTH) {
|
|
92
|
+
json(res, 400, { ok: false, code: "TTS_INPUT_TOO_LONG" });
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
const result = await options.backend.speak(text);
|
|
97
|
+
if (!result || typeof result.audioBase64 !== "string" || !result.audioBase64
|
|
98
|
+
|| result.audioBase64.length > MAX_SPEECH_AUDIO_BASE64_LENGTH || !base64(result.audioBase64)
|
|
99
|
+
|| !token(result.provider) || !token(result.outputFormat) || !mime(result.mimeType)) {
|
|
100
|
+
throw new HermesError("TTS_FAILED");
|
|
101
|
+
}
|
|
102
|
+
json(res, 200, { ok: true, audioBase64: result.audioBase64, provider: result.provider,
|
|
103
|
+
outputFormat: result.outputFormat, mimeType: result.mimeType });
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
const code = error instanceof HermesError && ERROR_STATUS[error.code] ? error.code : "TTS_UNAVAILABLE";
|
|
107
|
+
json(res, ERROR_STATUS[code], { ok: false, code });
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
};
|
|
111
|
+
}
|