dsh-watch-together 0.2.1 → 0.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-watch-together",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Watch a video together with a text-only agent: follow the user's real playback position, hand over one segment at a time just before it ends, and keep a single text stream of scripted lines, interjections and the user's replies.",
5
5
  "keywords": [
6
6
  "dsh",
@@ -53,7 +53,6 @@
53
53
  "src",
54
54
  "lib",
55
55
  "bin",
56
- "examples",
57
56
  "extension",
58
57
  "scripts",
59
58
  "docs",
@@ -62,7 +61,12 @@
62
61
  "README.md",
63
62
  "CHANGELOG.md",
64
63
  "LICENSE",
65
- "NOTICE"
64
+ "NOTICE",
65
+ "examples/floating-chat/*.py",
66
+ "examples/floating-chat/*.cmd",
67
+ "examples/floating-chat/*.png",
68
+ "examples/floating-chat/*.txt",
69
+ "examples/voice-edge-tts/index.mjs"
66
70
  ],
67
71
  "engines": {
68
72
  "node": ">=20"
@@ -95,6 +99,17 @@
95
99
  },
96
100
  "client": {
97
101
  "platform": "web"
102
+ },
103
+ "catalog": {
104
+ "category": "tool",
105
+ "summary": {
106
+ "en": "Watch a video together with a text-only agent: it follows your real playback position and hands over one segment at a time, just before that segment ends.",
107
+ "zh": "和只有文字的智能体一起看视频:跟着你真实的播放位置,一段一段把画面和台词交到它手上,在每段结束前说完。"
108
+ },
109
+ "capabilities": [
110
+ "fs",
111
+ "shell"
112
+ ]
98
113
  }
99
114
  }
100
115
  }
package/src/chat-store.js CHANGED
@@ -23,9 +23,8 @@ import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, readSync,
23
23
  import { join } from 'node:path';
24
24
 
25
25
  import { cacheDir } from 'dsh-video-storyboard/cache';
26
- import { emitSpeech, onSpeech, speechSubscribers } from './voice.js';
27
26
  import { noteReply } from './reply-guard.js';
28
- import { appendWindowEvent } from './window-protocol.js';
27
+ import { getTtsPort, getWindowPort } from './runtime-ports.js';
29
28
 
30
29
  /** 聊天记录(jsonl,一行一条 {role, text, at}) */
31
30
  export function chatFile(env = process.env) {
@@ -103,10 +102,15 @@ export function appendChat(role, text, meta = {}, env = process.env) {
103
102
  // 浏览器页和旧窗口还能读;窗口按 (role, text, at) 去重,不会出现两遍。
104
103
  // 写失败不能影响聊天主流程 —— 窗口是展示层,不是数据层。
105
104
  try {
106
- appendWindowEvent({
107
- type: role === 'meta' ? 'meta' : 'message',
108
- role, text: entry.text, at: entry.at, ...(entry.t != null ? { t: entry.t } : {}),
109
- }, env);
105
+ const win = getWindowPort();
106
+ if (role === 'meta') {
107
+ win.meta(entry.text, { role, at: entry.at }, env);
108
+ } else {
109
+ win.message({
110
+ role, text: entry.text, at: entry.at,
111
+ ...(entry.t != null ? { t: entry.t } : {}),
112
+ }, env);
113
+ }
110
114
  } catch { /* 展示接口不可用时静默降级到 chat.jsonl */ }
111
115
  return entry;
112
116
  }
@@ -132,7 +136,9 @@ export function appendChat(role, text, meta = {}, env = process.env) {
132
136
  * @param {{ env?: object, onEntry?: (e:object)=>void, fallbackMs?: number }} [o]
133
137
  * `fallbackMs` 兜底等待(默认 2500ms,可用 `DSH_WATCH_CAPTION_FALLBACK_MS` 覆盖)
134
138
  */
135
- export function attachSpeechToChat({ env = process.env, onEntry = null, fallbackMs = null } = {}) {
139
+ export function attachSpeechToChat({
140
+ env = process.env, onEntry = null, fallbackMs = null, tts = null,
141
+ } = {}) {
136
142
  const fromEnv = Number(env?.DSH_WATCH_CAPTION_FALLBACK_MS);
137
143
  const waitMs = Number.isFinite(fallbackMs) && fallbackMs >= 0
138
144
  ? Number(fallbackMs)
@@ -152,7 +158,8 @@ export function attachSpeechToChat({ env = process.env, onEntry = null, fallback
152
158
  try { onEntry?.(entry); } catch { /* 展示层的事,别影响写盘 */ }
153
159
  };
154
160
 
155
- const off = onSpeech((e) => {
161
+ const bus = tts ?? getTtsPort();
162
+ const off = bus.subscribe((e) => {
156
163
  // 插话那句是**先写流再广播**的(`appendSpoken`),这里再写就重复了
157
164
  if (e.origin === 'chat') return;
158
165
  if (e.state !== 'due' && e.state !== 'spoken' && e.state !== 'skipped') return;
@@ -178,7 +185,7 @@ export function attachSpeechToChat({ env = process.env, onEntry = null, fallback
178
185
  }
179
186
 
180
187
  // `due`:没人会出声就直接写 —— 零依赖路径不能因为等不到 `spoken` 而变哑
181
- if (speechSubscribers() === 0) { write({ at: e.at, text }); return; }
188
+ if (bus.subscribers() === 0) { write({ at: e.at, text }); return; }
182
189
  if (waiting.has(key) || writtenKeys.has(key)) return;
183
190
  const timer = setTimeout(() => {
184
191
  waiting.delete(key);
@@ -240,7 +247,7 @@ export function appendSpoken(role, text, { t = null, env = process.env, speak =
240
247
  // **登记**:这句已经在流里了。之后声音适配器发来的 `spoken`(没有 origin)看到这条就不会再写一遍。
241
248
  writtenKeys.add(speechKey(t, clean));
242
249
  if (writtenKeys.size > 500) writtenKeys.clear();
243
- if (speak) emitSpeech({ at: t, text: clean, state: 'due', origin: 'chat' });
250
+ if (speak) getTtsPort().due({ at: t, text: clean, origin: 'chat' });
244
251
  return entry;
245
252
  }
246
253
 
package/src/handler.js CHANGED
@@ -17,6 +17,7 @@ import { configuredPort } from 'dsh-video-storyboard/browser-time';
17
17
  import { createInputSurface } from './input-surface.js';
18
18
  import { createWatchInterfaces } from './interfaces.js';
19
19
  import { appendAssistantSay } from './chat.js';
20
+ import { installPorts } from './runtime-ports.js';
20
21
  import { replyReminder } from './interject.js';
21
22
  import { pullLinesNear, pulledLinesNote } from './reply-guard.js';
22
23
  import { serviceOf } from './timer.js';
@@ -40,6 +41,9 @@ export async function execute(ctx, args, {
40
41
  } = {}) {
41
42
  // 识别 / TTS / 悬浮窗只从这里拿;测试和伴生插件可以注入自己的实现。
42
43
  const api = interfaces ?? createWatchInterfaces();
44
+ // 把接口装进 runtime-ports:chat-store / watch-loop 等核心模块只拿端口,
45
+ // 不再 import voice.js / floating-window.js。
46
+ installPorts({ tts: api.tts, window: api.window });
43
47
  const problems = validateWatchArgs(args);
44
48
  // 这一次调用看到的循环状态:说话要用它的位置,开窗要用它的源。只读一次。
45
49
  const st0 = loopStatus();
@@ -92,7 +96,9 @@ export async function execute(ctx, args, {
92
96
  // `waitForVideo` 会在主流程之外提前预铺一遍,那一遍要是少了 `input`/`reopen`,
93
97
  // 后面真正的调用就再也传不进去 —— 用户关过窗、模型调 `waitForVideo` 时,
94
98
  // 因为没有 `input` 就判不出 `hung`,窗口又被顶回来("关了它自己弹出来"那个实报)。
95
- const prepareInputSurface = createInputSurface({ windowService: api.window });
99
+ const prepareInputSurface = createInputSurface({
100
+ windowService: api.window, tts: api.tts,
101
+ });
96
102
  const known = typeof args.input === 'string' && args.input.trim()
97
103
  ? args.input
98
104
  : (typeof st0.input === 'string' && st0.input ? st0.input : null);
@@ -117,6 +123,7 @@ export async function execute(ctx, args, {
117
123
  // 单发命令(status / voices / speak / cookies / wake / stop)在这里分流
118
124
  const quick = await runWatchAction(args, {
119
125
  ctx, sessionId, browserPort: args.browserPort ?? configuredPort(),
126
+ tts: api.tts, window: api.window,
120
127
  });
121
128
  // **待回执也跟着单发命令走**:模型很可能先 statusOnly 看一眼再回话,
122
129
  // 那一步用户同样只会看到沉默 —— 提醒要挂在每一条返回上,不能只挂主流程。
@@ -173,6 +180,8 @@ export async function execute(ctx, args, {
173
180
  formatManifest: api.recognition.manifest,
174
181
  signal,
175
182
  prepareWait: prepareInputSurface,
183
+ // 窗口存活也只走接口;不再让 watch-run 直接 import floating-window
184
+ windowAlive: () => api.window.alive(),
176
185
  // 关窗即收工:只有这次真把窗口开起来了,才把"窗口没了"当作"不看了"
177
186
  expectWindow: surface?.windowOpen === true,
178
187
  // 宿主没有 attachments 服务时给可读错误,而不是 TypeError(也不能靠 inject 硬等,见 index.js)。
@@ -216,6 +225,7 @@ export async function execute(ctx, args, {
216
225
  startWatchLoop({
217
226
  ctx, sessionId, input: r.input,
218
227
  tts: api.tts,
228
+ window: api.window,
219
229
  cursor: r.cursor, status: r.status,
220
230
  // 段缓存只用来报"缓存里已有几段"(statusOnly),不参与决策
221
231
  cache,
package/src/index.js CHANGED
@@ -17,8 +17,8 @@
17
17
  */
18
18
 
19
19
  import { attachSpeechToChat } from './chat.js';
20
+ import { getTtsPort } from './runtime-ports.js';
20
21
  import { watchTools } from './register.js';
21
- import { attachConfiguredVoice } from './voice.js';
22
22
  import { createSettingsPage } from './settings/server.js';
23
23
 
24
24
  export const name = 'dsh-watch-together';
@@ -99,11 +99,11 @@ async function registerAll(ctx) {
99
99
  }
100
100
  }
101
101
 
102
- // 声音适配器(可选)。核心**不内置任何引擎**:只按 `~/.dsh/voice.json` 里写的那个路径
103
- // 去 dynamic import,挂不上就算了 —— 声音是加分项,装坏了不能让插件起不来。
102
+ // 声音适配器(可选):只通过 tts 接口挂,不 import voice.js。
103
+ // 这里也保留启动时挂载,这样第一次只调 `say`(还没开窗)也有声音。
104
104
  try {
105
- const v = await attachConfiguredVoice({ log: (m) => ctx?.logger?.info?.(m) });
106
- if (!v.ok && v.reason !== 'not-configured') {
105
+ const v = await getTtsPort().attachConfigured?.({ log: (m) => ctx?.logger?.info?.(m) });
106
+ if (v && !v.ok && v.reason !== 'not-configured') {
107
107
  ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter not loaded: ${v.reason}`);
108
108
  }
109
109
  } catch (e) {
@@ -23,10 +23,9 @@
23
23
  import {
24
24
  DEFAULT_CHAT_PORT, appendSpoken, chatAlive, chatPageUrl, ensureChatSession,
25
25
  } from './chat.js';
26
- import { floatingWindowAlive, openFloatingWindow } from './floating-window.js';
26
+ import { getTtsPort, getWindowPort } from './runtime-ports.js';
27
27
  import { loopStatus, stopWatchLoop } from './watch-loop.js';
28
28
  import { clearHungUp, isHungUp, markHungUp } from './watch-state.js';
29
- import { attachConfiguredVoice, attachedAdapters, configuredVoiceAdapter } from './voice.js';
30
29
 
31
30
  /**
32
31
  * 造一个"准备输入面"的函数:**幂等**,同一个 execute 里调几次都只开一次窗。
@@ -36,7 +35,7 @@ import { attachConfiguredVoice, attachedAdapters, configuredVoiceAdapter } from
36
35
  *
37
36
  * @returns {() => Promise<{note: string}>}
38
37
  */
39
- export function createInputSurface({ windowService = null } = {}) {
38
+ export function createInputSurface({ windowService = null, tts = null } = {}) {
40
39
  let prepared = null;
41
40
  /**
42
41
  * @param {{start?: boolean}} [o]
@@ -47,7 +46,7 @@ export function createInputSurface({ windowService = null } = {}) {
47
46
  * "我不看了"的方式,下一次调用立刻又把窗口顶回来,等于把他的动作撤销了。
48
47
  */
49
48
  return ({ start = false, input = null, reopen = false } = {}) => {
50
- prepared ??= open({ start, input, reopen, windowService });
49
+ prepared ??= open({ start, input, reopen, windowService, tts });
51
50
  return prepared;
52
51
  };
53
52
  }
@@ -56,25 +55,27 @@ export function createInputSurface({ windowService = null } = {}) {
56
55
  let announced = false;
57
56
 
58
57
  /** 声音适配器:没挂就挂上(挂过就直接复用)。返回一句给人看的状态。 */
59
- async function ensureVoice() {
58
+ async function ensureVoice(tts) {
59
+ const bus = tts ?? getTtsPort();
60
60
  let spec = '';
61
61
  try {
62
- spec = String(configuredVoiceAdapter() ?? '').trim();
62
+ spec = String(bus.configured?.() ?? '').trim();
63
63
  } catch { spec = ''; }
64
64
  if (!spec) return { ok: false, reason: 'voice.json 没配 adapter' };
65
- if (attachedAdapters().includes(spec)) return { ok: true, name: tail(spec), cached: true };
66
- const r = await attachConfiguredVoice({ log: () => {} })
65
+ if ((bus.attached?.() ?? []).includes(spec)) return { ok: true, name: tail(spec), cached: true };
66
+ const r = await Promise.resolve(bus.attachConfigured?.({ log: () => {} }))
67
67
  .catch((e) => ({ ok: false, reason: String(e?.message ?? e) }));
68
68
  return { ok: r?.ok === true, name: r?.name ?? tail(spec), reason: r?.reason };
69
69
  }
70
70
 
71
71
  const tail = (p) => String(p).split(/[\\/]/).filter(Boolean).pop() || String(p);
72
72
 
73
- async function open({ start = false, input = null, reopen = false, windowService = null } = {}) {
74
- const winAlive = () => (windowService ? windowService.alive() : floatingWindowAlive());
75
- const winOpen = (opts) => (windowService ? windowService.open(opts) : openFloatingWindow(opts));
73
+ async function open({ start = false, input = null, reopen = false, windowService = null, tts = null } = {}) {
74
+ const winPort = windowService ?? getWindowPort();
75
+ const winAlive = () => winPort.alive();
76
+ const winOpen = (opts) => winPort.open(opts);
76
77
  // 0) 声音:每次开始陪看都确认一次 —— 不挂的话台词只会写进流、一句也不念
77
- const voice = await ensureVoice();
78
+ const voice = await ensureVoice(tts);
78
79
  const voiceNote = voice.ok
79
80
  ? `声音:${voice.name}${voice.cached ? ' 已在' : ' 已挂上'}`
80
81
  : `声音:没挂(${voice.reason ?? '未知原因'}),台词只写不念`;
package/src/interfaces.js CHANGED
@@ -15,9 +15,11 @@ import { createRecognitionInterface } from './recognition-interface.js';
15
15
  import { createTtsInterface } from './tts-interface.js';
16
16
  import { createWindowInterface } from './window-interface.js';
17
17
  import * as speechBus from './speech-bus.js';
18
+ import * as voiceAdapter from './voice-adapter.js';
18
19
  import { runStoryboard } from 'dsh-video-storyboard/pipeline';
19
20
  import { formatManifest } from 'dsh-video-storyboard/format';
20
21
  import { cachedCues } from './lines-util.js';
22
+ import { installPorts } from './runtime-ports.js';
21
23
 
22
24
  export const INTERFACE_VERSION = '1.0.0';
23
25
 
@@ -27,17 +29,21 @@ export function createWatchInterfaces(overrides = {}) {
27
29
  formatManifest,
28
30
  cues: cachedCues,
29
31
  });
30
- const tts = overrides.tts ?? createTtsInterface(speechBus);
32
+ const tts = overrides.tts ?? createTtsInterface({ ...speechBus, ...voiceAdapter });
31
33
  const window = overrides.window ?? createWindowInterface();
32
34
  const chat = overrides.chat ?? Object.freeze({
33
35
  append: appendChat,
34
36
  read: readChat,
35
37
  });
36
- return Object.freeze({
38
+ const api = Object.freeze({
37
39
  version: INTERFACE_VERSION,
38
40
  recognition,
39
41
  tts,
40
42
  window,
41
43
  chat,
42
44
  });
45
+ // 组合根:把这一组接口装进运行时端口,chat-store / watch-loop 等核心模块
46
+ // 只从这里取 TTS / 窗口,不再 import 具体实现。
47
+ installPorts(api);
48
+ return api;
43
49
  }
package/src/public-api.js CHANGED
@@ -7,6 +7,12 @@ export {
7
7
  INTERFACE_VERSION,
8
8
  createWatchInterfaces,
9
9
  } from './interfaces.js';
10
+ export {
11
+ getTtsPort,
12
+ getWindowPort,
13
+ installPorts,
14
+ resetPorts,
15
+ } from './runtime-ports.js';
10
16
  export { createRecognitionInterface } from './recognition-interface.js';
11
17
  export { createTtsInterface } from './tts-interface.js';
12
18
  export { createWindowInterface } from './window-interface.js';
@@ -0,0 +1,45 @@
1
+ /**
2
+ * runtime-ports.js — the only place core modules get their TTS/window adapters.
3
+ *
4
+ * Core modules (chat-store, watch-loop, watch-actions, input-surface) never import
5
+ * voice.js / floating-window.js / window-protocol.js directly. They ask for a port;
6
+ * this module is the composition root that supplies the default adapter pair and
7
+ * lets the host install injected interfaces with installPorts().
8
+ *
9
+ * A bare import of this module still gets the historical default (speech bus +
10
+ * bundled floating window), so CLI use and the existing tests keep working.
11
+ */
12
+
13
+ import { createTtsInterface } from './tts-interface.js';
14
+ import { createWindowInterface } from './window-interface.js';
15
+ import * as speechBus from './speech-bus.js';
16
+ import * as voiceAdapter from './voice-adapter.js';
17
+
18
+ let installed = { tts: null, window: null };
19
+
20
+ /** Default TTS adapter = event bus + the optional external-adapter loader. */
21
+ function defaultTts() {
22
+ return createTtsInterface({ ...speechBus, ...voiceAdapter });
23
+ }
24
+
25
+ /** Install host-provided interfaces. Missing sides keep their previous/default adapter. */
26
+ export function installPorts({ tts = null, window = null } = {}) {
27
+ if (tts) installed.tts = tts;
28
+ if (window) installed.window = window;
29
+ return { ...installed };
30
+ }
31
+
32
+ /** Drop injected interfaces (tests / host teardown). */
33
+ export function resetPorts() {
34
+ installed = { tts: null, window: null };
35
+ }
36
+
37
+ export function getTtsPort() {
38
+ if (!installed.tts) installed.tts = defaultTts();
39
+ return installed.tts;
40
+ }
41
+
42
+ export function getWindowPort() {
43
+ if (!installed.window) installed.window = createWindowInterface();
44
+ return installed.window;
45
+ }