dsh-feishu-lark-notify 0.25.2 → 0.26.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/README.md CHANGED
@@ -211,6 +211,25 @@ Feishu is not only an input channel — it can intervene:
211
211
  Stop uses the host's `agent.cancel({ kind: 'user' })`, identical to pressing stop in the UI, and only
212
212
  acts on **running** sessions (a stop command never wakes a dormant one).
213
213
 
214
+ ### Create a session
215
+
216
+ You can open a new session from Feishu, without touching the computer:
217
+
218
+ ```
219
+ 新建 → open a fresh session
220
+ 新建 前端日报 → open one and remember the title "前端日报"
221
+ 新建 实验台 跑一下冒烟 → open it and deliver the first command right away
222
+ ```
223
+
224
+ Reply: `🆕 已创建「实验台」(#a1b2),第一条指令已投进去`; afterwards `@实验台 …` reaches it directly.
225
+
226
+ | Detail | Notes |
227
+ |---|---|
228
+ | Model | Borrowed from a **running** session's `agent.options`, so `{{model}}` is never empty |
229
+ | Directory | The current project's directory |
230
+ | Requires | Host support for `agents.create()`; older hosts reply "not supported" instead of failing oddly |
231
+ | Errors | The host's message is echoed back and recorded as the last failure |
232
+
214
233
  **② Send `列表` (list) to get numbers**
215
234
 
216
235
  ```
package/README.zh.md CHANGED
@@ -207,6 +207,26 @@ DSH 里同时开着一堆会话时,飞书里发一句话默认只交给「当
207
207
  停止走的是宿主的 `agent.cancel({ kind: 'user' })`,和你在界面上按停止等价;
208
208
  只对**正在运行**的会话有效(不会为了一句「停止」把休眠会话唤醒)。
209
209
 
210
+ ### 新建会话
211
+
212
+ 飞书里也能**开新会话**,不用跑回电脑:
213
+
214
+ ```
215
+ 新建 → 开一个新会话
216
+ 新建 前端日报 → 开一个,并记下标题「前端日报」
217
+ 新建 实验台 跑一下冒烟 → 建完直接把第一条指令投进去
218
+ ```
219
+
220
+ 回执:`🆕 已创建「实验台」(#a1b2),第一条指令已投进去`,之后可以直接
221
+ `@实验台 内容`(标题在你没有额外设置时由模型生成,之前用你给的这个名字)。
222
+
223
+ | 说明 | 细节 |
224
+ |---|---|
225
+ | 模型 | 借用**当前运行中的会话**的模型配置(`agent.options`),不会出现 `{{model}}` 为空 |
226
+ | 目录 | 用当前项目的目录 |
227
+ | 前提 | 宿主支持 `agents.create()`;老版本会直接回「不支持新建会话」 |
228
+ | 失败 | 原样回宿主错误,并记进「最近一次失败」 |
229
+
210
230
  **② 发「列表」拿编号**
211
231
 
212
232
  ```
package/lib/index.js CHANGED
@@ -26,7 +26,7 @@ import { resolvePatchPath, writePatchRow } from './persist.js'
26
26
  import { loadEnvSources, applyEnv, renderEnvTemplate, resolveHome } from './env.js'
27
27
  import { listBotChats, getBotChat, listChatMembers, loadChatStore, saveChatStore, rememberChat, describeChatsError } from './chats.js'
28
28
  import { listSessionIndex, readArchivedIds, readWorkspaces, readSessionModel, normalizeSessionId } from './session-index.js'
29
- import { parseRoute, parseAtCommand, parseControl, matchByLabel, formatSessionList, formatStatus, formatHelp, createSessionRoster } from './session-router.js'
29
+ import { parseRoute, parseAtCommand, parseControl, parseCreate, matchByLabel, formatSessionList, formatStatus, formatCreated, formatHelp, createSessionRoster } from './session-router.js'
30
30
  import { appendLogLine } from './logfile.js'
31
31
  import { createLiveness, describeLiveness } from './liveness.js'
32
32
  import { verifyAfterSave, inspectPatch } from './patch-guard.js'
@@ -37,7 +37,7 @@ import { startWsInbound } from './inbound-ws.js'
37
37
  export const name = 'feishu-notify'
38
38
 
39
39
  /** 版本号(与 package.json 保持一致,单测会校验)。 */
40
- export const VERSION = '0.25.2'
40
+ export const VERSION = '0.26.0'
41
41
 
42
42
  /** 内存日志上限。 */
43
43
  const LOG_LIMIT = 200
@@ -98,6 +98,8 @@ export function apply(ctx, rawConfig) {
98
98
  let lastRoutedSessionId = ''
99
99
  /** 最近一次投递的时间(状态 里显示「几分钟前」)。 */
100
100
  let lastRoutedAt = 0
101
+ /** 飞书里「新建」时定的标题:模型还没生成标题前,路由按它找 */
102
+ const createdTitles = new Map()
101
103
  /** 存活探针:定时探一次飞书 API,把断线暴露出来。 */
102
104
  let liveness
103
105
 
@@ -1619,6 +1621,8 @@ export function apply(ctx, rawConfig) {
1619
1621
  }
1620
1622
  const state = states.get(id)
1621
1623
  if (typeof state?.lastUser === 'string' && state.lastUser.trim() !== '') return clip(state.lastUser.trim(), 30)
1624
+ // 飞书里「新建」时给的名字:模型还没生成标题前先顶用
1625
+ if (createdTitles.has(id)) return clip(createdTitles.get(id), 40)
1622
1626
  return ''
1623
1627
  }
1624
1628
 
@@ -1908,6 +1912,113 @@ export function apply(ctx, rawConfig) {
1908
1912
  return { ok: true, path: filePath, prompt, kindLabel }
1909
1913
  }
1910
1914
 
1915
+ /**
1916
+ * 新建会话时借一个模型配置。
1917
+ *
1918
+ * 优先用宿主给活会话的 `agent.options`(最准,不读磁盘),
1919
+ * 再退回会话索引里的 `modelSelection.lastUsed`,最后借其它活会话的。
1920
+ * @param agent - 借用的活会话。
1921
+ * @returns `{ provider, model, reasoningEffort? }` 或 undefined。
1922
+ */
1923
+ function modelForCreate(agent) {
1924
+ const options = agent?.options
1925
+ if (typeof options?.provider === 'string' && options.provider !== ''
1926
+ && typeof options?.model === 'string' && options.model !== '') {
1927
+ return {
1928
+ provider: options.provider,
1929
+ model: options.model,
1930
+ ...(typeof options.reasoningEffort === 'string' ? { reasoningEffort: options.reasoningEffort } : {}),
1931
+ }
1932
+ }
1933
+ const fromIndex = sessionModelFor(agent?.id ?? '')
1934
+ if (fromIndex !== undefined) return fromIndex
1935
+ for (const item of liveSessions()) {
1936
+ if (item.id === agent?.id) continue
1937
+ const other = sessionModelFor(item.id)
1938
+ if (other !== undefined) return other
1939
+ }
1940
+ return undefined
1941
+ }
1942
+
1943
+ /**
1944
+ * 新建一个会话(`新建 [标题] [指令]`)。
1945
+ *
1946
+ * 宿主签名:`agents.create({ agentOptions, meta: { cwd } })` → `AgentHandle { agent, dispose }`。
1947
+ * handle 必须留着,否则会被回收;模型用「当前运行中会话」的,避免又踩 `{{model}}` 为空。
1948
+ * @param options - title / text / message / via。
1949
+ * @returns 结构化结果。
1950
+ */
1951
+ async function createSession({ title, text, message, via }) {
1952
+ const agents = ctx.get('agents')
1953
+ if (agents === undefined || typeof agents.create !== 'function') {
1954
+ void replyToChat(message.chatId, '这个宿主版本不支持新建会话(没有 agents.create)。')
1955
+ return { ok: false, created: false, reason: 'unsupported' }
1956
+ }
1957
+ // 借一个「活着的」agent 来取模型配置(liveSessions() 是投影对象,没有 options)
1958
+ const anchorAgent = (() => {
1959
+ try {
1960
+ const roots = ctx.get('agents')?.roots?.() ?? []
1961
+ return Array.isArray(roots) ? roots[0] : undefined
1962
+ } catch {
1963
+ return undefined
1964
+ }
1965
+ })()
1966
+ if (anchorAgent === undefined) {
1967
+ void replyToChat(message.chatId, '现在没有运行中的会话可以借用模型配置,先在 DSH 里打开一个再试。')
1968
+ return { ok: false, created: false, reason: 'no-model-anchor' }
1969
+ }
1970
+ const anchor = { label: sessionLabel(anchorAgent), id: anchorAgent.id }
1971
+ const model = modelForCreate(anchorAgent)
1972
+ if (model === undefined) {
1973
+ void replyToChat(message.chatId, `借不到模型配置(${anchor.label || anchor.id.slice(-6)} 没有 modelSelection),先在 DSH 里给它选个模型。`)
1974
+ return { ok: false, created: false, reason: 'no-model' }
1975
+ }
1976
+
1977
+ let handle
1978
+ try {
1979
+ handle = await agents.create({
1980
+ agentOptions: {
1981
+ provider: model.provider,
1982
+ model: model.model,
1983
+ ...(model.reasoningEffort === undefined ? {} : { reasoningEffort: model.reasoningEffort }),
1984
+ },
1985
+ meta: { cwd: projectRoot() },
1986
+ })
1987
+ } catch (error) {
1988
+ const detail = String(error?.message ?? error)
1989
+ log(`[${via}] 新建会话失败:${detail}`)
1990
+ noteFailure('新建会话', detail)
1991
+ void replyToChat(message.chatId, `❌ 新建失败:${detail}`)
1992
+ return { ok: false, created: false, error: detail }
1993
+ }
1994
+
1995
+ const agent = handle?.agent
1996
+ if (agent === undefined || agent === null) {
1997
+ void replyToChat(message.chatId, '宿主返回了空 handle,新建失败。')
1998
+ return { ok: false, created: false, reason: 'empty-handle' }
1999
+ }
2000
+ revivedHandles.set(agent.id, handle)
2001
+
2002
+ // 记下标题,页面上新会话还没有模型标题时,路由也能按名字找到它
2003
+ if (typeof title === 'string' && title !== '') {
2004
+ createdTitles.set(agent.id, title)
2005
+ sessionRoster.remember([{ id: agent.id, label: title, status: 'running', live: true }, ...rosterSessions()])
2006
+ }
2007
+
2008
+ let sent = false
2009
+ if (typeof text === 'string' && text !== '') {
2010
+ try {
2011
+ await enqueue(text, { chatId: message.chatId, userId: message.userId, via }, agent)
2012
+ sent = true
2013
+ } catch (error) {
2014
+ log(`[${via}] 新会话投递失败:${error?.message ?? error}`)
2015
+ }
2016
+ }
2017
+ log(`[${via}] 新建会话 ${agent.id}${title ? `(${title})` : ''}${sent ? ',已投递第一条指令' : ''}`)
2018
+ void replyToChat(message.chatId, formatCreated({ title, id: agent.id, sent }))
2019
+ return { ok: true, created: true, session: agent.id, sent, title }
2020
+ }
2021
+
1911
2022
  /**
1912
2023
  * 执行控制命令(`停止` / `状态`),目标会话由调用方解析好。
1913
2024
  * @param options - control / target / message / via。
@@ -2120,6 +2231,12 @@ export function apply(ctx, rawConfig) {
2120
2231
  return applyControl({ control: bareControl, target, message, via })
2121
2232
  }
2122
2233
 
2234
+ // 新建会话:`新建 [标题] [指令]`
2235
+ const createCommand = parseCreate(command)
2236
+ if (createCommand !== undefined) {
2237
+ return createSession({ title: createCommand.title, text: createCommand.text, message, via })
2238
+ }
2239
+
2123
2240
  const route = parseRoute(command)
2124
2241
  if (route !== undefined && route.kind === 'help') {
2125
2242
  log(`[${via}] 路由:发送用法说明`)
@@ -29,6 +29,46 @@ const STOP_COMMANDS = new Set(['停止', '停', '中断', '打住', 'stop', 'can
29
29
  /** 控制命令:看状态。 */
30
30
  const STATUS_COMMANDS = new Set(['状态', '进度', '在干嘛', 'status', 'state'])
31
31
 
32
+ /** 新建会话的命令前缀词。 */
33
+ const CREATE_WORDS = ['新建', '新会话', '开一个', '开个', 'new', 'create']
34
+
35
+ /**
36
+ * 解析「新建」命令:`新建 [标题] [指令]`。
37
+ *
38
+ * - `新建` → 开一个没标题的会话
39
+ * - `新建 前端日报` → 标题设为「前端日报」
40
+ * - `新建 前端日报 帮我看下构建` → 建完直接投第一条指令
41
+ *
42
+ * @param text - 指令正文。
43
+ * @returns `{ title, text }` 或 undefined(不是新建命令)。
44
+ */
45
+ export function parseCreate(text) {
46
+ if (typeof text !== 'string') return undefined
47
+ const value = text.trim()
48
+ if (value === '') return undefined
49
+ const lower = value.toLowerCase()
50
+ const word = CREATE_WORDS.find((item) => lower === item || lower.startsWith(`${item} `) || lower.startsWith(`${item} `))
51
+ if (word === undefined) return undefined
52
+ const rest = value.slice(word.length).trim()
53
+ if (rest === '') return { title: '', text: '' }
54
+ // 第一个空格前是标题,后面全是指令;标题里允许没有空格(整段都当标题)
55
+ const match = rest.match(/^(\S+)\s+([\s\S]+)$/)
56
+ if (match === null) return { title: rest, text: '' }
57
+ return { title: match[1], text: match[2].trim() }
58
+ }
59
+
60
+ /**
61
+ * 把「新建会话」的结果说成人话。
62
+ * @param options - title / id / sent(是否已经投递了第一条指令)。
63
+ * @returns 纯文本。
64
+ */
65
+ export function formatCreated({ title, id, sent } = {}) {
66
+ const name = typeof title === 'string' && title !== '' ? `「${title}」` : '新会话'
67
+ const shortId = typeof id === 'string' && id !== '' ? `(#${id.slice(-4)})` : ''
68
+ const tail = sent === true ? ',第一条指令已投进去' : ',等你发第一条指令'
69
+ return `🆕 已创建${name}${shortId}${tail}\n之后可以直接「@${title !== undefined && title !== '' ? title : '它的标题'} 内容」,或发「列表」挑编号。`
70
+ }
71
+
32
72
  /**
33
73
  * 解析控制命令(可单独发,也可以跟在 `@标题` 后面)。
34
74
  * @param text - 指令正文。
@@ -186,6 +226,7 @@ export function formatHelp({ maxPerMinute, prefix } = {}) {
186
226
  '· 发「@最近 帮我跑测试」→ 交给上次那个会话',
187
227
  '· 发「列表」→ 收到正在跑的会话编号',
188
228
  '· 发「2 帮我跑测试」→ 只交给第 2 个会话(编号 10 分钟内有效)',
229
+ '· 发「新建 前端日报」→ 开一个新会话;「新建 标题 内容」→ 建完直接投第一条指令',
189
230
  '· 发「状态」→ 看各会话在跑还是空闲;「停止」→ 中断当前这一轮(也能 @标题 停止)',
190
231
  '',
191
232
  '【审批】',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-feishu-lark-notify",
3
- "version": "0.25.2",
3
+ "version": "0.26.0",
4
4
  "description": "把 DSH 的任务完成 / 需要你处理的通知推到飞书(Lark):在飞书里点审批、答选择题、按标题把指令交给指定会话,也能收发图片和文件。自带可视化配置页。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",