Repository navigation
Expand file tree
/
Copy pathruntime.py
More file actions
1948 lines (1717 loc) · 79.2 KB
/
Copy pathruntime.py
File metadata and controls
1948 lines (1717 loc) · 79.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Runtime primitives for Feishu Bridge."""
import contextlib
import json
import logging
import os
import queue
import re
import signal
import subprocess
import tempfile
import threading
import time
from abc import ABC, abstractmethod
from collections import OrderedDict, deque
from dataclasses import dataclass, field
from importlib.resources import as_file, files
from pathlib import Path
from typing import ClassVar, Optional
log = logging.getLogger("feishu-bridge")
def pick_primary_model(model_usage: dict, configured: str | None) -> str | None:
"""从 modelUsage 中挑选主模型名。
配置的模型(runner.model)若出现在 modelUsage 中则直接采用;
否则回退到 token 用量最大的条目。避免 /new 后首个 turn 的 haiku
(title gen / autocompact probe) 因 dict 插入顺序被误识别为主模型。
"""
if not model_usage:
return None
if configured and configured in model_usage:
return configured
def _tok(mu: dict) -> int:
return (mu.get("inputTokens", 0)
+ mu.get("outputTokens", 0)
+ mu.get("cacheReadInputTokens", 0)
+ mu.get("cacheCreationInputTokens", 0))
return max(model_usage.items(), key=lambda kv: _tok(kv[1]))[0]
DEFAULT_TIMEOUT = 300 # 5 minutes
SILENT_TIMEOUT = 480 # 8 min — no assistant text output
BG_AGENT_SILENT_TIMEOUT = 3600 # 1 hour — background agents (e.g. Codex review)
TOOL_ACTIVE_SILENT_TIMEOUT = 1800 # 30 min — a runner tool is actively executing
DEDUP_TTL = 43200 # 12 hours
def compute_silent_budget(base_silent: int, *, bg_agent_running: bool,
tool_active_count: int,
tool_active_enabled: bool) -> int:
"""Synthesize the silent-output timeout budget from concurrent liveness signals.
The budget is the max of three terms so any active signal can only *raise* the
window, never shrink it below the base hang-floor:
- ``base_silent`` — always; the floor that still catches a genuinely hung model.
- ``BG_AGENT_SILENT_TIMEOUT`` — when a background agent is running (Claude path).
- ``TOOL_ACTIVE_SILENT_TIMEOUT`` — when a runner tool is mid-execution (pi path),
gated by ``tool_active_enabled`` (the ``PI_TOOL_ACTIVE_BUDGET_ENABLED`` flag).
Pure function (no I/O) so the budget logic is unit-testable in isolation and the
loop has a single deterministic recompute point.
"""
budget = base_silent
if bg_agent_running:
budget = max(budget, BG_AGENT_SILENT_TIMEOUT)
if tool_active_enabled and tool_active_count > 0:
budget = max(budget, TOOL_ACTIVE_SILENT_TIMEOUT)
return budget
DEDUP_MAX = 5000
QUEUE_MAX = 50
MAX_PROMPT_CHARS = 50_000
# Static resources — materialized once at startup via ExitStack
_DATA = files("feishu_bridge.data")
_resource_stack = contextlib.ExitStack()
_BRIDGE_SETTINGS_PATH: Optional[str] = None
def materialize_data_files():
"""Extract data files and hold them for process lifetime. Idempotent."""
global _BRIDGE_SETTINGS_PATH
if _BRIDGE_SETTINGS_PATH is not None:
return
_BRIDGE_SETTINGS_PATH = str(
_resource_stack.enter_context(as_file(_DATA.joinpath("bridge-settings.json")))
)
import shutil
dst = Path.home() / ".feishu-bridge" / "bridge-settings.json"
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(_BRIDGE_SETTINGS_PATH, dst)
def get_bridge_settings_path() -> str:
"""Return materialized bridge-settings.json path, initializing on first call."""
if _BRIDGE_SETTINGS_PATH is None:
materialize_data_files()
return _BRIDGE_SETTINGS_PATH
EMPTY_RESULT_MESSAGE = "Claude 本次未返回任何内容,请稍后重试。"
SESSION_HISTORY_HINT = (
"若需历史细节请用 `session-history search <关键词>`(位于 `~/.claude/bin/`)。"
)
# Section names extracted from project MEMORY.md when project_workspace is set.
# Matching is case-insensitive and whitespace-tolerant; variant headings like
# "Pitfalls (project-specific)" still match "Known Pitfalls" via substring.
_MEMORY_SECTION_KEYS = (
"Commands",
"Constraints",
"Known Pitfalls",
"Pitfalls",
"待办",
"TODO",
"Anchor",
)
def _read_text_safe(path: Path) -> Optional[str]:
"""Read a UTF-8 text file or return None on any failure."""
try:
return path.read_text(encoding="utf-8", errors="replace")
except (OSError, UnicodeError) as exc:
log.warning("fresh-context: could not read %s: %s", path, exc)
return None
def _parse_projects_md(content: str) -> str:
"""Extract a compact `<id> → <path>` index from `memory/projects.md`.
The file format is a Markdown table with columns `ID | 名称 | 路径 | 状态`.
We tolerate extra columns and skip rows whose path cell is empty or whose id
looks like a separator (e.g. `---`).
"""
lines = []
for raw in content.splitlines():
line = raw.strip()
if not line.startswith("|"):
continue
cells = [c.strip() for c in line.strip("|").split("|")]
if len(cells) < 3:
continue
ident, _name, path_cell = cells[0], cells[1], cells[2]
if not ident or not path_cell:
continue
if set(ident) <= set("-: "):
continue
if ident.lower() in {"id", "项目"}:
continue
path = path_cell.strip().strip("`").strip()
if not path:
continue
lines.append(f"- {ident} → {path}")
if not lines:
return ""
return "## Projects index\n" + "\n".join(lines)
def _parse_memory_sections(content: str, anchor_max_bytes: int) -> str:
"""Extract the relevant H2 sections from a project MEMORY.md.
Headings are matched case-insensitively against `_MEMORY_SECTION_KEYS` via
substring; this tolerates variants like `## Known Pitfalls (project-specific)`.
Long sections (notably `Anchor`) are truncated to `anchor_max_bytes` bytes to
keep the injected payload bounded.
"""
out: list[str] = []
current_heading: Optional[str] = None
current_buf: list[str] = []
def _flush() -> None:
if current_heading is None:
return
body = "\n".join(current_buf).strip("\n")
if not body:
return
encoded = body.encode("utf-8")
if len(encoded) > anchor_max_bytes:
body = encoded[:anchor_max_bytes].decode("utf-8", errors="ignore").rstrip()
body += "\n…(truncated)"
out.append(f"{current_heading}\n{body}")
for raw in content.splitlines():
if raw.startswith("## "):
_flush()
heading_text = raw[3:].strip()
lower = heading_text.lower()
if any(key.lower() in lower for key in _MEMORY_SECTION_KEYS):
current_heading = f"## {heading_text}"
current_buf = []
else:
current_heading = None
current_buf = []
continue
if current_heading is not None:
current_buf.append(raw)
_flush()
return "\n\n".join(out)
def resolve_dotclaude_root(workspace: str) -> Path:
"""Locate the workspace's ``.claude`` config directory.
The bridge accepts two workspace layouts:
1. **Project workspace** — e.g. ``~/projects/feishu-bridge``. The Claude
configuration lives in a nested ``./.claude/`` subdirectory.
2. **Dotclaude root** — e.g. ``~/.claude``. The workspace path *is* the
config directory; ``memory/``, ``compact-context.md`` etc. are direct
children, not under another ``.claude/``.
This helper picks whichever layout actually exists. Callers should use it
as the single source of truth so that ``runtime.build_fresh_context_prompt``,
``commands._handle_project``, ``worker.process_message`` and ``done`` all
agree on the same physical directory.
"""
ws = Path(str(workspace)).expanduser()
nested = ws / ".claude"
# If the nested .claude dir contains memory/ or compact-context.md, prefer
# it — that's the project-workspace layout the unit tests model. Otherwise
# fall back to the workspace itself (dotclaude-root layout).
if (nested / "memory").is_dir() or (nested / "compact-context.md").exists():
return nested
if ws.name == ".claude" and ((ws / "memory").is_dir()
or (ws / "compact-context.md").exists()):
return ws
# Final fallback: assume the nested layout. Callers' `.exists()` checks
# downstream will handle the missing-file case via the fallback contract.
return nested
def build_fresh_context_prompt(
workspace: str,
*,
project_workspace: Optional[str] = None,
max_bytes: int = 2048,
anchor_max_bytes: int = 1024,
) -> Optional[str]:
"""Compose a fresh-session memory prompt for `--append-system-prompt`.
Sources merged in order (partial-OK; bad sources are skipped, not fatal):
1. ``<workspace>/.claude/compact-context.md`` — global rolling context.
2. ``<workspace>/.claude/memory/projects.md`` — distilled into a compact
``<id> → <path>`` index so the agent knows where each project lives.
3. ``<project_workspace>/.claude/MEMORY.md`` — only when ``project_workspace``
is provided (Stage 2 binding). Restricted to the H2 sections enumerated
in :data:`_MEMORY_SECTION_KEYS`.
A trailing :data:`SESSION_HISTORY_HINT` reminds the agent to consult
``session-history`` for older context.
Returns ``None`` only when every source contributes zero usable content; any
single source failure is logged at WARNING and skipped. Never raises.
The combined payload is hard-capped at ``max_bytes`` bytes; long single
sections (especially MEMORY ``Anchor``) are further bounded by
``anchor_max_bytes``.
"""
if workspace is None or not str(workspace).strip():
return None
parts: list[str] = []
ws_path = Path(str(workspace)).expanduser()
# Source 1 — compact-context.md
compact_path = resolve_dotclaude_root(workspace) / "compact-context.md"
if compact_path.exists():
text = _read_text_safe(compact_path)
if text and text.strip():
parts.append(f"## Compact context\n{text.strip()}")
# Source 2 — projects.md index
projects_path = resolve_dotclaude_root(workspace) / "memory" / "projects.md"
if projects_path.exists():
text = _read_text_safe(projects_path)
if text:
try:
index = _parse_projects_md(text)
except Exception as exc: # defensive: never raise out
log.warning("fresh-context: projects.md parse failed: %s", exc)
index = ""
if index:
parts.append(index)
# Source 3 — project-specific MEMORY (Stage 2 only)
if project_workspace:
proj_path = Path(str(project_workspace)).expanduser()
memory_path = proj_path / ".claude" / "MEMORY.md"
if memory_path.exists():
text = _read_text_safe(memory_path)
if text:
try:
sections = _parse_memory_sections(text, anchor_max_bytes)
except Exception as exc: # defensive
log.warning("fresh-context: MEMORY.md parse failed: %s", exc)
sections = ""
if sections:
parts.append(f"## Project MEMORY ({proj_path.name})\n{sections}")
if not parts:
return None
body = "\n\n".join(parts)
if len(body.encode("utf-8")) > max_bytes:
# Truncate at byte boundary, then decode-tolerant rstrip to keep valid UTF-8
body = body.encode("utf-8")[:max_bytes].decode("utf-8", errors="ignore").rstrip()
body += "\n…(truncated)"
return f"{body}\n\n---\n{SESSION_HISTORY_HINT}"
SILENT_OK_MESSAGE = "✓ 操作已完成(无文本输出)"
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class RunResult:
"""Runner 统一返回结构。"""
result: str = ""
session_id: Optional[str] = None
is_error: bool = False
cancelled: bool = False
usage: Optional[dict] = None
last_call_usage: Optional[dict] = None
model_usage: Optional[dict] = None
total_cost_usd: Optional[float] = None
peak_context_tokens: int = 0
compact_detected: bool = False
default_context_window: int = 0
rate_limit_info: Optional[dict] = None
def to_dict(self) -> dict:
"""向后兼容:转为 dict,保持 camelCase key。"""
from dataclasses import asdict
d = {k: v for k, v in asdict(self).items() if v is not None}
if "model_usage" in d:
d["modelUsage"] = d.pop("model_usage")
return d
@dataclass
class StreamState:
"""流式解析过程中的可变状态。"""
accumulated_text: str = ""
session_id: Optional[str] = None
final_result: Optional[dict] = None
last_call_usage: Optional[dict] = None
peak_context_tokens: int = 0
compact_detected: bool = False
rate_limit_info: Optional[dict] = None
is_error: bool = False
done: bool = False
pending_output: list[str] = field(default_factory=list)
pending_tool_status: list = field(default_factory=list)
pending_todo_update: list[dict] | None = None
pending_agent_launches: list[dict] | None = None
pending_agent_results: list[dict] = field(default_factory=list)
bg_agent_running: bool = False
# Number of runner tools currently mid-execution (pi tool_execution_start/end).
# >0 raises the silent budget to TOOL_ACTIVE_SILENT_TIMEOUT so a long single tool
# is not mistaken for a hang. Best-effort: clamped ≥0, reset on turn_end/error.
tool_active_count: int = 0
# Heartbeat signal: a tool lifecycle event arrived; the loop should re-arm the
# silent timer (carries no UI semantics, unlike pending_tool_status).
pending_silent_reset: bool = False
# OMP todo state machine — rebuilt from ops deltas
_todo_phases: list[dict] = field(default_factory=list)
# Pi tool-status: tool-call ids already emitted, split so a start never
# suppresses an end (Bug #4 root cause).
_tool_seen_starts: set = field(default_factory=set)
_tool_seen_ends: set = field(default_factory=set)
# Pi tool-call end ids ready for on_tool_end callback (drain loop).
pending_tool_end_ids: list[str] = field(default_factory=list)
# ── Pi cumulative usage (message_end accumulation across turns) ──
_current_message_accumulated: bool = False
cumulative_input: int = 0
cumulative_output: int = 0
cumulative_cache_read: int = 0
cumulative_cache_write: int = 0
cumulative_cost_total: float = 0.0
latest_cache_hit_rate: Optional[float] = None
context_window: int = 0
# ── Todo state machine (OMP ops format) ──
def apply_todo_ops(self, ops: list) -> None:
"""Apply OMP todo_write ops to internal state."""
for op_dict in ops:
if not isinstance(op_dict, dict):
continue
op = op_dict.get("op")
if op == "init":
self._todo_phases = []
for phase_def in (op_dict.get("list") or []):
if not isinstance(phase_def, dict):
continue
phase: dict = {"name": phase_def.get("phase", ""), "tasks": []}
for item in (phase_def.get("items") or []):
phase["tasks"].append({"content": str(item), "status": "pending"})
self._todo_phases.append(phase)
self._auto_promote()
elif op == "start":
task = op_dict.get("task")
if task:
# Demote any existing in_progress task before activating
self._demote_active()
self._set_task_status(task, "in_progress")
elif op == "done":
task = op_dict.get("task")
phase_name = op_dict.get("phase")
if task:
self._set_task_status(task, "completed")
self._auto_promote()
elif phase_name:
self._set_phase_status(phase_name, "completed")
self._auto_promote()
elif op == "drop":
task = op_dict.get("task")
phase_name = op_dict.get("phase")
if task:
self._set_task_status(task, "dropped")
self._auto_promote()
elif phase_name:
self._set_phase_status(phase_name, "dropped")
self._auto_promote()
elif op == "rm":
task = op_dict.get("task")
phase_name = op_dict.get("phase")
if not task and not phase_name:
self._todo_phases = []
elif task:
for p in self._todo_phases:
p["tasks"] = [t for t in p["tasks"] if t["content"] != task]
self._auto_promote()
elif phase_name:
self._todo_phases = [p for p in self._todo_phases if p["name"] != phase_name]
self._auto_promote()
elif op == "append":
phase_name = op_dict.get("phase", "")
items = op_dict.get("items") or []
phase = next((p for p in self._todo_phases if p["name"] == phase_name), None)
if phase is None:
phase = {"name": phase_name, "tasks": []}
self._todo_phases.append(phase)
for item in items:
phase["tasks"].append({"content": str(item), "status": "pending"})
self._auto_promote()
# "note" — no state change
def get_todo_list(self) -> list[dict]:
"""Flatten phases into [{content, status}] for UI rendering."""
result: list[dict] = []
for phase in self._todo_phases:
for task in phase["tasks"]:
result.append({"content": task["content"], "status": task["status"]})
return result
def _auto_promote(self) -> None:
"""Promote first pending task to in_progress if none is active."""
for phase in self._todo_phases:
for task in phase["tasks"]:
if task["status"] == "in_progress":
return # already have an active task
for phase in self._todo_phases:
for task in phase["tasks"]:
if task["status"] == "pending":
task["status"] = "in_progress"
return
def _set_task_status(self, content: str, status: str,
phase_name: str | None = None) -> None:
phases = self._todo_phases
if phase_name:
phases = [p for p in phases if p["name"] == phase_name]
for phase in phases:
for task in phase["tasks"]:
if task["content"] == content:
task["status"] = status
return
# Fallback: if phase_name was given but no match, try globally
if phase_name:
self._set_task_status(content, status)
def _set_phase_status(self, name: str, status: str) -> None:
"""Set all non-terminal tasks in a phase to the given status."""
for phase in self._todo_phases:
if phase["name"] == name:
for task in phase["tasks"]:
if task["status"] not in ("completed", "dropped"):
task["status"] = status
def _demote_active(self) -> None:
"""Demote any in_progress task back to pending."""
for phase in self._todo_phases:
for task in phase["tasks"]:
if task["status"] == "in_progress":
task["status"] = "pending"
return
def _extract_hint_data(tool_name: str, tool_input: dict) -> str:
"""Extract minimal hint string from tool input (avoids holding large dicts).
Supports both Claude Code (Alma) param names (file_path, command) and
OMP param names (path, command, _i). Falls back to OMP's ``_i`` intent
field when no tool-specific key is found.
"""
if tool_name == "Bash":
cmd = tool_input.get("command", "")
if not cmd:
return (tool_input.get("_i") or "")[:50]
# Prefer safe descriptors over raw command (may contain secrets)
desc = tool_input.get("description") or tool_input.get("_i") or ""
if desc:
return desc[:50]
# Fallback: executable basename only — never expose full args
first = cmd.split(maxsplit=1)[0]
return os.path.basename(first)
if tool_name in ("Read", "Write", "Edit"):
# Alma uses "file_path", OMP uses "path"
return tool_input.get("file_path") or tool_input.get("path") or ""
if tool_name in ("Agent", "Task"):
# OMP format: tasks[] array with per-task descriptions
tasks = tool_input.get("tasks")
if isinstance(tasks, list) and tasks:
descs = [t.get("description", "") for t in tasks if isinstance(t, dict)]
joined = ", ".join(d for d in descs if d)
if joined:
return joined[:40]
# Claude Code / Alma format: top-level description
return (tool_input.get("description") or tool_input.get("_i") or "")[:40]
if tool_name == "Subagent":
# Multi-task parallel dispatch: tasks=[{agent, task}, ...]
tasks = tool_input.get("tasks")
if isinstance(tasks, list) and tasks:
parts = []
for t in tasks:
if not isinstance(t, dict):
continue
a = t.get("agent", "")
tk = t.get("task", "")
if a and tk:
parts.append(f"{a}: {tk[:40]}")
elif a:
parts.append(a)
elif tk:
parts.append(tk[:40])
joined = ", ".join(parts)
if joined:
return joined[:60]
# Single agent+task path
agent = tool_input.get("agent", "")
task = tool_input.get("task", "")
if agent and task:
return f"{agent}: {task[:40]}"
return (agent or task or "")[:50]
if tool_name == "Skill":
return tool_input.get("skill", "")
if tool_name in ("Grep", "Search"):
return (tool_input.get("pattern") or "")[:30]
if tool_name == "WebSearch":
return (tool_input.get("query") or "")[:40]
if tool_name == "WebFetch":
return (tool_input.get("url") or "")[:60]
if tool_name == "GetSubagentResult":
return (tool_input.get("subagentId") or tool_input.get("subagent_id") or "")[:60]
if tool_name == "Ls":
# Pi `ls` tool: single directory path.
return (tool_input.get("path") or tool_input.get("file_path") or "")
if tool_name == "Find":
paths = tool_input.get("paths")
if isinstance(paths, list) and paths:
first = str(paths[0])[:40]
return f"{first} +{len(paths)-1}" if len(paths) > 1 else first
# Pi `find` tool: single `path` + `pattern`; pattern is the salient hint.
pattern = tool_input.get("pattern")
if pattern:
return str(pattern)[:40]
single = tool_input.get("path")
if single:
return str(single)[:40]
return (tool_input.get("_i") or "")[:50]
if tool_name == "Lsp":
action = tool_input.get("action", "")
target = tool_input.get("file") or tool_input.get("symbol") or ""
if action and target:
return f"{action} {target}"[:50]
return action or (tool_input.get("_i") or "")[:50]
if tool_name == "Browser":
action = tool_input.get("action", "")
url = tool_input.get("url", "")
if url:
return f"{action} {url}"[:50]
return action or (tool_input.get("_i") or "")[:50]
if tool_name == "Eval":
cells = tool_input.get("cells")
if isinstance(cells, list) and cells:
title = cells[0].get("title", "")
if title:
return title[:40]
return cells[0].get("language", "")
return (tool_input.get("_i") or "")[:50]
if tool_name in ("AstGrep", "AstEdit"):
pat = tool_input.get("pat", "")
if pat:
return pat[:30]
ops = tool_input.get("ops")
if isinstance(ops, list) and ops:
return (ops[0].get("pat") or "")[:30]
return (tool_input.get("_i") or "")[:50]
if tool_name == "Debug":
action = tool_input.get("action", "")
prog = tool_input.get("program", "")
if action and prog:
return f"{action} {prog}"[:50]
return action or (tool_input.get("_i") or "")[:50]
# Universal fallback: OMP tools carry _i (intent) field
return (tool_input.get("_i") or "")[:50]
# ---------------------------------------------------------------------------
# Dedup / Session / Queue (unchanged)
# ---------------------------------------------------------------------------
class MessageDedup:
"""LRU message dedup with TTL."""
def __init__(self, ttl: int = DEDUP_TTL, max_entries: int = DEDUP_MAX):
self._seen: OrderedDict[str, float] = OrderedDict()
self._ttl = ttl
self._max = max_entries
self._lock = threading.Lock()
def is_duplicate(self, message_id: str) -> bool:
now = time.time()
with self._lock:
expired = []
for mid, ts in self._seen.items():
if now - ts > self._ttl:
expired.append(mid)
else:
break
for mid in expired:
del self._seen[mid]
while len(self._seen) >= self._max:
self._seen.popitem(last=False)
if message_id in self._seen:
return True
self._seen[message_id] = now
return False
class SessionMap:
"""Thread-safe session mapping with atomic JSON persistence."""
_AGENT_TYPE_KEY = "_agent_type"
def __init__(self, path: Path, agent_type: str | None = None):
self._lock = threading.RLock()
self._path = path
self._data: dict[str, str] = {}
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
self._load()
if agent_type:
self._reconcile_agent_type(agent_type)
def _reconcile_agent_type(self, agent_type: str):
"""Clear stale sessions when agent type changes."""
stored = self._data.get(self._AGENT_TYPE_KEY)
if stored == agent_type:
return # match — nothing to do
session_count = sum(1 for k in self._data if k != self._AGENT_TYPE_KEY)
if stored is None and agent_type == "claude" and session_count > 0:
# Legacy file without metadata + still using claude → preserve sessions
log.info("Adding agent_type=claude to existing sessions file")
elif stored is not None and stored != agent_type and session_count > 0:
log.warning(
"Agent type changed %s → %s; clearing %d stale sessions",
stored, agent_type, session_count,
)
self._data = {}
elif stored is None and agent_type != "claude" and session_count > 0:
log.warning(
"Agent type set to %s but existing sessions have no type marker; "
"clearing %d sessions", agent_type, session_count,
)
self._data = {}
self._data[self._AGENT_TYPE_KEY] = agent_type
self._save()
def _load(self):
if self._path.exists():
try:
self._data = json.loads(self._path.read_text())
count = sum(1 for k in self._data if k != self._AGENT_TYPE_KEY)
log.info("Loaded %d sessions from %s", count, self._path)
except (json.JSONDecodeError, IOError) as e:
log.warning("Failed to load sessions: %s", e)
self._data = {}
def _save(self):
"""Best-effort atomic: write tmp (0600) -> fsync -> os.replace."""
tmp = self._path.with_suffix(".tmp")
fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
with os.fdopen(fd, "w") as f:
json.dump(self._data, f, indent=2)
f.flush()
os.fsync(f.fileno())
except BaseException:
try:
os.unlink(str(tmp))
except OSError:
pass
raise
os.replace(str(tmp), str(self._path))
@staticmethod
def format_key(key: tuple) -> str:
"""Public key encoding for cross-module consumers (e.g. bg_supervisor).
Single source of truth for "bot:chat:thread" string form so consumers
don't have to re-implement (and silently drift from) the format.
"""
return ":".join(str(k or "") for k in key)
def get(self, key: tuple) -> Optional[str]:
with self._lock:
return self._data.get(self.format_key(key))
def put(self, key: tuple, session_id: str):
with self._lock:
ks = self.format_key(key)
old = self._data.get(ks)
self._data[ks] = session_id
try:
self._save()
except Exception:
if old is None:
self._data.pop(ks, None)
else:
self._data[ks] = old
raise
def delete(self, key: tuple):
with self._lock:
ks = self.format_key(key)
old = self._data.pop(ks, None)
try:
self._save()
except Exception:
if old is not None:
self._data[ks] = old
raise
class SessionQueueFull(Exception):
"""Raised when a session's pending queue exceeds MAX_PENDING."""
class ChatTaskQueue:
"""Per-session FIFO task queue. Only one task per session in flight."""
MAX_PENDING_PER_SESSION = 10
def __init__(self, work_queue: queue.Queue):
self._work_queue = work_queue
self._active: set[str] = set()
self._pending: dict[str, deque] = {}
self._lock = threading.Lock()
def enqueue(
self, key: str, item: dict, *, bypass_backpressure: bool = False,
) -> str:
"""Enqueue `item` for session `key`.
bypass_backpressure: skip the MAX_PENDING_PER_SESSION check. Used
for synthetic bg-task completion turns where dropping the delivery
means the user never sees the result. Human messages keep the
backpressure so a session can't flood the worker.
"""
with self._lock:
if key in self._active:
pending = self._pending.get(key)
if (
not bypass_backpressure
and pending
and len(pending) >= self.MAX_PENDING_PER_SESSION
):
raise SessionQueueFull(
f"Session {key} has {self.MAX_PENDING_PER_SESSION} pending"
)
self._pending.setdefault(key, deque()).append(item)
return "queued"
self._active.add(key)
self._work_queue.put_nowait(item)
return "immediate"
def on_complete(self, key: str) -> None:
with self._lock:
pending = self._pending.get(key)
if pending:
next_item = pending.popleft()
if not pending:
del self._pending[key]
try:
self._work_queue.put_nowait(next_item)
except queue.Full:
self._pending.setdefault(key, deque()).appendleft(next_item)
log.warning("work_queue full in on_complete, retry in 2s (key=%s)", key)
threading.Timer(2.0, self.on_complete, args=(key,)).start()
else:
self._active.discard(key)
self._pending.pop(key, None)
def drain(self, key: str) -> list:
with self._lock:
return list(self._pending.pop(key, deque()))
def pending_count(self, key: str) -> int:
with self._lock:
return len(self._pending.get(key, []))
# ---------------------------------------------------------------------------
# BaseRunner ABC
# ---------------------------------------------------------------------------
class BaseRunner(ABC):
"""Abstract base for AI Agent CLI runners."""
ALWAYS_STREAMING: ClassVar[bool] = False
_SAFETY_PROMPT = (
"CRITICAL: You are running as a subprocess of feishu-bridge. "
"NEVER execute systemctl restart/stop/reload on feishu-bridge - "
"doing so kills your own parent process, causing an infinite restart loop.\n\n"
"Do not output 'Status:' lines at the end of responses — "
"status is tracked externally by the bridge."
)
_MINIMAL_SAFETY_PROMPT = (
"CRITICAL: You are running as a subprocess of feishu-bridge. "
"NEVER restart, stop, or reload feishu-bridge itself."
)
def __init__(self, command: Optional[str], model: Optional[str], workspace: str, timeout: int,
max_budget_usd: Optional[float] = None,
extra_system_prompts: Optional[list[str]] = None,
extra_cli_args: Optional[list[str]] = None,
fixed_env: Optional[dict[str, str]] = None,
safety_prompt_mode: str = "full",
setting_sources: Optional[str] = None):
self.command = command
self.model = model
self.workspace = workspace
self.timeout = timeout
self.max_budget_usd = max_budget_usd
self._extra_system_prompts = extra_system_prompts or []
self._extra_cli_args = [str(arg) for arg in (extra_cli_args or [])]
self._fixed_env = {
str(key): str(value) for key, value in (fixed_env or {}).items()
}
mode = str(safety_prompt_mode or "full").strip().lower()
self._safety_prompt_mode = mode if mode in {"full", "minimal", "off"} else "full"
self._setting_sources = setting_sources
self._active: dict[str, subprocess.Popen] = {}
self._cancelled: set[str] = set()
self._lock = threading.Lock()
# ── Abstract methods (subclass must implement) ──
@abstractmethod
def build_args(self, prompt: str, session_id: Optional[str],
resume: bool, streaming: bool, *,
fork_session: bool = False,
fresh_context: Optional[str] = None) -> list:
"""构建 CLI 命令行参数列表。
``fresh_context`` 用于把 :func:`build_fresh_context_prompt` 的产物追加到
子进程的 ``--append-system-prompt``;仅在 ``resume=False`` 时由 caller 传入。
"""
@abstractmethod
def parse_streaming_line(self, event: dict, state: StreamState) -> None:
"""解析单行流式 JSONL 事件,更新 StreamState。"""
@abstractmethod
def parse_blocking_output(self, stdout: str, session_id: Optional[str]) -> dict:
"""解析阻塞模式的完整 stdout,返回 result dict。"""
# ── Optional overrides ──
def get_session_not_found_signatures(self) -> list[str]:
"""返回表示 session 不存在的错误签名列表。默认空。"""
return []
def display_default_model(self) -> Optional[str]:
"""Real model the CLI uses when no model is pinned, for UI/status only.
Returns ``None`` when the bridge cannot know it — most CLIs choose a
default internally. NEVER influences process spawning (``build_args``);
this is purely a display hint.
"""
return None
def get_extra_env(self) -> dict:
"""额外环境变量。默认注入用户 PATH。"""
env = dict(self._fixed_env)
# Ensure user-local bin dirs are in PATH for subprocesses.
# systemd services don't source ~/.profile, so ~/.local/bin etc.
# are missing from PATH, causing tools like gh to be not found.
user_bins = [
os.path.expanduser("~/.local/bin"),
os.path.expanduser("~/bin"),
]
existing = env.get("PATH") or os.environ.get("PATH", "")
additions = [p for p in user_bins if os.path.isdir(p) and p not in existing]
if additions:
env["PATH"] = ":".join(additions) + ":" + existing
return env
def get_display_name(self) -> str:
"""用户可见的 Agent 名称。"""
return "AI Agent"
def supports_compact(self) -> bool:
"""是否支持 /compact 命令。"""
return True
def supports_auto_compact(self) -> bool:
"""Whether IdleCompactManager should track this runner's sessions."""
return self.supports_compact()
def has_session(self, session_id: str) -> bool:
"""Whether this runner holds state for the given session_id.
Default True — CLI runners persist via side-files, so we assume
the state exists unless a subclass explicitly tracks it in memory.
"""
return True
def wants_auth_file(self) -> bool:
"""Whether the worker should create /tmp/feishu_auth_*.json for this runner.
Default True — CLI runners need the file for feishu-cli OAuth.
"""
return True
def _build_system_prompt(self, extra: Optional[str] = None) -> str:
"""Merge safety guard + extra system prompts into one string.
``extra`` is an optional per-run addendum (e.g. fresh-session memory
produced by :func:`build_fresh_context_prompt`); it is appended after
the safety guard and any instance-level ``extra_system_prompts``.
Passing ``extra`` does not mutate instance state — callers may invoke
this concurrently with different ``extra`` values without interference.
"""
parts: list[str] = []
if self._safety_prompt_mode == "full":
parts.append(self._SAFETY_PROMPT)
elif self._safety_prompt_mode == "minimal":
parts.append(self._MINIMAL_SAFETY_PROMPT)
parts.extend(self._extra_system_prompts)
if extra:
parts.append(extra)
return "\n\n".join(parts)
def _build_streaming_result(self, state: StreamState,
session_id: Optional[str]) -> Optional[dict]:
"""Build content-level result from streaming state.
Return dict if a definitive result is available, None to fall through
to generic BaseRunner fallbacks (timeout, exit code, empty text).
Subclasses override this for protocol-specific result handling.
"""
return None
# ── Shared subprocess management ──
@staticmethod
def _force_kill(proc: subprocess.Popen):
"""Send SIGKILL to process tree (last resort)."""
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
try: