Hồi quy đã vá
-------------
F-12 Kéo–thả hoặc dán tệp vào ô chat ném NameError. R08 tách `_Input` sang
`chat_input_box.py` nhưng để `_paths_from_mime()` ở lại
`composer_widget.py`, nên hai hàm sự kiện Qt gọi một cái tên không tồn
tại. Bốn hàm dùng chung chuyển sang `composer_mime.py` — module thứ ba
là chỗ duy nhất không lặp lại được lỗi này. Đo lại: cả thả lẫn dán đều
gắn 1 tệp, khớp bản trước refactor.
F-01 Đổi provider thì bộ chọn model AI-Edit không làm gì. Hook cũ kiểm
`folder.ai_model_combo`, thuộc tính R08-T12 đã dời sang
`ai_panel.resolver`. Làm mới vô điều kiện, đúng như tab cũ: lần lấy đầu
tiên hỏng thì đổi provider chính là lúc phải thử lại.
F-07 Hàng chọn kỳ của Dashboard bị đẩy xuống dưới các thẻ số liệu. Hàng này
lọc CẢ BA thẻ con chứ không riêng biểu đồ, nên để nó nằm dưới là bắt
người dùng đọc con số trước khi thấy con số đó tính cho kỳ nào. Kèm
theo: `TokenUsageCardWidget` bị bỏ sót `setContentsMargins(0,0,0,0)`
mà hai thẻ con còn lại đã có, đẩy cả hàng thẻ lệch 9px.
`check_layout_geometry` nay khớp TỪNG BYTE với bản trước refactor.
F-11 Hai lớp khai trùng tên phương thức; Python giữ bản sau nên bản đầu là
mã chết. `co4e_tab.py::showEvent` bản đầu gọi `_narrow_guard.attach()`
và không bao giờ chạy.
Tách file (F-09)
----------------
Bốn file chạm trần 400 dòng, mỗi lần cắt ra một trách nhiệm thật:
graph_renderer.py -> graph_scene_builder.py + graph_export.py
co4e_workflow_service.py -> co4e_run_history.py
json_config_repository.py -> config_sections.py
agents_admin_tab.py -> shared/agent_kind_visuals.py
File cuối còn xoá 3 bản sao của hàm đã có trong `shared/formatters.py`,
giống hệt đến từng dòng — nay định dạng thời gian và avatar không lệch nhau
giữa các bảng Giám sát nữa.
Docstring
---------
41,6% -> 100% (3.478/3.478 định nghĩa production), kể cả module dormant và
phương thức dunder. Toàn bộ phần bổ sung viết bằng tiếng Việt; comment tiếng
Anh có sẵn giữ nguyên — dịch ngược là một đợt riêng.
Seam chưa nối dây (F-05)
------------------------
9 seam mang nhãn `SEAM · dựng <ngày>` kèm hai câu: được nối khi nào, và để
dormant thì hỏng gì. Ngày lấy từ lịch sử git, không phải hạn tự đặt. Gate O
đọc nhãn đó và nhắc khi quá 30 ngày.
859 test xanh · 4/4 cổng CASAN · 19/24 checker khớp từng byte bản cũ.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
123 lines
5.2 KiB
Python
123 lines
5.2 KiB
Python
"""Parse a ``/agent`` command typed in a chat box (Cowork parity with Co4E).
|
||
|
||
An *agent* directive applies a named agent PERSONA to the turn: its role +
|
||
instructions are prepended to the request as a system-style prefix, exactly the
|
||
way ``skills.parse_skill_command`` applies a skill. Only the WORK agents a user
|
||
composes with are callable here:
|
||
|
||
* built-in Co4E personas (``co4e_builtins.BUILTIN_AGENTS``) — includes the
|
||
delivery-lifecycle + Security agents;
|
||
* per-user custom Co4E agents (``co4e.list_custom_agents``).
|
||
|
||
Admin-defined agents (Monitoring → Agents Admin) are DELIBERATELY excluded:
|
||
they are system-management presets (help agent, task executors, …), not agents
|
||
to pick in Cowork/Co4E — so they never appear in the ``/agent`` list or the
|
||
Agent picker.
|
||
|
||
Only the persona (prompt) is applied — NOT a per-turn model/provider switch:
|
||
a Cowork panel runs several turns concurrently, so a shared model override would
|
||
race between them; the Agent picker remains the way to pin a model/provider.
|
||
Pure logic (no Qt) so it's unit-testable.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from typing import List, Optional, Tuple
|
||
|
||
# Same shape as skills.parse_skill_command: the command may sit mid-sentence, so
|
||
# trailing punctuation must not break recognition.
|
||
_CMD = re.compile(r"(?<!\S)/agent(?::([\w\-.]+))?(?=$|[\s.,;:!?)\]}»”’'\"、。」])",
|
||
re.DOTALL)
|
||
|
||
|
||
def _slug(name: str) -> str:
|
||
"""Định danh an toàn suy từ tên agent (dùng chung hàm với Co4E)."""
|
||
from .co4e import slugify
|
||
return slugify(name)
|
||
|
||
|
||
def collect_agents(shared_dir: str = "") -> List[dict]:
|
||
"""Every callable WORK agent as ``{slug, name, desc, persona, source}``,
|
||
de-duped by slug (built-in > custom). Admin agents are intentionally NOT
|
||
included — they are system-management presets, not Cowork/Co4E choices (see
|
||
the module docstring). ``shared_dir`` is kept for signature stability. Never
|
||
raises — a broken source is skipped so the command still works."""
|
||
out: List[dict] = []
|
||
seen: set[str] = set()
|
||
|
||
def _add(slug: str, name: str, desc: str, persona: str, source: str) -> None:
|
||
"""Thêm một agent vào danh sách gộp; bỏ qua nếu trùng slug hoặc thiếu persona.
|
||
|
||
Agent không có persona thì không dùng được — thêm vào chỉ làm bảng gợi ý dài
|
||
ra mà chọn vào lại không chạy.
|
||
"""
|
||
if not slug or slug in seen or not persona.strip():
|
||
return
|
||
seen.add(slug)
|
||
out.append({"slug": slug, "name": name, "desc": desc,
|
||
"persona": persona.strip(), "source": source})
|
||
|
||
try:
|
||
from .co4e_builtins import BUILTIN_AGENTS
|
||
for a in BUILTIN_AGENTS:
|
||
_add(a.slug, a.name, a.role,
|
||
f"You are the {a.role} agent — {a.name}.\n{a.instructions}", "builtin")
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
try:
|
||
from . import co4e
|
||
for ca in co4e.list_custom_agents():
|
||
_add(_slug(ca.name), ca.name, ca.role,
|
||
f"You are the {ca.role} agent — {ca.name}.\n{ca.instructions}", "custom")
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
return out
|
||
|
||
|
||
def _persona_block(agent: dict) -> str:
|
||
"""Khối prompt mô tả một agent, chèn vào đầu lượt chat khi người dùng gõ ``/agent:``."""
|
||
return f"## Agent: {agent['name']}\n{agent['persona']}"
|
||
|
||
|
||
def parse_agent_command(text: str, shared_dir: str = "") -> Tuple[str, str, Optional[str]]:
|
||
"""Parse a ``/agent`` command anywhere in ``text``.
|
||
|
||
Returns ``(prefix, request, info)``:
|
||
* ``prefix`` – agent persona to prepend to the agent prompt ('' if none)
|
||
* ``request`` – the message with the command stripped
|
||
* ``info`` – when not None, answer this inline (no agent turn)
|
||
|
||
Forms: ``/agent`` (list) · ``/agent:<name> <req>`` (apply that agent).
|
||
"""
|
||
raw = (text or "").strip()
|
||
m = _CMD.search(raw)
|
||
if not m:
|
||
return "", text, None
|
||
slug = m.group(1)
|
||
if slug:
|
||
slug = slug.rstrip(".") # "/agent:name." — the dot was sentence punctuation
|
||
rest = (raw[:m.start()] + " " + raw[m.end():]).strip()
|
||
rest = re.sub(r"[ \t]{2,}", " ", rest)
|
||
agents = collect_agents(shared_dir)
|
||
|
||
if slug:
|
||
low = slug.lower()
|
||
match = next((a for a in agents if a["slug"] == low or a["name"].lower() == low), None)
|
||
if match is None:
|
||
return "", text, (f"Agent `{slug}` not found. "
|
||
"Type `/agent` to see the available agents.")
|
||
if not rest:
|
||
return "", text, (f"Agent **{match['name']}** selected — add your request, e.g. "
|
||
f"`/agent:{match['slug']} review this file`.")
|
||
return _persona_block(match), rest, None
|
||
|
||
# Bare /agent → list what's available.
|
||
if not agents:
|
||
return "", text, ("No agents found. Add one in Agents Admin, or a custom Flow agent.")
|
||
listing = "\n".join(
|
||
f"- `/agent:{a['slug']}` — **{a['name']}**"
|
||
+ (f" _({a['desc']})_" if a.get("desc") else "")
|
||
for a in agents)
|
||
return "", text, ("**Available agents**\n" + listing
|
||
+ "\n\nApply one with `/agent:<name> <your request>`.")
|