@hfyjq/crannia 1.0.0 → 1.1.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/LICENSE +201 -201
- package/NOTICE +45 -45
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON.md +162 -153
- package/THIRD-PARTY.md +316 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +671 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/skill_md.py +676 -676
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +881 -881
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +813 -813
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/auth.py +23 -5
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/config.yaml +2 -2
- package/core/activity.py +3 -0
- package/core/agent_loop.py +390 -55
- package/core/approval.py +17 -6
- package/core/artifacts.py +7 -0
- package/core/auto_review.py +23 -5
- package/core/channel_configs.py +34 -2
- package/core/channel_turns.py +759 -759
- package/core/child_approval.py +150 -0
- package/core/config_requirements.py +205 -0
- package/core/cron/runner.py +118 -6
- package/core/cron/store.py +14 -5
- package/core/cron/tools.py +17 -5
- package/core/endpoint.py +141 -0
- package/core/events.py +23 -0
- package/core/i18n.py +329 -329
- package/core/ice/store.py +191 -191
- package/core/inbound.py +193 -193
- package/core/jobs.py +19 -3
- package/core/last_good.py +150 -150
- package/core/llm_errors.py +227 -227
- package/core/llm_retry.py +230 -230
- package/core/memory/compressor.py +1214 -1214
- package/core/memory/manager.py +14 -0
- package/core/model_configs.py +80 -0
- package/core/pipeline/scheduler.py +2 -2
- package/core/pipeline/stages/agent_loop.py +24 -4
- package/core/pipeline/stages/pre_process.py +58 -7
- package/core/prompt_assembler.py +680 -680
- package/core/rg.py +255 -255
- package/core/security.py +1544 -1544
- package/core/settings_baseline.py +70 -1
- package/core/shell.py +5 -17
- package/core/skill_settings.py +7 -2
- package/core/state_registry.py +19 -0
- package/core/subagent.py +64 -3
- package/core/task_tool.py +1 -1
- package/core/tasks_notify.py +69 -4
- package/core/tiers.py +9 -3
- package/core/tool_outcome.py +108 -0
- package/core/update_tui.py +158 -0
- package/core/version.py +2 -2
- package/core/web_cache.py +152 -0
- package/crannia_tray.py +278 -278
- package/creators/models.json +4 -4
- package/data/settings.example.json +67 -0
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +9 -4
- package/main.py +154 -154
- package/mcpx/manager.py +522 -522
- package/mcpx/servers/__init__.py +22 -22
- package/mcpx/servers/web_search.py +321 -33
- package/package.json +14 -9
- package/providers/anthropic/client.py +772 -772
- package/providers/cost_table.json +3779 -3779
- package/providers/deepseek/client.py +20 -20
- package/providers/deepseek/manifest.yaml +2 -2
- package/providers/factory.py +136 -136
- package/providers/lmstudio/client.py +2 -2
- package/providers/metadata.py +80 -80
- package/providers/model_capabilities.json +6665 -6665
- package/providers/moonshot/client.py +12 -12
- package/providers/ollama/client.py +2 -2
- package/providers/openai/client.py +13 -13
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +144 -144
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/window_table.json +8909 -8909
- package/sbom.json +4413 -4296
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +177 -4
- package/skills/file_parser/manifest.yaml +22 -1
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/github/manifest.yaml +5 -0
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +806 -806
- package/skills/mail_parser/manifest.yaml +5 -0
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +430 -430
- package/skills/media_gen/manifest.yaml +93 -88
- package/skills/office_parser/cell_validation.py +127 -127
- package/skills/office_parser/excel_transform.py +936 -936
- package/skills/office_parser/layout_spec.py +243 -243
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +2909 -2909
- package/tui/crannia.cmd +134 -0
- package/tui/crannia_tui/__init__.py +1 -0
- package/tui/crannia_tui/__main__.py +223 -0
- package/tui/crannia_tui/app.py +1318 -0
- package/tui/crannia_tui/app.tcss +153 -0
- package/tui/crannia_tui/approval.py +85 -0
- package/tui/crannia_tui/backend.py +279 -0
- package/tui/crannia_tui/channel.py +472 -0
- package/tui/crannia_tui/client.py +125 -0
- package/tui/crannia_tui/clipboard.py +62 -0
- package/tui/crannia_tui/commands.py +65 -0
- package/tui/crannia_tui/doctor.py +304 -0
- package/tui/crannia_tui/events.py +84 -0
- package/tui/crannia_tui/headless.py +152 -0
- package/tui/crannia_tui/i18n.py +164 -0
- package/tui/crannia_tui/locales/en.json +263 -0
- package/tui/crannia_tui/outcome.py +62 -0
- package/tui/crannia_tui/paths.py +181 -0
- package/tui/crannia_tui/probe.py +53 -0
- package/tui/crannia_tui/profile.py +169 -0
- package/tui/crannia_tui/render.py +209 -0
- package/tui/crannia_tui/settings.py +134 -0
- package/tui/crannia_tui/setup.py +380 -0
- package/tui/crannia_tui/term.py +116 -0
- package/tui/crannia_tui/ui.py +1236 -0
- package/tui/crannia_tui/update.py +389 -0
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +51 -51
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/package-source.json +19 -19
- package/web/__main__.py +15 -0
- package/web/server.py +168 -19
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
package/core/channel_turns.py
CHANGED
|
@@ -1,759 +1,759 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""通道的「收」与「跑」解耦—— IM 能打断、能 steer 的地基。
|
|
3
|
-
|
|
4
|
-
## 为什么要有它
|
|
5
|
-
|
|
6
|
-
六个通道今天都是 `await scheduler.execute(event)`,而管线的五个阶段文件里
|
|
7
|
-
一个 `await` 都没有(`core/pipeline/stages/*.py`,当场数的),那一轮里
|
|
8
|
-
通道线程的事件循环不回头:下一条消息连"收"都排不进来,`/stop` 同理。
|
|
9
|
-
Web 能打断是因为 waitress 多线程(`/api/stop` 走另一条连接),而 IM 是被动
|
|
10
|
-
推送,没有侧信道。
|
|
11
|
-
|
|
12
|
-
把"谁等这一轮"换掉:接收路径只入队并立刻返回,真正跑轮的是
|
|
13
|
-
每会话一条 worker 线程(自带常驻事件循环 + FIFO 队列)。
|
|
14
|
-
|
|
15
|
-
## 三条承重的判据
|
|
16
|
-
|
|
17
|
-
① worker 的循环必须常驻(`run_forever` + 消费协程),不许用
|
|
18
|
-
`asyncio.run(...)` / `run_until_complete(...)` 一轮一个循环:
|
|
19
|
-
`_sync_approval_timer` 把审批倒计时挂在当时正在跑的那个 loop 上
|
|
20
|
-
(`core/pipeline/scheduler.py:737` + `core/approval_timeout.py:204`),
|
|
21
|
-
而到点那一手是 `asyncio.ensure_future(self.execute(evt))`
|
|
22
|
-
(`scheduler.py:773`)。loop 在轮末就关,IM 的审批超时静默失效
|
|
23
|
-
(症状:一直等,不结算)。消费协程用 `await` 等新活,loop 一直活着。
|
|
24
|
-
|
|
25
|
-
② 每会话 FIFO,不靠锁:`_session_lock_for` 是一把普通
|
|
26
|
-
`threading.Lock`,没有公平性,解耦之后"谁先抢到锁"就是用户看得见的
|
|
27
|
-
乱序(同一会话里两句话被倒着做)。
|
|
28
|
-
|
|
29
|
-
③ 队列键用自然键(`core/session_key.py::session_key_for`):
|
|
30
|
-
`im_routing` 今天在 `execute` 里面才决定"进哪条会话"。私聊恰好就是
|
|
31
|
-
`workspace:private`(与绑定键同一条)、群聊是 `workspace:group:<id>`
|
|
32
|
-
常见情形完全对得上;真的被绑定改派到别的会话时只是过度串行
|
|
33
|
-
(不会错,只是不必要地排队)。
|
|
34
|
-
|
|
35
|
-
## 分流(`intake`,顺序承重)
|
|
36
|
-
|
|
37
|
-
| 判据 | 结果 |
|
|
38
|
-
|---|---|
|
|
39
|
-
| 文本是 `/stop`(只认这一条,`.strip().lower()`,与 `pre_process` 同形) | 立刻 `request_cancel` + 丢弃队列与收件箱 + 回一句;不入队 |
|
|
40
|
-
| 带图 / 文件 / 语音 | 排队(v1 不做附件 steer,同 Web) |
|
|
41
|
-
| `/` 开头 | 排队(命令在 `pre_process` 解析;注入进循环里没人执行它) |
|
|
42
|
-
| 该会话有待审批 | 排队(那句话是审批回答, 的原现场) |
|
|
43
|
-
| 该会话正忙且目标唯一 | 进 `core/steer.py` 收件箱 + ack |
|
|
44
|
-
| 其余 | 排队(前面有活时才 ack —— 没活还 ack 是纯噪声) |
|
|
45
|
-
|
|
46
|
-
## 轮末残留(`steer_leftover`)
|
|
47
|
-
|
|
48
|
-
这一轮没赶上的补话由这里接管(Web 那边是前端用同一口气泡接着跑)。
|
|
49
|
-
两条不许自动接管:被打断的那一轮(用户按了停,别再自己开一轮)、
|
|
50
|
-
停在待审批的那一轮(下一条用户消息是审批回答,不能被一句补话顶掉)。
|
|
51
|
-
|
|
52
|
-
## 残余(写进 ,别读成"做完了")
|
|
53
|
-
|
|
54
|
-
· CLI 不走这里(`input()` 阻塞是它自己的语义,Ctrl+C 就是它的打断);
|
|
55
|
-
· 补话不进 dedup(`pre_process` 那道闸在"轮"里):平台重投一条补话会让
|
|
56
|
-
同一句在上下文里出现两遍 —— 代价是一句话,不是坏一轮;
|
|
57
|
-
· `/clear` 不动 worker(只丢队列):停掉线程等于让挂在上面的审批定时器
|
|
58
|
-
静默失效。线程的回收在 `_evict_idle_locked` —— 条数满了才收,
|
|
59
|
-
且只收"队列空、没在跑、没有审批定时器"的那些;
|
|
60
|
-
· 通道被停掉时排队的那几条还会跑,回话会撞已经关掉的循环,计数 + 出声;
|
|
61
|
-
· 消息里"媒体下载慢"仍可能插队(入队发生在下载之后);纯文字不受影响。
|
|
62
|
-
|
|
63
|
-
ASCII-only 输出(Windows 控制台默认 GBK)。
|
|
64
|
-
"""
|
|
65
|
-
|
|
66
|
-
from __future__ import annotations
|
|
67
|
-
|
|
68
|
-
import asyncio
|
|
69
|
-
import threading
|
|
70
|
-
import time
|
|
71
|
-
import traceback
|
|
72
|
-
import uuid
|
|
73
|
-
from collections import deque
|
|
74
|
-
from typing import Awaitable, Callable, Deque, Dict, Optional
|
|
75
|
-
|
|
76
|
-
from core.i18n import t as tr
|
|
77
|
-
from core.session_key import session_key_for
|
|
78
|
-
|
|
79
|
-
__all__ = ["submit", "intake", "pending", "drop", "purge", "stop", "is_serving",
|
|
80
|
-
"MAX_QUEUE", "MAX_WORKERS"]
|
|
81
|
-
|
|
82
|
-
#: 通道回话的文案(中文原文 = 键,`locales/*.json` 按原文索引)。
|
|
83
|
-
#: 取值处一律 `tr(_COPY[...])`:这几种语言不在这里判,`t()` 一个口子。
|
|
84
|
-
_COPY = {
|
|
85
|
-
# `/stop`:队列里真的还有东西要丢
|
|
86
|
-
"stopped": "已中断,剩余消息已取消",
|
|
87
|
-
# `/stop`:有轮次在跑,但没有排队的
|
|
88
|
-
"stopped_bare": "已中断",
|
|
89
|
-
# `/stop`:什么都没在跑(说"已中断"就是撒谎)
|
|
90
|
-
"idle_stop": "无任务",
|
|
91
|
-
# 补话被收件箱接住(它会在下一次工具批之后进上下文)
|
|
92
|
-
"steer_ok": "正在处理,已收到消息",
|
|
93
|
-
# 排队:`/` 开头的命令
|
|
94
|
-
"queued": "命令信息,等待本轮任务结束后处理",
|
|
95
|
-
# 排队:带附件 / 待审批 / 目标不唯一 —— 都是"收到了,但要等"
|
|
96
|
-
"queued_media": "信息已收到,等待本轮任务结束后处理",
|
|
97
|
-
# 队列满了:这一条没收下(不说就是"发了没反应")
|
|
98
|
-
"queue_full": "消息太多,这条没有排队,请稍后重发",
|
|
99
|
-
# 这一轮抛了(与电报/钉钉原来那句同一份台词,收拢到一处)
|
|
100
|
-
"error": "内部处理异常,请稍后重试。",
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
#: 会话键 → worker。会话级状态,已登记在 `core/state_registry.py`。
|
|
104
|
-
_workers: Dict[str, "_Worker"] = {}
|
|
105
|
-
_lock = threading.Lock()
|
|
106
|
-
|
|
107
|
-
#: 一条会话最多排多少条(不含正在跑的那一条)。
|
|
108
|
-
#: 上限存在的理由不是"怕用户话多":没有上限的队列就是一条内存泄漏 ——
|
|
109
|
-
#: 一轮跑得很久、或者通道被灌时,队列会一直长,而没有任何一处会缩它。
|
|
110
|
-
MAX_QUEUE = 50
|
|
111
|
-
|
|
112
|
-
#: 进程里最多同时养多少条 worker 线程。超了就在建新的之前先收掉最闲的那些。
|
|
113
|
-
#: 它是收敛值,不是硬闸:收不掉的那几条(正在跑)不会被硬等,
|
|
114
|
-
#: 宁可多开一条线程也不丢用户一条消息。下一次新建时会再收一遍。
|
|
115
|
-
MAX_WORKERS = 64
|
|
116
|
-
|
|
117
|
-
#: 收 idle worker 的门槛(秒)。只在"已经到 MAX_WORKERS"时才看它 ——
|
|
118
|
-
#: 没满的时候一条都不收:留着不花钱,收错一次(把挂着审批定时器的那条停了)
|
|
119
|
-
#: 的代价是超时静默失效。
|
|
120
|
-
IDLE_EVICT_S = 1800.0
|
|
121
|
-
|
|
122
|
-
#: `_Worker.push` 的三种结果。"没排上"与"排上了"必须分得开。
|
|
123
|
-
_PUSH_OK = 0
|
|
124
|
-
_PUSH_FULL = 1
|
|
125
|
-
_PUSH_STOPPED = 2
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
# worker:一条会话的执行体
|
|
129
|
-
|
|
130
|
-
class _Worker:
|
|
131
|
-
"""常驻 loop + FIFO 队列。每条会话一个(同会话串行、跨会话并行)。"""
|
|
132
|
-
|
|
133
|
-
def __init__(self, session_key: str) -> None:
|
|
134
|
-
self.key = session_key
|
|
135
|
-
self._q: Deque[Callable[[], Awaitable[None]]] = deque()
|
|
136
|
-
self._lock = threading.Lock()
|
|
137
|
-
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
|
138
|
-
self._wake: Optional[asyncio.Event] = None
|
|
139
|
-
self._started = threading.Event()
|
|
140
|
-
self._stopped = False
|
|
141
|
-
#: 上一次开始干活 / 入队的时刻(收 idle worker 用)。
|
|
142
|
-
self.last_active = time.monotonic()
|
|
143
|
-
self.running = False
|
|
144
|
-
self._thread = threading.Thread(
|
|
145
|
-
target=self._run, name="turn-%s" % _short_key(session_key),
|
|
146
|
-
daemon=True)
|
|
147
|
-
self._thread.start()
|
|
148
|
-
#: 5 秒是防死等:起不来时 `submit` 仍能入队,loop 起来之后自己会消费。
|
|
149
|
-
self._started.wait(5.0)
|
|
150
|
-
|
|
151
|
-
# ---- 任意线程 ----
|
|
152
|
-
def push(self, job: Callable[[], Awaitable[None]]) -> int:
|
|
153
|
-
"""入队。返回 `_PUSH_OK` / `_PUSH_FULL` / `_PUSH_STOPPED`。
|
|
154
|
-
|
|
155
|
-
"没排上"必须是一种能看见的结果:静默丢一条,用户看到的是
|
|
156
|
-
"发了没反应",与"消息没进来"同形。
|
|
157
|
-
"""
|
|
158
|
-
with self._lock:
|
|
159
|
-
if self._stopped:
|
|
160
|
-
return _PUSH_STOPPED
|
|
161
|
-
if len(self._q) >= MAX_QUEUE:
|
|
162
|
-
return _PUSH_FULL
|
|
163
|
-
self._q.append(job)
|
|
164
|
-
self.last_active = time.monotonic()
|
|
165
|
-
self._kick()
|
|
166
|
-
return _PUSH_OK
|
|
167
|
-
|
|
168
|
-
def clear(self) -> int:
|
|
169
|
-
"""丢掉还没开始跑的那几条,返回条数(正在跑的那轮不动)。"""
|
|
170
|
-
with self._lock:
|
|
171
|
-
n = len(self._q)
|
|
172
|
-
self._q.clear()
|
|
173
|
-
return n
|
|
174
|
-
|
|
175
|
-
def depth(self) -> int:
|
|
176
|
-
with self._lock:
|
|
177
|
-
return len(self._q)
|
|
178
|
-
|
|
179
|
-
def stopped(self) -> bool:
|
|
180
|
-
return self._stopped
|
|
181
|
-
|
|
182
|
-
def idle_for(self) -> float:
|
|
183
|
-
"""闲了多久(秒);有活在跑或排着就是 0。"""
|
|
184
|
-
if self.running or self.depth():
|
|
185
|
-
return 0.0
|
|
186
|
-
return time.monotonic() - self.last_active
|
|
187
|
-
|
|
188
|
-
def stop(self) -> bool:
|
|
189
|
-
"""停掉这条 worker。队列空、没在跑才停(返回 False 表示还忙着)。
|
|
190
|
-
|
|
191
|
-
停的是它那条常驻循环 -> 挂在上面的审批定时器一起没了。
|
|
192
|
-
所以调用方只有两个:`_evict_idle_locked`(已确认没有待审批)
|
|
193
|
-
与 `stop()`(显式销毁)。
|
|
194
|
-
"""
|
|
195
|
-
with self._lock:
|
|
196
|
-
if self._stopped:
|
|
197
|
-
return True
|
|
198
|
-
if self._q or self.running:
|
|
199
|
-
return False
|
|
200
|
-
self._stopped = True
|
|
201
|
-
loop = self._loop
|
|
202
|
-
if loop is not None:
|
|
203
|
-
try:
|
|
204
|
-
loop.call_soon_threadsafe(loop.stop)
|
|
205
|
-
except RuntimeError:
|
|
206
|
-
pass # 循环已经关了
|
|
207
|
-
return True
|
|
208
|
-
|
|
209
|
-
def _kick(self) -> None:
|
|
210
|
-
loop = self._loop
|
|
211
|
-
if loop is None:
|
|
212
|
-
return # 还没起来:起来之后 `_consume` 自己会看队列
|
|
213
|
-
try:
|
|
214
|
-
loop.call_soon_threadsafe(self._signal)
|
|
215
|
-
except RuntimeError:
|
|
216
|
-
pass # 循环已关(进程收尾)
|
|
217
|
-
|
|
218
|
-
def _signal(self) -> None:
|
|
219
|
-
if self._wake is not None:
|
|
220
|
-
self._wake.set()
|
|
221
|
-
|
|
222
|
-
# ---- 本线程(常驻 loop)----
|
|
223
|
-
def _run(self) -> None:
|
|
224
|
-
loop = asyncio.new_event_loop()
|
|
225
|
-
asyncio.set_event_loop(loop)
|
|
226
|
-
#: 先建 `Event` 再起消费协程 —— 反过来的话,`_started` 之后那一小段里
|
|
227
|
-
#: 推来的活会撞上 `_wake is None`(信号被丢掉,队列要靠下一次推才动)。
|
|
228
|
-
self._wake = asyncio.Event()
|
|
229
|
-
self._loop = loop
|
|
230
|
-
loop.create_task(self._consume())
|
|
231
|
-
self._started.set()
|
|
232
|
-
try:
|
|
233
|
-
loop.run_forever()
|
|
234
|
-
finally:
|
|
235
|
-
#: 停的时候把还挂在循环上的协程收掉再关 —— 直接 `close()` 会留一条
|
|
236
|
-
#: "Task was destroyed but it is pending" 的噪声(它长得像故障)。
|
|
237
|
-
try:
|
|
238
|
-
pending = asyncio.all_tasks(loop)
|
|
239
|
-
for task in pending:
|
|
240
|
-
task.cancel()
|
|
241
|
-
if pending:
|
|
242
|
-
loop.run_until_complete(
|
|
243
|
-
asyncio.gather(*pending, return_exceptions=True))
|
|
244
|
-
except Exception: # noqa: BLE001
|
|
245
|
-
pass
|
|
246
|
-
loop.close()
|
|
247
|
-
|
|
248
|
-
async def _consume(self) -> None:
|
|
249
|
-
"""就在这里 `await` 每一条活:轮次因此跑在这个常驻循环上
|
|
250
|
-
(判据 ①:审批倒计时挂的正是它)。"""
|
|
251
|
-
wake = self._wake
|
|
252
|
-
if wake is None: # 到不了:`_run` 先建它
|
|
253
|
-
wake = self._wake = asyncio.Event()
|
|
254
|
-
while True:
|
|
255
|
-
await wake.wait()
|
|
256
|
-
wake.clear()
|
|
257
|
-
while True:
|
|
258
|
-
with self._lock:
|
|
259
|
-
job = self._q.popleft() if self._q else None
|
|
260
|
-
if job is None:
|
|
261
|
-
break
|
|
262
|
-
self.running = True
|
|
263
|
-
self.last_active = time.monotonic()
|
|
264
|
-
try:
|
|
265
|
-
await job()
|
|
266
|
-
except Exception: # noqa: BLE001
|
|
267
|
-
#: 一条活炸了不许把消费协程带走(那会让整条会话永久卡死,
|
|
268
|
-
#: 而症状是"发消息没反应" —— 与"没收到"同形)。
|
|
269
|
-
traceback.print_exc()
|
|
270
|
-
finally:
|
|
271
|
-
self.running = False
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
def _short_key(session_key: str) -> str:
|
|
275
|
-
"""线程名用的短键(ASCII,同会话一眼能认出来)。"""
|
|
276
|
-
return (session_key.rsplit(":", 1)[-1] or "x")[:24]
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
def _has_pending_approval(key: str) -> bool:
|
|
280
|
-
"""这条会话还有审批倒计时挂着吗(挂着的 worker 不许收)。"""
|
|
281
|
-
try:
|
|
282
|
-
from core import approval_timeout as _AT
|
|
283
|
-
return _AT.event_of(key) is not None
|
|
284
|
-
except Exception: # noqa: BLE001
|
|
285
|
-
return True # 读不到就当有 —— 宁可多留一条线程
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
def _evict_idle_locked() -> int:
|
|
289
|
-
"""收掉最闲的几条 worker(调用方持 `_lock`)。返回收掉的条数。
|
|
290
|
-
|
|
291
|
-
三条判据缺一不可:队列空、没在跑、没有审批定时器。
|
|
292
|
-
第三条是"worker 不回收"那条老规矩剩下的部分 —— 定时器挂在 worker 的
|
|
293
|
-
常驻循环上,停了它就是超时静默失效。
|
|
294
|
-
"""
|
|
295
|
-
idle = []
|
|
296
|
-
for key, w in list(_workers.items()):
|
|
297
|
-
if w.stopped():
|
|
298
|
-
idle.append((float("inf"), key))
|
|
299
|
-
continue
|
|
300
|
-
gap = w.idle_for()
|
|
301
|
-
if gap < IDLE_EVICT_S or _has_pending_approval(key):
|
|
302
|
-
continue
|
|
303
|
-
idle.append((gap, key))
|
|
304
|
-
idle.sort(reverse=True) # 最闲的在前
|
|
305
|
-
n = 0
|
|
306
|
-
for _, key in idle:
|
|
307
|
-
w = _workers.get(key)
|
|
308
|
-
if w is None:
|
|
309
|
-
continue
|
|
310
|
-
if w.stop() and w.stopped():
|
|
311
|
-
_workers.pop(key, None)
|
|
312
|
-
n += 1
|
|
313
|
-
return n
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
def _worker_for(session_key: str) -> "_Worker":
|
|
317
|
-
with _lock:
|
|
318
|
-
w = _workers.get(session_key)
|
|
319
|
-
if w is not None and not w.stopped():
|
|
320
|
-
return w
|
|
321
|
-
if w is not None:
|
|
322
|
-
_workers.pop(session_key, None) # 已停的那条换掉
|
|
323
|
-
if len(_workers) >= MAX_WORKERS:
|
|
324
|
-
_evict_idle_locked()
|
|
325
|
-
w = _Worker(session_key)
|
|
326
|
-
_workers[session_key] = w
|
|
327
|
-
return w
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
# 公共入口
|
|
331
|
-
|
|
332
|
-
def submit(session_key: str, job: Callable[[], Awaitable[None]]) -> bool:
|
|
333
|
-
"""把一条活排到这条会话的队尾。任意线程可调,立刻返回。
|
|
334
|
-
|
|
335
|
-
返回"排上了吗":队列满时是 `False`。调用方必须把它说出来 ——
|
|
336
|
-
静默丢一条与"消息没进来"在用户眼里完全一样。
|
|
337
|
-
"""
|
|
338
|
-
if not session_key or job is None:
|
|
339
|
-
return False
|
|
340
|
-
key = str(session_key)
|
|
341
|
-
for _ in range(3):
|
|
342
|
-
w = _worker_for(key)
|
|
343
|
-
state = w.push(job)
|
|
344
|
-
if state == _PUSH_OK:
|
|
345
|
-
return True
|
|
346
|
-
if state == _PUSH_FULL:
|
|
347
|
-
return False
|
|
348
|
-
# 已停(正好被收掉):换一条再来
|
|
349
|
-
return False
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
def pending(session_key: str) -> int:
|
|
353
|
-
"""队列里还没开始跑的条数(不含正在跑的那条)。"""
|
|
354
|
-
with _lock:
|
|
355
|
-
w = _workers.get(session_key)
|
|
356
|
-
return w.depth() if w is not None else 0
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
def is_serving(session_key: str) -> bool:
|
|
360
|
-
"""这条会话有 worker 吗(自检 / 日志用;不是"有活")。"""
|
|
361
|
-
with _lock:
|
|
362
|
-
return session_key in _workers
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
def drop(session_key: str) -> int:
|
|
366
|
-
"""丢掉这条会话排队的那几条,返回条数。"""
|
|
367
|
-
with _lock:
|
|
368
|
-
w = _workers.get(session_key)
|
|
369
|
-
return w.clear() if w is not None else 0
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
def purge(session_key: str) -> None:
|
|
373
|
-
"""`/clear` 走这里:把这条会话排队的那几条丢掉,worker 留着。
|
|
374
|
-
|
|
375
|
-
不停线程、也不动正在跑的那一轮(`/clear` 本来就是那一轮自己)。
|
|
376
|
-
停掉线程会让挂在它常驻循环上的审批倒计时静默失效 —— 回收是
|
|
377
|
-
`_evict_idle_locked` 的事:条数满了才收,且只收闲着的。
|
|
378
|
-
"""
|
|
379
|
-
with _lock:
|
|
380
|
-
w = _workers.get(str(session_key or ""))
|
|
381
|
-
if w is not None:
|
|
382
|
-
w.clear()
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
def stop(session_key: str) -> bool:
|
|
386
|
-
"""销毁一条 worker(显式停通道 / 进程收尾用)。`/clear` 不走这里。
|
|
387
|
-
|
|
388
|
-
返回"停掉了吗":队列里还有活、或者正在跑,就返回 `False`(那条活该跑完)。
|
|
389
|
-
"""
|
|
390
|
-
key = str(session_key or "")
|
|
391
|
-
with _lock:
|
|
392
|
-
w = _workers.get(key)
|
|
393
|
-
if w is None:
|
|
394
|
-
return True
|
|
395
|
-
if not w.stop() or not w.stopped():
|
|
396
|
-
return False
|
|
397
|
-
_workers.pop(key, None)
|
|
398
|
-
return True
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
# 接收路径:分流
|
|
402
|
-
|
|
403
|
-
async def intake(channel, event, *, on_reply=None) -> None:
|
|
404
|
-
"""接收路径的唯一入口:分流 + 入队 + 必要时回一句,然后立刻返回。
|
|
405
|
-
|
|
406
|
-
*on_reply* 是"这一轮的回答怎么发回去"的协程函数(`str -> awaitable`):
|
|
407
|
-
电报 / 微信走它(它们的回答是 `execute` 的返回值),飞书 / 钉钉给 `None`
|
|
408
|
-
(它们自己的 `reply_callback` 已经把回话发掉了)。
|
|
409
|
-
"""
|
|
410
|
-
session = getattr(event, "session", None)
|
|
411
|
-
key = session_key_for(session)
|
|
412
|
-
sch = getattr(channel, "_scheduler", None)
|
|
413
|
-
if sch is None or not key:
|
|
414
|
-
print("[im] 没有 scheduler 或没有会话键,这条消息丢掉")
|
|
415
|
-
return
|
|
416
|
-
loop = asyncio.get_running_loop()
|
|
417
|
-
text = str(getattr(getattr(event, "message", None), "content", "") or "").strip()
|
|
418
|
-
|
|
419
|
-
# ① `/stop`:在拿锁之前分流
|
|
420
|
-
if text.lower() == "/stop":
|
|
421
|
-
if _handle_stop(key):
|
|
422
|
-
await _note(channel, session, tr(_COPY["stopped"]), event)
|
|
423
|
-
elif _queue_ahead(sch, key):
|
|
424
|
-
await _note(channel, session, tr(_COPY["stopped_bare"]), event)
|
|
425
|
-
else:
|
|
426
|
-
await _note(channel, session, tr(_COPY["idle_stop"]), event)
|
|
427
|
-
return
|
|
428
|
-
|
|
429
|
-
ahead = _queue_ahead(sch, key)
|
|
430
|
-
|
|
431
|
-
# ② 可 steer 吗
|
|
432
|
-
if ahead and text and _steerable(event, sch, key, text):
|
|
433
|
-
item_id = _msg_id(event)
|
|
434
|
-
if _push_steer(key, item_id, text):
|
|
435
|
-
#: 推完再确认一次在不在跑:轮末与这一推之间有一道缝,
|
|
436
|
-
#: 错过它这条会一直躺在收件箱里(没人再取)。自己摘回来当普通消息跑。
|
|
437
|
-
if not _busy(sch, key):
|
|
438
|
-
from core import steer as _steer
|
|
439
|
-
if _steer.drop(key, item_id):
|
|
440
|
-
if not submit(key, _turn_job(channel, event, on_reply, loop)):
|
|
441
|
-
await _note(channel, session,
|
|
442
|
-
tr(_COPY["queue_full"]), event)
|
|
443
|
-
return
|
|
444
|
-
#: 两条出口都回一句 —— 这条已经被收下了,不回就成了"发完没反应"。
|
|
445
|
-
await _note(channel, session, tr(_COPY["steer_ok"]), event)
|
|
446
|
-
return
|
|
447
|
-
|
|
448
|
-
# ③ 排队
|
|
449
|
-
if not submit(key, _turn_job(channel, event, on_reply, loop)):
|
|
450
|
-
#: 队列满了:这一条没收下。不说就是"发了没反应"。
|
|
451
|
-
await _note(channel, session, tr(_COPY["queue_full"]), event)
|
|
452
|
-
return
|
|
453
|
-
if ahead:
|
|
454
|
-
note = (_COPY["queued"] if text.startswith("/")
|
|
455
|
-
else _COPY["queued_media"])
|
|
456
|
-
await _note(channel, session, tr(note), event)
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
def _busy(sch, key: str) -> bool:
|
|
460
|
-
try:
|
|
461
|
-
return bool(sch.is_busy(key))
|
|
462
|
-
except Exception: # noqa: BLE001
|
|
463
|
-
return False
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
def _queue_ahead(sch, key: str) -> bool:
|
|
467
|
-
"""前面还有活吗(正在跑的一轮,或者队里排着的)。"""
|
|
468
|
-
return _busy(sch, key) or pending(key) > 0
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
def _handle_stop(key: str) -> bool:
|
|
472
|
-
"""`/stop`:打断本轮 + 丢弃队列与收件箱。
|
|
473
|
-
|
|
474
|
-
返回"这次真的丢了东西吗"(决定回哪一句 —— 一句"剩余消息已取消"在
|
|
475
|
-
什么都没取消的时候就是撒谎,这一类)。
|
|
476
|
-
"""
|
|
477
|
-
from core.cancellation import request_cancel
|
|
478
|
-
request_cancel(key)
|
|
479
|
-
#: 在正在跑的那一轮的事件上打个标记:这一轮收尾时框架那句固定的
|
|
480
|
-
#: 「已打断,需要 … 怎么做?」不再发一遍 —— `intake` 已经当场回过
|
|
481
|
-
#: 「已中断」了,两句说一件事。
|
|
482
|
-
#: 不新增任何状态:`approval_timeout` 记的就是那条真事件(同一个对象),
|
|
483
|
-
#: 标记挂在它身上,随这一轮一起消失。
|
|
484
|
-
#: Web 那头按的打断不打这个标记,那句话照发(那是 IM 用户唯一的信息)。
|
|
485
|
-
try:
|
|
486
|
-
from core import approval_timeout as _AT
|
|
487
|
-
_ev = _AT.event_of(key)
|
|
488
|
-
if _ev is not None and getattr(_ev, "extras", None) is not None:
|
|
489
|
-
_ev.extras["im_stop_ack"] = True
|
|
490
|
-
except Exception as exc: # noqa: BLE001
|
|
491
|
-
print("[im] 打 /stop 标记失败(%s: %s)" % (type(exc).__name__, exc))
|
|
492
|
-
dropped = drop(key)
|
|
493
|
-
try:
|
|
494
|
-
from core import steer as _steer
|
|
495
|
-
dropped += _steer.pending(key)
|
|
496
|
-
_steer.clear(key)
|
|
497
|
-
except Exception as exc: # noqa: BLE001
|
|
498
|
-
print("[im] 清收件箱失败(%s: %s)" % (type(exc).__name__, exc))
|
|
499
|
-
return bool(dropped)
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
def _steerable(event, sch, key: str, text: str) -> bool:
|
|
503
|
-
"""能不能把这句话塞进正在跑的那一轮(五条判据,与 `/api/steer` 同源)。"""
|
|
504
|
-
if text.startswith("/"):
|
|
505
|
-
return False # 命令:注入进循环没人执行
|
|
506
|
-
chain = getattr(getattr(event, "message", None), "message_chain", None)
|
|
507
|
-
try:
|
|
508
|
-
from channels.message import File, Image, Voice
|
|
509
|
-
if any(isinstance(c, (Image, File, Voice))
|
|
510
|
-
for c in (getattr(chain, "components", None) or [])):
|
|
511
|
-
return False # 附件:v1 不注入
|
|
512
|
-
except Exception: # noqa: BLE001
|
|
513
|
-
return False
|
|
514
|
-
try:
|
|
515
|
-
if sch.pending_approval(key) is not None:
|
|
516
|
-
return False # 那句话是审批回答
|
|
517
|
-
except Exception: # noqa: BLE001
|
|
518
|
-
return False
|
|
519
|
-
return _target_is_unambiguous(event, sch)
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
def _target_is_unambiguous(event, sch) -> bool:
|
|
523
|
-
"""这条消息要进哪条会话 —— 判不出来就不 steer(fail-closed)。
|
|
524
|
-
|
|
525
|
-
`im_routing` 有多条活跃会话又没有认领时会问编号;那时把补话塞进
|
|
526
|
-
"碰巧在忙的那条"就是替用户猜。判据全在 `core/im_routing.py`,这里只读。
|
|
527
|
-
"""
|
|
528
|
-
try:
|
|
529
|
-
from core import im_routing
|
|
530
|
-
chan = im_routing.channel_key_of(getattr(event, "session", None))
|
|
531
|
-
if im_routing.bound_session_key(chan):
|
|
532
|
-
return True
|
|
533
|
-
snap = sch.activity_snapshot() if hasattr(sch, "activity_snapshot") else {}
|
|
534
|
-
return len(im_routing.hot_sessions(snap, time.monotonic())) <= 1
|
|
535
|
-
except Exception as exc: # noqa: BLE001
|
|
536
|
-
print("[im] 目标会话判不出来(%s: %s)—— 这条不 steer"
|
|
537
|
-
% (type(exc).__name__, exc))
|
|
538
|
-
return False
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
def _push_steer(key: str, item_id: str, text: str) -> bool:
|
|
542
|
-
try:
|
|
543
|
-
from core import steer as _steer
|
|
544
|
-
_steer.push(key, {"id": item_id, "text": text})
|
|
545
|
-
return True
|
|
546
|
-
except Exception as exc: # noqa: BLE001
|
|
547
|
-
print("[im] 补话没塞进收件箱(%s: %s)—— 这条按普通消息排队"
|
|
548
|
-
% (type(exc).__name__, exc))
|
|
549
|
-
return False
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
def _msg_id(event) -> str:
|
|
553
|
-
"""补话的 id:优先用平台消息号(重投时对得上),没有就现造一个。"""
|
|
554
|
-
mid = str(getattr(getattr(event, "message", None), "message_id", "") or "")
|
|
555
|
-
return mid or ("im-" + uuid.uuid4().hex[:12])
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
# 执行体:跑一轮 + 发回答 + 接管轮末残留
|
|
559
|
-
|
|
560
|
-
def _is_cancel_line(text: str) -> bool:
|
|
561
|
-
"""这句是不是框架自己的取消收尾(不是模型说的话)。"""
|
|
562
|
-
try:
|
|
563
|
-
from core.agent_loop import CANCEL_REPLY
|
|
564
|
-
except Exception: # noqa: BLE001
|
|
565
|
-
return False
|
|
566
|
-
t = str(text or "").strip()
|
|
567
|
-
return bool(t) and t == CANCEL_REPLY
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
def _suppress_cancel_line(ev, text: str) -> bool:
|
|
571
|
-
"""IM 按的 `/stop`:框架那句固定的收尾不再发一遍。
|
|
572
|
-
|
|
573
|
-
判据是这句话本身 + 事件上的标记(不读 `extras["cancelled"]`:
|
|
574
|
-
管线调 `reply_callback` 的时刻早于它写那一格 —— 读它永远是 False)。
|
|
575
|
-
"""
|
|
576
|
-
extras = getattr(ev, "extras", None) or {}
|
|
577
|
-
return bool(extras.get("im_stop_ack")) and _is_cancel_line(text)
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
def _wrap_reply_for_stop(ev) -> None:
|
|
581
|
-
"""给 `reply_callback`(飞书 / 钉钉那条路)套一层:只丢那句取消收尾,文件照发。"""
|
|
582
|
-
orig = getattr(ev, "reply_callback", None)
|
|
583
|
-
if orig is None or getattr(orig, "_im_stop_wrapped", False):
|
|
584
|
-
return
|
|
585
|
-
|
|
586
|
-
def _cb(e):
|
|
587
|
-
try:
|
|
588
|
-
if _suppress_cancel_line(e, (getattr(e, "extras", None) or {}).get("response")):
|
|
589
|
-
e.extras["response"] = ""
|
|
590
|
-
except Exception: # noqa: BLE001
|
|
591
|
-
pass
|
|
592
|
-
orig(e)
|
|
593
|
-
|
|
594
|
-
_cb._im_stop_wrapped = True
|
|
595
|
-
ev.reply_callback = _cb
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
def _turn_job(channel, event, on_reply, loop) -> Callable[[], Awaitable[None]]:
|
|
599
|
-
async def _job() -> None:
|
|
600
|
-
await _run_turn(channel, event, on_reply, loop)
|
|
601
|
-
return _job
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
async def _run_turn(channel, event, on_reply, loop) -> None:
|
|
605
|
-
"""在这个会话的 worker 循环上跑一轮;没赶上的补话接着跑。"""
|
|
606
|
-
sch = getattr(channel, "_scheduler", None)
|
|
607
|
-
if sch is None:
|
|
608
|
-
return
|
|
609
|
-
ev = event
|
|
610
|
-
while True:
|
|
611
|
-
_wrap_reply_for_stop(ev)
|
|
612
|
-
try:
|
|
613
|
-
resp = await sch.execute(ev)
|
|
614
|
-
except Exception as exc: # noqa: BLE001
|
|
615
|
-
print("[im] 这一轮抛了(%s: %s)" % (type(exc).__name__, exc))
|
|
616
|
-
traceback.print_exc()
|
|
617
|
-
err = tr(_COPY["error"])
|
|
618
|
-
if on_reply is not None:
|
|
619
|
-
await _hop(loop, on_reply(err))
|
|
620
|
-
else:
|
|
621
|
-
#: 飞书 / 钉钉没有 `on_reply`(回答走 `reply_callback`,而异常不
|
|
622
|
-
#: 走那条路),这里补一句人话,仍然走通道自己的回调
|
|
623
|
-
#: (钉钉要靠它拿 `session_webhook`,换成 `send()` 会发不出去)。
|
|
624
|
-
_cb = getattr(ev, "reply_callback", None)
|
|
625
|
-
if _cb is not None:
|
|
626
|
-
try:
|
|
627
|
-
ev.extras["response"] = err
|
|
628
|
-
_cb(ev)
|
|
629
|
-
except Exception: # noqa: BLE001
|
|
630
|
-
pass
|
|
631
|
-
else:
|
|
632
|
-
await _hop(loop, _send_note(channel, ev.session, err, ev))
|
|
633
|
-
return
|
|
634
|
-
text = str(resp or "")
|
|
635
|
-
if _suppress_cancel_line(ev, text):
|
|
636
|
-
#: 当场已经回过「已中断」了 —— 这句只丢文字,文件照发。
|
|
637
|
-
text = ""
|
|
638
|
-
if on_reply is not None:
|
|
639
|
-
await _hop(loop, on_reply(text))
|
|
640
|
-
elif (ev.extras or {}).get("steer_leftover_turn"):
|
|
641
|
-
#: 合成事件没有 `reply_callback`(那是给原渠道那条消息用的),
|
|
642
|
-
#: 它的回话走"主动投递"这条路 —— 与定时任务 / 后台回报同一格。
|
|
643
|
-
await _hop(loop, _send_note(channel, ev.session, text, ev))
|
|
644
|
-
nxt = _leftover_event(ev)
|
|
645
|
-
if nxt is None:
|
|
646
|
-
return
|
|
647
|
-
ev = nxt
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
#: 把回话投到通道循环上的等待上限(秒)。
|
|
651
|
-
#:
|
|
652
|
-
#: 必须有上限:通道被停掉时(`/api/channel/stop` → `loop.stop()` + `close()`)
|
|
653
|
-
#: 一个已经提交上去、却永远轮不到的协程会让这条会话的 worker 永久卡住
|
|
654
|
-
#: (同会话后面每一条消息都排在一个死掉的 hop 后面)。实际症状:`_hop` 一直
|
|
655
|
-
#: `await`,而通道那边什么都不发生 —— "发消息没反应"。
|
|
656
|
-
#: 60 秒远大于任何一次正常回话(上传附件+发文字)。
|
|
657
|
-
_HOP_TIMEOUT_S = 60.0
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
async def _hop(loop, coro) -> None:
|
|
661
|
-
"""把 *coro* 投到通道自己的循环上跑完(客户端绑在那上面,别新造循环)。"""
|
|
662
|
-
if loop is None or loop.is_closed():
|
|
663
|
-
try:
|
|
664
|
-
coro.close()
|
|
665
|
-
except Exception: # noqa: BLE001
|
|
666
|
-
pass
|
|
667
|
-
print("[im] 通道的循环已经关了,这条回话发不出去")
|
|
668
|
-
return
|
|
669
|
-
try:
|
|
670
|
-
fut = asyncio.run_coroutine_threadsafe(coro, loop)
|
|
671
|
-
except Exception as exc: # noqa: BLE001
|
|
672
|
-
try:
|
|
673
|
-
coro.close()
|
|
674
|
-
except Exception: # noqa: BLE001
|
|
675
|
-
pass
|
|
676
|
-
print("[im] 回话投递失败(%s: %s)" % (type(exc).__name__, exc))
|
|
677
|
-
return
|
|
678
|
-
try:
|
|
679
|
-
await asyncio.wait_for(asyncio.wrap_future(fut), timeout=_HOP_TIMEOUT_S)
|
|
680
|
-
except asyncio.TimeoutError:
|
|
681
|
-
#: 取消不一定能取消对面那个协程(它在另一个循环上),但至少
|
|
682
|
-
#: 这一条 worker 不会永远卡住 —— 卡住比"少发一句话"贵得多。
|
|
683
|
-
fut.cancel()
|
|
684
|
-
print("[im] 回话投递超时(%.0fs)—— 通道可能已经停了" % _HOP_TIMEOUT_S)
|
|
685
|
-
except Exception as exc: # noqa: BLE001
|
|
686
|
-
print("[im] 回话投递失败(%s: %s)" % (type(exc).__name__, exc))
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
async def _send_note(channel, session, text: str, event=None) -> bool:
|
|
690
|
-
fn = getattr(channel, "send_note", None) or getattr(channel, "send", None)
|
|
691
|
-
if fn is None or not str(text or "").strip():
|
|
692
|
-
return False
|
|
693
|
-
try:
|
|
694
|
-
return bool(await fn(session, text, event=event))
|
|
695
|
-
except Exception as exc: # noqa: BLE001
|
|
696
|
-
print("[im] 旁白没发出去(%s: %s)" % (type(exc).__name__, exc))
|
|
697
|
-
return False
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
async def _note(channel, session, text: str, event=None) -> None:
|
|
701
|
-
"""接收路径上的旁白(ack / 已中断)—— 不许弄挂收消息。
|
|
702
|
-
|
|
703
|
-
*event* 是触发它的那条消息:钉钉要靠它的 `session_webhook` 才发得出去。
|
|
704
|
-
"""
|
|
705
|
-
ok = await _send_note(channel, session, text, event=event)
|
|
706
|
-
if not ok:
|
|
707
|
-
#: 不静默:旁白发不出去时用户以为"它没理我",而这与"消息没进来"同形。
|
|
708
|
-
print("[im] 旁白未送达(%s)" % _short_key(str(getattr(session, "session_id", "") or "")))
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
def _leftover_event(ev):
|
|
712
|
-
"""这一轮没赶上的补话,一条合成事件(接着跑一轮);没有就 `None`。"""
|
|
713
|
-
extras = getattr(ev, "extras", None) or {}
|
|
714
|
-
if extras.get("cancelled") or extras.get("awaiting_approval"):
|
|
715
|
-
return None
|
|
716
|
-
items = list(extras.get("steer_leftover") or [])
|
|
717
|
-
key = str(extras.get("routed_session_key") or "") or session_key_for(
|
|
718
|
-
getattr(ev, "session", None))
|
|
719
|
-
#: 再取一次:轮末的 drain 与这里之间还有一道缝(推在 drain 之后的那条)。
|
|
720
|
-
try:
|
|
721
|
-
from core import steer as _steer
|
|
722
|
-
items += _steer.drain(key)
|
|
723
|
-
except Exception as exc: # noqa: BLE001
|
|
724
|
-
print("[im] 取残留补话失败(%s: %s)" % (type(exc).__name__, exc))
|
|
725
|
-
text = "\n".join(str(i.get("text") or "").strip()
|
|
726
|
-
for i in items if str(i.get("text") or "").strip())
|
|
727
|
-
if not text.strip():
|
|
728
|
-
return None
|
|
729
|
-
return _synthetic_event(ev, key, text)
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
def _synthetic_event(ev, key: str, text: str):
|
|
733
|
-
"""照 `core/tasks_notify.py` 的形状造一条用户口吻的事件。
|
|
734
|
-
|
|
735
|
-
不带 `origin`(`background` / `cron` 会被落成 `kind=framework_note`)——
|
|
736
|
-
这几句是用户自己说的,界面上该长成用户气泡。
|
|
737
|
-
带 `routed_session_key`,`im_routing.route()` 直接放过(不再问一句"进哪条会话")。
|
|
738
|
-
"""
|
|
739
|
-
from channels.base import ChannelMetadata, Message as ChannelMessage, MessageEvent
|
|
740
|
-
from channels.message import MessageChain
|
|
741
|
-
|
|
742
|
-
session = ev.session
|
|
743
|
-
msg = ChannelMessage(
|
|
744
|
-
sender_id=str(getattr(getattr(ev, "message", None), "sender_id", "") or ""),
|
|
745
|
-
message_chain=MessageChain.from_text(text),
|
|
746
|
-
sender_name=str(getattr(getattr(ev, "message", None), "sender_name", "") or ""),
|
|
747
|
-
message_type=session.message_type,
|
|
748
|
-
session=session,
|
|
749
|
-
)
|
|
750
|
-
return MessageEvent(
|
|
751
|
-
session=session,
|
|
752
|
-
message=msg,
|
|
753
|
-
platform_meta=ChannelMetadata(
|
|
754
|
-
name=str(getattr(getattr(ev, "platform_meta", None), "name", "") or "im"),
|
|
755
|
-
description="steer leftover",
|
|
756
|
-
platform_type=str(getattr(session, "platform", "") or ""),
|
|
757
|
-
),
|
|
758
|
-
extras={"routed_session_key": key, "steer_leftover_turn": True},
|
|
759
|
-
)
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""通道的「收」与「跑」解耦—— IM 能打断、能 steer 的地基。
|
|
3
|
+
|
|
4
|
+
## 为什么要有它
|
|
5
|
+
|
|
6
|
+
六个通道今天都是 `await scheduler.execute(event)`,而管线的五个阶段文件里
|
|
7
|
+
一个 `await` 都没有(`core/pipeline/stages/*.py`,当场数的),那一轮里
|
|
8
|
+
通道线程的事件循环不回头:下一条消息连"收"都排不进来,`/stop` 同理。
|
|
9
|
+
Web 能打断是因为 waitress 多线程(`/api/stop` 走另一条连接),而 IM 是被动
|
|
10
|
+
推送,没有侧信道。
|
|
11
|
+
|
|
12
|
+
把"谁等这一轮"换掉:接收路径只入队并立刻返回,真正跑轮的是
|
|
13
|
+
每会话一条 worker 线程(自带常驻事件循环 + FIFO 队列)。
|
|
14
|
+
|
|
15
|
+
## 三条承重的判据
|
|
16
|
+
|
|
17
|
+
① worker 的循环必须常驻(`run_forever` + 消费协程),不许用
|
|
18
|
+
`asyncio.run(...)` / `run_until_complete(...)` 一轮一个循环:
|
|
19
|
+
`_sync_approval_timer` 把审批倒计时挂在当时正在跑的那个 loop 上
|
|
20
|
+
(`core/pipeline/scheduler.py:737` + `core/approval_timeout.py:204`),
|
|
21
|
+
而到点那一手是 `asyncio.ensure_future(self.execute(evt))`
|
|
22
|
+
(`scheduler.py:773`)。loop 在轮末就关,IM 的审批超时静默失效
|
|
23
|
+
(症状:一直等,不结算)。消费协程用 `await` 等新活,loop 一直活着。
|
|
24
|
+
|
|
25
|
+
② 每会话 FIFO,不靠锁:`_session_lock_for` 是一把普通
|
|
26
|
+
`threading.Lock`,没有公平性,解耦之后"谁先抢到锁"就是用户看得见的
|
|
27
|
+
乱序(同一会话里两句话被倒着做)。
|
|
28
|
+
|
|
29
|
+
③ 队列键用自然键(`core/session_key.py::session_key_for`):
|
|
30
|
+
`im_routing` 今天在 `execute` 里面才决定"进哪条会话"。私聊恰好就是
|
|
31
|
+
`workspace:private`(与绑定键同一条)、群聊是 `workspace:group:<id>`
|
|
32
|
+
常见情形完全对得上;真的被绑定改派到别的会话时只是过度串行
|
|
33
|
+
(不会错,只是不必要地排队)。
|
|
34
|
+
|
|
35
|
+
## 分流(`intake`,顺序承重)
|
|
36
|
+
|
|
37
|
+
| 判据 | 结果 |
|
|
38
|
+
|---|---|
|
|
39
|
+
| 文本是 `/stop`(只认这一条,`.strip().lower()`,与 `pre_process` 同形) | 立刻 `request_cancel` + 丢弃队列与收件箱 + 回一句;不入队 |
|
|
40
|
+
| 带图 / 文件 / 语音 | 排队(v1 不做附件 steer,同 Web) |
|
|
41
|
+
| `/` 开头 | 排队(命令在 `pre_process` 解析;注入进循环里没人执行它) |
|
|
42
|
+
| 该会话有待审批 | 排队(那句话是审批回答, 的原现场) |
|
|
43
|
+
| 该会话正忙且目标唯一 | 进 `core/steer.py` 收件箱 + ack |
|
|
44
|
+
| 其余 | 排队(前面有活时才 ack —— 没活还 ack 是纯噪声) |
|
|
45
|
+
|
|
46
|
+
## 轮末残留(`steer_leftover`)
|
|
47
|
+
|
|
48
|
+
这一轮没赶上的补话由这里接管(Web 那边是前端用同一口气泡接着跑)。
|
|
49
|
+
两条不许自动接管:被打断的那一轮(用户按了停,别再自己开一轮)、
|
|
50
|
+
停在待审批的那一轮(下一条用户消息是审批回答,不能被一句补话顶掉)。
|
|
51
|
+
|
|
52
|
+
## 残余(写进 ,别读成"做完了")
|
|
53
|
+
|
|
54
|
+
· CLI 不走这里(`input()` 阻塞是它自己的语义,Ctrl+C 就是它的打断);
|
|
55
|
+
· 补话不进 dedup(`pre_process` 那道闸在"轮"里):平台重投一条补话会让
|
|
56
|
+
同一句在上下文里出现两遍 —— 代价是一句话,不是坏一轮;
|
|
57
|
+
· `/clear` 不动 worker(只丢队列):停掉线程等于让挂在上面的审批定时器
|
|
58
|
+
静默失效。线程的回收在 `_evict_idle_locked` —— 条数满了才收,
|
|
59
|
+
且只收"队列空、没在跑、没有审批定时器"的那些;
|
|
60
|
+
· 通道被停掉时排队的那几条还会跑,回话会撞已经关掉的循环,计数 + 出声;
|
|
61
|
+
· 消息里"媒体下载慢"仍可能插队(入队发生在下载之后);纯文字不受影响。
|
|
62
|
+
|
|
63
|
+
ASCII-only 输出(Windows 控制台默认 GBK)。
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
from __future__ import annotations
|
|
67
|
+
|
|
68
|
+
import asyncio
|
|
69
|
+
import threading
|
|
70
|
+
import time
|
|
71
|
+
import traceback
|
|
72
|
+
import uuid
|
|
73
|
+
from collections import deque
|
|
74
|
+
from typing import Awaitable, Callable, Deque, Dict, Optional
|
|
75
|
+
|
|
76
|
+
from core.i18n import t as tr
|
|
77
|
+
from core.session_key import session_key_for
|
|
78
|
+
|
|
79
|
+
__all__ = ["submit", "intake", "pending", "drop", "purge", "stop", "is_serving",
|
|
80
|
+
"MAX_QUEUE", "MAX_WORKERS"]
|
|
81
|
+
|
|
82
|
+
#: 通道回话的文案(中文原文 = 键,`locales/*.json` 按原文索引)。
|
|
83
|
+
#: 取值处一律 `tr(_COPY[...])`:这几种语言不在这里判,`t()` 一个口子。
|
|
84
|
+
_COPY = {
|
|
85
|
+
# `/stop`:队列里真的还有东西要丢
|
|
86
|
+
"stopped": "已中断,剩余消息已取消",
|
|
87
|
+
# `/stop`:有轮次在跑,但没有排队的
|
|
88
|
+
"stopped_bare": "已中断",
|
|
89
|
+
# `/stop`:什么都没在跑(说"已中断"就是撒谎)
|
|
90
|
+
"idle_stop": "无任务",
|
|
91
|
+
# 补话被收件箱接住(它会在下一次工具批之后进上下文)
|
|
92
|
+
"steer_ok": "正在处理,已收到消息",
|
|
93
|
+
# 排队:`/` 开头的命令
|
|
94
|
+
"queued": "命令信息,等待本轮任务结束后处理",
|
|
95
|
+
# 排队:带附件 / 待审批 / 目标不唯一 —— 都是"收到了,但要等"
|
|
96
|
+
"queued_media": "信息已收到,等待本轮任务结束后处理",
|
|
97
|
+
# 队列满了:这一条没收下(不说就是"发了没反应")
|
|
98
|
+
"queue_full": "消息太多,这条没有排队,请稍后重发",
|
|
99
|
+
# 这一轮抛了(与电报/钉钉原来那句同一份台词,收拢到一处)
|
|
100
|
+
"error": "内部处理异常,请稍后重试。",
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
#: 会话键 → worker。会话级状态,已登记在 `core/state_registry.py`。
|
|
104
|
+
_workers: Dict[str, "_Worker"] = {}
|
|
105
|
+
_lock = threading.Lock()
|
|
106
|
+
|
|
107
|
+
#: 一条会话最多排多少条(不含正在跑的那一条)。
|
|
108
|
+
#: 上限存在的理由不是"怕用户话多":没有上限的队列就是一条内存泄漏 ——
|
|
109
|
+
#: 一轮跑得很久、或者通道被灌时,队列会一直长,而没有任何一处会缩它。
|
|
110
|
+
MAX_QUEUE = 50
|
|
111
|
+
|
|
112
|
+
#: 进程里最多同时养多少条 worker 线程。超了就在建新的之前先收掉最闲的那些。
|
|
113
|
+
#: 它是收敛值,不是硬闸:收不掉的那几条(正在跑)不会被硬等,
|
|
114
|
+
#: 宁可多开一条线程也不丢用户一条消息。下一次新建时会再收一遍。
|
|
115
|
+
MAX_WORKERS = 64
|
|
116
|
+
|
|
117
|
+
#: 收 idle worker 的门槛(秒)。只在"已经到 MAX_WORKERS"时才看它 ——
|
|
118
|
+
#: 没满的时候一条都不收:留着不花钱,收错一次(把挂着审批定时器的那条停了)
|
|
119
|
+
#: 的代价是超时静默失效。
|
|
120
|
+
IDLE_EVICT_S = 1800.0
|
|
121
|
+
|
|
122
|
+
#: `_Worker.push` 的三种结果。"没排上"与"排上了"必须分得开。
|
|
123
|
+
_PUSH_OK = 0
|
|
124
|
+
_PUSH_FULL = 1
|
|
125
|
+
_PUSH_STOPPED = 2
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# worker:一条会话的执行体
|
|
129
|
+
|
|
130
|
+
class _Worker:
|
|
131
|
+
"""常驻 loop + FIFO 队列。每条会话一个(同会话串行、跨会话并行)。"""
|
|
132
|
+
|
|
133
|
+
def __init__(self, session_key: str) -> None:
|
|
134
|
+
self.key = session_key
|
|
135
|
+
self._q: Deque[Callable[[], Awaitable[None]]] = deque()
|
|
136
|
+
self._lock = threading.Lock()
|
|
137
|
+
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
|
138
|
+
self._wake: Optional[asyncio.Event] = None
|
|
139
|
+
self._started = threading.Event()
|
|
140
|
+
self._stopped = False
|
|
141
|
+
#: 上一次开始干活 / 入队的时刻(收 idle worker 用)。
|
|
142
|
+
self.last_active = time.monotonic()
|
|
143
|
+
self.running = False
|
|
144
|
+
self._thread = threading.Thread(
|
|
145
|
+
target=self._run, name="turn-%s" % _short_key(session_key),
|
|
146
|
+
daemon=True)
|
|
147
|
+
self._thread.start()
|
|
148
|
+
#: 5 秒是防死等:起不来时 `submit` 仍能入队,loop 起来之后自己会消费。
|
|
149
|
+
self._started.wait(5.0)
|
|
150
|
+
|
|
151
|
+
# ---- 任意线程 ----
|
|
152
|
+
def push(self, job: Callable[[], Awaitable[None]]) -> int:
|
|
153
|
+
"""入队。返回 `_PUSH_OK` / `_PUSH_FULL` / `_PUSH_STOPPED`。
|
|
154
|
+
|
|
155
|
+
"没排上"必须是一种能看见的结果:静默丢一条,用户看到的是
|
|
156
|
+
"发了没反应",与"消息没进来"同形。
|
|
157
|
+
"""
|
|
158
|
+
with self._lock:
|
|
159
|
+
if self._stopped:
|
|
160
|
+
return _PUSH_STOPPED
|
|
161
|
+
if len(self._q) >= MAX_QUEUE:
|
|
162
|
+
return _PUSH_FULL
|
|
163
|
+
self._q.append(job)
|
|
164
|
+
self.last_active = time.monotonic()
|
|
165
|
+
self._kick()
|
|
166
|
+
return _PUSH_OK
|
|
167
|
+
|
|
168
|
+
def clear(self) -> int:
|
|
169
|
+
"""丢掉还没开始跑的那几条,返回条数(正在跑的那轮不动)。"""
|
|
170
|
+
with self._lock:
|
|
171
|
+
n = len(self._q)
|
|
172
|
+
self._q.clear()
|
|
173
|
+
return n
|
|
174
|
+
|
|
175
|
+
def depth(self) -> int:
|
|
176
|
+
with self._lock:
|
|
177
|
+
return len(self._q)
|
|
178
|
+
|
|
179
|
+
def stopped(self) -> bool:
|
|
180
|
+
return self._stopped
|
|
181
|
+
|
|
182
|
+
def idle_for(self) -> float:
|
|
183
|
+
"""闲了多久(秒);有活在跑或排着就是 0。"""
|
|
184
|
+
if self.running or self.depth():
|
|
185
|
+
return 0.0
|
|
186
|
+
return time.monotonic() - self.last_active
|
|
187
|
+
|
|
188
|
+
def stop(self) -> bool:
|
|
189
|
+
"""停掉这条 worker。队列空、没在跑才停(返回 False 表示还忙着)。
|
|
190
|
+
|
|
191
|
+
停的是它那条常驻循环 -> 挂在上面的审批定时器一起没了。
|
|
192
|
+
所以调用方只有两个:`_evict_idle_locked`(已确认没有待审批)
|
|
193
|
+
与 `stop()`(显式销毁)。
|
|
194
|
+
"""
|
|
195
|
+
with self._lock:
|
|
196
|
+
if self._stopped:
|
|
197
|
+
return True
|
|
198
|
+
if self._q or self.running:
|
|
199
|
+
return False
|
|
200
|
+
self._stopped = True
|
|
201
|
+
loop = self._loop
|
|
202
|
+
if loop is not None:
|
|
203
|
+
try:
|
|
204
|
+
loop.call_soon_threadsafe(loop.stop)
|
|
205
|
+
except RuntimeError:
|
|
206
|
+
pass # 循环已经关了
|
|
207
|
+
return True
|
|
208
|
+
|
|
209
|
+
def _kick(self) -> None:
|
|
210
|
+
loop = self._loop
|
|
211
|
+
if loop is None:
|
|
212
|
+
return # 还没起来:起来之后 `_consume` 自己会看队列
|
|
213
|
+
try:
|
|
214
|
+
loop.call_soon_threadsafe(self._signal)
|
|
215
|
+
except RuntimeError:
|
|
216
|
+
pass # 循环已关(进程收尾)
|
|
217
|
+
|
|
218
|
+
def _signal(self) -> None:
|
|
219
|
+
if self._wake is not None:
|
|
220
|
+
self._wake.set()
|
|
221
|
+
|
|
222
|
+
# ---- 本线程(常驻 loop)----
|
|
223
|
+
def _run(self) -> None:
|
|
224
|
+
loop = asyncio.new_event_loop()
|
|
225
|
+
asyncio.set_event_loop(loop)
|
|
226
|
+
#: 先建 `Event` 再起消费协程 —— 反过来的话,`_started` 之后那一小段里
|
|
227
|
+
#: 推来的活会撞上 `_wake is None`(信号被丢掉,队列要靠下一次推才动)。
|
|
228
|
+
self._wake = asyncio.Event()
|
|
229
|
+
self._loop = loop
|
|
230
|
+
loop.create_task(self._consume())
|
|
231
|
+
self._started.set()
|
|
232
|
+
try:
|
|
233
|
+
loop.run_forever()
|
|
234
|
+
finally:
|
|
235
|
+
#: 停的时候把还挂在循环上的协程收掉再关 —— 直接 `close()` 会留一条
|
|
236
|
+
#: "Task was destroyed but it is pending" 的噪声(它长得像故障)。
|
|
237
|
+
try:
|
|
238
|
+
pending = asyncio.all_tasks(loop)
|
|
239
|
+
for task in pending:
|
|
240
|
+
task.cancel()
|
|
241
|
+
if pending:
|
|
242
|
+
loop.run_until_complete(
|
|
243
|
+
asyncio.gather(*pending, return_exceptions=True))
|
|
244
|
+
except Exception: # noqa: BLE001
|
|
245
|
+
pass
|
|
246
|
+
loop.close()
|
|
247
|
+
|
|
248
|
+
async def _consume(self) -> None:
|
|
249
|
+
"""就在这里 `await` 每一条活:轮次因此跑在这个常驻循环上
|
|
250
|
+
(判据 ①:审批倒计时挂的正是它)。"""
|
|
251
|
+
wake = self._wake
|
|
252
|
+
if wake is None: # 到不了:`_run` 先建它
|
|
253
|
+
wake = self._wake = asyncio.Event()
|
|
254
|
+
while True:
|
|
255
|
+
await wake.wait()
|
|
256
|
+
wake.clear()
|
|
257
|
+
while True:
|
|
258
|
+
with self._lock:
|
|
259
|
+
job = self._q.popleft() if self._q else None
|
|
260
|
+
if job is None:
|
|
261
|
+
break
|
|
262
|
+
self.running = True
|
|
263
|
+
self.last_active = time.monotonic()
|
|
264
|
+
try:
|
|
265
|
+
await job()
|
|
266
|
+
except Exception: # noqa: BLE001
|
|
267
|
+
#: 一条活炸了不许把消费协程带走(那会让整条会话永久卡死,
|
|
268
|
+
#: 而症状是"发消息没反应" —— 与"没收到"同形)。
|
|
269
|
+
traceback.print_exc()
|
|
270
|
+
finally:
|
|
271
|
+
self.running = False
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _short_key(session_key: str) -> str:
|
|
275
|
+
"""线程名用的短键(ASCII,同会话一眼能认出来)。"""
|
|
276
|
+
return (session_key.rsplit(":", 1)[-1] or "x")[:24]
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _has_pending_approval(key: str) -> bool:
|
|
280
|
+
"""这条会话还有审批倒计时挂着吗(挂着的 worker 不许收)。"""
|
|
281
|
+
try:
|
|
282
|
+
from core import approval_timeout as _AT
|
|
283
|
+
return _AT.event_of(key) is not None
|
|
284
|
+
except Exception: # noqa: BLE001
|
|
285
|
+
return True # 读不到就当有 —— 宁可多留一条线程
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _evict_idle_locked() -> int:
|
|
289
|
+
"""收掉最闲的几条 worker(调用方持 `_lock`)。返回收掉的条数。
|
|
290
|
+
|
|
291
|
+
三条判据缺一不可:队列空、没在跑、没有审批定时器。
|
|
292
|
+
第三条是"worker 不回收"那条老规矩剩下的部分 —— 定时器挂在 worker 的
|
|
293
|
+
常驻循环上,停了它就是超时静默失效。
|
|
294
|
+
"""
|
|
295
|
+
idle = []
|
|
296
|
+
for key, w in list(_workers.items()):
|
|
297
|
+
if w.stopped():
|
|
298
|
+
idle.append((float("inf"), key))
|
|
299
|
+
continue
|
|
300
|
+
gap = w.idle_for()
|
|
301
|
+
if gap < IDLE_EVICT_S or _has_pending_approval(key):
|
|
302
|
+
continue
|
|
303
|
+
idle.append((gap, key))
|
|
304
|
+
idle.sort(reverse=True) # 最闲的在前
|
|
305
|
+
n = 0
|
|
306
|
+
for _, key in idle:
|
|
307
|
+
w = _workers.get(key)
|
|
308
|
+
if w is None:
|
|
309
|
+
continue
|
|
310
|
+
if w.stop() and w.stopped():
|
|
311
|
+
_workers.pop(key, None)
|
|
312
|
+
n += 1
|
|
313
|
+
return n
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _worker_for(session_key: str) -> "_Worker":
|
|
317
|
+
with _lock:
|
|
318
|
+
w = _workers.get(session_key)
|
|
319
|
+
if w is not None and not w.stopped():
|
|
320
|
+
return w
|
|
321
|
+
if w is not None:
|
|
322
|
+
_workers.pop(session_key, None) # 已停的那条换掉
|
|
323
|
+
if len(_workers) >= MAX_WORKERS:
|
|
324
|
+
_evict_idle_locked()
|
|
325
|
+
w = _Worker(session_key)
|
|
326
|
+
_workers[session_key] = w
|
|
327
|
+
return w
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# 公共入口
|
|
331
|
+
|
|
332
|
+
def submit(session_key: str, job: Callable[[], Awaitable[None]]) -> bool:
|
|
333
|
+
"""把一条活排到这条会话的队尾。任意线程可调,立刻返回。
|
|
334
|
+
|
|
335
|
+
返回"排上了吗":队列满时是 `False`。调用方必须把它说出来 ——
|
|
336
|
+
静默丢一条与"消息没进来"在用户眼里完全一样。
|
|
337
|
+
"""
|
|
338
|
+
if not session_key or job is None:
|
|
339
|
+
return False
|
|
340
|
+
key = str(session_key)
|
|
341
|
+
for _ in range(3):
|
|
342
|
+
w = _worker_for(key)
|
|
343
|
+
state = w.push(job)
|
|
344
|
+
if state == _PUSH_OK:
|
|
345
|
+
return True
|
|
346
|
+
if state == _PUSH_FULL:
|
|
347
|
+
return False
|
|
348
|
+
# 已停(正好被收掉):换一条再来
|
|
349
|
+
return False
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def pending(session_key: str) -> int:
|
|
353
|
+
"""队列里还没开始跑的条数(不含正在跑的那条)。"""
|
|
354
|
+
with _lock:
|
|
355
|
+
w = _workers.get(session_key)
|
|
356
|
+
return w.depth() if w is not None else 0
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def is_serving(session_key: str) -> bool:
|
|
360
|
+
"""这条会话有 worker 吗(自检 / 日志用;不是"有活")。"""
|
|
361
|
+
with _lock:
|
|
362
|
+
return session_key in _workers
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def drop(session_key: str) -> int:
|
|
366
|
+
"""丢掉这条会话排队的那几条,返回条数。"""
|
|
367
|
+
with _lock:
|
|
368
|
+
w = _workers.get(session_key)
|
|
369
|
+
return w.clear() if w is not None else 0
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def purge(session_key: str) -> None:
|
|
373
|
+
"""`/clear` 走这里:把这条会话排队的那几条丢掉,worker 留着。
|
|
374
|
+
|
|
375
|
+
不停线程、也不动正在跑的那一轮(`/clear` 本来就是那一轮自己)。
|
|
376
|
+
停掉线程会让挂在它常驻循环上的审批倒计时静默失效 —— 回收是
|
|
377
|
+
`_evict_idle_locked` 的事:条数满了才收,且只收闲着的。
|
|
378
|
+
"""
|
|
379
|
+
with _lock:
|
|
380
|
+
w = _workers.get(str(session_key or ""))
|
|
381
|
+
if w is not None:
|
|
382
|
+
w.clear()
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def stop(session_key: str) -> bool:
|
|
386
|
+
"""销毁一条 worker(显式停通道 / 进程收尾用)。`/clear` 不走这里。
|
|
387
|
+
|
|
388
|
+
返回"停掉了吗":队列里还有活、或者正在跑,就返回 `False`(那条活该跑完)。
|
|
389
|
+
"""
|
|
390
|
+
key = str(session_key or "")
|
|
391
|
+
with _lock:
|
|
392
|
+
w = _workers.get(key)
|
|
393
|
+
if w is None:
|
|
394
|
+
return True
|
|
395
|
+
if not w.stop() or not w.stopped():
|
|
396
|
+
return False
|
|
397
|
+
_workers.pop(key, None)
|
|
398
|
+
return True
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
# 接收路径:分流
|
|
402
|
+
|
|
403
|
+
async def intake(channel, event, *, on_reply=None) -> None:
|
|
404
|
+
"""接收路径的唯一入口:分流 + 入队 + 必要时回一句,然后立刻返回。
|
|
405
|
+
|
|
406
|
+
*on_reply* 是"这一轮的回答怎么发回去"的协程函数(`str -> awaitable`):
|
|
407
|
+
电报 / 微信走它(它们的回答是 `execute` 的返回值),飞书 / 钉钉给 `None`
|
|
408
|
+
(它们自己的 `reply_callback` 已经把回话发掉了)。
|
|
409
|
+
"""
|
|
410
|
+
session = getattr(event, "session", None)
|
|
411
|
+
key = session_key_for(session)
|
|
412
|
+
sch = getattr(channel, "_scheduler", None)
|
|
413
|
+
if sch is None or not key:
|
|
414
|
+
print("[im] 没有 scheduler 或没有会话键,这条消息丢掉")
|
|
415
|
+
return
|
|
416
|
+
loop = asyncio.get_running_loop()
|
|
417
|
+
text = str(getattr(getattr(event, "message", None), "content", "") or "").strip()
|
|
418
|
+
|
|
419
|
+
# ① `/stop`:在拿锁之前分流
|
|
420
|
+
if text.lower() == "/stop":
|
|
421
|
+
if _handle_stop(key):
|
|
422
|
+
await _note(channel, session, tr(_COPY["stopped"]), event)
|
|
423
|
+
elif _queue_ahead(sch, key):
|
|
424
|
+
await _note(channel, session, tr(_COPY["stopped_bare"]), event)
|
|
425
|
+
else:
|
|
426
|
+
await _note(channel, session, tr(_COPY["idle_stop"]), event)
|
|
427
|
+
return
|
|
428
|
+
|
|
429
|
+
ahead = _queue_ahead(sch, key)
|
|
430
|
+
|
|
431
|
+
# ② 可 steer 吗
|
|
432
|
+
if ahead and text and _steerable(event, sch, key, text):
|
|
433
|
+
item_id = _msg_id(event)
|
|
434
|
+
if _push_steer(key, item_id, text):
|
|
435
|
+
#: 推完再确认一次在不在跑:轮末与这一推之间有一道缝,
|
|
436
|
+
#: 错过它这条会一直躺在收件箱里(没人再取)。自己摘回来当普通消息跑。
|
|
437
|
+
if not _busy(sch, key):
|
|
438
|
+
from core import steer as _steer
|
|
439
|
+
if _steer.drop(key, item_id):
|
|
440
|
+
if not submit(key, _turn_job(channel, event, on_reply, loop)):
|
|
441
|
+
await _note(channel, session,
|
|
442
|
+
tr(_COPY["queue_full"]), event)
|
|
443
|
+
return
|
|
444
|
+
#: 两条出口都回一句 —— 这条已经被收下了,不回就成了"发完没反应"。
|
|
445
|
+
await _note(channel, session, tr(_COPY["steer_ok"]), event)
|
|
446
|
+
return
|
|
447
|
+
|
|
448
|
+
# ③ 排队
|
|
449
|
+
if not submit(key, _turn_job(channel, event, on_reply, loop)):
|
|
450
|
+
#: 队列满了:这一条没收下。不说就是"发了没反应"。
|
|
451
|
+
await _note(channel, session, tr(_COPY["queue_full"]), event)
|
|
452
|
+
return
|
|
453
|
+
if ahead:
|
|
454
|
+
note = (_COPY["queued"] if text.startswith("/")
|
|
455
|
+
else _COPY["queued_media"])
|
|
456
|
+
await _note(channel, session, tr(note), event)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _busy(sch, key: str) -> bool:
|
|
460
|
+
try:
|
|
461
|
+
return bool(sch.is_busy(key))
|
|
462
|
+
except Exception: # noqa: BLE001
|
|
463
|
+
return False
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _queue_ahead(sch, key: str) -> bool:
|
|
467
|
+
"""前面还有活吗(正在跑的一轮,或者队里排着的)。"""
|
|
468
|
+
return _busy(sch, key) or pending(key) > 0
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _handle_stop(key: str) -> bool:
|
|
472
|
+
"""`/stop`:打断本轮 + 丢弃队列与收件箱。
|
|
473
|
+
|
|
474
|
+
返回"这次真的丢了东西吗"(决定回哪一句 —— 一句"剩余消息已取消"在
|
|
475
|
+
什么都没取消的时候就是撒谎,这一类)。
|
|
476
|
+
"""
|
|
477
|
+
from core.cancellation import request_cancel
|
|
478
|
+
request_cancel(key)
|
|
479
|
+
#: 在正在跑的那一轮的事件上打个标记:这一轮收尾时框架那句固定的
|
|
480
|
+
#: 「已打断,需要 … 怎么做?」不再发一遍 —— `intake` 已经当场回过
|
|
481
|
+
#: 「已中断」了,两句说一件事。
|
|
482
|
+
#: 不新增任何状态:`approval_timeout` 记的就是那条真事件(同一个对象),
|
|
483
|
+
#: 标记挂在它身上,随这一轮一起消失。
|
|
484
|
+
#: Web 那头按的打断不打这个标记,那句话照发(那是 IM 用户唯一的信息)。
|
|
485
|
+
try:
|
|
486
|
+
from core import approval_timeout as _AT
|
|
487
|
+
_ev = _AT.event_of(key)
|
|
488
|
+
if _ev is not None and getattr(_ev, "extras", None) is not None:
|
|
489
|
+
_ev.extras["im_stop_ack"] = True
|
|
490
|
+
except Exception as exc: # noqa: BLE001
|
|
491
|
+
print("[im] 打 /stop 标记失败(%s: %s)" % (type(exc).__name__, exc))
|
|
492
|
+
dropped = drop(key)
|
|
493
|
+
try:
|
|
494
|
+
from core import steer as _steer
|
|
495
|
+
dropped += _steer.pending(key)
|
|
496
|
+
_steer.clear(key)
|
|
497
|
+
except Exception as exc: # noqa: BLE001
|
|
498
|
+
print("[im] 清收件箱失败(%s: %s)" % (type(exc).__name__, exc))
|
|
499
|
+
return bool(dropped)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _steerable(event, sch, key: str, text: str) -> bool:
|
|
503
|
+
"""能不能把这句话塞进正在跑的那一轮(五条判据,与 `/api/steer` 同源)。"""
|
|
504
|
+
if text.startswith("/"):
|
|
505
|
+
return False # 命令:注入进循环没人执行
|
|
506
|
+
chain = getattr(getattr(event, "message", None), "message_chain", None)
|
|
507
|
+
try:
|
|
508
|
+
from channels.message import File, Image, Voice
|
|
509
|
+
if any(isinstance(c, (Image, File, Voice))
|
|
510
|
+
for c in (getattr(chain, "components", None) or [])):
|
|
511
|
+
return False # 附件:v1 不注入
|
|
512
|
+
except Exception: # noqa: BLE001
|
|
513
|
+
return False
|
|
514
|
+
try:
|
|
515
|
+
if sch.pending_approval(key) is not None:
|
|
516
|
+
return False # 那句话是审批回答
|
|
517
|
+
except Exception: # noqa: BLE001
|
|
518
|
+
return False
|
|
519
|
+
return _target_is_unambiguous(event, sch)
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _target_is_unambiguous(event, sch) -> bool:
|
|
523
|
+
"""这条消息要进哪条会话 —— 判不出来就不 steer(fail-closed)。
|
|
524
|
+
|
|
525
|
+
`im_routing` 有多条活跃会话又没有认领时会问编号;那时把补话塞进
|
|
526
|
+
"碰巧在忙的那条"就是替用户猜。判据全在 `core/im_routing.py`,这里只读。
|
|
527
|
+
"""
|
|
528
|
+
try:
|
|
529
|
+
from core import im_routing
|
|
530
|
+
chan = im_routing.channel_key_of(getattr(event, "session", None))
|
|
531
|
+
if im_routing.bound_session_key(chan):
|
|
532
|
+
return True
|
|
533
|
+
snap = sch.activity_snapshot() if hasattr(sch, "activity_snapshot") else {}
|
|
534
|
+
return len(im_routing.hot_sessions(snap, time.monotonic())) <= 1
|
|
535
|
+
except Exception as exc: # noqa: BLE001
|
|
536
|
+
print("[im] 目标会话判不出来(%s: %s)—— 这条不 steer"
|
|
537
|
+
% (type(exc).__name__, exc))
|
|
538
|
+
return False
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _push_steer(key: str, item_id: str, text: str) -> bool:
|
|
542
|
+
try:
|
|
543
|
+
from core import steer as _steer
|
|
544
|
+
_steer.push(key, {"id": item_id, "text": text})
|
|
545
|
+
return True
|
|
546
|
+
except Exception as exc: # noqa: BLE001
|
|
547
|
+
print("[im] 补话没塞进收件箱(%s: %s)—— 这条按普通消息排队"
|
|
548
|
+
% (type(exc).__name__, exc))
|
|
549
|
+
return False
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _msg_id(event) -> str:
|
|
553
|
+
"""补话的 id:优先用平台消息号(重投时对得上),没有就现造一个。"""
|
|
554
|
+
mid = str(getattr(getattr(event, "message", None), "message_id", "") or "")
|
|
555
|
+
return mid or ("im-" + uuid.uuid4().hex[:12])
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
# 执行体:跑一轮 + 发回答 + 接管轮末残留
|
|
559
|
+
|
|
560
|
+
def _is_cancel_line(text: str) -> bool:
|
|
561
|
+
"""这句是不是框架自己的取消收尾(不是模型说的话)。"""
|
|
562
|
+
try:
|
|
563
|
+
from core.agent_loop import CANCEL_REPLY
|
|
564
|
+
except Exception: # noqa: BLE001
|
|
565
|
+
return False
|
|
566
|
+
t = str(text or "").strip()
|
|
567
|
+
return bool(t) and t == CANCEL_REPLY
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _suppress_cancel_line(ev, text: str) -> bool:
|
|
571
|
+
"""IM 按的 `/stop`:框架那句固定的收尾不再发一遍。
|
|
572
|
+
|
|
573
|
+
判据是这句话本身 + 事件上的标记(不读 `extras["cancelled"]`:
|
|
574
|
+
管线调 `reply_callback` 的时刻早于它写那一格 —— 读它永远是 False)。
|
|
575
|
+
"""
|
|
576
|
+
extras = getattr(ev, "extras", None) or {}
|
|
577
|
+
return bool(extras.get("im_stop_ack")) and _is_cancel_line(text)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _wrap_reply_for_stop(ev) -> None:
|
|
581
|
+
"""给 `reply_callback`(飞书 / 钉钉那条路)套一层:只丢那句取消收尾,文件照发。"""
|
|
582
|
+
orig = getattr(ev, "reply_callback", None)
|
|
583
|
+
if orig is None or getattr(orig, "_im_stop_wrapped", False):
|
|
584
|
+
return
|
|
585
|
+
|
|
586
|
+
def _cb(e):
|
|
587
|
+
try:
|
|
588
|
+
if _suppress_cancel_line(e, (getattr(e, "extras", None) or {}).get("response")):
|
|
589
|
+
e.extras["response"] = ""
|
|
590
|
+
except Exception: # noqa: BLE001
|
|
591
|
+
pass
|
|
592
|
+
orig(e)
|
|
593
|
+
|
|
594
|
+
_cb._im_stop_wrapped = True
|
|
595
|
+
ev.reply_callback = _cb
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _turn_job(channel, event, on_reply, loop) -> Callable[[], Awaitable[None]]:
|
|
599
|
+
async def _job() -> None:
|
|
600
|
+
await _run_turn(channel, event, on_reply, loop)
|
|
601
|
+
return _job
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
async def _run_turn(channel, event, on_reply, loop) -> None:
|
|
605
|
+
"""在这个会话的 worker 循环上跑一轮;没赶上的补话接着跑。"""
|
|
606
|
+
sch = getattr(channel, "_scheduler", None)
|
|
607
|
+
if sch is None:
|
|
608
|
+
return
|
|
609
|
+
ev = event
|
|
610
|
+
while True:
|
|
611
|
+
_wrap_reply_for_stop(ev)
|
|
612
|
+
try:
|
|
613
|
+
resp = await sch.execute(ev)
|
|
614
|
+
except Exception as exc: # noqa: BLE001
|
|
615
|
+
print("[im] 这一轮抛了(%s: %s)" % (type(exc).__name__, exc))
|
|
616
|
+
traceback.print_exc()
|
|
617
|
+
err = tr(_COPY["error"])
|
|
618
|
+
if on_reply is not None:
|
|
619
|
+
await _hop(loop, on_reply(err))
|
|
620
|
+
else:
|
|
621
|
+
#: 飞书 / 钉钉没有 `on_reply`(回答走 `reply_callback`,而异常不
|
|
622
|
+
#: 走那条路),这里补一句人话,仍然走通道自己的回调
|
|
623
|
+
#: (钉钉要靠它拿 `session_webhook`,换成 `send()` 会发不出去)。
|
|
624
|
+
_cb = getattr(ev, "reply_callback", None)
|
|
625
|
+
if _cb is not None:
|
|
626
|
+
try:
|
|
627
|
+
ev.extras["response"] = err
|
|
628
|
+
_cb(ev)
|
|
629
|
+
except Exception: # noqa: BLE001
|
|
630
|
+
pass
|
|
631
|
+
else:
|
|
632
|
+
await _hop(loop, _send_note(channel, ev.session, err, ev))
|
|
633
|
+
return
|
|
634
|
+
text = str(resp or "")
|
|
635
|
+
if _suppress_cancel_line(ev, text):
|
|
636
|
+
#: 当场已经回过「已中断」了 —— 这句只丢文字,文件照发。
|
|
637
|
+
text = ""
|
|
638
|
+
if on_reply is not None:
|
|
639
|
+
await _hop(loop, on_reply(text))
|
|
640
|
+
elif (ev.extras or {}).get("steer_leftover_turn"):
|
|
641
|
+
#: 合成事件没有 `reply_callback`(那是给原渠道那条消息用的),
|
|
642
|
+
#: 它的回话走"主动投递"这条路 —— 与定时任务 / 后台回报同一格。
|
|
643
|
+
await _hop(loop, _send_note(channel, ev.session, text, ev))
|
|
644
|
+
nxt = _leftover_event(ev)
|
|
645
|
+
if nxt is None:
|
|
646
|
+
return
|
|
647
|
+
ev = nxt
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
#: 把回话投到通道循环上的等待上限(秒)。
|
|
651
|
+
#:
|
|
652
|
+
#: 必须有上限:通道被停掉时(`/api/channel/stop` → `loop.stop()` + `close()`)
|
|
653
|
+
#: 一个已经提交上去、却永远轮不到的协程会让这条会话的 worker 永久卡住
|
|
654
|
+
#: (同会话后面每一条消息都排在一个死掉的 hop 后面)。实际症状:`_hop` 一直
|
|
655
|
+
#: `await`,而通道那边什么都不发生 —— "发消息没反应"。
|
|
656
|
+
#: 60 秒远大于任何一次正常回话(上传附件+发文字)。
|
|
657
|
+
_HOP_TIMEOUT_S = 60.0
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
async def _hop(loop, coro) -> None:
|
|
661
|
+
"""把 *coro* 投到通道自己的循环上跑完(客户端绑在那上面,别新造循环)。"""
|
|
662
|
+
if loop is None or loop.is_closed():
|
|
663
|
+
try:
|
|
664
|
+
coro.close()
|
|
665
|
+
except Exception: # noqa: BLE001
|
|
666
|
+
pass
|
|
667
|
+
print("[im] 通道的循环已经关了,这条回话发不出去")
|
|
668
|
+
return
|
|
669
|
+
try:
|
|
670
|
+
fut = asyncio.run_coroutine_threadsafe(coro, loop)
|
|
671
|
+
except Exception as exc: # noqa: BLE001
|
|
672
|
+
try:
|
|
673
|
+
coro.close()
|
|
674
|
+
except Exception: # noqa: BLE001
|
|
675
|
+
pass
|
|
676
|
+
print("[im] 回话投递失败(%s: %s)" % (type(exc).__name__, exc))
|
|
677
|
+
return
|
|
678
|
+
try:
|
|
679
|
+
await asyncio.wait_for(asyncio.wrap_future(fut), timeout=_HOP_TIMEOUT_S)
|
|
680
|
+
except asyncio.TimeoutError:
|
|
681
|
+
#: 取消不一定能取消对面那个协程(它在另一个循环上),但至少
|
|
682
|
+
#: 这一条 worker 不会永远卡住 —— 卡住比"少发一句话"贵得多。
|
|
683
|
+
fut.cancel()
|
|
684
|
+
print("[im] 回话投递超时(%.0fs)—— 通道可能已经停了" % _HOP_TIMEOUT_S)
|
|
685
|
+
except Exception as exc: # noqa: BLE001
|
|
686
|
+
print("[im] 回话投递失败(%s: %s)" % (type(exc).__name__, exc))
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
async def _send_note(channel, session, text: str, event=None) -> bool:
|
|
690
|
+
fn = getattr(channel, "send_note", None) or getattr(channel, "send", None)
|
|
691
|
+
if fn is None or not str(text or "").strip():
|
|
692
|
+
return False
|
|
693
|
+
try:
|
|
694
|
+
return bool(await fn(session, text, event=event))
|
|
695
|
+
except Exception as exc: # noqa: BLE001
|
|
696
|
+
print("[im] 旁白没发出去(%s: %s)" % (type(exc).__name__, exc))
|
|
697
|
+
return False
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
async def _note(channel, session, text: str, event=None) -> None:
|
|
701
|
+
"""接收路径上的旁白(ack / 已中断)—— 不许弄挂收消息。
|
|
702
|
+
|
|
703
|
+
*event* 是触发它的那条消息:钉钉要靠它的 `session_webhook` 才发得出去。
|
|
704
|
+
"""
|
|
705
|
+
ok = await _send_note(channel, session, text, event=event)
|
|
706
|
+
if not ok:
|
|
707
|
+
#: 不静默:旁白发不出去时用户以为"它没理我",而这与"消息没进来"同形。
|
|
708
|
+
print("[im] 旁白未送达(%s)" % _short_key(str(getattr(session, "session_id", "") or "")))
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def _leftover_event(ev):
|
|
712
|
+
"""这一轮没赶上的补话,一条合成事件(接着跑一轮);没有就 `None`。"""
|
|
713
|
+
extras = getattr(ev, "extras", None) or {}
|
|
714
|
+
if extras.get("cancelled") or extras.get("awaiting_approval"):
|
|
715
|
+
return None
|
|
716
|
+
items = list(extras.get("steer_leftover") or [])
|
|
717
|
+
key = str(extras.get("routed_session_key") or "") or session_key_for(
|
|
718
|
+
getattr(ev, "session", None))
|
|
719
|
+
#: 再取一次:轮末的 drain 与这里之间还有一道缝(推在 drain 之后的那条)。
|
|
720
|
+
try:
|
|
721
|
+
from core import steer as _steer
|
|
722
|
+
items += _steer.drain(key)
|
|
723
|
+
except Exception as exc: # noqa: BLE001
|
|
724
|
+
print("[im] 取残留补话失败(%s: %s)" % (type(exc).__name__, exc))
|
|
725
|
+
text = "\n".join(str(i.get("text") or "").strip()
|
|
726
|
+
for i in items if str(i.get("text") or "").strip())
|
|
727
|
+
if not text.strip():
|
|
728
|
+
return None
|
|
729
|
+
return _synthetic_event(ev, key, text)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _synthetic_event(ev, key: str, text: str):
|
|
733
|
+
"""照 `core/tasks_notify.py` 的形状造一条用户口吻的事件。
|
|
734
|
+
|
|
735
|
+
不带 `origin`(`background` / `cron` 会被落成 `kind=framework_note`)——
|
|
736
|
+
这几句是用户自己说的,界面上该长成用户气泡。
|
|
737
|
+
带 `routed_session_key`,`im_routing.route()` 直接放过(不再问一句"进哪条会话")。
|
|
738
|
+
"""
|
|
739
|
+
from channels.base import ChannelMetadata, Message as ChannelMessage, MessageEvent
|
|
740
|
+
from channels.message import MessageChain
|
|
741
|
+
|
|
742
|
+
session = ev.session
|
|
743
|
+
msg = ChannelMessage(
|
|
744
|
+
sender_id=str(getattr(getattr(ev, "message", None), "sender_id", "") or ""),
|
|
745
|
+
message_chain=MessageChain.from_text(text),
|
|
746
|
+
sender_name=str(getattr(getattr(ev, "message", None), "sender_name", "") or ""),
|
|
747
|
+
message_type=session.message_type,
|
|
748
|
+
session=session,
|
|
749
|
+
)
|
|
750
|
+
return MessageEvent(
|
|
751
|
+
session=session,
|
|
752
|
+
message=msg,
|
|
753
|
+
platform_meta=ChannelMetadata(
|
|
754
|
+
name=str(getattr(getattr(ev, "platform_meta", None), "name", "") or "im"),
|
|
755
|
+
description="steer leftover",
|
|
756
|
+
platform_type=str(getattr(session, "platform", "") or ""),
|
|
757
|
+
),
|
|
758
|
+
extras={"routed_session_key": key, "steer_leftover_turn": True},
|
|
759
|
+
)
|