dsh-share-chat 0.3.3 → 0.29.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/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" %*
package/cli/chat.mjs DELETED
@@ -1,335 +0,0 @@
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()