dsh-channel-feishu 0.9.0 → 0.9.1

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/README.md CHANGED
@@ -82,7 +82,7 @@ dsh plugin add dsh-channel-feishu
82
82
 
83
83
  ```bash
84
84
  dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu
85
- dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu/releases/download/v0.9.0/dsh-channel-feishu-0.9.0.tgz
85
+ dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu/releases/download/v0.9.1/dsh-channel-feishu-0.9.1.tgz
86
86
  ```
87
87
 
88
88
  依赖必须用扁平结构装(非 ASCII 目录下 pnpm 的软链会把路径写坏):
package/cordis.patch.yml CHANGED
@@ -9,9 +9,10 @@
9
9
  provider: feishu
10
10
  # Register the tools at all.
11
11
  enabled: true
12
- # Long connection + inbound delivery. Off by default: an unattended
13
- # channel should be an explicit choice.
14
- inboundEnabled: false
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 (feishu_send_message/file).
15
+ inboundEnabled: true
15
16
  # Session inbound messages go to; `create` makes it when missing.
16
17
  sessionId: ''
17
18
  sessionMode: resume
package/index.js CHANGED
@@ -89,6 +89,7 @@ export const Config = z.object({
89
89
  appSecret: z.string().default('').description('Optional app secret; prefer the credentials store or credentials file.'),
90
90
  defaultChatId: z.string().default('').description('Destination used when a tool call omits receiveId.'),
91
91
  logFile: z.string().default('').description('Inbound diagnostics log path.'),
92
+ readyNotice: z.boolean().default(true).description('Send one "channel ready" message to the default chat after the inbound long connection comes up.'),
92
93
  logLevel: z.union([z.const('debug'), z.const('info'), z.const('warn'), z.const('error')])
93
94
  .default('info')
94
95
  .description('Minimum severity written to the diagnostics log.'),
@@ -1090,6 +1091,33 @@ const sendFileTool = (config) => ({
1090
1091
  },
1091
1092
  })
1092
1093
 
1094
+ /**
1095
+ * What the operator (or another agent) should do next, derived from live state.
1096
+ * Installing used to be trial and error; the tool now names the missing step.
1097
+ */
1098
+ function nextStepsOf(config, result, inbound) {
1099
+ const steps = []
1100
+ if (!result?.configured) {
1101
+ steps.push(
1102
+ `写凭据:把 appId / appSecret 放进 ${credentialsFilePath()}(UTF-8 无 BOM),`
1103
+ + '或设环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET',
1104
+ )
1105
+ }
1106
+ if (result?.configured && !result?.tokenOk) {
1107
+ steps.push('取 token 失败:核对 appId / appSecret、region(国际版用 lark),确认应用已发布并开通机器人能力')
1108
+ }
1109
+ if (config?.enabled !== false && config?.inboundEnabled !== true) {
1110
+ steps.push('入站未开启:在 profile 的 cordis.patch.yml 给 feishu-channel 行设 inboundEnabled: true,然后重启 DSH')
1111
+ }
1112
+ if (config?.inboundEnabled === true && !inbound?.ready) {
1113
+ steps.push('入站长连接未就绪:确认没有另一个飞书插件用同一个 App 在连接(会互相抢事件),然后重启 DSH')
1114
+ }
1115
+ if (!String(result?.defaultChatId ?? '').trim()) {
1116
+ steps.push('没有默认会话:把 defaultChatId(oc_ 开头)写进凭据文件,或在行 config 里设置')
1117
+ }
1118
+ return steps
1119
+ }
1120
+
1093
1121
  const statusTool = (config) => ({
1094
1122
  name: 'feishu_channel_status',
1095
1123
  description:
@@ -1124,13 +1152,18 @@ const statusTool = (config) => ({
1124
1152
  flushRan: { type: 'number' },
1125
1153
  streamShape: { type: 'string' },
1126
1154
  error: { type: 'string' },
1155
+ version: { type: 'string' },
1156
+ nextSteps: { type: 'array', items: { type: 'string' } },
1127
1157
  },
1128
1158
  required: ['configured', 'tokenOk'],
1129
1159
  additionalProperties: true,
1130
1160
  },
1131
1161
  render(_args, value) {
1162
+ const steps = Array.isArray(value?.nextSteps) && value.nextSteps.length > 0
1163
+ ? `\n下一步:\n${value.nextSteps.map((step, index) => `${index + 1}. ${step}`).join('\n')}`
1164
+ : ''
1132
1165
  if (!value?.configured) {
1133
- return [{ type: 'text', text: `飞书通道未配置。${value?.error ?? ''}`.trim() }]
1166
+ return [{ type: 'text', text: `飞书通道未配置。${value?.error ?? ''}`.trim() + steps }]
1134
1167
  }
1135
1168
  const head = value.tokenOk
1136
1169
  ? '飞书通道已配置,tenant_access_token 获取成功。'
@@ -1154,14 +1187,18 @@ const statusTool = (config) => ({
1154
1187
  + (value.streamShape ? `\n首帧结构=${value.streamShape}` : '')
1155
1188
  + `\n观察:不符=${value.observeMismatch ?? 0} 无帧=${value.observeNoFrame ?? 0}`
1156
1189
  + ` start=${value.observeStart ?? 0} end=${value.observeEnd ?? 0} chunk=${value.observeChunk ?? 0}`
1157
- + (value.lastObserve ? `\n最近=${value.lastObserve}` : ''),
1190
+ + (value.lastObserve ? `\n最近=${value.lastObserve}` : '')
1191
+ + `\n版本=${value.version || '(unknown)'}`
1192
+ + (Array.isArray(value.nextSteps) && value.nextSteps.length > 0
1193
+ ? `\n下一步:\n${value.nextSteps.map((step, index) => `${index + 1}. ${step}`).join('\n')}`
1194
+ : ''),
1158
1195
  }]
1159
1196
  },
1160
1197
  },
1161
1198
  async execute(_args, exec) {
1162
1199
  const inbound = inboundSnapshot()
1163
1200
  const result = await provider().checkStatus(exec?.signal)
1164
- return {
1201
+ const state = {
1165
1202
  ...result,
1166
1203
  autoReply: config.autoReply !== false,
1167
1204
  streamingCards: config.streamingCards !== false,
@@ -1189,7 +1226,9 @@ const statusTool = (config) => ({
1189
1226
  observeStart: observeStats.start,
1190
1227
  observeEnd: observeStats.end,
1191
1228
  observeChunk: observeStats.chunk,
1229
+ version: PLUGIN_VERSION,
1192
1230
  }
1231
+ return { ...state, nextSteps: nextStepsOf(config, state, inbound) }
1193
1232
  },
1194
1233
  })
1195
1234
 
@@ -1426,6 +1465,42 @@ function setInboundState(config, next) {
1426
1465
  logInbound(config, { event: 'channel', ...next })
1427
1466
  }
1428
1467
 
1468
+ /** Version of the running package, shown in the status tool and the ready notice. */
1469
+ const PLUGIN_VERSION = (() => {
1470
+ try {
1471
+ return String(JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '')
1472
+ } catch {
1473
+ return ''
1474
+ }
1475
+ })()
1476
+
1477
+ let readyAnnounced = false
1478
+
1479
+ /**
1480
+ * One "channel ready" message per process.
1481
+ *
1482
+ * Installing the plugin used to end with a manual test round trip; this hands the
1483
+ * first proof of life straight to the chat that configured `defaultChatId`.
1484
+ */
1485
+ async function announceReady(config) {
1486
+ if (readyAnnounced) return
1487
+ readyAnnounced = true
1488
+ if (config?.readyNotice === false) return
1489
+ try {
1490
+ const chatId = String(provider().settings().defaultChatId ?? '').trim()
1491
+ if (!chatId) return
1492
+ const session = String(config?.sessionId ?? '').trim()
1493
+ await provider().sendText({
1494
+ chatId,
1495
+ text: `✅ 飞书通道已就绪\n插件 dsh-channel-feishu v${PLUGIN_VERSION || '(unknown)'}\n`
1496
+ + `入站长连接正常,接收会话=${session || '按消息新建'}`,
1497
+ })
1498
+ logInbound(config, { event: 'channel', result: 'ready-notice', chatId })
1499
+ } catch (error) {
1500
+ logInbound(config, { event: 'channel', result: 'ready-notice-failed', reason: errorText(error) })
1501
+ }
1502
+ }
1503
+
1429
1504
  const errorText = (error) => (error instanceof Error ? error.message : String(error))
1430
1505
 
1431
1506
  /** Inbound diagnostics land next to the credentials unless `logFile` says otherwise. */
@@ -2966,8 +3041,10 @@ function startInbound(ctx, config) {
2966
3041
  onCardAction: async (data) => await handleQuestionCardAction(scoped, config, data),
2967
3042
  onState: ({ ready, error }) => {
2968
3043
  setInboundState(config, { ready: Boolean(ready), transport: 'websocket', error: String(error ?? '') })
2969
- if (ready) warnTo(scoped, 'inbound long connection ready')
2970
- else if (error && error !== 'closed') warnTo(scoped, `inbound connection problem: ${error}`)
3044
+ if (ready) {
3045
+ warnTo(scoped, 'inbound long connection ready')
3046
+ void announceReady(config)
3047
+ } else if (error && error !== 'closed') warnTo(scoped, `inbound connection problem: ${error}`)
2971
3048
  },
2972
3049
  })
2973
3050
  if (disposed) {
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-channel-feishu",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "type": "module",
5
- "description": "Feishu/Lark (飞书) channel for DeepSeek Harness: a chat bound to a DSH session, with streaming cards and attachments.",
5
+ "description": "Feishu/Lark (椋炰功) channel for DeepSeek Harness: a chat bound to a DSH session, with streaming cards and attachments.",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -41,6 +41,7 @@
41
41
  "AGENTS.md",
42
42
  "locale",
43
43
  "docs",
44
+ "scripts",
44
45
  "icon.svg",
45
46
  "LICENSE"
46
47
  ],
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * One-command credential setup for dsh-channel-feishu.
4
+ *
5
+ * The only manual step left after `dsh plugin add` is teaching the plugin the
6
+ * Feishu app credentials. Doing that by hand invites two mistakes: a UTF-8 BOM
7
+ * in the JSON file (the plugin then fails to load) and a wrong region. This
8
+ * script finds the credentials that another Feishu channel already uses, writes
9
+ * the file correctly, and verifies them against the Feishu API.
10
+ *
11
+ * Usage:
12
+ * node scripts/setup.mjs # scan, write, verify
13
+ * node scripts/setup.mjs --dry-run # scan and verify only
14
+ * node scripts/setup.mjs --region lark # international tenant
15
+ * node scripts/setup.mjs --app-id X --app-secret Y
16
+ */
17
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { dirname, join } from 'node:path'
20
+
21
+ const argv = process.argv.slice(2)
22
+ const has = (flag) => argv.includes(flag)
23
+ const valueOf = (flag) => {
24
+ const at = argv.indexOf(flag)
25
+ return at >= 0 ? String(argv[at + 1] ?? '') : ''
26
+ }
27
+
28
+ const dryRun = has('--dry-run')
29
+ const HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
30
+ const target = join(HOME, 'feishu-channel.json')
31
+ const say = (...args) => console.log(...args)
32
+
33
+ const mask = (value) => {
34
+ const text = String(value ?? '')
35
+ if (text.length <= 8) return text ? '****' : ''
36
+ return `${text.slice(0, 6)}…${text.slice(-4)}(${text.length} 字符)`
37
+ }
38
+
39
+ /** Read every small text file under the DSH home, skipping noise. */
40
+ function candidateFiles() {
41
+ const skip = new Set(['sessions', 'node_modules', 'attachments', 'feishu-inbound-files', '.git'])
42
+ const found = []
43
+ const walk = (dir, depth) => {
44
+ if (depth > 3) return
45
+ let entries
46
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
47
+ for (const entry of entries) {
48
+ const path = join(dir, entry.name)
49
+ if (entry.isDirectory()) {
50
+ if (skip.has(entry.name)) continue
51
+ walk(path, depth + 1)
52
+ continue
53
+ }
54
+ if (!/\.(json|ya?ml|env)$/i.test(entry.name)) continue
55
+ try {
56
+ if (statSync(path).size > 512 * 1024) continue
57
+ } catch { continue }
58
+ found.push(path)
59
+ }
60
+ }
61
+ walk(HOME, 0)
62
+ return found
63
+ }
64
+
65
+ const pick = (text, key) => {
66
+ const match = text.match(new RegExp(`["']?${key}["']?\\s*[:=]\\s*["']?([A-Za-z0-9_-]{6,})`, 'i'))
67
+ return match ? match[1] : ''
68
+ }
69
+
70
+ function scan() {
71
+ const fromEnv = {
72
+ appId: String(process.env.FEISHU_APP_ID ?? '').trim(),
73
+ appSecret: String(process.env.FEISHU_APP_SECRET ?? '').trim(),
74
+ source: 'environment',
75
+ }
76
+ if (fromEnv.appId && fromEnv.appSecret) return fromEnv
77
+
78
+ if (existsSync(target)) {
79
+ try {
80
+ const existing = JSON.parse(readFileSync(target, 'utf8'))
81
+ if (existing.appId && existing.appSecret) {
82
+ return { ...existing, source: target }
83
+ }
84
+ } catch { /* unreadable: fall through to the scan */ }
85
+ }
86
+
87
+ for (const path of candidateFiles()) {
88
+ let text
89
+ try { text = readFileSync(path, 'utf8') } catch { continue }
90
+ const appId = pick(text, 'appId') || pick(text, 'FEISHU_APP_ID') || pick(text, 'app_id')
91
+ const appSecret = pick(text, 'appSecret') || pick(text, 'FEISHU_APP_SECRET') || pick(text, 'app_secret')
92
+ if (!appId || !appSecret) continue
93
+ const region = /(?:region|lark)/i.test(text) && /lark/i.test(text) ? 'lark' : 'feishu'
94
+ const chat = pick(text, 'defaultChatId') || pick(text, 'chat_id')
95
+ return { appId, appSecret, region, defaultChatId: chat, source: path }
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ async function verify({ appId, appSecret, region }) {
101
+ const base = region === 'lark' ? 'https://open.larksuite.com' : 'https://open.feishu.cn'
102
+ try {
103
+ const response = await fetch(`${base}/open-apis/auth/v3/tenant_access_token/internal`, {
104
+ method: 'POST',
105
+ headers: { 'content-type': 'application/json; charset=utf-8' },
106
+ body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
107
+ })
108
+ const payload = await response.json().catch(() => undefined)
109
+ if (payload?.code === 0 && payload?.tenant_access_token) return { ok: true }
110
+ return { ok: false, reason: `code=${payload?.code ?? '?'} msg=${payload?.msg ?? response.status}` }
111
+ } catch (error) {
112
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) }
113
+ }
114
+ }
115
+
116
+ const explicitId = valueOf('--app-id')
117
+ const explicitSecret = valueOf('--app-secret')
118
+ const found = explicitId && explicitSecret
119
+ ? { appId: explicitId, appSecret: explicitSecret, source: 'command line' }
120
+ : scan()
121
+
122
+ if (!found) {
123
+ say('没找到飞书应用凭据。请二选一:')
124
+ say(` 1. 写 ${target}:{"appId":"…","appSecret":"…","region":"feishu","defaultChatId":"oc_…"}`)
125
+ say(' 2. 设置环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET')
126
+ say('提示:Windows 上用 PowerShell 5.1 的 Set-Content -Encoding UTF8 会写入 BOM,插件会加载失败。')
127
+ process.exit(1)
128
+ }
129
+
130
+ const region = valueOf('--region') || String(found.region ?? '').trim() || 'feishu'
131
+ say(`来源: ${found.source}`)
132
+ say(`appId: ${mask(found.appId)}`)
133
+ say(`appSecret: ${mask(found.appSecret)}`)
134
+ say(`region: ${region}`)
135
+
136
+ const check = await verify({ appId: found.appId, appSecret: found.appSecret, region })
137
+ say(`凭据校验: ${check.ok ? '通过(tenant_access_token 获取成功)' : `失败(${check.reason})`}`)
138
+
139
+ if (dryRun) {
140
+ say('dry run:未写入任何文件。')
141
+ process.exit(check.ok ? 0 : 1)
142
+ }
143
+ if (!check.ok) {
144
+ say('凭据未通过校验,不写入。核对 appId / appSecret / region 后重试。')
145
+ process.exit(1)
146
+ }
147
+
148
+ const payload = {
149
+ appId: found.appId,
150
+ appSecret: found.appSecret,
151
+ region,
152
+ ...(String(found.defaultChatId ?? '').trim() ? { defaultChatId: String(found.defaultChatId).trim() } : {}),
153
+ }
154
+ mkdirSync(dirname(target), { recursive: true })
155
+ // UTF-8 without BOM: a BOM makes the plugin's JSON.parse fail at load time.
156
+ writeFileSync(target, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
157
+ say(`已写入 ${target}(UTF-8 无 BOM,仅当前用户可读)`)
158
+ say('')
159
+ say('下一步:')
160
+ say(' 1. 如有别的飞书插件用同一个 App,先在 profile 的 cordis.patch.yml 里给它加 disabled: true')
161
+ say(' 2. 完全退出 DSH 再打开(关窗口只是隐藏)')
162
+ say(' 3. 打开后机器人会发一条「飞书通道已就绪」,也可以调 feishu_channel_status 确认')