dsh-share-chat 0.0.0-stage → 0.3.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/CHANGELOG.md +50 -0
- package/LICENSE +21 -0
- package/README.md +49 -2
- package/cli/chat-mcp.mjs +225 -0
- package/cli/chat.cmd +3 -0
- package/cli/chat.mjs +335 -0
- package/client.js +2500 -0
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +43 -0
- package/game-host/README.md +41 -0
- package/game-host/game.js +8 -0
- package/game-host/index.html +180 -0
- package/game-host/loader.js +106 -0
- package/game-host/wx-shim.js +447 -0
- package/icon.svg +7 -0
- package/index.js +170 -0
- package/locale/en.json +10 -0
- package/locale/zh.json +10 -0
- package/package.json +51 -3
- package/tools/deploy-game.sh +46 -0
- package/tools/game-static.inc +9 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# 更新记录
|
|
2
|
+
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
- **新增会议**:聊天页顶栏 `📹 开会`,新建/加入房间,最多 6 人音视频 + 屏幕共享
|
|
6
|
+
- 纯浏览器 WebRTC 网状直连,relay 只转发信令(SSE 长连接)与成员状态,**无时长限制**
|
|
7
|
+
- 工具栏:麦克风、摄像头、共享屏幕、复制房间号、离开;窗口可拖可缩放,`Esc` 离开
|
|
8
|
+
- STUN 用 Cloudflare / Google 公共节点;对称 NAT 下可能需要 TURN(后续在服务器加 coturn)
|
|
9
|
+
- relay 端:新增 `POST /api/meet/rooms`、`/join`、`/state`、`/signal`、`/leave` 与 `GET …/events`(SSE)
|
|
10
|
+
|
|
11
|
+
## 0.2.2
|
|
12
|
+
|
|
13
|
+
- 合并 0.1.6 的文件缩略图/卡片实现到 0.2 的新界面:图片、视频、音频内联,其它文件显示类型图标 + 类型 + 大小
|
|
14
|
+
- README 重写:三种不需要 Git 的安装方式(tgz / 本地文件夹 / npm),以及「为什么 git 地址必须装 Git」
|
|
15
|
+
- 新增 `docs/INSTALL.md`(安装与排错)、`docs/GAME.md`(小游戏移植与部署)、`CHANGELOG.md`
|
|
16
|
+
- 新增 `game-host/`(小游戏浏览器移植层)与 `tools/`(部署脚本 + nginx 片段)
|
|
17
|
+
- `docs/DETAIL.md` 补充小游戏、窗口尺寸设置与 50 MB 上限
|
|
18
|
+
|
|
19
|
+
## 0.2.1
|
|
20
|
+
|
|
21
|
+
- **界面重做**:整套样式改为注入一张 `<style>` + `--dsw-alias-*` 主题 token,亮色/暗色跟随 DSH
|
|
22
|
+
- 登录页:居中卡片、分段 tab、带标签输入框、聚焦光圈
|
|
23
|
+
- 聊天:头像、好友列表的最后一条摘要、双向气泡、时间戳、空状态
|
|
24
|
+
- 输入区:圆角输入框、表情/附件在框内、发送按钮禁用态
|
|
25
|
+
- 快照卡片、分享条(带预览)、设置页(预设卡片)
|
|
26
|
+
- 窄屏(≤720px)媒体查询
|
|
27
|
+
- 修复:文件消息的缩略图/卡片合并了 0.1.6 的实现(图片/视频/音频内联,其它显示类型图标)
|
|
28
|
+
|
|
29
|
+
## 0.2.0
|
|
30
|
+
|
|
31
|
+
- 首次引入 0.2 系列界面(注入 CSS、class 化组件),功能与 0.1.9 一致
|
|
32
|
+
|
|
33
|
+
## 0.1.9
|
|
34
|
+
|
|
35
|
+
- 小游戏窗口改为**原生 DOM 挂到 `document.body`**(`z-index: 2147483647`),绕开 DSH 面板的 stacking context 与裁切
|
|
36
|
+
- 窗口标题栏加点击诊断(`x,y → 命中区域`),`Esc` 关闭
|
|
37
|
+
|
|
38
|
+
## 0.1.8
|
|
39
|
+
|
|
40
|
+
- 点击问题排查版:窗口 `z-index` 提到最大、加 `pointer-events: auto`
|
|
41
|
+
|
|
42
|
+
## 0.1.7
|
|
43
|
+
|
|
44
|
+
- 小游戏窗口从全屏遮罩改为**右下角浮动窗口**:可拖标题栏、拉右下角改大小,尺寸存 localStorage
|
|
45
|
+
- 新增 **设置 → 社交小游戏**:预设(340×600 / 390×760 / 480×900)+ 自定义宽高 + 恢复默认
|
|
46
|
+
|
|
47
|
+
## 0.1.6
|
|
48
|
+
|
|
49
|
+
- 文件消息支持任意类型(≤50 MB):图片/视频/音频内联,其它文件显示类型图标与大小
|
|
50
|
+
- 上传失败文案由 8 MB 更正为 50 MB
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zhanghao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,50 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 社交(DSH 插件)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
在 DSH 里和好友聊天,并且能把一段对话一键分享给对方——不是截图,是带工具调用和回复的结构化快照。
|
|
4
|
+
|
|
5
|
+
消息不经过任何模型,**不消耗 token**。所有内容存在你自己的服务器上。
|
|
6
|
+
|
|
7
|
+
## 需要什么
|
|
8
|
+
|
|
9
|
+
- DeepSeek Harness **桌面端**(Web 版也行,但入口都在桌面端侧栏)
|
|
10
|
+
- 一个邀请码(找发给你这个插件的人要)
|
|
11
|
+
|
|
12
|
+
## 安装
|
|
13
|
+
|
|
14
|
+
1. 把这个文件夹解压到任意位置,比如 `D:\plugins\share-chat`
|
|
15
|
+
2. 打开 DSH → 左侧栏 **插件** → **添加插件** → 选这个文件夹
|
|
16
|
+
3. 装好后左侧栏会出现 **社交**(如果没有,去左侧栏底部的「更多」里点图钉固定)
|
|
17
|
+
|
|
18
|
+
## 第一次使用
|
|
19
|
+
|
|
20
|
+
1. 左侧栏 → **社交**
|
|
21
|
+
2. 点 **注册**
|
|
22
|
+
3. 填:
|
|
23
|
+
- **服务器地址**:已预填,不用改
|
|
24
|
+
- **邀请码**:找发插件的人要
|
|
25
|
+
- **账号名**:中文可以
|
|
26
|
+
- **密码**:至少 6 位。**一定要设**——账号在服务器上,有密码换电脑、换端口都能登
|
|
27
|
+
4. 进去后,在左栏输对方账号 ID 加好友(对方那边会自动出现你)
|
|
28
|
+
5. 选一个好友开始聊:`Enter` 发送,`Shift+Enter` 换行
|
|
29
|
+
|
|
30
|
+
## 分享一段对话
|
|
31
|
+
|
|
32
|
+
在会话里点 **社交** 标签页(跟「对话」「轨迹」那一排),顶部有 **「分享这一轮」**:
|
|
33
|
+
|
|
34
|
+
1. 点它 → 出现**预览**,一眼能看到将要发出去的内容
|
|
35
|
+
2. 选好友 → 发送
|
|
36
|
+
|
|
37
|
+
分享内容包含:你的提问、工具调用(压成一行)、我的回复。
|
|
38
|
+
**不包含**:思考过程、系统注入的上下文(运行时时间戳、工作目录等)。
|
|
39
|
+
|
|
40
|
+
## 已知限制
|
|
41
|
+
|
|
42
|
+
- 只分享**最后一轮**,不是整个会话
|
|
43
|
+
- 消息 5 秒轮询,不是实时推送
|
|
44
|
+
- 没有群聊、已读回执、撤回、图片、语音
|
|
45
|
+
- 服务器明文存储,分享的快照 **7 天后过期**
|
|
46
|
+
- 服务器地址和 token 存在浏览器本地;**换登录端口会掉登录,用密码重新登即可**
|
|
47
|
+
|
|
48
|
+
## 卸载
|
|
49
|
+
|
|
50
|
+
DSH → 插件 → 找到「社交」→ 停用或移除。
|
package/cli/chat-mcp.mjs
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
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
ADDED
package/cli/chat.mjs
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* chat —— 给你的 relay 用的命令行客户端
|
|
4
|
+
*
|
|
5
|
+
* 目标用户是 agent(Codex / Claude Code / DSH),所以:
|
|
6
|
+
* - 每个命令都是无状态的,跑完就退
|
|
7
|
+
* - --json 输出给程序吃
|
|
8
|
+
* - 光标(cursor)存在本地,`read` 只吐新消息
|
|
9
|
+
*
|
|
10
|
+
* 零依赖,只用 Node 内置模块。用法见 `node chat.mjs help`。
|
|
11
|
+
*/
|
|
12
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import os from 'node:os'
|
|
15
|
+
import readline from 'node:readline'
|
|
16
|
+
|
|
17
|
+
const DEFAULT_SERVER = 'https://xdxy-pet.com/relay'
|
|
18
|
+
const CONFIG_DIR = path.join(os.homedir(), '.dsh-chat')
|
|
19
|
+
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json')
|
|
20
|
+
|
|
21
|
+
function loadConfig() {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(readFileSync(CONFIG_FILE, 'utf8'))
|
|
24
|
+
} catch {
|
|
25
|
+
return {}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function saveConfig(cfg) {
|
|
30
|
+
mkdirSync(CONFIG_DIR, { recursive: true })
|
|
31
|
+
writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + '\n', 'utf8')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ── 参数 ───────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
const argv = process.argv.slice(2)
|
|
37
|
+
const command = argv[0]
|
|
38
|
+
|
|
39
|
+
/** 取出并移除 --flag [value] */
|
|
40
|
+
function takeFlag(name, hasValue) {
|
|
41
|
+
const i = argv.indexOf('--' + name)
|
|
42
|
+
if (i === -1) return undefined
|
|
43
|
+
if (!hasValue) {
|
|
44
|
+
argv.splice(i, 1)
|
|
45
|
+
return true
|
|
46
|
+
}
|
|
47
|
+
const v = argv[i + 1]
|
|
48
|
+
argv.splice(i, 2)
|
|
49
|
+
return v
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const jsonOut = !!takeFlag('json', false)
|
|
53
|
+
const serverFlag = takeFlag('server', true)
|
|
54
|
+
const tokenFlag = takeFlag('token', true)
|
|
55
|
+
const sinceFlag = takeFlag('since', true)
|
|
56
|
+
const withFlag = takeFlag('with', true)
|
|
57
|
+
const limitFlag = takeFlag('limit', true)
|
|
58
|
+
const allFlag = !!takeFlag('all', false)
|
|
59
|
+
const passwordFlag = takeFlag('password', true)
|
|
60
|
+
const inviteFlag = takeFlag('invite', true)
|
|
61
|
+
|
|
62
|
+
const positional = argv.slice(1).filter((a) => !a.startsWith('--'))
|
|
63
|
+
|
|
64
|
+
const cfg = loadConfig()
|
|
65
|
+
const server = String(
|
|
66
|
+
serverFlag || process.env.DSH_CHAT_SERVER || cfg.server || DEFAULT_SERVER,
|
|
67
|
+
).replace(/\/+$/, '')
|
|
68
|
+
const token = tokenFlag || process.env.DSH_CHAT_TOKEN || cfg.token || ''
|
|
69
|
+
|
|
70
|
+
function fail(msg, code) {
|
|
71
|
+
process.stderr.write(msg + '\n')
|
|
72
|
+
process.exit(code === undefined ? 1 : code)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function api(method, p, body) {
|
|
76
|
+
const headers = {}
|
|
77
|
+
if (body !== undefined) headers['content-type'] = 'application/json'
|
|
78
|
+
if (token) headers.authorization = 'Bearer ' + token
|
|
79
|
+
let res
|
|
80
|
+
try {
|
|
81
|
+
res = await fetch(server + p, {
|
|
82
|
+
method,
|
|
83
|
+
headers,
|
|
84
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
85
|
+
})
|
|
86
|
+
} catch (e) {
|
|
87
|
+
fail('连不上服务器 ' + server + ':' + (e && e.message))
|
|
88
|
+
}
|
|
89
|
+
let data = null
|
|
90
|
+
try {
|
|
91
|
+
data = await res.json()
|
|
92
|
+
} catch {}
|
|
93
|
+
if (!res.ok) {
|
|
94
|
+
const code = (data && data.error) || 'http-' + res.status
|
|
95
|
+
const hint = {
|
|
96
|
+
'bad-credentials': '账号或密码不对',
|
|
97
|
+
'invalid-invite': '邀请码不对',
|
|
98
|
+
unauthorized: '没有登录,先跑 chat login',
|
|
99
|
+
'not-friend': '你们还不是好友',
|
|
100
|
+
'no-such-user': '没有这个账号',
|
|
101
|
+
}[code]
|
|
102
|
+
fail('失败:' + code + (hint ? '(' + hint + ')' : ''))
|
|
103
|
+
}
|
|
104
|
+
return data
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function clockText(at) {
|
|
108
|
+
try {
|
|
109
|
+
return new Date(at).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
|
|
110
|
+
} catch {
|
|
111
|
+
return ''
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ── 密码输入(不回显)────────────────────────────────────
|
|
116
|
+
|
|
117
|
+
function askPassword(prompt) {
|
|
118
|
+
if (!process.stdin.isTTY) {
|
|
119
|
+
return new Promise((resolve) => {
|
|
120
|
+
let buf = ''
|
|
121
|
+
process.stdin.setEncoding('utf8')
|
|
122
|
+
process.stdin.on('data', (c) => {
|
|
123
|
+
buf += c
|
|
124
|
+
if (buf.includes('\n')) resolve(buf.split('\n')[0].trim())
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
return new Promise((resolve) => {
|
|
129
|
+
process.stderr.write(prompt)
|
|
130
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true })
|
|
131
|
+
const onData = (ch) => {
|
|
132
|
+
if (ch === '\n' || ch === '\r' || ch === '\u0004') process.stdin.removeListener('data', onData)
|
|
133
|
+
else if (ch === '\u0003') {
|
|
134
|
+
rl.close()
|
|
135
|
+
process.exit(130)
|
|
136
|
+
} else process.stderr.write('')
|
|
137
|
+
}
|
|
138
|
+
// 简单实现:行内读入但不回显(不同终端表现略有差异)
|
|
139
|
+
rl.question('', (answer) => {
|
|
140
|
+
rl.close()
|
|
141
|
+
process.stderr.write('\n')
|
|
142
|
+
resolve(answer.trim())
|
|
143
|
+
})
|
|
144
|
+
process.stdin.on('data', onData)
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ── 渲染 ───────────────────────────────────────────────
|
|
149
|
+
|
|
150
|
+
const WIDTH = Math.min(process.stdout.columns || 80, 100)
|
|
151
|
+
|
|
152
|
+
function frameSnapshot(snap) {
|
|
153
|
+
const title = ' 从 DSH 分享 · ' + (snap.title || '') + ' '
|
|
154
|
+
const top = '┌─' + title + '─'.repeat(Math.max(0, WIDTH - title.length - 3))
|
|
155
|
+
const lines = [top]
|
|
156
|
+
for (const b of snap.blocks || []) {
|
|
157
|
+
const tag = b.t === 'user' ? '你' : b.t === 'tool' ? b.name || '工具' : '我'
|
|
158
|
+
const body = String(b.text || '').replace(/\s+/g, ' ').trim()
|
|
159
|
+
// 简单折行
|
|
160
|
+
let rest = '[' + tag + '] ' + body
|
|
161
|
+
while (rest.length > 0) {
|
|
162
|
+
const chunk = rest.slice(0, WIDTH - 4)
|
|
163
|
+
rest = rest.slice(WIDTH - 4)
|
|
164
|
+
lines.push('│ ' + chunk)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
lines.push('└' + '─'.repeat(Math.max(0, WIDTH - 1)))
|
|
168
|
+
return lines.join('\n')
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function renderMessage(m, me) {
|
|
172
|
+
const mine = m.from === me
|
|
173
|
+
const who = mine ? '你' : m.from
|
|
174
|
+
const body = m.body || {}
|
|
175
|
+
if (body.kind === 'snapshot') {
|
|
176
|
+
try {
|
|
177
|
+
const r = await api('GET', '/api/snapshots/' + encodeURIComponent(body.snapshotId))
|
|
178
|
+
return '[' + clockText(m.at) + '] ' + who + ' 发来一个快照\n' + frameSnapshot(r.snapshot)
|
|
179
|
+
} catch {
|
|
180
|
+
return '[' + clockText(m.at) + '] ' + who + ' 发来一个快照(已过期或无权查看)'
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return '[' + clockText(m.at) + '] ' + who + ': ' + (body.text || '')
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ── 命令 ───────────────────────────────────────────────
|
|
187
|
+
|
|
188
|
+
async function cmdLogin() {
|
|
189
|
+
const id = positional[0]
|
|
190
|
+
if (!id) fail('用法:chat login <账号> [--password xxx]')
|
|
191
|
+
const password = passwordFlag || process.env.DSH_CHAT_PASSWORD || (await askPassword('密码: '))
|
|
192
|
+
const r = await api('POST', '/api/login', { id, password })
|
|
193
|
+
saveConfig({ ...loadConfig(), server, id: r.id, token: r.token, cursor: 0 })
|
|
194
|
+
if (jsonOut) console.log(JSON.stringify({ id: r.id, displayName: r.displayName }))
|
|
195
|
+
else console.log('✓ 已登录 @' + (r.displayName || r.id) + ' (' + server + ')')
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function cmdRegister() {
|
|
199
|
+
const id = positional[0]
|
|
200
|
+
if (!id) fail('用法:chat register <账号> --invite <邀请码> [--password xxx]')
|
|
201
|
+
const invite = inviteFlag || process.env.DSH_CHAT_INVITE
|
|
202
|
+
if (!invite) fail('缺 --invite 邀请码')
|
|
203
|
+
const password = passwordFlag || process.env.DSH_CHAT_PASSWORD || (await askPassword('设置密码: '))
|
|
204
|
+
const r = await api('POST', '/api/register', { invite, id, displayName: id, password })
|
|
205
|
+
saveConfig({ ...loadConfig(), server, id: r.id, token: r.token, cursor: 0 })
|
|
206
|
+
if (jsonOut) console.log(JSON.stringify({ id: r.id, displayName: r.displayName }))
|
|
207
|
+
else console.log('✓ 已注册并登录 @' + (r.displayName || r.id))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function cmdWhoami() {
|
|
211
|
+
const me = await api('GET', '/api/me')
|
|
212
|
+
if (jsonOut) console.log(JSON.stringify(me))
|
|
213
|
+
else console.log('@' + (me.displayName || me.id) + ' (' + server + ')')
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function cmdFriends() {
|
|
217
|
+
const r = await api('GET', '/api/friends')
|
|
218
|
+
if (jsonOut) console.log(JSON.stringify(r.friends))
|
|
219
|
+
else if (!r.friends.length) console.log('还没有好友。chat add <账号>')
|
|
220
|
+
else for (const f of r.friends) console.log((f.displayName || f.id).padEnd(16) + f.id)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function cmdAdd() {
|
|
224
|
+
const id = positional[0]
|
|
225
|
+
if (!id) fail('用法:chat add <账号>')
|
|
226
|
+
const r = await api('POST', '/api/friends', { id })
|
|
227
|
+
if (jsonOut) console.log(JSON.stringify(r))
|
|
228
|
+
else console.log('✓ 已加好友 ' + id)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function cmdSend() {
|
|
232
|
+
const to = positional[0]
|
|
233
|
+
const text = positional.slice(1).join(' ')
|
|
234
|
+
if (!to || !text) fail('用法:chat send <账号> "消息"')
|
|
235
|
+
const r = await api('POST', '/api/messages', { to, text })
|
|
236
|
+
if (jsonOut) console.log(JSON.stringify(r))
|
|
237
|
+
else console.log('✓ 已发送 seq=' + r.seq)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function cmdRead() {
|
|
241
|
+
const since = sinceFlag !== undefined ? Number(sinceFlag) : allFlag ? 0 : cfg.cursor || 0
|
|
242
|
+
const r = await api('GET', '/api/messages?since=' + since)
|
|
243
|
+
let msgs = r.messages || []
|
|
244
|
+
if (withFlag) msgs = msgs.filter((m) => m.from === withFlag || m.to === withFlag)
|
|
245
|
+
msgs.sort((a, b) => a.seq - b.seq)
|
|
246
|
+
|
|
247
|
+
const me = cfg.id || ''
|
|
248
|
+
if (jsonOut) {
|
|
249
|
+
const out = []
|
|
250
|
+
for (const m of msgs) {
|
|
251
|
+
const item = { seq: m.seq, from: m.from, to: m.to, at: m.at, body: m.body }
|
|
252
|
+
if (m.body && m.body.kind === 'snapshot') {
|
|
253
|
+
try {
|
|
254
|
+
const s = await api('GET', '/api/snapshots/' + encodeURIComponent(m.body.snapshotId))
|
|
255
|
+
item.snapshot = s.snapshot
|
|
256
|
+
} catch (e) {
|
|
257
|
+
item.snapshotError = String((e && e.message) || e)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
out.push(item)
|
|
261
|
+
}
|
|
262
|
+
console.log(JSON.stringify({ cursor: r.cursor, messages: out }, null, 2))
|
|
263
|
+
} else {
|
|
264
|
+
if (msgs.length === 0) console.log('(没有新消息)')
|
|
265
|
+
for (const m of msgs) console.log(await renderMessage(m, me))
|
|
266
|
+
}
|
|
267
|
+
if (sinceFlag === undefined && !allFlag && limitFlag === undefined) {
|
|
268
|
+
saveConfig({ ...loadConfig(), cursor: r.cursor })
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async function cmdWatch() {
|
|
273
|
+
let cursor = sinceFlag !== undefined ? Number(sinceFlag) : allFlag ? 0 : cfg.cursor || 0
|
|
274
|
+
const me = cfg.id || ''
|
|
275
|
+
console.error('监听中' + (withFlag ? '(只显示与 ' + withFlag + ' 的往來)' : '') + ' · Ctrl+C 退出')
|
|
276
|
+
let stop = false
|
|
277
|
+
process.on('SIGINT', () => {
|
|
278
|
+
stop = true
|
|
279
|
+
console.error('\n已退出')
|
|
280
|
+
process.exit(0)
|
|
281
|
+
})
|
|
282
|
+
while (!stop) {
|
|
283
|
+
try {
|
|
284
|
+
const r = await api('GET', '/api/messages?since=' + cursor)
|
|
285
|
+
let msgs = r.messages || []
|
|
286
|
+
if (withFlag) msgs = msgs.filter((m) => m.from === withFlag || m.to === withFlag)
|
|
287
|
+
for (const m of msgs) console.log(await renderMessage(m, me))
|
|
288
|
+
if (msgs.length) saveConfig({ ...loadConfig(), cursor: r.cursor })
|
|
289
|
+
cursor = r.cursor
|
|
290
|
+
} catch {
|
|
291
|
+
/* 网络抖动,继续 */
|
|
292
|
+
}
|
|
293
|
+
await new Promise((r) => setTimeout(r, 3000))
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function help() {
|
|
298
|
+
console.log(`chat —— relay 命令行客户端
|
|
299
|
+
|
|
300
|
+
chat login <账号> [--password x] 登录(password 不填会提示输入)
|
|
301
|
+
chat register <账号> --invite <码> 注册并登录
|
|
302
|
+
chat whoami 当前身份
|
|
303
|
+
chat friends 好友列表
|
|
304
|
+
chat add <账号> 加好友
|
|
305
|
+
chat send <账号> "内容" 发消息
|
|
306
|
+
chat read [--since N] [--with 账号] 收消息(默认只给上次之后的新消息)
|
|
307
|
+
chat watch [--with 账号] 前台持续收,Ctrl+C 退出
|
|
308
|
+
|
|
309
|
+
通用参数
|
|
310
|
+
--json 输出 JSON(给 agent / 脚本用)
|
|
311
|
+
--server <url> 指定服务器(默认 ${DEFAULT_SERVER})
|
|
312
|
+
--token <token> 临时指定 token
|
|
313
|
+
--all 忽略本地光标,从头读
|
|
314
|
+
|
|
315
|
+
环境变量
|
|
316
|
+
DSH_CHAT_SERVER DSH_CHAT_TOKEN DSH_CHAT_PASSWORD DSH_CHAT_INVITE
|
|
317
|
+
|
|
318
|
+
配置存放在 ${CONFIG_FILE}`)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const commands = {
|
|
322
|
+
login: cmdLogin,
|
|
323
|
+
register: cmdRegister,
|
|
324
|
+
whoami: cmdWhoami,
|
|
325
|
+
friends: cmdFriends,
|
|
326
|
+
add: cmdAdd,
|
|
327
|
+
send: cmdSend,
|
|
328
|
+
read: cmdRead,
|
|
329
|
+
watch: cmdWatch,
|
|
330
|
+
help,
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const fn = commands[command || 'help']
|
|
334
|
+
if (!fn) fail('未知命令:' + command + '\n跑 chat help 看用法')
|
|
335
|
+
await fn()
|