diff --git a/auto_dev_crew/ci_bootstrap.py b/auto_dev_crew/ci_bootstrap.py index 8a5a1cf..e48286a 100644 --- a/auto_dev_crew/ci_bootstrap.py +++ b/auto_dev_crew/ci_bootstrap.py @@ -13,7 +13,6 @@ """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import datetime as dt import json @@ -203,7 +202,7 @@ def build_workflow_spec(repo_dir: Path, rcfg: dict | None = None) -> tuple[dict, test_run = "cargo test\n" else: test_run = None - warnings.append(_i18n.t("ไม่พบคำสั่งทดสอบ — workflow จะไม่รันเทสต์จริง (ตั้งค่า test ใน config.yaml เพื่อแก้)")) + warnings.append("ไม่พบคำสั่งทดสอบ — workflow จะไม่รันเทสต์จริง (ตั้งค่า test ใน config.yaml เพื่อแก้)") if test_run is None: test_run = "echo 'No test command defined'\n" # pytest is the default runner for Python repos, but the install steps above only install the @@ -264,25 +263,25 @@ def validate_workflow(text: str) -> list[str]: return ["ไฟล์ไม่ใช่ mapping ระดับบนสุด"] errors: list[str] = [] if not (doc.get("on") or doc.get(True)): - errors.append(_i18n.t("ไม่มีส่วน on (trigger)")) + errors.append("ไม่มีส่วน on (trigger)") jobs = doc.get("jobs") if not isinstance(jobs, dict) or not jobs: return errors + ["ไม่มี jobs"] for job_name, job in jobs.items(): if not isinstance(job, dict): - errors.append(_i18n.t("job {p0} ไม่ใช่ mapping", p0=job_name)) + errors.append(f"job {job_name} ไม่ใช่ mapping") continue if not job.get("runs-on") or not isinstance(job.get("runs-on"), (str, list, dict)): - errors.append(_i18n.t("job {p0} ไม่มี runs-on ที่ถูกต้อง", p0=job_name)) + errors.append(f"job {job_name} ไม่มี runs-on ที่ถูกต้อง") steps = job.get("steps") if not isinstance(steps, list) or not steps: - errors.append(_i18n.t("job {p0} ไม่มี steps", p0=job_name)) + errors.append(f"job {job_name} ไม่มี steps") continue for i, step in enumerate(steps, 1): if not isinstance(step, dict) or not (step.get("uses") or step.get("run")): - errors.append(_i18n.t("job {p0} step {p1} ไม่มี uses หรือ run", p0=job_name, p1=i)) + errors.append(f"job {job_name} step {i} ไม่มี uses หรือ run") elif step.get("uses") and not _USES_RE.match(str(step["uses"])): - errors.append(_i18n.t("job {p0} step {p1} uses รูปแบบไม่ถูกต้อง: {p2}", p0=job_name, p1=i, p2=step['uses'])) + errors.append(f"job {job_name} step {i} uses รูปแบบไม่ถูกต้อง: {step['uses']}") return errors @@ -385,11 +384,11 @@ def _preflight_auth(repo: str) -> list[CiStep]: except (ValueError, RuntimeError): perm = "" if perm in _WRITE_PERMS: - steps.append(CiStep(_i18n.t("สิทธิ์เขียน repo"), "ok", perm)) + steps.append(CiStep("สิทธิ์เขียน repo", "ok", perm)) elif perm: - steps.append(CiStep(_i18n.t("สิทธิ์เขียน repo"), "fail", _i18n.t("สิทธิ์ปัจจุบัน {p0} ไม่พอสำหรับ push", p0=perm))) + steps.append(CiStep("สิทธิ์เขียน repo", "fail", f"สิทธิ์ปัจจุบัน {perm} ไม่พอสำหรับ push")) else: - steps.append(CiStep(_i18n.t("สิทธิ์เขียน repo"), "warn", _i18n.t("ตรวจสิทธิ์ไม่ได้ — จะลองทำจริง"))) + steps.append(CiStep("สิทธิ์เขียน repo", "warn", "ตรวจสิทธิ์ไม่ได้ — จะลองทำจริง")) return steps @@ -440,9 +439,9 @@ def _open_fallback_issue(repo: str, content: str, reason: str, steps: list[CiSte try: url = gh("issue", "create", "-R", repo, "--title", title, "--body", body) except RuntimeError as exc: - return CiBootstrapResult("failed", _i18n.t("push/เปิด PR และเปิด issue ไม่สำเร็จ: {p0}", p0=str(exc)[-300:]), + return CiBootstrapResult("failed", f"push/เปิด PR และเปิด issue ไม่สำเร็จ: {str(exc)[-300:]}", steps=steps, workflow=content) - return CiBootstrapResult("issue_opened", _i18n.t("push/เปิด PR ไม่ได้ จึงเปิด issue ให้เพิ่มไฟล์เอง"), + return CiBootstrapResult("issue_opened", "push/เปิด PR ไม่ได้ จึงเปิด issue ให้เพิ่มไฟล์เอง", url=url, steps=steps, workflow=content) @@ -512,53 +511,53 @@ def bootstrap_ci( try: steps.extend(_preflight_auth(repo_name)) if any(s.status == "fail" for s in steps): - return CiBootstrapResult("failed", _i18n.t("ตรวจสอบก่อนเริ่มไม่ผ่าน — ดูขั้นตอนที่ล้มเหลว"), steps=steps) + return CiBootstrapResult("failed", "ตรวจสอบก่อนเริ่มไม่ผ่าน — ดูขั้นตอนที่ล้มเหลว", steps=steps) if not _BRANCH_RE.match(base_branch): - steps.append(CiStep(_i18n.t("สาขาฐาน"), "fail", _i18n.t("ชื่อสาขา {p0} ไม่ถูกต้อง", p0=repr(base_branch)))) - return CiBootstrapResult("failed", _i18n.t("ชื่อสาขาฐานไม่ถูกต้อง"), steps=steps) + steps.append(CiStep("สาขาฐาน", "fail", f"ชื่อสาขา {base_branch!r} ไม่ถูกต้อง")) + return CiBootstrapResult("failed", "ชื่อสาขาฐานไม่ถูกต้อง", steps=steps) if not gh("api", f"repos/{repo_name}/branches/{base_branch}", "--jq", ".name", check=False): - steps.append(CiStep(_i18n.t("สาขาฐาน"), "fail", _i18n.t("ไม่พบสาขา {p0} ใน {p1}", p0=base_branch, p1=repo_name))) - return CiBootstrapResult("failed", _i18n.t("ไม่พบสาขาฐาน {p0}", p0=base_branch), steps=steps) - steps.append(CiStep(_i18n.t("สาขาฐาน"), "ok", base_branch)) + steps.append(CiStep("สาขาฐาน", "fail", f"ไม่พบสาขา {base_branch} ใน {repo_name}")) + return CiBootstrapResult("failed", f"ไม่พบสาขาฐาน {base_branch}", steps=steps) + steps.append(CiStep("สาขาฐาน", "ok", base_branch)) # A dry run only needs the tree to detect the stack, so it clones shallowly. cwd = clone(repo_name, base_branch, branch, slot_id=slot_id, depth=1 if dry_run else 50) - steps.append(CiStep(_i18n.t("clone สาขาหลัก"), "ok", base_branch)) + steps.append(CiStep("clone สาขาหลัก", "ok", base_branch)) if has_ci_workflows(cwd): - steps.append(CiStep(_i18n.t("ตรวจ workflow เดิม"), "skip", _i18n.t("มี workflow อยู่แล้ว"))) - return CiBootstrapResult("skipped", _i18n.t("{p0} มี workflow อยู่แล้ว ไม่ต้องเพิ่ม", p0=repo_name), steps=steps) - steps.append(CiStep(_i18n.t("ตรวจ workflow เดิม"), "ok", _i18n.t("ยังไม่มี"))) + steps.append(CiStep("ตรวจ workflow เดิม", "skip", "มี workflow อยู่แล้ว")) + return CiBootstrapResult("skipped", f"{repo_name} มี workflow อยู่แล้ว ไม่ต้องเพิ่ม", steps=steps) + steps.append(CiStep("ตรวจ workflow เดิม", "ok", "ยังไม่มี")) spec, warnings = build_workflow_spec(cwd, rcfg) content = render_workflow(spec) - steps.extend(CiStep(_i18n.t("คำเตือน"), "warn", w) for w in warnings) + steps.extend(CiStep("คำเตือน", "warn", w) for w in warnings) errors = validate_workflow(content) if errors: - steps.append(CiStep(_i18n.t("ตรวจโครงสร้าง YAML"), "fail", "; ".join(errors))) - return CiBootstrapResult("failed", _i18n.t("workflow ที่สร้างไม่ผ่านการตรวจ"), steps=steps, workflow=content) - steps.append(CiStep(_i18n.t("ตรวจโครงสร้าง YAML"), "ok", f"{len(spec['jobs']['test']['steps'])} steps")) + steps.append(CiStep("ตรวจโครงสร้าง YAML", "fail", "; ".join(errors))) + return CiBootstrapResult("failed", "workflow ที่สร้างไม่ผ่านการตรวจ", steps=steps, workflow=content) + steps.append(CiStep("ตรวจโครงสร้าง YAML", "ok", f"{len(spec['jobs']['test']['steps'])} steps")) lint = actionlint_errors(content) if lint is None: - steps.append(CiStep(_i18n.t("ตรวจด้วย actionlint"), "skip", _i18n.t("ไม่ได้ติดตั้ง actionlint (ข้ามการตรวจ schema)"))) + steps.append(CiStep("ตรวจด้วย actionlint", "skip", "ไม่ได้ติดตั้ง actionlint (ข้ามการตรวจ schema)")) elif lint: - steps.append(CiStep(_i18n.t("ตรวจด้วย actionlint"), "fail", "; ".join(lint))) - return CiBootstrapResult("failed", _i18n.t("workflow ที่สร้างไม่ผ่าน actionlint"), steps=steps, workflow=content) + steps.append(CiStep("ตรวจด้วย actionlint", "fail", "; ".join(lint))) + return CiBootstrapResult("failed", "workflow ที่สร้างไม่ผ่าน actionlint", steps=steps, workflow=content) else: - steps.append(CiStep(_i18n.t("ตรวจด้วย actionlint"), "ok")) + steps.append(CiStep("ตรวจด้วย actionlint", "ok")) if _contains_secret(content): - steps.append(CiStep(_i18n.t("ตรวจความลับ"), "fail", _i18n.t("คำสั่งใน config มีค่าที่หน้าตาเหมือนความลับ — ไม่ commit"))) - return CiBootstrapResult("failed", _i18n.t("พบค่าที่เหมือนความลับใน workflow"), steps=steps) - steps.append(CiStep(_i18n.t("ตรวจความลับ"), "ok")) + steps.append(CiStep("ตรวจความลับ", "fail", "คำสั่งใน config มีค่าที่หน้าตาเหมือนความลับ — ไม่ commit")) + return CiBootstrapResult("failed", "พบค่าที่เหมือนความลับใน workflow", steps=steps) + steps.append(CiStep("ตรวจความลับ", "ok")) if dry_run: - steps.append(CiStep("push branch", "skip", _i18n.t("จะ push {p0} (ยังไม่ทำในโหมดดราฟต์)", p0=branch))) - steps.append(CiStep(_i18n.t("เปิด PR"), "skip", _i18n.t("จะเปิด PR เข้า {p0}", p0=base_branch))) - return CiBootstrapResult("dry_run", _i18n.t("แผนการเพิ่ม CI (ยังไม่ได้ push หรือเปิด PR)"), + steps.append(CiStep("push branch", "skip", f"จะ push {branch} (ยังไม่ทำในโหมดดราฟต์)")) + steps.append(CiStep("เปิด PR", "skip", f"จะเปิด PR เข้า {base_branch}")) + return CiBootstrapResult("dry_run", "แผนการเพิ่ม CI (ยังไม่ได้ push หรือเปิด PR)", steps=steps, workflow=content) target = cwd / WORKFLOW_REL @@ -573,8 +572,8 @@ def bootstrap_ci( reason = str(exc) if _is_transient_push_error(reason): # Network trouble is not a refusal: leave it retryable instead of opening an issue. - steps.append(CiStep("push branch", "fail", _i18n.t("เครือข่ายขัดข้องหลังลองซ้ำแล้ว — จะลองใหม่รอบถัดไป"))) - return CiBootstrapResult("failed", _i18n.t("push ไม่สำเร็จเพราะเครือข่าย"), steps=steps, workflow=content) + steps.append(CiStep("push branch", "fail", "เครือข่ายขัดข้องหลังลองซ้ำแล้ว — จะลองใหม่รอบถัดไป")) + return CiBootstrapResult("failed", "push ไม่สำเร็จเพราะเครือข่าย", steps=steps, workflow=content) steps.append(CiStep("push branch", "fail", reason.splitlines()[-1][:200])) say("⚠️ [CI-Bootstrap] push ถูกปฏิเสธ — เปิด issue แนบไฟล์แทน") return _open_fallback_issue(repo_name, content, reason, steps) @@ -584,17 +583,17 @@ def bootstrap_ci( if not url: url = _existing_pr_url(repo_name, branch) # the PR may exist even if gh reported failure if url: - steps.append(CiStep(_i18n.t("เปิด PR"), "ok", url)) + steps.append(CiStep("เปิด PR", "ok", url)) say(f"[CI-Bootstrap] เปิด PR เพิ่ม CI ให้ {repo_name} สำเร็จ: {url} ✅") - return CiBootstrapResult("pr_opened", _i18n.t("เปิด PR เพิ่ม CI แล้ว"), url=url, steps=steps, workflow=content) + return CiBootstrapResult("pr_opened", "เปิด PR เพิ่ม CI แล้ว", url=url, steps=steps, workflow=content) - steps.append(CiStep(_i18n.t("เปิด PR"), "fail", _i18n.t("gh pr create ไม่สำเร็จ"))) + steps.append(CiStep("เปิด PR", "fail", "gh pr create ไม่สำเร็จ")) run(["git", "push", "origin", "--delete", branch], cwd=cwd, check=False) say("⚠️ [CI-Bootstrap] เปิด PR ไม่สำเร็จ — เปิด issue แนบไฟล์แทน") - return _open_fallback_issue(repo_name, content, _i18n.t("gh pr create ไม่สำเร็จ"), steps) + return _open_fallback_issue(repo_name, content, "gh pr create ไม่สำเร็จ", steps) except Exception as exc: say(f"⚠️ [CI-Bootstrap] ไม่สามารถเพิ่ม CI ให้ {repo_name} ได้: {exc}") - steps.append(CiStep(_i18n.t("ข้อผิดพลาด"), "fail", str(exc)[-300:])) + steps.append(CiStep("ข้อผิดพลาด", "fail", str(exc)[-300:])) return CiBootstrapResult("failed", str(exc)[-300:], steps=steps) finally: if cwd and cwd.exists(): diff --git a/auto_dev_crew/deep_scan.py b/auto_dev_crew/deep_scan.py index 456831d..c8da511 100644 --- a/auto_dev_crew/deep_scan.py +++ b/auto_dev_crew/deep_scan.py @@ -1,6 +1,5 @@ """Deep scan: validate and clean findings returned by a model.""" from __future__ import annotations -from auto_dev_crew import i18n as _i18n import datetime as dt import hashlib @@ -481,7 +480,7 @@ def __init__(self, limit: int): def wrap(self, call_model: Callable[[str], str]) -> Callable[[str], str]: def guarded(prompt: str) -> str: if self.used >= self.limit: - raise BudgetExhausted(_i18n.t("ถึงเพดาน {p0} call ต่อรันแล้ว", p0=self.limit)) + raise BudgetExhausted(f"ถึงเพดาน {self.limit} call ต่อรันแล้ว") self.used += 1 return call_model(prompt) return guarded @@ -541,9 +540,9 @@ def run_deep_scan(repo: str, cfg: dict, state_dir: Path, call_model: Callable[[s encoding="utf-8", errors="replace", timeout=60, env={**os.environ, "GIT_TERMINAL_PROMPT": "0"}) if res.returncode != 0: - warnings.append(redact_secrets(_i18n.t("git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {p0}", p0=(res.stderr or res.stdout).strip()[:300]))) + warnings.append(redact_secrets(f"git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {(res.stderr or res.stdout).strip()[:300]}")) except Exception as exc: - warnings.append(redact_secrets(_i18n.t("git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {p0}", p0=exc))) + warnings.append(redact_secrets(f"git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {exc}")) findings: list[Finding] = [] agentic = scan_mode(cfg) == "agentic" for name, files in chunk_by_top_folder(root): @@ -554,20 +553,20 @@ def run_deep_scan(repo: str, cfg: dict, state_dir: Path, call_model: Callable[[s if items is None: # ผิดรูปแบบ (ไม่ใช่ [] ที่ตั้งใจ) → ลองซ้ำ 1 ครั้งด้วยพรอมพ์เดิม + คำสั่ง JSON items = _parse_model_array(call_model(prompt + RETRY_NOTE)) if items is None: - warnings.append(_i18n.t("กลุ่ม {p0} ตอบผิดรูปแบบ (ไม่พบ JSON) แม้ลองซ้ำแล้ว ผลกลุ่มนี้ไม่ถูกนับ", p0=name)) + warnings.append(f"กลุ่ม {name} ตอบผิดรูปแบบ (ไม่พบ JSON) แม้ลองซ้ำแล้ว ผลกลุ่มนี้ไม่ถูกนับ") continue findings.extend(validate_findings(items, root)) except BudgetExhausted as exc: - warnings.append(redact_secrets(_i18n.t("หยุดสแกนที่กลุ่ม {p0}: {p1} (กลุ่มที่เหลือยังไม่ได้สแกน)", p0=name, p1=exc))) + warnings.append(redact_secrets(f"หยุดสแกนที่กลุ่ม {name}: {exc} (กลุ่มที่เหลือยังไม่ได้สแกน)")) break except Exception as exc: - warnings.append(redact_secrets(_i18n.t("สแกนกลุ่ม {p0} ล้มเหลว: {p1}", p0=name, p1=exc))) + warnings.append(redact_secrets(f"สแกนกลุ่ม {name} ล้มเหลว: {exc}")) rank = {s: i for i, s in enumerate(SEVERITIES)} findings.sort(key=lambda f: rank.get(f.severity, len(SEVERITIES))) # stable: chunk order kept per rank dropped = max(len(findings) - cap, 0) findings = findings[:cap] if dropped: # M11 ruling: scan every chunk (R9), but say when the cap hid findings - warnings.append(_i18n.t("พบ {p0} รายการเกินเพดาน {p1} จึงไม่ได้บันทึก (เรียงตามความรุนแรงแล้ว)", p0=dropped, p1=cap)) + warnings.append(f"พบ {dropped} รายการเกินเพดาน {cap} จึงไม่ได้บันทึก (เรียงตามความรุนแรงแล้ว)") data = save_run(state_dir, repo, findings, run_id, warnings=warnings) return {"ok": True, "repo": repo, "run_id": run_id, "findings": data["findings"], "warnings": warnings} diff --git a/auto_dev_crew/evaluator.py b/auto_dev_crew/evaluator.py index 6f8ca1b..d2dae56 100644 --- a/auto_dev_crew/evaluator.py +++ b/auto_dev_crew/evaluator.py @@ -1,6 +1,5 @@ """Pre-PR agentic-eval Gate: Evaluator-Optimizer pattern for quality-critical code PRs.""" from __future__ import annotations -from auto_dev_crew import i18n as _i18n import json import re @@ -130,7 +129,7 @@ def parse_eval_response( return EvaluationResult( score=0.0, passed=False, - critique_th=_i18n.t("ไม่สามารถแยกผลการประเมิน JSON จากการตอบกลับของโมเดล"), + critique_th="ไม่สามารถแยกผลการประเมิน JSON จากการตอบกลับของโมเดล", dimensions={"task_alignment": 0.0, "safety_cleanliness": 0.0, "quality": 0.0} ) @@ -142,7 +141,7 @@ def parse_eval_response( return EvaluationResult( score=0.0, passed=False, - critique_th=_i18n.t("รูปแบบ JSON ของการประเมินไม่ถูกต้อง"), + critique_th="รูปแบบ JSON ของการประเมินไม่ถูกต้อง", dimensions={"task_alignment": 0.0, "safety_cleanliness": 0.0, "quality": 0.0} ) @@ -156,7 +155,7 @@ def parse_eval_response( total_w = w_align + w_safety + w_quality or 1.0 score = ((task_align * w_align) + (safety * w_safety) + (quality * w_quality)) / total_w - critique = str(data.get("critique_th") or _i18n.t("ประเมินผลเรียบร้อย")) + critique = str(data.get("critique_th") or "ประเมินผลเรียบร้อย") passed = score >= min_score and task_align >= 0.5 and safety >= 0.5 @@ -204,7 +203,7 @@ def evaluate_diff( return EvaluationResult( score=1.0, passed=True, - critique_th=_i18n.t("ข้ามการประเมิน (evaluation.enabled: false)"), + critique_th="ข้ามการประเมิน (evaluation.enabled: false)", dimensions={"task_alignment": 1.0, "safety_cleanliness": 1.0, "quality": 1.0} ) @@ -214,7 +213,7 @@ def evaluate_diff( return EvaluationResult( score=0.0, passed=False, - critique_th=_i18n.t("⛔ Git diff ว่างเปล่า — ไม่พบการเปลี่ยนแปลงของโค้ด"), + critique_th="⛔ Git diff ว่างเปล่า — ไม่พบการเปลี่ยนแปลงของโค้ด", dimensions={"task_alignment": 0.0, "safety_cleanliness": 0.0, "quality": 0.0} ) @@ -240,7 +239,7 @@ def evaluate_diff( return EvaluationResult( score=0.0, passed=False, - critique_th=_i18n.t("⛔ Deterministic Pre-Eval ล้มเหลว: {p0}", p0=pre_eval_msg), + critique_th=f"⛔ Deterministic Pre-Eval ล้มเหลว: {pre_eval_msg}", dimensions={"task_alignment": 0.0, "safety_cleanliness": 0.0, "quality": 0.0} ) @@ -324,7 +323,7 @@ def evaluate_diff( agent = call_agent or runner.call_agent # default: runner's (patchable) call_agent res = agent(target_cfg, prompt, Path(judge_dir), role="judge") if res.get("status") == "ERROR": - err_msg = res.get("response") or _i18n.t("โมเดลประเมินไม่ตอบกลับหรือเกิดข้อผิดพลาด") + err_msg = res.get("response") or "โมเดลประเมินไม่ตอบกลับหรือเกิดข้อผิดพลาด" if matched: fallback_used = True runner.log(f"[agentic-eval] ⚠️ Judge เฉพาะกิจล้มเหลว ({err_msg}) -> สลับประเมินด้วย Default Fallback Engine...") @@ -334,12 +333,12 @@ def evaluate_diff( except Exception as fb_exc: runner.log(f"[agentic-eval] Default Fallback Engine ล้มเหลวเช่นกัน: {fb_exc}") if res.get("status") == "ERROR": - err_msg = res.get("response") or _i18n.t("โมเดลประเมินไม่ตอบกลับหรือเกิดข้อผิดพลาด") + err_msg = res.get("response") or "โมเดลประเมินไม่ตอบกลับหรือเกิดข้อผิดพลาด" runner.log(f"[agentic-eval] ⚠️ โมเดลประเมินตอบกลับล้มเหลว ({err_msg})") return EvaluationResult( score=0.0, passed=False, - critique_th=_i18n.t("การประเมินล้มเหลว ({p0})", p0=err_msg), + critique_th=f"การประเมินล้มเหลว ({err_msg})", dimensions={"task_alignment": 0.0, "safety_cleanliness": 0.0, "quality": 0.0} ) @@ -380,7 +379,7 @@ def evaluate_diff( return EvaluationResult( score=0.0, passed=False, - critique_th=_i18n.t("การประเมินขัดข้อง ({p0}) — บล็อกการเปิด PR เพื่อความปลอดภัย", p0=exc), + critique_th=f"การประเมินขัดข้อง ({exc}) — บล็อกการเปิด PR เพื่อความปลอดภัย", dimensions={"task_alignment": 0.0, "safety_cleanliness": 0.0, "quality": 0.0}, engine_error=isinstance(exc, runner.EngineBusy), ) diff --git a/auto_dev_crew/feature_gen.py b/auto_dev_crew/feature_gen.py index 94cf66f..569f57d 100644 --- a/auto_dev_crew/feature_gen.py +++ b/auto_dev_crew/feature_gen.py @@ -6,7 +6,6 @@ close_done_plans closes the plan issue too (otherwise the plan stays open forever). """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import datetime as dt import hashlib @@ -265,7 +264,7 @@ def propose(repo: str, cfg: dict | None, root: Path, call_model: Callable[[str], raw = call_model(prompt) parsed = deep_scan._parse_model_array(raw) if parsed is None: - raise ValueError(_i18n.t("โมเดลตอบไม่เป็น JSON array (ผิดรูปแบบ) จึงอ่านแผนไม่ได้")) + raise ValueError("โมเดลตอบไม่เป็น JSON array (ผิดรูปแบบ) จึงอ่านแผนไม่ได้") items = validate_proposals(parsed, s["max_proposals"]) for p in items: p["risk"] = risk_reasons(p["files"], s["large_change_files"]) diff --git a/auto_dev_crew/gui_check.py b/auto_dev_crew/gui_check.py index f992d9c..5300114 100644 --- a/auto_dev_crew/gui_check.py +++ b/auto_dev_crew/gui_check.py @@ -12,7 +12,6 @@ """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import json import subprocess @@ -34,7 +33,7 @@ def _open_http(url: str, timeout: float): """เปิด URL เฉพาะ http/https เท่านั้น — กัน scheme แปลก (file:, ftp:)""" if urllib.parse.urlsplit(url).scheme not in ("http", "https"): - raise ValueError(_i18n.t("อนุญาตเฉพาะ http/https URL: {p0}", p0=repr(url))) + raise ValueError(f"อนุญาตเฉพาะ http/https URL: {url!r}") return urllib.request.urlopen(url, timeout=timeout) # nosec B310 - scheme ถูกตรวจด้านบนแล้ว @@ -60,7 +59,10 @@ def check_page(base: str, shot: Path) -> list[str]: lambda msg: problems.append(f"console.error: {msg.text}") if msg.type == "error" else None, ) try: - page.goto(base + "/", wait_until="networkidle", timeout=PAGE_TIMEOUT_MS) + # "networkidle" never fires while the GUI keeps a long-poll request open, + # so wait for the load event, then give the page's scripts a moment to run. + page.goto(base + "/", wait_until="load", timeout=PAGE_TIMEOUT_MS) + page.wait_for_timeout(1500) shot.parent.mkdir(parents=True, exist_ok=True) page.screenshot(path=str(shot), full_page=True) except Exception as exc: # noqa: BLE001 diff --git a/auto_dev_crew/key_ping.py b/auto_dev_crew/key_ping.py index 2930e11..6ec8de5 100644 --- a/auto_dev_crew/key_ping.py +++ b/auto_dev_crew/key_ping.py @@ -5,7 +5,6 @@ ผลลัพธ์ที่ส่งกลับมีเฉพาะ key_id (ชื่อตัวแปร/แฮช), สถานะ, เวลาที่ใช้ และข้อความ error ที่ถูกปิดบังความลับแล้ว. """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import os import re @@ -100,7 +99,7 @@ def ping_key(eng: dict, spec: dict, timeout: int = DEFAULT_PING_TIMEOUT) -> dict masked = mask_key(spec["value"]) if spec["value"] else "" if eng.get("command") != "opencode": return {"key_id": key_id, "ok": False, "latency_ms": 0, - "message": _i18n.t("ปิงได้เฉพาะ engine ที่ใช้ opencode (engine นี้ใช้ {p0})", p0=eng.get('command'))} + "message": f"ปิงได้เฉพาะ engine ที่ใช้ opencode (engine นี้ใช้ {eng.get('command')})"} try: # ต้องส่ง path ของ engine: ไม่งั้น PATH จะเจอ shim opencode.CMD ของ npm แล้วถูกปฏิเสธทุกคีย์ opencode_bin = resolve_cli_exe("opencode", eng.get("path") or None) @@ -123,16 +122,16 @@ def ping_key(eng: dict, spec: dict, timeout: int = DEFAULT_PING_TIMEOUT) -> dict latency = int((time.monotonic() - started) * 1000) out = ((proc.stdout or "") + ("\n" + proc.stderr if proc.stderr else "")).strip() ok = proc.returncode == 0 and bool(out) and not re.search(r"error|unauthori[sz]ed|invalid|401|403", out, re.I) - message = _i18n.t("ใช้งานได้") if ok else redact_secrets(out[-300:]) or f"returncode={proc.returncode}" + message = "ใช้งานได้" if ok else redact_secrets(out[-300:]) or f"returncode={proc.returncode}" if ok: - message = _i18n.t("ใช้งานได้ (คีย์จาก opencode auth)") if from_auth_store else _i18n.t("ใช้งานได้ (คีย์ {p0})", p0=masked) + message = "ใช้งานได้ (คีย์จาก opencode auth)" if from_auth_store else f"ใช้งานได้ (คีย์ {masked})" return {"key_id": key_id, "ok": ok, "latency_ms": latency, "message": message} except subprocess.TimeoutExpired: return {"key_id": key_id, "ok": False, "latency_ms": int(timeout * 1000), - "message": _i18n.t("หมดเวลา ({p0} วินาที)", p0=timeout)} + "message": f"หมดเวลา ({timeout} วินาที)"} except Exception as exc: # noqa: BLE001 — รายงานผลให้ UI ไม่ให้ล้มทั้ง request return {"key_id": key_id, "ok": False, "latency_ms": 0, - "message": redact_secrets(_i18n.t("เกิดข้อผิดพลาด: {p0}", p0=exc))} + "message": redact_secrets(f"เกิดข้อผิดพลาด: {exc}")} def ping_engine_keys(eng: dict, only_key_id: str | None = None, diff --git a/auto_dev_crew/keys.py b/auto_dev_crew/keys.py index 3ef7752..190b9ee 100644 --- a/auto_dev_crew/keys.py +++ b/auto_dev_crew/keys.py @@ -7,7 +7,6 @@ """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import datetime as dt import hashlib @@ -83,6 +82,116 @@ "keyless": False, "default_keys": ["CLOUDFLARE_API_KEY_1", "CLOUDFLARE_ACCOUNT_ID"], }, + "opencode-zhipu": { + "display_name": "Zhipu AI (GLM-4-Flash)", + "tier": "standby", + "description": "โมเดล GLM-4-Flash ฟรีถาวร 100% ไม่จำกัดจำนวนวัน", + "portal_url": "https://open.bigmodel.cn", + "quota_label": "ฟรีถาวร 100%", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["ZHIPU_API_KEY_1"], + }, + "opencode-baidu": { + "display_name": "Baidu Qianfan (ERNIE-Speed)", + "tier": "standby", + "description": "ERNIE-Speed 128k บริการฟรีถาวรโดย Baidu Cloud", + "portal_url": "https://qianfan.cloud.baidu.com", + "quota_label": "ฟรีถาวร 100%", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["BAIDU_API_KEY_1"], + }, + "opencode-siliconflow": { + "display_name": "SiliconFlow Free Pool", + "tier": "standby", + "description": "พูลโมเดล Open Source ฟรีถาวร เช่น Qwen-2.5-Coder", + "portal_url": "https://siliconflow.cn", + "quota_label": "ฟรีโมเดล Open Source", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["SILICONFLOW_API_KEY_1"], + }, + "opencode-iflytek": { + "display_name": "iFlytek Spark Lite", + "tier": "standby", + "description": "Spark Lite เปิดให้ใช้ฟรีตลอดชีพ ไม่มีวันหมดอายุ", + "portal_url": "https://www.xfyun.cn", + "quota_label": "ฟรีตลอดชีพ", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["IFLYTEK_API_KEY_1"], + }, + "opencode-hunyuan": { + "display_name": "Tencent Hunyuan Lite", + "tier": "standby", + "description": "Hunyuan-Lite จาก Tencent เปิดให้ใช้งานฟรีตลอดชีพ", + "portal_url": "https://hunyuan.tencent.com", + "quota_label": "ฟรีตลอดชีพ", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["HUNYUAN_API_KEY_1"], + }, + "opencode-modelscope": { + "display_name": "ModelScope (Alibaba)", + "tier": "standby", + "description": "Serverless Inference โควตาฟรีรายวัน ไม่นำข้อมูลไปเทรน", + "portal_url": "https://modelscope.cn", + "quota_label": "โควตารายวันฟรี", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["MODELSCOPE_API_KEY_1"], + }, + "opencode-cohere": { + "display_name": "Cohere Trial", + "tier": "standby", + "description": "Trial Key 1,000 calls/เดือน รีเซ็ตใหม่ทุกเดือน", + "portal_url": "https://dashboard.cohere.com", + "quota_label": "1,000 calls/เดือน", + "rate_limit": "5 RPM", + "keyless": False, + "default_keys": ["COHERE_API_KEY_1"], + }, + "opencode-aion": { + "display_name": "Aion Labs", + "tier": "standby", + "description": "Serverless Endpoint 15 RPM / 20k tokens/วัน", + "portal_url": "https://aionlabs.ai", + "quota_label": "20,000 tokens/วัน", + "rate_limit": "15 RPM", + "keyless": False, + "default_keys": ["AION_API_KEY_1"], + }, + "opencode-kilo": { + "display_name": "Kilo Code", + "tier": "standby", + "description": "kilo-auto/free โมเดลฟรีถาวรสำหรับเขียนโค้ด", + "portal_url": "https://kilo.ai", + "quota_label": "ฟรีถาวร", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["KILO_API_KEY_1"], + }, + "opencode-llm7": { + "display_name": "LLM7.io", + "tier": "standby", + "description": "Serverless Free Token รีเซ็ตโควตาทุก 24 ชั่วโมง", + "portal_url": "https://llm7.io", + "quota_label": "รีเซ็ตโควตาทุกวัน", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["LLM7_API_KEY_1"], + }, + "opencode-kluster": { + "display_name": "Kluster.ai", + "tier": "standby", + "description": "Serverless Token ฟรีรีเซ็ตทุกวัน ไม่เก็บข้อมูลไปเทรน", + "portal_url": "https://kluster.ai", + "quota_label": "รีเซ็ตโควตาทุกวัน", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["KLUSTER_API_KEY_1"], + }, "opencode-pollinations": { "display_name": "Pollinations.ai", "tier": "standby", @@ -93,6 +202,96 @@ "keyless": False, "default_keys": ["POLLINATIONS_API_KEY_1"], }, + "opencode-shuttleai": { + "display_name": "ShuttleAI", + "tier": "standby", + "description": "แพ็กเกจฟรีถาวร $0/เดือน สำหรับนักพัฒนา", + "portal_url": "https://shuttleai.com", + "quota_label": "ฟรี $0/เดือน", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["SHUTTLEAI_API_KEY_1"], + }, + "opencode-gonka": { + "display_name": "Gonka Broker", + "tier": "standby", + "description": "ฟรี 1,000,000 โทเคน/เดือน รีเซ็ตใหม่ทุกเดือน", + "portal_url": "https://gonka.ai", + "quota_label": "1,000,000 tokens/เดือน", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["GONKA_API_KEY_1"], + }, + "opencode-glhf": { + "display_name": "Glhf.chat", + "tier": "standby", + "description": "Daily Free Tokens รีเซ็ตรายวัน ไม่นำข้อมูลไปเทรน", + "portal_url": "https://glhf.chat", + "quota_label": "รีเซ็ตโควตารายวัน", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["GLHF_API_KEY_1"], + }, + "opencode-huggingface": { + "display_name": "Hugging Face", + "tier": "standby", + "description": "User Access Token ฟรีสำหรับ Serverless Inference API", + "portal_url": "https://huggingface.co/settings/tokens", + "quota_label": "ฟรี Serverless Inference", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["HUGGINGFACE_API_KEY_1"], + }, + "opencode-nim-eval": { + "display_name": "NVIDIA NIM Dedicated Eval", + "tier": "standby", + "description": "Engine แยกสำหรับ Pre-PR Agentic Evaluation ไม่แย่งโควตา Coder", + "portal_url": "https://build.nvidia.com", + "quota_label": "1,000 เครดิต (แชร์กับ NVIDIA)", + "rate_limit": "40 RPM", + "keyless": False, + "default_keys": ["NVIDIA_API_KEY_1"], + }, + "opencode-voyage": { + "display_name": "Voyage AI", + "tier": "standby", + "description": "โควตา 50,000,000 โทเคนฟรี สำหรับ Code Embedding", + "portal_url": "https://voyageai.com", + "quota_label": "50M tokens ฟรีตลอดไป", + "rate_limit": "10 RPM", + "keyless": False, + "default_keys": ["VOYAGE_API_KEY_1"], + }, + "opencode-vercel": { + "display_name": "Vercel AI Gateway", + "tier": "standby", + "description": "100,000 requests ต่อเดือน ฟรีถาวร", + "portal_url": "https://vercel.com", + "quota_label": "100,000 req/เดือน", + "rate_limit": "20 RPM", + "keyless": False, + "default_keys": ["VERCEL_AI_KEY_1"], + }, + "opencode-mistral": { + "display_name": "Mistral Experimentation", + "tier": "standby", + "description": "Codestral สำหรับ Free Experimentation Tier", + "portal_url": "https://console.mistral.ai", + "quota_label": "Free Tier", + "rate_limit": "1 req/sec", + "keyless": False, + "default_keys": ["MISTRAL_API_KEY_1"], + }, + "opencode-ollama-local": { + "display_name": "Ollama Local Engine", + "tier": "standby", + "description": "รันบนฮาร์ดแวร์ในเครื่องคุณ 100% งบ 0 บาทตลอดกาล ออฟไลน์ได้", + "portal_url": "https://ollama.com", + "quota_label": "ไม่จำกัด (รันในเครื่อง)", + "rate_limit": "ไม่จำกัด", + "keyless": True, + "default_keys": [], + }, "agy-ai-pro": { "display_name": "Google AI Pro (CLI)", "tier": "standby", @@ -109,7 +308,7 @@ def _open_https(req: urllib.request.Request, timeout: float): """เปิด URL เฉพาะ https เท่านั้น — กัน scheme แปลก (file:, ftp:) ถ้า URL ถูกแก้โดยไม่ตั้งใจ""" if urllib.parse.urlsplit(req.full_url).scheme != "https": - raise ValueError(_i18n.t("อนุญาตเฉพาะการเชื่อมต่อ https")) + raise ValueError("อนุญาตเฉพาะการเชื่อมต่อ https") return urllib.request.urlopen(req, timeout=timeout) # nosec B310 - scheme ถูกตรวจด้านบนแล้ว def mask_key(val: str) -> str: @@ -175,7 +374,7 @@ def validate_dotenv_key_name(name: str) -> str: """ name = name.strip() if _is_denied_env_name(name): - raise ValueError(_i18n.t("ไม่อนุญาตให้ตั้งค่าตัวแปร {p0} ผ่าน GUI", p0=repr(name))) + raise ValueError(f"ไม่อนุญาตให้ตั้งค่าตัวแปร {name!r} ผ่าน GUI") if name in _catalog_env_names(): return name if _DOTENV_KEY_RE.match(name): @@ -183,14 +382,14 @@ def validate_dotenv_key_name(name: str) -> str: base = _DOTENV_ROLE_SUFFIX_RE.sub("", name) if base != name and _DOTENV_KEY_RE.match(base): return name - raise ValueError(_i18n.t("ชื่อ key {p0} ไม่ถูกต้อง (ต้องลงท้ายด้วย _API_KEY, _KEY, _TOKEN หรือ _ACCOUNT_ID)", p0=repr(name))) + raise ValueError(f"ชื่อ key {name!r} ไม่ถูกต้อง (ต้องลงท้ายด้วย _API_KEY, _KEY, _TOKEN หรือ _ACCOUNT_ID)") def _validate_dotenv_delete_name(name: str) -> str: """Deleting only removes a line, so the shape check is looser; reserved names are still refused.""" name = name.strip() if not _DOTENV_SHAPE_RE.match(name) or _is_denied_env_name(name): - raise ValueError(_i18n.t("ไม่อนุญาตให้ลบตัวแปร {p0}", p0=repr(name))) + raise ValueError(f"ไม่อนุญาตให้ลบตัวแปร {name!r}") return name @@ -209,7 +408,7 @@ def save_dotenv(updates: dict[str, str], path: Path | None = None) -> list[str]: continue validate_dotenv_key_name(str(raw_name)) if "\r" in str(raw_value) or "\n" in str(raw_value): - raise ValueError(_i18n.t("ค่าของ {p0} ต้องไม่มีการขึ้นบรรทัดใหม่", p0=str(raw_name).strip())) + raise ValueError(f"ค่าของ {str(raw_name).strip()} ต้องไม่มีการขึ้นบรรทัดใหม่") with cfg_file_lock(path): existing_content = "" @@ -616,7 +815,7 @@ def _check_engine_command(command: str, path: str | None) -> None: path is given, its file name must be the same command (with .exe/.cmd optional). """ if command not in ALLOWED_ENGINE_COMMANDS: - raise ValueError(_i18n.t("command ไม่ได้รับอนุญาต: {p0} (ใช้ได้: {p1})", p0=repr(command), p1=', '.join(ALLOWED_ENGINE_COMMANDS))) + raise ValueError(f"command ไม่ได้รับอนุญาต: {command!r} (ใช้ได้: {', '.join(ALLOWED_ENGINE_COMMANDS)})") if path: base = re.split(r"[\\/]", path.strip())[-1].lower() for suffix in (".exe", ".cmd"): @@ -624,7 +823,7 @@ def _check_engine_command(command: str, path: str | None) -> None: base = base[: -len(suffix)] break if base != command: - raise ValueError(_i18n.t("path {p0} ไม่ตรงกับ command {p1}", p0=repr(path), p1=repr(command))) + raise ValueError(f"path {path!r} ไม่ตรงกับ command {command!r}") def _check_engine_model(command: str, model: str) -> None: @@ -634,7 +833,7 @@ def _check_engine_model(command: str, model: str) -> None: """ model = (model or "").strip() if command == "opencode" and "/" not in model: - raise ValueError(_i18n.t("model {p0} ของ opencode ต้องอยู่ในรูป provider/model เช่น opencode/{p1}", p0=repr(model), p1=model)) + raise ValueError(f"model {model!r} ของ opencode ต้องอยู่ในรูป provider/model เช่น opencode/{model}") def add_engine(engine_data: dict, cfg_path: Path | None = None) -> bool: @@ -648,7 +847,7 @@ def add_engine(engine_data: dict, cfg_path: Path | None = None) -> bool: command = str(engine_data.get("command", "")).strip() model = str(engine_data.get("model", "")).strip() if not name or not command or not model: - raise ValueError(_i18n.t("ข้อมูลไม่ครบถ้วน: ต้องระบุ name, command, และ model")) + raise ValueError("ข้อมูลไม่ครบถ้วน: ต้องระบุ name, command, และ model") _check_engine_command(command, str(engine_data.get("path") or "").strip()) _check_engine_model(command, model) @@ -660,7 +859,7 @@ def add_engine(engine_data: dict, cfg_path: Path | None = None) -> bool: raw["engines"] = engines if any(e.get("name") == name for e in engines): - raise ValueError(_i18n.t("มี Engine ชื่อ '{p0}' อยู่ในระบบแล้ว", p0=name)) + raise ValueError(f"มี Engine ชื่อ '{name}' อยู่ในระบบแล้ว") new_engine = { "name": name, @@ -745,7 +944,7 @@ def update_engine(engine_name: str, updates: dict, cfg_path: Path | None = None) if new_name and new_name != engine_name: new_name_clean = str(new_name).strip() if any(e.get("name") == new_name_clean for e in engines): - raise ValueError(_i18n.t("มี Engine ชื่อ '{p0}' อยู่ในระบบแล้ว", p0=new_name_clean)) + raise ValueError(f"มี Engine ชื่อ '{new_name_clean}' อยู่ในระบบแล้ว") target["name"] = new_name_clean for field in ("provider", "command", "model", "path"): @@ -903,7 +1102,7 @@ def fetch_provider_models(provider_name: str, api_key: str | None = None) -> lis key = auth_map.get(prov_clean, "") if not key and req_type != "pollinations": - raise ValueError(_i18n.t("ไม่พบ API Key สำหรับ {p0} กรุณาระบุหรือบันทึกคีย์ก่อน", p0=provider_name)) + raise ValueError(f"ไม่พบ API Key สำหรับ {provider_name} กรุณาระบุหรือบันทึกคีย์ก่อน") headers = { "User-Agent": "auto-dev-crew/1.0", @@ -922,10 +1121,10 @@ def fetch_provider_models(provider_name: str, api_key: str | None = None) -> lis data = json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as err: if err.code in (401, 403): - raise ValueError(_i18n.t("API Key ไม่ถูกต้อง หรือไม่มีสิทธิ์เข้าถึง ({p0} Unauthorized)", p0=err.code)) - raise ValueError(_i18n.t("เรียก API ไม่สำเร็จ ({p0}): {p1}", p0=err.code, p1=err.reason)) + raise ValueError(f"API Key ไม่ถูกต้อง หรือไม่มีสิทธิ์เข้าถึง ({err.code} Unauthorized)") + raise ValueError(f"เรียก API ไม่สำเร็จ ({err.code}): {err.reason}") except Exception as exc: - raise ValueError(_i18n.t("เกิดข้อผิดพลาดในการเชื่อมต่อ: {p0}", p0=exc)) + raise ValueError(f"เกิดข้อผิดพลาดในการเชื่อมต่อ: {exc}") models = [] if req_type == "pollinations": diff --git a/auto_dev_crew/multi_repo.py b/auto_dev_crew/multi_repo.py index 49c01b9..9c899ae 100644 --- a/auto_dev_crew/multi_repo.py +++ b/auto_dev_crew/multi_repo.py @@ -1,7 +1,6 @@ """GitHub Multi-Repo Support & Cross-Repo Dispatching.""" from __future__ import annotations -from auto_dev_crew import i18n as _i18n import dataclasses import json @@ -416,7 +415,7 @@ def scan_user_repositories(cfg: dict | None = None) -> list[dict]: def _validate_repo_name(repo_name: str) -> str: if not isinstance(repo_name, str) or not REPO_NAME_RE.match(repo_name) or ".." in repo_name.split("/"): - raise ValueError(_i18n.t("ชื่อ repo ไม่ถูกต้อง: {p0}", p0=repr(repo_name))) + raise ValueError(f"ชื่อ repo ไม่ถูกต้อง: {repo_name!r}") return repo_name @@ -467,12 +466,12 @@ def find_or_prepare_repo_dir(repo_name: str, cfg: dict | None = None) -> Path: ) except subprocess.TimeoutExpired as exc: shutil.rmtree(cached_repo, ignore_errors=True) - raise RuntimeError(_i18n.t("clone {p0} หมดเวลา ({p1}s)", p0=repo_name, p1=CLONE_TIMEOUT_SECONDS)) from exc + raise RuntimeError(f"clone {repo_name} หมดเวลา ({CLONE_TIMEOUT_SECONDS}s)") from exc if res.returncode != 0 or not (cached_repo / ".git").exists(): shutil.rmtree(cached_repo, ignore_errors=True) detail = (res.stderr or res.stdout or "").strip() or "no .git directory created" - raise RuntimeError(_i18n.t("clone {p0} ไม่สำเร็จ: {p1}", p0=repo_name, p1=detail)) + raise RuntimeError(f"clone {repo_name} ไม่สำเร็จ: {detail}") return cached_repo.resolve() @@ -526,10 +525,10 @@ def get_repo_file_content(repo_name: str, rel_path: str, mode: str = "full", cfg clean_rel = rel_path.lstrip("/\\") target = (repo_dir / clean_rel).resolve() if repo_dir.resolve() not in target.parents and target != repo_dir.resolve(): - raise PermissionError(_i18n.t("Path นอกขอบเขตของ repository")) + raise PermissionError("Path นอกขอบเขตของ repository") if not target.exists() or not target.is_file(): - raise FileNotFoundError(_i18n.t("ไม่พบไฟล์: {p0}", p0=rel_path)) + raise FileNotFoundError(f"ไม่พบไฟล์: {rel_path}") raw_text = target.read_text(encoding="utf-8", errors="replace") if mode == "ast" and clean_rel.endswith(".py"): @@ -552,7 +551,7 @@ def run_repo_verification(repo_name: str, check_type: str, cfg: dict) -> dict: # Only the named checks may run. Anything else used to be executed as a raw shell # command, which made /api/repo/run-command a remote-code-execution path (CRIT-01). if check_type not in VERIFICATION_CHECKS: - raise ValueError(_i18n.t("check_type ไม่ถูกต้อง: {p0} (ใช้ได้: {p1})", p0=repr(check_type), p1=', '.join(VERIFICATION_CHECKS))) + raise ValueError(f"check_type ไม่ถูกต้อง: {check_type!r} (ใช้ได้: {', '.join(VERIFICATION_CHECKS)})") rcfg = ensure_repo_config(cfg, repo_name) repo_dir = find_or_prepare_repo_dir(repo_name, cfg) @@ -660,7 +659,7 @@ def dispatch_studio_coding_task( "ok": True, "sandbox": False, "issue_url": issue_url, - "message": _i18n.t("สั่งงานลงคิว GitHub เรียบร้อยแล้ว ({p0})", p0=issue_url), + "message": f"สั่งงานลงคิว GitHub เรียบร้อยแล้ว ({issue_url})", } @@ -680,7 +679,7 @@ def sync_repo(repo_name: str, cfg: dict | None = None) -> dict: "ok": res.returncode == 0, "stdout": res.stdout, "stderr": res.stderr, - "message": _i18n.t("ซิงค์ repository สำเร็จ") if res.returncode == 0 else _i18n.t("เกิดข้อผิดพลาดในการซิงค์"), + "message": "ซิงค์ repository สำเร็จ" if res.returncode == 0 else "เกิดข้อผิดพลาดในการซิงค์", } except Exception as exc: return {"ok": False, "message": str(exc)} diff --git a/auto_dev_crew/opencode_db.py b/auto_dev_crew/opencode_db.py index bbf8e1e..5c5ca3d 100644 --- a/auto_dev_crew/opencode_db.py +++ b/auto_dev_crew/opencode_db.py @@ -6,7 +6,6 @@ แต่ทำเฉพาะเมื่อตารางว่าง (ไม่มีข้อมูลที่จะสูญหาย) และสำรอง DB ก่อนเสมอ. """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import datetime as dt import sqlite3 @@ -87,9 +86,9 @@ def repair(db_path: Path = DEFAULT_DB, backup_dir: Path | None = None, apply: bo conn.execute(WORKSPACE_DDL) conn.execute("COMMIT") if "project_id" not in _columns(conn, "workspace"): - raise RuntimeError(_i18n.t("สร้าง workspace แล้วยังไม่มี project_id")) + raise RuntimeError("สร้าง workspace แล้วยังไม่มี project_id") if conn.execute("PRAGMA integrity_check").fetchone()[0] != "ok": - raise RuntimeError(_i18n.t("integrity_check ไม่ผ่านหลังซ่อม")) + raise RuntimeError("integrity_check ไม่ผ่านหลังซ่อม") except Exception: if conn.in_transaction: conn.execute("ROLLBACK") diff --git a/auto_dev_crew/playwright_env.py b/auto_dev_crew/playwright_env.py index 4efd1a2..10f4e3b 100644 --- a/auto_dev_crew/playwright_env.py +++ b/auto_dev_crew/playwright_env.py @@ -8,7 +8,6 @@ """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import os import subprocess @@ -124,7 +123,7 @@ def gui_url(rcfg: dict | None) -> str | None: def _open_http(url: str, timeout: float): """เปิด URL เฉพาะ http/https เท่านั้น — กัน scheme แปลก (file:, ftp:)""" if urllib.parse.urlsplit(url).scheme not in ("http", "https"): - raise ValueError(_i18n.t("อนุญาตเฉพาะ http/https URL: {p0}", p0=repr(url))) + raise ValueError(f"อนุญาตเฉพาะ http/https URL: {url!r}") return urllib.request.urlopen(url, timeout=timeout) # nosec B310 - scheme ถูกตรวจด้านบนแล้ว diff --git a/auto_dev_crew/procs.py b/auto_dev_crew/procs.py index a1d1384..015d91b 100644 --- a/auto_dev_crew/procs.py +++ b/auto_dev_crew/procs.py @@ -6,7 +6,6 @@ entire tree with ``taskkill /T`` (Windows) or ``os.killpg`` (POSIX). """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import os import shutil @@ -29,7 +28,7 @@ def resolve_cli_exe(command: str, path: str | None = None) -> str: """ candidate = os.path.expanduser(path) if path else shutil.which(command) if not candidate or not Path(candidate).exists(): - raise RuntimeError(_i18n.t("ไม่พบ {p0} — ติดตั้งหรือแก้ engine.path ใน config.yaml", p0=command)) + raise RuntimeError(f"ไม่พบ {command} — ติดตั้งหรือแก้ engine.path ใน config.yaml") if candidate.lower().endswith((".cmd", ".bat")): native = Path(candidate).parent / "node_modules" / f"{command}-ai" / "bin" / f"{command}.exe" if not native.exists(): diff --git a/auto_dev_crew/providers.py b/auto_dev_crew/providers.py index 21a7b97..7dd88e5 100644 --- a/auto_dev_crew/providers.py +++ b/auto_dev_crew/providers.py @@ -7,7 +7,6 @@ """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import json import re @@ -29,17 +28,17 @@ def validate_provider_id(pid: str) -> str: pid = (pid or "").strip().lower() if not _ID_RE.match(pid): - raise ValueError(_i18n.t("id ผู้ให้บริการต้องเป็นตัวอักษรภาษาอังกฤษพิมพ์เล็ก ตัวเลข หรือ - ยาว 2–31 ตัว เช่น deepseek")) + raise ValueError("id ผู้ให้บริการต้องเป็นตัวอักษรภาษาอังกฤษพิมพ์เล็ก ตัวเลข หรือ - ยาว 2–31 ตัว เช่น deepseek") return pid def validate_base_url(url: str) -> str: url = (url or "").strip() if not url or any(c.isspace() for c in url): - raise ValueError(_i18n.t("URL ต้องไม่ว่างและห้ามมีช่องว่าง")) + raise ValueError("URL ต้องไม่ว่างและห้ามมีช่องว่าง") parts = urllib.parse.urlsplit(url) if parts.scheme != "https" or not parts.netloc: - raise ValueError(_i18n.t("URL ต้องขึ้นต้นด้วย https:// และมีชื่อโดเมน")) + raise ValueError("URL ต้องขึ้นต้นด้วย https:// และมีชื่อโดเมน") return url.rstrip("/") @@ -127,22 +126,22 @@ def add_provider(*, pid: str, display_name: str, base_url: str, api_key: str, mo api_key = (api_key or "").strip() model = (model or "").strip() if not api_key: - raise ValueError(_i18n.t("ต้องระบุ API Key")) + raise ValueError("ต้องระบุ API Key") if "/" not in model: - raise ValueError(_i18n.t("โมเดลต้องอยู่ในรูป provider/model เช่น deepseek/deepseek-chat")) + raise ValueError("โมเดลต้องอยู่ในรูป provider/model เช่น deepseek/deepseek-chat") display_name = (display_name or "").strip() or pid providers = load_providers(providers_path, opencode_path) if pid in providers: - raise ValueError(_i18n.t("มีผู้ให้บริการ '{p0}' อยู่แล้ว", p0=pid)) + raise ValueError(f"มีผู้ให้บริการ '{pid}' อยู่แล้ว") engine_name = f"opencode-{pid}" engine_kw = {"cfg_path": cfg_path} if cfg_path is not None else {} if keys.get_engine(engine_name, **engine_kw): - raise ValueError(_i18n.t("มี Engine ชื่อ '{p0}' อยู่แล้ว", p0=engine_name)) + raise ValueError(f"มี Engine ชื่อ '{engine_name}' อยู่แล้ว") key_var = keys.validate_dotenv_key_name(provider_key_var(pid)) if keys.load_env_file(env_path).get(key_var): - raise ValueError(_i18n.t("มีคีย์ {p0} ใน .env อยู่แล้ว ไม่เขียนทับ", p0=key_var)) + raise ValueError(f"มีคีย์ {key_var} ใน .env อยู่แล้ว ไม่เขียนทับ") engine = { "name": engine_name, "provider": display_name, "command": "opencode", "model": model, diff --git a/auto_dev_crew/static_checks.py b/auto_dev_crew/static_checks.py index 530dba4..9eb74d8 100644 --- a/auto_dev_crew/static_checks.py +++ b/auto_dev_crew/static_checks.py @@ -4,7 +4,6 @@ กฎที่ blocking=True จะทำให้ diff ไม่ผ่านทันที โดยไม่เสียโควตา judge; กฎที่เป็นคำเตือนจะส่งให้ judge เป็นข้อมูลประกอบ. """ from __future__ import annotations -from auto_dev_crew import i18n as _i18n import re from dataclasses import dataclass @@ -43,8 +42,8 @@ _ISSUE_REF = re.compile(r"#\d+|/issues/\d+") RULE_HINTS = { - "broad-except-swallow": _i18n.t("จับ exception กว้างแล้วกลืนทิ้ง (except: pass) ให้จับเฉพาะชนิดที่คาดไว้ หรือ log/raise ใหม่"), - "js-empty-catch": _i18n.t("catch ว่างกลืน error ให้จัดการ แสดงผล หรือส่งต่อ"), + "broad-except-swallow": "จับ exception กว้างแล้วกลืนทิ้ง (except: pass) ให้จับเฉพาะชนิดที่คาดไว้ หรือ log/raise ใหม่", + "js-empty-catch": "catch ว่างกลืน error ให้จัดการ แสดงผล หรือส่งต่อ", "debug-artifact": "มีโค้ดดีบักหลงเหลือ (debugger / breakpoint / pdb / .only)", "hardcoded-secret": "ฝังค่าความลับไว้ในโค้ด ให้อ่านจาก environment หรือไฟล์ .env ที่ไม่ commit", "todo-without-issue": "TODO/FIXME ไม่ได้อ้าง issue (เช่น #123)", diff --git a/auto_dev_crew/todo_scan.py b/auto_dev_crew/todo_scan.py index a89df91..81d212d 100644 --- a/auto_dev_crew/todo_scan.py +++ b/auto_dev_crew/todo_scan.py @@ -1,6 +1,5 @@ """สแกนแท็ก [AI-TODO] ในโค้ดแล้วแปลงเป็น issue ติดป้าย ai-task (ไม่สแกน TODO/FIXME ทั่วไป กัน issue ท่วม).""" from __future__ import annotations -from auto_dev_crew import i18n as _i18n import hashlib import json @@ -173,9 +172,9 @@ def run_scan(repo: str, cfg: dict, create: bool = False) -> dict: encoding="utf-8", errors="replace", timeout=60, env={**os.environ, "GIT_TERMINAL_PROMPT": "0"}) if res.returncode != 0: - warnings.append(redact_secrets(_i18n.t("git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {p0}", p0=(res.stderr or res.stdout).strip()[:300]))) + warnings.append(redact_secrets(f"git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {(res.stderr or res.stdout).strip()[:300]}")) except Exception as exc: - warnings.append(redact_secrets(_i18n.t("git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {p0}", p0=exc))) + warnings.append(redact_secrets(f"git pull ล้มเหลว (สแกนจากข้อมูลเดิม): {exc}")) items = scan_todos(root) result: dict = {"ok": True, "repo": repo, "items": [i.to_dict() for i in items], "warnings": warnings} if create: diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 2db14b0..c13e110 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -22,7 +22,7 @@ Updated: 2026-11-18. Read this first when starting a new chat. Then read `STATE. | `/api/github/*`, `github_login.py`, `/classic` | `6d9e186` | Deleted. Guarded by `tests/test_removed_leftovers.py`. | | `REQUIREMENTS.md` | (banner, 2026-11-18) | Kept as history. Banner says it is not the current spec. | | `reserve_for_issues` | `e054139` | Removed from test fixtures. Config guard test stays. | -| `merge_level` 1/2/3 | (traced) | Matches `runner.py`; documented in `docs/architecture.md` section 8.1. | +| `merge_level` 1/2/3 | (traced) | Matches `runner.py`; documented in `docs/architecture_EN.md` section 8.1. | | GUI gate 3 and gate 4 wording | `eedfc7d` | Fixed in `static/index_sidebar.html`, `static/index.html`, `locales/en.json`. Guarded by `tests/test_gate_wording_gui.py`. | | Docs sync (Thai vs English) | `e054139` | Guard-hook list, config.yaml tracking statements, and English README note fixed. Checked by structure and inline code tokens only, not sentence by sentence. | | Main README in English | `fed6d2b` | `README.md` is English. Thai text moved to `README.th.md`. Both link to each other. Later, `README.md` was made English only and the Thai file became `README_TH.md` (`6b22e13`); `README.th.md` was removed (`f32b0e2`). | diff --git a/opencode.json b/opencode.json index 0d6fe53..d9289bc 100644 --- a/opencode.json +++ b/opencode.json @@ -6,14 +6,52 @@ "autoupdate": false, "provider": { "pollinations": { - "name": "Pollinations", + "name": "Pollinations AI", "options": { "baseURL": "https://gen.pollinations.ai/v1", "apiKey": "{env:POLLINATIONS_API_KEY_1}" }, "models": { + "deepseek/deepseek-v4.1-flash": { + "name": "DeepSeek V4.1 Flash" + }, + "deepseek/deepseek-v4.1-flash-1017": { + "name": "DeepSeek V4.1 Flash 1017" + }, "openai/gpt-6-luna": { - "name": "openai/gpt-6-luna" + "name": "GPT-6 Luna" + }, + "openai/gpt-oss-20b": { + "name": "GPT-OSS 20B" + }, + "stealth/glyph-cluster": { + "name": "Glyph Cluster" + } + } + } + }, + "providers": { + "pollinations": { + "name": "Pollinations AI", + "package": "@opencode/ai/providers/openai-compatible", + "env": [ + "POLLINATIONS_API_KEY_1" + ], + "settings": { + "baseURL": "https://gen.pollinations.ai/v1" + }, + "models": { + "deepseek/deepseek-v4.1-flash": { + "name": "DeepSeek V4.1 Flash" + }, + "deepseek/deepseek-v4.1-flash-1017": { + "name": "DeepSeek V4.1 Flash 1017" + }, + "openai/gpt-6-luna": { + "name": "GPT-6 Luna" + }, + "openai/gpt-oss-20b": { + "name": "GPT-OSS 20B" } } } diff --git a/tests/test_gui_check_page_load.py b/tests/test_gui_check_page_load.py new file mode 100644 index 0000000..c3908fd --- /dev/null +++ b/tests/test_gui_check_page_load.py @@ -0,0 +1,76 @@ +"""check_page must not fail just because the page keeps one request open (long-poll). + +Regression: `page.goto(..., wait_until="networkidle")` waits for 500 ms with no +network activity. The GUI keeps a long-poll request open, so the smoke check timed +out even though the page loaded and had no JS errors. +""" +from __future__ import annotations + +import http.server +import threading +import time + +import pytest + +pytest.importorskip("playwright.sync_api") + +from auto_dev_crew import gui_check # noqa: E402 + +PAGE = ( + b"
ok
" +) + + +class _Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): # noqa: N802 - http.server API + if self.path == "/hang": + # Keep this request open for longer than the test runs, like a long-poll. + time.sleep(60) + return + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(PAGE))) + self.end_headers() + self.wfile.write(PAGE) + + def log_message(self, *args): # keep test output quiet + pass + + +class _Server(http.server.ThreadingHTTPServer): + daemon_threads = True + + +@pytest.fixture +def long_poll_server(): + server = _Server(("127.0.0.1", 0), _Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + server.server_close() + + +def _chromium_available() -> bool: + from playwright.sync_api import sync_playwright + + try: + with sync_playwright() as p: + p.chromium.launch().close() + return True + except Exception: # noqa: BLE001 - browser not installed on this machine + return False + + +def test_check_page_passes_when_one_request_stays_open(long_poll_server, tmp_path, monkeypatch): + if not _chromium_available(): + pytest.skip("Chromium for Playwright is not installed") + monkeypatch.setattr(gui_check, "PAGE_TIMEOUT_MS", 5000) + + problems = gui_check.check_page(long_poll_server, tmp_path / "shot.png") + + assert problems == [] + assert (tmp_path / "shot.png").exists()