diff --git a/.gitignore b/.gitignore index 3b63770..3a2434e 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,9 @@ ignore/ __pycache__/ *.py[cod] *$py.class +.coverage +.coverage.* +htmlcov/ # Virtual environments .venv/ diff --git a/agentoffice/core/agent.py b/agentoffice/core/agent.py index fe84e35..5a0b9e5 100644 --- a/agentoffice/core/agent.py +++ b/agentoffice/core/agent.py @@ -5,6 +5,7 @@ from dotenv import load_dotenv from openai import OpenAI +from agentoffice.core.memory import AgentMemory from agentoffice.core.tool import BaseTool load_dotenv() @@ -16,14 +17,26 @@ def __init__( model: str = "gemini-3.5-flash-lite", system_prompt: str = "", tools: list[BaseTool] | None = None, + history: list[dict] | None = None, + on_tool_call=None, + memory=None, + client: OpenAI | None = None, ): - self.client = OpenAI( + self.client = client or OpenAI( api_key=os.getenv("GEMINI_API_KEY"), base_url="https://generativelanguage.googleapis.com/v1beta/openai/", ) self.model = model self.system_prompt = system_prompt self.tool_map: dict[str, BaseTool] = {} + self.on_tool_call = on_tool_call + if memory is not None: + self.memory = memory + else: + self.memory = AgentMemory(system_prompt=system_prompt) + if history: + self.memory.history = list(history) + if tools: for tool in tools: self.register_tool(tool) @@ -44,35 +57,80 @@ def execute_tool(self, name: str, arguments: str) -> str: return json.dumps({"error": f"{type(e).__name__}: {e}"}) def run(self, message: str, max_iterations: int = 10) -> str: - messages = [] - if self.system_prompt: - messages.append({"role": "system", "content": self.system_prompt}) - messages.append({"role": "user", "content": message}) + prev_history_len = len(self.memory.history) + self.memory.add_user_message(message) + tools_schema = [tool.to_schema() for tool in self.tool_map.values()] or None - for turn in range(max_iterations): - response = self.client.chat.completions.create( - model=self.model, - messages=messages, - tools=tools_schema, - ) + try: + for turn in range(max_iterations): + # Check token budget before each LLM call to prevent exceeding limits + self.compact(force=False) - response_message = response.choices[0].message - messages.append(response_message) + response = self.client.chat.completions.create( + model=self.model, + tools=tools_schema, + messages=self.memory.history, + ) - if not response_message.tool_calls: - return response_message.content + response_message = response.choices[0].message + if response.usage: + self.memory.record_usage(response.usage) + self.memory.add_assistant_message(response_message) - for tool_call in response_message.tool_calls: - result = self.execute_tool( - tool_call.function.name, tool_call.function.arguments - ) - messages.append( - { - "role": "tool", - "tool_call_id": tool_call.id, - "name": tool_call.function.name, - "content": result, - } - ) - return "Max iterations reached" + if not response_message.tool_calls: + return response_message.content + + for tool_call in response_message.tool_calls: + try: + result = self.execute_tool( + tool_call.function.name, tool_call.function.arguments + ) + except Exception as exc: + # Record the error so the conversation history remains valid + result = f"Error executing {tool_call.function.name}: {exc}" + + self.memory.add_tool_message( + tool_call.id, tool_call.function.name, result + ) + + if self.on_tool_call: + try: + print(f"Tool called: {tool_call.function.name}") + self.on_tool_call( + tool_call.function.name, + tool_call.function.arguments, + result, + ) + except Exception: + # Callback failures should never crash other tool executions + pass + return "Max tool calls reached" + except Exception: + # If the request failed before completing an assistant turn, remove + # the unanswered user message so history maintains a valid role sequence + if ( + len(self.memory.history) == prev_history_len + 1 + and self.memory.history[-1].get("role") == "user" + ): + self.memory.history.pop() + raise + + def clear_history(self): + self.memory.clear_history() + return self.memory.history + + @property + def history(self) -> list[dict]: + return self.memory.history + + @property + def session_usage(self) -> dict: + return self.memory.session_usage + + @property + def last_usage(self) -> dict: + return self.memory.last_usage + + def compact(self, force: bool = True): + return self.memory.compact(self.client, self.model, force=force) diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py new file mode 100644 index 0000000..d3eb6ee --- /dev/null +++ b/agentoffice/core/memory.py @@ -0,0 +1,219 @@ +class AgentMemory: + def __init__( + self, + system_prompt: str = "", + token_threshold: int = 12000, + max_tool_chars: int = 40000, + ): + self.system_prompt = system_prompt + self.token_threshold = token_threshold + self.max_tool_chars = max_tool_chars + self.history: list[dict] = [] + + if self.system_prompt: + self.history.append({"role": "system", "content": self.system_prompt}) + + self.last_usage = { + "prompt_tokens": 0, + "completion_tokens": 0, + "cached_tokens": 0, + "total_tokens": 0, + } + self.session_usage = { + "prompt_tokens": 0, + "completion_tokens": 0, + "cached_tokens": 0, + "total_tokens": 0, + "compactions": 0, + "tokens_saved": 0, + } + + def add_user_message(self, content: str) -> None: + self.history.append({"role": "user", "content": content}) + + def add_tool_message(self, tool_call_id: str, name: str, content: str) -> None: + if len(content) > self.max_tool_chars: + content = ( + content[: self.max_tool_chars] + "\n... [Truncated: output too large]" + ) + + self.history.append( + { + "role": "tool", + "tool_call_id": tool_call_id, + "name": name, + "content": content, + } + ) + + def add_assistant_message(self, message) -> None: + if isinstance(message, dict): + self.history.append(message) + return + + msg_dict: dict = { + "role": "assistant", + "content": getattr(message, "content", None) or "", + } + + tool_calls = getattr(message, "tool_calls", None) + if tool_calls: + msg_dict["tool_calls"] = [] + for tc in tool_calls: + tc_data = { + "id": tc.id, + "type": "function", + "function": { + "name": tc.function.name, + "arguments": tc.function.arguments, + }, + } + extra_content = getattr(tc, "extra_content", None) + if extra_content: + tc_data["extra_content"] = extra_content + msg_dict["tool_calls"].append(tc_data) + + self.history.append(msg_dict) + + def record_usage(self, usage) -> None: + if not usage: + return + + cached = ( + getattr(usage.prompt_tokens_details, "cached_tokens", 0) + if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details + else 0 + ) or 0 + + self.last_usage = { + "prompt_tokens": usage.prompt_tokens, + "completion_tokens": usage.completion_tokens, + "cached_tokens": cached, + "total_tokens": usage.total_tokens, + } + self.session_usage["count"] = self.session_usage.get("count", 0) + 1 + for key in self.last_usage: + self.session_usage[key] = ( + self.session_usage.get(key, 0) + self.last_usage[key] + ) + + def clear_history(self): + self.history = [] + if self.system_prompt: + self.history.append({"role": "system", "content": self.system_prompt}) + return self.history + + def get_history(self): + return self.history + + def get_last_usage(self): + return self.last_usage + + def get_session_usage(self): + return self.session_usage + + def compact(self, client, model: str, force: bool = True): + if not force and self.last_usage.get("prompt_tokens", 0) < self.token_threshold: + return None + slice_index = self._find_safe_slice_index() + if slice_index is None: + return None + start_index = ( + 1 if (self.history and self.history[0].get("role") == "system") else 0 + ) + old_messages = self.history[start_index:slice_index] + + if not old_messages: + return None + + text_for_compaction = [] + for msg in old_messages: + role = msg.get("role", "") + content = msg.get("content", "") + if content: + text_for_compaction.append(f"{role.upper()}: {content}") + + # Include tool calls even if content is empty/None + if msg.get("tool_calls"): + tool_info = [] + for tc in msg["tool_calls"]: + tool_name = tc.get("function", {}).get("name", "") + tool_args = str(tc.get("function", {}).get("arguments", "")) + tool_info.append(f"{tool_name}({tool_args})") + if tool_info: + text_for_compaction.append( + f"{role.upper()}: called {'; '.join(tool_info)}" + ) + + transcript = "\n\n".join(text_for_compaction) + + summary_messages = [ + { + "role": "system", + "content": ( + "You are a helpful assistant. Summarize the following conversation history concisely. " + "Crucially preserve: any file names, paths, identifiers, technical decisions, key " + "results, and the current task status." + ), + }, + {"role": "user", "content": f"Conversation:\n{transcript}"}, + ] + + tokens_before = self.last_usage.get("total_tokens", 0) + + response = client.chat.completions.create( + model=model, + messages=summary_messages, + ) + if response.usage: + # Record summary usage into session totals only without corrupting last_usage + self.session_usage["count"] = self.session_usage.get("count", 0) + 1 + self.session_usage["prompt_tokens"] += ( + getattr(response.usage, "prompt_tokens", 0) or 0 + ) + self.session_usage["completion_tokens"] += ( + getattr(response.usage, "completion_tokens", 0) or 0 + ) + cached = ( + getattr(response.usage.prompt_tokens_details, "cached_tokens", 0) + if hasattr(response.usage, "prompt_tokens_details") + and response.usage.prompt_tokens_details + else 0 + ) or 0 + self.session_usage["cached_tokens"] += cached + self.session_usage["total_tokens"] += ( + getattr(response.usage, "total_tokens", 0) or 0 + ) + + summary = (response.choices[0].message.content or "").strip() + if not summary: + return None + + new_history = ( + self.history[:1] + if self.history and self.history[0].get("role") == "system" + else [] + ) + new_history.append( + { + "role": "assistant", + "content": f"[Summary of previous conversation]\n{summary}", + } + ) + new_history.extend(self.history[slice_index:]) + self.history = new_history + self.session_usage["compactions"] += 1 + self.session_usage["tokens_saved"] += tokens_before + return summary + + def _find_safe_slice_index(self, keep_ratio: float = 0.25) -> int: + + if len(self.history) <= 3: + return None + + target = int(len(self.history) * (1 - keep_ratio)) + + for i in range(target, 0, -1): + if self.history[i]["role"] == "user": + return i + return None diff --git a/agentoffice/core/tool.py b/agentoffice/core/tool.py index a5d60c8..73467eb 100644 --- a/agentoffice/core/tool.py +++ b/agentoffice/core/tool.py @@ -5,7 +5,7 @@ class BaseTool(ABC): def __init__(self, name: str, description: str, parameters: dict): self.name = name self.description = description - self.parameters = parameters + self.parameters = dict(parameters) if "additionalProperties" not in self.parameters: self.parameters["additionalProperties"] = False diff --git a/agentoffice/interface/chat.py b/agentoffice/interface/chat.py new file mode 100644 index 0000000..d36092a --- /dev/null +++ b/agentoffice/interface/chat.py @@ -0,0 +1,48 @@ +from pathlib import Path + +from agentoffice.core.agent import BaseAgent +from agentoffice.tools.excel import create_excel_tools + + +def print_tool_call(name: str, arguments: str, result: str) -> None: + print(f"\n[Tool] {name}({arguments}) -> {result[:120]}") + + +class ChatInterface: + def __init__(self, agent: BaseAgent): + self.agent = agent + + def run(self): + while True: + try: + user_input = input("You: ") + except (KeyboardInterrupt, EOFError): + print("\nExiting chat session.") + break + if user_input.strip().lower() in {"exit", "quit", "q"}: + print("Exiting chat session.") + break + if not user_input.strip(): + continue + try: + reply = self.agent.run(user_input) + print(f"Agent: {reply}") + except Exception as e: + print( + f"Error during request: {e}. " + "Tool calls completed earlier in this request may have already changed the workbook. " + "Please check the workbook before repeating a write." + ) + + +if __name__ == "__main__": + workspace = Path("./workspace").resolve() + tools = create_excel_tools(workspace) + agent = BaseAgent( + model="gemini-3.5-flash-lite", + tools=tools, + system_prompt="You are an office assistant. You can inspect, read, and update Excel workbooks in the workspace.", + on_tool_call=print_tool_call, + ) + interface = ChatInterface(agent=agent) + interface.run() diff --git a/agentoffice/tools/excel/factory.py b/agentoffice/tools/excel/factory.py index be053b5..06d2535 100644 --- a/agentoffice/tools/excel/factory.py +++ b/agentoffice/tools/excel/factory.py @@ -7,9 +7,13 @@ from agentoffice.tools.excel.write import UpdateWorkbookTool -def create_excel_tools(workspace_dir: str | Path) -> list[BaseTool]: +def create_excel_tools(workspace_dir: str | Path | ExcelWorkspace) -> list[BaseTool]: """Create and return all Excel tools bound to the given workspace directory.""" - ws = ExcelWorkspace(workspace_dir) + ws = ( + workspace_dir + if isinstance(workspace_dir, ExcelWorkspace) + else ExcelWorkspace(workspace_dir) + ) return [ InspectWorkbookTool(ws), ReadRangesTool(ws), diff --git a/agentoffice/tools/excel/guards.py b/agentoffice/tools/excel/guards.py index 09ba2c8..f5a062a 100644 --- a/agentoffice/tools/excel/guards.py +++ b/agentoffice/tools/excel/guards.py @@ -1,23 +1,40 @@ from openpyxl.cell.cell import Cell +FORMULA_TRIGGERS = ("=", "+", "-", "@") + def clean_coord(coord: str) -> str: """Strip whitespace and remove absolute reference '$' markers.""" return str(coord).strip().replace("$", "") +def get_formula_trigger(value: object) -> str | None: + """Return the trigger character if value is an unescaped formula-like string, else None.""" + if not isinstance(value, str): + return None + cleaned = value.strip() + if cleaned.startswith(FORMULA_TRIGGERS): + try: + float(cleaned) + return None + except ValueError: + return cleaned[0] + return None + + def is_formula(cell: Cell) -> bool: - """Check if a cell contains a formula (starts with '=').""" + """Check if a cell contains a formula (data_type == 'f' or formula trigger string).""" if cell.data_type == "f": return True - return isinstance(cell.value, str) and cell.value.strip().startswith("=") + return get_formula_trigger(cell.value) is not None def guard_not_formula_injection(value: object, target_desc: str) -> None: - """Guard against formula injection in a cell.""" - if isinstance(value, str) and value.strip().startswith("="): + """Guard against formula injection in a cell value (CWE-1236).""" + trigger = get_formula_trigger(value) + if trigger is not None: raise PermissionError( - f"Formula injection prohibited: {target_desc} begins with '='" + f"Formula injection prohibited: {target_desc} begins with a formula trigger character ({trigger!r})" ) @@ -28,5 +45,10 @@ def guard_sheet_unprotected(sheet, error_message: str = "Sheet is protected") -> def format_limit_exceeded_error(requested_cells: int, limit: int) -> str: - """Format error message for format limit exceeded.""" - return f"Format limit exceeded: requested {requested_cells} cells, consider using smaller targeted coordinates, please consider using preview_sheet for headers and totals,paginate_table for scrolling rows." # noqa: E501 + """Format error message for format/cell limit exceeded with steering suggestions.""" + return ( + f"Cell limit exceeded: requested {requested_cells} cells, " + f"maximum allowed per request is {limit}. " + f"Please narrow your range (e.g. read specific sub-ranges or columns), " + f"or use 'inspect_workbook' to examine sheet dimensions and table structures." + ) diff --git a/agentoffice/tools/excel/inspect.py b/agentoffice/tools/excel/inspect.py index f4f106d..9825204 100644 --- a/agentoffice/tools/excel/inspect.py +++ b/agentoffice/tools/excel/inspect.py @@ -3,13 +3,23 @@ from agentoffice.core.tool import BaseTool from agentoffice.tools.excel.guards import is_formula +from agentoffice.tools.excel.slots import classify_slot, collect_named_slots from agentoffice.tools.excel.workspace import ExcelWorkspace def inspect_workbook( workspace: ExcelWorkspace, file_name: str | Path ) -> dict[str, Any]: + """Inspect workbook structure, sheet dimensions, formula locations, native tables, and named slots. + Args: + workspace: Workspace environment managing the file. + file_name: Name or relative path of the Excel workbook in the workspace. + + Returns: + A dictionary containing sheet_names, active_sheet, sheet_details, + formulas, tables, and discoverable named_slots. + """ with workspace.open_workbook(file_name) as wb: sheet_details = { ws.title: { @@ -20,7 +30,7 @@ def inspect_workbook( } for ws in wb.worksheets } - formula = [ + formulas = [ {"sheet": ws.title, "cell": cell.coordinate, "formula": cell.value} for ws in wb.worksheets for row in ws.iter_rows() @@ -32,30 +42,49 @@ def inspect_workbook( for ws in wb.worksheets for t in ws.tables.values() ] + from collections import Counter + + raw_slots = collect_named_slots(wb) + name_counts = Counter(name for name, _, _ in raw_slots) + named_slots = [ + { + "name": name, + "scope": scope, + "ref": defn.attr_text or defn.value, + "kind": (kind := classify_slot(defn)), + "settable": (kind == "cell" and name_counts[name] == 1), + } + for name, scope, defn in raw_slots + ] return { "sheet_names": list(sheet_details.keys()), - "active_sheet": wb.active.title, + "active_sheet": wb.active.title if wb.active else None, "sheet_details": sheet_details, - "formulas": formula, + "formulas": formulas, "tables": tables, + "named_slots": named_slots, } class InspectWorkbookTool(BaseTool): + """Tool adapter exposing workbook structural inspection to the agent.""" + def __init__(self, workspace: ExcelWorkspace): self.workspace = workspace super().__init__( name="inspect_workbook", description=( - "inspect workbook and return sheet names, active sheet, " - "sheet details, formulas, and tables" + "Inspect workbook structure and return sheet names, active sheet, " + "sheet details, formulas, tables, and named_slots (defined names " + "with a 'kind' and 'settable' flag; only settable=true, kind='cell' " + "names can be updated via the set_slot action of update_workbook)." ), parameters={ "type": "object", "properties": { "file_name": { "type": "string", - "description": "name of the excel workbook file in the workspace directory to inspect (e.g., 'data.xlsx')", + "description": "Name of the Excel workbook file in the workspace directory to inspect (e.g. 'data.xlsx').", } }, "required": ["file_name"], diff --git a/agentoffice/tools/excel/read.py b/agentoffice/tools/excel/read.py index f419c68..c1dcd16 100644 --- a/agentoffice/tools/excel/read.py +++ b/agentoffice/tools/excel/read.py @@ -1,12 +1,55 @@ from pathlib import Path from typing import Any +from openpyxl.utils.cell import range_boundaries +from openpyxl.worksheet.worksheet import Worksheet + from agentoffice.core.tool import BaseTool +from agentoffice.tools.excel.guards import format_limit_exceeded_error from agentoffice.tools.excel.workspace import ExcelWorkspace DEFAULT_MAX_CELLS: int = 1000 +def _resolve_sheet_and_coords( + workbook: Any, range_str: str, file_name: str | Path +) -> tuple[Worksheet, str]: + """Resolve worksheet and coordinate string from 'Sheet!A1' or 'A1'.""" + if "!" in range_str: + sheet_name, coords = range_str.rsplit("!", 1) + clean_sheet = sheet_name.strip("'").replace("''", "'") + if clean_sheet not in workbook.sheetnames: + raise KeyError(f"Sheet '{sheet_name}' not found in workbook '{file_name}'") + return workbook[clean_sheet], coords + return workbook.active, range_str + + +def _count_range_cells(ws: Worksheet, coords: str) -> int: + """Calculate total cells in coordinates.""" + min_col, min_row, max_col, max_row = range_boundaries(coords) + cols = (max_col or ws.max_column or 1) - (min_col or 1) + 1 + rows = (max_row or ws.max_row or 1) - (min_row or 1) + 1 + return max(0, cols) * max(0, rows) + + +def _extract_values_from_target(target: Any) -> list[list[Any]]: + """Extract 2D list of cell values handling Cell, 2D tuple, and 1D tuple.""" + if not isinstance(target, tuple): + return [[target.value]] + if not target: + return [] + if isinstance(target[0], tuple): + return [[cell.value for cell in row] for row in target] + if ( + len(target) > 1 + and hasattr(target[0], "column") + and hasattr(target[1], "column") + ): + if target[0].column == target[1].column: + return [[cell.value] for cell in target] + return [[cell.value for cell in target]] + + def read_ranges( workspace: ExcelWorkspace, file_name: str | Path, @@ -16,36 +59,27 @@ def read_ranges( ) -> dict[str, Any]: """Reads one or more A1 ranges from a workbook in a single atomic turn.""" - value_ranges = [] - total_cells = 0 with workspace.open_workbook(file_name, data_only=data_only) as workbook: + initial_total = sum( + _count_range_cells(*_resolve_sheet_and_coords(workbook, r, file_name)) + for r in ranges + ) + if initial_total > max_cells: + raise ValueError(format_limit_exceeded_error(initial_total, max_cells)) + + accumulated_cells = 0 + value_ranges = [] for range_str in ranges: - if "!" in range_str: - sheet_name, coords = range_str.split("!", 1) - if sheet_name not in workbook.sheetnames: - raise KeyError( - f"Sheet '{sheet_name}' not found in workbook '{file_name}'" - ) - ws = workbook[sheet_name] - else: - ws = workbook.active - coords = range_str - - target = ws[coords] - if isinstance(target, tuple): - values = [[cell.value for cell in row] for row in target] - total_cells += sum(len(row) for row in values) - else: - values = [[target.value]] - total_cells += 1 + ws, coords = _resolve_sheet_and_coords(workbook, range_str, file_name) + count = _count_range_cells(ws, coords) + if accumulated_cells + count > max_cells: + raise ValueError( + format_limit_exceeded_error(accumulated_cells + count, max_cells) + ) + accumulated_cells += count + values = _extract_values_from_target(ws[coords]) value_ranges.append({"range": range_str, "values": values}) - if total_cells > max_cells: - raise ValueError( - f"Requested ranges contain {total_cells} cells, exceeding " - f"the safety ceiling of {max_cells}." - ) - return {"file_name": str(file_name), "ranges": value_ranges} diff --git a/agentoffice/tools/excel/slots.py b/agentoffice/tools/excel/slots.py new file mode 100644 index 0000000..fdf0078 --- /dev/null +++ b/agentoffice/tools/excel/slots.py @@ -0,0 +1,133 @@ +"""Named-slot domain helpers shared by the inspect and write tools.""" + +import re + +from openpyxl.formula.tokenizer import Tokenizer +from openpyxl.utils.cell import range_boundaries +from openpyxl.workbook.defined_name import DefinedName + +from agentoffice.tools.excel.guards import clean_coord + +CELL_OR_RANGE_RE = re.compile( + r"^=?" + r"(?:'(?:[^']|'')*'|[^'!\s]+)!" # Sheet + r"(?:" + r"\$?[A-Za-z]{1,3}\$?[1-9]\d*(?::\$?[A-Za-z]{1,3}\$?[1-9]\d*)?" # Cell or 2-cell range + r"|" + r"\$?[A-Za-z]{1,3}:\$?[A-Za-z]{1,3}" # Col range + r"|" + r"\$?[1-9]\d*:\$?[1-9]\d*" # Row range + r")$" + r"|" + r"^=?" + r"(?:" + r"\$?[A-Za-z]{1,3}\$?[1-9]\d*(?::\$?[A-Za-z]{1,3}\$?[1-9]\d*)?" + r"|" + r"\$?[A-Za-z]{1,3}:\$?[A-Za-z]{1,3}" + r"|" + r"\$?[1-9]\d*:\$?[1-9]\d*" + r")$" +) + + +def is_direct_grid_reference(defn: DefinedName) -> bool: + """Return True if defn is a direct single grid reference, not an expression or formula.""" + raw = (defn.attr_text or defn.value or "").strip() + if not raw: + return False + try: + tok = Tokenizer("=" + raw.lstrip("=")) + if len(tok.items) != 1 or tok.items[0].subtype != "RANGE": + return False + return bool(CELL_OR_RANGE_RE.match(raw)) + except Exception: + return False + + +def collect_named_slots(workbook) -> list[tuple[str, str, DefinedName]]: + """Collect user-defined named slots from every scope. + + Returns (name, scope, defn) tuples covering both workbook-global + names (scope='workbook') and sheet-scoped names (scope=sheet + title). Excel-internal names ('_xlnm.*', e.g. Print_Area) and + hidden names are excluded so tool output stays LLM-readable. + """ + slots: list[tuple[str, str, DefinedName]] = [] + for name, defn in workbook.defined_names.items(): + if name.startswith("_xlnm.") or defn.hidden: + continue + slots.append((name, "workbook", defn)) + for ws in workbook.worksheets: + for name, defn in ws.defined_names.items(): + if name.startswith("_xlnm.") or defn.hidden: + continue + slots.append((name, ws.title, defn)) + return slots + + +def classify_slot(defn: DefinedName) -> str: + """Classify a defined name by what set_slot could do with it. + + Returns one of: + 'cell' - single-cell grid reference (set_slot-able) + 'range' - multi-cell or whole-column/row reference + 'constant' - literal value, not a grid reference + 'formula' - formula definition, not a grid reference + 'multi' - resolves to more than one destination + """ + raw = (defn.attr_text or defn.value or "").strip() + if not raw: + return "constant" + + try: + tok = Tokenizer("=" + raw.lstrip("=")) + except Exception: + return "formula" + + items = tok.items + if not items: + return "constant" + + # Single-token operand + if len(items) == 1: + item = items[0] + if item.subtype == "RANGE" and CELL_OR_RANGE_RE.match(raw): + try: + dests = list(defn.destinations) + if dests: + min_col, min_row, max_col, max_row = range_boundaries( + clean_coord(dests[0][1]) + ) + if ( + None not in (min_col, min_row, max_col, max_row) + and min_col == max_col + and min_row == max_row + ): + return "cell" + except Exception: + pass + return "range" + + if item.subtype == "RANGE": + return "formula" if raw.startswith("=") else "range" + return "constant" + + # Multi-token: check if it is a pure comma-separated union of direct grid references + # e.g. [RANGE, ',', RANGE] like Summary!$A$1,Summary!$B$2 + is_union = True + range_count = 0 + for i, it in enumerate(items): + if i % 2 == 0: + if it.subtype != "RANGE" or not CELL_OR_RANGE_RE.match(it.value): + is_union = False + break + range_count += 1 + else: + if it.value != ",": + is_union = False + break + + if is_union and range_count > 1: + return "multi" + + return "formula" diff --git a/agentoffice/tools/excel/workspace.py b/agentoffice/tools/excel/workspace.py index 05aab74..d2ba3c5 100644 --- a/agentoffice/tools/excel/workspace.py +++ b/agentoffice/tools/excel/workspace.py @@ -7,7 +7,7 @@ class ExcelWorkspace: def __init__(self, workspace_dir: str | Path): - self.workspace_dir = Path(workspace_dir) + self.workspace_dir = Path(workspace_dir).resolve() self.workspace_dir.mkdir(parents=True, exist_ok=True) def resolve_path(self, path: str | Path, must_exist: bool = True) -> Path: diff --git a/agentoffice/tools/excel/write.py b/agentoffice/tools/excel/write.py index dc05d73..20d892d 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -1,5 +1,6 @@ import os import tempfile +from difflib import get_close_matches from pathlib import Path from typing import Any @@ -14,6 +15,10 @@ guard_sheet_unprotected, is_formula, ) +from agentoffice.tools.excel.slots import ( + collect_named_slots, + is_direct_grid_reference, +) from agentoffice.tools.excel.workspace import ExcelWorkspace @@ -32,6 +37,9 @@ def track(self, sheet: str, cell_coord: str, error_message: str) -> None: class SetCellHandler: + REQUIRED_KEYS = frozenset({"cell", "value"}) + OPTIONAL_KEYS = frozenset({"sheet"}) + @staticmethod def validate( wb: openpyxl.Workbook, @@ -39,9 +47,6 @@ def validate( tracker: ConflictTracker, ) -> dict[str, Any]: - if "cell" not in operation or "value" not in operation: - raise ValueError("Operation must contain 'cell' and 'value' keys") - value = operation["value"] guard_not_formula_injection(value, f"Value at cell {operation['cell']}") @@ -84,7 +89,105 @@ def verify(verify_wb: openpyxl.Workbook, validated: dict[str, Any]) -> None: ) +class SetSlotHandler: + REQUIRED_KEYS = frozenset({"name", "value"}) + OPTIONAL_KEYS = frozenset() + + @staticmethod + def validate( + wb: openpyxl.Workbook, + operation: dict[str, Any], + tracker: ConflictTracker, + ) -> dict[str, Any]: + name = operation["name"] + value = operation["value"] + + # Index slots across all scopes + by_name: dict[str, list[tuple[str, Any]]] = {} + for slot_name, scope, defn in collect_named_slots(wb): + by_name.setdefault(slot_name, []).append((scope, defn)) + + matches = by_name.get(str(name)) + if not matches: + available = sorted(by_name, key=str) + close = get_close_matches(str(name), available, n=1) + suggestion = f" Did you mean '{close[0]}'?" if close else "" + raise KeyError( + f"Named slot '{name}' not found.{suggestion} " + f"Available slots: {available}" + ) + if len(matches) > 1: + scopes = sorted(scope for scope, _ in matches) + raise ValueError( + f"Named slot '{name}' is ambiguous (defined at scopes {scopes})." + ) + defn = matches[0][1] + + if not is_direct_grid_reference(defn): + ref_desc = defn.attr_text or defn.value or "" + raise ValueError( + f"Named slot '{name}' does not resolve to a worksheet grid cell " + f"(defined as constant/formula: '{ref_desc}'). Slot updates only apply to grid-backed cells." + ) + + try: + dests = list(defn.destinations) + except Exception: + # Non-grid expressions crash openpyxl's tokenizer + dests = [] + + if not dests: + ref_desc = defn.attr_text or defn.value or "" + raise ValueError( + f"Named slot '{name}' does not resolve to a worksheet grid cell " + f"(defined as constant/formula: '{ref_desc}'). Slot updates only apply to grid-backed cells." + ) + if len(dests) > 1: + raise ValueError(f"Named slot '{name}' points to multiple destinations.") + + sheet_title, cell_coord = dests[0] + sheet_name = ( + sheet_title.strip("'").replace("''", "'") if sheet_title else None + ) or (wb.active.title if wb.active else None) + if not sheet_name: + raise ValueError( + f"Named slot '{name}' destination worksheet could not be determined." + ) + + clean_c = clean_coord(cell_coord) + try: + min_col, min_row, max_col, max_row = range_boundaries(clean_c) + except (ValueError, TypeError): + raise ValueError(f"Named slot '{name}' coordinate '{clean_c}' is invalid.") + is_single_cell = ( + None not in (min_col, min_row, max_col, max_row) + and min_col == max_col + and min_row == max_row + ) + if not is_single_cell: + raise ValueError( + f"Named slot '{name}' spans multiple cells ({clean_c}); " + f"scalar slot updates require a single cell." + ) + + # Normalize accepted single-cell range (e.g. 'B2:B2' -> 'B2') to a single coordinate + single_cell_coord = f"{get_column_letter(min_col)}{min_row}" + + # Delegate to SetCellHandler for protection, collision tracking, formula checks + return SetCellHandler.validate( + wb, + {"sheet": sheet_name, "cell": single_cell_coord, "value": value}, + tracker, + ) + + apply = SetCellHandler.apply + verify = SetCellHandler.verify + + class AppendTableHandler: + REQUIRED_KEYS = frozenset({"table", "rows"}) + OPTIONAL_KEYS = frozenset() + @staticmethod def validate( wb: openpyxl.Workbook, @@ -92,8 +195,16 @@ def validate( tracker: ConflictTracker, ) -> dict[str, Any]: - t_name = operation.get("table") - rows = operation.get("rows", []) + t_name = operation["table"] + rows = operation["rows"] + if not isinstance(rows, list): + raise ValueError( + f"append_table 'rows' must be a list, got {type(rows).__name__}." + ) + if not rows: + raise ValueError( + "append_table 'rows' must be a non-empty list of row values." + ) # 1. Find the table's sheet ws = next((s for s in wb.worksheets if t_name in s.tables), None) @@ -111,18 +222,26 @@ def validate( headers = [ ws.cell(row=min_row, column=c).value for c in range(min_col, max_col + 1) ] + header_str_set = {str(h) for h in headers if h is not None} # 3. Validate row shapes, normalize to header order, & check values normalized_rows = [] for row in rows: if isinstance(row, dict): - unknown = set(row) - set(headers) + if not row: + raise ValueError( + f"Table '{t_name}' row dictionary cannot be empty." + ) + str_row = {str(k): v for k, v in row.items()} + unknown = [k for k in row if str(k) not in header_str_set] if unknown: raise ValueError( - f"Table '{t_name}' has no column(s) {sorted(unknown)}. " + f"Table '{t_name}' has no column(s) {sorted(unknown, key=str)}. " f"Expected columns: {headers}" ) - row_vals = [row.get(h) for h in headers] + row_vals = [ + row[h] if h in row else str_row.get(str(h)) for h in headers + ] elif isinstance(row, (list, tuple)): if len(row) != expected_cols: raise ValueError( @@ -235,43 +354,113 @@ def verify(verify_wb: openpyxl.Workbook, validated: dict[str, Any]) -> None: OPERATION_HANDLERS = { "set_cell": SetCellHandler, "append_table": AppendTableHandler, - "append_rows": AppendTableHandler, + "set_slot": SetSlotHandler, } -def update_workbook( +def _resolve_dest_path( workspace: ExcelWorkspace, file_name: str | Path, - operations: list[dict[str, Any]] | None = None, - output_filename: str | Path | None = None, - overwrite: bool = False, - mutations: list[dict[str, Any]] | None = None, -) -> dict[str, Any]: - """Applies an atomic batch of ordered operations to an Excel workbook.""" + output_filename: str | Path | None, + overwrite: bool, +) -> tuple[Path, Path, str]: + """Resolves source and destination paths, validating the overwrite policy.""" src_path = workspace.resolve_path(file_name, must_exist=True) - # Determine destination path if output_filename and str(output_filename) != str(file_name): dest_path = workspace.resolve_path(output_filename, must_exist=False) if dest_path.exists() and not overwrite: raise FileExistsError( f"Destination file '{output_filename}' already exists and overwrite=False." ) - is_inplace = False + output_name = str(output_filename) else: dest_path = src_path - is_inplace = True + output_name = str(file_name) + + return src_path, dest_path, output_name + + +def _validate_operation_envelope( + op: dict[str, Any], + handler: Any, + action: str, +) -> None: + """Validates that required keys are present and no unknown keys were passed.""" + keys = op.keys() - {"action"} + unknown = keys - handler.REQUIRED_KEYS - handler.OPTIONAL_KEYS + if unknown: + allowed = sorted(handler.REQUIRED_KEYS | handler.OPTIONAL_KEYS) + hints = [] + for bad in sorted(unknown, key=str): + str_bad = str(bad) + close = get_close_matches(str_bad, allowed, n=1) + hints.append( + f"'{str_bad}'" + (f" (did you mean '{close[0]}'?)" if close else "") + ) + raise ValueError( + f"Unknown key(s) {', '.join(hints)} for '{action}'. Allowed keys: {allowed}" + ) + + missing = handler.REQUIRED_KEYS - keys + if missing: + raise ValueError( + f"'{action}' requires key(s) {sorted(handler.REQUIRED_KEYS)}, " + f"missing: {sorted(missing)}" + ) + + +def _atomic_commit( + wb: openpyxl.Workbook, + dest_path: Path, + validated_ops: list[tuple[Any, dict[str, Any]]], + keep_vba: bool, +) -> None: + """Saves workbook to a temp file, verifies on disk, and atomically replaces dest_path.""" + tmp_fd, tmp_path_str = tempfile.mkstemp( + dir=dest_path.parent, prefix=".tmp_", suffix=dest_path.suffix + ) + os.close(tmp_fd) + tmp_path = Path(tmp_path_str) + + try: + wb.save(tmp_path) + + verify_wb = openpyxl.load_workbook(tmp_path, keep_vba=keep_vba, data_only=False) + try: + for handler, validated in validated_ops: + handler.verify(verify_wb, validated) + finally: + verify_wb.close() + + os.replace(tmp_path, dest_path) + except Exception: + if tmp_path.exists(): + tmp_path.unlink() + raise + + +def update_workbook( + workspace: ExcelWorkspace, + file_name: str | Path, + operations: list[dict[str, Any]] | None = None, + output_filename: str | Path | None = None, + overwrite: bool = False, +) -> dict[str, Any]: + """Applies an atomic batch of ordered operations to an Excel workbook.""" + src_path, dest_path, out_name = _resolve_dest_path( + workspace, file_name, output_filename, overwrite + ) - ops = operations if operations is not None else (mutations or []) + ops = operations or [] if not ops: raise ValueError("No operations provided.") keep_vba = src_path.suffix.lower() in (".xlsm", ".xltm") wb = openpyxl.load_workbook(src_path, keep_vba=keep_vba, data_only=False) - tmp_path: Path | None = None try: - # 1. Preflight validation + # 1. validation tracker = ConflictTracker() validated_ops: list[tuple[Any, dict[str, Any]]] = [] @@ -282,43 +471,22 @@ def update_workbook( f"Unsupported operation action: '{action}'. Supported actions: {list(OPERATION_HANDLERS.keys())}" ) handler = OPERATION_HANDLERS[action] - validated = handler.validate(wb, op, tracker) - validated_ops.append((handler, validated)) + _validate_operation_envelope(op, handler, action) + validated_ops.append((handler, handler.validate(wb, op, tracker))) # 2. In-memory application for handler, validated in validated_ops: handler.apply(wb, validated) # 3. Atomic temporary write - tmp_fd, tmp_path_str = tempfile.mkstemp( - dir=dest_path.parent, prefix=".tmp_", suffix=dest_path.suffix - ) - os.close(tmp_fd) - tmp_path = Path(tmp_path_str) - - wb.save(tmp_path) + _atomic_commit(wb, dest_path, validated_ops, keep_vba) finally: wb.close() - # 4. Post-save verification & 5. Atomic swap - try: - verify_wb = openpyxl.load_workbook(tmp_path, keep_vba=keep_vba, data_only=False) - try: - for handler, validated in validated_ops: - handler.verify(verify_wb, validated) - finally: - verify_wb.close() - - os.replace(tmp_path, dest_path) - except Exception: - if tmp_path and tmp_path.exists(): - tmp_path.unlink() - raise - return { "status": "success", "file_name": str(file_name), - "output_file": str(dest_path.name if is_inplace else output_filename), + "output_file": out_name, "operations_applied": len(validated_ops), } @@ -331,6 +499,9 @@ def __init__(self, workspace: ExcelWorkspace): description=( "Apply an atomic batch of ordered operations to an Excel workbook. " "Supported actions: 'set_cell' (keys: sheet, cell, value), " + "'set_slot' (keys: name, value; updates a single-cell defined " + "name — discover available names via inspect_workbook's " + "named_slots), " "'append_table' (keys: table, rows; each row is a dict keyed by the " "table's column names, e.g. {'Item': 'Mouse', 'Price': 50}, preferred, " "or a list of scalar values in column order). " @@ -350,7 +521,21 @@ def __init__(self, workspace: ExcelWorkspace): }, "operations": { "type": "array", - "items": {"type": "object"}, + "items": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": [ + "set_cell", + "set_slot", + "append_table", + ], + "description": "The operation action: 'set_cell', 'set_slot', or 'append_table'.", + }, + }, + "required": ["action"], + }, "description": "List of operations to apply.", }, "overwrite": { @@ -369,14 +554,13 @@ def execute( operations: list[dict[str, Any]] | None = None, output_filename: str | None = None, overwrite: bool = False, - **kwargs: Any, ) -> dict[str, Any]: if not file_name: return { "status": "error", "error": "ValueError: Parameter 'file_name' is required.", } - ops = operations or kwargs.get("mutations") + ops = operations if not ops: return { "status": "error", diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..1875583 --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,164 @@ +import json +import unittest +from unittest.mock import MagicMock + +from agentoffice.core.agent import BaseAgent +from agentoffice.core.tool import BaseTool + + +class DummyTool(BaseTool): + def __init__(self): + super().__init__( + name="dummy_tool", + description="A dummy test tool.", + parameters={ + "type": "object", + "properties": {"query": {"type": "string"}}, + "required": ["query"], + }, + ) + + def execute(self, query: str = ""): + if query == "fail": + raise ValueError("Intentional tool failure") + return {"result": f"processed: {query}"} + + +class TestBaseAgent(unittest.TestCase): + def setUp(self): + self.mock_client = MagicMock() + self.tool = DummyTool() + self.agent = BaseAgent( + model="test-model", + system_prompt="Test system prompt", + tools=[self.tool], + client=self.mock_client, + ) + + def test_agent_initialization(self): + self.assertEqual(self.agent.model, "test-model") + self.assertEqual(self.agent.system_prompt, "Test system prompt") + self.assertIn("dummy_tool", self.agent.tool_map) + self.assertEqual(len(self.agent.history), 1) + self.assertEqual(self.agent.history[0]["role"], "system") + + def test_agent_initialization_with_history(self): + initial_history = [ + {"role": "user", "content": "hello"}, + {"role": "assistant", "content": "hi"}, + ] + agent = BaseAgent( + model="test-model", + history=initial_history, + client=self.mock_client, + ) + self.assertEqual(len(agent.history), 2) + self.assertEqual(agent.history[0]["content"], "hello") + + def test_execute_tool_success(self): + result_str = self.agent.execute_tool("dummy_tool", json.dumps({"query": "abc"})) + result = json.loads(result_str) + self.assertEqual(result, {"result": "processed: abc"}) + + def test_execute_tool_not_found(self): + result_str = self.agent.execute_tool("unknown_tool", "{}") + result = json.loads(result_str) + self.assertIn("error", result) + self.assertIn("not found", result["error"]) + + def test_execute_tool_handles_exception(self): + result_str = self.agent.execute_tool( + "dummy_tool", json.dumps({"query": "fail"}) + ) + result = json.loads(result_str) + self.assertIn("error", result) + self.assertIn("Intentional tool failure", result["error"]) + + def test_run_single_turn_reply(self): + mock_msg = MagicMock() + mock_msg.content = "Here is the answer." + mock_msg.tool_calls = None + mock_choice = MagicMock() + mock_choice.message = mock_msg + + mock_resp = MagicMock() + mock_resp.choices = [mock_choice] + mock_resp.usage = None + self.mock_client.chat.completions.create.return_value = mock_resp + + reply = self.agent.run("What is 2+2?") + self.assertEqual(reply, "Here is the answer.") + self.assertEqual(self.agent.history[-1]["role"], "assistant") + self.assertEqual(self.agent.history[-1]["content"], "Here is the answer.") + + def test_run_tool_call_loop(self): + # First turn: model requests dummy_tool + tc = MagicMock() + tc.id = "call_123" + tc.function.name = "dummy_tool" + tc.function.arguments = json.dumps({"query": "data"}) + mock_msg_1 = MagicMock() + mock_msg_1.content = None + mock_msg_1.tool_calls = [tc] + mock_choice_1 = MagicMock(message=mock_msg_1) + mock_resp_1 = MagicMock(choices=[mock_choice_1], usage=None) + + # Second turn: model replies with final answer + mock_msg_2 = MagicMock() + mock_msg_2.content = "Done with data." + mock_msg_2.tool_calls = None + mock_choice_2 = MagicMock(message=mock_msg_2) + mock_resp_2 = MagicMock(choices=[mock_choice_2], usage=None) + + self.mock_client.chat.completions.create.side_effect = [ + mock_resp_1, + mock_resp_2, + ] + + callback_calls = [] + + def callback(name, args, res): + callback_calls.append((name, args, res)) + + self.agent.on_tool_call = callback + reply = self.agent.run("Process data") + self.assertEqual(reply, "Done with data.") + self.assertEqual(len(callback_calls), 1) + self.assertEqual(callback_calls[0][0], "dummy_tool") + + def test_run_callback_exception_does_not_break_execution(self): + tc = MagicMock() + tc.id = "call_123" + tc.function.name = "dummy_tool" + tc.function.arguments = json.dumps({"query": "data"}) + mock_msg_1 = MagicMock(content=None, tool_calls=[tc]) + mock_resp_1 = MagicMock(choices=[MagicMock(message=mock_msg_1)], usage=None) + + mock_msg_2 = MagicMock(content="Finished smoothly.", tool_calls=None) + mock_resp_2 = MagicMock(choices=[MagicMock(message=mock_msg_2)], usage=None) + + self.mock_client.chat.completions.create.side_effect = [ + mock_resp_1, + mock_resp_2, + ] + + def crashing_callback(name, args, res): + raise BrokenPipeError("Stdout broken") + + self.agent.on_tool_call = crashing_callback + reply = self.agent.run("Process data safely") + self.assertEqual(reply, "Finished smoothly.") + + def test_run_failure_removes_unanswered_user_message(self): + self.mock_client.chat.completions.create.side_effect = RuntimeError( + "API unavailable" + ) + initial_history_len = len(self.agent.history) + + with self.assertRaises(RuntimeError): + self.agent.run("Tell me a secret") + + # The unanswered user message must be removed so consecutive user messages don't occur + self.assertEqual(len(self.agent.history), initial_history_len) + if initial_history_len > 0: + self.assertEqual(self.agent.history[-1]["role"], "system") diff --git a/tests/test_excel_guards.py b/tests/test_excel_guards.py new file mode 100644 index 0000000..f26a6ce --- /dev/null +++ b/tests/test_excel_guards.py @@ -0,0 +1,78 @@ +import unittest +from unittest.mock import MagicMock + +from openpyxl.cell.cell import Cell + +from agentoffice.tools.excel.guards import ( + format_limit_exceeded_error, + guard_not_formula_injection, + is_formula, +) + + +class TestExcelGuards(unittest.TestCase): + def test_guard_formula_injection_blocks_trigger_prefixes(self): + malicious_inputs = [ + "=SUM(A1:A10)", + "+cmd|' /C calc'!A0", + "-1+1", + "@HYPERLINK('http://attacker.com')", + "\t=1+1", + "\r-2+2", + "\n@calc", + ] + for val in malicious_inputs: + with self.subTest(val=val): + with self.assertRaises(PermissionError) as ctx: + guard_not_formula_injection(val, "Test cell") + self.assertIn("Formula injection prohibited", str(ctx.exception)) + + def test_guard_formula_injection_allows_numeric_strings_and_scalars(self): + safe_inputs = [ + "-50000", + "+12.5", + "-.15", + "+0", + "-0.0", + -42, + 3.14159, + 0, + True, + False, + None, + "Normal text", + "Revenue (Q3)", + ] + for val in safe_inputs: + with self.subTest(val=val): + # Should not raise + guard_not_formula_injection(val, "Test cell") + + def test_is_formula_detection(self): + # Explicit formula data type + mock_f_cell = MagicMock(spec=Cell) + mock_f_cell.data_type = "f" + mock_f_cell.value = "100" + self.assertTrue(is_formula(mock_f_cell)) + + # Formula string representations + for expr in ["=SUM(A1)", "+A1+B1", "-1+1", "@FUNC()"]: + cell = MagicMock(spec=Cell) + cell.data_type = "s" + cell.value = expr + self.assertTrue(is_formula(cell)) + + # Safe numbers and text + for safe in ["-500", "+3.14", "Normal text", 100, None]: + cell = MagicMock(spec=Cell) + cell.data_type = "n" if isinstance(safe, (int, float)) else "s" + cell.value = safe + self.assertFalse(is_formula(cell)) + + def test_format_limit_exceeded_error_steering(self): + msg = format_limit_exceeded_error(requested_cells=5000, limit=1000) + self.assertIn("requested 5000 cells", msg) + self.assertIn("maximum allowed per request is 1000", msg) + self.assertIn("inspect_workbook", msg) + self.assertNotIn("preview_sheet", msg) + self.assertNotIn("paginate_table", msg) diff --git a/tests/test_excel_inspect.py b/tests/test_excel_inspect.py index da31abe..e424c73 100644 --- a/tests/test_excel_inspect.py +++ b/tests/test_excel_inspect.py @@ -3,9 +3,11 @@ from pathlib import Path import openpyxl +from openpyxl.workbook.defined_name import DefinedName from openpyxl.worksheet.table import Table from agentoffice.tools.excel.inspect import InspectWorkbookTool, inspect_workbook +from agentoffice.tools.excel.slots import classify_slot, collect_named_slots from agentoffice.tools.excel.workspace import ExcelWorkspace @@ -37,6 +39,15 @@ def setUp(self): tab = Table(displayName="OrdersTable", ref="A1:B2") ws2.add_table(tab) + # Named slots: settable single-cell names plus non-settable shapes + wb.defined_names.add(DefinedName("TaxRate", attr_text="Summary!$C$1")) + ws2.defined_names.add(DefinedName("LocalNote", attr_text="Orders!$C$1")) + wb.defined_names.add(DefinedName("Quarterly", attr_text="Summary!$A$1:$B$2")) + wb.defined_names.add(DefinedName("Commission", attr_text="0.05")) + wb.defined_names.add( + DefinedName("Computed", attr_text="=SUM(Summary!$B$1:$B$2)") + ) + wb.save(self.wb_path) wb.close() @@ -52,6 +63,79 @@ def test_inspect_workbook_finds_sheets_formulas_and_tables(self): self.assertEqual(result["formulas"][0]["formula"], "=B1*0.2") self.assertEqual(result["tables"][0]["name"], "OrdersTable") + def test_inspect_reports_named_slots_across_scopes(self): + result = inspect_workbook(self.workspace, "test_data.xlsx") + slots = {s["name"]: s for s in result["named_slots"]} + self.assertEqual(slots["TaxRate"]["scope"], "workbook") + self.assertEqual(slots["TaxRate"]["ref"], "Summary!$C$1") + self.assertEqual(slots["LocalNote"]["scope"], "Orders") + + def test_inspect_classifies_slot_settability(self): + result = inspect_workbook(self.workspace, "test_data.xlsx") + slots = {s["name"]: s for s in result["named_slots"]} + self.assertTrue(slots["TaxRate"]["settable"]) + self.assertEqual(slots["TaxRate"]["kind"], "cell") + self.assertEqual(slots["Quarterly"]["kind"], "range") + self.assertFalse(slots["Quarterly"]["settable"]) + self.assertEqual(slots["Commission"]["kind"], "constant") + self.assertFalse(slots["Commission"]["settable"]) + self.assertEqual(slots["Computed"]["kind"], "formula") + self.assertFalse(slots["Computed"]["settable"]) + + def test_classify_slot_multi_destination(self): + defn = DefinedName("TwoCells", attr_text="Summary!$A$1,Summary!$B$2") + self.assertEqual(classify_slot(defn), "multi") + + def test_classify_slot_handles_formula_expressions_and_broken_refs(self): + expr_defn = DefinedName("Expr", attr_text="Summary!$A$1+$B$1") + self.assertEqual(classify_slot(expr_defn), "formula") + + computed_defn = DefinedName("Computed", attr_text="Config!$B$2*2") + self.assertEqual(classify_slot(computed_defn), "formula") + + ref_defn = DefinedName("Broken", attr_text="#REF!") + self.assertEqual(classify_slot(ref_defn), "constant") + + bad_defn = DefinedName("BadCoord", attr_text="Summary!NOT_A_VALID_RANGE") + self.assertEqual(classify_slot(bad_defn), "range") + + indirect_defn = DefinedName("Indirect", attr_text="Config!B2_Input") + self.assertEqual(classify_slot(indirect_defn), "range") + + sum_no_equal = DefinedName("SumExpr", attr_text="SUM(Config!$B$2)") + self.assertEqual(classify_slot(sum_no_equal), "formula") + + add_expr = DefinedName("AddExpr", attr_text="Config!$B$2+Config!$C$2") + self.assertEqual(classify_slot(add_expr), "formula") + + def test_inspect_marks_ambiguous_slots_non_settable(self): + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + wb.defined_names.add(DefinedName("Rate", attr_text="Config!$B$2")) + ws.defined_names.add(DefinedName("Rate", attr_text="Config!$B$3")) + wb.save(self.workspace_path / "ambig.xlsx") + wb.close() + + result = inspect_workbook(self.workspace, "ambig.xlsx") + rate_slots = [s for s in result["named_slots"] if s["name"] == "Rate"] + self.assertEqual(len(rate_slots), 2) + for s in rate_slots: + self.assertEqual(s["kind"], "cell") + self.assertFalse(s["settable"]) + + def test_collect_named_slots_filters_internal_and_hidden(self): + wb = openpyxl.Workbook() + wb.defined_names.add(DefinedName("TaxRate", attr_text="Summary!$B$2")) + wb.defined_names.add( + DefinedName("_xlnm.Print_Area", attr_text="Summary!$A$1:$B$2") + ) + wb.defined_names.add( + DefinedName("Secret", attr_text="Summary!$B$5", hidden=True) + ) + names = [name for name, _, _ in collect_named_slots(wb)] + self.assertEqual(names, ["TaxRate"]) + def test_inspect_tool_execution(self): tool = InspectWorkbookTool(workspace=self.workspace) result = tool.execute("test_data.xlsx") diff --git a/tests/test_excel_read.py b/tests/test_excel_read.py index 98b529c..fe9b71e 100644 --- a/tests/test_excel_read.py +++ b/tests/test_excel_read.py @@ -46,6 +46,13 @@ def test_read_ranges_single_sheet(self): result["ranges"][0]["values"], [["Revenue", 1000], ["Tax", "=B1*0.2"]] ) + def test_read_ranges_quoted_sheet_name(self): + result = read_ranges(self.workspace, "test_data.xlsx", ["'Summary'!A1:B2"]) + self.assertEqual(len(result["ranges"]), 1) + self.assertEqual( + result["ranges"][0]["values"], [["Revenue", 1000], ["Tax", "=B1*0.2"]] + ) + def test_read_ranges_multi_sheet(self): result = read_ranges( self.workspace, "test_data.xlsx", ["Summary!A1:B2", "Orders!A1:B1"] @@ -75,4 +82,67 @@ def test_read_ranges_tool_max_cells_limit(self): result = tool.execute("test_data.xlsx", ["A1:B100000"]) self.assertIn("error", result) self.assertIn("ValueError", result["error"]) - self.assertIn("exceeding the safety ceiling", result["error"]) + self.assertIn("Cell limit exceeded", result["error"]) + self.assertIn("inspect_workbook", result["error"]) + + def test_read_ranges_giant_range_rejected_without_allocating_cells(self): + import time + + start_time = time.perf_counter() + with self.assertRaises(ValueError) as ctx: + read_ranges(self.workspace, "test_data.xlsx", ["A1:XFD1048576"]) + elapsed = time.perf_counter() - start_time + + # Cell limit check should fail in less than 50ms without allocating 17B cells + self.assertLess(elapsed, 0.05) + self.assertIn("Cell limit exceeded", str(ctx.exception)) + self.assertIn("inspect_workbook", str(ctx.exception)) + + def test_read_ranges_unbounded_columns_and_rows(self): + # A:B bounded by max_row (which is 2 in Summary sheet); openpyxl column slice yields columns + result_cols = read_ranges(self.workspace, "test_data.xlsx", ["Summary!A:B"]) + self.assertEqual(len(result_cols["ranges"]), 1) + self.assertEqual( + result_cols["ranges"][0]["values"], + [["Revenue", "Tax"], [1000, "=B1*0.2"]], + ) + + # 1:2 bounded by max_column (which is 2 in Summary sheet); row slice yields rows + result_rows = read_ranges(self.workspace, "test_data.xlsx", ["Summary!1:2"]) + self.assertEqual(len(result_rows["ranges"]), 1) + self.assertEqual( + result_rows["ranges"][0]["values"], + [["Revenue", 1000], ["Tax", "=B1*0.2"]], + ) + + def test_read_ranges_cumulative_cell_limit_exceeded_on_dimension_change(self): + # A100 is 1 cell, A:Z on a 2x2 sheet initially looks like 52 cells. + # But reading A100 causes max_row to expand to 100, making A:Z require 2,600 cells. + with self.assertRaises(ValueError) as ctx: + read_ranges( + self.workspace, + "test_data.xlsx", + ["Summary!A100", "Summary!A:Z"], + max_cells=200, + ) + self.assertIn("Cell limit exceeded", str(ctx.exception)) + + def test_read_ranges_escaped_apostrophe_sheet_name(self): + wb = openpyxl.load_workbook(self.wb_path) + ws = wb.create_sheet(title="O'Brien") + ws["A1"] = "Found" + wb.save(self.wb_path) + wb.close() + + result = read_ranges(self.workspace, "test_data.xlsx", ["'O''Brien'!A1"]) + self.assertEqual(result["ranges"][0]["values"], [["Found"]]) + + def test_read_ranges_sheet_title_containing_exclamation_mark(self): + wb = openpyxl.load_workbook(self.wb_path) + ws = wb.create_sheet(title="Data!2024") + ws["A1"] = "Exclamation" + wb.save(self.wb_path) + wb.close() + + result = read_ranges(self.workspace, "test_data.xlsx", ["'Data!2024'!A1"]) + self.assertEqual(result["ranges"][0]["values"], [["Exclamation"]]) diff --git a/tests/test_excel_write.py b/tests/test_excel_write.py index d4f9716..14867c8 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -4,10 +4,12 @@ from unittest.mock import patch import openpyxl +from openpyxl.workbook.defined_name import DefinedName from openpyxl.worksheet.table import Table from agentoffice.tools.excel.workspace import ExcelWorkspace from agentoffice.tools.excel.write import ( + OPERATION_HANDLERS, AppendTableHandler, SetCellHandler, UpdateWorkbookTool, @@ -274,6 +276,27 @@ def test_disk_verification_failure_handling(self): tmp_files = list(self.workspace_path.glob(".tmp_*")) self.assertEqual(tmp_files, []) + def test_save_failure_cleans_up_temp_file(self): + # Simulate a crash during wb.save (e.g. disk full or serialization crash) + with patch.object(openpyxl.Workbook, "save", side_effect=OSError("Disk full")): + with self.assertRaises(OSError): + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[ + { + "action": "set_cell", + "sheet": "Summary", + "cell": "B1", + "value": 9999, + } + ], + ) + + # Confirm temporary files were cleaned up + tmp_files = list(self.workspace_path.glob(".tmp_*")) + self.assertEqual(tmp_files, []) + def test_update_workbook_tool_execution(self): tool = UpdateWorkbookTool(workspace=self.workspace) result = tool.execute( @@ -433,3 +456,458 @@ def test_formulas_survive_successful_update(self): with self.workspace.open_workbook("roundtrip.xlsx") as wb: self.assertEqual(wb["Summary"]["B2"].value, "=B1*0.2") self.assertEqual(wb["Orders"]["A3"].value, "Mouse") + + def test_canonical_operation_names(self): + self.assertIn("set_cell", OPERATION_HANDLERS) + self.assertIn("append_table", OPERATION_HANDLERS) + self.assertNotIn("append_rows", OPERATION_HANDLERS) + + def test_unknown_action_rejected_with_supported_list(self): + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[{"action": "delete_sheet", "sheet": "Summary"}], + ) + self.assertIn("Unsupported operation action", str(ctx.exception)) + self.assertIn("set_cell", str(ctx.exception)) + self.assertIn("append_table", str(ctx.exception)) + + def test_missing_required_key_rejected(self): + # Regression: a missing 'rows' key previously defaulted to [] and the + # batch silently succeeded as a no-op. + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[{"action": "append_table", "table": "OrdersTable"}], + ) + self.assertIn("missing: ['rows']", str(ctx.exception)) + + def test_typo_key_rejected_with_suggestion(self): + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[ + { + "action": "append_table", + "table": "OrdersTable", + "row": [["Mouse", 50]], + } + ], + ) + self.assertIn("did you mean 'rows'", str(ctx.exception)) + + def test_empty_rows_rejected(self): + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[ + {"action": "append_table", "table": "OrdersTable", "rows": []} + ], + ) + self.assertIn("non-empty", str(ctx.exception)) + + def test_table_append_empty_dict_row_rejected(self): + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[ + { + "action": "append_table", + "table": "OrdersTable", + "rows": [{}], + } + ], + ) + self.assertIn("cannot be empty", str(ctx.exception)) + + def test_table_append_numeric_header_mapping(self): + # Create a workbook with numeric year headers in a table + num_hdr_file = "numeric_headers.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Sales" + ws.append(["Region", "2024", "2025"]) + ws.append(["North", 100, 200]) + tab = Table(displayName="SalesTable", ref="A1:C2") + ws.add_table(tab) + wb.save(self.workspace_path / num_hdr_file) + wb.close() + + # Test both integer keys (2024: 300) and string keys ("2024": 500) + result = update_workbook( + self.workspace, + num_hdr_file, + operations=[ + { + "action": "append_table", + "table": "SalesTable", + "rows": [ + {"Region": "South", 2024: 300, 2025: 400}, + {"Region": "West", "2024": 500, "2025": 600}, + ], + } + ], + output_filename="sales_updated.xlsx", + ) + self.assertEqual(result["status"], "success") + + with self.workspace.open_workbook("sales_updated.xlsx") as saved_wb: + saved_ws = saved_wb["Sales"] + self.assertEqual(saved_ws["A3"].value, "South") + self.assertEqual(saved_ws["B3"].value, 300) + self.assertEqual(saved_ws["C3"].value, 400) + self.assertEqual(saved_ws["A4"].value, "West") + self.assertEqual(saved_ws["B4"].value, 500) + self.assertEqual(saved_ws["C4"].value, 600) + + def test_unknown_non_string_key_rejected_without_type_error(self): + # Passing a non-string key in an operation must not raise TypeError in sorted() or difflib + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[ + { + "action": "set_cell", + "cell": "A1", + "value": 10, + 999: "unexpected", + } + ], + ) + self.assertIn("Unknown key(s) '999'", str(ctx.exception)) + + def test_set_slot_success(self): + # Create workbook with a single-cell defined name + slot_wb_file = "slot_test.xlsx" + slot_wb_path = self.workspace_path / slot_wb_file + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + ws["B2"] = 0.10 + defn = DefinedName("TaxRate", attr_text="Config!$B$2") + wb.defined_names.add(defn) + wb.save(slot_wb_path) + wb.close() + + result = update_workbook( + self.workspace, + slot_wb_file, + operations=[{"action": "set_slot", "name": "TaxRate", "value": 0.25}], + ) + self.assertEqual(result["status"], "success") + self.assertEqual(result["operations_applied"], 1) + + with self.workspace.open_workbook(slot_wb_file) as saved_wb: + self.assertEqual(saved_wb["Config"]["B2"].value, 0.25) + + def test_set_slot_missing_name_raises_key_error(self): + with self.assertRaises(KeyError) as ctx: + update_workbook( + self.workspace, + "test_data.xlsx", + operations=[ + {"action": "set_slot", "name": "NonExistentSlot", "value": 100} + ], + ) + self.assertIn("Named slot 'NonExistentSlot' not found", str(ctx.exception)) + + def test_set_slot_constant_or_formula_raises_value_error(self): + const_wb_file = "const_slot.xlsx" + wb = openpyxl.Workbook() + defn = DefinedName("ConstSlot", attr_text="0.25") + wb.defined_names.add(defn) + wb.save(self.workspace_path / const_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + const_wb_file, + operations=[{"action": "set_slot", "name": "ConstSlot", "value": 0.30}], + ) + self.assertIn("does not resolve to a worksheet grid cell", str(ctx.exception)) + + def test_set_slot_formula_expression_raises_value_error(self): + expr_wb_file = "expr_slot.xlsx" + wb = openpyxl.Workbook() + defn = DefinedName("ExprSlot", attr_text="Summary!$A$1+$B$1") + wb.defined_names.add(defn) + wb.save(self.workspace_path / expr_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + expr_wb_file, + operations=[{"action": "set_slot", "name": "ExprSlot", "value": 10}], + ) + self.assertIn("does not resolve to a worksheet grid cell", str(ctx.exception)) + + def test_set_slot_multi_cell_raises_value_error(self): + multi_wb_file = "multi_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Data" + defn = DefinedName("MatrixSlot", attr_text="Data!$A$1:$B$2") + wb.defined_names.add(defn) + wb.save(self.workspace_path / multi_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + multi_wb_file, + operations=[{"action": "set_slot", "name": "MatrixSlot", "value": 42}], + ) + self.assertIn("spans multiple cells", str(ctx.exception)) + + def test_set_slot_whole_column_range_rejected(self): + col_wb_file = "col_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Data" + defn = DefinedName("ColSlot", attr_text="Data!A:A") + wb.defined_names.add(defn) + wb.save(self.workspace_path / col_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + col_wb_file, + operations=[{"action": "set_slot", "name": "ColSlot", "value": 42}], + ) + self.assertIn("spans multiple cells", str(ctx.exception)) + + def test_set_slot_collision_with_set_cell_caught_by_tracker(self): + slot_wb_file = "collision_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Settings" + ws["C5"] = 10 + defn = DefinedName("Threshold", attr_text="Settings!$C$5") + wb.defined_names.add(defn) + wb.save(self.workspace_path / slot_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + slot_wb_file, + operations=[ + { + "action": "set_cell", + "sheet": "Settings", + "cell": "C5", + "value": 20, + }, + {"action": "set_slot", "name": "Threshold", "value": 30}, + ], + ) + self.assertIn("Conflicting update", str(ctx.exception)) + self.assertIn("Settings!C5", str(ctx.exception)) + + def test_set_slot_formula_overwrite_protection(self): + formula_wb_file = "formula_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Math" + ws["A1"] = 10 + ws["A2"] = "=A1*2" + defn = DefinedName("Doubled", attr_text="Math!$A$2") + wb.defined_names.add(defn) + wb.save(self.workspace_path / formula_wb_file) + wb.close() + + with self.assertRaises(PermissionError) as ctx: + update_workbook( + self.workspace, + formula_wb_file, + operations=[{"action": "set_slot", "name": "Doubled", "value": 99}], + ) + self.assertIn("contains formula", str(ctx.exception)) + + def test_set_slot_formula_injection_protection(self): + slot_wb_file = "inject_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Main" + ws["B2"] = 1 + defn = DefinedName("TargetSlot", attr_text="Main!$B$2") + wb.defined_names.add(defn) + wb.save(self.workspace_path / slot_wb_file) + wb.close() + + with self.assertRaises(PermissionError) as ctx: + update_workbook( + self.workspace, + slot_wb_file, + operations=[ + { + "action": "set_slot", + "name": "TargetSlot", + "value": "+cmd|' /C calc'!A0", + } + ], + ) + self.assertIn("Formula injection prohibited", str(ctx.exception)) + + def test_set_slot_typo_suggests_close_match(self): + slot_wb_file = "typo_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + ws["B2"] = 0.10 + wb.defined_names.add(DefinedName("TaxRate", attr_text="Config!$B$2")) + wb.save(self.workspace_path / slot_wb_file) + wb.close() + + with self.assertRaises(KeyError) as ctx: + update_workbook( + self.workspace, + slot_wb_file, + operations=[{"action": "set_slot", "name": "tax_rate", "value": 0.2}], + ) + self.assertIn("Did you mean 'TaxRate'?", str(ctx.exception)) + self.assertIn("Available slots: ['TaxRate']", str(ctx.exception)) + + def test_set_slot_sheet_scoped_name_resolves(self): + slot_wb_file = "local_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + ws["B3"] = 0.5 + ws.defined_names.add(DefinedName("LocalRate", attr_text="Config!$B$3")) + wb.save(self.workspace_path / slot_wb_file) + wb.close() + + result = update_workbook( + self.workspace, + slot_wb_file, + operations=[{"action": "set_slot", "name": "LocalRate", "value": 0.75}], + ) + self.assertEqual(result["status"], "success") + + with self.workspace.open_workbook(slot_wb_file) as saved_wb: + self.assertEqual(saved_wb["Config"]["B3"].value, 0.75) + + def test_set_slot_ambiguous_name_rejected(self): + slot_wb_file = "ambiguous_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + wb.defined_names.add(DefinedName("Rate", attr_text="Config!$B$2")) + ws.defined_names.add(DefinedName("Rate", attr_text="Config!$B$3")) + wb.save(self.workspace_path / slot_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + slot_wb_file, + operations=[{"action": "set_slot", "name": "Rate", "value": 1}], + ) + self.assertIn("ambiguous", str(ctx.exception)) + + def test_set_slot_computed_expression_rejected(self): + computed_wb_file = "computed_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + ws["B2"] = 10 + defn = DefinedName("Computed", attr_text="Config!$B$2*2") + wb.defined_names.add(defn) + wb.save(self.workspace_path / computed_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + computed_wb_file, + operations=[{"action": "set_slot", "name": "Computed", "value": 99}], + ) + self.assertIn("does not resolve to a worksheet grid cell", str(ctx.exception)) + + def test_set_slot_indirect_named_range_rejected(self): + indirect_wb_file = "indirect_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + ws["B2"] = 100 + defn = DefinedName("IndirectSlot", attr_text="Config!B2_Input") + wb.defined_names.add(defn) + wb.save(self.workspace_path / indirect_wb_file) + wb.close() + + with self.assertRaises(ValueError) as ctx: + update_workbook( + self.workspace, + indirect_wb_file, + operations=[ + {"action": "set_slot", "name": "IndirectSlot", "value": 99} + ], + ) + self.assertIn("does not resolve to a worksheet grid cell", str(ctx.exception)) + # Ensure B2 was not overwritten + with self.workspace.open_workbook(indirect_wb_file) as check_wb: + self.assertEqual(check_wb["Config"]["B2"].value, 100) + + def test_set_slot_single_cell_range_normalized(self): + range_wb_file = "single_range_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Config" + defn = DefinedName("SingleRange", attr_text="Config!$B$2:$B$2") + wb.defined_names.add(defn) + wb.save(self.workspace_path / range_wb_file) + wb.close() + + result = update_workbook( + self.workspace, + range_wb_file, + operations=[{"action": "set_slot", "name": "SingleRange", "value": 42}], + ) + self.assertEqual(result["status"], "success") + + with self.workspace.open_workbook(range_wb_file) as saved_wb: + self.assertEqual(saved_wb["Config"]["B2"].value, 42) + + def test_set_slot_escaped_apostrophe_sheet_name(self): + apostrophe_wb_file = "apostrophe_slot.xlsx" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "O'Brien" + defn = DefinedName("OBrienSlot", attr_text="'O''Brien'!$A$1") + wb.defined_names.add(defn) + wb.save(self.workspace_path / apostrophe_wb_file) + wb.close() + + result = update_workbook( + self.workspace, + apostrophe_wb_file, + operations=[{"action": "set_slot", "name": "OBrienSlot", "value": 99}], + ) + self.assertEqual(result["status"], "success") + + with self.workspace.open_workbook(apostrophe_wb_file) as saved_wb: + self.assertEqual(saved_wb["O'Brien"]["A1"].value, 99) + + def test_update_workbook_preserves_subfolder_output_name(self): + sub_dir = self.workspace_path / "reports" + sub_dir.mkdir(parents=True, exist_ok=True) + wb = openpyxl.Workbook() + wb.save(sub_dir / "data.xlsx") + wb.close() + + result = update_workbook( + self.workspace, + "reports/data.xlsx", + operations=[{"action": "set_cell", "cell": "A1", "value": "test"}], + ) + self.assertEqual(result["file_name"], "reports/data.xlsx") diff --git a/tests/test_memory.py b/tests/test_memory.py new file mode 100644 index 0000000..ef98c2d --- /dev/null +++ b/tests/test_memory.py @@ -0,0 +1,195 @@ +from unittest.mock import MagicMock + +from agentoffice.core.memory import AgentMemory + + +def test_record_usage_with_cache(): + memory = AgentMemory() + usage = MagicMock() + usage.prompt_tokens = 5000 + usage.completion_tokens = 200 + usage.total_tokens = 5200 + usage.prompt_tokens_details.cached_tokens = 4096 + + memory.record_usage(usage) + assert memory.last_usage["cached_tokens"] == 4096 + assert memory.session_usage["cached_tokens"] == 4096 + assert memory.session_usage["total_tokens"] == 5200 + + +def test_memory(): + memory = AgentMemory(system_prompt="You are an assistant") + + assert len(memory.history) == 1 + assert memory.history[0] == {"role": "system", "content": "You are an assistant"} + assert memory.last_usage["total_tokens"] == 0 + assert memory.session_usage["total_tokens"] == 0 + + +def test_add_user_message(): + memory = AgentMemory(system_prompt="You are an assistant") + memory.add_user_message("Hello") + assert len(memory.history) == 2 + assert memory.history[1] == {"role": "user", "content": "Hello"} + + +def test_add_assistant_message(): + memory = AgentMemory(system_prompt="You are an assistant") + memory.add_assistant_message({"role": "assistant", "content": "Hello"}) + assert len(memory.history) == 2 + assert memory.history[1] == {"role": "assistant", "content": "Hello"} + + +def test_add_tool_message(): + memory = AgentMemory(system_prompt="You are an assistant") + memory.add_tool_message("tool_id", "tool_name", "tool_result") + assert len(memory.history) == 2 + assert memory.history[1] == { + "role": "tool", + "tool_call_id": "tool_id", + "name": "tool_name", + "content": "tool_result", + } + + +def test_clear_history(): + memory = AgentMemory(system_prompt="You are an assistant") + memory.add_user_message("Hello") + memory.add_assistant_message({"role": "assistant", "content": "Hello"}) + memory.add_tool_message("tool_id", "tool_name", "tool_result") + memory.clear_history() + assert len(memory.history) == 1 + assert memory.history[0] == {"role": "system", "content": "You are an assistant"} + + +def test_memory_initialization_empty(): + memory = AgentMemory() + assert len(memory.history) == 0 + assert memory.last_usage["total_tokens"] == 0 + assert memory.session_usage["total_tokens"] == 0 + + +def test_find_safe_slice_index_too_short(): + memory = AgentMemory() + memory.add_user_message("Hello") + assert memory._find_safe_slice_index() is None + + +def test_find_safe_slice_index_finds_user_boundary(): + memory = AgentMemory(system_prompt="System") # index 0 + memory.add_user_message("Turn 1") # index 1 + memory.add_assistant_message({"role": "assistant", "content": "R1"}) # index 2 + memory.add_tool_message("t1", "tool", "out1") # index 3 + memory.add_user_message("Turn 2") # index 4 + memory.add_assistant_message({"role": "assistant", "content": "R2"}) # index 5 + memory.add_tool_message("t2", "tool", "out2") # index 6 + + # Total length is 7. If we keep the last ~30% (keep_ratio=0.3): + # target = int(7 * 0.7) = 4 + # Index 4 is a "user" message! + slice_idx = memory._find_safe_slice_index(keep_ratio=0.3) + assert slice_idx is not None + assert memory.history[slice_idx]["role"] == "user" + + +def test_compact_without_system_prompt_includes_first_user_message(): + memory = AgentMemory() # no system prompt + memory.add_user_message("First user instruction: use data.xlsx") + memory.add_assistant_message({"role": "assistant", "content": "R1"}) + memory.add_user_message("Second user instruction: continue") + memory.add_assistant_message({"role": "assistant", "content": "R2"}) + + mock_client = MagicMock() + mock_choice = MagicMock() + mock_choice.message.content = "Summary of conversation" + mock_response = MagicMock() + mock_response.choices = [mock_choice] + mock_response.usage = None + mock_client.chat.completions.create.return_value = mock_response + + summary = memory.compact(mock_client, model="mock-model", force=True) + assert summary == "Summary of conversation" + + # Verify that the first user instruction was sent in the compaction transcript + create_call = mock_client.chat.completions.create.call_args + prompt_sent = create_call.kwargs["messages"][1]["content"] + assert "First user instruction: use data.xlsx" in prompt_sent + + +def test_compact_with_system_prompt_preserves_system_prompt(): + memory = AgentMemory(system_prompt="You are a helper") + memory.add_user_message("Turn 1") + memory.add_assistant_message({"role": "assistant", "content": "R1"}) + memory.add_user_message("Turn 2") + memory.add_assistant_message({"role": "assistant", "content": "R2"}) + + mock_client = MagicMock() + mock_choice = MagicMock() + mock_choice.message.content = "Summary of conversation" + mock_response = MagicMock() + mock_response.choices = [mock_choice] + mock_response.usage = None + mock_client.chat.completions.create.return_value = mock_response + + summary = memory.compact(mock_client, model="mock-model", force=True) + assert summary == "Summary of conversation" + + # System prompt remains at index 0, followed by assistant summary + assert memory.history[0]["role"] == "system" + assert memory.history[0]["content"] == "You are a helper" + assert memory.history[1]["role"] == "assistant" + assert "[Summary of previous conversation]" in memory.history[1]["content"] + + +def test_compact_returns_none_and_keeps_history_when_summary_empty(): + memory = AgentMemory(system_prompt="System prompt") + memory.add_user_message("Turn 1") + memory.add_assistant_message({"role": "assistant", "content": "R1"}) + memory.add_user_message("Turn 2") + memory.add_assistant_message({"role": "assistant", "content": "R2"}) + + initial_history = [dict(m) for m in memory.history] + + mock_client = MagicMock() + mock_choice = MagicMock() + mock_choice.message.content = None # None summary + mock_response = MagicMock(choices=[mock_choice], usage=None) + mock_client.chat.completions.create.return_value = mock_response + + summary = memory.compact(mock_client, model="mock-model", force=True) + assert summary is None + assert memory.history == initial_history + mock_client.chat.completions.create.assert_called_once() + + +def test_compact_does_not_overwrite_last_usage(): + memory = AgentMemory(system_prompt="System prompt") + memory.last_usage = { + "prompt_tokens": 15000, + "completion_tokens": 500, + "cached_tokens": 0, + "total_tokens": 15500, + } + memory.add_user_message("Turn 1") + memory.add_assistant_message({"role": "assistant", "content": "R1"}) + memory.add_user_message("Turn 2") + memory.add_assistant_message({"role": "assistant", "content": "R2"}) + + summary_usage = MagicMock() + summary_usage.prompt_tokens = 200 + summary_usage.completion_tokens = 50 + summary_usage.total_tokens = 250 + summary_usage.prompt_tokens_details = None + + mock_client = MagicMock() + mock_choice = MagicMock() + mock_choice.message.content = "Summary" + mock_response = MagicMock(choices=[mock_choice], usage=summary_usage) + mock_client.chat.completions.create.return_value = mock_response + + summary = memory.compact(mock_client, model="mock-model", force=True) + assert summary == "Summary" + # last_usage must remain the conversation's usage, NOT the summary request's 200 tokens + assert memory.last_usage["prompt_tokens"] == 15000 + assert memory.session_usage["tokens_saved"] == 15500 + assert memory.session_usage["prompt_tokens"] == 200 diff --git a/workspace/.gitkeep b/workspace/.gitkeep new file mode 100644 index 0000000..e69de29