From d21ac8ac977fe566250e17f5aa31cf8123a6fbdd Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Mon, 15 Jun 2026 10:05:17 +0200 Subject: [PATCH] refac --- cptr/utils/documents.py | 292 ++++++++++++++++++++++++++++++++++++++++ cptr/utils/tools.py | 181 +++++++++++++++++++------ pyproject.toml | 1 + 3 files changed, 434 insertions(+), 40 deletions(-) create mode 100644 cptr/utils/documents.py diff --git a/cptr/utils/documents.py b/cptr/utils/documents.py new file mode 100644 index 0000000..637015d --- /dev/null +++ b/cptr/utils/documents.py @@ -0,0 +1,292 @@ +"""Document text extraction utilities. + +Extracts readable text from binary document formats so LLMs can +consume their content. Each ``extract_*`` function takes a file path +and returns the document's text as a plain string. + +All imports are lazy — missing libraries produce a clear ImportError +with install instructions, not a crash. +""" + +import os +import zipfile + + +def extract_pdf(file_path: str) -> str: + """Extract text from a PDF file.""" + try: + from pypdf import PdfReader + except ImportError: + raise ImportError("pip install pypdf") + + reader = PdfReader(file_path) + return "\n".join(page.extract_text() or "" for page in reader.pages) + + +def extract_docx(file_path: str) -> str: + """Extract text from a Word (.docx) file.""" + try: + from docx import Document as DocxDocument + except ImportError: + raise ImportError("pip install python-docx") + + doc = DocxDocument(file_path) + parts = [] + for para in doc.paragraphs: + parts.append(para.text) + for table in doc.tables: + for row in table.rows: + parts.append("\t".join(cell.text for cell in row.cells)) + return "\n".join(parts) + + +def extract_xlsx(file_path: str) -> str: + """Extract text from an Excel (.xlsx) file.""" + try: + from openpyxl import load_workbook + except ImportError: + raise ImportError("pip install openpyxl") + + wb = load_workbook(file_path, read_only=True, data_only=True) + parts = [] + for sheet in wb.worksheets: + parts.append(f"--- {sheet.title} ---") + for row in sheet.iter_rows(values_only=True): + parts.append("\t".join(str(c) if c is not None else "" for c in row)) + wb.close() + return "\n".join(parts) + + +def extract_pptx(file_path: str) -> str: + """Extract text from a PowerPoint (.pptx) file.""" + try: + from pptx import Presentation + except ImportError: + raise ImportError("pip install python-pptx") + + prs = Presentation(file_path) + parts = [] + for i, slide in enumerate(prs.slides, 1): + parts.append(f"--- Slide {i} ---") + for shape in slide.shapes: + if shape.has_text_frame: + parts.append(shape.text_frame.text) + return "\n".join(parts) + + +def extract_rtf(file_path: str) -> str: + """Extract text from a Rich Text Format (.rtf) file.""" + try: + from striprtf.striprtf import rtf_to_text + except ImportError: + raise ImportError("pip install striprtf") + + with open(file_path, "rb") as f: + raw = f.read() + return rtf_to_text(raw.decode("utf-8", errors="replace")) + + +def extract_xls(file_path: str) -> str: + """Extract text from a legacy Excel (.xls) file.""" + try: + import xlrd + except ImportError: + raise ImportError("pip install xlrd") + + wb = xlrd.open_workbook(file_path) + parts = [] + for sheet in wb.sheets(): + parts.append(f"--- {sheet.name} ---") + for row_idx in range(sheet.nrows): + parts.append("\t".join( + str(sheet.cell_value(row_idx, col_idx)) + for col_idx in range(sheet.ncols) + )) + return "\n".join(parts) + + +def extract_odt(file_path: str) -> str: + """Extract text from an OpenDocument Text (.odt) file.""" + try: + from lxml import etree + except ImportError: + raise ImportError("pip install lxml") + + with zipfile.ZipFile(file_path) as zf: + with zf.open("content.xml") as f: + tree = etree.parse(f) + ns = "urn:oasis:names:tc:opendocument:xmlns:text:1.0" + return "\n".join( + "".join(p.itertext()) + for p in tree.iter(f"{{{ns}}}p") + ) + + +def extract_ods(file_path: str) -> str: + """Extract text from an OpenDocument Spreadsheet (.ods) file.""" + try: + from lxml import etree + except ImportError: + raise ImportError("pip install lxml") + + with zipfile.ZipFile(file_path) as zf: + with zf.open("content.xml") as f: + tree = etree.parse(f) + ns_table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0" + ns_text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0" + parts = [] + for table in tree.iter(f"{{{ns_table}}}table"): + name = table.get(f"{{{ns_table}}}name", "Sheet") + parts.append(f"--- {name} ---") + for row in table.iter(f"{{{ns_table}}}table-row"): + cells = [] + for cell in row.iter(f"{{{ns_table}}}table-cell"): + cell_text = " ".join( + "".join(p.itertext()) + for p in cell.iter(f"{{{ns_text}}}p") + ) + cells.append(cell_text) + parts.append("\t".join(cells)) + return "\n".join(parts) + + +def extract_odp(file_path: str) -> str: + """Extract text from an OpenDocument Presentation (.odp) file.""" + try: + from lxml import etree + except ImportError: + raise ImportError("pip install lxml") + + with zipfile.ZipFile(file_path) as zf: + with zf.open("content.xml") as f: + tree = etree.parse(f) + ns_draw = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" + ns_text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0" + parts = [] + for i, page in enumerate(tree.iter(f"{{{ns_draw}}}page"), 1): + parts.append(f"--- Slide {i} ---") + for p in page.iter(f"{{{ns_text}}}p"): + text = "".join(p.itertext()).strip() + if text: + parts.append(text) + return "\n".join(parts) + + +def extract_epub(file_path: str) -> str: + """Extract text from an EPUB e-book.""" + try: + from lxml import etree + except ImportError: + raise ImportError("pip install lxml") + + parts = [] + with zipfile.ZipFile(file_path) as zf: + # Parse the container to find the root file + with zf.open("META-INF/container.xml") as cf: + container = etree.parse(cf) + ns_container = "urn:oasis:names:tc:opendocument:xmlns:container" + rootfile = container.find(f".//{{{ns_container}}}rootfile") + if rootfile is None: + rootfile = container.xpath("//*[local-name()='rootfile']") + rootfile = rootfile[0] if rootfile else None + + if rootfile is not None: + opf_path = rootfile.get("full-path", "") + opf_dir = opf_path.rsplit("/", 1)[0] + "/" if "/" in opf_path else "" + with zf.open(opf_path) as opf_file: + opf = etree.parse(opf_file) + spine_ids = [ + item.get("idref") + for item in opf.xpath("//*[local-name()='itemref']") + ] + manifest = { + item.get("id"): item.get("href") + for item in opf.xpath("//*[local-name()='item']") + } + for idref in spine_ids: + href = manifest.get(idref, "") + item_path = opf_dir + href if not href.startswith("/") else href.lstrip("/") + try: + with zf.open(item_path) as html_file: + html_tree = etree.parse(html_file, etree.HTMLParser()) + body = html_tree.find(".//body") + if body is not None: + text = "".join(body.itertext()) + parts.append(text.strip()) + except (KeyError, etree.XMLSyntaxError): + continue + else: + for name in zf.namelist(): + if name.endswith((".html", ".xhtml", ".htm")): + try: + with zf.open(name) as html_file: + html_tree = etree.parse(html_file, etree.HTMLParser()) + body = html_tree.find(".//body") + if body is not None: + text = "".join(body.itertext()) + parts.append(text.strip()) + except etree.XMLSyntaxError: + continue + return "\n\n".join(parts) + + +def extract_eml(file_path: str) -> str: + """Extract text from an email message (.eml).""" + import email + from email import policy + + with open(file_path, "rb") as f: + msg = email.message_from_binary_file(f, policy=policy.default) + parts = [] + for header in ("From", "To", "Cc", "Date", "Subject"): + val = msg.get(header) + if val: + parts.append(f"{header}: {val}") + parts.append("") # blank line after headers + body = msg.get_body(preferencelist=("plain", "html")) + if body: + content = body.get_content() + if body.get_content_type() == "text/html": + try: + from lxml import etree + tree = etree.HTML(content) + content = "".join(tree.itertext()) if tree is not None else content + except ImportError: + pass # Fall back to raw HTML text + parts.append(content) + return "\n".join(parts) + + +# MIME type / extension → extractor mapping. +# Each entry: (mime_type_or_None, file_extension_or_None, extractor) +EXTRACTORS: list[tuple[str | None, str | None, callable]] = [ + ("application/pdf", None, extract_pdf), + ("application/vnd.openxmlformats-officedocument.wordprocessingml.document", None, extract_docx), + ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", None, extract_xlsx), + ("application/vnd.openxmlformats-officedocument.presentationml.presentation", None, extract_pptx), + ("application/rtf", ".rtf", extract_rtf), + ("application/vnd.ms-excel", ".xls", extract_xls), + ("application/vnd.oasis.opendocument.text", ".odt", extract_odt), + ("application/vnd.oasis.opendocument.spreadsheet", ".ods", extract_ods), + ("application/vnd.oasis.opendocument.presentation", ".odp", extract_odp), + ("application/epub+zip", ".epub", extract_epub), + ("message/rfc822", ".eml", extract_eml), +] + + +def extract_by_path(file_path: str) -> str | None: + """Try all extractors for a file by MIME type / extension. + + Returns extracted text, or None if no extractor matches. + Raises ImportError with install instructions if the matching + extractor's library is missing. + """ + import mimetypes + + mime, _ = mimetypes.guess_type(file_path) + ext = os.path.splitext(file_path)[1].lower() + + for ext_mime, ext_suffix, extractor in EXTRACTORS: + if (ext_mime and mime == ext_mime) or (ext_suffix and ext == ext_suffix): + return extractor(file_path) + return None diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index bd70591..e7c39e1 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -17,6 +17,7 @@ import inspect import json import os import re +import time import uuid from pathlib import Path from typing import Callable, Optional, Pattern, get_type_hints @@ -30,8 +31,21 @@ _BG_TASK_LIMIT = 5 async def _collect_bg_output(task_id: str, proc: asyncio.subprocess.Process): - """Collect output from a background process into the task buffer.""" + """Collect output from a background process into memory + JSONL log.""" + task = _bg_tasks.get(task_id) + log_path = task.get("log_path") if task else None + log_file = None + try: + if log_path: + Path(log_path).parent.mkdir(parents=True, exist_ok=True) + log_file = open(log_path, "a", encoding="utf-8") + log_file.write( + json.dumps({"type": "start", "command": task["command"], + "ts": time.time()}) + "\n" + ) + log_file.flush() + while True: chunk = await proc.stdout.read(4096) if not chunk: @@ -39,15 +53,28 @@ async def _collect_bg_output(task_id: str, proc: asyncio.subprocess.Process): task = _bg_tasks.get(task_id) if task: task["output"].extend(chunk) - # Cap buffer at 256KB + # Cap in-memory buffer at 256KB if len(task["output"]) > 256 * 1024: - task["output"] = task["output"][-256 * 1024 :] + task["output"] = task["output"][-256 * 1024:] + if log_file: + log_file.write( + json.dumps({"type": "output", + "data": chunk.decode(errors="replace"), + "ts": time.time()}) + "\n" + ) + log_file.flush() except Exception: pass finally: task = _bg_tasks.get(task_id) if task: task["done"] = True + if log_file: + log_file.write( + json.dumps({"type": "end", "exit_code": proc.returncode, + "ts": time.time()}) + "\n" + ) + log_file.close() # ── Helper ────────────────────────────────────────────────── @@ -187,7 +214,37 @@ async def read_file( if size > 500_000: return f"Error: file too large ({size} bytes, max 500KB)" - lines = full.read_text(errors="replace").splitlines() + # Try strict text decoding first + try: + content = full.read_text(errors="strict") + except (UnicodeDecodeError, ValueError): + # Binary file — try document extraction (PDF, DOCX, XLSX, etc.) + try: + from cptr.utils.documents import extract_by_path + + text = extract_by_path(str(full)) + if text: + lines = text.splitlines() + total = len(lines) + if start_line > 0 or end_line > 0: + s = max(1, start_line) - 1 + e = min(total, end_line) if end_line > 0 else total + selected = lines[s:e] + numbered = [f"{i + s + 1}: {line}" for i, line in enumerate(selected)] + return f"File: {path} | Lines {s + 1}-{e} of {total}\n" + "\n".join(numbered) + capped = lines[:800] + numbered = [f"{i + 1}: {line}" for i, line in enumerate(capped)] + header = f"File: {path} | Total lines: {total}" + if total > 800: + header += " (showing first 800)" + return header + "\n" + "\n".join(numbered) + except ImportError as e: + return f"Error: reading {full.suffix} files requires: {e}" + except Exception as e: + return f"Error: failed to extract text from {path}: {e}" + return f"Error: binary file ({full.suffix}), cannot read as text" + + lines = content.splitlines() total = len(lines) if start_line > 0 or end_line > 0: @@ -628,21 +685,23 @@ async def multi_edit_file( async def run_command( command: str, cwd: str = ".", - timeout: int = 30, - background: bool = False, + wait: int = 10, *, workspace: str, ) -> str: - """Run a shell command. Use background=true for long-running processes. + """Run a shell command. Returns a task_id for status checks and input. :param command: The shell command to execute. :param cwd: Working directory relative to workspace root. - :param timeout: Timeout in seconds (max 300, ignored if background). - :param background: Run in background and return a task_id for status checks. + :param wait: Seconds to wait for output before returning (0-30). The command continues running regardless. """ work_dir = _resolve_path(cwd, workspace) if not work_dir.is_dir(): return f"Error: not a directory: {cwd}" + active = sum(1 for t in _bg_tasks.values() if not t.get("done")) + if active >= _BG_TASK_LIMIT: + return f"Error: too many running tasks ({active}/{_BG_TASK_LIMIT}). Kill one first." + env = {**os.environ, "PAGER": "cat", "GIT_PAGER": "cat"} try: @@ -650,43 +709,52 @@ async def run_command( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, + stdin=asyncio.subprocess.PIPE, cwd=str(work_dir), env=env, ) - - if background: - active = sum(1 for t in _bg_tasks.values() if not t.get("done")) - if active >= _BG_TASK_LIMIT: - proc.kill() - return ( - f"Error: too many background tasks ({active}/{_BG_TASK_LIMIT}). Kill one first." - ) - - task_id = uuid.uuid4().hex[:8] - _bg_tasks[task_id] = { - "proc": proc, - "output": bytearray(), - "command": command, - "done": False, - } - asyncio.create_task(_collect_bg_output(task_id, proc)) - return f"Background task started: {task_id}\nCommand: {command}\nUse check_task('{task_id}') to see output or kill_task('{task_id}') to stop it." - - timeout = min(max(timeout, 5), 300) - stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout) - output = stdout.decode(errors="replace").strip() - output = _truncate_output(output, max_chars=CHAT_TOOL_COMMAND_MAX_CHARS) - - if proc.returncode != 0: - return f"Exit code {proc.returncode}\n{output}" - return output or "(no output)" - - except asyncio.TimeoutError: - proc.kill() - return f"Error: command timed out after {timeout}s. Consider using background=true for long commands." except Exception as e: return f"Error: {e}" + task_id = uuid.uuid4().hex[:8] + log_dir = Path(workspace) / ".cptr" / "task_logs" + log_dir.mkdir(parents=True, exist_ok=True) + log_path = log_dir / f"{task_id}.jsonl" + + _bg_tasks[task_id] = { + "proc": proc, + "output": bytearray(), + "command": command, + "done": False, + "log_path": str(log_path), + } + collect_task = asyncio.create_task(_collect_bg_output(task_id, proc)) + + # Wait for quick commands to finish inline + wait = min(max(wait, 0), 30) + if wait > 0: + try: + await asyncio.wait_for(asyncio.shield(collect_task), timeout=wait) + except asyncio.TimeoutError: + pass + + task = _bg_tasks.get(task_id) + output = task["output"].decode(errors="replace") if task else "" + output = _truncate_output(output, max_chars=CHAT_TOOL_COMMAND_MAX_CHARS) + done = task.get("done", False) if task else True + exit_code = proc.returncode + + if done: + status = f"exited (code {exit_code})" + else: + status = "running" + + return ( + f"Task {task_id}: {status}\n" + f"Command: {command}\n" + f"---\n{output}" + ) + async def check_task(task_id: str, *, workspace: str) -> str: """Check status and recent output of a background task. @@ -732,6 +800,38 @@ async def kill_task(task_id: str, *, workspace: str) -> str: return f"Killed task {task_id}" +async def send_input(task_id: str, input: str, *, workspace: str) -> str: + """Send input to a running task's stdin. Use for interactive prompts, REPLs, or control characters. + :param task_id: The task ID returned by run_command. + :param input: Text to send. Use \\n for Enter, \\x03 for Ctrl-C, \\x04 for Ctrl-D. + """ + task = _bg_tasks.get(task_id) + if not task: + available = list(_bg_tasks.keys()) + return f"Error: no task '{task_id}'. Active: {available or 'none'}" + + proc = task["proc"] + if proc.returncode is not None: + return f"Error: task {task_id} already exited (code {proc.returncode})" + + if proc.stdin is None: + return f"Error: task {task_id} has no stdin" + + # LLMs emit literal "\n" — convert to real characters + try: + text = input.encode("raw_unicode_escape").decode("unicode_escape") + except (UnicodeDecodeError, ValueError): + text = input + + try: + proc.stdin.write(text.encode()) + await proc.stdin.drain() + except (BrokenPipeError, ConnectionResetError, OSError): + return f"Error: stdin closed for task {task_id}" + + return f"Sent {len(text)} bytes to task {task_id}" + + async def web_search(query: str, *, workspace: str) -> str: """Search the web for information. Returns summaries with source URLs. :param query: The search query. @@ -1191,6 +1291,7 @@ TOOLS: dict[str, dict] = { "multi_edit_file": {"fn": multi_edit_file, "auto": False}, "write_file": {"fn": write_file, "auto": False}, "run_command": {"fn": run_command, "auto": False}, + "send_input": {"fn": send_input, "auto": False}, "kill_task": {"fn": kill_task, "auto": False}, "create_automation": {"fn": create_automation, "auto": False}, "update_automation": {"fn": update_automation, "auto": False}, diff --git a/pyproject.toml b/pyproject.toml index 9c623fa..5726f71 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ dependencies = [ [project.optional-dependencies] pam = ["python-pam>=2.0"] mcp = ["mcp>=1.8"] +docs = ["pypdf>=4.0", "python-docx>=1.0", "openpyxl>=3.1"] [dependency-groups] dev = [