()
| 2174 | )) |
| 2175 | |
| 2176 | def _do_dispatch(): |
| 2177 | try: |
| 2178 | # Gateway 可能暂时不可达(休眠恢复、进程重启),等待后重试 |
| 2179 | import time as _time |
| 2180 | _gw_alive = False |
| 2181 | for _gw_attempt in range(3): |
| 2182 | if _check_gateway_alive(): |
| 2183 | _gw_alive = True |
| 2184 | break |
| 2185 | if _gw_attempt < 2: |
| 2186 | _time.sleep(5 * (_gw_attempt + 1)) # 5s, 10s |
| 2187 | if not _gw_alive: |
| 2188 | log.warning(f'⚠️ {task_id} 自动派发跳过: Gateway 未启动(重试3次仍不可达)') |
| 2189 | _update_task_scheduler(task_id, lambda t, s: s.update({ |
| 2190 | 'lastDispatchAt': now_iso(), |
| 2191 | 'lastDispatchStatus': 'gateway-offline', |
| 2192 | 'lastDispatchAgent': agent_id, |
| 2193 | 'lastDispatchTrigger': trigger, |
| 2194 | })) |
| 2195 | return |
| 2196 | # Fix #139/#182: dispatch channel 可配置;未配置时不传 --deliver 避免 |
| 2197 | # "unknown channel: feishu" 错误(非飞书用户) |
| 2198 | _agent_cfg = read_json(DATA / 'agent_config.json', {}) |
| 2199 | _channel = (_agent_cfg.get('dispatchChannel') or '').strip() |
| 2200 | openclaw_bin = _resolve_openclaw_bin() |
| 2201 | if not openclaw_bin: |
| 2202 | err = 'OpenClaw CLI 未找到:请确认已安装 openclaw 并加入 PATH;Windows 可设置 OPENCLAW_BIN 指向 openclaw.cmd' |
| 2203 | log.warning(f'⚠️ {task_id} 自动派发异常: {err}') |
| 2204 | _update_task_scheduler(task_id, lambda t, s: ( |
| 2205 | s.update({ |
| 2206 | 'lastDispatchAt': now_iso(), |
| 2207 | 'lastDispatchStatus': 'openclaw-missing', |
| 2208 | 'lastDispatchAgent': agent_id, |
| 2209 | 'lastDispatchTrigger': trigger, |
| 2210 | 'lastDispatchError': err, |
| 2211 | }), |
| 2212 | _scheduler_add_flow(t, f'派发异常:OpenClaw CLI 未找到({trigger})', to=t.get('org', '')) |
| 2213 | )) |
| 2214 | return |
| 2215 | cmd = [openclaw_bin, 'agent', '--agent', agent_id, '-m', msg, '--timeout', '300'] |
| 2216 | if _channel: |
| 2217 | cmd.extend(['--deliver', '--channel', _channel]) |
| 2218 | max_retries = 2 |
| 2219 | err = '' |
| 2220 | for attempt in range(1, max_retries + 1): |
| 2221 | log.info(f'🔄 自动派发 {task_id} → {agent_id} (第{attempt}次)...') |
| 2222 | result = subprocess.run(cmd, capture_output=True, text=True, timeout=310) |
| 2223 | if result.returncode == 0: |
| 2224 | log.info(f'✅ {task_id} 自动派发成功 → {agent_id}') |
| 2225 | _update_task_scheduler(task_id, lambda t, s: ( |
| 2226 | s.update({ |
| 2227 | 'lastDispatchAt': now_iso(), |
| 2228 | 'lastDispatchStatus': 'success', |
| 2229 | 'lastDispatchAgent': agent_id, |
| 2230 | 'lastDispatchTrigger': trigger, |
| 2231 | 'lastDispatchError': '', |
| 2232 | }), |
| 2233 | _scheduler_add_flow(t, f'派发成功:{agent_id}({trigger})', to=t.get('org', '')) |
nothing calls this directly
no test coverage detected