dsh-channel-wechat-ilink 0.1.0 → 0.1.2

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/AGENTS.md CHANGED
@@ -10,8 +10,9 @@ dsh plugin add dsh-channel-wechat-ilink
10
10
  ```
11
11
 
12
12
  The row is inserted by the bundle patch and defaults to `provider: wechat`.
13
- Inbound defaults to off; enabling it lets anyone allowed in the chat drive the
14
- local agent, so ask first.
13
+ Inbound defaults to off; enabling it lets allowed senders drive the local agent,
14
+ so ask first. With an empty `allowedUsers`, the account that scanned the QR is
15
+ bound as the owner automatically, and every other sender is refused.
15
16
 
16
17
  ## 2. Log in
17
18
 
package/README.md CHANGED
@@ -14,16 +14,24 @@
14
14
  name: "dsh-channel-wechat-ilink"
15
15
  config:
16
16
  provider: wechat
17
- inboundEnabled: true
17
+ inboundEnabled: false # 默认关;开启前先确认下面三个安全项
18
18
  sessionMode: create
19
19
  workspacePath: "" # 空 = <非系统盘>/dsh/wechat
20
20
  ```
21
21
 
22
+ ### 开启入站前先看这三个默认值
23
+
24
+ | 配置 | 默认 | 含义 |
25
+ |---|---|---|
26
+ | `inboundEnabled` | `false` | 打开后,能给它发消息的人就能驱动本地 Agent |
27
+ | `allowedUsers` | `[]` | 空不是"谁都可以":扫码登录的那个微信号会**自动绑定**为 owner,其他人被拒;要加人再显式列出 |
28
+ | `permissionPreset` / `applyPermissionPreset` | `danger-full-access` / `true` | 无人值守没人能点审批,所以通道工作区里的会话切到这个预设;嫌大就改 `workspace-write` 或关掉 apply |
29
+
22
30
  3. **重启 DSH**(插件在启动时加载,没有热更新)。
23
31
 
24
32
  ## 与飞书的差异
25
33
 
26
- - 没有卡片、不能编辑消息:回答按段落分条发送,进度用「正在输入」+ 阶段性文本;
34
+ - 没有卡片、不能编辑消息:**一轮回答一条完整消息**(超过 1800 字才拆续条),进度用「正在输入」+ 阶段性文本;
27
35
  - **没有历史消息接口**:断线后无法像飞书那样按时间补拉。用两个定时器兜底——长轮询 2 分钟没完成就重建,游标 20 分钟没新消息就重置重新拉取;
28
36
  - 只能在用户最近一次发消息后的 24 小时内主动推送;
29
37
  - 问答是纯文本编号:回数字选择,直接回文字就是补充。
package/cordis.patch.yml CHANGED
@@ -1,6 +1,14 @@
1
1
  # Bundle patch: inserts the channel row into the profile that installs this
2
2
  # package. Everything here is a default; a profile's cordis.patch.yml overrides
3
3
  # it (a matching override replaces the complete `config`).
4
+ #
5
+ # Three defaults are deliberately conservative — read them before enabling:
6
+ # inboundEnabled: false the channel does not listen until you opt in
7
+ # allowedUsers: [] empty = the logged-in account owns it (WeChat)
8
+ # / the first sender binds it (Feishu)
9
+ # permissionPreset + apply... unattended turns cannot answer approvals, so
10
+ # sessions in the channel workspace switch to the
11
+ # preset below once inbound is on
4
12
  - insert:
5
13
  - id: wechat-channel
6
14
  name: 'dsh-channel-wechat-ilink'
@@ -9,15 +17,19 @@
9
17
  provider: wechat
10
18
  # Register the tools at all.
11
19
  enabled: true
12
- # Long connection + inbound delivery. On by default: this is a channel
13
- # plugin, so "installs and starts receiving" is the expected behaviour.
14
- # Set false when the bot should only send (wechat_send_message/file).
15
- inboundEnabled: true
20
+ # Long connection + inbound delivery. OFF by default: anyone inside the
21
+ # app's visibility scope can drive the local agent once this is on, so
22
+ # enabling it is an explicit decision (set it to true after you have an
23
+ # allowlist and understand the permission preset below).
24
+ # Leave false when the bot should only send (wechat_send_message/file).
25
+ inboundEnabled: false
16
26
  # Session inbound messages go to; `create` makes it when missing, which
17
27
  # is what a fresh install needs: the first message opens the session.
18
28
  sessionId: ''
19
29
  sessionMode: create
20
- # Sender allowlist (open_id); empty accepts anyone.
30
+ # Sender allowlist (open_id). Empty is not "open to everyone": the first
31
+ # sender binds the channel and later senders are refused. Fill it in to
32
+ # choose the owner up front instead of letting a message choose it.
21
33
  allowedUsers: []
22
34
  # Workspace that owns channel sessions; '' uses <home>/dsh/wechat.
23
35
  workspacePath: ''
@@ -29,8 +41,9 @@
29
41
  # conversation can be followed from either surface.
30
42
  mirrorUserMessages: true
31
43
  # Unattended turns have nobody to answer approvals, so sessions in the
32
- # workspace switch to this preset (set applyPermissionPreset: false to
33
- # keep each session's own policy).
44
+ # workspace switch to this preset. danger-full-access means "the bot can
45
+ # do anything on this machine when you chat with it"; use workspace-write
46
+ # or set applyPermissionPreset: false if that is too much.
34
47
  permissionPreset: danger-full-access
35
48
  applyPermissionPreset: true
36
49
  # Credentials stay out of this file: run scripts/wechat-login.mjs, which
package/index.js CHANGED
@@ -2178,6 +2178,26 @@ function persistSeenEvents(config, seen) {
2178
2178
  return writeChannelState(config, { seenEvents: [...seen].slice(-SEEN_EVENTS_LIMIT) })
2179
2179
  }
2180
2180
 
2181
+ /**
2182
+ * Bind the channel owner from the login, not from the first message.
2183
+ *
2184
+ * An empty `allowedUsers` used to mean "whoever writes first owns the channel",
2185
+ * which leaves a window where a stranger can take it. Providers that know who
2186
+ * logged in (WeChat stores the scanning user id with the bot token) hand it over
2187
+ * here, so the owner is fixed before the first message arrives.
2188
+ */
2189
+ function bindOwnerFromCredentials(config) {
2190
+ try {
2191
+ const state = readChannelState(config)
2192
+ if (String(state.owner?.openId ?? '').trim()) return
2193
+ const settings = provider()?.settings?.()
2194
+ const ownerId = String(settings?.userId ?? '').trim()
2195
+ if (!ownerId) return
2196
+ writeChannelState(config, { owner: { openId: ownerId, at: Date.now(), source: 'login' } })
2197
+ logInbound(config, { event: 'inbound', result: 'owner-bound', senderId: ownerId, source: 'login' })
2198
+ } catch { /* binding is best effort: the first-message path still covers it */ }
2199
+ }
2200
+
2181
2201
  function writeChannelState(config, patch) {
2182
2202
  try {
2183
2203
  const next = { ...readChannelState(config), ...patch, updatedAt: Date.now() }
@@ -3646,6 +3666,7 @@ function startInbound(ctx, config) {
3646
3666
  // Dedupe survives restarts: a reconnecting long connection can redeliver
3647
3667
  // an event the previous process already handled.
3648
3668
  for (const eventId of loadSeenEvents(config)) seen.add(eventId)
3669
+ bindOwnerFromCredentials(config)
3649
3670
  channelRuntime = { ctx: scoped, config }
3650
3671
  // The active session may already be live from an earlier message; its
3651
3672
  // policy must match the channel's preset even before the next inbound one,
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "WeChat channel",
4
- "description": "Connects WeChat (ClawBot / iLink) to a DSH session: staged plain-text answers, a typing indicator plus progress notes, and media in both directions. Run scripts/wechat-login.mjs to scan the QR code; the token lands in ~/.dsh/wechat-channel.json."
4
+ "description": "Connects WeChat (ClawBot / iLink) to a DSH session: one complete plain-text message per turn (split only when very long), a typing indicator plus progress notes, and media in both directions. Run scripts/wechat-login.mjs to scan the QR code; the token lands in ~/.dsh/wechat-channel.json."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "微信通道",
4
- "description": "把微信(ClawBot / iLink)接到一个 DSH 会话:回答按段落分条发送,长任务先显示「正在输入」再补进度,图片和文件双向收发,通道独占一个工作区。用 scripts/wechat-login.mjs 扫码登录,凭据写到 ~/.dsh/wechat-channel.json。",
4
+ "description": "把微信(ClawBot / iLink)接到一个 DSH 会话:一轮回答一条完整消息(只有超长才拆续条),长任务先显示「正在输入」再补进度,图片和文件双向收发,通道独占一个工作区。用 scripts/wechat-login.mjs 扫码登录,凭据写到 ~/.dsh/wechat-channel.json。",
5
5
  "detail": "docs/DETAIL.zh.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-channel-wechat-ilink",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
- "description": "WeChat (iLink / ClawBot) channel for DeepSeek Harness: staged plain-text answers, typing plus progress, media both ways, one workspace per channel.",
5
+ "description": "WeChat (iLink / ClawBot) channel for DeepSeek Harness: one plain-text message per turn (split only when very long), typing plus progress, media both ways, one workspace per channel.",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -2,8 +2,8 @@
2
2
  * WeChat (iLink / 微信 ClawBot) transport adapter for the DSH channel framework.
3
3
  *
4
4
  * Protocol facts are taken from Tencent's official client
5
- * (`@tencent-weixin/openclaw-weixin`, MIT) and verified live by
6
- * `scripts/wechat-probe.mjs`:
5
+ * (`@tencent-weixin/openclaw-weixin`, MIT) and verified live with
6
+ * `scripts/wechat-e2e.mjs`:
7
7
  *
8
8
  * - login: QR scan → `bot_token` + `ilink_bot_id` (+ `baseurl`)
9
9
  * - inbound: long-poll `ilink/bot/getupdates` with a `get_updates_buf` cursor
@@ -13,8 +13,9 @@
13
13
  * padding, so decryption runs with `setAutoPadding(false)`
14
14
  *
15
15
  * There is no editable message and no card, so `card.*` is implemented on top of
16
- * `text-stream.js`: one turn becomes a sequence of plain messages (progress,
17
- * staged answer, final flush).
16
+ * `text-stream.js`: a turn is delivered as ONE plain-text message (progress notes
17
+ * while it runs, then the whole answer), and only an answer over the size cap is
18
+ * continued in a second message.
18
19
  */
19
20
 
20
21
  import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto'
@@ -1,386 +0,0 @@
1
- /**
2
- * WeChat (iLink) probe: receive → typing → reply → media in/out.
3
- *
4
- * Uses the token saved by `scripts/wechat-login.mjs`. It is intentionally a
5
- * separate script (not a plugin provider): the point is to learn the live
6
- * behaviour — message shapes, typing, tool-call items, CDN round trips — before
7
- * `providers/wechat.js` is written against it.
8
- *
9
- * Commands the phone can send:
10
- * anything → typing on, echo "收到:<text>", a native tool-call pair
11
- * (start + result), typing off
12
- * "img" → reply with a generated PNG (outbound media test)
13
- * an image/file → download + AES decrypt, then echo it straight back
14
- *
15
- * Usage: node scripts/wechat-probe.mjs
16
- */
17
- import { createDecipheriv, createCipheriv, createHash, randomBytes, randomUUID } from 'node:crypto'
18
- import { gunzipSync } from 'node:zlib'
19
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
20
- import { homedir } from 'node:os'
21
- import { join } from 'node:path'
22
-
23
- const CRED_PATH = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'wechat-channel.json')
24
- const MEDIA_DIR = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'wechat-probe-media')
25
- const CDN_BASE = 'https://novac2c.cdn.weixin.qq.com/c2c'
26
- const CLIENT_VERSION = '2.4.10'
27
- const APP_ID = 'bot'
28
- const POLL_MS = 35_000
29
-
30
- const cred = JSON.parse(readFileSync(CRED_PATH, 'utf8'))
31
- const BASE = String(cred.baseUrl || 'https://ilinkai.weixin.qq.com').replace(/\/$/, '')
32
- mkdirSync(MEDIA_DIR, { recursive: true })
33
-
34
- const encodeVersion = (version) => {
35
- const [major = 0, minor = 0, patch = 0] = String(version).split('.').map((part) => parseInt(part, 10) || 0)
36
- return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff)
37
- }
38
- const baseInfo = () => ({ channel_version: CLIENT_VERSION, bot_agent: 'DSH/0.1' })
39
- const headers = () => ({
40
- 'Content-Type': 'application/json',
41
- AuthorizationType: 'ilink_bot_token',
42
- 'X-WECHAT-UIN': Buffer.from(String(randomBytes(4).readUInt32BE(0))).toString('base64'),
43
- 'iLink-App-Id': APP_ID,
44
- 'iLink-App-ClientVersion': String(encodeVersion(CLIENT_VERSION)),
45
- Authorization: `Bearer ${cred.botToken}`,
46
- })
47
- const log = (...args) => console.log(...args)
48
- const short = (text, size = 60) => {
49
- const value = String(text ?? '')
50
- return value.length > size ? `${value.slice(0, size)}…` : value
51
- }
52
- const clientId = () => `dsh-wechat-${randomUUID()}`
53
-
54
- async function api(path, body, timeoutMs = 15_000) {
55
- const controller = new AbortController()
56
- const timer = setTimeout(() => controller.abort(), timeoutMs)
57
- try {
58
- const res = await fetch(`${BASE}/${path}`, { method: 'POST', headers: headers(), body: JSON.stringify(body), signal: controller.signal })
59
- const text = await res.text()
60
- if (!res.ok) throw new Error(`${path} ${res.status}: ${short(text, 200)}`)
61
- return text ? JSON.parse(text) : {}
62
- } finally {
63
- clearTimeout(timer)
64
- }
65
- }
66
-
67
- const itemOf = (message, type) => (message.item_list ?? []).find((item) => item?.type === type)
68
-
69
- async function sendItems(to, contextToken, items, runId) {
70
- const response = await api('ilink/bot/sendmessage', {
71
- msg: {
72
- from_user_id: '',
73
- to_user_id: to,
74
- client_id: clientId(),
75
- message_type: 2,
76
- message_state: 2,
77
- item_list: items,
78
- context_token: contextToken,
79
- run_id: runId,
80
- },
81
- base_info: baseInfo(),
82
- })
83
- if (response.ret && response.ret !== 0) throw new Error(`send ret=${response.ret} ${response.errmsg ?? ''}`)
84
- return response
85
- }
86
-
87
- const textItem = (text) => ({ type: 1, text_item: { text } })
88
- const toolStart = (name, id) => ({
89
- type: 11, create_time_ms: Date.now(), is_completed: false,
90
- tool_call_start_item: { tool_name: name, tool_call_id: id },
91
- })
92
- const toolResult = (name, id, status = 'completed') => ({
93
- type: 12, create_time_ms: Date.now(), is_completed: true,
94
- tool_call_result_item: { tool_name: name, tool_call_id: id, status },
95
- })
96
-
97
- let typingTicketCache = new Map()
98
- async function typingTicket(userId, contextToken) {
99
- if (typingTicketCache.has(userId)) return typingTicketCache.get(userId)
100
- const response = await api('ilink/bot/getconfig', { ilink_user_id: userId, context_token: contextToken, base_info: baseInfo() }, 10_000)
101
- const ticket = response?.typing_ticket
102
- if (ticket) typingTicketCache.set(userId, ticket)
103
- return ticket
104
- }
105
- async function typing(userId, contextToken, status) {
106
- try {
107
- const ticket = await typingTicket(userId, contextToken)
108
- if (!ticket) return { ok: false, reason: 'no typing_ticket' }
109
- await api('ilink/bot/sendtyping', { ilink_user_id: userId, typing_ticket: ticket, status, base_info: baseInfo() }, 10_000)
110
- return { ok: true }
111
- } catch (error) {
112
- return { ok: false, reason: String(error).slice(0, 120) }
113
- }
114
- }
115
-
116
- const parseAesKey = (aesKeyBase64) => {
117
- const decoded = Buffer.from(aesKeyBase64, 'base64')
118
- if (decoded.length === 16) return decoded
119
- if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(decoded.toString('ascii'))) {
120
- return Buffer.from(decoded.toString('ascii'), 'hex')
121
- }
122
- throw new Error(`bad aes_key (${decoded.length} bytes)`)
123
- }
124
- /**
125
- * AES-128-ECB decrypt that survives an unpadded (or oddly padded) tail.
126
- *
127
- * WeChat pads outbound CDN uploads, but the inbound payload can end on an exact
128
- * block boundary without PKCS#7 padding — `final()` then throws
129
- * "wrong final block length". Decrypt without auto-padding and strip the pad
130
- * only when it is genuinely there.
131
- */
132
- const aesDecrypt = (cipher, key) => {
133
- const decipher = createDecipheriv('aes-128-ecb', key, null)
134
- decipher.setAutoPadding(false)
135
- const raw = Buffer.concat([decipher.update(cipher), decipher.final()])
136
- const pad = raw[raw.length - 1]
137
- if (pad > 0 && pad <= 16 && raw.length % 16 === 0) {
138
- let valid = true
139
- for (let at = raw.length - pad; at < raw.length; at += 1) {
140
- if (raw[at] !== pad) { valid = false; break }
141
- }
142
- if (valid) return raw.subarray(0, raw.length - pad)
143
- }
144
- return raw
145
- }
146
- const aesEncrypt = (plain, key) => Buffer.concat([createCipheriv('aes-128-ecb', key, null).update(plain), createCipheriv('aes-128-ecb', key, null).final()])
147
- const paddedSize = (size) => Math.ceil((size + 1) / 16) * 16
148
- const AES_KEY_NAMES = ['aes_key', 'aeskey', 'aesKey', 'AESKey']
149
- const mediaKeyOf = (item, media) => {
150
- // WeChat sends the image key twice: `image_item.aeskey` is raw hex and is the
151
- // one its own client decrypts with; `media.aes_key` is base64.
152
- for (const name of AES_KEY_NAMES) {
153
- const raw = item?.[name]
154
- if (typeof raw === 'string' && raw.trim()) {
155
- const value = raw.trim()
156
- const key = /^[0-9a-fA-F]{32}$/.test(value)
157
- ? Buffer.from(value, 'hex')
158
- : (() => { try { return parseAesKey(value) } catch { return undefined } })()
159
- if (key) return { key, source: name }
160
- }
161
- }
162
- for (const name of AES_KEY_NAMES) {
163
- const raw = media?.[name]
164
- if (typeof raw === 'string' && raw.trim()) {
165
- try { return { key: parseAesKey(raw.trim()), source: `media.${name}` } } catch { /* try next */ }
166
- }
167
- }
168
- return undefined
169
- }
170
-
171
- const looksLikeImage = (buf) => {
172
- if (!buf || buf.length < 4) return false
173
- const hex = buf.subarray(0, 8).toString('hex')
174
- return hex.startsWith('89504e47') || hex.startsWith('ffd8') || hex.startsWith('52494646') || hex.startsWith('47494638')
175
- }
176
- const looksLikeArchive = (buf) => {
177
- if (!buf || buf.length < 4) return false
178
- const hex = buf.subarray(0, 4).toString('hex')
179
- return hex.startsWith('1f8b') || hex.startsWith('504b0304') || hex.startsWith('25504446')
180
- }
181
- const aesDecryptCbc = (cipher, key, iv) => Buffer.concat([createDecipheriv('aes-128-cbc', key, iv).update(cipher), createDecipheriv('aes-128-cbc', key, iv).final()])
182
-
183
- /**
184
- * Image payloads show up in a few shapes in the wild (ECB is the documented one,
185
- * but the CDN has also served CBC with a zero IV, and occasionally plain bytes).
186
- * Try them in order and keep the first result that is recognisably an image.
187
- */
188
- async function downloadMedia(item, media, label) {
189
- const url = media.full_url?.trim() || `${CDN_BASE}/download?encrypted_query_param=${encodeURIComponent(media.encrypt_query_param ?? '')}`
190
- const res = await fetch(url)
191
- if (!res.ok) throw new Error(`${label} download ${res.status}`)
192
- const cipher = Buffer.from(await res.arrayBuffer())
193
- const rawPath = join(MEDIA_DIR, `${label}-${Date.now()}-cipher.bin`)
194
- writeFileSync(rawPath, cipher)
195
- const found = mediaKeyOf(item, media)
196
- log(`${label}: bytes=${cipher.length} key=${found?.source ?? 'none'} media.aes_key=${media.aes_key ? 'yes' : 'no'} head=${cipher.subarray(0, 16).toString('hex')}`)
197
- log(`${label} item=${short(JSON.stringify(item), 700)}`)
198
- const candidates = []
199
- if (found) {
200
- candidates.push({ name: 'ecb', run: () => aesDecrypt(cipher, found.key) })
201
- candidates.push({ name: 'cbc0', run: () => aesDecryptCbc(cipher, found.key, Buffer.alloc(16)) })
202
- if (cipher.length > 32) {
203
- candidates.push({ name: 'cbc-iv1', run: () => aesDecryptCbc(cipher.subarray(16), found.key, cipher.subarray(0, 16)) })
204
- }
205
- }
206
- candidates.push({ name: 'plain', run: () => cipher })
207
- for (const candidate of candidates) {
208
- try {
209
- const produced = candidate.run()
210
- // Some CDN responses are gzipped before encryption; unwrap before judging.
211
- const plain = produced[0] === 0x1f && produced[1] === 0x8b
212
- ? gunzipSync(produced)
213
- : produced
214
- if (looksLikeImage(plain) || looksLikeArchive(plain)) {
215
- const file = join(MEDIA_DIR, `${label}-${Date.now()}-${candidate.name}.bin`)
216
- writeFileSync(file, plain)
217
- log(`${label}: decoded via ${candidate.name} -> ${plain.length} bytes head=${plain.subarray(0, 8).toString('hex')}`)
218
- return { file, size: plain.length, cipherSize: cipher.length, via: candidate.name }
219
- }
220
- log(`${label}: ${candidate.name} -> ${plain.length} bytes, head=${plain.subarray(0, 8).toString('hex')} (not an image)`)
221
- } catch (error) {
222
- log(`${label}: ${candidate.name} failed: ${short(error.message, 90)}`)
223
- }
224
- }
225
- throw new Error(`${label}: no decode path produced an image (bytes=${cipher.length} head=${cipher.subarray(0, 16).toString('hex')}, raw saved ${rawPath})`)
226
- }
227
-
228
- async function uploadMedia(plain, { mediaType, fileName, toUserId }) {
229
- const rawsize = plain.length
230
- const rawfilemd5 = createHash('md5').update(plain).digest('hex')
231
- const filesize = paddedSize(rawsize)
232
- const filekey = randomBytes(16).toString('hex')
233
- const aeskey = randomBytes(16)
234
- const urlResponse = await api('ilink/bot/getuploadurl', {
235
- filekey,
236
- media_type: mediaType,
237
- to_user_id: toUserId,
238
- rawsize,
239
- rawfilemd5,
240
- filesize,
241
- no_need_thumb: true,
242
- aeskey: aeskey.toString('hex'),
243
- base_info: baseInfo(),
244
- })
245
- const uploadUrl = urlResponse.upload_full_url?.trim()
246
- || `${CDN_BASE}/upload?encrypted_query_param=${encodeURIComponent(urlResponse.upload_param)}&filekey=${encodeURIComponent(filekey)}`
247
- const cipher = aesEncrypt(plain, aeskey)
248
- const res = await fetch(uploadUrl, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: new Uint8Array(cipher) })
249
- if (res.status !== 200) {
250
- const detail = res.headers.get('x-error-message') ?? (await res.text().catch(() => ''))
251
- throw new Error(`upload ${res.status}: ${short(detail, 160)}`)
252
- }
253
- const downloadParam = res.headers.get('x-encrypted-param')
254
- if (!downloadParam) throw new Error('upload missing x-encrypted-param')
255
- return {
256
- filekey,
257
- aesKeyBase64: Buffer.from(aeskey.toString('hex')).toString('base64'),
258
- encryptQueryParam: downloadParam,
259
- cipherSize: filesize,
260
- size: rawsize,
261
- fileName,
262
- }
263
- }
264
-
265
- async function handleMessage(message) {
266
- const from = String(message.from_user_id ?? '')
267
- const contextToken = String(message.context_token ?? '')
268
- const runId = randomUUID()
269
- log(`MSG from=${from} id=${message.message_id ?? '?'} token=${contextToken ? 'yes' : 'no'} items=${(message.item_list ?? []).map((i) => i.type).join(',') || 'none'} session=${message.session_id ?? '?'}`)
270
- if (message.item_list?.length) log(`RAW items=${short(JSON.stringify(message.item_list), 400)}`)
271
-
272
- const typingStart = await typing(from, contextToken, 1)
273
- log(`TYPING start: ${typingStart.ok ? 'ok' : `failed (${typingStart.reason})`}`)
274
-
275
- try {
276
- const text = itemOf(message, 1)?.text_item?.text
277
- if (typeof text === 'string' && text.trim()) {
278
- log(`TEXT: ${short(text, 80)}`)
279
- const toolId = `probe-${Date.now()}`
280
- // Give the client a moment to render the tool chip before the answer
281
- // lands: everything in one burst is easy to miss.
282
- await sendItems(from, contextToken, [toolStart('probe_echo', toolId)], runId)
283
- await new Promise((resolve) => setTimeout(resolve, 900))
284
- await sendItems(from, contextToken, [textItem(`收到:${text.trim().slice(0, 500)}`)], runId)
285
- await new Promise((resolve) => setTimeout(resolve, 400))
286
- await sendItems(from, contextToken, [toolResult('probe_echo', toolId, 'completed')], runId)
287
- log('REPLY sent (tool start + text + tool result)')
288
- if (/img|图片/i.test(text)) {
289
- const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
290
- const uploaded = await uploadMedia(png, { mediaType: 1, fileName: 'probe.png', toUserId: from })
291
- await sendItems(from, contextToken, [{
292
- type: 2,
293
- image_item: {
294
- media: { encrypt_query_param: uploaded.encryptQueryParam, aes_key: uploaded.aesKeyBase64, encrypt_type: 1 },
295
- mid_size: uploaded.cipherSize,
296
- },
297
- }], runId)
298
- log(`IMAGE sent filekey=${uploaded.filekey} size=${uploaded.size}`)
299
- }
300
- }
301
-
302
- const image = itemOf(message, 2)?.image_item
303
- if (image?.media) {
304
- try {
305
- const got = await downloadMedia(image, image.media, 'image')
306
- log(`IMAGE received ${got.size} bytes (cipher ${got.cipherSize}) -> ${got.file}`)
307
- await sendItems(from, contextToken, [textItem(`收到图片:${got.size} 字节(密文 ${got.cipherSize} 字节)`)], runId)
308
- const uploaded = await uploadMedia(readFileSync(got.file), { mediaType: 1, fileName: 'echo.bin', toUserId: from })
309
- await sendItems(from, contextToken, [{
310
- type: 2,
311
- image_item: {
312
- media: { encrypt_query_param: uploaded.encryptQueryParam, aes_key: uploaded.aesKeyBase64, encrypt_type: 1 },
313
- mid_size: uploaded.cipherSize,
314
- },
315
- }], runId)
316
- log(`IMAGE echoed back filekey=${uploaded.filekey}`)
317
- } catch (error) {
318
- log(`IMAGE failed: ${short(error, 240)}`)
319
- await sendItems(from, contextToken, [textItem(`图片处理失败:${String(error).slice(0, 150)}`)], runId)
320
- }
321
- }
322
-
323
- const fileItem = itemOf(message, 4)?.file_item
324
- if (fileItem?.media) {
325
- try {
326
- const got = await downloadMedia(fileItem, fileItem.media, 'file')
327
- log(`FILE received name=${fileItem.file_name ?? '?'} ${got.size} bytes (cipher ${got.cipherSize}) -> ${got.file}`)
328
- await sendItems(from, contextToken, [textItem(`收到文件:${fileItem.file_name ?? 'file'},${got.size} 字节`)], runId)
329
- const uploaded = await uploadMedia(readFileSync(got.file), { mediaType: 3, fileName: fileItem.file_name || 'echo.bin', toUserId: from })
330
- await sendItems(from, contextToken, [{
331
- type: 4,
332
- file_item: {
333
- media: { encrypt_query_param: uploaded.encryptQueryParam, aes_key: uploaded.aesKeyBase64, encrypt_type: 1 },
334
- file_name: fileItem.file_name || 'echo.bin',
335
- len: String(uploaded.size),
336
- },
337
- }], runId)
338
- log(`FILE echoed back filekey=${uploaded.filekey}`)
339
- } catch (error) {
340
- log(`FILE failed: ${short(error, 240)}`)
341
- await sendItems(from, contextToken, [textItem(`文件处理失败:${String(error).slice(0, 150)}`)], runId)
342
- }
343
- }
344
- } finally {
345
- const typingStop = await typing(from, contextToken, 2)
346
- log(`TYPING stop: ${typingStop.ok ? 'ok' : `failed (${typingStop.reason})`}`)
347
- }
348
- }
349
-
350
- async function main() {
351
- log(`probe start account=${cred.accountId} base=${BASE}`)
352
- let cursor = ''
353
- for (;;) {
354
- let response
355
- try {
356
- response = await api('ilink/bot/getupdates', { get_updates_buf: cursor ?? '', base_info: baseInfo() }, POLL_MS)
357
- } catch (error) {
358
- if (error?.name === 'AbortError') continue
359
- log(`POLL error: ${short(error, 200)}`)
360
- await new Promise((resolve) => setTimeout(resolve, 2_000))
361
- continue
362
- }
363
- if (response.ret && response.ret !== 0) {
364
- log(`POLL ret=${response.ret} ${short(response.errmsg ?? '', 120)}`)
365
- if (response.ret === -14) { log('SESSION_TIMEOUT: run scripts/wechat-login.mjs again'); return }
366
- await new Promise((resolve) => setTimeout(resolve, 3_000))
367
- continue
368
- }
369
- if (response.get_updates_buf) cursor = response.get_updates_buf
370
- const messages = Array.isArray(response.msgs) ? response.msgs : []
371
- if (messages.length === 0) continue
372
- log(`BATCH ${messages.length} message(s)`)
373
- for (const message of messages) {
374
- try {
375
- await handleMessage(message)
376
- } catch (error) {
377
- log(`HANDLE error: ${short(error, 300)}`)
378
- }
379
- }
380
- }
381
- }
382
-
383
- main().catch((error) => {
384
- log(`FATAL ${short(error, 400)}`)
385
- process.exitCode = 1
386
- })
@@ -1,84 +0,0 @@
1
- /**
2
- * Streaming probe v2: does the WeChat client repaint one bubble when several
3
- * `sendmessage` frames share a `client_id` and move GENERATING(1) → FINISH(2)?
4
- *
5
- * The probe waits for a fresh context token: iLink rejects a send without one
6
- * ("prepare failed"), and only an inbound message issues a token.
7
- *
8
- * Run: node scripts/wechat-stream-probe.mjs
9
- */
10
- import { readFileSync } from 'node:fs'
11
- import { homedir } from 'node:os'
12
- import { join } from 'node:path'
13
- import { randomUUID, randomBytes } from 'node:crypto'
14
-
15
- const HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
16
- const cred = JSON.parse(readFileSync(join(HOME, 'wechat-channel.json'), 'utf8'))
17
- const BASE = String(cred.baseUrl || 'https://ilinkai.weixin.qq.com').replace(/\/$/, '')
18
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
19
-
20
- const readTokens = () => {
21
- try { return JSON.parse(readFileSync(join(HOME, 'wechat-context-tokens.json'), 'utf8')) } catch { return {} }
22
- }
23
-
24
- let [userId, contextToken] = Object.entries(readTokens()).at(-1) ?? []
25
- if (!userId || !contextToken) {
26
- console.log('WAITING_FOR_TOKEN: 请在微信里给机器人发一条消息(任意内容),探针会自动继续…')
27
- const deadline = Date.now() + 5 * 60_000
28
- while (Date.now() < deadline) {
29
- await sleep(1_000)
30
- ;[userId, contextToken] = Object.entries(readTokens()).at(-1) ?? []
31
- if (userId && contextToken) break
32
- }
33
- }
34
- if (!userId || !contextToken) {
35
- console.log('NO_TOKEN: 5 分钟内没有收到新消息,探针退出')
36
- process.exit(1)
37
- }
38
- console.log('token ready for', userId)
39
-
40
- const encodeVersion = (version) => {
41
- const [major = 0, minor = 0, patch = 0] = String(version).split('.').map((part) => parseInt(part, 10) || 0)
42
- return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff)
43
- }
44
- const headers = {
45
- 'Content-Type': 'application/json',
46
- AuthorizationType: 'ilink_bot_token',
47
- 'X-WECHAT-UIN': Buffer.from(String(randomBytes(4).readUInt32BE(0))).toString('base64'),
48
- 'iLink-App-Id': 'bot',
49
- 'iLink-App-ClientVersion': String(encodeVersion('2.4.10')),
50
- Authorization: `Bearer ${cred.botToken}`,
51
- }
52
-
53
- async function send(clientId, state, text) {
54
- const res = await fetch(`${BASE}/ilink/bot/sendmessage`, {
55
- method: 'POST',
56
- headers,
57
- body: JSON.stringify({
58
- msg: {
59
- from_user_id: '',
60
- to_user_id: userId,
61
- client_id: clientId,
62
- message_type: 2,
63
- message_state: state,
64
- item_list: [{ type: 1, text_item: { text } }],
65
- context_token: contextToken,
66
- },
67
- base_info: { channel_version: '2.4.10', bot_agent: 'DSH/0.1' },
68
- }),
69
- })
70
- const body = await res.text()
71
- console.log(`state=${state} chars=${text.length} http=${res.status} ${body.slice(0, 120)}`)
72
- return body
73
- }
74
-
75
- const clientId = `dsh-stream-probe-${randomUUID()}`
76
- console.log('开始:先发【第 1 版】,5 秒后发【第 2 版】… 请盯着那条气泡看 15 秒')
77
- await send(clientId, 1, '【第 1 版】请盯着这条气泡看 15 秒。')
78
- await sleep(5_000)
79
- await send(clientId, 1, '【第 1 版】请盯着这条气泡看 15 秒。\n【第 2 版】现在应该多出这一行。')
80
- await sleep(5_000)
81
- await send(clientId, 1, '【第 1 版】请盯着这条气泡看 15 秒。\n【第 2 版】现在应该多出这一行。\n【第 3 版】又多了这一行。')
82
- await sleep(5_000)
83
- await send(clientId, 2, '【完成】如果第 1→2→3 版是在同一条气泡里依次出现的,说明支持真流式;如果直到这一帧才一起出现,说明客户端只在 FINISH 时渲染。')
84
- console.log('probe done; clientId =', clientId)
@@ -1,69 +0,0 @@
1
- /**
2
- * Streaming probe v3: is the update keyed by the SERVER message id?
3
- *
4
- * v2 showed the server returns a *different* message_id for every frame, even
5
- * with the same client_id. So the next hypothesis is `msg.message_id`: create
6
- * the bubble once, then keep sending with its id.
7
- *
8
- * Run: node scripts/wechat-stream-probe3.mjs
9
- */
10
- import { readFileSync } from 'node:fs'
11
- import { homedir } from 'node:os'
12
- import { join } from 'node:path'
13
- import { randomUUID, randomBytes } from 'node:crypto'
14
-
15
- const HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
16
- const cred = JSON.parse(readFileSync(join(HOME, 'wechat-channel.json'), 'utf8'))
17
- const BASE = String(cred.baseUrl || 'https://ilinkai.weixin.qq.com').replace(/\/$/, '')
18
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
19
- const tokens = JSON.parse(readFileSync(join(HOME, 'wechat-context-tokens.json'), 'utf8'))
20
- const [userId, contextToken] = Object.entries(tokens).at(-1) ?? []
21
- if (!userId || !contextToken) {
22
- console.log('NO_TOKEN: send the bot a message first')
23
- process.exit(1)
24
- }
25
-
26
- const encodeVersion = (version) => {
27
- const [major = 0, minor = 0, patch = 0] = String(version).split('.').map((part) => parseInt(part, 10) || 0)
28
- return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff)
29
- }
30
- const headers = {
31
- 'Content-Type': 'application/json',
32
- AuthorizationType: 'ilink_bot_token',
33
- 'X-WECHAT-UIN': Buffer.from(String(randomBytes(4).readUInt32BE(0))).toString('base64'),
34
- 'iLink-App-Id': 'bot',
35
- 'iLink-App-ClientVersion': String(encodeVersion('2.4.10')),
36
- Authorization: `Bearer ${cred.botToken}`,
37
- }
38
-
39
- async function send({ clientId, state, text, messageId }) {
40
- const msg = {
41
- from_user_id: '',
42
- to_user_id: userId,
43
- client_id: clientId,
44
- message_type: 2,
45
- message_state: state,
46
- item_list: [{ type: 1, text_item: { text } }],
47
- context_token: contextToken,
48
- }
49
- if (messageId) msg.message_id = messageId
50
- const res = await fetch(`${BASE}/ilink/bot/sendmessage`, {
51
- method: 'POST',
52
- headers,
53
- body: JSON.stringify({ msg, base_info: { channel_version: '2.4.10', bot_agent: 'DSH/0.1' } }),
54
- })
55
- const text2 = await res.text()
56
- let parsed = {}
57
- try { parsed = JSON.parse(text2) } catch { /* ignore */ }
58
- console.log(`state=${state} sentId=${messageId ?? '-'} -> http=${res.status} message_id=${parsed.message_id ?? '-'} ${text2.slice(0, 90)}`)
59
- return parsed.message_id
60
- }
61
-
62
- const clientId = `dsh-stream-probe-${randomUUID()}`
63
- console.log('实验:第 1 帧创建气泡,拿到 message_id 后,第 2/3 帧带同一个 message_id 更新')
64
- const firstId = await send({ clientId, state: 1, text: '【A】这是第一条。' })
65
- await sleep(4_000)
66
- const secondId = await send({ clientId, state: 1, text: '【A】这是第一条。\n【B】带 message_id 的第二次发送。', messageId: firstId })
67
- await sleep(4_000)
68
- await send({ clientId, state: 2, text: '【A】这是第一条。\n【B】带 message_id 的第二次发送。\n【C】完成。', messageId: secondId ?? firstId })
69
- console.log('done. firstId=', firstId, 'secondId=', secondId)