Files
cowork-local/infrastructure/filesystem/command_tools.py
T
vudt15 2a5ee29c2c fix(qa): resolve DF-002 through DF-011 from QA defect tracking sheet
Batch of fixes for defects tracked in "Task Tracking Template.xlsx" (sheet
Defect Management), verified against the sheet's Root Cause/Cach xu ly
columns before this commit:

- DF-002: Co4E node status not reflected after tab switch + missing
  edit-lock on running/done nodes (node_property_panel.py, co4e_runs.py,
  co4e_workflow_crud.py, co4e_canvas_widget.py, co4e_flow_tabs.py,
  canvas_items.py)
- DF-003: hide the run.bat console window unless the app exits with an
  error (run.bat, scripts/console_visibility.ps1 - new)
- DF-004: floating Help Assistant icon covering the Send button after a
  window resize (presentation/shell/main_window.py)
- DF-005: "block network" toggle didn't stop ICMP/raw-socket tools like
  ping (infrastructure/filesystem/command_tools.py,
  security/command_risk_classifier.py)
- DF-006: Monitoring "gay nang khi log lon" - root cause was re-reading
  the ENTIRE audit log history every 3s tick, not missing pagination;
  bounded to a 30-day window (presentation/monitoring/monitoring_tab.py)
  AND added the "So dong/trang" page-size control the ticket also asked
  for (presentation/monitoring/shared/event_table.py,
  shared/filter_scaffold.py, tabs/action_logs_tab.py, tabs/mcp_tab.py,
  tabs/security_events_tab.py, i18n/agents_admin_tab.py)
- DF-007: support choosing a OneDrive/SharePoint folder as a project's
  working directory via Microsoft Graph, downloaded as a local mirror
  with manual sync (core/projects.py, core/ms365_graph.py,
  core/cloud_workspace_sync.py - new, ui/ms365_signin_dialog.py - new,
  ui/cloud_folder_picker_dialog.py - new, i18n/cloud_workspace.py - new,
  ui/workspace_tab.py)
- DF-008: AI-edit instruction box was a fixed-height single-line QLineEdit;
  replaced with an auto-expanding, Enter-to-send/Shift+Enter-newline input
  (presentation/folder/ai_file_editor_dialog.py)
- DF-011: run_command failed with WinError 267 for a project whose
  per-turn output directory had never been created
  (application/conversations/core_runtime_adapter.py)

DF-009 (AI-edit Apply/Discard buttons easy to miss) and DF-010 (AI reply
language - dev-confirmed not a bug) are intentionally NOT part of this
commit: DF-009 has no code fix yet (still "Assigned" in the sheet, only a
UX recommendation was recorded), DF-010 was rejected as expected behavior.

Tests: tests/test_cloud_workspace_sync.py, tests/test_ms365_cloud_dialogs.py,
tests/test_ai_file_editor_input.py, tests/test_monitoring_page_size.py (all
new, all passing). Full suite: 896 passed, 13 known-and-documented failures
unrelated to this change (an existing core/audit_log.py bug, this checkout
not being a git repo before now, and a repo/subprocess folder-naming
mismatch affecting ~66 characterization tests) - see the sheet's DF-006
Evidence column for details.
2026-09-07 21:22:00 +09:00

138 lines
5.7 KiB
Python

"""Command tools - run_command, install_package (R05-T02).
Moved verbatim out of ``core/tools.py`` (see ``file_tools.py`` for why). These
two are the ones today's hand-written permission gate in
``core/chat_agent.py`` singles out by literal name
(``name in ("run_command", "install_package")``) — R05-T03 replaces that
tuple with a capability lookup, but the tools themselves are unchanged here.
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import Any, Dict, Optional
from .tool_context import CancelFn, ToolContext
COMMAND_TIMEOUT = 120 # seconds
_SNAPSHOT_SKIP = {".git", "__pycache__", "node_modules", ".scratch", ".venv",
".idea", ".mypy_cache", ".pytest_cache"}
def _snapshot(workdir: Path) -> Dict[str, Any]:
"""Map of file path -> (mtime, size) under the workdir (noise dirs skipped)."""
snap: Dict[str, Any] = {}
try:
for dirpath, dirnames, filenames in os.walk(str(workdir)):
dirnames[:] = [d for d in dirnames if d not in _SNAPSHOT_SKIP]
for fn in filenames:
full = os.path.join(dirpath, fn)
try:
st = os.stat(full)
snap[full] = (st.st_mtime_ns, st.st_size)
except OSError:
pass
if len(snap) > 5000:
return snap
except OSError:
pass
return snap
def _sandbox_python(ctx: ToolContext, cancel: Optional[CancelFn] = None,
on_output=None) -> Optional[str]:
"""Lazily create/reuse this ctx's project sandbox venv (Code tab only —
``ctx.sandbox``); returns its python path, or None to use the app's own."""
if not ctx.sandbox:
return None
from cowork_local.core.deps import ensure_project_venv
py = ensure_project_venv(ctx.workdir, cancel=cancel, on_output=on_output)
return str(py) if py else None
def run_command(ctx: ToolContext, args: Dict[str, Any],
cancel: Optional[CancelFn] = None,
on_output=None) -> Dict[str, Any]:
"""Chạy một lệnh shell trong thư mục làm việc, có hạn giờ và có sandbox.
Biến môi trường được lọc và mạng bị chặn theo cấu hình an toàn — agent chạy
lệnh không được thừa hưởng toàn bộ môi trường của người dùng.
"""
from cowork_local.core.deps import network_blocked_env, run_cancellable, sandbox_env
from cowork_local.core.sandbox_manager import ExecutionConfig, SandboxManager
from cowork_local.security.command_risk_classifier import (
classify_command, command_bypasses_network_proxy,
)
command = str(args.get("command", "")).strip()
if not command:
return {"ok": False, "output": "Empty command."}
# --- Security validation pipeline ---
risk = classify_command(command, is_cowork_mode=ctx.flatten_writes)
if risk.blocked:
denial = "Command blocked by security policy: " + "; ".join(risk.reasons)
return {"ok": False, "output": denial}
# Every sandbox backend's network block is a proxy-env-var trick (see
# core/deps.py::network_blocked_env) — it does nothing against a tool
# that reaches the network without an HTTP proxy (ping/ICMP, nslookup/
# direct DNS, ssh/ftp/raw TCP...). Deny those BY NAME here instead, so
# "Chặn mạng cho lệnh do agent chạy" actually blocks them too.
if ctx.block_network:
bypass_tool = command_bypasses_network_proxy(command)
if bypass_tool:
return {"ok": False, "output": (
f"Command blocked: '{bypass_tool}' can reach the network without going through "
"an HTTP proxy, so the sandbox's network block (which only filters proxy-aware "
"traffic) cannot stop it by itself — blocked by name instead while "
"'Chặn mạng cho lệnh do agent chạy' is on."
)}
# Route through SandboxManager for risk-based isolation
mgr = SandboxManager(ExecutionConfig(
enabled=True,
block_network_by_default=ctx.block_network,
is_cowork_mode=ctx.flatten_writes,
))
sandbox_result = mgr.run(
command=command,
workdir=str(ctx.workdir),
block_network=ctx.block_network,
timeout_sec=COMMAND_TIMEOUT,
cancel=cancel,
)
# Sandbox ALWAYS executes (never double-run). Return its result directly.
if sandbox_result.get("sandbox") == "blocked":
return {"ok": False, "output": sandbox_result.get("stderr", "Command blocked")}
out = sandbox_result.get("stdout", "").strip() or "(no output)"
err = sandbox_result.get("stderr", "")
rc = sandbox_result.get("returncode", -1)
if err:
out = f"{out}\n{err}" if out else err
return {"ok": sandbox_result.get("ok", False), "output": f"[exit {rc}]\n{out}"}
def install_package(ctx: ToolContext, args: Dict[str, Any],
cancel: Optional[CancelFn] = None,
on_output=None) -> Dict[str, Any]:
"""Cài một gói Python vào môi trường phụ trợ của lượt chạy.
Cài vào venv riêng chứ không vào Python của hệ thống — một task không được
phép làm hỏng môi trường của cả máy.
"""
from cowork_local.core.deps import pip_install
package = str(args.get("package", "")).strip()
if not package:
return {"ok": False, "output": "No package specified."}
python = _sandbox_python(ctx, cancel, on_output)
ok, detail = pip_install(package, cancel=cancel, on_output=on_output, python=python)
head = f"Installed {package}." if ok else f"Could not install {package}."
return {"ok": ok, "output": f"{head}\n{detail}"}
__all__ = ["COMMAND_TIMEOUT", "run_command", "install_package", "_snapshot"]