femo-plugin 1.0.4 → 1.0.6

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.
Files changed (112) hide show
  1. package/LICENSE +1 -1
  2. package/NOTICE +8 -0
  3. package/README.md +12 -1
  4. package/docs/ActiveRoadmaps/Func/345/201/234/346/255/242/350/257/255/344/271/211-/351/201/227/345/274/203/346/216/245/347/273/255-/346/226/275/345/267/245/346/270/205/345/215/225.md +91 -0
  5. package/docs/ActiveRoadmaps//345/217/214user/346/226/275/345/267/245/346/270/205/345/215/225.md +326 -0
  6. package/docs/Specs//346/212/225/345/275/261/344/270/255/345/277/203/350/241/214/345/215/217/350/256/256.md +616 -569
  7. package/femo2host/AGENTS.md +1 -1
  8. package/femo2host/femoGenConnector/engine-client.mjs +7 -2
  9. package/femo2host/femoGenConnector/file-dialogs.mjs +108 -2
  10. package/femo2host/femoToolcall/chronica.py +99 -19
  11. package/femo2host/femo_api.py +14 -1
  12. package/femo2host/host/actor-core.d.mts +25 -0
  13. package/femo2host/host/actor-core.mjs +72 -0
  14. package/femo2host/host/cast-core.d.mts +3 -0
  15. package/femo2host/host/cast-core.mjs +14 -0
  16. package/femo2host/host/daemon-client.mjs +59 -10
  17. package/femo2host/host/hub-render-core.d.mts +2 -0
  18. package/femo2host/host/hub-render-core.mjs +6 -2
  19. package/femo2host/host/run-state-core.d.mts +4 -0
  20. package/femo2host/host/run-state-core.mjs +4 -0
  21. package/femo2host/host/speech-core.mjs +11 -4
  22. package/femo2host/host/tools-core.d.mts +11 -0
  23. package/femo2host/host/tools-core.mjs +39 -0
  24. package/femo2host/mailbox.py +630 -545
  25. package/femo2host/projectionCenter/app.css +61 -0
  26. package/femo2host/projectionCenter/composer.mjs +233 -20
  27. package/femo2host/projectionCenter/identity.mjs +131 -0
  28. package/femo2host/projectionCenter/index.html +55 -1
  29. package/femo2host/projectionCenter/main.mjs +231 -35
  30. package/femo2host/projectionCenter/panels.mjs +108 -16
  31. package/femo2host/projectionCenter/render.mjs +813 -695
  32. package/femo2host/projectionCenter/state.mjs +30 -0
  33. package/femo2host/projectionCenter/util.mjs +28 -0
  34. package/femo2host/projection_hub.py +1796 -230
  35. package/femo2host/python/femo_bridge.py +303 -33
  36. package/femo2host/python/femo_daemon.py +1528 -1209
  37. package/femo2host/python/mirror_window.py +237 -0
  38. package/femoBridges/ContextExample.py +113 -71
  39. package/femoCompiler/AGENTS.md +1 -0
  40. package/femoCompiler/FEMO_parser.py +2641 -2567
  41. package/femoCompiler/FEMO_runtime.py +217 -44
  42. package/femoCompiler/FEMO_scope_resolver.py +26 -12
  43. package/femoCompiler/block_collector.py +24 -27
  44. package/femoCompiler/db_utils.py +560 -503
  45. package/femoCompiler/femoAsync.py +466 -436
  46. package/femoCompiler/func_registry.py +74 -0
  47. package/femoCompiler/protocol.py +127 -127
  48. package/femoCompiler/save_dialog.py +497 -446
  49. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/AI/350/201/212/345/244/251/345/256/244-/345/270/246agent/347/211/210.femo +229 -142
  50. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +91 -2
  51. package/femoExamples/LuxFiat/luxfiat-loop.femo +0 -1
  52. package/femoExamples/LuxFiat/luxfiat-simple.femo +23 -24
  53. package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +221 -222
  54. package/femoExamples/discussion.femo +72 -72
  55. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210-9/344/272/272/351/242/204/345/245/263/347/214/216.femo +1 -2
  56. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +1 -2
  57. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +1 -2
  58. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +1 -1
  59. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +1 -1
  60. package/femoGen/document_ch.html +1 -0
  61. package/femoGen/document_en.html +1 -0
  62. package/femoGen/index.html +1 -0
  63. package/femoGen/intro_ch.html +1 -0
  64. package/femoGen/intro_en.html +1 -0
  65. package/femoGen/package.json +7 -0
  66. package/femoGen/public/femo-logo-slogan.svg +5 -0
  67. package/femoGen/public/femo-logo.svg +6 -1
  68. package/femoGen/src/femoParser.jsx +14 -0
  69. package/hostAdapter/dshAdapter/host/femo-skill.ts +23 -10
  70. package/hostAdapter/dshAdapter/host/routes/projection-input.ts +3 -0
  71. package/hostAdapter/dshAdapter/lib/client.js +20 -2
  72. package/hostAdapter/dshAdapter/lib/client.js.map +2 -2
  73. package/hostAdapter/dshAdapter/lib/main.js +161 -18
  74. package/hostAdapter/dshAdapter/lib/main.js.map +3 -3
  75. package/hostAdapter/dshAdapter/package.json +11 -1
  76. package/hostAdapter/webAdapter/console/index.html +13 -4
  77. package/hostAdapter/webAdapter/extension/background.js +16 -5
  78. package/hostAdapter/webAdapter/extension/seat-agent-core.js +836 -791
  79. package/hostAdapter/webAdapter/extension/sidepanel/actors.mjs +101 -0
  80. package/hostAdapter/webAdapter/extension/sidepanel/main.mjs +81 -20
  81. package/hostAdapter/webAdapter/extension/sidepanel/reconnect.mjs +33 -0
  82. package/hostAdapter/webAdapter/extension/sidepanel/run-control.mjs +22 -11
  83. package/hostAdapter/webAdapter/extension/sidepanel/seats.mjs +6 -20
  84. package/hostAdapter/webAdapter/extension/sidepanel.html +31 -8
  85. package/hostAdapter/webAdapter/native/install-native-host.mjs +1 -0
  86. package/hostAdapter/webAdapter/native/register-core.mjs +69 -28
  87. package/hostAdapter/webAdapter/native/web-launcher.sh +37 -0
  88. package/hostAdapter/webAdapter/package.json +7 -0
  89. package/hostAdapter/webAdapter/readme.md +51 -10
  90. package/hostAdapter/webAdapter/server/bridge.mjs +1 -1
  91. package/hostAdapter/webAdapter/server/runtime.mjs +51 -5
  92. package/hostAdapter/webAdapter/server/seats.mjs +11 -6
  93. package/hostAdapter/webAdapter/server/service.mjs +108 -15
  94. package/hostAdapter/webAdapter/shared/seats-core.mjs +31 -6
  95. package/hostAdapter/webAdapter/sites/chat.deepseek.com/SITE.md +7 -0
  96. package/hostAdapter/webAdapter/sites/chat.deepseek.com/content.js +83 -68
  97. package/hostAdapter/webAdapter/sites/chatglm.cn/inject.js +76 -4
  98. package/hostAdapter/webAdapter/sites/chatgpt.com/SITE.md +7 -1
  99. package/hostAdapter/webAdapter/sites/chatgpt.com/content.js +37 -5
  100. package/hostAdapter/webAdapter/sites/chatgpt.com/inject.js +40 -4
  101. package/hostAdapter/webAdapter/start-service.command +16 -0
  102. package/hostAdapter/webAdapter/tests/chatgpt-input.test.mjs +58 -0
  103. package/hostAdapter/webAdapter/tests/chatgpt-parser.test.mjs +37 -0
  104. package/hostAdapter/webAdapter/tests/deepseek-sanitize.test.mjs +68 -0
  105. package/hostAdapter/webAdapter/tests/runtime.test.mjs +42 -0
  106. package/hostAdapter/webAdapter/tests/seats-core.test.mjs +37 -1
  107. package/hostAdapter/webAdapter/tests/smoke-service.mjs +261 -232
  108. package/hostAdapter/zcodeAdapter/runtime/speech-collect.mjs +6 -0
  109. package/hostAdapter/zcodeAdapter/skills/femo/SKILL.md +3 -0
  110. package/hostAdapter/zcodeAdapter/tests/unbound-actors.test.mjs +51 -0
  111. package/package.json +7 -1
  112. package//350/257/255/346/263/225/346/226/207/346/241/243.md +1224 -1202
@@ -1,436 +1,466 @@
1
- # femoCompiler/femoAsync.py
2
- """
3
- 多 Agent 并发引擎 - asyncio 版本
4
- 提供: 协程任务管理, 进程池(CPU 密集), 线程池(快速/兜底), 人类输入异步等待
5
-
6
- 接口说明:
7
- - run_in_process(func, *args, **kwargs): 强制使用进程池执行(默认所有 @func 走这里)
8
- - run_in_thread(func, *args, **kwargs): 强制使用线程池执行
9
- - run_func(func, *args, mode='process', **kwargs): 通用入口,根据 mode 路由
10
- - create_task(coro): 创建协程任务(用于 fork 分支)
11
- - gather_with_cancel(tasks, return_when='all', count=1): 等待多个协程任务
12
- - human_input.wait_for_input(key, timeout): 异步等待人类输入
13
- """
14
-
15
- import asyncio
16
- # 在 import asyncio 下方添加(如果有需要的话,但 FEMO_runtime 会导入这个)
17
- CancelledError = asyncio.CancelledError
18
- import os
19
- from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
20
- from typing import Any, Callable, Coroutine, Dict, Optional, Set
21
- import contextvars
22
-
23
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ workflow_ctx / WorkflowContext:
24
- # 早期"工作流上下文"设计的残留,全仓零引用(双窗口交叉扫描+逐项复核),
25
- # 连本文件尾部的 __main__ 自测都不用它们;现行簿记走 FEMO_runtime 的 task_ctx/contextvars。
26
- # 无报错数日后整段删除(含本注)。
27
- # 每个工作流实例独立的上下文变量
28
- # workflow_ctx = contextvars.ContextVar('workflow_ctx', default=None)
29
- #
30
- #
31
- # class WorkflowContext:
32
- # """工作流上下文,存储当前状态、取消事件等"""
33
- # def __init__(self, name: str):
34
- # self.name = name
35
- # self.cancelled = asyncio.Event()
36
- # self.locals: Dict[str, Any] = {}
37
- # self.current_node_id: str = ""
38
- # ━━━ 观察期退役段结束:workflow_ctx / WorkflowContext ━━━
39
-
40
-
41
- class HumanInputManager:
42
- """管理多个等待点的人类输入事件(线程安全)。
43
-
44
- Job 模型增补(运行状态链路重构,施工清单 v3 §5.1):
45
- - ``_aborted``:机制性停止识别(v1 吸收)——stop 流程置位后,所有现在与
46
- 未来的 wait_for_input 调用点统一在恢复点 raise CancelledError,不靠人工
47
- 逐点核对调用方。CancelledError 继承 BaseException(Python 3.8+),
48
- ``except Exception`` 不会误接成正常返回——branch_main / run_async 的既有
49
- ``except CancelledError`` 自然接住(分支安静退场/主流程走 suspended),
50
- 零新增异常类型、零新增传播规则。
51
- - ``abort_all``(A2 方案 A):stop 时对全部 executor 等待者 set 唤醒——
52
- worker 秒退不占锁(旧世界 cancel 打不进 executor,挂满 3600s 超时占死
53
- bridge 单跑锁)。
54
- - ``discard_all``:任何"Runner 就绪开跑"时刻信箱必须从零开始(attach 调用,
55
- 幂等保险;清的是无主滞留信)。
56
- - ``provide_input`` 不变(仍先存 _data 再 set——孤儿信清理不在 provide 侧)。
57
- """
58
-
59
- def __init__(self):
60
- import threading
61
- self._events: Dict[str, threading.Event] = {}
62
- self._data: Dict[str, str] = {}
63
- self._lock = threading.Lock()
64
- self._aborted = False
65
-
66
- async def wait_for_input(self, key: str, timeout: float = None):
67
- import threading
68
- print(f"[AsyncEngine] 👤 等待人类输入 (专属频道: {key})")
69
-
70
- # 快速路径:provide_input 可能已经先到了(前端响应极快时)
71
- with self._lock:
72
- if self._aborted:
73
- # 机制性停止识别:job 已停止,等待点在入口即退出(不上 executor)
74
- raise CancelledError("job paused")
75
- if key in self._data:
76
- print(f"[AsyncEngine] 📩 人类输入已抢先到达 (key={key})")
77
- return self._data.pop(key, "")
78
-
79
- event = threading.Event()
80
- with self._lock:
81
- # double-check:注册 event 前再检查一次,防止 provide_input 在上锁间隙到达
82
- if self._aborted:
83
- raise CancelledError("job paused")
84
- if key in self._data:
85
- print(f"[AsyncEngine] 📩 人类输入在注册 event 时已到达 (key={key})")
86
- return self._data.pop(key, "")
87
- self._events[key] = event
88
-
89
- loop = asyncio.get_running_loop()
90
- # [END 收幕不等人(2026-09-22)] 线程无法被 cancel:收幕/停止掐掉的分支若
91
- # 正卡在 executor 里 event.wait(3600),线程会一直挂到超时——asyncio.run
92
- # 退出时 shutdown_default_executor 要 join 默认线程池,Python 硬编码
93
- # 300s 上限,等满才放弃(RuntimeWarning)——run() 因此整整迟到 5 分钟,
94
- # 桥的终局信与 bridge_run_ended 全链推迟(Job 2314 实锤:flow_done
95
- # 08:21:54,通知 08:26:55)。修法:给 executor future 挂 done-callback,
96
- # 协程被取消(收幕/停止/异常收场)即 event.set()——线程立即退场,
97
- # shutdown 秒级 join。用户拍板语义:只要到了 END,有没有等待人类都不
98
- # 再管了。正常路径(真等到输入/provide_input 先 set)callback 幂等无害;
99
- # _aborted 场景 abort_all 已 set,同样幂等。
100
- future = loop.run_in_executor(None, event.wait, timeout)
101
- future.add_done_callback(lambda _f, _ev=event: _ev.set())
102
- try:
103
- await future
104
- # executor 唤醒后的取数路径:先查 _aborted(abort_all 唤醒的等待者
105
- # 在此恢复点直接吃 CancelledError 零推进,不会拿着空值继续演)
106
- with self._lock:
107
- if self._aborted:
108
- raise CancelledError("job paused")
109
- return self._data.pop(key, "")
110
- finally:
111
- with self._lock:
112
- self._events.pop(key, None)
113
-
114
- def provide_input(self, key: str, data):
115
- with self._lock:
116
- self._data[key] = data
117
- event = self._events.get(key)
118
- if event:
119
- event.set()
120
-
121
- def abort_all(self) -> None:
122
- """唤醒所有 cancel 漏网的 executor 等待者(A2,stop 链 ⑤——先 cancel 后
123
- abort 的顺序红线由 FEMORunner.stop 保证)。锁内置 _aborted 并收集全部
124
- event,锁外逐个 set()——唤醒的等待者在 wait_for_input 取数路径的
125
- _aborted 检查处 raise CancelledError。"""
126
- with self._lock:
127
- self._aborted = True
128
- events = list(self._events.values())
129
- for event in events:
130
- event.set()
131
-
132
- def discard_all(self) -> None:
133
- """信箱从零开始(JobManager.attach 在"Runner 就绪开跑"时刻调用,幂等):
134
- 清无主滞留信——宿主晚到投递把旧 wait_key 数据投进活跃新 manager 的
135
- 污染路径,由 run_tag 世代前缀机制性免疫(§5.6),本清空是同 Runner
136
- 生命周期内的保险层。"""
137
- with self._lock:
138
- self._data.clear()
139
-
140
-
141
- class AsyncEngine:
142
- def __init__(self, cpu_workers: int = None, thread_workers: int = 10):
143
- import threading
144
- print("[AsyncEngine] 初始化引擎...")
145
- cpu_workers = cpu_workers or os.cpu_count() or 4
146
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ process_pool:唯一执行入口 run_in_process 已退役
147
- # (生产链路全部走 run_in_thread,进程池建成之后从未接过任务)。
148
- # shutdown() 里对应的关闭行同步注释。文件头"接口说明"里 run_in_process/run_func
149
- # 两行描述随观察期一并过期,删段时同步改写。无报错数日后整段删除(含本注)。
150
- # self.process_pool = ProcessPoolExecutor(max_workers=cpu_workers)
151
- self.thread_pool = ThreadPoolExecutor(max_workers=thread_workers)
152
- self.human_input = HumanInputManager()
153
- self._active_tasks: Set[asyncio.Task] = set()
154
- # ── LLM 速率控制 (按 source 分组) ──
155
- # (D 收尾 2026-09-05:此处原有一段字面重复赋值(_active_tasks/llm_delay/
156
- # _throttle_locks/_last_call_time/_throttle_meta_lock 各重复一遍)——同
157
- # 名同值幂等覆盖、__init__ 期无并发窗口,删除重复段零行为变化。)
158
- self.llm_delay: float = 0.0
159
- self._throttle_locks: Dict[str, asyncio.Lock] = {}
160
- self._last_call_time: Dict[str, float] = {}
161
- self._throttle_meta_lock = threading.Lock()
162
-
163
-
164
-
165
- def is_event_loop_running(self) -> bool:
166
- """检查当前线程是否已有运行中的事件循环"""
167
- try:
168
- asyncio.get_running_loop()
169
- return True
170
- except RuntimeError:
171
- return False
172
-
173
- def run_async_until_complete(self, coro):
174
- """根据环境自动选择 asyncio.run 或直接 await(由调用方负责)"""
175
- if self.is_event_loop_running():
176
- raise RuntimeError("不能在已有事件循环中调用 run_async_until_complete,请使用 await coro")
177
- return asyncio.run(coro)
178
-
179
- def check_cancel(self):
180
- """检查当前协程是否被取消,若取消则抛出 CancelledError"""
181
- task = asyncio.current_task()
182
- if task and task.cancelled():
183
- raise asyncio.CancelledError("任务被取消")
184
-
185
- def get_running_loop(self):
186
- """返回当前事件循环,供需要直接操作 loop 的场景使用"""
187
- return asyncio.get_running_loop()
188
-
189
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ schedule_threadsafe:全仓零调用(双窗口交叉扫描+逐项复核)。
190
- # 注意:femoGen 画布文档(document_ch/en.html)把它写成公开 API——观察期通过删除本段时,
191
- # 需同步改写画布文档。无报错数日后整段删除(含本注)。
192
- # def schedule_threadsafe(self, callback, *args):
193
- # """线程安全地将回调调度到事件循环中执行"""
194
- # self.get_running_loop().call_soon_threadsafe(callback, *args)
195
- # ━━━ 观察期退役段结束:schedule_threadsafe ━━━
196
-
197
- async def gather(self, *coros, return_exceptions=True):
198
- """封装 asyncio.gather,方便分支等待"""
199
- return await asyncio.gather(*coros, return_exceptions=return_exceptions)
200
-
201
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ run_in_process:生产链路零调用(双窗口交叉扫描+逐项复核)——
202
- # 唯一生产调用方 run_func 自身也是死代码;仅存的两处引用在文件尾 __main__ 自测里
203
- # (观察期内如需跑内嵌自测会在这些行响亮 NameError,属预期)。进程池因此整链退役。
204
- # 无报错数日后整段删除(含本注)。
205
- # async def run_in_process(self, func: Callable, *args, **kwargs) -> Any:
206
- # """CPU 密集任务:自动排队到进程池"""
207
- # print(f"[AsyncEngine] 🧠 分配 CPU 密集任务到进程池 (func={getattr(func, '__name__', func)})")
208
- # loop = asyncio.get_running_loop()
209
- # return await loop.run_in_executor(self.process_pool, func, *args, **kwargs)
210
- # ━━━ 观察期退役段结束:run_in_process ━━━
211
-
212
- async def run_in_thread(self, func: Callable, *args, **kwargs) -> Any:
213
- """
214
- 将快速函数或同步 I/O 提交到线程池。
215
- 为每次调用创建独立的事件循环,确保函数内部能正常使用 asyncio。
216
- """
217
- from functools import partial
218
- print(f"[AsyncEngine] 🧵 分配同步 I/O 或 AI 调用到线程池 (func={getattr(func, '__name__', func)})")
219
-
220
- def _wrapper(*a, **kw):
221
- import asyncio
222
- async def _runner():
223
- return func(*a, **kw)
224
- return asyncio.run(_runner())
225
-
226
- loop = asyncio.get_running_loop()
227
- if kwargs:
228
- wrapped = partial(_wrapper, *args, **kwargs)
229
- return await loop.run_in_executor(self.thread_pool, wrapped)
230
- else:
231
- return await loop.run_in_executor(self.thread_pool, _wrapper, *args)
232
-
233
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ run_func:自称"@func 通用执行入口",
234
- # 实际全仓零调用(双窗口交叉扫描+逐项复核)——现行 @func 全部直接走 run_in_thread。
235
- # 它是进程池链(run_in_process→process_pool)的最后一环。无报错数日后整段删除(含本注)。
236
- # async def run_func(self, func: Callable, *args, mode: str = 'process', **kwargs) -> Any:
237
- # """
238
- # 通用执行入口,支持后续扩展自动判断。
239
- # 目前 mode 默认为 'process',即所有 @func 先走进程池。
240
- # 未来可根据用户标注或自动检测切换到 'thread'。
241
- # """
242
- # if mode == 'process':
243
- # return await self.run_in_process(func, *args, **kwargs)
244
- # elif mode == 'thread':
245
- # return await self.run_in_thread(func, *args, **kwargs)
246
- # else:
247
- # raise ValueError(f"Unknown execution mode: {mode}")
248
- # ━━━ 观察期退役段结束:run_func ━━━
249
-
250
- def create_task(self, coro: Coroutine) -> asyncio.Task:
251
- task = asyncio.create_task(coro)
252
- self._active_tasks.add(task)
253
- task.add_done_callback(self._active_tasks.discard)
254
- return task
255
-
256
- async def gather_with_cancel(self, tasks: list, return_when: str = 'all',
257
- count: int = 1) -> list:
258
- if not tasks:
259
- return []
260
- if return_when == 'all':
261
- return await asyncio.gather(*tasks, return_exceptions=True)
262
-
263
- pending = set(tasks)
264
- required = 1 if return_when == 'any' else int(count)
265
- finished_results = {}
266
- while pending and len(finished_results) < required:
267
- done, pending = await asyncio.wait(
268
- pending, return_when=asyncio.FIRST_COMPLETED
269
- )
270
- for task in done:
271
- idx = tasks.index(task)
272
- try:
273
- finished_results[idx] = task.result()
274
- except asyncio.CancelledError:
275
- finished_results[idx] = None
276
- except Exception as e:
277
- finished_results[idx] = e
278
-
279
- for task in pending:
280
- task.cancel()
281
- await asyncio.gather(*pending, return_exceptions=True)
282
-
283
- # 按原顺序排列结果
284
- final = [None] * len(tasks)
285
- for idx, val in finished_results.items():
286
- final[idx] = val
287
- return final
288
-
289
- async def throttle_llm(self, resource: str, delay: float = None):
290
- """
291
- 确保对同一 resource 的连续调用至少间隔 delay 秒。
292
- 若 delay 为 None,使用 self.llm_delay。delay <= 0 则不限流。
293
- """
294
- if delay is None:
295
- delay = self.llm_delay
296
- if delay <= 0:
297
- return
298
-
299
- # 获取或创建 resource 专用锁
300
- with self._throttle_meta_lock:
301
- if resource not in self._throttle_locks:
302
- self._throttle_locks[resource] = asyncio.Lock()
303
- lock = self._throttle_locks[resource]
304
-
305
- async with lock:
306
- loop = asyncio.get_running_loop()
307
- now = loop.time()
308
- last = self._last_call_time.get(resource, 0.0)
309
- wait_time = delay - (now - last)
310
- if wait_time > 0:
311
- await asyncio.sleep(wait_time)
312
- self._last_call_time[resource] = loop.time()
313
-
314
- async def shutdown(self):
315
- for task in list(self._active_tasks):
316
- task.cancel()
317
- if self._active_tasks:
318
- await asyncio.gather(*self._active_tasks, return_exceptions=True)
319
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ 随 process_pool 创建行一并退役(见 __init__ 注)。
320
- # self.process_pool.shutdown(wait=True)
321
- self.thread_pool.shutdown(wait=True)
322
-
323
-
324
- # ============================================================
325
- # 测试辅助函数(必须定义在顶层以便 pickle)
326
- # ============================================================
327
- def _heavy_computation(n):
328
- """纯 CPU 密集函数,用于测试进程池"""
329
- total = 0
330
- for i in range(n):
331
- total += i * i
332
- return total
333
-
334
-
335
- # ============================================================
336
- # 测试用例
337
- # ============================================================
338
- async def _test_cpu_task():
339
- engine = AsyncEngine()
340
- print("Testing CPU task via process pool...")
341
- result = await engine.run_in_process(_heavy_computation, 10_000_000)
342
- print(f"CPU task result: {result}")
343
-
344
- # 测试并发排队
345
- tasks = [engine.run_in_process(_heavy_computation, 5_000_000) for _ in range(10)]
346
- results = await asyncio.gather(*tasks)
347
- print(f"10 concurrent CPU tasks completed, sample: {results[:3]}")
348
- await engine.shutdown()
349
-
350
-
351
- async def _test_fork_join():
352
- engine = AsyncEngine()
353
-
354
- async def branch(name, sleep_time):
355
- try:
356
- await asyncio.sleep(sleep_time)
357
- print(f"Branch {name} finished")
358
- return f"{name}_result"
359
- except asyncio.CancelledError:
360
- print(f"Branch {name} cancelled")
361
- raise
362
-
363
- print("\n=== Test gather all ===")
364
- t1 = engine.create_task(branch("A", 1))
365
- t2 = engine.create_task(branch("B", 1.5))
366
- results = await engine.gather_with_cancel([t1, t2], return_when='all')
367
- print("All results:", results)
368
-
369
- print("\n=== Test any (cancel others) ===")
370
- t3 = engine.create_task(branch("C", 2))
371
- t4 = engine.create_task(branch("D", 0.5))
372
- results = await engine.gather_with_cancel([t3, t4], return_when='any')
373
- print("Any results:", results)
374
-
375
- print("\n=== Test n=1 ===")
376
- t5 = engine.create_task(branch("E", 1.5))
377
- t6 = engine.create_task(branch("F", 0.8))
378
- t7 = engine.create_task(branch("G", 2))
379
- results = await engine.gather_with_cancel([t5, t6, t7], return_when='n', count=1)
380
- print("N=1 results:", results)
381
-
382
- await engine.shutdown()
383
-
384
-
385
- async def _test_human_input():
386
- engine = AsyncEngine()
387
-
388
- async def wait_human(key):
389
- print(f"[{key}] Waiting for human input...")
390
- data = await engine.human_input.wait_for_input(key)
391
- print(f"[{key}] Received: {data}")
392
- return data
393
-
394
- t1 = engine.create_task(wait_human("user1"))
395
- t2 = engine.create_task(wait_human("user2"))
396
-
397
- async def provider():
398
- await asyncio.sleep(1)
399
- engine.human_input.provide_input("user1", "Hello from user1")
400
- await asyncio.sleep(0.5)
401
- engine.human_input.provide_input("user2", "Hi from user2")
402
-
403
- p = asyncio.create_task(provider())
404
- results = await asyncio.gather(t1, t2, p)
405
- print("Human input results:", results[:2])
406
- await engine.shutdown()
407
-
408
-
409
- async def _test_context_vars():
410
- ctx_var = contextvars.ContextVar('test_key', default='default')
411
-
412
- async def worker(name, val):
413
- ctx_var.set(val)
414
- await asyncio.sleep(0.1)
415
- return f"{name}: {ctx_var.get()}"
416
-
417
- engine = AsyncEngine()
418
- t1 = engine.create_task(worker("A", "value_A"))
419
- t2 = engine.create_task(worker("B", "value_B"))
420
- results = await asyncio.gather(t1, t2)
421
- print("Context var isolation:", results)
422
- await engine.shutdown()
423
-
424
-
425
- def main():
426
- async def run_all():
427
- await _test_cpu_task()
428
- await _test_fork_join()
429
- await _test_human_input()
430
- await _test_context_vars()
431
- print("\nAll tests completed.")
432
- asyncio.run(run_all())
433
-
434
-
435
- if __name__ == "__main__":
436
- main()
1
+ # femoCompiler/femoAsync.py
2
+ """
3
+ 多 Agent 并发引擎 - asyncio 版本
4
+ 提供: 协程任务管理, 进程池(CPU 密集), 线程池(快速/兜底), 人类输入异步等待
5
+
6
+ 接口说明:
7
+ - run_in_process(func, *args, **kwargs): 强制使用进程池执行(默认所有 @func 走这里)
8
+ - run_in_thread(func, *args, **kwargs): 强制使用线程池执行
9
+ - run_func(func, *args, mode='process', **kwargs): 通用入口,根据 mode 路由
10
+ - create_task(coro): 创建协程任务(用于 fork 分支)
11
+ - gather_with_cancel(tasks, return_when='all', count=1): 等待多个协程任务
12
+ - human_input.wait_for_input(key, timeout): 异步等待人类输入
13
+ """
14
+
15
+ import asyncio
16
+ # 在 import asyncio 下方添加(如果有需要的话,但 FEMO_runtime 会导入这个)
17
+ CancelledError = asyncio.CancelledError
18
+ import os
19
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
20
+ from typing import Any, Callable, Coroutine, Dict, Optional, Set
21
+ import contextvars
22
+
23
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ workflow_ctx / WorkflowContext:
24
+ # 早期"工作流上下文"设计的残留,全仓零引用(双窗口交叉扫描+逐项复核),
25
+ # 连本文件尾部的 __main__ 自测都不用它们;现行簿记走 FEMO_runtime 的 task_ctx/contextvars。
26
+ # 无报错数日后整段删除(含本注)。
27
+ # 每个工作流实例独立的上下文变量
28
+ # workflow_ctx = contextvars.ContextVar('workflow_ctx', default=None)
29
+ #
30
+ #
31
+ # class WorkflowContext:
32
+ # """工作流上下文,存储当前状态、取消事件等"""
33
+ # def __init__(self, name: str):
34
+ # self.name = name
35
+ # self.cancelled = asyncio.Event()
36
+ # self.locals: Dict[str, Any] = {}
37
+ # self.current_node_id: str = ""
38
+ # ━━━ 观察期退役段结束:workflow_ctx / WorkflowContext ━━━
39
+
40
+
41
+ class HumanInputManager:
42
+ """管理多个等待点的人类输入事件(线程安全)。
43
+
44
+ Job 模型增补(运行状态链路重构,施工清单 v3 §5.1):
45
+ - ``_aborted``:机制性停止识别(v1 吸收)——stop 流程置位后,所有现在与
46
+ 未来的 wait_for_input 调用点统一在恢复点 raise CancelledError,不靠人工
47
+ 逐点核对调用方。CancelledError 继承 BaseException(Python 3.8+),
48
+ ``except Exception`` 不会误接成正常返回——branch_main / run_async 的既有
49
+ ``except CancelledError`` 自然接住(分支安静退场/主流程走 suspended),
50
+ 零新增异常类型、零新增传播规则。
51
+ - ``abort_all``(A2 方案 A):stop 时对全部 executor 等待者 set 唤醒——
52
+ worker 秒退不占锁(旧世界 cancel 打不进 executor,挂满 3600s 超时占死
53
+ bridge 单跑锁)。
54
+ - ``discard_all``:任何"Runner 就绪开跑"时刻信箱必须从零开始(attach 调用,
55
+ 幂等保险;清的是无主滞留信)。
56
+ - ``provide_input`` 不变(仍先存 _data 再 set——孤儿信清理不在 provide 侧)。
57
+ """
58
+
59
+ def __init__(self):
60
+ import threading
61
+ self._events: Dict[str, threading.Event] = {}
62
+ self._data: Dict[str, str] = {}
63
+ self._lock = threading.Lock()
64
+ self._aborted = False
65
+
66
+ async def wait_for_input(self, key: str, timeout: float = None):
67
+ import threading
68
+ print(f"[AsyncEngine] 👤 等待人类输入 (专属频道: {key})")
69
+
70
+ # 快速路径:provide_input 可能已经先到了(前端响应极快时)
71
+ with self._lock:
72
+ if self._aborted:
73
+ # 机制性停止识别:job 已停止,等待点在入口即退出(不上 executor)
74
+ raise CancelledError("job paused")
75
+ if key in self._data:
76
+ print(f"[AsyncEngine] 📩 人类输入已抢先到达 (key={key})")
77
+ return self._data.pop(key, "")
78
+
79
+ event = threading.Event()
80
+ with self._lock:
81
+ # double-check:注册 event 前再检查一次,防止 provide_input 在上锁间隙到达
82
+ if self._aborted:
83
+ raise CancelledError("job paused")
84
+ if key in self._data:
85
+ print(f"[AsyncEngine] 📩 人类输入在注册 event 时已到达 (key={key})")
86
+ return self._data.pop(key, "")
87
+ self._events[key] = event
88
+
89
+ loop = asyncio.get_running_loop()
90
+ # [END 收幕不等人(2026-09-22)] 线程无法被 cancel:收幕/停止掐掉的分支若
91
+ # 正卡在 executor 里 event.wait(3600),线程会一直挂到超时——asyncio.run
92
+ # 退出时 shutdown_default_executor 要 join 默认线程池,Python 硬编码
93
+ # 300s 上限,等满才放弃(RuntimeWarning)——run() 因此整整迟到 5 分钟,
94
+ # 桥的终局信与 bridge_run_ended 全链推迟(Job 2314 实锤:flow_done
95
+ # 08:21:54,通知 08:26:55)。修法:给 executor future 挂 done-callback,
96
+ # 协程被取消(收幕/停止/异常收场)即 event.set()——线程立即退场,
97
+ # shutdown 秒级 join。用户拍板语义:只要到了 END,有没有等待人类都不
98
+ # 再管了。正常路径(真等到输入/provide_input 先 set)callback 幂等无害;
99
+ # _aborted 场景 abort_all 已 set,同样幂等。
100
+ future = loop.run_in_executor(None, event.wait, timeout)
101
+ future.add_done_callback(lambda _f, _ev=event: _ev.set())
102
+ try:
103
+ await future
104
+ # executor 唤醒后的取数路径:先查 _aborted(abort_all 唤醒的等待者
105
+ # 在此恢复点直接吃 CancelledError 零推进,不会拿着空值继续演)
106
+ with self._lock:
107
+ if self._aborted:
108
+ raise CancelledError("job paused")
109
+ return self._data.pop(key, "")
110
+ finally:
111
+ with self._lock:
112
+ self._events.pop(key, None)
113
+
114
+ def provide_input(self, key: str, data):
115
+ with self._lock:
116
+ self._data[key] = data
117
+ event = self._events.get(key)
118
+ if event:
119
+ event.set()
120
+
121
+ def abort_all(self) -> None:
122
+ """唤醒所有 cancel 漏网的 executor 等待者(A2,stop 链 ⑤——先 cancel 后
123
+ abort 的顺序红线由 FEMORunner.stop 保证)。锁内置 _aborted 并收集全部
124
+ event,锁外逐个 set()——唤醒的等待者在 wait_for_input 取数路径的
125
+ _aborted 检查处 raise CancelledError。"""
126
+ with self._lock:
127
+ self._aborted = True
128
+ events = list(self._events.values())
129
+ for event in events:
130
+ event.set()
131
+
132
+ def discard_all(self) -> None:
133
+ """信箱从零开始(JobManager.attach 在"Runner 就绪开跑"时刻调用,幂等):
134
+ 清无主滞留信——宿主晚到投递把旧 wait_key 数据投进活跃新 manager 的
135
+ 污染路径,由 run_tag 世代前缀机制性免疫(§5.6),本清空是同 Runner
136
+ 生命周期内的保险层。"""
137
+ with self._lock:
138
+ self._data.clear()
139
+
140
+
141
+ class AsyncEngine:
142
+ def __init__(self, cpu_workers: int = None, thread_workers: int = 10):
143
+ import threading
144
+ print("[AsyncEngine] 初始化引擎...")
145
+ cpu_workers = cpu_workers or os.cpu_count() or 4
146
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ process_pool:唯一执行入口 run_in_process 已退役
147
+ # (生产链路全部走 run_in_thread,进程池建成之后从未接过任务)。
148
+ # shutdown() 里对应的关闭行同步注释。文件头"接口说明"里 run_in_process/run_func
149
+ # 两行描述随观察期一并过期,删段时同步改写。无报错数日后整段删除(含本注)。
150
+ # self.process_pool = ProcessPoolExecutor(max_workers=cpu_workers)
151
+ self.thread_pool = ThreadPoolExecutor(max_workers=thread_workers)
152
+ self.human_input = HumanInputManager()
153
+ self._active_tasks: Set[asyncio.Task] = set()
154
+ # ── LLM 速率控制 (按 source 分组) ──
155
+ # (D 收尾 2026-09-05:此处原有一段字面重复赋值(_active_tasks/llm_delay/
156
+ # _throttle_locks/_last_call_time/_throttle_meta_lock 各重复一遍)——同
157
+ # 名同值幂等覆盖、__init__ 期无并发窗口,删除重复段零行为变化。)
158
+ self.llm_delay: float = 0.0
159
+ self._throttle_locks: Dict[str, asyncio.Lock] = {}
160
+ self._last_call_time: Dict[str, float] = {}
161
+ self._throttle_meta_lock = threading.Lock()
162
+ # ── 在途线程计数(2026-10-13 遗弃语义):收场不再等线程下班(shutdown
163
+ # 改 wait=False),但「遗弃了几个」必须点名留痕——提交时 +1、线程退场
164
+ # finally -1,shutdown 时读差值响亮报数。
165
+ self._inflight = 0
166
+ self._inflight_lock = threading.Lock()
167
+
168
+
169
+
170
+ def is_event_loop_running(self) -> bool:
171
+ """检查当前线程是否已有运行中的事件循环"""
172
+ try:
173
+ asyncio.get_running_loop()
174
+ return True
175
+ except RuntimeError:
176
+ return False
177
+
178
+ def run_async_until_complete(self, coro):
179
+ """根据环境自动选择 asyncio.run 或直接 await(由调用方负责)"""
180
+ if self.is_event_loop_running():
181
+ raise RuntimeError("不能在已有事件循环中调用 run_async_until_complete,请使用 await coro")
182
+ return asyncio.run(coro)
183
+
184
+ def check_cancel(self):
185
+ """检查当前协程是否被取消,若取消则抛出 CancelledError"""
186
+ task = asyncio.current_task()
187
+ if task and task.cancelled():
188
+ raise asyncio.CancelledError("任务被取消")
189
+
190
+ def get_running_loop(self):
191
+ """返回当前事件循环,供需要直接操作 loop 的场景使用"""
192
+ return asyncio.get_running_loop()
193
+
194
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ schedule_threadsafe:全仓零调用(双窗口交叉扫描+逐项复核)。
195
+ # 注意:femoGen 画布文档(document_ch/en.html)把它写成公开 API——观察期通过删除本段时,
196
+ # 需同步改写画布文档。无报错数日后整段删除(含本注)。
197
+ # def schedule_threadsafe(self, callback, *args):
198
+ # """线程安全地将回调调度到事件循环中执行"""
199
+ # self.get_running_loop().call_soon_threadsafe(callback, *args)
200
+ # ━━━ 观察期退役段结束:schedule_threadsafe ━━━
201
+
202
+ async def gather(self, *coros, return_exceptions=True):
203
+ """封装 asyncio.gather,方便分支等待"""
204
+ return await asyncio.gather(*coros, return_exceptions=return_exceptions)
205
+
206
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ run_in_process:生产链路零调用(双窗口交叉扫描+逐项复核)——
207
+ # 唯一生产调用方 run_func 自身也是死代码;仅存的两处引用在文件尾 __main__ 自测里
208
+ # (观察期内如需跑内嵌自测会在这些行响亮 NameError,属预期)。进程池因此整链退役。
209
+ # 无报错数日后整段删除(含本注)。
210
+ # async def run_in_process(self, func: Callable, *args, **kwargs) -> Any:
211
+ # """CPU 密集任务:自动排队到进程池"""
212
+ # print(f"[AsyncEngine] 🧠 分配 CPU 密集任务到进程池 (func={getattr(func, '__name__', func)})")
213
+ # loop = asyncio.get_running_loop()
214
+ # return await loop.run_in_executor(self.process_pool, func, *args, **kwargs)
215
+ # ━━━ 观察期退役段结束:run_in_process ━━━
216
+
217
+ def _thread_entry(self, func: Callable, args: tuple, kwargs: dict):
218
+ """线程体:包一层 asyncio.run(函数内部可能用 asyncio)。退场时在途计数减一。"""
219
+ import asyncio
220
+ async def _runner():
221
+ return func(*args, **kwargs)
222
+ try:
223
+ return asyncio.run(_runner())
224
+ finally:
225
+ with self._inflight_lock:
226
+ self._inflight -= 1
227
+
228
+ def submit_in_thread(self, func: Callable, *args, **kwargs):
229
+ """同 run_in_thread 的线程提交,但返回底层 concurrent Future、不 await。
230
+
231
+ 接续模式(2026-10-13 拍板「遗弃/接续」停止语义)专用:协程侧
232
+ ``await asyncio.wrap_future(cf)``,取消只取消协程、不取消线程——
233
+ future 由此可以登记进接续登记簿(func_registry),被续跑方重新
234
+ await 接上,或跑完后由 done-callback 收割结果存档。"""
235
+ with self._inflight_lock:
236
+ self._inflight += 1
237
+ return self.thread_pool.submit(self._thread_entry, func, args, kwargs)
238
+
239
+ async def run_in_thread(self, func: Callable, *args, **kwargs) -> Any:
240
+ """
241
+ 将快速函数或同步 I/O 提交到线程池。
242
+ 为每次调用创建独立的事件循环,确保函数内部能正常使用 asyncio。
243
+ """
244
+ print(f"[AsyncEngine] 🧵 分配同步 I/O 或 AI 调用到线程池 (func={getattr(func, '__name__', func)})")
245
+ cf = self.submit_in_thread(func, *args, **kwargs)
246
+ return await asyncio.wrap_future(cf)
247
+
248
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ run_func:自称"@func 通用执行入口",
249
+ # 实际全仓零调用(双窗口交叉扫描+逐项复核)——现行 @func 全部直接走 run_in_thread。
250
+ # 它是进程池链(run_in_process→process_pool)的最后一环。无报错数日后整段删除(含本注)。
251
+ # async def run_func(self, func: Callable, *args, mode: str = 'process', **kwargs) -> Any:
252
+ # """
253
+ # 通用执行入口,支持后续扩展自动判断。
254
+ # 目前 mode 默认为 'process',即所有 @func 先走进程池。
255
+ # 未来可根据用户标注或自动检测切换到 'thread'。
256
+ # """
257
+ # if mode == 'process':
258
+ # return await self.run_in_process(func, *args, **kwargs)
259
+ # elif mode == 'thread':
260
+ # return await self.run_in_thread(func, *args, **kwargs)
261
+ # else:
262
+ # raise ValueError(f"Unknown execution mode: {mode}")
263
+ # ━━━ 观察期退役段结束:run_func ━━━
264
+
265
+ def create_task(self, coro: Coroutine) -> asyncio.Task:
266
+ task = asyncio.create_task(coro)
267
+ self._active_tasks.add(task)
268
+ task.add_done_callback(self._active_tasks.discard)
269
+ return task
270
+
271
+ async def gather_with_cancel(self, tasks: list, return_when: str = 'all',
272
+ count: int = 1) -> list:
273
+ if not tasks:
274
+ return []
275
+ if return_when == 'all':
276
+ return await asyncio.gather(*tasks, return_exceptions=True)
277
+
278
+ pending = set(tasks)
279
+ required = 1 if return_when == 'any' else int(count)
280
+ finished_results = {}
281
+ while pending and len(finished_results) < required:
282
+ done, pending = await asyncio.wait(
283
+ pending, return_when=asyncio.FIRST_COMPLETED
284
+ )
285
+ for task in done:
286
+ idx = tasks.index(task)
287
+ try:
288
+ finished_results[idx] = task.result()
289
+ except asyncio.CancelledError:
290
+ finished_results[idx] = None
291
+ except Exception as e:
292
+ finished_results[idx] = e
293
+
294
+ for task in pending:
295
+ task.cancel()
296
+ await asyncio.gather(*pending, return_exceptions=True)
297
+
298
+ # 按原顺序排列结果
299
+ final = [None] * len(tasks)
300
+ for idx, val in finished_results.items():
301
+ final[idx] = val
302
+ return final
303
+
304
+ async def throttle_llm(self, resource: str, delay: float = None):
305
+ """
306
+ 确保对同一 resource 的连续调用至少间隔 delay 秒。
307
+ 若 delay 为 None,使用 self.llm_delay。delay <= 0 则不限流。
308
+ """
309
+ if delay is None:
310
+ delay = self.llm_delay
311
+ if delay <= 0:
312
+ return
313
+
314
+ # 获取或创建 resource 专用锁
315
+ with self._throttle_meta_lock:
316
+ if resource not in self._throttle_locks:
317
+ self._throttle_locks[resource] = asyncio.Lock()
318
+ lock = self._throttle_locks[resource]
319
+
320
+ async with lock:
321
+ loop = asyncio.get_running_loop()
322
+ now = loop.time()
323
+ last = self._last_call_time.get(resource, 0.0)
324
+ wait_time = delay - (now - last)
325
+ if wait_time > 0:
326
+ await asyncio.sleep(wait_time)
327
+ self._last_call_time[resource] = loop.time()
328
+
329
+ async def shutdown(self):
330
+ for task in list(self._active_tasks):
331
+ task.cancel()
332
+ if self._active_tasks:
333
+ await asyncio.gather(*self._active_tasks, return_exceptions=True)
334
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ 随 process_pool 创建行一并退役(见 __init__ 注)。
335
+ # self.process_pool.shutdown(wait=True)
336
+ # ━━━ 观察期退役段结束:process_pool.shutdown ━━━
337
+ # ── 遗弃语义(2026-10-13 拍板,三病案同根治):收场不再等函数线程下班。
338
+ # 旧法 shutdown(wait=True) 把 worker 退场时间绑给最慢的在跑线程——睡
339
+ # 100~300 秒的选人函数一被暂停就撞 job_pause 的 join 上限,触发强停
340
+ # 自尽整个引擎(2734 场实锤,暂停 10.2s join 打满 → os._exit → 重生)。
341
+ # 新法:不等、不杀(Python 也杀不了线程),在途线程遗弃后台自灭;
342
+ # 接续模式的调用完成后由 done-callback 把结果登记进 func_registry
343
+ # 供续跑取用。cancel_futures 撤掉还在排队的(没开跑的不再开跑)。
344
+ # wait=False 后本池不再收新活——本引擎对象随 run 结束一并废弃,无
345
+ # 后续提交方(wait_empty 落库等待在本调用之前已经完成)。
346
+ with self._inflight_lock:
347
+ inflight = self._inflight
348
+ if inflight:
349
+ print(f"[AsyncEngine] ⏹ 遗弃 {inflight} 个在跑线程(结果作废,后台自灭;"
350
+ f"接续模式的调用完成后结果会登记进接续登记簿供续跑取用)")
351
+ self.thread_pool.shutdown(wait=False, cancel_futures=True)
352
+
353
+
354
+ # ============================================================
355
+ # 测试辅助函数(必须定义在顶层以便 pickle)
356
+ # ============================================================
357
+ def _heavy_computation(n):
358
+ """纯 CPU 密集函数,用于测试进程池"""
359
+ total = 0
360
+ for i in range(n):
361
+ total += i * i
362
+ return total
363
+
364
+
365
+ # ============================================================
366
+ # 测试用例
367
+ # ============================================================
368
+ async def _test_cpu_task():
369
+ engine = AsyncEngine()
370
+ print("Testing CPU task via process pool...")
371
+ result = await engine.run_in_process(_heavy_computation, 10_000_000)
372
+ print(f"CPU task result: {result}")
373
+
374
+ # 测试并发排队
375
+ tasks = [engine.run_in_process(_heavy_computation, 5_000_000) for _ in range(10)]
376
+ results = await asyncio.gather(*tasks)
377
+ print(f"10 concurrent CPU tasks completed, sample: {results[:3]}")
378
+ await engine.shutdown()
379
+
380
+
381
+ async def _test_fork_join():
382
+ engine = AsyncEngine()
383
+
384
+ async def branch(name, sleep_time):
385
+ try:
386
+ await asyncio.sleep(sleep_time)
387
+ print(f"Branch {name} finished")
388
+ return f"{name}_result"
389
+ except asyncio.CancelledError:
390
+ print(f"Branch {name} cancelled")
391
+ raise
392
+
393
+ print("\n=== Test gather all ===")
394
+ t1 = engine.create_task(branch("A", 1))
395
+ t2 = engine.create_task(branch("B", 1.5))
396
+ results = await engine.gather_with_cancel([t1, t2], return_when='all')
397
+ print("All results:", results)
398
+
399
+ print("\n=== Test any (cancel others) ===")
400
+ t3 = engine.create_task(branch("C", 2))
401
+ t4 = engine.create_task(branch("D", 0.5))
402
+ results = await engine.gather_with_cancel([t3, t4], return_when='any')
403
+ print("Any results:", results)
404
+
405
+ print("\n=== Test n=1 ===")
406
+ t5 = engine.create_task(branch("E", 1.5))
407
+ t6 = engine.create_task(branch("F", 0.8))
408
+ t7 = engine.create_task(branch("G", 2))
409
+ results = await engine.gather_with_cancel([t5, t6, t7], return_when='n', count=1)
410
+ print("N=1 results:", results)
411
+
412
+ await engine.shutdown()
413
+
414
+
415
+ async def _test_human_input():
416
+ engine = AsyncEngine()
417
+
418
+ async def wait_human(key):
419
+ print(f"[{key}] Waiting for human input...")
420
+ data = await engine.human_input.wait_for_input(key)
421
+ print(f"[{key}] Received: {data}")
422
+ return data
423
+
424
+ t1 = engine.create_task(wait_human("user1"))
425
+ t2 = engine.create_task(wait_human("user2"))
426
+
427
+ async def provider():
428
+ await asyncio.sleep(1)
429
+ engine.human_input.provide_input("user1", "Hello from user1")
430
+ await asyncio.sleep(0.5)
431
+ engine.human_input.provide_input("user2", "Hi from user2")
432
+
433
+ p = asyncio.create_task(provider())
434
+ results = await asyncio.gather(t1, t2, p)
435
+ print("Human input results:", results[:2])
436
+ await engine.shutdown()
437
+
438
+
439
+ async def _test_context_vars():
440
+ ctx_var = contextvars.ContextVar('test_key', default='default')
441
+
442
+ async def worker(name, val):
443
+ ctx_var.set(val)
444
+ await asyncio.sleep(0.1)
445
+ return f"{name}: {ctx_var.get()}"
446
+
447
+ engine = AsyncEngine()
448
+ t1 = engine.create_task(worker("A", "value_A"))
449
+ t2 = engine.create_task(worker("B", "value_B"))
450
+ results = await asyncio.gather(t1, t2)
451
+ print("Context var isolation:", results)
452
+ await engine.shutdown()
453
+
454
+
455
+ def main():
456
+ async def run_all():
457
+ await _test_cpu_task()
458
+ await _test_fork_join()
459
+ await _test_human_input()
460
+ await _test_context_vars()
461
+ print("\nAll tests completed.")
462
+ asyncio.run(run_all())
463
+
464
+
465
+ if __name__ == "__main__":
466
+ main()