dsh-share-chat 0.3.3 → 0.9.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.
package/docs/DETAIL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 社交
2
2
 
3
- 在 DSH 里和好友聊天,好友发来的对话快照可以直接展开看;还能顺手在聊天页里玩一把「鱼塘摸鱼」。两个入口共用一份登录状态。
3
+ 在 DSH 里和好友聊天,好友发来的对话快照可以直接展开看。有两个入口,共用一份登录状态。
4
4
 
5
5
  ## 怎么用
6
6
 
@@ -20,21 +20,10 @@
20
20
  - 注册、用 token 登录、退出
21
21
  - 加好友(互相添加)
22
22
  - 一对一发文字消息、收消息
23
- - **发图片 / 视频 / 音频 / 任意文件**:点 📎 选文件(单件上限 50 MB)。图片和视频直接内嵌显示,音频给播放器,其它文件显示类型图标 + 类型 + 大小,点开下载
23
+ - **发图片 / 文件**:点 📎 选文件,图片直接显示,其他文件给下载链接(单件 ≤ 8 MB)
24
24
  - **表情**:点 😀 打开表情面板,插进输入框(unicode 表情,当普通文字发)
25
25
  - 收到对话快照时展开查看(标题、用户消息、工具调用、回复)
26
26
  - **一键分享当前会话**:在会话里的「社交」tab 顶部点「分享这一轮」,选好友发出去。只取**最后一轮**,每段最多 1500 字,工具调用压成一行短摘要
27
- - **内置小游戏**:聊天页顶栏的 `🎮 摸鱼`,右下角浮动窗口,可拖可缩放;默认尺寸在 **设置 → 社交小游戏** 里调(340×600 / 390×760 / 480×900 或自定义)
28
-
29
- ## 界面
30
-
31
- 整套界面使用 DSH 的主题 token(`--dsw-alias-*`),亮色/暗色随宿主自动切换:
32
-
33
- - 登录页是一张居中卡片:服务器、邀请码、账号、密码,分段 tab 切换登录 / 注册 / token
34
- - 左侧好友列表带头像与最后一条消息摘要
35
- - 消息是双向气泡(自己的用品牌色),下面是时间
36
- - 空状态有图标和提示,不会只剩一行灰字
37
- - 窄窗口(≤720px)侧栏自动收窄
38
27
 
39
28
  ## 明确的限制
40
29
 
@@ -43,13 +32,12 @@
43
32
  - 会剥掉运行时注入的 `<system-reminder>` 上下文(时间戳、工作目录、权限策略那类)
44
33
  - 分享内容按「用户 / 工具 / 回复」三类归一化,原始 Markdown 结构和附件不会带过去
45
34
  - 过滤是黑名单,不是白名单:不保证 100% 不漏,分享前建议自己过一眼
46
- - 没有好友申请与同意流程,双方互相添加即成立
47
- - 没有群聊、已读回执、撤回、语音
48
- - 消息 5 秒轮询,不是实时推送;断线后下一次轮询自动恢复
49
- - 服务器不加密存储:消息和快照以明文 JSON 落在 relay 的 `/opt/dsh-relay/data/`,快照 7 天过期
50
- - 浏览器 localStorage 里存的是 bearer token,共用电脑时注意退出
51
- - 小游戏在网页端没有微信登录、没有激励视频、没有游戏圈;视频/音频能否播放取决于浏览器编解码
35
+ - 没有好友申请与同意流程,双方互相添加即成立。
36
+ - 没有群聊、已读回执、撤回、图片、语音。
37
+ - 消息 5 秒轮询,不是实时推送;断线后下一次轮询自动恢复。
38
+ - 服务器不加密存储:消息和快照以明文 JSON 落在 relay 的 `/opt/dsh-relay/data/`,快照 7 天过期。
39
+ - 浏览器 localStorage 里存的是 bearer token,共用电脑时注意退出。
52
40
 
53
41
  ## 服务器地址
54
42
 
55
- 默认指向 `https://xdxy-pet.com/relay`,可在登录页改。relay 只存信封(谁发给谁 + 时间 + 快照引用),不解析消息内容语义。小游戏固定指向 `https://xdxy-pet.com/game/`(和鱼塘 `/api/fish/` 同源),目前不可配置。
43
+ 默认指向 `https://xdxy-pet.com/relay`,可在登录页改。relay 只存信封(谁发给谁 + 时间 + 快照引用),不解析消息内容语义。
package/index.js CHANGED
@@ -12,6 +12,8 @@
12
12
  * 不会把已经能用的聊天一起拖下水。
13
13
  */
14
14
 
15
+ import { randomBytes } from 'node:crypto'
16
+
15
17
  const PREFIX = '/api/share-chat'
16
18
 
17
19
  function json(status, body) {
@@ -167,4 +169,188 @@ export function apply(ctx) {
167
169
  'share-chat: transcript route',
168
170
  )
169
171
  })
172
+
173
+ // ── 营地:采集本机插件清单(给「串门」发布用,只读)──
174
+ ctx.inject(['webServer', 'pluginManager'], (scope) => {
175
+ scope.effect(
176
+ () =>
177
+ scope.webServer.register({
178
+ path: PREFIX + '/camp/collect',
179
+ kind: 'exact',
180
+ resource: async () => {
181
+ if (!isLoopbackOrigin(scope)) return json(403, { error: 'not-loopback' })
182
+ try {
183
+ const raw = await scope.pluginManager.listBundles()
184
+ const list = Array.isArray(raw) ? raw : raw && Array.isArray(raw.entries) ? raw.entries : []
185
+ const plugins = list
186
+ .map((b) => {
187
+ const name = String((b && b.name) || '')
188
+ const spec = String((b && b.source) || '')
189
+ // 本地路径来源不能分享:别人装不了,也不该知道你的磁盘布局
190
+ if (/^(file|link):/i.test(spec)) return null
191
+ const builtin = !spec
192
+ const source = spec.startsWith('git+') ? 'git' : builtin ? 'builtin' : 'npm'
193
+ return {
194
+ name,
195
+ version: String((b && b.version) || ''),
196
+ spec,
197
+ source,
198
+ builtin,
199
+ enabled: !!(b && b.enabled),
200
+ }
201
+ })
202
+ .filter((p) => p && p.name)
203
+ return json(200, { collectedAt: Date.now(), plugins })
204
+ } catch (e) {
205
+ return json(500, { error: String((e && e.message) || e) })
206
+ }
207
+ },
208
+ }),
209
+ 'share-chat: camp collect route',
210
+ )
211
+ })
212
+
213
+ // ── 营地:复刻(装插件 / 撤销),仅本机 + 一次性 nonce ──
214
+ ctx.inject(['webServer', 'pluginManager'], (scope) => {
215
+ let nonceValue = ''
216
+ let nonceExpires = 0
217
+
218
+ /** 只放行 npm 精确版本、pinned git、https tgz;本地路径一律拒绝 */
219
+ const okSpec = (spec) => {
220
+ const v = String(spec || '').trim()
221
+ if (!v || /^(file|link):/i.test(v)) return false
222
+ if (/^git\+https?:\/\/[^\s#]+#[0-9a-f]{40}$/i.test(v)) return true
223
+ if (/^https:\/\/[^\s?#]+\.tgz$/i.test(v)) return true
224
+ if (/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@[0-9][0-9A-Za-z.+-]*$/i.test(v)) return true
225
+ return false
226
+ }
227
+
228
+ /** handler 是 node 风格:resource 只接 GET/HEAD,POST 必须用 handler */
229
+ const sendJson = (res, status, body) => {
230
+ const text = JSON.stringify(body)
231
+ res.writeHead(status, {
232
+ 'content-type': 'application/json; charset=utf-8',
233
+ 'cache-control': 'no-store',
234
+ })
235
+ res.end(text)
236
+ }
237
+
238
+ const readJsonBody = (req) =>
239
+ new Promise((resolve) => {
240
+ let size = 0
241
+ const chunks = []
242
+ req.on('data', (c) => {
243
+ size += c.length
244
+ if (size > 256 * 1024) {
245
+ resolve(null)
246
+ req.destroy()
247
+ return
248
+ }
249
+ chunks.push(c)
250
+ })
251
+ req.on('end', () => {
252
+ try {
253
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'))
254
+ } catch {
255
+ resolve(null)
256
+ }
257
+ })
258
+ req.on('error', () => resolve(null))
259
+ })
260
+
261
+ scope.effect(
262
+ () =>
263
+ scope.webServer.register({
264
+ path: PREFIX + '/camp/nonce',
265
+ kind: 'exact',
266
+ resource: async () => {
267
+ if (!isLoopbackOrigin(scope)) return json(403, { error: 'not-loopback' })
268
+ nonceValue = randomBytes(16).toString('hex')
269
+ nonceExpires = Date.now() + 5 * 60 * 1000
270
+ return json(200, { nonce: nonceValue, expiresAt: nonceExpires })
271
+ },
272
+ }),
273
+ 'share-chat: camp nonce route',
274
+ )
275
+
276
+ scope.effect(
277
+ () =>
278
+ scope.webServer.register({
279
+ path: PREFIX + '/camp/apply',
280
+ kind: 'exact',
281
+ handler: async (req, res) => {
282
+ if (req.method !== 'POST') return sendJson(res, 405, { error: 'method', allow: 'POST' })
283
+ if (!isLoopbackOrigin(scope)) return sendJson(res, 403, { error: 'not-loopback' })
284
+ const body = await readJsonBody(req)
285
+ if (!body) return sendJson(res, 400, { error: 'bad-json' })
286
+ const token = String(body.nonce || '')
287
+ if (!nonceValue || token !== nonceValue || Date.now() > nonceExpires) {
288
+ return sendJson(res, 403, { error: 'bad-nonce' })
289
+ }
290
+ nonceValue = ''
291
+ const items = Array.isArray(body.specs) ? body.specs.slice(0, 12) : []
292
+ const results = []
293
+ for (const item of items) {
294
+ const spec = String((item && item.spec) || '')
295
+ if (!okSpec(spec)) {
296
+ results.push({ spec, ok: false, error: 'bad-spec' })
297
+ continue
298
+ }
299
+ try {
300
+ const r = await scope.pluginManager.installBundle(spec, { saveExact: true, enabled: true })
301
+ const application = String((r && r.application) || '')
302
+ const ok = application !== 'failed' && application !== 'cancelled'
303
+ const failure = r && r.error
304
+ const detail = failure
305
+ ? String(failure.diagnostic || failure.message || failure.code || failure)
306
+ : 'install-failed'
307
+ results.push({
308
+ spec,
309
+ ok,
310
+ bundle: String((r && r.bundle) || spec.replace(/@[^@]*$/, '')),
311
+ version: String((r && r.version) || ''),
312
+ application,
313
+ error: ok ? '' : detail,
314
+ })
315
+ } catch (e) {
316
+ results.push({ spec, ok: false, error: String((e && e.message) || e) })
317
+ }
318
+ }
319
+ return sendJson(res, 200, { results })
320
+ },
321
+ }),
322
+ 'share-chat: camp apply route',
323
+ )
324
+
325
+ scope.effect(
326
+ () =>
327
+ scope.webServer.register({
328
+ path: PREFIX + '/camp/remove',
329
+ kind: 'exact',
330
+ handler: async (req, res) => {
331
+ if (req.method !== 'POST') return sendJson(res, 405, { error: 'method', allow: 'POST' })
332
+ if (!isLoopbackOrigin(scope)) return sendJson(res, 403, { error: 'not-loopback' })
333
+ const body = await readJsonBody(req)
334
+ if (!body) return sendJson(res, 400, { error: 'bad-json' })
335
+ const targets = Array.isArray(body.targets) ? body.targets.slice(0, 12) : []
336
+ const results = []
337
+ for (const t of targets) {
338
+ const name = String(t || '')
339
+ if (!name || /\s/.test(name)) {
340
+ results.push({ name, ok: false, error: 'bad-name' })
341
+ continue
342
+ }
343
+ try {
344
+ const r = await scope.pluginManager.removeBundle(name)
345
+ results.push({ name, ok: true, application: String((r && r.application) || '') })
346
+ } catch (e) {
347
+ results.push({ name, ok: false, error: String((e && e.message) || e) })
348
+ }
349
+ }
350
+ return sendJson(res, 200, { results })
351
+ },
352
+ }),
353
+ 'share-chat: camp remove route',
354
+ )
355
+ })
170
356
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-share-chat",
3
- "version": "0.3.3",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -11,14 +11,9 @@
11
11
  "snapshot",
12
12
  "minigame",
13
13
  "meeting",
14
- "webrtc"
14
+ "camp"
15
15
  ],
16
- "description": "Social chat, calls and shared session snapshots inside the DSH conversation view, with an embedded fish-game mini game.",
17
- "repository": {
18
- "type": "git",
19
- "url": "git+https://gitee.com/laughing-faith/dsh-share-chat.git"
20
- },
21
- "homepage": "https://gitee.com/laughing-faith/dsh-share-chat#readme",
16
+ "description": "Social chat, calls, camps and shared session snapshots inside the DSH conversation view.",
22
17
  "exports": {
23
18
  ".": "./index.js",
24
19
  "./client": "./client.js",
@@ -31,9 +26,7 @@
31
26
  "cordis.patch.yml",
32
27
  "locale/*.json",
33
28
  "docs",
34
- "cli",
35
29
  "README.md",
36
- "CHANGELOG.md",
37
30
  "LICENSE",
38
31
  "icon.svg"
39
32
  ],
@@ -48,5 +41,10 @@
48
41
  "@deepseek-ai/dsh-client-ui-conversation"
49
42
  ]
50
43
  }
51
- }
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://gitee.com/laughing-faith/dsh-share-chat.git"
48
+ },
49
+ "homepage": "https://gitee.com/laughing-faith/dsh-share-chat#readme"
52
50
  }
package/CHANGELOG.md DELETED
@@ -1,65 +0,0 @@
1
- # 更新记录
2
-
3
- ## 0.3.2
4
-
5
- - **群聊**:侧栏改成「会话」,好友和群混排;新增「建群」按钮;群会话标题带人数,群里可「+人」拉人
6
- - 群消息在气泡上方显示**发送者名字**(一对一不显示,保持干净)
7
- - **真头像**:点头顶账号名上传头像;侧栏、群成员都用图片头像,没图的沿用首字母色块
8
- - 群消息复用同一条消息流:`to = "g:<groupId>"`,游标 / 轮询 / 未读 / 上传 / 快照全都不用另做一套
9
- - relay 端新增:`POST /api/avatar`、`POST|GET /api/groups`、`POST /api/groups/:id/members`、`/leave`、`/avatar`(仅群主)
10
- - 网页版(`/chat/`)同步支持群聊与头像,并做成 PWA(可添加到主屏幕)
11
-
12
- ## 0.3.0
13
-
14
- - 仓库整理:移除小游戏的移植层与部署脚手架(运行时动态执行模块源码的加载器、以及向本机回环发起 HTTP 的部署脚本)。
15
- 它们不属于插件运行时,却会被 dsh.so 的安全扫描判为 critical / warning;部署方式改为 docs/GAME.md 里的文字说明
16
-
17
- - **包名改为 `dsh-share-chat`**(去掉 `@local/`,发布到 npm);`cordis.patch.yml` 的 row 名与 client 模块 id 一并修改
18
- - 老用户从 `@local/dsh-share-chat` 迁移:先移除旧包,再 `dsh plugin add dsh-share-chat`
19
-
20
- - **新增会议**:聊天页顶栏 `📹 开会`,新建/加入房间,最多 6 人音视频 + 屏幕共享
21
- - 纯浏览器 WebRTC 网状直连,relay 只转发信令(SSE 长连接)与成员状态,**无时长限制**
22
- - 工具栏:麦克风、摄像头、共享屏幕、复制房间号、离开;窗口可拖可缩放,`Esc` 离开
23
- - STUN 用 Cloudflare / Google 公共节点;对称 NAT 下可能需要 TURN(后续在服务器加 coturn)
24
- - relay 端:新增 `POST /api/meet/rooms`、`/join`、`/state`、`/signal`、`/leave` 与 `GET …/events`(SSE)
25
-
26
- ## 0.2.2
27
-
28
- - 合并 0.1.6 的文件缩略图/卡片实现到 0.2 的新界面:图片、视频、音频内联,其它文件显示类型图标 + 类型 + 大小
29
- - README 重写:三种不需要 Git 的安装方式(tgz / 本地文件夹 / npm),以及「为什么 git 地址必须装 Git」
30
- - 新增 `docs/INSTALL.md`(安装与排错)、`docs/GAME.md`(小游戏移植与部署)、`CHANGELOG.md`
31
- - 新增 `game-host/`(小游戏浏览器移植层)与 `tools/`(部署脚本 + nginx 片段)
32
- - `docs/DETAIL.md` 补充小游戏、窗口尺寸设置与 50 MB 上限
33
-
34
- ## 0.2.1
35
-
36
- - **界面重做**:整套样式改为注入一张 `<style>` + `--dsw-alias-*` 主题 token,亮色/暗色跟随 DSH
37
- - 登录页:居中卡片、分段 tab、带标签输入框、聚焦光圈
38
- - 聊天:头像、好友列表的最后一条摘要、双向气泡、时间戳、空状态
39
- - 输入区:圆角输入框、表情/附件在框内、发送按钮禁用态
40
- - 快照卡片、分享条(带预览)、设置页(预设卡片)
41
- - 窄屏(≤720px)媒体查询
42
- - 修复:文件消息的缩略图/卡片合并了 0.1.6 的实现(图片/视频/音频内联,其它显示类型图标)
43
-
44
- ## 0.2.0
45
-
46
- - 首次引入 0.2 系列界面(注入 CSS、class 化组件),功能与 0.1.9 一致
47
-
48
- ## 0.1.9
49
-
50
- - 小游戏窗口改为**原生 DOM 挂到 `document.body`**(`z-index: 2147483647`),绕开 DSH 面板的 stacking context 与裁切
51
- - 窗口标题栏加点击诊断(`x,y → 命中区域`),`Esc` 关闭
52
-
53
- ## 0.1.8
54
-
55
- - 点击问题排查版:窗口 `z-index` 提到最大、加 `pointer-events: auto`
56
-
57
- ## 0.1.7
58
-
59
- - 小游戏窗口从全屏遮罩改为**右下角浮动窗口**:可拖标题栏、拉右下角改大小,尺寸存 localStorage
60
- - 新增 **设置 → 社交小游戏**:预设(340×600 / 390×760 / 480×900)+ 自定义宽高 + 恢复默认
61
-
62
- ## 0.1.6
63
-
64
- - 文件消息支持任意类型(≤50 MB):图片/视频/音频内联,其它文件显示类型图标与大小
65
- - 上传失败文案由 8 MB 更正为 50 MB
package/cli/chat-mcp.mjs DELETED
@@ -1,225 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * chat-mcp —— 把 relay 的收发消息暴露成 MCP 工具,给 WorkBuddy / Claude Desktop 等用
4
- *
5
- * 协议:JSON-RPC over stdio,按行分隔。不依赖 MCP SDK,只用 Node 内置模块。
6
- * 凭据:复用 CLI 的 ~/.dsh-chat/config.json(先跑一次 `node chat.mjs login`)
7
- * 也可以用环境变量 DSH_CHAT_SERVER / DSH_CHAT_TOKEN 覆盖。
8
- */
9
- import { readFileSync } from 'node:fs'
10
- import path from 'node:path'
11
- import os from 'node:os'
12
-
13
- const CONFIG_FILE = path.join(os.homedir(), '.dsh-chat', 'config.json')
14
- const PROTOCOL = '2024-11-05'
15
- const NAME = 'dsh-chat'
16
- const VERSION = '0.1.0'
17
-
18
- function loadConfig() {
19
- try {
20
- return JSON.parse(readFileSync(CONFIG_FILE, 'utf8'))
21
- } catch {
22
- return {}
23
- }
24
- }
25
-
26
- const cfg = loadConfig()
27
- const server = String(process.env.DSH_CHAT_SERVER || cfg.server || 'https://xdxy-pet.com/relay').replace(/\/+$/, '')
28
- const token = process.env.DSH_CHAT_TOKEN || cfg.token || ''
29
- const me = cfg.id || ''
30
-
31
- async function api(method, p, body) {
32
- const headers = {}
33
- if (body !== undefined) headers['content-type'] = 'application/json'
34
- if (token) headers.authorization = 'Bearer ' + token
35
- const res = await fetch(server + p, {
36
- method,
37
- headers,
38
- body: body === undefined ? undefined : JSON.stringify(body),
39
- })
40
- let data = null
41
- try {
42
- data = await res.json()
43
- } catch {}
44
- if (!res.ok) {
45
- const err = new Error((data && data.error) || 'http-' + res.status)
46
- err.code = (data && data.error) || 'http-' + res.status
47
- throw err
48
- }
49
- return data
50
- }
51
-
52
- // ── 工具实现 ────────────────────────────────────────────
53
-
54
- const TOOLS = [
55
- {
56
- name: 'chat_friends',
57
- description: '列出当前账号的好友。返回每个好友的账号 id 与显示名。',
58
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
59
- },
60
- {
61
- name: 'chat_read',
62
- description:
63
- '读取新消息(只返回上次读取之后的新消息)。用于看同事有没有找你。消息里的 kind=snapshot 表示对方分享了 DSH 对话快照,快照内容会一并取回。',
64
- inputSchema: {
65
- type: 'object',
66
- properties: {
67
- all: { type: 'boolean', description: '忽略本地光标,从头读取全部消息' },
68
- with: { type: 'string', description: '只看与某个账号的往来' },
69
- },
70
- additionalProperties: false,
71
- },
72
- },
73
- {
74
- name: 'chat_send',
75
- description: '给一个好友发一条文字消息。只在用户明确要求时调用,不要自动发送。',
76
- inputSchema: {
77
- type: 'object',
78
- properties: {
79
- to: { type: 'string', description: '对方的账号 id' },
80
- text: { type: 'string', description: '消息内容' },
81
- },
82
- required: ['to', 'text'],
83
- additionalProperties: false,
84
- },
85
- },
86
- {
87
- name: 'chat_add_friend',
88
- description: '添加好友(对方会自动反向添加)。',
89
- inputSchema: {
90
- type: 'object',
91
- properties: { id: { type: 'string', description: '对方的账号 id' } },
92
- required: ['id'],
93
- additionalProperties: false,
94
- },
95
- },
96
- ]
97
-
98
- async function callTool(name, args) {
99
- if (!token) {
100
- return {
101
- isError: true,
102
- text: '还没登录。先在终端跑一次:node chat.mjs login <你的账号>',
103
- }
104
- }
105
- if (name === 'chat_friends') {
106
- const r = await api('GET', '/api/friends')
107
- if (!r.friends.length) return { text: '还没有好友。可以用 chat_add_friend 加。' }
108
- return { text: r.friends.map((f) => `${f.id}(${f.displayName || f.id})`).join('\n') }
109
- }
110
- if (name === 'chat_read') {
111
- const since = args.all ? 0 : cfg.cursor || 0
112
- const r = await api('GET', '/api/messages?since=' + since)
113
- let msgs = r.messages || []
114
- if (args.with) msgs = msgs.filter((m) => m.from === args.with || m.to === args.with)
115
- msgs.sort((a, b) => a.seq - b.seq)
116
- if (!msgs.length) return { text: '没有新消息。' }
117
- const out = []
118
- for (const m of msgs) {
119
- const who = m.from === me ? '我' : m.from
120
- const body = m.body || {}
121
- if (body.kind === 'snapshot') {
122
- let snapText = '(快照内容取不到,可能已过期)'
123
- try {
124
- const s = await api('GET', '/api/snapshots/' + encodeURIComponent(body.snapshotId))
125
- const blocks = (s.snapshot && s.snapshot.blocks) || []
126
- snapText =
127
- '【' + ((s.snapshot && s.snapshot.title) || '对话快照') + '】\n' +
128
- blocks
129
- .map((b) => {
130
- const tag = b.t === 'user' ? '用户' : b.t === 'tool' ? b.name || '工具' : '助手'
131
- return `[${tag}] ${String(b.text || '').replace(/\s+/g, ' ').trim()}`
132
- })
133
- .join('\n')
134
- } catch {}
135
- out.push(`[${new Date(m.at).toLocaleTimeString('zh-CN')}] ${who} 分享了快照:\n${snapText}`)
136
- } else {
137
- out.push(`[${new Date(m.at).toLocaleTimeString('zh-CN')}] ${who}: ${body.text || ''}`)
138
- }
139
- }
140
- return { text: out.join('\n') }
141
- }
142
- if (name === 'chat_send') {
143
- if (!args.to || !args.text) return { isError: true, text: 'to 和 text 都不能为空' }
144
- const r = await api('POST', '/api/messages', { to: args.to, text: args.text })
145
- return { text: `已发送给 ${args.to}(seq=${r.seq})` }
146
- }
147
- if (name === 'chat_add_friend') {
148
- await api('POST', '/api/friends', { id: args.id })
149
- return { text: `已添加 ${args.id} 为好友` }
150
- }
151
- return { isError: true, text: '未知工具:' + name }
152
- }
153
-
154
- // ── JSON-RPC over stdio ─────────────────────────────────
155
-
156
- function send(obj) {
157
- process.stdout.write(JSON.stringify(obj) + '\n')
158
- }
159
-
160
- function reply(id, result) {
161
- send({ jsonrpc: '2.0', id, result })
162
- }
163
-
164
- function replyError(id, code, message) {
165
- send({ jsonrpc: '2.0', id, error: { code, message } })
166
- }
167
-
168
- async function handle(msg) {
169
- const { id, method, params } = msg
170
- if (method === 'initialize') {
171
- reply(id, {
172
- protocolVersion: PROTOCOL,
173
- capabilities: { tools: {} },
174
- serverInfo: { name: NAME, version: VERSION },
175
- })
176
- return
177
- }
178
- if (method === 'notifications/initialized') return
179
- if (method === 'ping') {
180
- reply(id, {})
181
- return
182
- }
183
- if (method === 'tools/list') {
184
- reply(id, { tools: TOOLS })
185
- return
186
- }
187
- if (method === 'tools/call') {
188
- const name = params && params.name
189
- const args = (params && params.arguments) || {}
190
- try {
191
- const out = await callTool(name, args)
192
- reply(id, {
193
- content: [{ type: 'text', text: out.text }],
194
- isError: !!out.isError,
195
- })
196
- } catch (e) {
197
- reply(id, {
198
- content: [{ type: 'text', text: '失败:' + ((e && (e.code || e.message)) || e) }],
199
- isError: true,
200
- })
201
- }
202
- return
203
- }
204
- if (id !== undefined) replyError(id, -32601, 'Method not found: ' + method)
205
- }
206
-
207
- let buf = ''
208
- process.stdin.setEncoding('utf8')
209
- process.stdin.on('data', (chunk) => {
210
- buf += chunk
211
- let idx
212
- while ((idx = buf.indexOf('\n')) !== -1) {
213
- const line = buf.slice(0, idx).trim()
214
- buf = buf.slice(idx + 1)
215
- if (!line) continue
216
- let msg
217
- try {
218
- msg = JSON.parse(line)
219
- } catch {
220
- continue
221
- }
222
- handle(msg).catch(() => {})
223
- }
224
- })
225
- process.stdin.on('end', () => process.exit(0))
package/cli/chat.cmd DELETED
@@ -1,3 +0,0 @@
1
- @echo off
2
- rem chat 的 Windows 启动器:把本文件所在目录放进 PATH,就能直接打 chat
3
- node "%~dp0chat.mjs" %*