dsh-watch-together 0.2.13 → 0.2.15

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,151 @@
1
+ """check-input-caret.py — 输入框光标的回归(不需要真的开窗)。
2
+
3
+ 跑法(仓库根):
4
+
5
+ python scripts/check-input-caret.py
6
+
7
+ 覆盖两件事:
8
+
9
+ 1. **光标跟着插入点走**:`LiveGlass._visible_input` 要以插入点为锚点开窗,
10
+ 并把插入点换算成可见段里的下标。旧实现只从左边砍(`text = text[1:]`),
11
+ 光标恒在末尾 —— 左右键移动时画面上那条线根本不动(#20 的同一处输入框)。
12
+ 2. **右边留余量**:插入点不在原文末尾时,可见段右端必须比插入点再多几个字符,
13
+ 否则往左移动时光标一直贴着右缘,看不出右边还有内容。
14
+
15
+ `_visible_input` 只用到 `self.fonts.get(11).measure`,所以这里拿一个等宽假字体
16
+ 注入,边界值可以手算核对,不需要 Tk、不需要显示器。
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ HERE = Path(__file__).resolve().parent
25
+ sys.path.insert(0, str(HERE.parent / "examples" / "floating-chat"))
26
+
27
+ CHAR_W = 10 # 假字体:每个字符固定 10px,断言才能手算
28
+
29
+ failures: list[str] = []
30
+
31
+
32
+ class FakeFont:
33
+ def measure(self, s):
34
+ return len(s) * CHAR_W
35
+
36
+
37
+ class FakeFonts:
38
+ def get(self, _size, _bold=False):
39
+ return FakeFont()
40
+
41
+
42
+ def check(name, cond, detail=""):
43
+ if not cond:
44
+ failures.append(f"{name}{(': ' + detail) if detail else ''}")
45
+
46
+
47
+ def visible_input(text, maxw, caret):
48
+ """调真实实现:只绑 fonts,其余属性都用不到。"""
49
+ from window import LiveGlass
50
+
51
+ stub = object.__new__(LiveGlass)
52
+ stub.fonts = FakeFonts()
53
+ return LiveGlass._visible_input(stub, text, maxw, caret)
54
+
55
+
56
+ def legacy_visible(text, maxw):
57
+ """改动前的实现,作为对照:只从左边砍,光标恒在末尾。"""
58
+ font = FakeFont()
59
+ while text and font.measure(text) > maxw:
60
+ text = text[1:]
61
+ return text
62
+
63
+
64
+ def test_caret_stays_visible():
65
+ """每个插入点位置,光标都必须落在可见段里,且下标换算不错位。"""
66
+ text = "0123456789abcdefghij" # 20 字符
67
+ maxw = 10 * CHAR_W # 可见 10 字符
68
+ for caret in range(len(text) + 1):
69
+ shown, idx = visible_input(text, maxw, caret)
70
+ check(f"caret={caret} 可见段不超宽",
71
+ FakeFont().measure(shown) <= maxw, f"{shown!r}")
72
+ check(f"caret={caret} 光标在可见段内",
73
+ 0 <= idx <= len(shown), f"idx={idx} len={len(shown)}")
74
+ # 光标右边那个字符若也在可见段里,必须对得上原文(下标没错位)
75
+ if caret < len(text) and idx < len(shown):
76
+ check(f"caret={caret} 下标不错位",
77
+ shown[idx] == text[caret], f"{shown[idx]!r} != {text[caret]!r}")
78
+
79
+
80
+ def test_right_padding():
81
+ """插入点不在末尾时,右边要留得出余量。"""
82
+ text = "0123456789abcdefghij"
83
+ maxw = 10 * CHAR_W
84
+ for caret in range(len(text)): # 不含末尾
85
+ shown, idx = visible_input(text, maxw, caret)
86
+ check(f"caret={caret} 右边有余量", len(shown) - idx >= 1,
87
+ f"右余量={len(shown) - idx}")
88
+
89
+
90
+ def test_legacy_loses_caret():
91
+ """对照:旧实现在插入点靠前时,连插入点那个字符都不在可见段里。"""
92
+ text = "0123456789abcdefghij"
93
+ maxw = 10 * CHAR_W
94
+ old = legacy_visible(text, maxw)
95
+ check("旧实现把句首砍掉了", text[3] not in old,
96
+ f"{old!r} 里不该还有 {text[3]!r}")
97
+ # 新实现同样位置必须看得见
98
+ shown, idx = visible_input(text, maxw, 3)
99
+ check("新实现句首可见", idx < len(shown) and shown[idx] == text[3],
100
+ f"{shown!r} idx={idx}")
101
+
102
+
103
+ def test_short_text_untouched():
104
+ """放得下就原样返回,插入点下标不变 —— 不能为了开窗改短消息的观感。"""
105
+ for text, caret in (("", 0), ("abc", 0), ("abc", 3), ("0123456789", 5)):
106
+ shown, idx = visible_input(text, 10 * CHAR_W, caret)
107
+ check(f"{text!r} 原样返回", (shown, idx) == (text, caret),
108
+ f"得到 {(shown, idx)}")
109
+
110
+
111
+ def test_narrow_window():
112
+ """窗口窄到只剩一个字符时也不能抛、不能返回负下标。"""
113
+ text = "0123456789abcdefghij"
114
+ for maxw in (CHAR_W, CHAR_W * 2, CHAR_W * 3):
115
+ for caret in (0, 5, len(text)):
116
+ shown, idx = visible_input(text, maxw, caret)
117
+ check(f"maxw={maxw} caret={caret} 不超宽",
118
+ FakeFont().measure(shown) <= maxw, f"{shown!r}")
119
+ check(f"maxw={maxw} caret={caret} 下标合法",
120
+ 0 <= idx <= len(shown), f"idx={idx}")
121
+
122
+
123
+ def test_blink_contract():
124
+ """闪烁只认两个常量和三个方法;改名了这里要跟着改。"""
125
+ from window import LiveGlass
126
+
127
+ check("CARET_MS 是 530", LiveGlass.CARET_MS == 530, str(LiveGlass.CARET_MS))
128
+ check("CARET_PAD 是 3", LiveGlass.CARET_PAD == 3, str(LiveGlass.CARET_PAD))
129
+ for m in ("_schedule_caret", "_blink_caret", "_visible_input"):
130
+ check(f"{m} 还在", callable(getattr(LiveGlass, m, None)))
131
+
132
+
133
+ def main():
134
+ test_caret_stays_visible()
135
+ test_right_padding()
136
+ test_legacy_loses_caret()
137
+ test_short_text_untouched()
138
+ test_narrow_window()
139
+ test_blink_contract()
140
+
141
+ if failures:
142
+ print(f"FAIL ({len(failures)})")
143
+ for f in failures:
144
+ print(" -", f)
145
+ return 1
146
+ print("OK: 光标跟随插入点、右边留余量、短文本不动、窄窗口不崩")
147
+ return 0
148
+
149
+
150
+ if __name__ == "__main__":
151
+ raise SystemExit(main())
@@ -0,0 +1,144 @@
1
+ /**
2
+ * define-tool.js — `@deepseek-ai/dsh-tools` 的**离线兜底**。
3
+ *
4
+ * ## 为什么需要它(2026-11-06 社区实报)
5
+ *
6
+ * 插件的工具定义要用宿主的 `defineTool()`:它把 author spec 编译成 JSON Schema、
7
+ * 给 execute 包一层参数校验。但 `@deepseek-ai/dsh-tools` **被打包进宿主的 `app.asar`**,
8
+ * 插件从自己的 `node_modules` 往上解析时**找不到这个包** →
9
+ * `import()` 抛 → `apply()` 被 catch 吞掉 → **整个插件静默不注册任何工具**。
10
+ *
11
+ * 社区原话:「根源没变:它 `import('@deepseek-ai/dsh-tools')`,宿主的这份被打进 `app.asar`,
12
+ * plugins 侧解析不到,加载时就在注册工具之前抛了」。
13
+ *
14
+ * ## 兜底做什么、不做什么
15
+ *
16
+ * **做**:把 author spec 编译成宿主 `register()` 认的 JSON Schema。规则逐条照抄
17
+ * `dsh-tools/lib/index.js` 的 `runSchemaCompiler`:
18
+ * - `property-map`:每个属性的 `required: true` 提升到父级 `required` 数组,并从属性里删掉;
19
+ * 没写 `required: true` 的属性 = 可选(宿主的参数**默认全是可选**)。
20
+ * - `type: 'json'` 是 author-only 节点 → 退化成 `{}`(任意 JSON,只保留 description 等注解)。
21
+ * - `properties` / `items` 递归;其余键(`description` / `enum` / `additionalProperties`)原样透传。
22
+ *
23
+ * **不做**:运行时参数校验(宿主那层 `validateJsonSchemaValue` 拿不到)。
24
+ * 代价是模型传错参数时不再抛 `ToolArgsError`,而是走各 handler 自己的默认值分支 ——
25
+ * 真出问题时表现为"参数没生效",所以 `schema-audit.test.mjs` 那套静态审计更要守住。
26
+ *
27
+ * **首选仍然是宿主的版本**:`loadDefineTool()` 先 import、再 `DSH_TOOLS_PATH`,
28
+ * 两个都不行才落到这里,并打一条 warn 让用户知道降级了。
29
+ */
30
+
31
+ const AUTHOR_ONLY_JSON = 'json';
32
+
33
+ /**
34
+ * 编译一个属性表(`parameters` 或某个 object 节点的 `properties`)。
35
+ * @param {object} map - 属性名 → author value spec
36
+ * @param {string} path - 报错用的路径前缀
37
+ * @returns {{properties: object, required?: string[]}}
38
+ */
39
+ function compilePropertyMap(map, path) {
40
+ if (!map || typeof map !== 'object' || Array.isArray(map)) {
41
+ throw new Error(`${path} 必须是对象(属性名 → 值 schema)`);
42
+ }
43
+ const properties = {};
44
+ const required = [];
45
+ for (const [key, spec] of Object.entries(map)) {
46
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {
47
+ throw new Error(`${path}.${key} 必须是值 schema 对象`);
48
+ }
49
+ const { required: mark, ...rest } = spec;
50
+ if (mark !== undefined && mark !== true) throw new Error(`${path}.${key}.required 写了就只能是 true`);
51
+ if (mark === true) required.push(key);
52
+ properties[key] = compileValue(rest, `${path}.${key}`);
53
+ }
54
+ return required.length > 0 ? { properties, required } : { properties };
55
+ }
56
+
57
+ /**
58
+ * 编译一个值 schema。`type: 'json'` 退化成注解(不写 `type`)。
59
+ * @param {object} spec
60
+ * @param {string} path
61
+ * @returns {object}
62
+ */
63
+ function compileValue(spec, path) {
64
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {
65
+ throw new Error(`${path} 必须是值 schema 对象`);
66
+ }
67
+ const out = {};
68
+ for (const [key, value] of Object.entries(spec)) {
69
+ if (key === 'required') continue; // 由 compilePropertyMap 提走
70
+ if (key === 'properties') {
71
+ const compiled = compilePropertyMap(value, `${path}.properties`);
72
+ out.properties = compiled.properties;
73
+ if (compiled.required) out.required = compiled.required;
74
+ continue;
75
+ }
76
+ if (key === 'items') {
77
+ out.items = compileValue(value, `${path}.items`);
78
+ continue;
79
+ }
80
+ // author-only:任意 JSON。宿主把它变成"只有注解、没有 type"的 schema
81
+ if (key === 'type' && value === AUTHOR_ONLY_JSON) continue;
82
+ out[key] = value;
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * 编译 `parameters`:隐式开放对象,根上不写 `required`(除非属性显式标了)。
89
+ * @param {object} spec
90
+ * @returns {object}
91
+ */
92
+ export function parametersToJsonSchema(spec) {
93
+ const { properties, required } = compilePropertyMap(spec, 'parameters');
94
+ return { type: 'object', properties, ...(required ? { required } : {}) };
95
+ }
96
+
97
+ /**
98
+ * 编译 `output.schema`。
99
+ * @param {object} spec
100
+ * @returns {object}
101
+ */
102
+ export function outputSchemaToJsonSchema(spec) {
103
+ return compileValue(spec, 'schema');
104
+ }
105
+
106
+ /**
107
+ * `defineTool` 的兜底实现:**签名和返回值与宿主一致,只是不做运行时参数校验**。
108
+ * @param {object} options - 与宿主 `defineTool` 相同的入参
109
+ * @returns {object} registry-ready definition
110
+ */
111
+ export function defineToolCompat(options) {
112
+ if (!options || typeof options !== 'object') throw new Error('defineTool: options 必须是对象');
113
+ const { name, description, parameters, output, execute } = options;
114
+ if (typeof name !== 'string' || !name) throw new Error('defineTool: name 必须是非空字符串');
115
+ if (!output || typeof output !== 'object') throw new Error(`defineTool(${name}): 缺 output`);
116
+ if (typeof output.render !== 'function') throw new Error(`defineTool(${name}): output.render 必须是函数`);
117
+ if (typeof execute !== 'function') throw new Error(`defineTool(${name}): execute 必须是函数`);
118
+ if (options.timeoutMs !== undefined
119
+ && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) {
120
+ throw new Error(`defineTool(${name}): timeoutMs 必须是正数`);
121
+ }
122
+
123
+ const tool = {
124
+ name,
125
+ description,
126
+ parameters: parametersToJsonSchema(parameters ?? {}),
127
+ output: {
128
+ schema: outputSchemaToJsonSchema(output.schema ?? {}),
129
+ render: output.render,
130
+ ...(typeof output.presentationMeta === 'function' ? { presentationMeta: output.presentationMeta } : {}),
131
+ },
132
+ ...(options.deferLoading === true ? { deferLoading: true } : {}),
133
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
134
+ async execute(args, exec) {
135
+ return execute(args, exec);
136
+ },
137
+ };
138
+ if (typeof options.projectContent === 'function') tool.projectContent = options.projectContent;
139
+ if (typeof options.finalizeContent === 'function') tool.finalizeContent = options.finalizeContent;
140
+ if (typeof options.presentCall === 'function') tool.presentCall = options.presentCall;
141
+ if (typeof options.presentResult === 'function') tool.presentResult = options.presentResult;
142
+ if (typeof options.isConcurrencySafe === 'function') tool.isConcurrencySafe = options.isConcurrencySafe;
143
+ return tool;
144
+ }
package/src/index.js CHANGED
@@ -1,164 +1,177 @@
1
- /**
2
- * index.js — **dsh-watch-together** 的 DSH 插件入口。只做注册:
3
- *
4
- * watch_together 陪看:按用户真实播放进度,一段一段往下看
5
- *
6
- * 这一个工具就够。它和 `dsh-video-storyboard` 的四个 `video_*` 工具是**两个插件**:
7
- * 那个负责"把一段视频变成一张可引用的宫格",这个负责"跟着你一段段看下去"。
8
- * 这里不注册任何 `video_*` —— 那是另一个包的职责。
9
- *
10
- * 契约要点(对着 @deepseek-ai/dsh-tools 的类型定义核对过):
11
- * - `apply` 返回 disposer(把所有 `ctx.tools.register()` 的返回值串起来)
12
- * - `execute` 返回**规范值**(要过 output.schema)
13
- * - `output.render(args, value)` 把规范值渲染成 ContentBlock[],图片块是
14
- * `{ type: 'image', attachment: ImageAttachmentRef }`,ref 必须由
15
- * `ctx.attachments.saveImage()` 提交过后才能拿到(不能自己编)
16
- * - saveImage 要的是**真正编码后的字节**(PNG/JPEG),不是裸 RGB —— 它会解码校验
17
- */
18
-
19
- import { attachSpeechToChat } from './chat.js';
20
- import { getTtsPort } from './runtime-ports.js';
21
- import { watchTools } from './register.js';
22
- import { createSettingsPage } from './settings/server.js';
23
-
24
- export const name = 'dsh-watch-together';
25
- // **只声明 tools**:cordis 的 inject 是硬依赖,服务缺失时 apply 永远不会被调用,
26
- // 插件就停在"加载中"(用户侧:装完插件 DSH 卡死)。attachments 只在截图那条路上用,
27
- // 改成运行期探测(src/handler.js),没有它就返回文本。
28
- export const inject = ['tools'];
29
-
30
- /**
31
- * 解析宿主的 dsh-tools。正常安装时裸包名就能解析;本地开发/测试时
32
- * 用 `DSH_TOOLS_PATH` 指向安装里的 lib/index.js。
33
- */
34
- async function loadDefineTool() {
35
- try {
36
- const mod = await import('@deepseek-ai/dsh-tools');
37
- if (mod?.defineTool) return mod.defineTool;
38
- } catch {
39
- /* 落到环境变量 */
40
- }
41
- const override = process.env.DSH_TOOLS_PATH;
42
- if (override) {
43
- const { pathToFileURL } = await import('node:url');
44
- const mod = await import(pathToFileURL(override).href);
45
- if (mod?.defineTool) return mod.defineTool;
46
- }
47
- throw new Error('cannot resolve @deepseek-ai/dsh-tools (set DSH_TOOLS_PATH for local dev)');
48
- }
49
-
50
- const APPLY_TIMEOUT_MS = 15_000;
51
-
52
- export async function apply(ctx) {
53
- try {
54
- return await withTimeout(registerAll(ctx), APPLY_TIMEOUT_MS, 'registerAll');
55
- } catch (e) {
56
- // **最坏的情况是插件不能用,不是应用起不来**。
57
- // 真实事故:在 apply 里做 ctx 探测,`Object.keys(ctx)` 在 cordis 上下文上抛错,
58
- // 整个 DSH 直接崩在启动阶段("The application could not start")。
59
- // 所以 apply 的异常一律吞掉并记录,交回一个空 disposer。
60
- try {
61
- ctx?.logger?.error?.(`[dsh-watch-together] failed to load: ${e?.stack ?? e}`);
62
- } catch { /* 连日志都写不了就算了 */ }
63
- // DSH_VIDEO_DEBUG=1 时把错误抛出去 —— 否则"插件静默不工作"很难查
64
- if (process.env.DSH_VIDEO_DEBUG) throw e;
65
- return () => {};
66
- }
67
- }
68
-
69
- async function registerAll(ctx) {
70
- const defineTool = await loadDefineTool();
71
-
72
- // 当前会话:从 session/event 里拿(`session.header.id`)。这是 dsh-fish 的做法,
73
- // 比反射 ctx 安全得多 —— 反射会把整个应用搞崩(见 apply 的注释)。
74
- let lastSessionId = null;
75
-
76
- // 陪看跨调用复用同一批已建好的段(一部电影几十段,只留最近 8 段)
77
- const watchCache = new Map();
78
-
79
- const tools = [
80
- ...watchTools(defineTool, ctx, { getSessionId: () => lastSessionId, cache: watchCache }),
81
- ];
82
-
83
- // **disposers 必须在最前面声明**:它曾经声明在 ctx.on 之后,于是 `disposers.push(off)`
84
- // 撞上 const 的暂时性死区,抛 ReferenceError,又被下面的 catch 静默吞掉 ——
85
- // 监听器注册成功了,解绑函数却从来没登记过(插件卸载时不会解绑,而且没人知道出过错)。
86
- const disposers = [];
87
- if (typeof ctx.on === 'function') {
88
- try {
89
- const off = ctx.on('session/event', (session) => {
90
- const id = session?.header?.id ?? session?.id;
91
- if (id) lastSessionId = id;
92
- });
93
- if (typeof off === 'function') disposers.push(off);
94
- } catch (e) {
95
- // 拿不到就退化成"只能手动触发",但要说出来 —— 静默失败是这类 bug 的温床
96
- try {
97
- ctx?.logger?.warn?.(`[dsh-watch-together] session/event hook failed: ${e?.message ?? e}`);
98
- } catch { /* 日志都没有就只能算了 */ }
99
- }
100
- }
101
-
102
- // 声音适配器(可选):只通过 tts 接口挂,不 import voice.js。
103
- // 这里也保留启动时挂载,这样第一次只调 `say`(还没开窗)也有声音。
104
- try {
105
- const tts = getTtsPort();
106
- const v = await tts.attachConfigured?.({ log: (m) => ctx?.logger?.info?.(m) });
107
- if (v && !v.ok && v.reason !== 'not-configured') {
108
- ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter not loaded: ${v.reason}`);
109
- }
110
- // 适配器订阅了 speech bus;插件卸载必须退订,否则 speechSubscribers()
111
- // 会一直 > 0,重载后循环误以为"有人会念",模型就再也不会被叫醒。
112
- if (v?.ok && typeof tts.detachConfigured === 'function') {
113
- disposers.push(() => {
114
- try { void tts.detachConfigured(); } catch { /* 卸载失败不能影响其他 disposer */ }
115
- });
116
- }
117
- } catch (e) {
118
- ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter crashed: ${e?.message ?? e}`);
119
- }
120
-
121
- // 到点的台词写进**统一文本流**(聊天框 / 悬浮窗读同一份,声音也从这里取)。
122
- // 订阅时带 `voice: false` —— 只做展示,不该让循环以为"有人会念"而不再叫醒模型。
123
- disposers.push(attachSpeechToChat());
124
-
125
- disposers.push(...tools.map((tool) => ctx.tools.register(tool)));
126
-
127
- // 设置页是可选能力:没有本机 webServer 的宿主只注册 watch_together。
128
- const attachSettings = (settingsCtx) => {
129
- try {
130
- const settings = createSettingsPage({ ctx: settingsCtx, env: process.env, log: (message) => settingsCtx?.logger?.warn?.(message) });
131
- if (settings) {
132
- disposers.push(settings.dispose);
133
- disposers.push(settingsCtx.tools.register(defineTool(settings.tool)));
134
- }
135
- } catch (e) {
136
- try { settingsCtx?.logger?.warn?.('[dsh-watch-together] settings page failed: ' + String(e?.message ?? e)); } catch { /* ignore */ }
137
- }
138
- };
139
- // webServer 可能晚于插件就绪;动态 inject 比 apply 时硬探测更可靠。
140
- if (typeof ctx.inject === 'function') {
141
- try {
142
- const off = ctx.inject(['webServer'], (webCtx) => attachSettings(webCtx));
143
- if (typeof off === 'function') disposers.push(off);
144
- } catch (e) {
145
- try { ctx?.logger?.warn?.('[dsh-watch-together] settings injection failed: ' + String(e?.message ?? e)); } catch { /* ignore */ }
146
- }
147
- } else {
148
- attachSettings(ctx);
149
- }
150
-
151
- return () => {
152
- for (const dispose of disposers.reverse()) dispose?.();
153
- };
154
- }
155
-
156
- /** 看门狗:apply 里任何 await 卡住都会拖住宿主启动,超时就交回空 disposer。 */
157
- function withTimeout(promise, ms, label) {
158
- let timer;
159
- const timeout = new Promise((_, reject) => {
160
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
161
- timer.unref?.();
162
- });
163
- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
164
- }
1
+ /**
2
+ * index.js — **dsh-watch-together** 的 DSH 插件入口。只做注册:
3
+ *
4
+ * watch_together 陪看:按用户真实播放进度,一段一段往下看
5
+ *
6
+ * 这一个工具就够。它和 `dsh-video-storyboard` 的四个 `video_*` 工具是**两个插件**:
7
+ * 那个负责"把一段视频变成一张可引用的宫格",这个负责"跟着你一段段看下去"。
8
+ * 这里不注册任何 `video_*` —— 那是另一个包的职责。
9
+ *
10
+ * 契约要点(对着 @deepseek-ai/dsh-tools 的类型定义核对过):
11
+ * - `apply` 返回 disposer(把所有 `ctx.tools.register()` 的返回值串起来)
12
+ * - `execute` 返回**规范值**(要过 output.schema)
13
+ * - `output.render(args, value)` 把规范值渲染成 ContentBlock[],图片块是
14
+ * `{ type: 'image', attachment: ImageAttachmentRef }`,ref 必须由
15
+ * `ctx.attachments.saveImage()` 提交过后才能拿到(不能自己编)
16
+ * - saveImage 要的是**真正编码后的字节**(PNG/JPEG),不是裸 RGB —— 它会解码校验
17
+ */
18
+
19
+ import { defineToolCompat } from './define-tool.js';
20
+ import { attachSpeechToChat } from './chat.js';
21
+ import { getTtsPort } from './runtime-ports.js';
22
+ import { watchTools } from './register.js';
23
+ import { createSettingsPage } from './settings/server.js';
24
+
25
+ export const name = 'dsh-watch-together';
26
+ // **只声明 tools**:cordis 的 inject 是硬依赖,服务缺失时 apply 永远不会被调用,
27
+ // 插件就停在"加载中"(用户侧:装完插件 DSH 卡死)。attachments 只在截图那条路上用,
28
+ // 改成运行期探测(src/handler.js),没有它就返回文本。
29
+ export const inject = ['tools'];
30
+
31
+ /**
32
+ * 解析宿主的 dsh-tools。正常安装时裸包名就能解析;本地开发/测试时
33
+ * 用 `DSH_TOOLS_PATH` 指向安装里的 lib/index.js。
34
+ */
35
+ async function loadDefineTool() {
36
+ try {
37
+ const mod = await import('@deepseek-ai/dsh-tools');
38
+ if (mod?.defineTool) return mod.defineTool;
39
+ } catch {
40
+ /* 落到环境变量 */
41
+ }
42
+ /**
43
+ * 第二跳:`DSH_TOOLS_PATH` 指向磁盘上的那份(本地开发时用)。
44
+ * **包一层 try**:路径写错不该让插件整个废掉。
45
+ */
46
+ const override = process.env.DSH_TOOLS_PATH;
47
+ if (override) {
48
+ try {
49
+ const { pathToFileURL } = await import('node:url');
50
+ const mod = await import(pathToFileURL(override).href);
51
+ if (mod?.defineTool) return mod.defineTool;
52
+ } catch { /* 路径不对,继续落到兜底 */ }
53
+ }
54
+ /**
55
+ * 最后一跳:内置兼容实现。**不能再抛** ——
56
+ * 宿主的包在 `app.asar` 里,插件侧经常解析不到(社区实报),
57
+ * 抛出去会被 apply 的 catch 吞掉,结果是**整个插件静默不注册任何工具**。
58
+ * 内置版只少了运行时参数校验,工具照常能用(详见 define-tool.js)。
59
+ */
60
+ return defineToolCompat;
61
+ }
62
+
63
+ const APPLY_TIMEOUT_MS = 15_000;
64
+
65
+ export async function apply(ctx) {
66
+ try {
67
+ return await withTimeout(registerAll(ctx), APPLY_TIMEOUT_MS, 'registerAll');
68
+ } catch (e) {
69
+ // **最坏的情况是插件不能用,不是应用起不来**。
70
+ // 真实事故:在 apply 里做 ctx 探测,`Object.keys(ctx)` 在 cordis 上下文上抛错,
71
+ // 整个 DSH 直接崩在启动阶段("The application could not start")。
72
+ // 所以 apply 的异常一律吞掉并记录,交回一个空 disposer。
73
+ try {
74
+ ctx?.logger?.error?.(`[dsh-watch-together] failed to load: ${e?.stack ?? e}`);
75
+ } catch { /* 连日志都写不了就算了 */ }
76
+ // DSH_VIDEO_DEBUG=1 时把错误抛出去 —— 否则"插件静默不工作"很难查
77
+ if (process.env.DSH_VIDEO_DEBUG) throw e;
78
+ return () => {};
79
+ }
80
+ }
81
+
82
+ async function registerAll(ctx) {
83
+ const defineTool = await loadDefineTool();
84
+
85
+ // 当前会话:从 session/event 里拿(`session.header.id`)。这是 dsh-fish 的做法,
86
+ // 比反射 ctx 安全得多 —— 反射会把整个应用搞崩(见 apply 的注释)。
87
+ let lastSessionId = null;
88
+
89
+ // 陪看跨调用复用同一批已建好的段(一部电影几十段,只留最近 8 段)
90
+ const watchCache = new Map();
91
+
92
+ const tools = [
93
+ ...watchTools(defineTool, ctx, { getSessionId: () => lastSessionId, cache: watchCache }),
94
+ ];
95
+
96
+ // **disposers 必须在最前面声明**:它曾经声明在 ctx.on 之后,于是 `disposers.push(off)`
97
+ // 撞上 const 的暂时性死区,抛 ReferenceError,又被下面的 catch 静默吞掉 ——
98
+ // 监听器注册成功了,解绑函数却从来没登记过(插件卸载时不会解绑,而且没人知道出过错)。
99
+ const disposers = [];
100
+ if (typeof ctx.on === 'function') {
101
+ try {
102
+ const off = ctx.on('session/event', (session) => {
103
+ const id = session?.header?.id ?? session?.id;
104
+ if (id) lastSessionId = id;
105
+ });
106
+ if (typeof off === 'function') disposers.push(off);
107
+ } catch (e) {
108
+ // 拿不到就退化成"只能手动触发",但要说出来 —— 静默失败是这类 bug 的温床
109
+ try {
110
+ ctx?.logger?.warn?.(`[dsh-watch-together] session/event hook failed: ${e?.message ?? e}`);
111
+ } catch { /* 日志都没有就只能算了 */ }
112
+ }
113
+ }
114
+
115
+ // 声音适配器(可选):只通过 tts 接口挂,不 import voice.js。
116
+ // 这里也保留启动时挂载,这样第一次只调 `say`(还没开窗)也有声音。
117
+ try {
118
+ const tts = getTtsPort();
119
+ const v = await tts.attachConfigured?.({ log: (m) => ctx?.logger?.info?.(m) });
120
+ if (v && !v.ok && v.reason !== 'not-configured') {
121
+ ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter not loaded: ${v.reason}`);
122
+ }
123
+ // 适配器订阅了 speech bus;插件卸载必须退订,否则 speechSubscribers()
124
+ // 会一直 > 0,重载后循环误以为"有人会念",模型就再也不会被叫醒。
125
+ if (v?.ok && typeof tts.detachConfigured === 'function') {
126
+ disposers.push(() => {
127
+ try { void tts.detachConfigured(); } catch { /* 卸载失败不能影响其他 disposer */ }
128
+ });
129
+ }
130
+ } catch (e) {
131
+ ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter crashed: ${e?.message ?? e}`);
132
+ }
133
+
134
+ // 到点的台词写进**统一文本流**(聊天框 / 悬浮窗读同一份,声音也从这里取)。
135
+ // 订阅时带 `voice: false` —— 只做展示,不该让循环以为"有人会念"而不再叫醒模型。
136
+ disposers.push(attachSpeechToChat());
137
+
138
+ disposers.push(...tools.map((tool) => ctx.tools.register(tool)));
139
+
140
+ // 设置页是可选能力:没有本机 webServer 的宿主只注册 watch_together。
141
+ const attachSettings = (settingsCtx) => {
142
+ try {
143
+ const settings = createSettingsPage({ ctx: settingsCtx, env: process.env, log: (message) => settingsCtx?.logger?.warn?.(message) });
144
+ if (settings) {
145
+ disposers.push(settings.dispose);
146
+ disposers.push(settingsCtx.tools.register(defineTool(settings.tool)));
147
+ }
148
+ } catch (e) {
149
+ try { settingsCtx?.logger?.warn?.('[dsh-watch-together] settings page failed: ' + String(e?.message ?? e)); } catch { /* ignore */ }
150
+ }
151
+ };
152
+ // webServer 可能晚于插件就绪;动态 inject 比 apply 时硬探测更可靠。
153
+ if (typeof ctx.inject === 'function') {
154
+ try {
155
+ const off = ctx.inject(['webServer'], (webCtx) => attachSettings(webCtx));
156
+ if (typeof off === 'function') disposers.push(off);
157
+ } catch (e) {
158
+ try { ctx?.logger?.warn?.('[dsh-watch-together] settings injection failed: ' + String(e?.message ?? e)); } catch { /* ignore */ }
159
+ }
160
+ } else {
161
+ attachSettings(ctx);
162
+ }
163
+
164
+ return () => {
165
+ for (const dispose of disposers.reverse()) dispose?.();
166
+ };
167
+ }
168
+
169
+ /** 看门狗:apply 里任何 await 卡住都会拖住宿主启动,超时就交回空 disposer。 */
170
+ function withTimeout(promise, ms, label) {
171
+ let timer;
172
+ const timeout = new Promise((_, reject) => {
173
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
174
+ timer.unref?.();
175
+ });
176
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
177
+ }