新增语音输入(mcp_asr)与健康检查服务标识

语音输入:输入框为空时发送键变麦克风,进入语音模式后按住说话、松手转写并发送;套壳 App 走原生录音桥,浏览器走 MediaRecorder(需 HTTPS)。转写在 mcp_asr,经 /api/asr/transcribe 直达,不经过模型、不消耗 token。

/api/health 增加 service/api/auth_required 字段并设 no-store,供套壳 App 校验手填的服务器地址;免认证路径容忍尾斜杠,避免 /api/health/ 被中间件 401。

接线与文档:compose 新增 mcp_asr;init.sh 默认复用 BIGMODEL_KEY 作为 ASR_API_KEY;README/AGENTS/mcp 文档同步。版本 2.3.0 → 2.4.0。
This commit is contained in:
2026-10-24 16:13:30 +08:00
parent 5b70f7d614
commit 53fa5da82b
24 changed files with 1810 additions and 29 deletions
+6 -1
View File
@@ -266,6 +266,7 @@ preview-proxy.earlyGuard
express.static(public)
/api/sessions ×4 ← sessions / messages / files / skill-run(通用执行面)
/api/skills
/api/asr ← 语音识别代理:/transcribe 走登录态;ASR_URL 空则 503
/api/config ← requireAdmin
/api/platforms
/api/system ← /restart 需 admin,其余登录即可
@@ -274,6 +275,8 @@ express.static(public)
/api/memory
/api/wechat
/api/channel
/api/health ← 免认证探活:套壳 App / 运维脚本用它校验服务器地址
(只认 200 + body.ok + service==='agent-core')
data-page ← GET /app/:task_id/*、POST /api/db/:task_id/query
preview-proxy.mount(末尾兜底)
```
@@ -281,13 +284,15 @@ preview-proxy.mount(末尾兜底)
- 错误形状统一 `{ error: string }`,`err.status_code` 决定 HTTP 码。
- 认证:HMAC 签名 HttpOnly cookie(`agent_token`),`Authorization: Basic` 兜底,
`Authorization: Bearer` 仅用于 `/api/login_restore`。`auth.users` 为空 = 完全关闭认证。
- 免认证路径集中在 `auth.js` 的 `PUBLIC_EXACT`(含 `/api/health`,且容忍尾斜杠)。
新增免登录接口必须加进去,否则会被中间件先拦成 401。
- **单租户警告**:除管理员接口外不做资源级授权;按用户的会话列表隔离在查询层(`sessions.user`)。
- 公网短链 `/p/<id>` 的信任模型:随机 ID + 服务端 TTL + 签发时 `realpath` 校验,不靠登录态。
## 前端(`server/public/`)
- **无构建**:`index.html` 按顺序加载经典脚本,共享全局作用域:
`core.js → chat.js → sessions.js → stream.js → files.js → preview.js → settings.js`
`core.js → chat.js → sessions.js → stream.js → files.js → voice.js → preview.js → settings.js`
(`settings.js` 必须最后,尾部有全局初始化);`marked.min.js` 走 `vendor/`。
- 新增 JS 文件必须同时改 `index.html` 的 `<script>` 顺序——没有 import/export,顺序就是依赖。
- `sw.js`:HTML/JS/CSS 网络优先,图片/JSON 缓存优先。**改图片或 JSON 才需要升 `CACHE_VERSION`**;
+7 -1
View File
@@ -79,9 +79,15 @@ auth: # users 留空 = 不启用登
role: admin # admin=管理员(全部设置 + 用户管理);user 或缺省=普通用户(仅账户页)
# model: qwen-tp/qwen3.8-flash # 选填:该用户新建会话时锁定的模型(内部键「平台名/模型id」)
# MCP 服务列表(仓库自带的 mcp/ 三个服务,或栈外服务):每项 {name?, url, headers?, mode?(默认 advertise), timeout_ms?, tools_allow?, tools_deny?}。
# MCP 服务列表(仓库自带的 mcp/ 服务,或栈外服务):每项 {name?, url, headers?, mode?(默认 advertise), timeout_ms?, tools_allow?, tools_deny?}。
# mode 三态:advertise=工具下发给模型;skill=不下发,改为以技能形式暴露(get 返回原始 input_schema,run 转发);
# disable=不连接、不发现。旧字段 enable 已废弃;mode: silent 已移除(改用 skill),写进配置会启动报错。
#
# 语音识别(mcp/asr)建议用 skill:转写音频是低频能力,不必把 schema 塞进每轮请求。
# - name: asr
# url: "http://mcp_asr:3000/mcp"
# mode: skill
# 注意:输入框里的语音输入走的是 core 的 /api/asr(由 compose 的 ASR_URL 接线),不经这个工具,也不消耗 token。
mcp_servers: []
public_link:
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "agent-app",
"version": "2.3.0",
"version": "2.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "agent-app",
"version": "2.3.0",
"version": "2.4.0",
"dependencies": {
"better-sqlite3": "11.3.0",
"cron-parser": "5.10.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "agent-app",
"version": "2.3.0",
"version": "2.4.0",
"description": "自用通用 Agent 系统:多模型调度 + 任务目录 + 工具调用 + H5 Web UI",
"main": "server/server.js",
"scripts": {
+4 -1
View File
@@ -73,7 +73,10 @@ function basicAuthUser(req, users) {
// ---------- 免认证路径(登录页自身需要的资源) ----------
const PUBLIC_EXACT = new Set(['/login', '/logout', '/api/login', '/api/logout', '/api/login_restore', '/api/health']);
function isPublicPath(p) {
if (PUBLIC_EXACT.has(p)) return true;
// 尾斜杠容忍:客户端手动填服务器地址常多带一个 `/`(拼成 `/api/health/`),
// Express 路由本身能匹配,但这里若不规范化,中间件会先回 401——地址明明是对的却报未登录。
const norm = p.length > 1 ? p.replace(/\/+$/, '') : p;
if (PUBLIC_EXACT.has(norm)) return true;
if (p.startsWith('/css/')) return true; // 登录页复用 style.css
if (p === '/favicon.ico') return true;
return false;
+71
View File
@@ -338,6 +338,7 @@ footer { position: relative; flex: none; padding: 8px 12px calc(10px + env(safe-
}
.up-card.done::after, .up-card.err::after { display: none; }
.input-shell {
position: relative; /* 按住说话的遮罩以它为定位基准 */
display: flex;
flex-direction: column;
align-items: stretch;
@@ -404,6 +405,76 @@ footer { position: relative; flex: none; padding: 8px 12px calc(10px + env(safe-
}
.plus-btn:active { background: #dde0e6; }
.plus-btn.active { background: var(--active-soft); color: var(--active); } /* 文件面板展开时高亮 */
/* 语音模式:输入框位置换成「按住 说话」——只有居中文字,不做出按钮外观 */
#voice-hold {
position: relative;
height: 44px; border-radius: 8px;
display: flex; align-items: center; justify-content: center;
font-size: 15px; color: var(--ink); cursor: pointer;
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;
touch-action: none; transition: background .12s;
}
/* 按住区与下方操作栏之间的分隔线(用伪元素画,避开录音态底色的圆角) */
#voice-hold::after {
content: '';
position: absolute; left: 0; right: 0; bottom: -1px;
height: 1px; background: var(--border);
}
/* 录音中给一个极浅底色作反馈(文字同时变成「松开 结束」) */
#voice-hold.recording { background: var(--surface); }
/* 录音期间:输入卡内容整体让位给遮罩(透明渐变不能把按钮/文字透出来) */
body.voice-active .input-shell { border-color: transparent; box-shadow: none; }
body.voice-active .input-shell > *:not(#voice-overlay) { visibility: hidden; }
body.voice-active .attach-chips { visibility: hidden; }
body.voice-active .scroll-bottom-btn { display: none; }
/* 按住说话的遮罩:左右贴屏幕两边;底部一直铺到屏幕底(含 footer 的 10px 内边距与安全区),
向上多铺 72px 让渐变淡出。
声波中心对齐「按住 说话」那一行:padding-bottom 70px + 安全区 =
59(声波中心到输入卡底部)+ 11(遮罩底边向下外扩的 1px 边框 + 10px footer 内边距)。 */
#voice-overlay {
position: absolute;
top: -72px;
bottom: calc(-11px - env(safe-area-inset-bottom, 0px));
left: -13px; right: -13px;
z-index: 6;
display: flex; flex-direction: column; align-items: center; justify-content: flex-end;
gap: 20px;
padding-bottom: calc(70px + env(safe-area-inset-bottom, 0px));
/* 极淡的蓝调,从下往上淡出(“几乎看不出来,仔细看才有一层”) */
background: linear-gradient(to top, rgba(57, 100, 254, .09), rgba(57, 100, 254, 0));
color: var(--active);
pointer-events: auto; touch-action: none;
transition: background .15s linear, color .15s linear;
}
/* 上滑取消态:整体换成极淡的红调,声波/文案同步变红 */
#voice-overlay.cancel {
background: linear-gradient(to top, rgba(192, 57, 43, .09), rgba(192, 57, 43, 0));
color: #c0392b;
}
.vo-hint { font-size: 13px; line-height: 18px; color: var(--gray); letter-spacing: .2px; }
.vo-wave { display: flex; align-items: center; justify-content: center; gap: 3px; height: 34px; max-width: 100%; }
/* 柱子高度用 scaleY 而不是 height:只走合成层,不触发重排 */
.vo-wave i {
display: block; width: 3px; height: 34px; border-radius: 2px;
background: currentColor;
transform: scaleY(.12); transform-origin: center;
transition: transform 70ms linear;
}
/* 上滑取消态:声波与文案统一转警示色 */
#voice-overlay.cancel .vo-hint { color: #c0392b; }
@media (prefers-reduced-motion: reduce) { .vo-wave i { transition: none; } }
/* 发送键四态:发送 / 停止 / 语音 / 键盘。语音与键盘用中性底色,和蓝色「发送」区分开 */
.send-btn > svg { display: none; }
.send-btn[data-state="send"] .ic-send { display: block; }
.send-btn[data-state="voice"] .ic-voice,
.send-btn[data-state="keyboard"] .ic-kb { display: block; }
.send-btn[data-state="voice"],
.send-btn[data-state="keyboard"] { background: var(--surface); color: var(--ink); box-shadow: none; }
.send-btn[data-state="voice"]:active,
.send-btn[data-state="keyboard"]:active { background: #dde0e6; opacity: 1; }
/* 发送按钮:蓝底白向上箭头 */
.send-btn {
flex: none; width: 36px; height: 36px; border-radius: 50%;
+14 -2
View File
@@ -165,6 +165,8 @@
</div>
<div class="up-cards hidden" id="up-cards" aria-label="已上传文件"></div>
<textarea id="msg-input" placeholder="传送信息" rows="2" enterkeyhint="enter"></textarea>
<!-- 语音模式:输入框位置变成「按住 说话」(只有居中文字,无按钮外观) -->
<div id="voice-hold" class="hidden" role="button" tabindex="0" aria-label="按住说话">按住 说话</div>
<div class="input-actions">
<div class="ia-side ia-left">
<button class="think-toggle" id="deep-think-btn" title="深度思考">
@@ -179,13 +181,22 @@
<button class="plus-btn" id="attach-btn" title="上传文件" aria-label="上传文件">
<svg viewBox="0 0 24 24" class="ic sm"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg>
</button>
<!-- 同一按钮两态:发送(↑)/ 停止(白色方块)。data-state 由 JS 切换,尺寸不变避免输入区跳动 -->
<!-- 同一按钮四态:发送(↑)/ 停止(方块)/ 语音(麦克风)/ 键盘。
data-state 由 JS 切换,尺寸不变避免输入区跳动 -->
<button class="send-btn" id="send-btn" data-state="send" title="发送" aria-label="发送">
<svg viewBox="0 0 24 24" class="ic sm"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></svg>
<svg class="ic sm ic-send" viewBox="0 0 24 24"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></svg>
<svg class="ic sm ic-voice" viewBox="0 0 24 24"><rect x="9" y="2" width="6" height="12" rx="3"></rect><path d="M5 10a7 7 0 0 0 14 0"></path><line x1="12" y1="19" x2="12" y2="22"></line></svg>
<svg class="ic sm ic-kb" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2.5"></rect><circle cx="7" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="12" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="17" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="7" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="17" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><line x1="8" y1="16" x2="16" y2="16"></line></svg>
<span class="stop-sq" aria-hidden="true"></span>
</button>
</div>
</div>
<!-- 按住说话的遮罩:盖满输入卡并扩到屏幕两边(footer 有 12px 内边距 + shell 1px 边框)。
声波由 JS 生成 25 根柱子;上滑到文案区域进入取消态(整体变红)。 -->
<div id="voice-overlay" class="hidden" aria-hidden="true">
<div class="vo-hint" id="voice-hint">松手传送,上滑取消</div>
<div class="vo-wave" id="voice-wave"></div>
</div>
</div>
<!-- 回到底部浮动按钮(搬自 index;上翻历史时出现、AI 输出中常驻转圈)。
放在 footer 内、相对 footer 顶边停靠:输入框长高/编辑条出现时不会被盖住 -->
@@ -509,6 +520,7 @@
<script src="/js/sessions.js"></script>
<script src="/js/stream.js"></script>
<script src="/js/files.js"></script>
<script src="/js/voice.js"></script>
<script src="/js/preview.js"></script>
<script src="/js/settings.js"></script>
<script>
+4 -2
View File
@@ -30,11 +30,13 @@
send();
}
});
// 发送键双职:生成中且输入框为空时变「停止」(白色方块),点击终止当前回合;
// 输入框有字时它仍是「发送」——运行中允许插话,直接发出去(后端 live 追投)。
// 发送键四职:语音 / 键盘(语音模式)/ 停止 / 发送,由 data-state 决定点击含义。
// 400ms 内重复点击忽略:防双击重复 abort(服务端 status 事件回来前按钮仍是停止态)。
let stopClickAt = 0;
$('send-btn').addEventListener('click', () => {
const st = $('send-btn').dataset.state;
if (st === 'voice' && window.AgentVoice) { window.AgentVoice.enter(); return; }
if (st === 'keyboard' && window.AgentVoice) { window.AgentVoice.exit(true); return; }
if (stopModeActive()) {
if (Date.now() - stopClickAt < 400) return;
stopClickAt = Date.now();
+17 -4
View File
@@ -300,13 +300,26 @@
// 有附件时按钮保持「发送」:粘贴长文本转成的附件不应被当成停止操作
return state.status === 'active' && !(($('msg-input') || {}).value || '').trim() && !state.attachments.length;
}
// 发送键四态:停止 / 键盘(语音模式)/ 语音(空输入且支持录音)/ 发送。
// 停止优先:生成中且输入框为空时,用户最可能想停止,不能被语音入口顶掉。
// 语音与键盘两态由 voice.js 暴露的 window.AgentVoice 提供(脚本加载顺序在 sessions 之后,
// 初始化阶段它还不存在,此处必须容错——那时按普通「发送」渲染即可)。
function updateSendBtn() {
const sb = $('send-btn');
if (!sb) return;
const stop = stopModeActive();
sb.dataset.state = stop ? 'stop' : 'send';
sb.title = stop ? '停止生成' : '发送';
sb.setAttribute('aria-label', stop ? '停止生成' : '发送');
const v = window.AgentVoice;
const empty = !(($('msg-input') || {}).value || '').trim() && !state.attachments.length;
let mode;
if (stopModeActive()) mode = 'stop';
else if (v && v.isVoiceMode()) mode = 'keyboard';
else if (empty && v && v.isAvailable()) mode = 'voice';
else mode = 'send';
sb.dataset.state = mode;
const label = mode === 'stop' ? '停止生成'
: mode === 'keyboard' ? '切换到键盘输入'
: mode === 'voice' ? '语音输入' : '发送';
if (sb.title !== label) sb.title = label;
if (sb.getAttribute('aria-label') !== label) sb.setAttribute('aria-label', label);
}
function updateHeaderActions() {
+559
View File
@@ -0,0 +1,559 @@
// 语音输入(按住说话)
//
// 交互:
// · 输入框为空时,发送键变成麦克风;点一下进入语音模式
// · 语音模式下输入框位置变成「按住 说话」:按住后整块输入区被全宽遮罩盖住,
// 显示实时电平声波 + 「松手传送,上滑取消」
// · 手指上滑进入文案区域 → 取消态(声波与文案变红,文案改「松开取消」),滑回下方恢复
// · 松手:取消态 → 丢弃 + 轻提示;否则转写后**直接发送**
// · 发送键位置变成键盘按钮,点一下回文本模式并聚焦输入框(移动端弹键盘)
//
// 录音在客户端:套壳原生桥(http 页面也能用)或 HTTPS 下的 MediaRecorder;
// 转写在服务端 mcp_asr(经 core 的 /api/asr 中转)。
// 电平:浏览器用 AnalyserNode 算 RMS;套壳上报 onNativeVoiceAmp(原始 getMaxAmplitude)。
// 归一化/门限/平滑全部在页面侧做,壳不做任何换算。
//
// 包在 IIFE 里:前端是共享全局作用域的经典脚本,顶层声明会和其他文件撞名。
(function () {
'use strict';
const hold = $('voice-hold');
const ta = $('msg-input');
const overlay = $('voice-overlay');
const hintEl = $('voice-hint');
const waveEl = $('voice-wave');
if (!hold || !ta) return;
const native = (window.AgentNative && typeof window.AgentNative.startVoice === 'function')
? window.AgentNative : null;
const webOk = !!(window.isSecureContext && navigator.mediaDevices
&& typeof navigator.mediaDevices.getUserMedia === 'function' && window.MediaRecorder);
const MAX_MS = 60000; // 单次录音上限
const MIN_MS = 500; // 短于这个时长按误触处理,不上传
const NO_RESULT_MS = 3000; // 松开后壳迟迟不回音频(比如还在等权限)→ 复位
const BAR_COUNT = 45; // 声波柱数(要足够宽,手指按住时两侧仍能看到)
// 两端矮、中间高的包络:看起来像一段声波而不是一排等高柱子
const WEIGHTS = [];
for (let i = 0; i < BAR_COUNT; i++) {
WEIGHTS.push(0.45 + 0.55 * Math.sin(Math.PI * (i + 0.5) / BAR_COUNT));
}
const bars = [];
if (waveEl) {
for (let i = 0; i < BAR_COUNT; i++) {
const b = document.createElement('i');
waveEl.appendChild(b);
bars.push(b);
}
}
let available = false; // 有能力 + 服务端接线:发送键才显示麦克风
let mode = false; // 是否处于语音模式
let phase = 'idle'; // idle | arming(等 getMedia)| recording | busy
let pressing = false;
let pressY = 0; // 本次按压的起始 Y(判断“确实上滑了”)
let cancelArmed = false; // 已上滑到取消区
let discard = false; // 本次录音太短/已取消:结果到了也丢掉
let recordStartAt = 0;
let stopTimer = null;
let hardTimer = null;
let watchdog = null;
let rec = null;
let stream = null;
let chunks = [];
let mime = '';
// 电平与渲染
let rafId = 0;
let levelTarget = 0;
let levelCur = 0;
let lastRealLevelAt = 0;
let audioCtx = null;
let analyser = null;
let audioBuf = null;
let srcNode = null;
function clamp01(v) { return v < 0 ? 0 : v > 1 ? 1 : v; }
// 电平归一化的唯一实现:浏览器(RMS)和壳(峰值幅度)都在这里落到 0~1。
// 低于 -55dB 视为静音,-5dB 及以上视为满幅;要调灵敏度只改这两个常量。
const LEVEL_FLOOR_DB = -55;
const LEVEL_RANGE_DB = 50;
function dbToLevel(db) {
return clamp01((db - LEVEL_FLOOR_DB) / LEVEL_RANGE_DB);
}
function setHoldText(s) {
if (hold.textContent !== s) hold.textContent = s;
}
// ---------- 遮罩 / 声波 ----------
function setOverlayMode(m) { // 'send' | 'cancel' | 'busy'
cancelArmed = m === 'cancel';
if (overlay) overlay.classList.toggle('cancel', m === 'cancel');
if (hintEl) {
hintEl.textContent = m === 'cancel' ? '松开取消'
: m === 'busy' ? '正在识别…' : '松手传送,上滑取消';
}
}
function renderBars(level, animate) {
if (!bars.length) return;
const t = Date.now() / 1000;
// 只有真的收到可听电平(大于门限)才加流动感;安静时保持完全静止,不靠抖动“装活”
const flow = animate && level > 0.02;
for (let i = 0; i < bars.length; i++) {
const ripple = flow ? (0.88 + 0.12 * Math.sin(t * 6 + i * 0.55)) : 1;
const h = Math.max(0.08, Math.min(1, (0.15 + 0.85 * level) * WEIGHTS[i] * ripple));
bars[i].style.transform = 'scaleY(' + h.toFixed(3) + ')';
}
}
function startLoop() {
if (rafId || !overlay || overlay.classList.contains('hidden')) return;
if (typeof requestAnimationFrame !== 'function') return;
rafId = requestAnimationFrame(tickMeter);
}
function tickMeter() {
rafId = 0;
if (!overlay || overlay.classList.contains('hidden')) return;
let animate = false;
if (analyser && audioBuf) {
analyser.getFloatTimeDomainData(audioBuf);
let sum = 0;
for (let i = 0; i < audioBuf.length; i++) sum += audioBuf[i] * audioBuf[i];
const rms = Math.sqrt(sum / audioBuf.length);
const db = 20 * Math.log10(rms + 1e-7); // 静音约 -140,正常说话 -35 ~ -12
levelTarget = dbToLevel(db);
animate = true;
} else if (Date.now() - lastRealLevelAt <= 300) {
animate = true; // 壳刚上报过电平
}
if (!animate) {
// 没有电平来源(壳没实现 onNativeVoiceAmp / AnalyserNode 不可用):
// 静默停在基线,不再空转(也绝不能假动)
levelCur = 0;
renderBars(0, false);
return;
}
// 快攻慢放:起音跟得紧,收音回落慢,柱体不抽筋
levelCur += (levelTarget - levelCur) * (levelTarget > levelCur ? 0.55 : 0.18);
renderBars(levelCur, true);
rafId = requestAnimationFrame(tickMeter);
}
function attachAnalyser() {
if (!stream) return;
try {
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) return;
audioCtx = new AC();
analyser = audioCtx.createAnalyser();
analyser.fftSize = 512;
audioBuf = new Float32Array(analyser.fftSize);
srcNode = audioCtx.createMediaStreamSource(stream);
srcNode.connect(analyser); // 不接 destination,不会回放
if (audioCtx.state === 'suspended') audioCtx.resume();
startLoop(); // 之前可能在静默态停掉了循环
} catch (_) {
analyser = null;
audioBuf = null;
}
}
function startMeter() {
stopMeter(false);
levelTarget = 0;
levelCur = 0;
lastRealLevelAt = 0;
startLoop();
}
function stopMeter(flatten) {
if (rafId) { cancelAnimationFrame(rafId); rafId = 0; }
if (srcNode) { try { srcNode.disconnect(); } catch (_) { /* 已断 */ } srcNode = null; }
analyser = null;
audioBuf = null;
if (audioCtx) { try { audioCtx.close(); } catch (_) { /* 已关 */ } audioCtx = null; }
if (flatten !== false) {
for (let i = 0; i < bars.length; i++) bars[i].style.transform = 'scaleY(.12)';
}
}
function showOverlay() {
if (overlay) overlay.classList.remove('hidden');
// 录音期间隐藏输入卡内容(否则透明渐变会把按钮/文字透出来)
if (document.body) document.body.classList.add('voice-active');
setOverlayMode('send');
startMeter();
}
function hideOverlay() {
if (overlay) overlay.classList.add('hidden');
if (document.body) document.body.classList.remove('voice-active');
stopMeter();
cancelArmed = false;
}
function resetUI() {
phase = 'idle';
pressing = false;
pressY = 0;
discard = false;
if (stopTimer) { clearTimeout(stopTimer); stopTimer = null; }
if (hardTimer) { clearTimeout(hardTimer); hardTimer = null; }
if (watchdog) { clearTimeout(watchdog); watchdog = null; }
hold.classList.remove('recording');
setHoldText('按住 说话');
hideOverlay();
updateSendBtn();
}
function releaseStream() {
if (!stream) return;
try { stream.getTracks().forEach(function (t) { t.stop(); }); } catch (_) { /* 已关 */ }
stream = null;
}
function pickMime() {
const list = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
for (let i = 0; i < list.length; i++) {
try { if (MediaRecorder.isTypeSupported(list[i])) return list[i]; } catch (_) { /* 忽略 */ }
}
return '';
}
// ---------- 模式切换 ----------
function enter() {
if (!available || mode) return;
mode = true;
ta.classList.add('hidden');
hold.classList.remove('hidden');
try { ta.blur(); } catch (_) { /* 忽略 */ }
resetUI();
updateSendBtn();
}
function exit(focus) {
if (!mode) return;
cancelHold();
mode = false;
hold.classList.add('hidden');
ta.classList.remove('hidden');
autosize();
updateSendBtn();
// 必须在点击手势里同步 focus,移动端才会弹键盘
if (focus) { try { ta.focus(); } catch (_) { /* 忽略 */ } }
}
// ---------- 录音 ----------
function startHold() {
if (phase !== 'idle') return;
pressing = true;
discard = false;
hold.classList.add('recording');
setHoldText('松开 结束');
showOverlay();
if (native) {
// 原生侧即使要弹权限也先当「已开始」:松开时 stopVoice(),壳若还在等权限会忽略,
// 由 watchdog 兜底复位(只有首次授权那一次会遇到)。
phase = 'recording';
recordStartAt = Date.now();
stopTimer = setTimeout(finishHold, MAX_MS);
hardTimer = setTimeout(function () {
try { if (native.cancelVoice) native.cancelVoice(); } catch (_) { /* 忽略 */ }
resetUI();
toast('录音超时');
}, MAX_MS + NO_RESULT_MS);
try {
native.startVoice();
} catch (e) {
resetUI();
toast('无法开始录音:' + String((e && e.message) || e));
}
return;
}
phase = 'arming'; // 等 getUserMedia/MediaRecorder 起来
startWeb();
}
async function startWeb() {
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
} catch (e) {
resetUI();
const denied = e && (e.name === 'NotAllowedError' || e.name === 'SecurityError');
toast(denied ? '麦克风权限被拒绝' : '无法打开麦克风:' + String((e && e.message) || e));
return;
}
if (!pressing) { releaseStream(); resetUI(); return; } // 松开得比授权快
attachAnalyser(); // 声波接同一路 MediaStream
mime = pickMime();
try {
rec = mime ? new MediaRecorder(stream, { mimeType: mime }) : new MediaRecorder(stream);
} catch (_) {
rec = new MediaRecorder(stream);
mime = rec.mimeType || '';
}
chunks = [];
rec.ondataavailable = function (ev) {
if (ev.data && ev.data.size) chunks.push(ev.data);
};
rec.onstop = function () {
const type = mime || 'audio/webm';
const blob = new Blob(chunks, { type: type });
chunks = [];
rec = null;
releaseStream();
if (discard) { discard = false; resetUI(); toast('说话时间太短'); return; }
upload(blob);
};
rec.onerror = function () {
releaseStream();
resetUI();
toast('录音出错');
};
try {
rec.start();
} catch (e) {
releaseStream();
resetUI();
toast('无法开始录音:' + String((e && e.message) || e));
return;
}
phase = 'recording';
recordStartAt = Date.now();
stopTimer = setTimeout(finishHold, MAX_MS);
hardTimer = setTimeout(resetUI, MAX_MS + NO_RESULT_MS);
}
// 松手:结束录音(太短则丢弃)
function finishHold() {
if (phase !== 'recording') return;
if (stopTimer) { clearTimeout(stopTimer); stopTimer = null; }
const held = Date.now() - recordStartAt;
if (held < MIN_MS) discard = true;
phase = 'busy';
hold.classList.remove('recording');
setHoldText(discard ? '按住 说话' : '正在识别…');
// 遮罩留着,文案换成「正在识别…」;柱子停在低位,等结果回来再收
setOverlayMode(discard ? 'send' : 'busy');
stopMeter();
if (native) {
try {
native.stopVoice();
} catch (e) {
resetUI();
toast('结束录音失败:' + String((e && e.message) || e));
return;
}
// 壳若因为权限弹窗没有真正开录,stopVoice() 会被忽略、结果不会回来
watchdog = setTimeout(function () {
if (phase !== 'busy') return;
try { if (native.cancelVoice) native.cancelVoice(); } catch (_) { /* 忽略 */ }
resetUI();
}, NO_RESULT_MS);
return;
}
try {
if (rec && rec.state !== 'inactive') rec.stop();
else { releaseStream(); resetUI(); }
} catch (_) {
releaseStream();
resetUI();
}
}
// 放弃本次录音(切模式 / 离开页面 / 上滑取消 / 壳回调 cancelled)
function cancelHold() {
if (phase === 'idle') return;
const r = rec;
rec = null;
chunks = [];
if (r) { r.onstop = null; r.onerror = null; }
releaseStream();
resetUI();
try {
if (r && r.state !== 'inactive') r.stop();
else if (native && native.cancelVoice) native.cancelVoice();
} catch (_) { /* 已停 */ }
}
// ---------- 上传 + 自动发送 ----------
function upload(blob) {
if (!blob || !blob.size) { resetUI(); toast('没有录到声音'); return; }
phase = 'busy';
setOverlayMode('busy');
req('POST', '/api/asr/transcribe', blob, true, 120000)
.then(function (r) {
const text = String((r && r.text) || '').replace(/\s+/g, ' ').trim();
// 先收遮罩再做后续:toast 固定在 bottom:96px,遮罩还在时弹出来会压住声波
resetUI();
if (!text) { toast('没有识别到内容'); return; }
ta.value = text;
send();
})
.catch(function (e) {
resetUI();
toast('语音识别失败:' + String((e && e.message) || e));
});
}
// ---------- 按住 / 滑动 / 松开 ----------
hold.addEventListener('pointerdown', function (e) {
if (e && e.button != null && e.button !== 0) return; // 只响应左键/触摸
e.preventDefault();
if (phase !== 'idle') return;
pressY = e.clientY || 0;
try { hold.setPointerCapture(e.pointerId); } catch (_) { /* 忽略 */ }
startHold();
});
function onMove(e) {
if (!pressing) return;
if (phase !== 'recording' && phase !== 'arming') return;
if (!overlay || overlay.classList.contains('hidden') || !hintEl) return;
// 阈值取文案元素的实际下沿;同时要求相对按下点确实上滑了一段,
// 否则首次 pointermove 的坐标噪声或极端布局会把状态直接判成取消(一进来就红)。
const line = hintEl.getBoundingClientRect().bottom;
const limit = pressY ? Math.min(line - 4, pressY - 24) : (line - 4);
const y = e.clientY;
if (!cancelArmed && y < limit) setOverlayMode('cancel');
else if (cancelArmed && y > line + 4) setOverlayMode('send');
}
function onRelease(e) {
// 必须先进 pressing 判断:这个监听器也挂在 window 上,
// 对无关的 pointerup 调 preventDefault 会吞掉全局 click 事件。
if (!pressing) return;
if (e) e.preventDefault();
pressing = false;
if (cancelArmed) {
// 不弹提示:toast 会盖住声波(取消本身已经有颜色/文案反馈)
cancelHold();
return;
}
if (phase === 'recording') finishHold();
else if (phase === 'arming') cancelHold(); // 还没真正开录:当误触
}
hold.addEventListener('pointerup', onRelease);
hold.addEventListener('pointercancel', onRelease);
hold.addEventListener('pointermove', onMove);
// 兜底:个别环境下 setPointerCapture 不生效,手指移出按钮后也要跟手
window.addEventListener('pointerup', onRelease);
window.addEventListener('pointercancel', onRelease);
window.addEventListener('pointermove', onMove);
// 长按不弹系统菜单(移动端)
hold.addEventListener('contextmenu', function (e) { e.preventDefault(); });
// 键盘可达:空格/回车按下开始,松开结束
hold.addEventListener('keydown', function (e) {
if (e.repeat) return;
if (e.key !== ' ' && e.key !== 'Enter') return;
e.preventDefault();
if (!pressing) startHold();
});
hold.addEventListener('keyup', function (e) {
if (e.key !== ' ' && e.key !== 'Enter') return;
e.preventDefault();
onRelease(null);
});
// 录音中离开页面:释放麦克风
window.addEventListener('pagehide', cancelHold);
// ---------- 原生桥回调(契约见 docs/voice-input.md) ----------
// 实时幅度:套壳每 ~100ms 上报一次 MediaRecorder.getMaxAmplitude() 的**原始值**(0~32767)。
// 换算、门限、平滑全部在页面侧做——规则只存在这一份,壳不要做任何数学。
function onNativeAmp(raw) {
if (!native) return;
const amp = Number(raw);
if (!isFinite(amp)) return;
lastRealLevelAt = Date.now();
if (amp <= 0) {
levelTarget = 0;
} else {
const db = 20 * Math.log10(Math.min(amp, 32767) / 32767);
levelTarget = dbToLevel(db);
}
startLoop(); // 静默态下循环已停,下一帧数据到了再启
}
window.onNativeVoiceAmp = onNativeAmp;
window.onNativeVoiceLevel = onNativeAmp; // 旧名兼容:同样按原始幅度解释
window.onNativeVoiceResult = function (b64, mimeType) {
if (phase !== 'busy' && phase !== 'recording') return;
if (watchdog) { clearTimeout(watchdog); watchdog = null; }
if (discard) { discard = false; resetUI(); toast('说话时间太短'); return; }
try {
const bin = atob(String(b64 || ''));
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
upload(new Blob([arr], { type: mimeType || 'audio/mp4' }));
} catch (_) {
resetUI();
toast('语音数据解析失败');
}
};
window.onNativeVoiceState = function (s) {
if (!native || s !== 'recording' || phase !== 'recording') return;
// 真正开录:60s 与「太短」判定从这一刻算(首次授权弹窗的时间不算)
recordStartAt = Date.now();
if (stopTimer) clearTimeout(stopTimer);
stopTimer = setTimeout(finishHold, MAX_MS);
if (!pressing) finishHold(); // 弹窗期间已经松手:立刻收口(held≈0 → 丢弃)
};
window.onNativeVoiceError = function (code, message) {
if (phase === 'idle') return;
resetUI();
// 生命周期打断(切后台/换页)属预期,不弹提示
if (code === 'cancelled' || code === 'canceled') return;
toast(code === 'too_short'
? '说话时间太短,请按住再说'
: '录音失败:' + String(message || code || '未知错误'));
};
// ---------- 对外暴露给发送键 / sessions.js 的状态查询 ----------
window.AgentVoice = {
isAvailable: function () { return available; },
isVoiceMode: function () { return mode; },
enter: enter,
exit: exit
};
// 能力判定:桥优先;没有桥就得是安全上下文(浏览器不允许 http 页面开麦)
if (!native && !webOk) {
console.info('[voice] 语音入口未启用:没有 window.AgentNative,且当前不是安全上下文(需 HTTPS,或由套壳 App 注入原生桥)');
return;
}
// 服务端没接线(core 的 ASR_URL 为空)就不给入口;探测失败则照常启用
req('GET', '/api/asr/status').then(function (s) {
if (s && s.enabled === false) {
console.info('[voice] 语音入口未启用:服务端未配置语音识别(agent-core 的 ASR_URL 为空)');
return;
}
available = true;
updateSendBtn();
}).catch(function () {
available = true;
updateSendBtn();
});
})();
+71
View File
@@ -0,0 +1,71 @@
// 语音识别代理:浏览器 / 套壳 App 录好的音频 → agent-core → mcp_asr → 文字。
//
// 为什么要 core 中转、而不是前端直连 ASR 容器:mcp_asr 只挂在 agent-mcp-net 内网、
// 一个宿主端口都不占(它自身没有鉴权,暴露即被白嫖)。对外唯一的入口仍是 core,
// 鉴权沿用全局登录态(auth.middleware 已挂在 /api 之前)。
//
// 开关:core 的 ASR_URL 为空 = 未部署语音识别,本路由一律 503,前端据此不显示麦克风。
const express = require('express');
const log = require('../log');
const router = express.Router();
const ASR_URL = String(process.env.ASR_URL || '').trim().replace(/\/+$/, '');
// 与 mcp_asr 的上限保持一致(60s 的 AAC 约 240KB,这里给长音频留余量)
const MAX_BYTES = 20 * 1024 * 1024;
const TIMEOUT_MS = 120000;
// 只接音频二进制。全局 express.json(2mb) 只解析 application/json,两者不冲突。
// 注意 WebView 可能发 audio/mp4、audio/webm;codecs=opus,统一按 audio/* 接。
const rawAudio = express.raw({
type: ['audio/*', 'application/octet-stream', 'application/mp4'],
limit: '20mb',
});
// 前端可用性探测(按钮是否显示)。不碰网络,纯看接线。
router.get('/status', function (req, res) {
res.json({ enabled: !!ASR_URL, max_bytes: MAX_BYTES });
});
router.post('/transcribe', rawAudio, async function (req, res) {
if (!ASR_URL) {
return res.status(503).json({ error: '语音识别未配置(core 未设置 ASR_URL)' });
}
const buf = req.body;
if (!Buffer.isBuffer(buf) || !buf.length) {
return res.status(400).json({ error: '未收到音频数据(Content-Type 需为 audio/*)' });
}
try {
const r = await fetch(ASR_URL + '/transcribe', {
method: 'POST',
headers: { 'Content-Type': req.headers['content-type'] || 'application/octet-stream' },
body: buf,
signal: AbortSignal.timeout(TIMEOUT_MS),
});
const text = await r.text();
if (!r.ok) {
// ASR 服务回的是 {error:string}:解出来再转,不然前端会看到两层套嵌的 JSON
let msg = text.slice(0, 300);
try { msg = JSON.parse(text).error || msg; } catch (_) { /* 非 JSON 保留原文 */ }
log.warn('asr', '识别失败 HTTP ' + r.status + ':' + msg);
// 4xx(静音 / 坏音频 / 过载)原样透传;5xx 统一当上游故障
const code = r.status >= 400 && r.status < 500 ? r.status : 502;
return res.status(code).json({ error: msg });
}
// 原样透传 ASR 的 {text, ms, backend}
res.type('application/json').send(text);
} catch (e) {
log.warn('asr', '调用 ASR 服务失败:' + String(e && e.message || e));
res.status(502).json({ error: '语音识别服务不可用:' + String(e && e.message || e) });
}
});
// express.raw 超限时抛 entity.too.large,默认会回 HTML;这里翻成前端能读的 JSON。
router.use(function (err, req, res, next) {
if (err && (err.type === 'entity.too.large' || err.status === 413)) {
return res.status(413).json({ error: '音频过大(上限 ' + Math.round(MAX_BYTES / 1048576) + 'MB)' });
}
next(err);
});
module.exports = router;
+1 -1
View File
@@ -15,7 +15,7 @@ const router = express.Router();
const STARTED_AT = Date.now();
// 版本以本文件字面量为准:容器部署只挂载 app/server,镜像里的 package.json 可能是旧的,
// 读它会一直显示发版时的版本号(之前 2.1.0 改完仍显 2.0.0 即此因)。发版时记得同步这里。
const VERSION = '2.3.0';
const VERSION = '2.4.0';
// git 提交号单独返回(提交时 post-commit 钩子自动生成),前端只显示简洁版本号
const VERSION_COMMIT = versionInfo.commit || '';
+19 -1
View File
@@ -71,6 +71,9 @@ app.use('/api/sessions', require('./routes/files'));
// 与 /api/db 对称;执行核心仍复用 tools/skills.runSkill,core 不感知具体技能。
app.use('/api/sessions', require('./routes/skill-run'));
app.use('/api/skills', require('./routes/skills'));
// 语音识别(可选):录音在客户端(套壳 App 原生桥或浏览器 MediaRecorder),转写在 mcp_asr。
// ASR_URL 为空时接口回 503,前端据此不显示麦克风按钮(见 routes/asr.js)。
app.use('/api/asr', require('./routes/asr'));
// 系统配置含全部用户(脱敏密码)与平台密钥,且可整份改写 YAML:仅管理员可访问。
app.use('/api/config', auth.requireAdmin, require('./routes/config'));
app.use('/api/platforms', require('./routes/platforms'));
@@ -145,7 +148,22 @@ app.get('/api/models', (req, res) => {
res.json(rows);
});
app.get('/api/health', (req, res) => res.json({ ok: true, time: Date.now() }));
// 探活 + 服务器地址校验(免认证,见 auth.js 的 PUBLIC_EXACT)。
// 套壳 App / 运维脚本会手动填服务器地址,必须能判断“这个地址到底是不是本服务”:
// 只认 HTTP 200 + body.ok===true + service==='agent-core',不能只看状态码——
// 填到别的站点、反代首页或劫持页同样可能回 200。
// no-store:避免 WebView / 反向代理 / Service Worker 把旧响应当成“服务在线”。
// auth_required 让客户端区分“连上了但没登录”和“地址填错了”。
app.get('/api/health', (req, res) => {
res.setHeader('Cache-Control', 'no-store');
res.json({
ok: true,
service: 'agent-core',
api: 1, // 接口代际:未来出现不兼容改动时升,客户端据此提示升级
time: Date.now(),
auth_required: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
});
});
const PORT = process.env.PORT || cfg.port;