speakdock-mcp 0.5.0 → 0.6.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.
@@ -19,6 +19,8 @@
19
19
  import fs from 'node:fs';
20
20
  import path from 'node:path';
21
21
  import os from 'node:os';
22
+ import { spawn } from 'node:child_process';
23
+ import { fileURLToPath } from 'node:url';
22
24
 
23
25
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
24
26
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
@@ -69,15 +71,161 @@ async function call(method, pathAndQuery, body, timeoutMs) {
69
71
  }
70
72
  }
71
73
 
72
- /** 统一的失败话术:网关没起是**最常见**的情况,别让它看起来像模型出错。 */
74
+ const USER_CLOSED_FILE = path.join(os.homedir(), '.speakdock', 'user-closed.json');
75
+ const USER_CLOSED_HARD_COOLDOWN_SEC = 60;
76
+ const USER_CLOSED_LOCK_SEC = 300; // 5 分钟后不再自动拉起,需用户手动重开
77
+ const USER_CLOSED_RESET_SEC = 1800; // 30 分钟后自然过期
78
+ const MAX_AUTO_OPENS_PER_10MIN = 2;
79
+
80
+ function readUserClosedState() {
81
+ try {
82
+ if (!fs.existsSync(USER_CLOSED_FILE)) return { closed_at: null, auto_open_times: [] };
83
+ const raw = fs.readFileSync(USER_CLOSED_FILE, 'utf8').replace(/^\uFEFF/, '');
84
+ const data = JSON.parse(raw);
85
+ return {
86
+ closed_at: Number(data?.closed_at) || null,
87
+ auto_open_times: Array.isArray(data?.auto_open_times) ? data.auto_open_times.map(Number).filter(Number.isFinite) : [],
88
+ };
89
+ } catch {
90
+ return { closed_at: null, auto_open_times: [] };
91
+ }
92
+ }
93
+
94
+ function recordAutoOpenTime() {
95
+ try {
96
+ const nowSec = Math.floor(Date.now() / 1000);
97
+ const st = readUserClosedState();
98
+ const recent = st.auto_open_times.filter((t) => (nowSec - t) <= 600);
99
+ recent.push(nowSec);
100
+ fs.mkdirSync(path.dirname(USER_CLOSED_FILE), { recursive: true });
101
+ fs.writeFileSync(USER_CLOSED_FILE, JSON.stringify({ closed_at: st.closed_at, auto_open_times: recent }, null, 2), 'utf8');
102
+ } catch {}
103
+ }
104
+
105
+ /** 统一的失败话术:网关没起时结合共享冷却文件返回清晰契约文案。 */
73
106
  function failText(err) {
74
107
  const msg = String(err?.message ?? err);
108
+ if (/手动关闭浮窗|已达自动拉起上限|网关已停止/.test(msg)) return msg;
75
109
  if (/ECONNREFUSED|fetch failed|无法连接/i.test(msg)) {
110
+ const st = readUserClosedState();
111
+ if (st.closed_at) {
112
+ const ago = Math.max(0, Math.floor(Date.now() / 1000) - st.closed_at);
113
+ if (ago < USER_CLOSED_RESET_SEC) {
114
+ return `感官网关已停止(用户于 ${ago} 秒前手动关闭了浮窗)。如需重新启用,请由用户手动打开浮窗或显式要求重开。`;
115
+ }
116
+ }
76
117
  return `感官网关没在跑(${BASE})。启动:首次使用请先运行 SpeakDock 的 gateway/scripts/setup.ps1 完成环境初始化,再运行 gateway/scripts/open-window.ps1 启动本机网关与浮窗。`;
77
118
  }
78
119
  return `感官网关调用失败:${msg}`;
79
120
  }
80
121
 
122
+ function findGatewayDirs() {
123
+ const dirs = [];
124
+ if (process.env.SENSE_GATEWAY_HOME) dirs.push(process.env.SENSE_GATEWAY_HOME);
125
+ try {
126
+ const here = path.dirname(fileURLToPath(import.meta.url));
127
+ dirs.push(path.resolve(here, '../../gateway'));
128
+ dirs.push(path.resolve(here, '../../../gateway'));
129
+ } catch {}
130
+ dirs.push('D:\\tools\\sense-gateway');
131
+ return [...new Set(dirs)].filter((d) => {
132
+ try { return fs.existsSync(path.join(d, 'gateway.py')); } catch { return false; }
133
+ });
134
+ }
135
+
136
+ function checkAutoOpenAllowed(humanInitiated = false) {
137
+ const nowSec = Math.floor(Date.now() / 1000);
138
+ const st = readUserClosedState();
139
+ const recentOpens = st.auto_open_times.filter((t) => (nowSec - t) <= 600);
140
+ if (recentOpens.length >= MAX_AUTO_OPENS_PER_10MIN) {
141
+ return {
142
+ allowed: false,
143
+ reason: `感官网关已达自动拉起上限(10 分钟内已自动启动 ${recentOpens.length} 次),为避免打扰已锁定,请由用户手动打开浮窗。`,
144
+ };
145
+ }
146
+ if (st.closed_at) {
147
+ const ago = nowSec - st.closed_at;
148
+ if (ago >= 0 && ago < USER_CLOSED_HARD_COOLDOWN_SEC) {
149
+ return {
150
+ allowed: false,
151
+ reason: `感官网关已由用户于 ${ago} 秒前手动关闭浮窗退出(60 秒硬冷却期内拒绝自动重开,还剩 ${USER_CLOSED_HARD_COOLDOWN_SEC - ago} 秒)。`,
152
+ };
153
+ }
154
+ if (ago >= USER_CLOSED_HARD_COOLDOWN_SEC && ago < USER_CLOSED_LOCK_SEC && !humanInitiated) {
155
+ return {
156
+ allowed: false,
157
+ reason: `感官网关已停止(用户 ${ago} 秒前手动关闭浮窗),5 分钟内仅允许人触发的显式请求拉起。`,
158
+ };
159
+ }
160
+ if (ago >= USER_CLOSED_LOCK_SEC && ago < USER_CLOSED_RESET_SEC) {
161
+ return {
162
+ allowed: false,
163
+ reason: `感官网关已停止(用户 ${Math.round(ago / 60)} 分钟前手动关闭浮窗),如需恢复请由用户手动打开浮窗。`,
164
+ };
165
+ }
166
+ }
167
+ return { allowed: true };
168
+ }
169
+
170
+ async function ensureGatewayWithWindow(humanInitiated = false) {
171
+ const check = checkAutoOpenAllowed(humanInitiated);
172
+ if (!check.allowed) {
173
+ throw new Error(check.reason);
174
+ }
175
+ const dirs = findGatewayDirs();
176
+ if (!dirs.length) return false;
177
+ const gwDir = dirs[0];
178
+ const startPs1 = path.join(gwDir, 'scripts', 'start-gateway.ps1');
179
+ try {
180
+ if (fs.existsSync(startPs1)) {
181
+ const child = spawn('powershell.exe', ['-NoProfile', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass', '-File', startPs1], {
182
+ cwd: gwDir,
183
+ detached: true,
184
+ stdio: 'ignore',
185
+ windowsHide: true,
186
+ });
187
+ child.unref();
188
+ } else {
189
+ const pyw = fs.existsSync('D:\\tools\\python\\pythonw.exe') ? 'D:\\tools\\python\\pythonw.exe' : 'pythonw.exe';
190
+ const child = spawn(pyw, [path.join(gwDir, 'gateway.py')], {
191
+ cwd: gwDir,
192
+ detached: true,
193
+ stdio: 'ignore',
194
+ windowsHide: true,
195
+ });
196
+ child.unref();
197
+ }
198
+ } catch {
199
+ return false;
200
+ }
201
+ const deadline = Date.now() + 8000;
202
+ while (Date.now() < deadline) {
203
+ await new Promise((r) => setTimeout(r, 350));
204
+ try {
205
+ const h = await call('GET', '/health', undefined, 1500);
206
+ if (h?.ok) {
207
+ recordAutoOpenTime();
208
+ try { await call('POST', '/window/open', { topmost: true }, 5000); } catch {}
209
+ return true;
210
+ }
211
+ } catch {}
212
+ }
213
+ return false;
214
+ }
215
+
216
+ /** 仅用于显式人触发的感官请求:网关未起时按分级退避策略拉起并弹出浮窗,后台轮询禁止调用此函数。 */
217
+ async function callSensory(method, pathAndQuery, body, timeoutMs, { humanInitiated = true } = {}) {
218
+ try {
219
+ return await call(method, pathAndQuery, body, timeoutMs);
220
+ } catch (err) {
221
+ const msg = String(err?.message ?? err);
222
+ if (!/ECONNREFUSED|fetch failed|无法连接/i.test(msg)) throw err;
223
+ const launched = await ensureGatewayWithWindow(humanInitiated);
224
+ if (!launched) throw err;
225
+ return await call(method, pathAndQuery, body, timeoutMs);
226
+ }
227
+ }
228
+
81
229
  function readMcpVersion() {
82
230
  for (const rel of ['../package.json', '../../package.json']) {
83
231
  try {
@@ -110,6 +258,7 @@ server.tool(
110
258
  const since = Number.isFinite(after_seq) ? Number(after_seq) : readCursor(who);
111
259
  const seconds = Math.min(60, Math.max(1, Number(timeout_sec) || 25));
112
260
  try {
261
+ // 后台轮询禁止触发自启/弹窗,防止关窗后反复重弹
113
262
  const data = await call(
114
263
  'GET',
115
264
  `/chat/wait?after_seq=${since}&target=${encodeURIComponent(who)}&timeout_sec=${seconds}`,
@@ -179,14 +328,17 @@ server.tool(
179
328
  interrupt: z.boolean().optional().describe('是否打断当前正在播的,默认 true'),
180
329
  source: z.string().optional()
181
330
  .describe("谁的音色/气泡:dsh(大鲸鱼) / feiyu_qq(肥鱼) / antigravity(哈基米),默认 dsh"),
331
+ leave: z.boolean().optional()
332
+ .describe('说完后立即标记下麦(黄灯秒变灰),退出语音会话告别时传 true,默认 false'),
182
333
  },
183
- async ({ text, display_text, interrupt, source }) => {
334
+ async ({ text, display_text, interrupt, source, leave }) => {
184
335
  try {
185
- const r = await call('POST', '/tts', {
336
+ const r = await callSensory('POST', '/tts', {
186
337
  text: String(text),
187
338
  display_text: display_text ? String(display_text) : String(text),
188
339
  interrupt: interrupt !== false,
189
340
  record_chat: true,
341
+ leave_loop: leave === true,
190
342
  // 网关按 source 分气泡颜色和音色(config.tts_voice_by_source 可再覆盖)。
191
343
  // 肥鱼那个会话调这个工具时传 feiyu_qq,才能用她自己的头像和嗓子。
192
344
  source: String(source || 'dsh').trim() || 'dsh',
@@ -368,14 +520,21 @@ server.tool(
368
520
  */
369
521
  server.tool(
370
522
  'sense_frame',
371
- '看屏幕:抓当前一帧,或把变化最大的几帧拼成一张(走感官网关 /frame,省 token)。',
523
+ '看屏幕:抓当前一帧,或按时间跨度+变化量把最关键的几帧拼成一张(走感官网关 /frame,省 token)。',
372
524
  {
373
525
  frames: z.number().min(1).max(6).optional().describe('拼几帧,默认 4;1 = 只抓当前一帧'),
374
- region: z.string().optional().describe('只看一块:x,y,w,h(屏幕物理像素,用来读小字)'),
526
+ span: z.number().min(5).max(1800).optional().describe('时间跨度(秒,如 60/180/300),在最近 span 秒内按变化量+均匀度选帧,默认 180'),
527
+ highlight: z.boolean().optional().describe('是否用琥珀色框+★标出变化最大的历史帧,默认 false'),
528
+ stamp: z.boolean().optional().describe('是否在每帧左上角打时间戳水印,默认 true'),
529
+ use_region: z.boolean().optional().describe('是否显式套用用户在浮窗中框选的固定观察区域,默认 false(全屏)'),
530
+ adaptive: z.boolean().optional().describe('画面基本静止时是否自动降帧以提升清晰度,默认 true;传 false 强制满格'),
531
+ open_window: z.boolean().optional().describe('网关未起或浮窗未开时是否显式弹出浮窗,默认 false(后台截屏不主动弹窗打扰)'),
532
+ region: z.string().optional().describe('临时覆盖观察区域:x,y,w,h(支持物理像素或 0~1 归一化比例,用来读小字)'),
375
533
  width: z.number().optional().describe('画布宽,默认 798'),
376
534
  height: z.number().optional().describe('画布高,默认 462'),
535
+ max_bytes: z.number().min(10000).max(5000000).optional().describe('可选体积上限(字节),超出自动降低 JPEG 质量'),
377
536
  },
378
- async ({ frames, region, width, height }) => {
537
+ async ({ frames, span, highlight, stamp, use_region, adaptive, open_window, region, width, height, max_bytes }) => {
379
538
  const n = Math.min(6, Math.max(1, Math.trunc(Number(frames) || 4)));
380
539
  const w = Math.max(200, Math.min(1600, Math.trunc(Number(width) || 798)));
381
540
  const h = Math.max(120, Math.min(1200, Math.trunc(Number(height) || 462)));
@@ -387,9 +546,18 @@ server.tool(
387
546
  h: String(h),
388
547
  base64: '1',
389
548
  });
549
+ if (Number.isFinite(Number(span)) && Number(span) > 0) qs.set('span', String(Number(span)));
550
+ if (highlight) qs.set('highlight', '1');
551
+ if (stamp === false) qs.set('stamp', '0');
552
+ if (use_region === true) qs.set('use_region', '1');
553
+ if (adaptive === false) qs.set('adaptive', '0');
554
+ if (open_window === true) qs.set('open_window', '1');
555
+ if (Number.isFinite(Number(max_bytes)) && Number(max_bytes) > 0) qs.set('max_bytes', String(Math.trunc(Number(max_bytes))));
390
556
  if (region) qs.set('region', String(region).trim());
391
557
  try {
392
- const data = await call('GET', `/frame?${qs.toString()}`, undefined, 30_000);
558
+ const data = open_window === true
559
+ ? await callSensory('GET', `/frame?${qs.toString()}`, undefined, 30_000, { humanInitiated: true })
560
+ : await call('GET', `/frame?${qs.toString()}`, undefined, 30_000);
393
561
  if (!data?.ok || !data?.base64) {
394
562
  return {
395
563
  content: [{ type: 'text', text: `抓屏失败:${JSON.stringify(data).slice(0, 200)}` }],
@@ -398,11 +566,11 @@ server.tool(
398
566
  }
399
567
  const list = Array.isArray(data.frames) ? data.frames : [];
400
568
  const meta = list
401
- .map((f) => `${f.time ?? '?'}${Number.isFinite(Number(f.diff)) ? `(Δ${Number(f.diff).toFixed(2)})` : ''}`)
569
+ .map((f) => `${f.highlight ? '★' : ''}${f.time ?? '?'}${Number.isFinite(Number(f.diff)) ? `(Δ${Number(f.diff).toFixed(2)})` : ''}`)
402
570
  .join(' / ');
403
571
  const head = `${data.width}x${data.height} · 约 ${data.token_est ?? '?'} token · ${list.length} 帧`
404
572
  + (meta ? ` · ${meta}` : '')
405
- + (region ? ` · 局部 ${region}` : '');
573
+ + (region ? ` · 局部 ${region}` : (data.region_applied ? ` · 选区 ${data.region_applied.join(',')}` : ''));
406
574
  return {
407
575
  content: [
408
576
  { type: 'text', text: head },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "speakdock-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "MCP stdio bridge for SpeakDock — cross-host local live voice & screen companion gateway (Windows 10/11).",
5
5
  "keywords": [
6
6
  "mcp",
@@ -35,4 +35,4 @@
35
35
  "directory": "packages/speakdock-mcp"
36
36
  },
37
37
  "homepage": "https://github.com/gggoe/SpeakDock#readme"
38
- }
38
+ }