dsh-im-lark 0.1.2 → 0.1.4
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.en.md +176 -0
- package/README.md +10 -3
- package/assets/hero.en.png +0 -0
- package/assets/hero.zh.png +0 -0
- package/lib/client.js +2 -2
- package/lib/src/host/approvals.js +3 -3
- package/lib/src/host/bridge.js +38 -2
- package/lib/src/host/claim.js +1 -0
- package/lib/src/host/done-align.js +32 -0
- package/lib/src/host/inbound-pipeline.js +29 -56
- package/lib/src/host/index.js +10 -4
- package/lib/src/host/questions.js +6 -4
- package/lib/src/host/reactions.js +15 -0
- package/lib/src/host/reminders.js +10 -4
- package/lib/src/host/stack.js +18 -1
- package/lib/src/host/standalone-command.js +49 -0
- package/lib/src/host/standalone.js +34 -45
- package/lib/src/shared/version.js +1 -1
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +3 -1
package/README.en.md
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# dsh-im-lark
|
|
2
|
+
|
|
3
|
+
[简体中文](README.md) · **English**
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
Connect a Feishu / Lark bot to DeepSeek Harness: DM the bot in Feishu and it is the same as chatting in the Web UI.
|
|
8
|
+
|
|
9
|
+
Two independent modes:
|
|
10
|
+
|
|
11
|
+
| Mode | Switch | Needs the core | Behaviour |
|
|
12
|
+
| --- | --- | --- | --- |
|
|
13
|
+
| **Standalone** (default) | Connect Feishu, turn off "Use my super agent" | No | The plugin creates its own session and you chat in Feishu directly; text commands, question and approval reminders are handled by the plugin |
|
|
14
|
+
| **Core** | Connect Feishu + Use my super agent | Yes | Feishu becomes another entry point to the Web UI: messages, commands and reminders all go to the core |
|
|
15
|
+
|
|
16
|
+
The two modes are mutually exclusive: the core is used only when "Use my super agent" is on and the core service is running; otherwise everything stays standalone, so a message is never handled twice. The core switch on the panel is disabled when the core is not installed.
|
|
17
|
+
|
|
18
|
+
## Features
|
|
19
|
+
|
|
20
|
+
- **Inbound**: text, rich text, images, files; voice, video and stickers get an explicit notice instead of being dropped silently
|
|
21
|
+
- **Outbound**: Markdown cards and images; long answers are split by both character count and card size limits
|
|
22
|
+
- **Quoted replies**: answers quote the message that triggered them, in DMs and groups alike
|
|
23
|
+
- **Processing feedback**: an incoming message gets a `Get` reaction first; `DONE` is added to the original message only after the answer is actually delivered, and the two stay side by side. Being queued is not completion (the core queues the message and runs the task asynchronously). In core mode the plugin follows the core's `completes` markers (stall notices, dispatch receipts and transfer confirmations never carry them; cancelled, failed, approval-rejected or token-limit-truncated rounds do not carry them either, because they have no normal answer; older cores do not send them at all). Standalone mode aligns reactions per turn, and reminder answers are marked at settlement time (when only some questions are answered the reminder is still waiting, so no `DONE`). On failure only `Get` remains — never a false "done". Each message is marked once. Feishu has no official "typing" API
|
|
24
|
+
- **Card updates**: streaming answers update the same card in place; after platform limits (14 days, 5 QPS per card) a new card is sent
|
|
25
|
+
- **Interactive cards**: in core mode, **single-question** single- and multi-select questions are answered in Feishu and the result is returned to the core; in standalone mode single questions are also sent as cards (single and multi select are both checkboxes, distinguished by copy, and must be submitted), everything else stays a text reminder. Multi-question and approval prompts are notice-only and must be answered in the Web UI (the core requires all questions in one submission, which card callbacks cannot do per question); both support an "other" input
|
|
26
|
+
- **Groups**: only messages that @mention the bot are handled (only the @-scoped group permissions are requested); the whole group is never read
|
|
27
|
+
- **Task reminders**: in standalone mode, a long turn (30 minutes by default) sends a reminder with elapsed time and conclusion when it ends; a failed or externally aborted turn is reported immediately with the original error. A stop pressed by the owner is not a failure
|
|
28
|
+
- **Panel**: create an app with one scan on the Web plugin page, or enter App ID / App Secret manually; see connection state, toggle send/receive and core mode, change message behaviour; in standalone mode, adjust in-turn steering, session workspace, question/approval reminders and long-task reminders
|
|
29
|
+
|
|
30
|
+
> Question cards (checkboxes + submit + "other" input) have been verified in a real Feishu tenant in both standalone and core mode: single and multi select are distinguished by card copy, and a submission returns the checked options plus the "other" input. Rejected answers give visible feedback in both modes: a card that can still be answered is **re-rendered whole** with the reason (Feishu form submissions are one-shot; a text-only hint would leave the card unclickable) so you can re-select and submit; a card that can no longer be answered becomes invalid and loses its checkboxes. `Get` / `DONE` reactions and card layout vary slightly with tenant settings; what you see is what the platform does.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
Stable releases go to `latest`, prereleases to channel tags (`stage` / `rc`); they never overwrite each other:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
# stable
|
|
38
|
+
dsh plugin --profile web add dsh-im-lark
|
|
39
|
+
|
|
40
|
+
# prerelease
|
|
41
|
+
dsh plugin --profile web add dsh-im-lark@stage
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
From source (development):
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npm install
|
|
48
|
+
npm run build
|
|
49
|
+
dsh plugin --profile web add file:/absolute/path/dsh-im-lark
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
A `file:` dependency is an **injected copy**: once installed into the profile's `node_modules` it is decoupled from the repo. After changing code run `npm run build`, then remove and re-add to sync the running host.
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
dsh plugin --profile web remove dsh-im-lark
|
|
56
|
+
dsh plugin --profile web add file:/absolute/path/dsh-im-lark
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
No need to restart `dsh web` after reinstalling: the host half is hot-reloaded, so just refresh the browser. Open **Settings → Lark Bot** (or **Plugins → dsh-im-lark**) to enter credentials.
|
|
60
|
+
|
|
61
|
+
### Create an app by QR code
|
|
62
|
+
|
|
63
|
+
On the panel, under "App credentials", click "Create app by QR code", scan the QR code with Feishu and confirm on your phone. Credentials are saved and the connection starts automatically; the QR code is valid for 1 hour and can be used by one user only.
|
|
64
|
+
|
|
65
|
+
The created app still needs its permissions and event subscriptions confirmed (next section). If the long connection never receives messages, first check that "Event subscriptions" uses the **long connection** mode and that `im.message.receive_v1` is subscribed.
|
|
66
|
+
|
|
67
|
+
## Feishu setup
|
|
68
|
+
|
|
69
|
+
1. Create an **enterprise self-built app** on the [Feishu Open Platform](https://open.feishu.cn/app) and copy its App ID and App Secret.
|
|
70
|
+
2. **Add app capability → Bot**.
|
|
71
|
+
3. Under **Permissions**, enable:
|
|
72
|
+
- `im:message.p2p_msg:readonly` (receive DM messages)
|
|
73
|
+
- `im:message.group_at_msg:readonly` (receive group messages that @mention the bot)
|
|
74
|
+
- `im:message:send_as_bot` (send messages as the bot)
|
|
75
|
+
- `im:resource` (upload/download images and files)
|
|
76
|
+
- Reaction permissions (optional): the reaction-related scopes in the console. Missing them does not break the main flow; the "processing" hint degrades to not being sent
|
|
77
|
+
4. **Events & callbacks**:
|
|
78
|
+
- "Event subscriptions": choose the **long connection** mode and subscribe to `im.message.receive_v1`;
|
|
79
|
+
- "Callback configuration": add `card.action.trigger` (needed for card interactions), also over the long connection
|
|
80
|
+
5. **Publish a version** and wait for admin approval; before publishing only the developer can use it.
|
|
81
|
+
|
|
82
|
+
> Long-connection mode needs no public URL and no request URL. Each app allows up to 50 long connections; with multiple instances **only one** connection receives events, so do not scale horizontally by running several processes.
|
|
83
|
+
|
|
84
|
+
## Configuration
|
|
85
|
+
|
|
86
|
+
Static config lives in the profile patch; restart to apply:
|
|
87
|
+
|
|
88
|
+
```yaml
|
|
89
|
+
- id: dsh-im-lark
|
|
90
|
+
name: dsh-im-lark
|
|
91
|
+
config:
|
|
92
|
+
domain: feishu # feishu (default) or lark (international)
|
|
93
|
+
maxText: 2000 # max characters per message; longer text is split automatically
|
|
94
|
+
typingIndicator: true # Get on receipt; DONE on the original message after delivery (Get is never removed)
|
|
95
|
+
replyStatus: false # append model, elapsed time and tokens to the answer
|
|
96
|
+
directBusyMode: steer # a message arriving mid-turn in standalone mode: steer / queue (legacy interrupt migrates to steer)
|
|
97
|
+
directWorkspaceId: '' # workspace id for standalone sessions; empty uses the auto-created default
|
|
98
|
+
questionReminders: true # standalone: send a Feishu reminder when a question or approval is waiting
|
|
99
|
+
questionDelayMinutes: 5 # how long to wait before reminding (0–120): answering in the Web UI within this window avoids it
|
|
100
|
+
longTaskReminders: true # standalone: send a completion reminder when a turn exceeds the threshold
|
|
101
|
+
longTaskMinutes: 30 # long-task threshold (1–1440 minutes)
|
|
102
|
+
failureReminders: true # standalone: report a failed or externally aborted turn immediately
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Items editable in the panel are written to `$DSH_HOME/.dsh-im-lark/config.json` and survive a reinstall. Credentials live in `credentials.json` (directory 0700, file 0600); logs and errors only ever show the last six characters of the App ID. The panel shows the full App ID and binding time; the Secret is never echoed.
|
|
106
|
+
|
|
107
|
+
## Standalone commands
|
|
108
|
+
|
|
109
|
+
| Command | Effect |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `/help` | List commands |
|
|
112
|
+
| `/new` | Start a new session |
|
|
113
|
+
| `/sessions` | List recent sessions and switch to one |
|
|
114
|
+
| `/status` | Current session and runtime state |
|
|
115
|
+
| `/stop` | Abort the running turn |
|
|
116
|
+
| `/trace` | Model and elapsed time of the last answer |
|
|
117
|
+
| `/send <text>` | Send text directly, without the model |
|
|
118
|
+
|
|
119
|
+
## CLI and slash command
|
|
120
|
+
|
|
121
|
+
- **`/lark`** (Web input box): `/lark <text>` sends a piece of text to your own Feishu; `/lark status` shows whether credentials and the recipient are ready. No model involved.
|
|
122
|
+
- **`dsh-lark-send`** (terminal / scripts): `dsh-lark-send text <text>`, `status`, `help`. The recipient is always the owner and there is no `--to`; exit codes `0` success, `1` send failure, `2` bad arguments.
|
|
123
|
+
|
|
124
|
+
The recipient is always the "owner": in standalone mode the first person who DMs the bot in Feishu, in core mode the user bound by the core. With no owner yet it reports an explicit error.
|
|
125
|
+
|
|
126
|
+
## Scope notes
|
|
127
|
+
|
|
128
|
+
- Standalone: while a question or tool approval is waiting for the owner, the plugin sends a Feishu reminder (delay configurable): single questions with options are answered by tapping the card; multi-question, approval and free-form input still use text (reply with a number or the option text). Long-task completion reminders remain the core's job.
|
|
129
|
+
- Standalone: received files only get a notice; their contents are not fed into the session. Images are attached as input.
|
|
130
|
+
- In core mode `DONE` first translates the inbound `messageId` from the core into a platform message id; that table keeps only the latest 500 entries (bounded to avoid unbounded memory): after a plugin restart, or when a message is reported complete more than 500 inbound messages later, the id cannot be resolved and no `DONE` is added — this only affects the completion reaction, never answer delivery.
|
|
131
|
+
- IM cards only carry single-question, option-based interactions; multi-question, approval and free-form input go back to the Web UI, avoiding cards that look clickable but can never be completed.
|
|
132
|
+
|
|
133
|
+
## Limits (platform-determined, not implementation choices)
|
|
134
|
+
|
|
135
|
+
- Event handling must return within **3 seconds**; heavy work is always done asynchronously
|
|
136
|
+
- Text message body ≤ 150 KB, card ≤ 30 KB; the platform rejects anything larger
|
|
137
|
+
- 5 QPS for sending (per user / per group); the plugin rate-limits and backs off internally
|
|
138
|
+
- A card can be PATCHed for 14 days at 5 QPS per card; after that a new message is sent
|
|
139
|
+
- Images ≤ 10 MB, files ≤ 30 MB; checked locally before upload
|
|
140
|
+
- Message editing has a count limit, and the recall window is set by the admin (commonly 24 hours)
|
|
141
|
+
- No official "typing" API, so reactions are the only weak hint
|
|
142
|
+
|
|
143
|
+
## Development
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
npm run typecheck # type check (test files included)
|
|
147
|
+
npm test # unit tests
|
|
148
|
+
npm run build # tsc for the host + esbuild bundle for the client
|
|
149
|
+
npm run verify # verify artifacts, dependency allowlist, insert-only patch
|
|
150
|
+
npm run check # all four above
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Layout:
|
|
154
|
+
|
|
155
|
+
```
|
|
156
|
+
index.ts entry, re-exports src/host/index.ts
|
|
157
|
+
src/host/ host side: connection, inbound, outbound, cards, bridge, standalone sessions, panel RPC
|
|
158
|
+
src/client/ Web panel (React, bundled into lib/client.js)
|
|
159
|
+
src/shared/ constants and version shared by both sides
|
|
160
|
+
locale/ panel copy
|
|
161
|
+
docs/design/ design document
|
|
162
|
+
docs/protocol/ Feishu open-platform facts (with source links)
|
|
163
|
+
docs/adr/ architecture decision records
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Read `AGENTS.md` before changing code (file size, log redaction, no new dependencies, and other hard rules).
|
|
167
|
+
|
|
168
|
+
### Gate and release
|
|
169
|
+
|
|
170
|
+
`npm run check` is the full local gate and the tests are self-contained: they do not depend on the private `dsh-my-superagent` core, and public CI runs the same set.
|
|
171
|
+
|
|
172
|
+
Releases are handled by `.github/workflows/release.yml` on main ([ADR-0007](docs/adr/0007-发布流程与版本通道.md)): the version is kept in sync in three places (`package.json`, the lock file, `src/shared/version.ts`), stable release notes live in `docs/releases/v<version>.md`, prereleases skip `docs/releases/` and get their notes generated by the workflow. A push to main tags, publishes to npm and creates the Release automatically: prereleases only go to npm channel tags (`stage` / `rc`), `latest` is reserved for stable releases.
|
|
173
|
+
|
|
174
|
+
## License
|
|
175
|
+
|
|
176
|
+
MIT
|
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# dsh-im-lark
|
|
2
2
|
|
|
3
|
+
**简体中文** · [English](README.en.md)
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
3
7
|
把飞书 / Lark 机器人接到 DeepSeek Harness:在飞书里私聊机器人,等于在 Web 端对话。
|
|
4
8
|
|
|
5
9
|
两条互相独立的使用路径:
|
|
@@ -17,7 +21,7 @@
|
|
|
17
21
|
- **入站**:文本、富文本、图片、文件;语音/视频/表情包等给一句明确提示,不静默丢弃
|
|
18
22
|
- **出站**:Markdown 卡片、图片;长回答按字符与卡片体积双上限切段
|
|
19
23
|
- **引用回复**:回答引用触发它的那条消息,单聊与群里都成立
|
|
20
|
-
- **处理反馈**:收到消息先打 `
|
|
24
|
+
- **处理反馈**:收到消息先打 `Get`(收到)表情,**回答真正送达后**才在原消息追加 `DONE`,两个标记并排保留——入队不算完成(核心把消息入队后任务才异步跑);核心模式按核心的 `completes` 完成标记打(停滞、派发回执、转投确认等都不带;取消、失败、审批被拒、超出 token 上限而中断的回合也不带,因为它们没有正常答复;旧核心不打),独立模式按回合对齐,提醒作答在**结算**后当场打(多题只答一半时提醒还在等,不盖 `DONE`);失败只保留 `Get`,不留「已完成」的假信号;同一消息只补一次。飞书没有官方「正在输入」接口
|
|
21
25
|
- **卡片更新**:流式回答原地更新同一张卡片;超过平台限制(14 天、单卡 5 QPS)后改发新卡
|
|
22
26
|
- **交互卡片**:核心模式的**单问题**单选题与多选题在飞书里勾选后提交,结果交回核心;
|
|
23
27
|
独立模式的单题提问同样发卡片(单选/多选都是勾选器,靠文案区分,必须点提交),其余仍走
|
|
@@ -31,7 +35,7 @@
|
|
|
31
35
|
> 单选/多选靠卡片文案区分,提交后回传勾选项与「其他」输入。两种模式的作答被拒都有可见
|
|
32
36
|
> 反馈:还能答的卡会**整卡重画**并写上原因(飞书的表单提交是一次性的,只发一句提示
|
|
33
37
|
> 会让卡片点不动),可以重新勾选提交;已经不能再答的卡直接改成失效态、去掉勾选框。
|
|
34
|
-
> `
|
|
38
|
+
> `Get` / `DONE` 表情与卡片排版随租户配置略有差异,以实际表现为准。
|
|
35
39
|
|
|
36
40
|
## 安装
|
|
37
41
|
|
|
@@ -98,7 +102,7 @@ dsh plugin --profile web add file:/绝对路径/dsh-im-lark
|
|
|
98
102
|
config:
|
|
99
103
|
domain: feishu # feishu(默认)或 lark(国际版)
|
|
100
104
|
maxText: 2000 # 单条消息字符上限,超出自动切段
|
|
101
|
-
typingIndicator: true # 收到打
|
|
105
|
+
typingIndicator: true # 收到打 Get;回答送达后原消息追加 DONE(Get 不撤)
|
|
102
106
|
replyStatus: false # 回答末尾附加模型、耗时、token
|
|
103
107
|
directBusyMode: steer # 独立会话里回合进行中又来消息:steer 插话 / queue 排队(旧值 interrupt 会迁移成 steer)
|
|
104
108
|
directWorkspaceId: '' # 独立会话的工作区 id;留空用自动创建的默认工作区
|
|
@@ -137,6 +141,9 @@ dsh plugin --profile web add file:/绝对路径/dsh-im-lark
|
|
|
137
141
|
- 独立模式:问题与工具授权在等主人时,插件发飞书提醒(延迟可调):单题有选项的直接
|
|
138
142
|
点卡片作答,多题/审批/自由输入仍用文字(回序号或选项文字)。长任务完成提醒仍由核心负责。
|
|
139
143
|
- 独立模式收到文件只给一句提示,不把文件内容送进会话;图片会作为输入附上。
|
|
144
|
+
- 核心模式的 `DONE` 要先把握手的入站 `messageId` 翻成平台消息 id,这张表只留最近 500 条
|
|
145
|
+
(有界,防常驻内存增长):插件重启后,或一条消息在 500 条之后才被核心报完成,
|
|
146
|
+
就翻不到平台 id、不打 `DONE`——只影响完成表情,不影响答案送达。
|
|
140
147
|
- IM 卡片只承载单问题、有选项的交互;多问题/审批/自由输入交回 Web 端,避免出现
|
|
141
148
|
「点了按钮但永远答不完」的卡。
|
|
142
149
|
|
|
Binary file
|
|
Binary file
|
package/lib/client.js
CHANGED
|
@@ -131,7 +131,7 @@ var en_default = {
|
|
|
131
131
|
"register.failed": "Failed to create the app. Please retry.",
|
|
132
132
|
"behavior.title": "Message behavior",
|
|
133
133
|
"behavior.typing": "Working / done reaction",
|
|
134
|
-
"behavior.typingHint": "
|
|
134
|
+
"behavior.typingHint": "Adds a Get (received) reaction on arrival, then appends DONE to the original message only once the reply is actually delivered (queueing does not count); both stay on the message. Lark has no official typing API.",
|
|
135
135
|
"behavior.replyStatus": "Status line in replies",
|
|
136
136
|
"behavior.replyStatusHint": "Model, reasoning effort and duration.",
|
|
137
137
|
"common.save": "Save",
|
|
@@ -243,7 +243,7 @@ var zh_default = {
|
|
|
243
243
|
"register.failed": "\u521B\u5EFA\u5E94\u7528\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5",
|
|
244
244
|
"behavior.title": "\u6D88\u606F\u884C\u4E3A",
|
|
245
245
|
"behavior.typing": "\u5904\u7406\u72B6\u6001\u8868\u60C5",
|
|
246
|
-
"behavior.typingHint": "\u6536\u5230\u6D88\u606F\u5148\u6253
|
|
246
|
+
"behavior.typingHint": "\u6536\u5230\u6D88\u606F\u5148\u6253\u300C\u6536\u5230\u300D(Get)\uFF0C\u56DE\u7B54\u771F\u6B63\u9001\u8FBE\u540E\u624D\u5728\u539F\u6D88\u606F\u8FFD\u52A0 DONE\uFF08\u5165\u961F\u4E0D\u7B97\u5B8C\u6210\uFF09\uFF0C\u4E24\u4E2A\u90FD\u4FDD\u7559\u3002\u98DE\u4E66\u6CA1\u6709\u5B98\u65B9\u8F93\u5165\u72B6\u6001\u63A5\u53E3\u3002",
|
|
247
247
|
"behavior.replyStatus": "\u56DE\u590D\u672B\u5C3E\u663E\u793A\u72B6\u6001",
|
|
248
248
|
"behavior.replyStatusHint": "\u9644\u52A0\u6A21\u578B\u3001\u63A8\u7406\u7B49\u7EA7\u4E0E\u8017\u65F6\u3002",
|
|
249
249
|
"common.save": "\u4FDD\u5B58",
|
|
@@ -167,15 +167,15 @@ export class ApprovalBroker {
|
|
|
167
167
|
reply(text) {
|
|
168
168
|
const decision = parseDecision(text);
|
|
169
169
|
if (decision === null)
|
|
170
|
-
return
|
|
170
|
+
return undefined;
|
|
171
171
|
const pending = decision.no === undefined ? this.#pending.newest() : this.#byNo(decision.no);
|
|
172
172
|
if (pending === undefined)
|
|
173
|
-
return
|
|
173
|
+
return undefined;
|
|
174
174
|
pending.resolve(decision.outcome);
|
|
175
175
|
this.#pending.delete(pending.id);
|
|
176
176
|
// 回执尽力而为:不阻塞入站流水线,也不因为回执失败改变已经做出的决定。
|
|
177
177
|
void this.#options.send(receipt(pending, decision.outcome)).catch(() => { });
|
|
178
|
-
return
|
|
178
|
+
return 'settled';
|
|
179
179
|
}
|
|
180
180
|
/** 停机/停用:把等待中的审批交回 Web(不吞掉请求,也不把它变成拒绝)。 */
|
|
181
181
|
cancelAll(reason = '插件已停止') {
|
package/lib/src/host/bridge.js
CHANGED
|
@@ -93,12 +93,19 @@ export function createLarkBridge(deps) {
|
|
|
93
93
|
if (delivery.expiresAt !== undefined && delivery.expiresAt <= now()) {
|
|
94
94
|
return failure(deliveryId, 'window-closed', '交付已过期,未发送');
|
|
95
95
|
}
|
|
96
|
+
// 本次交付完成的原消息;只在平台确认发送/更新成功后打(判据见 completionTargets)。
|
|
97
|
+
const doneTargets = completionTargets(delivery);
|
|
98
|
+
const markDone = () => {
|
|
99
|
+
for (const target of doneTargets)
|
|
100
|
+
deps.markDone?.(target);
|
|
101
|
+
};
|
|
96
102
|
const stream = delivery.stream;
|
|
97
103
|
let streamOversized = false;
|
|
98
104
|
if (stream !== undefined) {
|
|
99
105
|
const detached = detachedStreams.get(stream.id);
|
|
100
|
-
if (detached !== undefined) {
|
|
101
|
-
//
|
|
106
|
+
if (detached !== undefined && stream.final !== true) {
|
|
107
|
+
// 这条流已经改用分条消息了:中间修订再发只会刷屏。
|
|
108
|
+
// 终稿不能在这里吞掉——它和中间修订内容不同,要往下走正常发送。
|
|
102
109
|
return { deliveryId, status: 'sent', bridgeMessageId: detached, messagesSent: 0 };
|
|
103
110
|
}
|
|
104
111
|
const current = streams.get(stream.id);
|
|
@@ -117,6 +124,7 @@ export function createLarkBridge(deps) {
|
|
|
117
124
|
try {
|
|
118
125
|
await deps.api.patchCard({ messageId: current.messageId, card });
|
|
119
126
|
remember(streams, stream.id, { revision: stream.revision, messageId: current.messageId }, MAX_DELIVERED);
|
|
127
|
+
markDone();
|
|
120
128
|
return { deliveryId, status: 'sent', bridgeMessageId: current.messageId, messagesSent: 0 };
|
|
121
129
|
}
|
|
122
130
|
catch (error) {
|
|
@@ -166,6 +174,8 @@ export function createLarkBridge(deps) {
|
|
|
166
174
|
...(receipt.error === undefined ? {} : { error: receipt.error }),
|
|
167
175
|
};
|
|
168
176
|
}
|
|
177
|
+
// 回答送达成功才补 DONE;发送失败只留「收到」,不给假信号。
|
|
178
|
+
markDone();
|
|
169
179
|
const messageId = receipt.messageIds[0];
|
|
170
180
|
if (messageId !== undefined) {
|
|
171
181
|
remember(delivered, deliveryId, { delivery, messageId }, MAX_DELIVERED);
|
|
@@ -209,6 +219,32 @@ export function createLarkBridge(deps) {
|
|
|
209
219
|
? { ...sent, error: '交互卡片超过平台上限,已降级为纯文本;请在 Web 端作答' }
|
|
210
220
|
: sent;
|
|
211
221
|
}
|
|
222
|
+
/**
|
|
223
|
+
* 这次交付完成了哪些原消息(平台侧消息 id)。
|
|
224
|
+
*
|
|
225
|
+
* 判据直接读核心的 `completes`(my-superagent#3):只有「该轮以 completed 结束 +
|
|
226
|
+
* 消息自己的 rpcId 在这轮里 + 这条交付送达」三条同时成立才会带,停滞提醒、重启孤儿、
|
|
227
|
+
* 派发回执、转投确认、命令回复都不带。**不再按 `refs`/标题猜**——那套启发式会误判:
|
|
228
|
+
* 派发恢复告知与转投确认带 refs 却任务未完(误打),前台会话收尾不带 refs 却是正常
|
|
229
|
+
* 回答(漏打)。
|
|
230
|
+
*
|
|
231
|
+
* 旧核心不发这个字段 → 空数组 → 不打完成标记(漏打优于误打)。一条交付可能完成多条
|
|
232
|
+
* 消息(宿主把连发的几条并成一轮),所以返回数组逐个打。
|
|
233
|
+
*/
|
|
234
|
+
function completionTargets(delivery) {
|
|
235
|
+
const targets = [];
|
|
236
|
+
for (const id of delivery.completes ?? []) {
|
|
237
|
+
// 核心给的是入站草稿的 messageId,要翻成平台消息 id;查不到就不打。
|
|
238
|
+
// 常见原因:插件重启后入站映射被淘汰(有界 FIFO)、核心契约漂移。留一条调试日志,
|
|
239
|
+
// 否则「少打了一个 DONE」在线上无从排查(不打对用户无害,但说不清为什么)。
|
|
240
|
+
const platformId = inbound.get(id);
|
|
241
|
+
if (platformId !== undefined)
|
|
242
|
+
targets.push(platformId);
|
|
243
|
+
else
|
|
244
|
+
logger.debug?.('完成标记找不到对应的平台消息,跳过', id);
|
|
245
|
+
}
|
|
246
|
+
return targets;
|
|
247
|
+
}
|
|
212
248
|
/** 核心传的是 sender/open_id;飞书发消息要 chat_id,用入站学到的映射翻译。 */
|
|
213
249
|
function chatOf(recipient) {
|
|
214
250
|
const learned = senderChats.get(recipient);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export class DoneAlign {
|
|
2
|
+
/** 已提交、尚无定论的消息,按提交顺序。 */
|
|
3
|
+
#pending = [];
|
|
4
|
+
/** 提交成功(已入会话)后登记。 */
|
|
5
|
+
push(messageId, mode) {
|
|
6
|
+
this.#pending.push({ messageId, mode });
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* 一轮结束:出队本轮应答的消息(平台消息 id)。
|
|
10
|
+
* 交付失败时调用方仍要结算(这一轮已经消耗掉它们),只是不盖完成标记。
|
|
11
|
+
*/
|
|
12
|
+
settle() {
|
|
13
|
+
const head = this.#pending.shift();
|
|
14
|
+
if (head === undefined)
|
|
15
|
+
return [];
|
|
16
|
+
const settled = [head.messageId];
|
|
17
|
+
// 队头之后、连续提交的 steer 消息已被这一轮在步骤边界吸收。
|
|
18
|
+
while (this.#pending[0]?.mode === 'steer') {
|
|
19
|
+
const absorbed = this.#pending.shift();
|
|
20
|
+
if (absorbed !== undefined)
|
|
21
|
+
settled.push(absorbed.messageId);
|
|
22
|
+
}
|
|
23
|
+
return settled;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 绑定会话换了(`/new`、`/sessions <序号>`):旧会话的 `turn/end` 会被会话校验
|
|
27
|
+
* 丢弃,残留条目永远等不到自己的回合,只会被下一轮错认。整队清掉。
|
|
28
|
+
*/
|
|
29
|
+
clear() {
|
|
30
|
+
this.#pending.length = 0;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -10,18 +10,10 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { MAX_FILE_BYTES, MAX_FILES_BYTES, MAX_IMAGE_BYTES, OWNER_FILES_MAX, OWNER_IMAGES_MAX } from "../shared/limits.js";
|
|
12
12
|
import { parseCardAction, parseMessageEvent } from "./inbound.js";
|
|
13
|
+
import { addReaction, REACTION_ACK } from "./reactions.js";
|
|
13
14
|
import { SeenStore } from "./state/seen.js";
|
|
14
15
|
const TEXT_MAX = 20_000;
|
|
15
|
-
/**
|
|
16
|
-
* 消息上的处理状态标记,走官方「添加消息表情回复」接口的 `emoji_type`。
|
|
17
|
-
*
|
|
18
|
-
* - `Typing`:收到就开始处理;
|
|
19
|
-
* - `DONE`:处理完成,覆盖 `Typing`,让主人一眼看出这条已经答完了。
|
|
20
|
-
*
|
|
21
|
-
* 只有成功处理完才盖 `DONE`:失败时不该给出「已完成」的假信号。
|
|
22
|
-
*/
|
|
23
|
-
const REACTION_TYPING = 'Typing';
|
|
24
|
-
const REACTION_DONE = 'DONE';
|
|
16
|
+
/** 图片类型白名单:只有这几种能当 `image` 交给核心。 */
|
|
25
17
|
const KNOWN_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
|
|
26
18
|
/** 卡片回调的重推窗口:没有 `event_id` 时用它兜住平台重推,窗口之外允许同一张卡再提交。 */
|
|
27
19
|
const CARD_RETRY_WINDOW_MS = 5_000;
|
|
@@ -38,6 +30,7 @@ export class InboundPipeline {
|
|
|
38
30
|
#onOwner;
|
|
39
31
|
#now;
|
|
40
32
|
#claim;
|
|
33
|
+
#markDone;
|
|
41
34
|
#claimCard;
|
|
42
35
|
#fallback;
|
|
43
36
|
#chain = Promise.resolve();
|
|
@@ -54,6 +47,7 @@ export class InboundPipeline {
|
|
|
54
47
|
this.#onOwner = options.onOwner;
|
|
55
48
|
this.#now = options.now ?? Date.now;
|
|
56
49
|
this.#claim = options.claim;
|
|
50
|
+
this.#markDone = options.markDone;
|
|
57
51
|
this.#claimCard = options.claimCard;
|
|
58
52
|
this.#fallback = options.fallback;
|
|
59
53
|
}
|
|
@@ -134,55 +128,34 @@ export class InboundPipeline {
|
|
|
134
128
|
this.#logger.warn?.('入站处理失败', error instanceof Error ? error.message : String(error));
|
|
135
129
|
});
|
|
136
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* 入站只负责「收到」标记(`Get`,取值与打点约定见 `reactions.ts`)。
|
|
133
|
+
* `DONE` 不在这里打:`receive` 返回 accepted 只代表消息入队,任务是之后异步跑的
|
|
134
|
+
* (核心 emit 事件即返回、独立模式提交即返回),入队就打会给「已完成」的假信号。
|
|
135
|
+
* 完成标记在回答真正送达时补(bridge 的交付路径、独立模式的回合结束),
|
|
136
|
+
* 唯一例外是提醒作答:只有**结算成功**时当场打,没答完(`unsettled`)不打。
|
|
137
|
+
*/
|
|
137
138
|
async #processMessage(message, body) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
|
-
const result = await this.#bridge.receive(draft);
|
|
154
|
-
if (!result.accepted && result.reason === 'unknown' && this.#fallback !== undefined) {
|
|
155
|
-
await this.#fallback(message, draft);
|
|
156
|
-
}
|
|
157
|
-
else if (!result.accepted) {
|
|
158
|
-
this.#logger.debug?.('消息未被核心接受', `${result.reason} ${result.detail ?? ''}`);
|
|
159
|
-
}
|
|
160
|
-
settled = true;
|
|
161
|
-
}
|
|
162
|
-
finally {
|
|
163
|
-
if (typingId !== undefined)
|
|
164
|
-
await this.#removeReaction(message.messageId, typingId);
|
|
165
|
-
if (settled && this.#typing)
|
|
166
|
-
await this.#addReaction(message.messageId, REACTION_DONE);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
/** 加一条表情回复;失败不外抛,输入状态与完成标记都是尽力而为。 */
|
|
170
|
-
async #addReaction(messageId, emojiType) {
|
|
171
|
-
try {
|
|
172
|
-
const result = await this.#api.addReaction({ messageId, emojiType });
|
|
173
|
-
return result.reactionId;
|
|
174
|
-
}
|
|
175
|
-
catch (error) {
|
|
176
|
-
// 表情是否可用随租户配置变化,失败就当作没有这个标记。
|
|
177
|
-
return undefined;
|
|
139
|
+
if (this.#typing)
|
|
140
|
+
await addReaction(this.#api, message.messageId, REACTION_ACK);
|
|
141
|
+
const draft = await this.#toDraft(message, body);
|
|
142
|
+
if (draft === null)
|
|
143
|
+
return;
|
|
144
|
+
// 提醒的作答先于一切:主人回「批准」「2」时不该把它当聊天送进会话。
|
|
145
|
+
// 只有**已结算**的作答当场补完成标记;多题只答一半时提醒还在等(回了格式提示),
|
|
146
|
+
// 那条消息不算处理完,不能盖 DONE。普通消息的完成标记由回答送达时补。
|
|
147
|
+
const claim = this.#claim?.(draft);
|
|
148
|
+
if (claim !== undefined) {
|
|
149
|
+
if (claim === 'settled')
|
|
150
|
+
this.#markDone?.(message.messageId);
|
|
151
|
+
return;
|
|
178
152
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
await this.#api.removeReaction({ messageId, reactionId });
|
|
153
|
+
const result = await this.#bridge.receive(draft);
|
|
154
|
+
if (!result.accepted && result.reason === 'unknown' && this.#fallback !== undefined) {
|
|
155
|
+
await this.#fallback(message, draft);
|
|
183
156
|
}
|
|
184
|
-
|
|
185
|
-
|
|
157
|
+
else if (!result.accepted) {
|
|
158
|
+
this.#logger.debug?.('消息未被核心接受', `${result.reason} ${result.detail ?? ''}`);
|
|
186
159
|
}
|
|
187
160
|
}
|
|
188
161
|
/** 事件 → 协议草稿;媒体下载失败时降级成文字说明,不让整条消息丢掉。 */
|
package/lib/src/host/index.js
CHANGED
|
@@ -157,10 +157,16 @@ export async function apply(ctx, config = {}) {
|
|
|
157
157
|
controller: () => controller,
|
|
158
158
|
workspaceId: () => workspaces.defaultId,
|
|
159
159
|
// 提醒的作答先于普通消息:主人回「批准」「2」时不该把它当聊天送进会话。
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
(
|
|
163
|
-
|
|
160
|
+
// 带媒体的草稿不当作答(那是发给模型的内容)。
|
|
161
|
+
claim: (draft) => {
|
|
162
|
+
if (coreEnabled())
|
|
163
|
+
return undefined;
|
|
164
|
+
if ((draft.images?.length ?? 0) > 0)
|
|
165
|
+
return undefined;
|
|
166
|
+
if ((draft.files?.length ?? 0) > 0)
|
|
167
|
+
return undefined;
|
|
168
|
+
return reminders.reply(draft.text);
|
|
169
|
+
},
|
|
164
170
|
// 独立模式的提问卡不是核心交付:先给提醒认领,认不出再交给桥。
|
|
165
171
|
claimCard: (action) => !coreEnabled() && reminders.applyCardAction(action),
|
|
166
172
|
ownerLabel: () => tailOf(app.appId),
|
|
@@ -198,7 +198,8 @@ export class QuestionBroker {
|
|
|
198
198
|
}
|
|
199
199
|
}
|
|
200
200
|
/**
|
|
201
|
-
* 入站文本尝试当作作答;返回
|
|
201
|
+
* 入站文本尝试当作作答;返回 `settled`(已结算)、`unsettled`(认下了但还在等后续
|
|
202
|
+
* 作答,如多题只答一半回了格式提示),两者都不再进普通消息路径;`undefined` 表示不是作答。
|
|
202
203
|
* 多条待答时认**最后一条**:主人在飞书里看到的是最近发出的那条提醒。
|
|
203
204
|
*/
|
|
204
205
|
reply(text) {
|
|
@@ -208,8 +209,9 @@ export class QuestionBroker {
|
|
|
208
209
|
if (claim === null)
|
|
209
210
|
continue;
|
|
210
211
|
if (claim === 'partial') {
|
|
212
|
+
// 认下了但没结算:提醒仍挂起并回了格式提示,不能当成「已答完」。
|
|
211
213
|
this.#noteGuidance(pending, text);
|
|
212
|
-
return
|
|
214
|
+
return 'unsettled';
|
|
213
215
|
}
|
|
214
216
|
const answer = answerFromText(pending.questions, text);
|
|
215
217
|
if (answer === null)
|
|
@@ -217,9 +219,9 @@ export class QuestionBroker {
|
|
|
217
219
|
pending.resolve(answer);
|
|
218
220
|
this.#pending.delete(pending.id);
|
|
219
221
|
this.#closeCard(pending, `已在飞书作答:${describeAnswer(answer)}`);
|
|
220
|
-
return
|
|
222
|
+
return 'settled';
|
|
221
223
|
}
|
|
222
|
-
return
|
|
224
|
+
return undefined;
|
|
223
225
|
}
|
|
224
226
|
/**
|
|
225
227
|
* 多题只答了几段:提醒里回一句格式提示,保留待答。
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const REACTION_ACK = 'Get';
|
|
2
|
+
export const REACTION_DONE = 'DONE';
|
|
3
|
+
/**
|
|
4
|
+
* 最佳努力加表情:表情可用性随租户配置变化,失败静默,绝不影响消息处理。
|
|
5
|
+
* 返回是否成功,便于测试断言;调用方不据此做分支。
|
|
6
|
+
*/
|
|
7
|
+
export async function addReaction(api, messageId, emojiType) {
|
|
8
|
+
try {
|
|
9
|
+
await api.addReaction({ messageId, emojiType });
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -128,10 +128,16 @@ export class ReminderCenter {
|
|
|
128
128
|
* 顺序由本类记录——两个 broker 各自计数不可比(各发一次时恒为 1:1)。
|
|
129
129
|
*/
|
|
130
130
|
reply(text) {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
131
|
+
// 谁最后发就先给谁认;三态不能用 `||` 串('settled' 与 'unsettled' 都是真值)。
|
|
132
|
+
const order = this.#lastSent === 'approval'
|
|
133
|
+
? [this.#approvals, this.#questions]
|
|
134
|
+
: [this.#questions, this.#approvals];
|
|
135
|
+
for (const center of order) {
|
|
136
|
+
const outcome = center.reply(text);
|
|
137
|
+
if (outcome !== undefined)
|
|
138
|
+
return outcome;
|
|
139
|
+
}
|
|
140
|
+
return undefined;
|
|
135
141
|
}
|
|
136
142
|
/** 更新设置;关掉时把在等的请求交回 Web,别挂到超时。 */
|
|
137
143
|
configure(patch) {
|
package/lib/src/host/stack.js
CHANGED
|
@@ -10,6 +10,8 @@ import { InboundPipeline } from "./inbound-pipeline.js";
|
|
|
10
10
|
import { createSdkLarkApi } from "./lark/api.js";
|
|
11
11
|
import { createSdkClient } from "./lark/sdk.js";
|
|
12
12
|
import { OutboundChannel } from "./outbound.js";
|
|
13
|
+
import { addReaction, REACTION_DONE } from "./reactions.js";
|
|
14
|
+
import { SeenStore } from "./state/seen.js";
|
|
13
15
|
import { StandaloneChat } from "./standalone.js";
|
|
14
16
|
export function createLarkStack(options) {
|
|
15
17
|
const { app, logger } = options;
|
|
@@ -19,6 +21,18 @@ export function createLarkStack(options) {
|
|
|
19
21
|
client: createSdkClient({ ...app, ...(logger === undefined ? {} : { logger }) }),
|
|
20
22
|
logger,
|
|
21
23
|
});
|
|
24
|
+
// 「处理状态表情」开关同时管完成标记:关掉时收到的 Get 与完成的 DONE 都不打。
|
|
25
|
+
const typing = options.typing ?? options.config.typingIndicator;
|
|
26
|
+
// 同一平台消息只补一次 DONE:交付重投、同一入站收到多条 result 时不要重复加表情
|
|
27
|
+
// (重复加同一表情时平台行为未验证,去重后无论如何都不会发生)。
|
|
28
|
+
const doneSeen = new SeenStore({ ttlMs: 6 * 60 * 60 * 1000, max: 2_000 });
|
|
29
|
+
const markDone = (platformMessageId) => {
|
|
30
|
+
if (!typing)
|
|
31
|
+
return;
|
|
32
|
+
if (!doneSeen.claim(platformMessageId))
|
|
33
|
+
return;
|
|
34
|
+
void addReaction(api, platformMessageId, REACTION_DONE);
|
|
35
|
+
};
|
|
22
36
|
const bridge = createLarkBridge({
|
|
23
37
|
account: app.appId,
|
|
24
38
|
api,
|
|
@@ -27,6 +41,7 @@ export function createLarkStack(options) {
|
|
|
27
41
|
...(options.now === undefined ? {} : { now: options.now }),
|
|
28
42
|
...(options.health === undefined ? {} : { health: options.health }),
|
|
29
43
|
...(options.chatFor === undefined ? {} : { chatFor: options.chatFor }),
|
|
44
|
+
markDone,
|
|
30
45
|
});
|
|
31
46
|
const standaloneOutbound = new OutboundChannel({
|
|
32
47
|
api,
|
|
@@ -44,18 +59,20 @@ export function createLarkStack(options) {
|
|
|
44
59
|
...(options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId }),
|
|
45
60
|
...(options.ownerLabel === undefined ? {} : { ownerLabel: options.ownerLabel }),
|
|
46
61
|
...(options.now === undefined ? {} : { now: options.now }),
|
|
62
|
+
markDone,
|
|
47
63
|
});
|
|
48
64
|
const pipeline = new InboundPipeline({
|
|
49
65
|
api,
|
|
50
66
|
bridge,
|
|
51
67
|
logger,
|
|
52
|
-
typing
|
|
68
|
+
typing,
|
|
53
69
|
...(options.botOpenId === undefined ? {} : { botOpenId: options.botOpenId }),
|
|
54
70
|
...(options.ownerOpenId === undefined ? {} : { ownerOpenId: options.ownerOpenId }),
|
|
55
71
|
...(options.features === undefined ? {} : { features: options.features }),
|
|
56
72
|
...(options.isOwner === undefined ? {} : { isOwner: options.isOwner }),
|
|
57
73
|
...(options.onOwner === undefined ? {} : { onOwner: options.onOwner }),
|
|
58
74
|
...(options.claim === undefined ? {} : { claim: options.claim }),
|
|
75
|
+
markDone,
|
|
59
76
|
...(options.claimCard === undefined ? {} : { claimCard: options.claimCard }),
|
|
60
77
|
...(options.now === undefined ? {} : { now: options.now }),
|
|
61
78
|
fallback: (message, draft) => standalone.handleInbound(message, draft),
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 独立模式的文本命令:解析与帮助文案。
|
|
3
|
+
*
|
|
4
|
+
* 纯函数、不碰会话状态,与 `standalone.ts` 的会话编排分开——命令表会随功能长,
|
|
5
|
+
* 编排代码读起来才不用来回翻命令分支。
|
|
6
|
+
*/
|
|
7
|
+
/** 解析以 `/` 开头的文本;不是命令返回 null。 */
|
|
8
|
+
export function parseCommand(input) {
|
|
9
|
+
const trimmed = input.trim();
|
|
10
|
+
if (!trimmed.startsWith('/'))
|
|
11
|
+
return null;
|
|
12
|
+
const [head = '', ...rest] = trimmed.slice(1).split(/\s+/);
|
|
13
|
+
const name = head.toLowerCase();
|
|
14
|
+
const tail = rest.join(' ').trim();
|
|
15
|
+
switch (name) {
|
|
16
|
+
case '':
|
|
17
|
+
case 'help':
|
|
18
|
+
return { kind: 'help' };
|
|
19
|
+
case 'new':
|
|
20
|
+
return { kind: 'new' };
|
|
21
|
+
case 'status':
|
|
22
|
+
return { kind: 'status' };
|
|
23
|
+
case 'stop':
|
|
24
|
+
return { kind: 'stop' };
|
|
25
|
+
case 'trace':
|
|
26
|
+
return { kind: 'trace' };
|
|
27
|
+
case 'send':
|
|
28
|
+
return tail === '' ? { kind: 'help' } : { kind: 'send', text: tail };
|
|
29
|
+
case 'sessions': {
|
|
30
|
+
if (tail === '')
|
|
31
|
+
return { kind: 'sessions' };
|
|
32
|
+
const index = Number(tail);
|
|
33
|
+
return Number.isInteger(index) && index > 0 ? { kind: 'sessions', index } : { kind: 'sessions' };
|
|
34
|
+
}
|
|
35
|
+
default:
|
|
36
|
+
return { kind: 'unknown', name };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export const HELP_TEXT = [
|
|
40
|
+
'我是这个工作区的飞书入口。可用命令:',
|
|
41
|
+
'',
|
|
42
|
+
'`/new` 开新会话',
|
|
43
|
+
'`/sessions` 查看最近会话;`/sessions 2` 切到第 2 个',
|
|
44
|
+
'`/status` 当前会话与连接状态',
|
|
45
|
+
'`/stop` 中止正在跑的回合',
|
|
46
|
+
'`/trace` 上一条回答的模型与耗时',
|
|
47
|
+
'`/send <文本>` 不经过模型,直接发一段文本',
|
|
48
|
+
'`/help` 这份说明',
|
|
49
|
+
].join('\n');
|
|
@@ -9,49 +9,8 @@
|
|
|
9
9
|
* 也不写进会话历史。
|
|
10
10
|
*/
|
|
11
11
|
import { randomUUID } from 'node:crypto';
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const trimmed = input.trim();
|
|
15
|
-
if (!trimmed.startsWith('/'))
|
|
16
|
-
return null;
|
|
17
|
-
const [head = '', ...rest] = trimmed.slice(1).split(/\s+/);
|
|
18
|
-
const name = head.toLowerCase();
|
|
19
|
-
const tail = rest.join(' ').trim();
|
|
20
|
-
switch (name) {
|
|
21
|
-
case '':
|
|
22
|
-
case 'help':
|
|
23
|
-
return { kind: 'help' };
|
|
24
|
-
case 'new':
|
|
25
|
-
return { kind: 'new' };
|
|
26
|
-
case 'status':
|
|
27
|
-
return { kind: 'status' };
|
|
28
|
-
case 'stop':
|
|
29
|
-
return { kind: 'stop' };
|
|
30
|
-
case 'trace':
|
|
31
|
-
return { kind: 'trace' };
|
|
32
|
-
case 'send':
|
|
33
|
-
return tail === '' ? { kind: 'help' } : { kind: 'send', text: tail };
|
|
34
|
-
case 'sessions': {
|
|
35
|
-
if (tail === '')
|
|
36
|
-
return { kind: 'sessions' };
|
|
37
|
-
const index = Number(tail);
|
|
38
|
-
return Number.isInteger(index) && index > 0 ? { kind: 'sessions', index } : { kind: 'sessions' };
|
|
39
|
-
}
|
|
40
|
-
default:
|
|
41
|
-
return { kind: 'unknown', name };
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
export const HELP_TEXT = [
|
|
45
|
-
'我是这个工作区的飞书入口。可用命令:',
|
|
46
|
-
'',
|
|
47
|
-
'`/new` 开新会话',
|
|
48
|
-
'`/sessions` 查看最近会话;`/sessions 2` 切到第 2 个',
|
|
49
|
-
'`/status` 当前会话与连接状态',
|
|
50
|
-
'`/stop` 中止正在跑的回合',
|
|
51
|
-
'`/trace` 上一条回答的模型与耗时',
|
|
52
|
-
'`/send <文本>` 不经过模型,直接发一段文本',
|
|
53
|
-
'`/help` 这份说明',
|
|
54
|
-
].join('\n');
|
|
12
|
+
import { DoneAlign } from "./done-align.js";
|
|
13
|
+
import { HELP_TEXT, parseCommand } from "./standalone-command.js";
|
|
55
14
|
const SUBMIT_TIMEOUT_MS = 30_000;
|
|
56
15
|
const LIST_LIMIT = 10;
|
|
57
16
|
export class StandaloneChat {
|
|
@@ -65,8 +24,15 @@ export class StandaloneChat {
|
|
|
65
24
|
#now;
|
|
66
25
|
#ownerLabel;
|
|
67
26
|
#submitTimeoutMs;
|
|
27
|
+
#markDone;
|
|
68
28
|
#chatId = '';
|
|
69
29
|
#lastUserMessageId;
|
|
30
|
+
/**
|
|
31
|
+
* 已提交、等回合结束的消息(按提交顺序对齐)。
|
|
32
|
+
* 规则与宿主回合语义见 `done-align.ts`:不用 `#lastUserMessageId` 结算,那会把
|
|
33
|
+
* 完成标记盖到没被回答的消息上。
|
|
34
|
+
*/
|
|
35
|
+
#align = new DoneAlign();
|
|
70
36
|
#running = false;
|
|
71
37
|
#answer = '';
|
|
72
38
|
#startedAt = 0;
|
|
@@ -85,6 +51,7 @@ export class StandaloneChat {
|
|
|
85
51
|
this.#now = options.now ?? Date.now;
|
|
86
52
|
this.#ownerLabel = options.ownerLabel ?? (() => '');
|
|
87
53
|
this.#submitTimeoutMs = options.submitTimeoutMs ?? SUBMIT_TIMEOUT_MS;
|
|
54
|
+
this.#markDone = options.markDone;
|
|
88
55
|
}
|
|
89
56
|
status() {
|
|
90
57
|
const binding = this.#bindings.peek();
|
|
@@ -109,11 +76,16 @@ export class StandaloneChat {
|
|
|
109
76
|
const command = parseCommand(text);
|
|
110
77
|
if (command !== null) {
|
|
111
78
|
await this.#runCommand(command);
|
|
79
|
+
// 命令当场就答完了:回复发出即处理结束,补完成标记(失败的回复也一样,命令本身已处理)。
|
|
80
|
+
this.#markDone?.(message.messageId);
|
|
112
81
|
return;
|
|
113
82
|
}
|
|
114
83
|
const showNotice = await this.#submit(text, draft);
|
|
84
|
+
// 提交失败的通知不是完成:只留「收到」,不盖 DONE;回答要等回合结束。
|
|
115
85
|
if (showNotice !== null)
|
|
116
86
|
await this.#reply(showNotice);
|
|
87
|
+
else
|
|
88
|
+
this.#align.push(message.messageId, this.#busyMode());
|
|
117
89
|
}
|
|
118
90
|
/** `session/event`:跟踪绑定会话的回合,结束后把回答发回飞书。 */
|
|
119
91
|
handleEvent(sessionId, event) {
|
|
@@ -147,10 +119,20 @@ export class StandaloneChat {
|
|
|
147
119
|
this.#running = false;
|
|
148
120
|
const answer = this.#answer.trim();
|
|
149
121
|
this.#answer = '';
|
|
122
|
+
// 无论有没有回答都结算:这一轮已经消耗掉这些消息,留在队里只会被下一轮错认。
|
|
123
|
+
const settled = this.#align.settle();
|
|
150
124
|
if (answer === '')
|
|
151
125
|
return;
|
|
152
126
|
this.#lastTrace = { model: this.#model, durationMs: Math.max(0, this.#now() - this.#startedAt), at: this.#now() };
|
|
153
|
-
|
|
127
|
+
// 回答真正发出去才算这一轮结束;发送失败(含没有目标会话)只留「收到」,不给假信号。
|
|
128
|
+
void this.#reply(answer, this.#lastTrace)
|
|
129
|
+
.then((delivered) => {
|
|
130
|
+
if (!delivered)
|
|
131
|
+
return;
|
|
132
|
+
for (const messageId of settled)
|
|
133
|
+
this.#markDone?.(messageId);
|
|
134
|
+
})
|
|
135
|
+
.catch((error) => {
|
|
154
136
|
this.#logger.warn?.('独立模式回复失败', errorText(error));
|
|
155
137
|
});
|
|
156
138
|
return;
|
|
@@ -162,6 +144,8 @@ export class StandaloneChat {
|
|
|
162
144
|
async reset() {
|
|
163
145
|
this.#running = false;
|
|
164
146
|
this.#answer = '';
|
|
147
|
+
// 旧会话的回合结束会被会话校验丢弃,残留的待结算条目只会被下一轮错认。
|
|
148
|
+
this.#align.clear();
|
|
165
149
|
await this.#bindings.clear();
|
|
166
150
|
}
|
|
167
151
|
/** 主动发一段文本(CLI 与命令共用);返回 `deliveryId` 为空的失败原因。 */
|
|
@@ -298,6 +282,8 @@ export class StandaloneChat {
|
|
|
298
282
|
if (target === undefined || id === '')
|
|
299
283
|
return `没有第 ${index} 个会话。`;
|
|
300
284
|
await this.#bindings.set({ sessionId: id, workspaceId: '', ...(sessionTitle(target) === '' ? {} : { title: sessionTitle(target) }) });
|
|
285
|
+
// 换会话后旧会话的 turn/end 不再被接受,残留条目会错挂到新会话的回合上。
|
|
286
|
+
this.#align.clear();
|
|
301
287
|
return `已切到:${sessionTitle(target) || id.slice(0, 8)}`;
|
|
302
288
|
}
|
|
303
289
|
return ['最近的会话:', ...lines, '', '用 `/sessions <序号>` 切换。'].join('\n');
|
|
@@ -317,6 +303,7 @@ export class StandaloneChat {
|
|
|
317
303
|
#busyMode() {
|
|
318
304
|
return this.#settings().directBusyMode === 'queue' ? 'queue' : 'steer';
|
|
319
305
|
}
|
|
306
|
+
/** 发一段文本;返回是否真的发出去了(没有目标会话或平台报错都算没送到)。 */
|
|
320
307
|
async #reply(text, trace) {
|
|
321
308
|
const settings = this.#settings();
|
|
322
309
|
const footer = settings.replyStatus && trace !== undefined && trace !== null ? statusLine(trace) : '';
|
|
@@ -325,7 +312,7 @@ export class StandaloneChat {
|
|
|
325
312
|
const chatId = this.#chatId !== '' ? this.#chatId : (await this.#owners.get())?.chatId ?? '';
|
|
326
313
|
if (chatId === '') {
|
|
327
314
|
this.#logger.warn?.('独立模式回复没有目标会话,已丢弃');
|
|
328
|
-
return;
|
|
315
|
+
return false;
|
|
329
316
|
}
|
|
330
317
|
const receipt = await this.#outbound.deliver({
|
|
331
318
|
deliveryId: `direct-${this.#now()}-${(this.#sequence += 1)}`,
|
|
@@ -335,7 +322,9 @@ export class StandaloneChat {
|
|
|
335
322
|
});
|
|
336
323
|
if (receipt.errorCode !== undefined) {
|
|
337
324
|
this.#logger.warn?.('独立模式回复没有发出去', receipt.error ?? receipt.errorCode);
|
|
325
|
+
return false;
|
|
338
326
|
}
|
|
327
|
+
return true;
|
|
339
328
|
}
|
|
340
329
|
}
|
|
341
330
|
/** 文字在前、图片在后;附件在独立模式下先只给提示。 */
|
package/locale/en.json
CHANGED
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"register.failed": "Failed to create the app. Please retry.",
|
|
63
63
|
"behavior.title": "Message behavior",
|
|
64
64
|
"behavior.typing": "Working / done reaction",
|
|
65
|
-
"behavior.typingHint": "
|
|
65
|
+
"behavior.typingHint": "Adds a Get (received) reaction on arrival, then appends DONE to the original message only once the reply is actually delivered (queueing does not count); both stay on the message. Lark has no official typing API.",
|
|
66
66
|
"behavior.replyStatus": "Status line in replies",
|
|
67
67
|
"behavior.replyStatusHint": "Model, reasoning effort and duration.",
|
|
68
68
|
"common.save": "Save",
|
package/locale/zh.json
CHANGED
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"register.failed": "创建应用失败,请重试",
|
|
63
63
|
"behavior.title": "消息行为",
|
|
64
64
|
"behavior.typing": "处理状态表情",
|
|
65
|
-
"behavior.typingHint": "
|
|
65
|
+
"behavior.typingHint": "收到消息先打「收到」(Get),回答真正送达后才在原消息追加 DONE(入队不算完成),两个都保留。飞书没有官方输入状态接口。",
|
|
66
66
|
"behavior.replyStatus": "回复末尾显示状态",
|
|
67
67
|
"behavior.replyStatusHint": "附加模型、推理等级与耗时。",
|
|
68
68
|
"common.save": "保存",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-im-lark",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "把飞书(Lark)接入 DeepSeek Harness 的 IM 桥插件",
|
|
6
6
|
"license": "MIT",
|
|
@@ -40,6 +40,8 @@
|
|
|
40
40
|
"cordis.patch.yml",
|
|
41
41
|
"locale/*.json",
|
|
42
42
|
"assets/icon.svg",
|
|
43
|
+
"assets/hero.zh.png",
|
|
44
|
+
"assets/hero.en.png",
|
|
43
45
|
"docs/adr",
|
|
44
46
|
"README.md",
|
|
45
47
|
"LICENSE"
|