From 0d7401de78590c6b432435a5f59b7b955eb6ae88 Mon Sep 17 00:00:00 2001 From: VENKATANATHA AV Date: Tue, 3 Nov 2026 23:23:43 +0530 Subject: [PATCH 01/16] fix(excel): enforce strict operation contract with typo suggestions - Remove silent aliases ('append_rows' action, 'mutations' parameter): exactly one canonical name per contract, matching the tool schema - Reject missing required keys instead of silently defaulting to empty (a missing 'rows' key previously committed a no-op as 'success') - Reject unknown keys with difflib 'did you mean' suggestions so the model self-corrects on the next turn; unknown checked before missing because a typo'd required key triggers both errors - Reject non-list and empty 'rows' payloads up front - Require 'action' on every operation in the tool schema - Add 5 contract regression tests (canonical names, unknown action, missing key, typo suggestion, empty rows) --- agentoffice/tools/excel/write.py | 58 ++++++++++++++++++++++++++------ tests/test_excel_write.py | 54 +++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 11 deletions(-) diff --git a/agentoffice/tools/excel/write.py b/agentoffice/tools/excel/write.py index dc05d73..f85619a 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -1,3 +1,4 @@ +from difflib import get_close_matches import os import tempfile from pathlib import Path @@ -32,6 +33,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 +43,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']}") @@ -85,6 +86,9 @@ def verify(verify_wb: openpyxl.Workbook, validated: dict[str, Any]) -> None: class AppendTableHandler: + REQUIRED_KEYS = frozenset({"table", "rows"}) + OPTIONAL_KEYS = frozenset() + @staticmethod def validate( wb: openpyxl.Workbook, @@ -92,8 +96,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) @@ -235,7 +247,6 @@ def verify(verify_wb: openpyxl.Workbook, validated: dict[str, Any]) -> None: OPERATION_HANDLERS = { "set_cell": SetCellHandler, "append_table": AppendTableHandler, - "append_rows": AppendTableHandler, } @@ -245,7 +256,6 @@ def update_workbook( 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.""" src_path = workspace.resolve_path(file_name, must_exist=True) @@ -262,7 +272,7 @@ def update_workbook( dest_path = src_path is_inplace = True - ops = operations if operations is not None else (mutations or []) + ops = operations or [] if not ops: raise ValueError("No operations provided.") @@ -282,6 +292,33 @@ def update_workbook( f"Unsupported operation action: '{action}'. Supported actions: {list(OPERATION_HANDLERS.keys())}" ) handler = OPERATION_HANDLERS[action] + + # Strict envelope: no unknown keys, required keys present. + # Unknown keys are checked first because a typo'd required key + # appears as both unknown and missing, and the suggestion is the + # more actionable error. Happy-path cost is two set operations + # per op; the difflib search below only runs on failures. + 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): + close = get_close_matches(bad, allowed, n=1) + hints.append( + f"'{bad}'" + (f" (did you mean '{close[0]}'?)" if close else "") + ) + raise ValueError( + f"Unknown key(s) {', '.join(hints)} for '{action}'. " + f"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)}" + ) + validated = handler.validate(wb, op, tracker) validated_ops.append((handler, validated)) @@ -350,7 +387,7 @@ def __init__(self, workspace: ExcelWorkspace): }, "operations": { "type": "array", - "items": {"type": "object"}, + "items": {"type": "object", "required": ["action"]}, "description": "List of operations to apply.", }, "overwrite": { @@ -369,14 +406,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_excel_write.py b/tests/test_excel_write.py index d4f9716..76fd668 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -8,6 +8,7 @@ from agentoffice.tools.excel.workspace import ExcelWorkspace from agentoffice.tools.excel.write import ( + OPERATION_HANDLERS, AppendTableHandler, SetCellHandler, UpdateWorkbookTool, @@ -433,3 +434,56 @@ 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): + # Aliases (append_rows, mutations) were removed: exactly two + # canonical actions exist. + self.assertEqual(set(OPERATION_HANDLERS.keys()), {"set_cell", "append_table"}) + + 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)) From bd7140041d6b222185f658f31638c97502033111 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 4 Nov 2026 09:24:49 +0530 Subject: [PATCH 02/16] fix(excel): robust header mapping, reject empty dict rows,and crash-proof typo suggestions --- agentoffice/tools/excel/write.py | 24 +++++++--- tests/test_excel_write.py | 78 ++++++++++++++++++++++++++++++-- 2 files changed, 92 insertions(+), 10 deletions(-) diff --git a/agentoffice/tools/excel/write.py b/agentoffice/tools/excel/write.py index f85619a..6538eaf 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -1,6 +1,6 @@ -from difflib import get_close_matches import os import tempfile +from difflib import get_close_matches from pathlib import Path from typing import Any @@ -123,18 +123,27 @@ 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( @@ -303,10 +312,11 @@ def update_workbook( if unknown: allowed = sorted(handler.REQUIRED_KEYS | handler.OPTIONAL_KEYS) hints = [] - for bad in sorted(unknown): - close = get_close_matches(bad, allowed, n=1) + for bad in sorted(unknown, key=str): + str_bad = str(bad) + close = get_close_matches(str_bad, allowed, n=1) hints.append( - f"'{bad}'" + (f" (did you mean '{close[0]}'?)" if close else "") + f"'{str_bad}'" + (f" (did you mean '{close[0]}'?)" if close else "") ) raise ValueError( f"Unknown key(s) {', '.join(hints)} for '{action}'. " diff --git a/tests/test_excel_write.py b/tests/test_excel_write.py index 76fd668..2284202 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -436,9 +436,9 @@ def test_formulas_survive_successful_update(self): self.assertEqual(wb["Orders"]["A3"].value, "Mouse") def test_canonical_operation_names(self): - # Aliases (append_rows, mutations) were removed: exactly two - # canonical actions exist. - self.assertEqual(set(OPERATION_HANDLERS.keys()), {"set_cell", "append_table"}) + 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: @@ -487,3 +487,75 @@ def test_empty_rows_rejected(self): ], ) 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)) From 4b7fe521c4aac109219818a4e19be6d42db42d73 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 4 Nov 2026 09:49:09 +0530 Subject: [PATCH 03/16] refactor(excel): modularize update_workbook pipeline and prevent temp file leaks --- agentoffice/tools/excel/write.py | 151 ++++++++++++++++++------------- tests/test_excel_write.py | 21 +++++ 2 files changed, 108 insertions(+), 64 deletions(-) diff --git a/agentoffice/tools/excel/write.py b/agentoffice/tools/excel/write.py index 6538eaf..7883d74 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -259,27 +259,100 @@ def verify(verify_wb: openpyxl.Workbook, validated: dict[str, Any]) -> None: } -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, -) -> 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 = src_path.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}'. " + f"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 or [] if not ops: @@ -287,10 +360,9 @@ def update_workbook( 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]]] = [] @@ -301,71 +373,22 @@ def update_workbook( f"Unsupported operation action: '{action}'. Supported actions: {list(OPERATION_HANDLERS.keys())}" ) handler = OPERATION_HANDLERS[action] - - # Strict envelope: no unknown keys, required keys present. - # Unknown keys are checked first because a typo'd required key - # appears as both unknown and missing, and the suggestion is the - # more actionable error. Happy-path cost is two set operations - # per op; the difflib search below only runs on failures. - 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}'. " - f"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)}" - ) - - 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), } diff --git a/tests/test_excel_write.py b/tests/test_excel_write.py index 2284202..a86c6e1 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -275,6 +275,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( From 36fc0196927af3c8d41106810ff5f7cc6808f824 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 4 Nov 2026 10:43:57 +0530 Subject: [PATCH 04/16] feat(excel): guard formula injection, enforce cell limits, and add set_slot - guards.py: - Block formula injection for trigger prefixes (=, +, -, @) - Allow valid numeric strings (e.g. "-50000") via float() whitelist - Unify formula detection in get_formula_trigger() - Improve limit error message to steer agents to inspect_workbook - read.py: - Check total cell count before fetching cell objects from openpyxl - Fast-fail giant range queries (e.g. A1:XFD1048576) in <50ms without memory growth - Strip quotes from sheet names (e.g. 'Sheet 1'!A1) to avoid KeyError - write.py: - Add SetSlotHandler to update Excel Defined Names by name - Reject formulas, constants, and multi-cell or whole-column ranges (A:A) - Delegate to SetCellHandler for protection checks and batch collision detection - tests: - Add unit tests for guards, named slots, and cell limits (51 passing, 0 warnings) --- agentoffice/tools/excel/guards.py | 39 ++++++-- agentoffice/tools/excel/read.py | 75 +++++++++------ agentoffice/tools/excel/write.py | 61 ++++++++++++ tests/test_excel_guards.py | 78 ++++++++++++++++ tests/test_excel_read.py | 40 +++++++- tests/test_excel_write.py | 149 ++++++++++++++++++++++++++++++ 6 files changed, 408 insertions(+), 34 deletions(-) create mode 100644 tests/test_excel_guards.py diff --git a/agentoffice/tools/excel/guards.py b/agentoffice/tools/excel/guards.py index aa26def..f5a062a 100644 --- a/agentoffice/tools/excel/guards.py +++ b/agentoffice/tools/excel/guards.py @@ -1,21 +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})" ) @@ -24,6 +43,12 @@ def guard_sheet_unprotected(sheet, error_message: str = "Sheet is protected") -> if sheet.protection.sheet: raise PermissionError(error_message) + 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/read.py b/agentoffice/tools/excel/read.py index f419c68..2fe2e4e 100644 --- a/agentoffice/tools/excel/read.py +++ b/agentoffice/tools/excel/read.py @@ -1,12 +1,51 @@ 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.split("!", 1) + clean_sheet = sheet_name.strip("'") + 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 +55,20 @@ 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: + total_cells = sum( + _count_range_cells(*_resolve_sheet_and_coords(workbook, r, file_name)) + for r in ranges + ) + if total_cells > max_cells: + raise ValueError(format_limit_exceeded_error(total_cells, max_cells)) + + 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) + 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/write.py b/agentoffice/tools/excel/write.py index 7883d74..643efbb 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -85,6 +85,65 @@ 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"] + + defn = wb.defined_names.get(name) + if defn is None: + raise KeyError(f"Named slot '{name}' not found in workbook.") + + dests = list(defn.destinations) + if not dests: + raise ValueError( + f"Named slot '{name}' does not resolve to a worksheet grid cell " + f"(defined as constant/formula: '{defn.attr_text}'). 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("'") 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) + min_col, min_row, max_col, max_row = range_boundaries(clean_c) + 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." + ) + + # Delegate to SetCellHandler for protection, collision tracking, formula checks + return SetCellHandler.validate( + wb, + {"sheet": sheet_name, "cell": clean_c, "value": value}, + tracker, + ) + + apply = SetCellHandler.apply + verify = SetCellHandler.verify + + class AppendTableHandler: REQUIRED_KEYS = frozenset({"table", "rows"}) OPTIONAL_KEYS = frozenset() @@ -256,6 +315,7 @@ def verify(verify_wb: openpyxl.Workbook, validated: dict[str, Any]) -> None: OPERATION_HANDLERS = { "set_cell": SetCellHandler, "append_table": AppendTableHandler, + "set_slot": SetSlotHandler, } @@ -401,6 +461,7 @@ 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), " "'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). " 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_read.py b/tests/test_excel_read.py index 98b529c..f59f453 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,35 @@ 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"]], + ) diff --git a/tests/test_excel_write.py b/tests/test_excel_write.py index a86c6e1..0363366 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -4,6 +4,7 @@ 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 @@ -11,6 +12,7 @@ OPERATION_HANDLERS, AppendTableHandler, SetCellHandler, + SetSlotHandler, UpdateWorkbookTool, update_workbook, ) @@ -580,3 +582,150 @@ def test_unknown_non_string_key_rejected_without_type_error(self): ], ) 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_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)) From b9de295ca2324ae4475e3954267277a85882fe6e Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 4 Nov 2026 11:25:40 +0530 Subject: [PATCH 05/16] feat(license): add Apache-2.0 license --- LICENSE | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 1 + 2 files changed, 202 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..db8dc7e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or exemplary damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 VENKATANATHA AV + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/pyproject.toml b/pyproject.toml index 26c724b..b874d2e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,6 +2,7 @@ name = "agent-office" version = "0.1.0" requires-python = ">=3.11" +license = "Apache-2.0" dependencies = [ "openai", "openpyxl", From 2b2dfd53a0699d445f3e00dd25bc38e8702e08a6 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 4 Nov 2026 11:42:55 +0530 Subject: [PATCH 06/16] chore(tooling): add ruff to dev dependencies and format codebase --- agentoffice/tools/excel/factory.py | 7 +++--- agentoffice/tools/excel/inspect.py | 36 +++++++++++++++++------------- agentoffice/tools/excel/read.py | 6 ++++- agentoffice/tools/excel/write.py | 6 ++--- examples/raw_gemini_test.py | 3 +-- pyproject.toml | 4 ++++ tests/test_excel_inspect.py | 12 +++++----- tests/test_excel_write.py | 20 +++++++++++++---- uv.lock | 35 ++++++++++++++++++++++++++--- 9 files changed, 90 insertions(+), 39 deletions(-) diff --git a/agentoffice/tools/excel/factory.py b/agentoffice/tools/excel/factory.py index 80ae7f0..be053b5 100644 --- a/agentoffice/tools/excel/factory.py +++ b/agentoffice/tools/excel/factory.py @@ -1,9 +1,10 @@ +from pathlib import Path + +from agentoffice.core.tool import BaseTool from agentoffice.tools.excel.inspect import InspectWorkbookTool from agentoffice.tools.excel.read import ReadRangesTool from agentoffice.tools.excel.workspace import ExcelWorkspace from agentoffice.tools.excel.write import UpdateWorkbookTool -from agentoffice.core.tool import BaseTool -from pathlib import Path def create_excel_tools(workspace_dir: str | Path) -> list[BaseTool]: @@ -13,4 +14,4 @@ def create_excel_tools(workspace_dir: str | Path) -> list[BaseTool]: InspectWorkbookTool(ws), ReadRangesTool(ws), UpdateWorkbookTool(ws), - ] \ No newline at end of file + ] diff --git a/agentoffice/tools/excel/inspect.py b/agentoffice/tools/excel/inspect.py index 2ea91bf..f4f106d 100644 --- a/agentoffice/tools/excel/inspect.py +++ b/agentoffice/tools/excel/inspect.py @@ -1,13 +1,14 @@ from pathlib import Path from typing import Any -import openpyxl -from agentoffice.tools.excel.workspace import ExcelWorkspace +from agentoffice.core.tool import BaseTool from agentoffice.tools.excel.guards import is_formula +from agentoffice.tools.excel.workspace import ExcelWorkspace -from agentoffice.core.tool import BaseTool -def inspect_workbook(workspace: ExcelWorkspace, file_name: str | Path) -> dict[str, Any]: +def inspect_workbook( + workspace: ExcelWorkspace, file_name: str | Path +) -> dict[str, Any]: with workspace.open_workbook(file_name) as wb: sheet_details = { @@ -19,7 +20,7 @@ def inspect_workbook(workspace: ExcelWorkspace, file_name: str | Path) -> dict[s } for ws in wb.worksheets } - formula=[ + formula = [ {"sheet": ws.title, "cell": cell.coordinate, "formula": cell.value} for ws in wb.worksheets for row in ws.iter_rows() @@ -40,7 +41,7 @@ def inspect_workbook(workspace: ExcelWorkspace, file_name: str | Path) -> dict[s } -class InspectWorkbookTool(BaseTool): +class InspectWorkbookTool(BaseTool): def __init__(self, workspace: ExcelWorkspace): self.workspace = workspace super().__init__( @@ -50,21 +51,24 @@ def __init__(self, workspace: ExcelWorkspace): "sheet details, formulas, and tables" ), 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')" + "type": "object", + "properties": { + "file_name": { + "type": "string", + "description": "name of the excel workbook file in the workspace directory to inspect (e.g., 'data.xlsx')", } }, - "required":["file_name"] - } + "required": ["file_name"], + }, ) - + def execute(self, file_name: str) -> dict[str, Any]: if not file_name: - return {"status": "error", "error": "ValueError: Parameter 'file_name' is required."} + return { + "status": "error", + "error": "ValueError: Parameter 'file_name' is required.", + } try: return inspect_workbook(self.workspace, file_name) except Exception as e: - return {"status": "error", "error": f"{type(e).__name__}: {str(e)}"} \ No newline at end of file + return {"status": "error", "error": f"{type(e).__name__}: {str(e)}"} diff --git a/agentoffice/tools/excel/read.py b/agentoffice/tools/excel/read.py index 2fe2e4e..066ad4b 100644 --- a/agentoffice/tools/excel/read.py +++ b/agentoffice/tools/excel/read.py @@ -40,7 +40,11 @@ def _extract_values_from_target(target: Any) -> list[list[Any]]: 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 ( + 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]] diff --git a/agentoffice/tools/excel/write.py b/agentoffice/tools/excel/write.py index 643efbb..c664326 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -200,8 +200,7 @@ def validate( f"Expected columns: {headers}" ) row_vals = [ - row[h] if h in row else str_row.get(str(h)) - for h in headers + 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: @@ -360,8 +359,7 @@ def _validate_operation_envelope( f"'{str_bad}'" + (f" (did you mean '{close[0]}'?)" if close else "") ) raise ValueError( - f"Unknown key(s) {', '.join(hints)} for '{action}'. " - f"Allowed keys: {allowed}" + f"Unknown key(s) {', '.join(hints)} for '{action}'. Allowed keys: {allowed}" ) missing = handler.REQUIRED_KEYS - keys diff --git a/examples/raw_gemini_test.py b/examples/raw_gemini_test.py index bb5522b..16546ae 100644 --- a/examples/raw_gemini_test.py +++ b/examples/raw_gemini_test.py @@ -1,3 +1,4 @@ +import json import os from dotenv import load_dotenv @@ -5,8 +6,6 @@ load_dotenv() -import json - def add_numbers(a: int, b: int) -> int: return a + b diff --git a/pyproject.toml b/pyproject.toml index b874d2e..1373fef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,10 +21,14 @@ select = [ "I", # isort (automatically sort imports) "UP", # pyupgrade (modern Python syntax) ] +ignore = [ + "E501", # line-too-long (handled automatically by ruff format) +] [dependency-groups] dev = [ "pytest>=9.2.0", + "ruff>=0.17.3", ] [tool.pytest.ini_options] diff --git a/tests/test_excel_inspect.py b/tests/test_excel_inspect.py index 8bb044d..da31abe 100644 --- a/tests/test_excel_inspect.py +++ b/tests/test_excel_inspect.py @@ -1,11 +1,12 @@ import tempfile import unittest from pathlib import Path + import openpyxl from openpyxl.worksheet.table import Table +from agentoffice.tools.excel.inspect import InspectWorkbookTool, inspect_workbook from agentoffice.tools.excel.workspace import ExcelWorkspace -from agentoffice.tools.excel.inspect import inspect_workbook, InspectWorkbookTool class TestExcelInspect(unittest.TestCase): @@ -42,23 +43,22 @@ def setUp(self): def tearDown(self): self.temp_dir.cleanup() - def test_inspect_workbook_finds_sheets_formulas_and_tables(self): result = inspect_workbook(self.workspace, "test_data.xlsx") self.assertIn("sheet_names", result) self.assertIn("formulas", result) self.assertIn("tables", result) - self.assertEqual(result["sheet_names"], ["Summary","Orders"]) - self.assertEqual(result["formulas"][0]["formula"],"=B1*0.2") + self.assertEqual(result["sheet_names"], ["Summary", "Orders"]) + self.assertEqual(result["formulas"][0]["formula"], "=B1*0.2") self.assertEqual(result["tables"][0]["name"], "OrdersTable") - + def test_inspect_tool_execution(self): tool = InspectWorkbookTool(workspace=self.workspace) result = tool.execute("test_data.xlsx") self.assertEqual(result["active_sheet"], "Summary") self.assertEqual(result["sheet_names"], ["Summary", "Orders"]) self.assertEqual(result["tables"][0]["name"], "OrdersTable") - + def test_inspect_tool_error_handling(self): tool = InspectWorkbookTool(workspace=self.workspace) result = tool.execute("nonexistent.xlsx") diff --git a/tests/test_excel_write.py b/tests/test_excel_write.py index 0363366..9ca3e73 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -12,7 +12,6 @@ OPERATION_HANDLERS, AppendTableHandler, SetCellHandler, - SetSlotHandler, UpdateWorkbookTool, update_workbook, ) @@ -612,7 +611,9 @@ def test_set_slot_missing_name_raises_key_error(self): update_workbook( self.workspace, "test_data.xlsx", - operations=[{"action": "set_slot", "name": "NonExistentSlot", "value": 100}], + operations=[ + {"action": "set_slot", "name": "NonExistentSlot", "value": 100} + ], ) self.assertIn("Named slot 'NonExistentSlot' not found", str(ctx.exception)) @@ -684,7 +685,12 @@ def test_set_slot_collision_with_set_cell_caught_by_tracker(self): self.workspace, slot_wb_file, operations=[ - {"action": "set_cell", "sheet": "Settings", "cell": "C5", "value": 20}, + { + "action": "set_cell", + "sheet": "Settings", + "cell": "C5", + "value": 20, + }, {"action": "set_slot", "name": "Threshold", "value": 30}, ], ) @@ -726,6 +732,12 @@ def test_set_slot_formula_injection_protection(self): update_workbook( self.workspace, slot_wb_file, - operations=[{"action": "set_slot", "name": "TargetSlot", "value": "+cmd|' /C calc'!A0"}], + operations=[ + { + "action": "set_slot", + "name": "TargetSlot", + "value": "+cmd|' /C calc'!A0", + } + ], ) self.assertIn("Formula injection prohibited", str(ctx.exception)) diff --git a/uv.lock b/uv.lock index 6794da9..ab3ca64 100644 --- a/uv.lock +++ b/uv.lock @@ -20,6 +20,7 @@ dependencies = [ [package.dev-dependencies] dev = [ { name = "pytest" }, + { name = "ruff" }, ] [package.metadata] @@ -31,7 +32,10 @@ requires-dist = [ ] [package.metadata.requires-dev] -dev = [{ name = "pytest", specifier = ">=9.2.0" }] +dev = [ + { name = "pytest", specifier = ">=9.2.0" }, + { name = "ruff", specifier = ">=0.17.3" }, +] [[package]] name = "annotated-types" @@ -87,8 +91,8 @@ name = "httpcore2" version = "2.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11" }, - { name = "truststore" }, + { name = "h11", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, + { name = "truststore", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/30/ff/b53af1b49bb2cb5fa97c92215614b173ca5c1a99ded80e2d52f15a94fa6d/httpcore2-2.14.0.tar.gz", hash = "sha256:4f57a1a8249fe6af589d935cfd456f1d13bbdcb0f0fc72af9142368fc94811d7", size = 69096, upload-time = "2026-10-18T16:29:21.898Z" } wheels = [ @@ -481,6 +485,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, ] +[[package]] +name = "ruff" +version = "0.17.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/59/73/81f140c4edd9cc323de5478e6bbd3bbcfae9a82692df1a258de8cec6a6d2/ruff-0.17.3.tar.gz", hash = "sha256:a57049c8addb3662073859bb55a7ad35aa54f8a7c9ed268911d1333c5aadaaa9", size = 5339444, upload-time = "2026-10-27T00:34:05.914Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/8c/083365310c4e79c842f25bf5a842facbd9b0c0ec336f96dffa5074fe723d/ruff-0.17.3-py3-none-linux_armv6l.whl", hash = "sha256:ab86b84cd9d05e56d329742c0cabdcbe2d1d56c98f4a04aab9b5b66196febfb4", size = 10216522, upload-time = "2026-10-27T00:33:29.822Z" }, + { url = "https://files.pythonhosted.org/packages/72/26/4b2edf31cfebe9605d8f6ed8f1d6f376d3a53d4c9a123e62661c64c440f0/ruff-0.17.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e407b4a6852853a9a2cdce96963e94ad9775578bb44e7561a0f2829f3cc04b11", size = 10217786, upload-time = "2026-10-27T00:33:33.949Z" }, + { url = "https://files.pythonhosted.org/packages/a2/7e/537aba4b7f54397a374d2f6a6fc93e9c8015e18553f31a4a7b7dbced48b5/ruff-0.17.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b75cc113b3aca388933d8296b667b1ac401a80317ea3074c9b0a66541199da29", size = 9440362, upload-time = "2026-10-27T00:33:35.784Z" }, + { url = "https://files.pythonhosted.org/packages/3d/66/283e39734f66c8a5ebaa93c22eb7b7515779a0b1d5a5c0ad20e05c0edb41/ruff-0.17.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab5fa7ed5ce18554ea69d850ad162cbaa0c85fc47c08d83a569f806681c9a6ad", size = 10094281, upload-time = "2026-10-27T00:33:38.216Z" }, + { url = "https://files.pythonhosted.org/packages/21/4c/1ffc768497bd025a32c72152771e40c0b99bddc5cc6e4f50c7949a395346/ruff-0.17.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c673c170e27834d1262e3a9c1e97bdc9b9c3b180c63d89173ce69747232474c1", size = 10022543, upload-time = "2026-10-27T00:33:40.181Z" }, + { url = "https://files.pythonhosted.org/packages/73/c3/f90db547301080fcb82c92abf914c8bd57b89911d9b65a6c4cc6b52d0635/ruff-0.17.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a754c0341bc9ca151b7b335988b3263921c08859f84ca219b70cee825571b6f", size = 10683921, upload-time = "2026-10-27T00:33:42.182Z" }, + { url = "https://files.pythonhosted.org/packages/e5/98/92d4a8a26c6c96cf1a5b34dd59036d8a71e52d650aab065c58867e964e63/ruff-0.17.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4590b9d86c0b1543ebb09094254e191cd43fe8edaf330baa035aab03da251532", size = 11373408, upload-time = "2026-10-27T00:33:44.19Z" }, + { url = "https://files.pythonhosted.org/packages/43/02/1f24d2e3064c9753926deeb901afa57777b37ee46799b09ddd7aee6e5145/ruff-0.17.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bbde18beccd98c29a227c63c99022e3443b99258e08326df6425dfe0443705ef", size = 10977469, upload-time = "2026-10-27T00:33:46.179Z" }, + { url = "https://files.pythonhosted.org/packages/f0/20/fecedea2209f574ab92033b344e01a7f0c2dc76c6d6d19a14c9f8141173f/ruff-0.17.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7fa4b0f931cdbcb8a52044f370a3eb429fb42eb88807b0e800fcaa98dd42b24e", size = 10577491, upload-time = "2026-10-27T00:33:48.233Z" }, + { url = "https://files.pythonhosted.org/packages/33/36/b93fdf0bc6f84f0cd487aadfb0354deb40013669ea35ac3d26855de1e959/ruff-0.17.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:39405f341deec934b4289634324ad695f72df2970f9121582872eaf5b722f0f5", size = 10608748, upload-time = "2026-10-27T00:33:50.284Z" }, + { url = "https://files.pythonhosted.org/packages/5d/b7/7d3f5f14145daead1efb0b9a8289ed1daa100f419d60774375951723ce00/ruff-0.17.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:68074094f55ca3d29ab19491f640282f7a84061c4c7977aa5094b968ca457e9a", size = 10075057, upload-time = "2026-10-27T00:33:52.074Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ed/93ff7a5909ee56e2bd4b982deae9e0efb2724417874a90c9e41ad66c6dd7/ruff-0.17.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:27bb571ac78fef178fe5118d2827df95c2aae74a48fff2b15f6acd03af5ff5bb", size = 10022431, upload-time = "2026-10-27T00:33:54.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/07/a83b9eeec8c1c3c0e4eda15f06c3a91001bfd2687ea2f07b750719bf9712/ruff-0.17.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:029c37cbd3de48ca37aa12117bead2d065f15da17d66bf84e0d4274013705db2", size = 10394903, upload-time = "2026-10-27T00:33:56.158Z" }, + { url = "https://files.pythonhosted.org/packages/af/b2/05c39857c2526fcbebe46ad93a8dc97424656dfef14d3ef933abe1ffd331/ruff-0.17.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:692fdb46d0fd9c71e380947dc5fc72f2c3f881073bc1f739e4579376231affbe", size = 10799780, upload-time = "2026-10-27T00:33:58.204Z" }, + { url = "https://files.pythonhosted.org/packages/ec/d9/47171a16739eb7a353936b31c20cf54340531e68c9af7d72fd7a784e235d/ruff-0.17.3-py3-none-win32.whl", hash = "sha256:46539cb031b01fd29ae0a02142483c46640b233ee12bb1c1b690bffa1555d5ca", size = 9908481, upload-time = "2026-10-27T00:34:00.087Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a0/f08c1631bfd81faa6a90eaf70c37c786c11bed2046302b56bb506c25e1a0/ruff-0.17.3-py3-none-win_amd64.whl", hash = "sha256:56b8ffb3f3b3cbccb8b76b71b38261b7ed982ef5d20f5b447b1b61a7f4949b24", size = 10341333, upload-time = "2026-10-27T00:34:02.099Z" }, + { url = "https://files.pythonhosted.org/packages/99/d5/4ad4ed31413c301430918e70d3d38ae6f097af0766cb9ab8c9d502b2a4d6/ruff-0.17.3-py3-none-win_arm64.whl", hash = "sha256:81fce74bcd6be0e9da7c67c7553fd0f1f12964a2052cd728ef917b937a5ca1d9", size = 9854332, upload-time = "2026-10-27T00:34:03.847Z" }, +] + [[package]] name = "sniffio" version = "1.3.1" From 04bced12d2ede86acf7d7e8406343e62e37ffd04 Mon Sep 17 00:00:00 2001 From: VENKATANATHA AV Date: Thu, 5 Nov 2026 22:25:52 +0530 Subject: [PATCH 07/16] feat(excel): add named_slots discovery, scope resolution, and typo suggestion for set_slot --- agentoffice/tools/excel/inspect.py | 31 +++++++++++-- agentoffice/tools/excel/slots.py | 62 +++++++++++++++++++++++++ agentoffice/tools/excel/write.py | 43 +++++++++++++++--- tests/test_excel_inspect.py | 56 +++++++++++++++++++++++ tests/test_excel_write.py | 73 ++++++++++++++++++++++++++++++ 5 files changed, 255 insertions(+), 10 deletions(-) create mode 100644 agentoffice/tools/excel/slots.py diff --git a/agentoffice/tools/excel/inspect.py b/agentoffice/tools/excel/inspect.py index f4f106d..8d1e4c7 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: { @@ -32,30 +42,45 @@ def inspect_workbook( for ws in wb.worksheets for t in ws.tables.values() ] + named_slots = [ + { + "name": name, + "scope": scope, + "ref": defn.attr_text or defn.value, + "kind": (kind := classify_slot(defn)), + "settable": kind == "cell", + } + for name, scope, defn in collect_named_slots(wb) + ] return { "sheet_names": list(sheet_details.keys()), "active_sheet": wb.active.title, "sheet_details": sheet_details, "formulas": formula, "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/slots.py b/agentoffice/tools/excel/slots.py new file mode 100644 index 0000000..966db35 --- /dev/null +++ b/agentoffice/tools/excel/slots.py @@ -0,0 +1,62 @@ +"""Named-slot domain helpers shared by the inspect and write tools.""" + +from openpyxl.utils.cell import range_boundaries +from openpyxl.workbook.defined_name import DefinedName + +from agentoffice.tools.excel.guards import clean_coord + + +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 + """ + try: + dests = list(defn.destinations) + except Exception: + return "formula" + + if len(dests) > 1: + return "multi" + if not dests: + attr = (defn.attr_text or defn.value or "").strip() + return "formula" if attr.startswith("=") else "constant" + + _, coord = dests[0] + try: + min_col, min_row, max_col, max_row = range_boundaries(clean_coord(coord)) + except (ValueError, TypeError): + return "range" + + is_single_cell = ( + None not in (min_col, min_row, max_col, max_row) + and min_col == max_col + and min_row == max_row + ) + return "cell" if is_single_cell else "range" diff --git a/agentoffice/tools/excel/write.py b/agentoffice/tools/excel/write.py index c664326..f0e74ae 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -15,6 +15,7 @@ guard_sheet_unprotected, is_formula, ) +from agentoffice.tools.excel.slots import collect_named_slots from agentoffice.tools.excel.workspace import ExcelWorkspace @@ -98,15 +99,38 @@ def validate( name = operation["name"] value = operation["value"] - defn = wb.defined_names.get(name) - if defn is None: - raise KeyError(f"Named slot '{name}' not found in workbook.") + # 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] + + try: + dests = list(defn.destinations) + except Exception: + # Non-grid expressions crash openpyxl's tokenizer + dests = [] - dests = list(defn.destinations) 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: '{defn.attr_text}'). Slot updates only apply to grid-backed cells." + 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.") @@ -121,7 +145,10 @@ def validate( ) clean_c = clean_coord(cell_coord) - min_col, min_row, max_col, max_row = range_boundaries(clean_c) + 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 @@ -459,7 +486,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), " + "'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). " diff --git a/tests/test_excel_inspect.py b/tests/test_excel_inspect.py index da31abe..d4130e2 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,51 @@ 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") + + 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") + + 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_write.py b/tests/test_excel_write.py index 9ca3e73..b905632 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -633,6 +633,22 @@ def test_set_slot_constant_or_formula_raises_value_error(self): ) 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() @@ -741,3 +757,60 @@ def test_set_slot_formula_injection_protection(self): ], ) 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)) From f06a7b7d29da69faf5e3453c48bfb4f842df597e Mon Sep 17 00:00:00 2001 From: venk-ee Date: Fri, 13 Nov 2026 15:13:04 +0530 Subject: [PATCH 08/16] feat(core): add conversation memory, token tracking, and AgentMemory foundation --- .gitignore | 3 + agentoffice/core/agent.py | 61 ++++++++++++++-- agentoffice/core/memory.py | 70 ++++++++++++++++++ pyproject.toml | 1 + uv.lock | 142 +++++++++++++++++++++++++++++++++++++ 5 files changed, 270 insertions(+), 7 deletions(-) create mode 100644 agentoffice/core/memory.py 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..a9315c7 100644 --- a/agentoffice/core/agent.py +++ b/agentoffice/core/agent.py @@ -16,6 +16,8 @@ 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, ): self.client = OpenAI( api_key=os.getenv("GEMINI_API_KEY"), @@ -24,6 +26,24 @@ def __init__( self.model = model self.system_prompt = system_prompt self.tool_map: dict[str, BaseTool] = {} + self.history = history or [] + self.on_tool_call = on_tool_call + self.last_usage: dict[str, int] = { + "prompt_tokens": 0, + "completion_tokens": 0, + "cached_tokens": 0, + "total_tokens": 0, + } + self.session_usage: dict[str, int] = { + "prompt_tokens": 0, + "completion_tokens": 0, + "cached_tokens": 0, + "total_tokens": 0, + "compactions": 0, + } + + if self.system_prompt and not self.history: + self.history.append({"role": "system", "content": self.system_prompt}) if tools: for tool in tools: self.register_tool(tool) @@ -44,21 +64,36 @@ 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}) + user_message = {"role": "user", "content": message} + self.history.append(user_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, + messages=self.history, ) response_message = response.choices[0].message - messages.append(response_message) + if response.usage: + details = getattr(response.usage, "prompt_tokens_details", None) + cached = (getattr(details, "cached_tokens", 0) or 0) if details else 0 + p_toks = response.usage.prompt_tokens or 0 + c_toks = response.usage.completion_tokens or 0 + t_toks = response.usage.total_tokens or 0 + + self.last_usage = { + "prompt_tokens": p_toks, + "completion_tokens": c_toks, + "cached_tokens": cached, + "total_tokens": t_toks, + } + self.session_usage["prompt_tokens"] += p_toks + self.session_usage["completion_tokens"] += c_toks + self.session_usage["cached_tokens"] += cached + self.session_usage["total_tokens"] += t_toks + self.history.append(response_message) if not response_message.tool_calls: return response_message.content @@ -67,7 +102,10 @@ def run(self, message: str, max_iterations: int = 10) -> str: result = self.execute_tool( tool_call.function.name, tool_call.function.arguments ) - messages.append( + if self.on_tool_call: + print(f"Tool called: {tool_call.function.name}") + self.on_tool_call(tool_call.function.name, tool_call.function.arguments, result) + self.history.append( { "role": "tool", "tool_call_id": tool_call.id, @@ -76,3 +114,12 @@ def run(self, message: str, max_iterations: int = 10) -> str: } ) return "Max iterations reached" + + def clear_history(self): + self.history = [] + if self.system_prompt: + self.history.append({"role": "system", "content": self.system_prompt}) + return self.history + + def compact(self): + pass diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py new file mode 100644 index 0000000..93deb36 --- /dev/null +++ b/agentoffice/core/memory.py @@ -0,0 +1,70 @@ +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, + } + + 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"] = [ + { + "id": tc.id, + "type": "function", + "function": { + "name": tc.function.name, + "arguments": tc.function.arguments, + }, + } + for tc in tool_calls + ] + + self.history.append(msg_dict) diff --git a/pyproject.toml b/pyproject.toml index 1373fef..018f987 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,7 @@ ignore = [ [dependency-groups] dev = [ "pytest>=9.2.0", + "pytest-cov>=7.1.0", "ruff>=0.17.3", ] diff --git a/uv.lock b/uv.lock index ab3ca64..8a0c140 100644 --- a/uv.lock +++ b/uv.lock @@ -20,6 +20,7 @@ dependencies = [ [package.dev-dependencies] dev = [ { name = "pytest" }, + { name = "pytest-cov" }, { name = "ruff" }, ] @@ -34,6 +35,7 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ { name = "pytest", specifier = ">=9.2.0" }, + { name = "pytest-cov", specifier = ">=7.1.0" }, { name = "ruff", specifier = ">=0.17.3" }, ] @@ -68,6 +70,132 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "coverage" +version = "7.17.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/02/9b/639ff6f5b3158999fab6f03cb7597526ad57e15cad0c6cfa9b64bac874dc/coverage-7.17.1.tar.gz", hash = "sha256:5c5c77f95a0e83e6b79eff948d251c9911cfd61d67f5059159fc25b7bc4aec27", size = 995565, upload-time = "2026-11-03T12:38:47.608Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/28/bc914aa69f2dd27cfcebedc62acf472fca357389ba80295a8fa693d6ea59/coverage-7.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:e7429e44cf754fec4baf895307d7b3b906140df82f5c8637777e9cf4227afd87", size = 227529, upload-time = "2026-11-03T12:36:03.283Z" }, + { url = "https://files.pythonhosted.org/packages/97/46/60f46d3219278e53455a4fdb4b755e7c47a0be5b14b89f2c827bf28bc8eb/coverage-7.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:08d773b49e0001ef360a4ee7cf8e7a2101a52007fcc5b46ef56ad1032bd403b7", size = 227947, upload-time = "2026-11-03T12:36:06.739Z" }, + { url = "https://files.pythonhosted.org/packages/27/18/791ca5cf2f4b38c1e3e421d80992a67be4f0c09b5add22ff1e3c164899ea/coverage-7.17.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fa52a8600a7cd6f219b41254bb6a04e000da4a79bb993d3c5b21a625f93425f8", size = 259977, upload-time = "2026-11-03T12:36:08.067Z" }, + { url = "https://files.pythonhosted.org/packages/b8/ed/952fea2330a020cd2bb4315aee09d75716c20f2920d0c3b952e7bf28c992/coverage-7.17.1-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c33792ae97208a5a978ac63b16e70d344946ed1a0db3abb1ea64f1f7b110b5b5", size = 262198, upload-time = "2026-11-03T12:36:09.452Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e6/761f6eefeee17b634b104004214cccd08b0350295ad5d0fd8bec447c5224/coverage-7.17.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:23a49c5949e96b5eae1cf16aa3f37ab6fbcf1a15602cdab9c7c31cf2ebd49307", size = 264294, upload-time = "2026-11-03T12:36:10.725Z" }, + { url = "https://files.pythonhosted.org/packages/ae/dc/4ebdbb17f038dc1e1b8677514af2e832705085327dbe4ca5760914aad83a/coverage-7.17.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:adc720c43f820c91e3b89158ab6b6d162532fd925b0d06ad32baf2bdf130f41c", size = 266304, upload-time = "2026-11-03T12:36:12.32Z" }, + { url = "https://files.pythonhosted.org/packages/8f/34/7597613c900c361370d2a8a7345939072aa8c751fe54dc374ee55fed0bb4/coverage-7.17.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f96ac45a2adb46bc59c2c2c3dc4303501397a906a7ed953832d2f03712a82774", size = 260091, upload-time = "2026-11-03T12:36:13.759Z" }, + { url = "https://files.pythonhosted.org/packages/3d/36/b6b0dc241df22b3f61ef2fd26675fc14309bc3642a6f9c9d9cfb5f689383/coverage-7.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f75d95a0fbbfa4095c307027e9a9286063f12c4f4b9f5df46023f9011175b32e", size = 261993, upload-time = "2026-11-03T12:36:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/f6/c9/c8d973fe07fd67378d49a45085c7fde6f2da5a01329541fb26cc83afd0a1/coverage-7.17.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:06ee57242ba8b5da8a38289f4d70c767529e089c5e5f5492dec1851e3c0981a2", size = 260006, upload-time = "2026-11-03T12:36:16.487Z" }, + { url = "https://files.pythonhosted.org/packages/a0/b0/1f321be70939ffc74ede6b1387f5b727397870cb867382873fa6b23c047d/coverage-7.17.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:eb3e0fa955355da7cca2b4b55d93a4c59b60862e5563f9fac506e35e245cd302", size = 263932, upload-time = "2026-11-03T12:36:17.855Z" }, + { url = "https://files.pythonhosted.org/packages/a7/d5/5cd76e78fceab21289e344768660638b2373aebb4155c6fa76007a2e25b9/coverage-7.17.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:2dbdfb11dd06d10829e13724b4858e61925bbb16c5b396f7d9ccc250bcee916d", size = 259534, upload-time = "2026-11-03T12:36:19.331Z" }, + { url = "https://files.pythonhosted.org/packages/e9/52/265f3b4eef6b51f7cb5ac12f356e186388861530719437b29a8d76f5c218/coverage-7.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:23faef6b1b30335aff610b70f4203ae19b19deb6abd637fa9736f01da4d5588c", size = 260733, upload-time = "2026-11-03T12:36:20.643Z" }, + { url = "https://files.pythonhosted.org/packages/92/b9/fe77b52f2ded65934e0d9a559ca8385400fd54401988004dfe4242af9606/coverage-7.17.1-cp311-cp311-win32.whl", hash = "sha256:110ecef18899cbe49d7a904bb45e3c5f13a7d9c2114ba39daa9a0f3ca9eaf41b", size = 229397, upload-time = "2026-11-03T12:36:22.021Z" }, + { url = "https://files.pythonhosted.org/packages/57/f6/6b856eba8d5bcdb521c9cc41b4c4edf88a4ac61aa04e0e463f67b38872ee/coverage-7.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:c4935efed225aa96f39b5ed7db08baa96996efa85c5a9d3ae2bde3ff8487631b", size = 230001, upload-time = "2026-11-03T12:36:23.372Z" }, + { url = "https://files.pythonhosted.org/packages/77/d8/11cd7ebb5b80f5570705a10f9f3ddd11e6a0b8ff9d6580f46707145dd458/coverage-7.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:6c7182c03dcea5e457553f38ee0005dda781bc26c734d10659365775d5a02fe7", size = 229910, upload-time = "2026-11-03T12:36:24.679Z" }, + { url = "https://files.pythonhosted.org/packages/64/37/0e501535cfd4c71555ac26fc951cd926d6200f20ba5146cb34de429f5e36/coverage-7.17.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7ae17b0127df7298fffec6866d45969620ca70267cf8961c5102a872abfd0198", size = 227626, upload-time = "2026-11-03T12:36:26.151Z" }, + { url = "https://files.pythonhosted.org/packages/84/f8/619e48ba82da0ff2fea7e377e427d5a1d4e918dd90613240145576aa76c9/coverage-7.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b8a8f0b1d662828e7cfd52ba6d4e8d79496d4711057c33daaf29f50414d5f8c6", size = 227859, upload-time = "2026-11-03T12:36:27.659Z" }, + { url = "https://files.pythonhosted.org/packages/45/9c/93a83fdb0120538192d38b0fe77deb6036eae357a803a1e62b9bb7d1cf57/coverage-7.17.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:710a02c4a2f7de5f08c2ecd26fced31099032b8c3fcf2f602e4cef5190008baf", size = 260153, upload-time = "2026-11-03T12:36:29.012Z" }, + { url = "https://files.pythonhosted.org/packages/35/be/2704ac4e51ef9075255314cf547e44f43cd4bde96c9efb7da826ce39ce57/coverage-7.17.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:622f0d4869db8fdfa3a7ee2c6b0207b17abe59b462617599c8c3def27f482d78", size = 263480, upload-time = "2026-11-03T12:36:30.308Z" }, + { url = "https://files.pythonhosted.org/packages/ef/83/64edd51a572196239890825cdfefce0c38f634de439d3d840bbe33e09271/coverage-7.17.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d8ba77c22882009f4f6599ccc88a9170b9c6e69f4464c2ef235e9ca24b62f68", size = 264016, upload-time = "2026-11-03T12:36:31.667Z" }, + { url = "https://files.pythonhosted.org/packages/71/95/c9998e7e718e86f85142a0cbf517d100ba2bb4c068f814245f96a253772c/coverage-7.17.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8ff5288d8b03519e05697cc7065e75c55a10ce4d7581108978b549516c7edaab", size = 266294, upload-time = "2026-11-03T12:36:33.03Z" }, + { url = "https://files.pythonhosted.org/packages/46/b0/73c6276d5c75239b725207e60b19ed23a4d8c564a92232890d7ba9e70bef/coverage-7.17.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6c461a379dbacd1b92c3800f529025e3b85a41a90b97e49d3b004ec690a13847", size = 260386, upload-time = "2026-11-03T12:36:34.463Z" }, + { url = "https://files.pythonhosted.org/packages/3b/57/9374f6513341d07c1a02bdbd37ee7e98fbc8d963da9e71dc4b580ef86994/coverage-7.17.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bf29880edc2dbe589f3bc9fc7ea9a4c81cdce118a69feb52bf4dc420b475ed9b", size = 261901, upload-time = "2026-11-03T12:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/ea/ca/50a4fab6983deb19d0ef8941c64e69e09d9428523c16e38262a0a28d379e/coverage-7.17.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:d416449f86fa1af6a9c1031fbd27ad7c1d30f57945bb52cd28250266c46ae549", size = 260066, upload-time = "2026-11-03T12:36:37.426Z" }, + { url = "https://files.pythonhosted.org/packages/66/db/4c5e12596e68084a59a108712f2a89e5cedf30fc3f2fd8b2b38e62d300a5/coverage-7.17.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a7858779514aa04242f7fd7b4a92dd395d08fe791ba33624187d6c68f96245c6", size = 264114, upload-time = "2026-11-03T12:36:38.937Z" }, + { url = "https://files.pythonhosted.org/packages/bc/9b/2c8bc32551e15080c894d7f7d8c13589c91980923a11a96b51ca7c538eee/coverage-7.17.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:b367f16bf32939fafa8f26669fdb59ab21ee601527ad716aab7cd178ed3bd28f", size = 259566, upload-time = "2026-11-03T12:36:40.514Z" }, + { url = "https://files.pythonhosted.org/packages/f3/54/9cbf5e95496e2f8d8684eea3e7f1f4911375d01c73ccb51b067385c0d77c/coverage-7.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a20b2945e275fe76ed2ed6be6103aa4d8e923b8f2678f1f3dc31c6ec8849c8a1", size = 262053, upload-time = "2026-11-03T12:36:41.975Z" }, + { url = "https://files.pythonhosted.org/packages/d1/3e/ef5728364207026031aac8f068e68f15bf71c1a84046efbca4623617cd2a/coverage-7.17.1-cp312-cp312-win32.whl", hash = "sha256:6c89aa3497bd593e1bfd9f57ebdecc5544387b5e94e6d4c6cb7597565eb551e6", size = 229457, upload-time = "2026-11-03T12:36:43.227Z" }, + { url = "https://files.pythonhosted.org/packages/e9/a9/8830de67aa3b16f94e6cc456dde07db95d0ea8001cf8224340cdb6d47cb4/coverage-7.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:6e6c9759a42cf946ca427dbbd772305516401ff6d280b93cc52e7b11fcedfb2a", size = 230037, upload-time = "2026-11-03T12:36:44.547Z" }, + { url = "https://files.pythonhosted.org/packages/6b/00/a932037e8a27705d8f1aded46edf879d8f2592392dcd025349fa72d9b5a8/coverage-7.17.1-cp312-cp312-win_arm64.whl", hash = "sha256:1c06c40a9fb03ab43ace3ee27a11e61ebf233161fb9ebabfb2b51f78cf1602e0", size = 229843, upload-time = "2026-11-03T12:36:45.821Z" }, + { url = "https://files.pythonhosted.org/packages/04/e0/ff26f5a74cfcfe131bebe09649a9c9dc84a8fe8fed5cbed0117c57f7efeb/coverage-7.17.1-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:9b8d68b2330cda90e1972e78c93c6fd572453c5b4e29594aa98550694efb0466", size = 228775, upload-time = "2026-11-03T12:36:47.054Z" }, + { url = "https://files.pythonhosted.org/packages/df/af/b83c4a7d7ed81458298c137aeefbfb7a088d36fff6fb60a0f8375e731990/coverage-7.17.1-cp313-cp313-android_24_x86_64.whl", hash = "sha256:b975d0bd867eefeff37ba28aee6ee08a0987ca3ce6bfb5e0d3ddc1b40cf3e52e", size = 228845, upload-time = "2026-11-03T12:36:48.362Z" }, + { url = "https://files.pythonhosted.org/packages/52/07/3156d72bb538d05aa4cf51d90a86cc705e9cb570d8a0eeef80880cb21d09/coverage-7.17.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:60002a0ea7f5e5f64006aba9f37aa29a4b1e52756bc0fbbc2471188b2732e4ed", size = 227091, upload-time = "2026-11-03T12:36:49.687Z" }, + { url = "https://files.pythonhosted.org/packages/cb/50/03128c382b303e02a48b1f9658bda6412288fa1d83b478696a08e410c0f6/coverage-7.17.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:80b613bd68caa146d090023a18dfc504eb958ff525e31e6f2368b363502bb1ea", size = 227396, upload-time = "2026-11-03T12:36:51.162Z" }, + { url = "https://files.pythonhosted.org/packages/90/83/b617213e11609d6d5d64afc701e40384bbfb39c9999531ef747b6d1259cb/coverage-7.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8c2e67f95c8de089ba0ff11c7b7ee83ec0890d418e8d0185e863367f5250a087", size = 227516, upload-time = "2026-11-03T12:36:52.897Z" }, + { url = "https://files.pythonhosted.org/packages/44/98/71e36bd7bc121a33c5c78a1f687587802b2806299feb4b9f2fcf21616007/coverage-7.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:56f81ec13a8790a0f2ea30a14d2f39dec2374115eb88cb25cc2c0226f72f8b0e", size = 227781, upload-time = "2026-11-03T12:36:54.144Z" }, + { url = "https://files.pythonhosted.org/packages/04/e8/28f4c350e124242a757b86cd19d71d807eda8b202126c39fb57eb1495f7b/coverage-7.17.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:b7fb16b5c4fa1a37d69204ec5f7b8b187d2cfc54a2c084e2750ceee443748ac0", size = 258947, upload-time = "2026-11-03T12:36:55.461Z" }, + { url = "https://files.pythonhosted.org/packages/64/94/f99d4cbd1b187ac1029cadf293a934f8a2300908d8055b5c9de11577a875/coverage-7.17.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b05c06318fd46706c9055a1acc6f4aa0d3a63b211bf3b6114d3c1feab76e37f2", size = 261858, upload-time = "2026-11-03T12:36:56.804Z" }, + { url = "https://files.pythonhosted.org/packages/58/9c/b91da5d4790ac926e6bede81a1bac0b8e216d2574f5c332c7494d23b88de/coverage-7.17.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8f3bbb5f9c074e97f7082987ead736036aa522cb39b996b8ed9c5aa8eee008be", size = 262791, upload-time = "2026-11-03T12:36:58.072Z" }, + { url = "https://files.pythonhosted.org/packages/4b/15/2527c7e46bcc7f69e792b7a0eba1e70d9effb5ae29f29d704487954975ba/coverage-7.17.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6eb807f5eb02f64eb19f39b63015de046b312b847e3919b639a0ca19ae9a10eb", size = 264857, upload-time = "2026-11-03T12:36:59.79Z" }, + { url = "https://files.pythonhosted.org/packages/b8/83/6cf7a9cc1a4188227dc74e9293dd006e6e76b97e24747452f3b17b300f30/coverage-7.17.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0bf74f2960a3d0f39067bddd658db1331a17828c93102922864699401df82dc7", size = 258994, upload-time = "2026-11-03T12:37:01.07Z" }, + { url = "https://files.pythonhosted.org/packages/98/0d/1f027bbe75df8b9553e87ad49889a288409e25bad00032391678b612c5ab/coverage-7.17.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3da4fe4cd099239c10691ff6deb9fd291e5438ad77c2583cf235a5b9aa9250ae", size = 260950, upload-time = "2026-11-03T12:37:02.553Z" }, + { url = "https://files.pythonhosted.org/packages/a4/25/5f02f89f262a126a90fda3061ea5beb0721202d9b8469b4a50adb85b2e2a/coverage-7.17.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d2c2973dcbcd883ec94305f513b7c05be6359679f25ad7134adf0cc512cf405e", size = 258871, upload-time = "2026-11-03T12:37:03.896Z" }, + { url = "https://files.pythonhosted.org/packages/50/2e/61f046a3ecddb2fc6e44350de857840e01fffbe83246302aa2382e8b9ac5/coverage-7.17.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:deea769f5199ea3e8053d5274e737e84f4a9cfbb1e69330066101825b098aac6", size = 262967, upload-time = "2026-11-03T12:37:05.191Z" }, + { url = "https://files.pythonhosted.org/packages/33/41/a45075de5bb61a646882912b7fc21cd594a83fe9be0ee6c77ffafa3a2ba7/coverage-7.17.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:7fdea302c956e1e85526a294ce64495b0029edc451b4655e2a9a85af6029fa24", size = 258721, upload-time = "2026-11-03T12:37:06.44Z" }, + { url = "https://files.pythonhosted.org/packages/89/ac/a58424f93baf37f1f36a9ad60d622d84482e26b017157e101ad87e965e28/coverage-7.17.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:32141eb9f9d228da33d45baf789736bc3c00a31ea9150aa7f48bbc08cfe2849f", size = 260799, upload-time = "2026-11-03T12:37:08.058Z" }, + { url = "https://files.pythonhosted.org/packages/27/10/9c424a67004ebeff99a03030115c4f8562eefabf0fa2ae889289efa85aa9/coverage-7.17.1-cp313-cp313-win32.whl", hash = "sha256:fc7b1ee12d7376ea85f6d09a272da3011c879e605d2f354d4a1c21c890cb571c", size = 229400, upload-time = "2026-11-03T12:37:09.337Z" }, + { url = "https://files.pythonhosted.org/packages/9e/0c/1b92a40cf24fa09e1bc2e7f9120a312e0b4a792b5f907852cbf64b75ab98/coverage-7.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:26d0fa82cd76c888058c182b8ebb6326578f89f01cc1e576dde76bba8e446261", size = 230128, upload-time = "2026-11-03T12:37:10.69Z" }, + { url = "https://files.pythonhosted.org/packages/c3/af/67fa4bc27bdd15514810ac43c1f1285ca46e9b7af29859655948574f419a/coverage-7.17.1-cp313-cp313-win_arm64.whl", hash = "sha256:ddaca2c745275aede7b7511618aba9e1e17728f772edd1d2016529def73df01d", size = 229853, upload-time = "2026-11-03T12:37:12.173Z" }, + { url = "https://files.pythonhosted.org/packages/80/3b/41fb1e5297e4a14ec9a4f8d620b7c5bc4acd62ad8247a84287c5f05a3611/coverage-7.17.1-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:932a542ea396dc842d0d2882ac95f33242c0029ddc226323c243d7e35978bfde", size = 228890, upload-time = "2026-11-03T12:37:13.495Z" }, + { url = "https://files.pythonhosted.org/packages/80/a0/e7b12a2e40f9af75ed4e64cbf7a9bfd17b9e1834bebd4e46b5965cb0be06/coverage-7.17.1-cp314-cp314-android_24_x86_64.whl", hash = "sha256:6cd9deae02bf24bf16fd72d1c505e81beb4cd0bbfc1b75af8ba1096a8461e62f", size = 229006, upload-time = "2026-11-03T12:37:14.729Z" }, + { url = "https://files.pythonhosted.org/packages/6e/d7/3b69b6d1fdaeb399c6a0f0dee5b94b337f5248c0d0d5b78d736563d7eda6/coverage-7.17.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d1d62732067fe938796db0b460b0788db69cef8f91e802747eb59b2d4c1da9f9", size = 227174, upload-time = "2026-11-03T12:37:16.022Z" }, + { url = "https://files.pythonhosted.org/packages/1f/5a/a7fa52b9a98b98fbbeecc18abbd0bdacb292c4121a31497b39f54146a0d1/coverage-7.17.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:7681bd8f1eb33c778fff244bd06dacabf1e4325fa578c8265367216ac8b5a059", size = 227475, upload-time = "2026-11-03T12:37:17.356Z" }, + { url = "https://files.pythonhosted.org/packages/12/d3/394272eadeb616010db92d4d650b983c54b0596be87685c242b9e1f35b1f/coverage-7.17.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4c948f185d1ca81ee2f1383f1a51387277bf6da5b14a469136031827d51d0ced", size = 227712, upload-time = "2026-11-03T12:37:19.062Z" }, + { url = "https://files.pythonhosted.org/packages/3a/5a/35108cca71cb81b671492aede98a422330bca2558aa07d2cf3ee249ff06e/coverage-7.17.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:9db719b76551607ca01b5b5464f554bec78344fff4a7f09c58f4d55cf9499cd7", size = 227866, upload-time = "2026-11-03T12:37:20.408Z" }, + { url = "https://files.pythonhosted.org/packages/5d/56/21400d3216320c3214bcd88b6d57e7217a4475d37494cfc05b2c2984b6f0/coverage-7.17.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:612b22d9322a0728bc209122847fd48d6353eea92e314f70a1278350dcd48de3", size = 259786, upload-time = "2026-11-03T12:37:21.688Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ba/a8ab57e646da306d854613bbf2972a8a20257fecb5edb13ca2378774af9b/coverage-7.17.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:22edba362121a928bb4bff377915e5ce9b8f2e254239f93f38931de021485d32", size = 262792, upload-time = "2026-11-03T12:37:23.015Z" }, + { url = "https://files.pythonhosted.org/packages/c1/94/5e40670e4893e8e8cb338ae80f7c43e6cc47ce1f49891a2d02b94184605f/coverage-7.17.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f5ee8e36fd04c566fdf3d0e978b343eb1b96e9444484c199a32648cd60b0c2e4", size = 263774, upload-time = "2026-11-03T12:37:24.314Z" }, + { url = "https://files.pythonhosted.org/packages/af/1e/cf67121055a6540e7ad0060dac0d2061bd39ac9bc45fe9168a47c0fa40c9/coverage-7.17.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4a87e4286f0743d0e2a0eba077453595afb6cfb2d0d18b25dea74dc9553e8dad", size = 266251, upload-time = "2026-11-03T12:37:25.535Z" }, + { url = "https://files.pythonhosted.org/packages/18/8d/b2884aa3cee232c924393ba0b7db5d44f520e02a56497e176e5128e9a4ef/coverage-7.17.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:806ab974da8a718697a329a126ae3655f0c8d8bfd12a7ca6c2089a2350ed0485", size = 259565, upload-time = "2026-11-03T12:37:26.798Z" }, + { url = "https://files.pythonhosted.org/packages/fc/11/1c0ccea4d6d35ac421d10f2b210bb61f3e412ad769bd5cc08011876c7577/coverage-7.17.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2cd58acb64ad41f2e01a4d35e35c1060a1dd64699a146caef8c360cf7408083a", size = 261626, upload-time = "2026-11-03T12:37:28.196Z" }, + { url = "https://files.pythonhosted.org/packages/13/1a/ba1b45a8da773e70e5b1cdd08450a5a7cda84ab31a7aeb2c2a8c94361b2b/coverage-7.17.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:354ceff3c2233ed017df0f4d5d65dcd87c350ca6a129fcaa9478a7031957b03c", size = 259668, upload-time = "2026-11-03T12:37:29.526Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ff/5e4ca2c677569f439269a0aab412f8e198751660412b4613ffa3f2473e5f/coverage-7.17.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:b927e5e4708344f94011bcb36a58023f82d2f0c8757ff2c5bf869d5c6ca0aa16", size = 263965, upload-time = "2026-11-03T12:37:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/14/28/d0880224c1f8182e523c454aadd30c89af959b477245463decc7bf166cc1/coverage-7.17.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:65ad67be7eb4c9c48814c35c53f5fc1cf6ba17892b0e183ef3413b991085df62", size = 259298, upload-time = "2026-11-03T12:37:32.282Z" }, + { url = "https://files.pythonhosted.org/packages/5a/64/0f7c0ba50b6d3083478be28b0ffdc1de9d16df1d8abfc920de164e8ef60c/coverage-7.17.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9e85d83d4e41e7ec7fcd026765947ae1b068eb134ba820c8ebb3bba290878972", size = 261408, upload-time = "2026-11-03T12:37:33.999Z" }, + { url = "https://files.pythonhosted.org/packages/92/71/6eab8cd02e941a8473b1e1ed579848e51a3ecaaf8300e1a43d4059d32fa0/coverage-7.17.1-cp314-cp314-win32.whl", hash = "sha256:457ad13b8ec34f5dd607cc9b68c4f6af579dfe1bb6368a25e334976860c03329", size = 229639, upload-time = "2026-11-03T12:37:35.238Z" }, + { url = "https://files.pythonhosted.org/packages/54/42/fb8cedbe674bcdecf37327b014764c98a6bbcbdf2b5faf4ff12ad850555e/coverage-7.17.1-cp314-cp314-win_amd64.whl", hash = "sha256:73a8278e7dcd338e8be66eb66deea97dc290cdc0b50e176bf96095dd498addb3", size = 230271, upload-time = "2026-11-03T12:37:36.738Z" }, + { url = "https://files.pythonhosted.org/packages/08/78/2fc61e1a128f21a6673e3ee5273e494f02489c6f2b818152db534d0c879f/coverage-7.17.1-cp314-cp314-win_arm64.whl", hash = "sha256:3be94c7a728f5bdeb09fe6d0b89542e57e0162a80555a205eec849fc25e45695", size = 230121, upload-time = "2026-11-03T12:37:38.417Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ab/bcbd5e621a8c6e14336fbb0570a2d4268e1259e7ed1f0704701c314608b9/coverage-7.17.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:5208b4cbd83fdbf6cce21fb6137e1986c9c5a5eda6400029ab1b448c5b8f9747", size = 228174, upload-time = "2026-11-03T12:37:39.637Z" }, + { url = "https://files.pythonhosted.org/packages/9a/0b/d0307ba45d2f46d1ebfd421e9eb8201bb3bbdc5edd388432e33c3c2f850b/coverage-7.17.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:efb34d2401f0ef64502f46f9f077b376836cb5cdb98b5d481da534487f7d3f15", size = 228551, upload-time = "2026-11-03T12:37:41.044Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b3/d855372f3e102e3ad9f4bdb8fbdd71df501a932b17b8da9dcd14dd2188f3/coverage-7.17.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:70c1747f2c7b146396da314ec0a7e45ac3dc25b883f39fc7e73cbbb42ee02a6a", size = 268543, upload-time = "2026-11-03T12:37:42.233Z" }, + { url = "https://files.pythonhosted.org/packages/5a/2c/c0dffce72ab78176d2fc9d0c695399394b172a8fef880f73670bd9061759/coverage-7.17.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9412b525747a004fb450432aba6b0ed28891c6d224507020f2c1b05787b9c9da", size = 271097, upload-time = "2026-11-03T12:37:43.461Z" }, + { url = "https://files.pythonhosted.org/packages/cb/54/1e810bf8040b335a9a1434aa29ac278027413b0209638674481a7a4439e6/coverage-7.17.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45946d12c25ceb14967e873a0a46526cfe337b075b6dff917603fd4b5448b90a", size = 273718, upload-time = "2026-11-03T12:37:44.734Z" }, + { url = "https://files.pythonhosted.org/packages/0a/5d/c8c8becee8228047577f7b352902fe34a4cca5691be12120caf3faf71d5d/coverage-7.17.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:76e08d61b3791098befa989da61b899ad0e4b36686534cd0078d68e940a97eed", size = 275208, upload-time = "2026-11-03T12:37:46.06Z" }, + { url = "https://files.pythonhosted.org/packages/26/fb/b00edd3abb50265c7165922b1a6820fd4b34d2917f5d573fa19ae32f73dc/coverage-7.17.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c5b025803be4dee29fafc44aa6bc20255842ab26dc27de19cd0e90c4e8bf6ac9", size = 268433, upload-time = "2026-11-03T12:37:47.833Z" }, + { url = "https://files.pythonhosted.org/packages/45/af/42809663d7a98ba6f95dd976527a0b5d762eed87701dab71af4e14e60adb/coverage-7.17.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:782d2f15f59864202d3939e9bea35b8a6fae6a1d4ef489beca7bacd24058b160", size = 271007, upload-time = "2026-11-03T12:37:49.118Z" }, + { url = "https://files.pythonhosted.org/packages/92/4f/9b93e96f43f8dcc10bba69ac1ade3e707b91581d04847e05f29abf0b0136/coverage-7.17.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:b34dac11d9e03897f64732e3cb3a3e8dba29a7f32a34eacb9536591099fc254f", size = 268434, upload-time = "2026-11-03T12:37:50.413Z" }, + { url = "https://files.pythonhosted.org/packages/5b/ee/bc1983e6715cd211c21dc0389d1d32b789f7dfec31988cc67016aa5ed7a9/coverage-7.17.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:a01f6f44bd92958dba923aa414d1b868a74d175574adb50d50d60157f85da242", size = 272731, upload-time = "2026-11-03T12:37:51.802Z" }, + { url = "https://files.pythonhosted.org/packages/53/29/7a7be7b0f778d48f13908f1bb8eb0d02f9e09448d3852974cc235effbe0f/coverage-7.17.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:62726d1c435d1476de876bd9c6656cc69d157e0e3c419cceb4a8a588db55017c", size = 267851, upload-time = "2026-11-03T12:37:53.083Z" }, + { url = "https://files.pythonhosted.org/packages/f1/80/9b8e09889158a06d9776551d7765ac2627ae21428189af39d21818a314f3/coverage-7.17.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:05858414f6c3557c9ce2d4348215997c3834bdb95a9f6f62e97ab558d1960fc5", size = 269785, upload-time = "2026-11-03T12:37:54.396Z" }, + { url = "https://files.pythonhosted.org/packages/1b/d6/975b76074ce079c3a91248b94bab4f938f5fc39970b384cb292d26b3bfa2/coverage-7.17.1-cp314-cp314t-win32.whl", hash = "sha256:04d8ce47c70cc3f8e760cfabac5c3182f3e03829dc3cecfbfca69ff7d7ee48a6", size = 229953, upload-time = "2026-11-03T12:37:55.731Z" }, + { url = "https://files.pythonhosted.org/packages/bb/34/b55e15f3a916bb9111bad357a44413bc123346f4b72ee002f810c2e8eecc/coverage-7.17.1-cp314-cp314t-win_amd64.whl", hash = "sha256:006453b2515ea4c44a857e07b985429038b164080fa777cabea6d22d2e686325", size = 230884, upload-time = "2026-11-03T12:37:56.971Z" }, + { url = "https://files.pythonhosted.org/packages/d1/73/55ce659eb8a4e31c48ff433f4910dc48fb843a672a64f51fc6dd918d00b1/coverage-7.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:b1dc930b405b761efbfef2b3782ae5d12e22708d8086875c5f1e64318b2b857f", size = 230453, upload-time = "2026-11-03T12:37:58.467Z" }, + { url = "https://files.pythonhosted.org/packages/8d/76/a3443e64fd29e8709f274875d56f9d0c399d13d2146ff785865ec8df7766/coverage-7.17.1-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:67e193d7c93aa93870d78594adfbe2926e9ca8bbc92c963c011092441880edb0", size = 228888, upload-time = "2026-11-03T12:37:59.709Z" }, + { url = "https://files.pythonhosted.org/packages/28/37/de21f8bebe25f3bf95f368451db12e884147514139fd0b8bc18990b2a1bb/coverage-7.17.1-cp315-cp315-android_24_x86_64.whl", hash = "sha256:eea6030a00b96f656016ea58b19d61fad3de7add8340e2e7c3b032d1516561d5", size = 229006, upload-time = "2026-11-03T12:38:01.022Z" }, + { url = "https://files.pythonhosted.org/packages/a5/41/fbf7073c3d6b053106352bfd2b4de8e0c9d27756fccc22d6b0ee20a892e9/coverage-7.17.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:603b5795c56fabfe2d0fcd64685eacba5eff1c7797741fa9b898564bb53a9207", size = 227185, upload-time = "2026-11-03T12:38:02.539Z" }, + { url = "https://files.pythonhosted.org/packages/2e/b1/e758d35cf81d6c4f405f66578ed59c1dcfbb1de5deb5662c5bf23057b6e5/coverage-7.17.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:ae938f631ffdf9183851140a245b44f74e35f25fc7d72edb261546ffbe8e5dde", size = 227486, upload-time = "2026-11-03T12:38:03.816Z" }, + { url = "https://files.pythonhosted.org/packages/7e/f3/c9c3d530bb7bb6142095e5d0a10e9d73107964b4b6345c922809806f6eb7/coverage-7.17.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:65f74048adacb5b031186becc29ce2a12a8aa6f86df86562a947120f5d8e58bc", size = 227716, upload-time = "2026-11-03T12:38:05.14Z" }, + { url = "https://files.pythonhosted.org/packages/1f/40/cc5395ca5038c96637510122da45d58d023e50491a2796cb920eb25ee266/coverage-7.17.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:185ff7348ca70b1663b558a9a8ec66f34451c7a9428627543a0e9575045bed0a", size = 227882, upload-time = "2026-11-03T12:38:06.491Z" }, + { url = "https://files.pythonhosted.org/packages/73/89/5b8f9051cc86dba736c3b35538faa8dc4792e1b7140641531e65661274c6/coverage-7.17.1-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5b0b4793548784c9986a4df4c90b9f672447a25c40783f1a736c7fe171a79cf0", size = 259735, upload-time = "2026-11-03T12:38:07.752Z" }, + { url = "https://files.pythonhosted.org/packages/47/5e/14081087f40abde7006010ba12cc3a0412de8088ab4afb857bf19ece28c9/coverage-7.17.1-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:834a15c96d92d2fa9503674c42615f843cc2f427b93d0a0a6c8e437ec728b1b3", size = 263426, upload-time = "2026-11-03T12:38:09.139Z" }, + { url = "https://files.pythonhosted.org/packages/ba/2c/8c41550d3280cc71640905f0961e734488328627bd367e95451fd2b10df3/coverage-7.17.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:16903fc7d3e60fb9336ade7b12a8343f0381a1ca719d008b3d94a051b520a1c1", size = 264509, upload-time = "2026-11-03T12:38:10.656Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d7/37d4eaf0313b042b26decc8b3d4f90baae3302b0e940074b4720b724392b/coverage-7.17.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6611d1cceadef78a6c136bb94d4e1d1db9024fe8f14b6ba4424e95bb2ac9e1a", size = 266883, upload-time = "2026-11-03T12:38:11.916Z" }, + { url = "https://files.pythonhosted.org/packages/c9/c5/45823bfbb8d0c0d3ac69f6ad1fda556d87ee3d2bc930790ad12d54bc3484/coverage-7.17.1-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:efaa35a6671a9ce23d568e291edc5f97efe689eaa291a6468007cf12d3402e85", size = 260122, upload-time = "2026-11-03T12:38:13.282Z" }, + { url = "https://files.pythonhosted.org/packages/80/22/3b7eb82197af8a7b11ce57b1a3b2ecb891287a9016a77d3587051147ed8e/coverage-7.17.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:125b5146f8624275df6ade5b10d40fb18231ed8f79650a4c522adf7e300db963", size = 262389, upload-time = "2026-11-03T12:38:14.568Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ba/460b53c3ba449af2c70cb2ca5f2583d483b57fb9a15f2a964badbd8c18bd/coverage-7.17.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:08e6db8cef186e7954861705102d50d56f273026fce963135a029b1eed870955", size = 260339, upload-time = "2026-11-03T12:38:15.907Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6e/9a6f1abdcc0ce00de6aa28a2ccb5c622c0f4c4fc2365d4b18d54073eec9b/coverage-7.17.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:3832721ed2cae5d70ee4c6549ef166d16b41ff5c351fa0aae24463b620e65bec", size = 264672, upload-time = "2026-11-03T12:38:17.149Z" }, + { url = "https://files.pythonhosted.org/packages/82/b5/cdd25a9319af55fa504ba6cfc063cd38c1326b7382aa2f73a66e376ce5a6/coverage-7.17.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:b785cc3b82f469db18ca5b123c5eab7cf739d6a99be1fc5b4eb1c395dace5ab4", size = 259651, upload-time = "2026-11-03T12:38:18.475Z" }, + { url = "https://files.pythonhosted.org/packages/d6/80/273c406302ca223d3c72d2a277b1e776b4b21a2391c22fd2c4f41582949c/coverage-7.17.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2f09e92d9f3bc2f7193fd6b354a45817c89d3cebfdd0912900f67c7822af105f", size = 262195, upload-time = "2026-11-03T12:38:19.983Z" }, + { url = "https://files.pythonhosted.org/packages/81/ec/f2d4baf81838d3fe269090b26c98f5c48f6efb482ca365f852d72d0671a3/coverage-7.17.1-cp315-cp315-win32.whl", hash = "sha256:d27344a94963356614e884c5739871190438bce03d2973ff9c13be37d40c7371", size = 229634, upload-time = "2026-11-03T12:38:21.688Z" }, + { url = "https://files.pythonhosted.org/packages/e5/bd/6b6467a081d5da4c5fbd65908070bb9c6b90471738d74239a23ab8ef1e59/coverage-7.17.1-cp315-cp315-win_amd64.whl", hash = "sha256:4ebb24cdee700ba3987aa5c9bc773677cafb6d88edc6f6d9cf79bc0df96b473e", size = 230256, upload-time = "2026-11-03T12:38:23.307Z" }, + { url = "https://files.pythonhosted.org/packages/00/1f/522e0d03e2cdf4a7f2538d6858b64fb95a3193003bb0d79a42b6e1426bc2/coverage-7.17.1-cp315-cp315-win_arm64.whl", hash = "sha256:cbbfb4b9d99766653447f664622168e0d00fef41e6d25a7700eaf6d9f10ae0fd", size = 230120, upload-time = "2026-11-03T12:38:24.514Z" }, + { url = "https://files.pythonhosted.org/packages/bf/47/7ea4bdf31bf175b53067998a6e9b1e4e50fef191f0e3d4c426843dcc1801/coverage-7.17.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:9cd33f622f11927736fcacf884fc6a61605e9c15e489d24dc77cf84c7015ffe5", size = 228174, upload-time = "2026-11-03T12:38:25.837Z" }, + { url = "https://files.pythonhosted.org/packages/14/bd/05a784dffccc384aa939e3d4afbfed7c03dbbd4e56c15fa2262fc665a789/coverage-7.17.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:719b3925108a2ce55a6a9dd5bfd9bf9114c7da1c57b9ea39e59f0fc1ba9d4fa7", size = 228566, upload-time = "2026-11-03T12:38:27.073Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c7/c91c08cb288588711eaf448873536472aa6bec8e97e8f5c4bb7c3472f9a6/coverage-7.17.1-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:15981f51ef23c16de05e740677e1dbc59fd078fbf60ce4cb89687135585a791e", size = 268923, upload-time = "2026-11-03T12:38:28.267Z" }, + { url = "https://files.pythonhosted.org/packages/9c/96/99fc10e4eb6e64e6c613158c79805653366991b93293d18a1a62748e2038/coverage-7.17.1-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:042e093be797b929741fb71238da028f0f2d9d669a3a7ab3588967d77f860b51", size = 271762, upload-time = "2026-11-03T12:38:29.534Z" }, + { url = "https://files.pythonhosted.org/packages/5e/33/fd2aa355efe9cceca9518a7b1f73623ff9a1deb2709cac2b8a096a1773ee/coverage-7.17.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:118f9bacb98a78b5e81c3a4721adcfb1b404942a5a2ec34e0d47a1ee7d772b3d", size = 274461, upload-time = "2026-11-03T12:38:30.828Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ad/e67a208e56876a5b632cfeff790804e331db581c9c5f439235bf40cfc13f/coverage-7.17.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0411fe8b17b7f481cdfe9138bd5b266bb18de124114cfab0cf796b61383ef321", size = 275794, upload-time = "2026-11-03T12:38:32.203Z" }, + { url = "https://files.pythonhosted.org/packages/ad/c9/90717d790b248e1f081f9498d91050969de86d35c687a755db1c48ada4f8/coverage-7.17.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:af1f1c7057ff655f0e2673ca931ab9e69683c26841d7838a9677eb6484c637fd", size = 269483, upload-time = "2026-11-03T12:38:33.602Z" }, + { url = "https://files.pythonhosted.org/packages/3e/bc/162be11201171171e084cb388bdd8a44ccb820733a3cf13bd3da398e46a5/coverage-7.17.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:0bc7c1dbd90be3ddb3bab347deb91996bcb33828aa662acbe83334c55ee0642d", size = 271952, upload-time = "2026-11-03T12:38:34.874Z" }, + { url = "https://files.pythonhosted.org/packages/cb/2d/9ae1eb08020d998d4c9bb6e539b096642129eaec5cc423b0eca6ea216a3a/coverage-7.17.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:7c93a389c1f696ab7ca4764f6629dae187f41aac19ae763e18b35cd60dd7d2b4", size = 268977, upload-time = "2026-11-03T12:38:36.164Z" }, + { url = "https://files.pythonhosted.org/packages/81/6c/33577528fdb8a9d6af5e5f188c28a364d5ed82c57c49dcade7e96682da06/coverage-7.17.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:208ecaaa274e8c97ff8939baa15cfd4e9a5ed0b7a0132206548277e7938e96e7", size = 273587, upload-time = "2026-11-03T12:38:37.412Z" }, + { url = "https://files.pythonhosted.org/packages/5f/a7/6449f497df0012d8e793bab0788d0265d9d2753b33b64fbd47ce8dc50eed/coverage-7.17.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:043af54ef18a5ea6ec5c5347408d21165fd5ddff4f62f63efea32cf3c0ba6ca1", size = 269072, upload-time = "2026-11-03T12:38:38.858Z" }, + { url = "https://files.pythonhosted.org/packages/9f/08/35148999d7e8bef6e596cc056d5a7a403d2c702daa5b51e22d138056b254/coverage-7.17.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:8830f81b489c1fcba77338cf9e176d253117dd886fb58e587a137f9f5bf9b062", size = 270684, upload-time = "2026-11-03T12:38:40.155Z" }, + { url = "https://files.pythonhosted.org/packages/fd/bb/6c0714bcd3ed4b9ec00902281dc17fcf59eb308185ae78e7bea2f037dc20/coverage-7.17.1-cp315-cp315t-win32.whl", hash = "sha256:f705761e5187ba08bbc80fd4b5b6d675e23ecc4f468daee2f5b22cfc8f5ed96b", size = 229942, upload-time = "2026-11-03T12:38:41.524Z" }, + { url = "https://files.pythonhosted.org/packages/5c/34/8d88d51ff9c3da15430c902aca5409a98c01b8d7fad18d631daa53df734b/coverage-7.17.1-cp315-cp315t-win_amd64.whl", hash = "sha256:87e86e0c7712ce64316f649c6d0b30225aaa64da25ff201bf6a1d86d21168d73", size = 230870, upload-time = "2026-11-03T12:38:43.146Z" }, + { url = "https://files.pythonhosted.org/packages/8e/58/9cdb5667edcd9bd5b17293e96620e50e89d425d8a450a1fa57f18e68b5d9/coverage-7.17.1-cp315-cp315t-win_arm64.whl", hash = "sha256:9cd4319b51f18519688baf38e01424ec439a5da5ef034a7e429bc631afa95e63", size = 230443, upload-time = "2026-11-03T12:38:44.433Z" }, + { url = "https://files.pythonhosted.org/packages/18/61/7ad3e5f92557c73044d3dfaf88cc65fb7b1ad589c744e8629af8e6370224/coverage-7.17.1-py3-none-any.whl", hash = "sha256:fda1023828e4a9f4a40ef06783e005f3630f805f839edc679c87f597f33e041f", size = 219074, upload-time = "2026-11-03T12:38:46.229Z" }, +] + [[package]] name = "et-xmlfile" version = "2.0.0" @@ -476,6 +604,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, ] +[[package]] +name = "pytest-cov" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "coverage" }, + { name = "pluggy" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/51/a849f96e117386044471c8ec2bd6cfebacda285da9525c9106aeb28da671/pytest_cov-7.1.0.tar.gz", hash = "sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2", size = 55592, upload-time = "2026-03-21T20:11:16.284Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, +] + [[package]] name = "python-dotenv" version = "1.2.4" From 6c773a8a69f70b2877de12d1086f671fc8b37887 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Tue, 17 Nov 2026 13:08:02 +0530 Subject: [PATCH 09/16] feat:add memory and compaction --- agentoffice/core/agent.py | 78 +++++++++------------------ agentoffice/core/memory.py | 105 +++++++++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 52 deletions(-) diff --git a/agentoffice/core/agent.py b/agentoffice/core/agent.py index a9315c7..db2c9a0 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() @@ -18,6 +19,7 @@ def __init__( tools: list[BaseTool] | None = None, history: list[dict] | None = None, on_tool_call=None, + memory=None, ): self.client = OpenAI( api_key=os.getenv("GEMINI_API_KEY"), @@ -26,24 +28,9 @@ def __init__( self.model = model self.system_prompt = system_prompt self.tool_map: dict[str, BaseTool] = {} - self.history = history or [] self.on_tool_call = on_tool_call - self.last_usage: dict[str, int] = { - "prompt_tokens": 0, - "completion_tokens": 0, - "cached_tokens": 0, - "total_tokens": 0, - } - self.session_usage: dict[str, int] = { - "prompt_tokens": 0, - "completion_tokens": 0, - "cached_tokens": 0, - "total_tokens": 0, - "compactions": 0, - } - - if self.system_prompt and not self.history: - self.history.append({"role": "system", "content": self.system_prompt}) + self.memory = memory or AgentMemory(system_prompt=system_prompt) + if tools: for tool in tools: self.register_tool(tool) @@ -64,36 +51,20 @@ 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: - user_message = {"role": "user", "content": message} - self.history.append(user_message) + 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, tools=tools_schema, - messages=self.history, + messages=self.memory.history, ) response_message = response.choices[0].message if response.usage: - details = getattr(response.usage, "prompt_tokens_details", None) - cached = (getattr(details, "cached_tokens", 0) or 0) if details else 0 - p_toks = response.usage.prompt_tokens or 0 - c_toks = response.usage.completion_tokens or 0 - t_toks = response.usage.total_tokens or 0 - - self.last_usage = { - "prompt_tokens": p_toks, - "completion_tokens": c_toks, - "cached_tokens": cached, - "total_tokens": t_toks, - } - self.session_usage["prompt_tokens"] += p_toks - self.session_usage["completion_tokens"] += c_toks - self.session_usage["cached_tokens"] += cached - self.session_usage["total_tokens"] += t_toks - self.history.append(response_message) + self.memory.record_usage(response.usage) + self.memory.add_assistant_message(response_message) if not response_message.tool_calls: return response_message.content @@ -105,21 +76,24 @@ def run(self, message: str, max_iterations: int = 10) -> str: if self.on_tool_call: print(f"Tool called: {tool_call.function.name}") self.on_tool_call(tool_call.function.name, tool_call.function.arguments, result) - self.history.append( - { - "role": "tool", - "tool_call_id": tool_call.id, - "name": tool_call.function.name, - "content": result, - } - ) - return "Max iterations reached" + self.memory.add_tool_message(tool_call.id, tool_call.function.name, result) + return "Max tool calls reached" def clear_history(self): - self.history = [] - if self.system_prompt: - self.history.append({"role": "system", "content": self.system_prompt}) - return self.history + self.memory.clear_history() + return self.memory.history + + @property + def history(self) -> list[dict]: + return self.memory.history - def compact(self): - pass + @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) \ No newline at end of file diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py index 93deb36..f4f6fd2 100644 --- a/agentoffice/core/memory.py +++ b/agentoffice/core/memory.py @@ -1,3 +1,5 @@ + + class AgentMemory: def __init__( self, @@ -25,6 +27,7 @@ def __init__( "cached_tokens": 0, "total_tokens": 0, "compactions": 0, + "tokens_saved": 0, } def add_user_message(self, content: str) -> None: @@ -68,3 +71,105 @@ def add_assistant_message(self, message) -> None: ] 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 + old_messages = self.history[1: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}") + + 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}"}, + ] + + response = client.chat.completions.create( + model=model, + messages=summary_messages, + ) + if response.usage: + self.record_usage(response.usage) + summary = response.choices[0].message.content + + 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"] += self.last_usage.get("total_tokens", 0) + 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 + From cb529638b03c9b370b2e2f4483baa93049db7960 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Tue, 17 Nov 2026 13:22:48 +0530 Subject: [PATCH 10/16] feat(core): add AgentMemory unit tests --- tests/test_memory.py | 81 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 tests/test_memory.py diff --git a/tests/test_memory.py b/tests/test_memory.py new file mode 100644 index 0000000..2455e5a --- /dev/null +++ b/tests/test_memory.py @@ -0,0 +1,81 @@ +from agentoffice.core.memory import AgentMemory +from unittest.mock import MagicMock + + +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" + From e35a97364cd1ad1296cc27af2fa343d1318ae0d6 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Tue, 17 Nov 2026 14:27:05 +0530 Subject: [PATCH 11/16] fix(core,tools): preserve thought signatures, resolve workspace paths, and add ChatInterface --- agentoffice/core/memory.py | 11 +++++---- agentoffice/interface/chat.py | 34 ++++++++++++++++++++++++++++ agentoffice/tools/excel/workspace.py | 2 +- agentoffice/tools/excel/write.py | 11 ++++++++- tests/test_memory.py | 3 ++- workspace/.gitkeep | 0 6 files changed, 54 insertions(+), 7 deletions(-) create mode 100644 agentoffice/interface/chat.py create mode 100644 workspace/.gitkeep diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py index f4f6fd2..75ca2fd 100644 --- a/agentoffice/core/memory.py +++ b/agentoffice/core/memory.py @@ -58,8 +58,9 @@ def add_assistant_message(self, message) -> None: tool_calls = getattr(message, "tool_calls", None) if tool_calls: - msg_dict["tool_calls"] = [ - { + msg_dict["tool_calls"] = [] + for tc in tool_calls: + tc_data = { "id": tc.id, "type": "function", "function": { @@ -67,8 +68,10 @@ def add_assistant_message(self, message) -> None: "arguments": tc.function.arguments, }, } - for tc in tool_calls - ] + 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) diff --git a/agentoffice/interface/chat.py b/agentoffice/interface/chat.py new file mode 100644 index 0000000..c40e0fd --- /dev/null +++ b/agentoffice/interface/chat.py @@ -0,0 +1,34 @@ +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})") + print(f"\n⚙️ [Tool] {name}({arguments}) -> {result[:120]}") + + +class ChatInterface: + def __init__(self, agent: BaseAgent): + self.agent = agent + + def run(self): + while True: + user_input = input("You: ") + reply = self.agent.run(user_input) + print(f"Agent: {reply}") + + + +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() \ No newline at end of file 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 f0e74ae..c2bda01 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -508,7 +508,16 @@ def __init__(self, workspace: ExcelWorkspace): }, "operations": { "type": "array", - "items": {"type": "object", "required": ["action"]}, + "items": { + "type": "object", + "properties": { + "action": { + "type": "string", + "description": "The operation to perform, e.g. 'write_cells', 'add_sheet'", + }, + }, + "required": ["action"], + }, "description": "List of operations to apply.", }, "overwrite": { diff --git a/tests/test_memory.py b/tests/test_memory.py index 2455e5a..5842c4f 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -1,6 +1,7 @@ -from agentoffice.core.memory import AgentMemory from unittest.mock import MagicMock +from agentoffice.core.memory import AgentMemory + def test_record_usage_with_cache(): memory = AgentMemory() diff --git a/workspace/.gitkeep b/workspace/.gitkeep new file mode 100644 index 0000000..e69de29 From c67f9eeb2648e94bbb31aa2e79d86fdc234c2345 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Tue, 17 Nov 2026 16:00:15 +0530 Subject: [PATCH 12/16] fix(core): isolate callback exceptions, trigger threshold compaction, and preserve tool calls in compaction --- agentoffice/core/agent.py | 24 +++++++++++++++++++----- agentoffice/core/memory.py | 12 ++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/agentoffice/core/agent.py b/agentoffice/core/agent.py index a382b9b..073689e 100644 --- a/agentoffice/core/agent.py +++ b/agentoffice/core/agent.py @@ -52,6 +52,14 @@ def execute_tool(self, name: str, arguments: str) -> str: def run(self, message: str, max_iterations: int = 10) -> str: self.memory.add_user_message(message) + + # Check if we need to compact before making the LLM call + if ( + self.memory.session_usage.get("total_tokens", 0) + > self.memory.token_threshold + ): + self.compact(force=False) + tools_schema = [tool.to_schema() for tool in self.tool_map.values()] or None for turn in range(max_iterations): @@ -73,14 +81,20 @@ def run(self, message: str, max_iterations: int = 10) -> str: result = self.execute_tool( tool_call.function.name, tool_call.function.arguments ) - if self.on_tool_call: - print(f"Tool called: {tool_call.function.name}") - self.on_tool_call( - tool_call.function.name, tool_call.function.arguments, result - ) self.memory.add_tool_message( tool_call.id, tool_call.function.name, result ) + if self.on_tool_call: + print(f"Tool called: {tool_call.function.name}") + try: + self.on_tool_call( + tool_call.function.name, + tool_call.function.arguments, + result, + ) + except Exception: + # Logging/callback failures should never crash the agent's conversation state + pass return "Max tool calls reached" def clear_history(self): diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py index b5ac250..1127efe 100644 --- a/agentoffice/core/memory.py +++ b/agentoffice/core/memory.py @@ -130,6 +130,18 @@ def compact(self, client, model: str, force: bool = True): 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 = [ From 426d86c87638f5d2db4a0cfde8f58ee1914e9000 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Tue, 17 Nov 2026 17:26:04 +0530 Subject: [PATCH 13/16] fix(core): check token budget inside tool loop and isolate tool callbacks --- agentoffice/core/agent.py | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/agentoffice/core/agent.py b/agentoffice/core/agent.py index 073689e..a02828a 100644 --- a/agentoffice/core/agent.py +++ b/agentoffice/core/agent.py @@ -53,16 +53,16 @@ def execute_tool(self, name: str, arguments: str) -> str: def run(self, message: str, max_iterations: int = 10) -> str: self.memory.add_user_message(message) - # Check if we need to compact before making the LLM call - if ( - self.memory.session_usage.get("total_tokens", 0) - > self.memory.token_threshold - ): - self.compact(force=False) - tools_schema = [tool.to_schema() for tool in self.tool_map.values()] or None for turn in range(max_iterations): + # Check token budget before each LLM call to prevent exceeding limits + if ( + self.memory.session_usage.get("total_tokens", 0) + > self.memory.token_threshold + ): + self.compact(force=False) + response = self.client.chat.completions.create( model=self.model, tools=tools_schema, @@ -78,22 +78,28 @@ def run(self, message: str, max_iterations: int = 10) -> str: return response_message.content for tool_call in response_message.tool_calls: - result = self.execute_tool( - tool_call.function.name, tool_call.function.arguments - ) + 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: - print(f"Tool called: {tool_call.function.name}") try: + print(f"Tool called: {tool_call.function.name}") self.on_tool_call( tool_call.function.name, tool_call.function.arguments, result, ) except Exception: - # Logging/callback failures should never crash the agent's conversation state + # Callback failures should never crash other tool executions pass return "Max tool calls reached" From 47fea606b5a531d16c6c1314d43a05ba77c532c1 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 18 Nov 2026 10:11:41 +0530 Subject: [PATCH 14/16] fix: resolve review issues, clean code smells, and add agent tests - memory: preserve first user request during compaction without system prompt - slots: validate direct grid references and reject computed formula slots - write: normalize single-cell range coordinates and preserve relative subfolder paths - read: check cumulative cell limits dynamically and decode escaped apostrophes - agent: streamline compaction checks, honor initial history, and allow client injection - interface: handle interrupts and exit commands cleanly in chat interface - tests: add test_agent.py and expand test coverage for edge cases --- agentoffice/core/agent.py | 16 +-- agentoffice/core/memory.py | 7 +- agentoffice/core/tool.py | 2 +- agentoffice/interface/chat.py | 14 ++- agentoffice/tools/excel/factory.py | 8 +- agentoffice/tools/excel/inspect.py | 6 +- agentoffice/tools/excel/read.py | 15 ++- agentoffice/tools/excel/slots.py | 16 +++ agentoffice/tools/excel/write.py | 32 ++++-- tests/test_agent.py | 150 +++++++++++++++++++++++++++++ tests/test_excel_inspect.py | 3 + tests/test_excel_read.py | 22 +++++ tests/test_excel_write.py | 73 ++++++++++++++ tests/test_memory.py | 49 ++++++++++ 14 files changed, 384 insertions(+), 29 deletions(-) create mode 100644 tests/test_agent.py diff --git a/agentoffice/core/agent.py b/agentoffice/core/agent.py index a02828a..aeb3450 100644 --- a/agentoffice/core/agent.py +++ b/agentoffice/core/agent.py @@ -20,8 +20,9 @@ def __init__( 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/", ) @@ -29,7 +30,12 @@ def __init__( self.system_prompt = system_prompt self.tool_map: dict[str, BaseTool] = {} self.on_tool_call = on_tool_call - self.memory = memory or AgentMemory(system_prompt=system_prompt) + 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: @@ -57,11 +63,7 @@ def run(self, message: str, max_iterations: int = 10) -> str: for turn in range(max_iterations): # Check token budget before each LLM call to prevent exceeding limits - if ( - self.memory.session_usage.get("total_tokens", 0) - > self.memory.token_threshold - ): - self.compact(force=False) + self.compact(force=False) response = self.client.chat.completions.create( model=self.model, diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py index 1127efe..915ef77 100644 --- a/agentoffice/core/memory.py +++ b/agentoffice/core/memory.py @@ -118,7 +118,10 @@ def compact(self, client, model: str, force: bool = True): slice_index = self._find_safe_slice_index() if slice_index is None: return None - old_messages = self.history[1:slice_index] + 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 @@ -162,7 +165,7 @@ def compact(self, client, model: str, force: bool = True): ) if response.usage: self.record_usage(response.usage) - summary = response.choices[0].message.content + summary = response.choices[0].message.content or "" new_history = ( self.history[:1] 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 index 301acdb..ef229c9 100644 --- a/agentoffice/interface/chat.py +++ b/agentoffice/interface/chat.py @@ -5,8 +5,7 @@ def print_tool_call(name: str, arguments: str, result: str) -> None: - # print(f"\n⚙️ [Tool] {name}({arguments})") - print(f"\n⚙️ [Tool] {name}({arguments}) -> {result[:120]}") + print(f"\n[Tool] {name}({arguments}) -> {result[:120]}") class ChatInterface: @@ -15,7 +14,16 @@ def __init__(self, agent: BaseAgent): def run(self): while True: - user_input = input("You: ") + 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 reply = self.agent.run(user_input) print(f"Agent: {reply}") 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/inspect.py b/agentoffice/tools/excel/inspect.py index 8d1e4c7..593f8ef 100644 --- a/agentoffice/tools/excel/inspect.py +++ b/agentoffice/tools/excel/inspect.py @@ -30,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() @@ -54,9 +54,9 @@ def inspect_workbook( ] 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, } diff --git a/agentoffice/tools/excel/read.py b/agentoffice/tools/excel/read.py index 066ad4b..f7ff2fe 100644 --- a/agentoffice/tools/excel/read.py +++ b/agentoffice/tools/excel/read.py @@ -17,7 +17,7 @@ def _resolve_sheet_and_coords( """Resolve worksheet and coordinate string from 'Sheet!A1' or 'A1'.""" if "!" in range_str: sheet_name, coords = range_str.split("!", 1) - clean_sheet = sheet_name.strip("'") + 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 @@ -60,16 +60,23 @@ def read_ranges( """Reads one or more A1 ranges from a workbook in a single atomic turn.""" with workspace.open_workbook(file_name, data_only=data_only) as workbook: - total_cells = sum( + initial_total = sum( _count_range_cells(*_resolve_sheet_and_coords(workbook, r, file_name)) for r in ranges ) - if total_cells > max_cells: - raise ValueError(format_limit_exceeded_error(total_cells, max_cells)) + 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: 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}) diff --git a/agentoffice/tools/excel/slots.py b/agentoffice/tools/excel/slots.py index 966db35..731e89a 100644 --- a/agentoffice/tools/excel/slots.py +++ b/agentoffice/tools/excel/slots.py @@ -1,11 +1,24 @@ """Named-slot domain helpers shared by the inspect and write tools.""" +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 +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("=")) + return len(tok.items) == 1 and tok.items[0].subtype == "RANGE" + except Exception: + return False + + def collect_named_slots(workbook) -> list[tuple[str, str, DefinedName]]: """Collect user-defined named slots from every scope. @@ -48,6 +61,9 @@ def classify_slot(defn: DefinedName) -> str: attr = (defn.attr_text or defn.value or "").strip() return "formula" if attr.startswith("=") else "constant" + if not is_direct_grid_reference(defn): + return "formula" + _, coord = dests[0] try: min_col, min_row, max_col, max_row = range_boundaries(clean_coord(coord)) diff --git a/agentoffice/tools/excel/write.py b/agentoffice/tools/excel/write.py index c2bda01..20d892d 100644 --- a/agentoffice/tools/excel/write.py +++ b/agentoffice/tools/excel/write.py @@ -15,7 +15,10 @@ guard_sheet_unprotected, is_formula, ) -from agentoffice.tools.excel.slots import collect_named_slots +from agentoffice.tools.excel.slots import ( + collect_named_slots, + is_direct_grid_reference, +) from agentoffice.tools.excel.workspace import ExcelWorkspace @@ -120,6 +123,13 @@ def validate( ) 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: @@ -136,9 +146,9 @@ def validate( raise ValueError(f"Named slot '{name}' points to multiple destinations.") sheet_title, cell_coord = dests[0] - sheet_name = (sheet_title.strip("'") if sheet_title else None) or ( - wb.active.title if wb.active else None - ) + 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." @@ -160,10 +170,13 @@ def validate( 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": clean_c, "value": value}, + {"sheet": sheet_name, "cell": single_cell_coord, "value": value}, tracker, ) @@ -363,7 +376,7 @@ def _resolve_dest_path( output_name = str(output_filename) else: dest_path = src_path - output_name = src_path.name + output_name = str(file_name) return src_path, dest_path, output_name @@ -513,7 +526,12 @@ def __init__(self, workspace: ExcelWorkspace): "properties": { "action": { "type": "string", - "description": "The operation to perform, e.g. 'write_cells', 'add_sheet'", + "enum": [ + "set_cell", + "set_slot", + "append_table", + ], + "description": "The operation action: 'set_cell', 'set_slot', or 'append_table'.", }, }, "required": ["action"], diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..afd44e9 --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,150 @@ +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.") diff --git a/tests/test_excel_inspect.py b/tests/test_excel_inspect.py index d4130e2..f74b881 100644 --- a/tests/test_excel_inspect.py +++ b/tests/test_excel_inspect.py @@ -90,6 +90,9 @@ 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") diff --git a/tests/test_excel_read.py b/tests/test_excel_read.py index f59f453..ea4664f 100644 --- a/tests/test_excel_read.py +++ b/tests/test_excel_read.py @@ -114,3 +114,25 @@ def test_read_ranges_unbounded_columns_and_rows(self): 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"]]) diff --git a/tests/test_excel_write.py b/tests/test_excel_write.py index b905632..218a3aa 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -814,3 +814,76 @@ def test_set_slot_ambiguous_name_rejected(self): 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_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 index 679a1b8..fe3f48c 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -90,3 +90,52 @@ def test_find_safe_slice_index_finds_user_boundary(): 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"] From 318bb6cfdec447bf35f463d57e428eba061a8899 Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 18 Nov 2026 11:06:25 +0530 Subject: [PATCH 15/16] fix(core,tools): handle empty summary fallback, chat request errors, exclamation in sheet titles, and indirect slot names --- agentoffice/core/memory.py | 4 +++- agentoffice/interface/chat.py | 7 ++++-- agentoffice/tools/excel/read.py | 2 +- agentoffice/tools/excel/slots.py | 37 ++++++++++++++++++++++++++++++-- tests/test_excel_inspect.py | 3 +++ tests/test_excel_read.py | 10 +++++++++ tests/test_excel_write.py | 24 +++++++++++++++++++++ tests/test_memory.py | 21 ++++++++++++++++++ 8 files changed, 102 insertions(+), 6 deletions(-) diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py index 915ef77..05c770a 100644 --- a/agentoffice/core/memory.py +++ b/agentoffice/core/memory.py @@ -165,7 +165,9 @@ def compact(self, client, model: str, force: bool = True): ) if response.usage: self.record_usage(response.usage) - summary = response.choices[0].message.content or "" + summary = (response.choices[0].message.content or "").strip() + if not summary: + return None new_history = ( self.history[:1] diff --git a/agentoffice/interface/chat.py b/agentoffice/interface/chat.py index ef229c9..529900c 100644 --- a/agentoffice/interface/chat.py +++ b/agentoffice/interface/chat.py @@ -24,8 +24,11 @@ def run(self): break if not user_input.strip(): continue - reply = self.agent.run(user_input) - print(f"Agent: {reply}") + try: + reply = self.agent.run(user_input) + print(f"Agent: {reply}") + except Exception as e: + print(f"Error during request: {e}") if __name__ == "__main__": diff --git a/agentoffice/tools/excel/read.py b/agentoffice/tools/excel/read.py index f7ff2fe..c1dcd16 100644 --- a/agentoffice/tools/excel/read.py +++ b/agentoffice/tools/excel/read.py @@ -16,7 +16,7 @@ def _resolve_sheet_and_coords( ) -> tuple[Worksheet, str]: """Resolve worksheet and coordinate string from 'Sheet!A1' or 'A1'.""" if "!" in range_str: - sheet_name, coords = range_str.split("!", 1) + 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}'") diff --git a/agentoffice/tools/excel/slots.py b/agentoffice/tools/excel/slots.py index 731e89a..29516c0 100644 --- a/agentoffice/tools/excel/slots.py +++ b/agentoffice/tools/excel/slots.py @@ -1,11 +1,34 @@ """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.""" @@ -14,7 +37,9 @@ def is_direct_grid_reference(defn: DefinedName) -> bool: return False try: tok = Tokenizer("=" + raw.lstrip("=")) - return len(tok.items) == 1 and tok.items[0].subtype == "RANGE" + 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 @@ -61,9 +86,17 @@ def classify_slot(defn: DefinedName) -> str: attr = (defn.attr_text or defn.value or "").strip() return "formula" if attr.startswith("=") else "constant" - if not is_direct_grid_reference(defn): + raw = (defn.attr_text or defn.value or "").strip() + try: + tok = Tokenizer("=" + raw.lstrip("=")) + if len(tok.items) > 1: + return "formula" + except Exception: return "formula" + if not is_direct_grid_reference(defn): + return "formula" if raw.startswith("=") else "range" + _, coord = dests[0] try: min_col, min_row, max_col, max_row = range_boundaries(clean_coord(coord)) diff --git a/tests/test_excel_inspect.py b/tests/test_excel_inspect.py index f74b881..984cfa7 100644 --- a/tests/test_excel_inspect.py +++ b/tests/test_excel_inspect.py @@ -99,6 +99,9 @@ def test_classify_slot_handles_formula_expressions_and_broken_refs(self): 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") + def test_collect_named_slots_filters_internal_and_hidden(self): wb = openpyxl.Workbook() wb.defined_names.add(DefinedName("TaxRate", attr_text="Summary!$B$2")) diff --git a/tests/test_excel_read.py b/tests/test_excel_read.py index ea4664f..fe9b71e 100644 --- a/tests/test_excel_read.py +++ b/tests/test_excel_read.py @@ -136,3 +136,13 @@ def test_read_ranges_escaped_apostrophe_sheet_name(self): 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 218a3aa..14867c8 100644 --- a/tests/test_excel_write.py +++ b/tests/test_excel_write.py @@ -834,6 +834,30 @@ def test_set_slot_computed_expression_rejected(self): ) 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() diff --git a/tests/test_memory.py b/tests/test_memory.py index fe3f48c..16abc41 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -139,3 +139,24 @@ def test_compact_with_system_prompt_preserves_system_prompt(): 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_len = len(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 len(memory.history) == initial_len + assert memory.history[1]["content"] == "Turn 1" From cf708e485e42b981517c922ad6497045e438019b Mon Sep 17 00:00:00 2001 From: venk-ee Date: Wed, 18 Nov 2026 13:25:36 +0530 Subject: [PATCH 16/16] fix(core,tools): isolate summary usage, recover unanswered user messages, and refine slot classification --- agentoffice/core/agent.py | 85 +++++++++++++++++------------- agentoffice/core/memory.py | 24 ++++++++- agentoffice/interface/chat.py | 6 ++- agentoffice/tools/excel/inspect.py | 8 ++- agentoffice/tools/excel/slots.py | 76 ++++++++++++++++---------- tests/test_agent.py | 14 +++++ tests/test_excel_inspect.py | 22 ++++++++ tests/test_memory.py | 39 ++++++++++++-- 8 files changed, 202 insertions(+), 72 deletions(-) diff --git a/agentoffice/core/agent.py b/agentoffice/core/agent.py index aeb3450..5a0b9e5 100644 --- a/agentoffice/core/agent.py +++ b/agentoffice/core/agent.py @@ -57,53 +57,64 @@ 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: + 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): - # Check token budget before each LLM call to prevent exceeding limits - self.compact(force=False) + try: + for turn in range(max_iterations): + # Check token budget before each LLM call to prevent exceeding limits + self.compact(force=False) + + response = self.client.chat.completions.create( + model=self.model, + tools=tools_schema, + messages=self.memory.history, + ) - response = self.client.chat.completions.create( - model=self.model, - tools=tools_schema, - messages=self.memory.history, - ) + response_message = response.choices[0].message + if response.usage: + self.memory.record_usage(response.usage) + self.memory.add_assistant_message(response_message) - response_message = response.choices[0].message - if response.usage: - self.memory.record_usage(response.usage) - self.memory.add_assistant_message(response_message) + if not response_message.tool_calls: + return response_message.content - 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}" - for tool_call in response_message.tool_calls: - try: - result = self.execute_tool( - tool_call.function.name, tool_call.function.arguments + self.memory.add_tool_message( + tool_call.id, tool_call.function.name, result ) - 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" + 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() diff --git a/agentoffice/core/memory.py b/agentoffice/core/memory.py index 05c770a..d3eb6ee 100644 --- a/agentoffice/core/memory.py +++ b/agentoffice/core/memory.py @@ -159,12 +159,32 @@ def compact(self, client, model: str, force: bool = True): {"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: - self.record_usage(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 @@ -183,7 +203,7 @@ def compact(self, client, model: str, force: bool = True): new_history.extend(self.history[slice_index:]) self.history = new_history self.session_usage["compactions"] += 1 - self.session_usage["tokens_saved"] += self.last_usage.get("total_tokens", 0) + self.session_usage["tokens_saved"] += tokens_before return summary def _find_safe_slice_index(self, keep_ratio: float = 0.25) -> int: diff --git a/agentoffice/interface/chat.py b/agentoffice/interface/chat.py index 529900c..d36092a 100644 --- a/agentoffice/interface/chat.py +++ b/agentoffice/interface/chat.py @@ -28,7 +28,11 @@ def run(self): reply = self.agent.run(user_input) print(f"Agent: {reply}") except Exception as e: - print(f"Error during request: {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__": diff --git a/agentoffice/tools/excel/inspect.py b/agentoffice/tools/excel/inspect.py index 593f8ef..9825204 100644 --- a/agentoffice/tools/excel/inspect.py +++ b/agentoffice/tools/excel/inspect.py @@ -42,15 +42,19 @@ 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", + "settable": (kind == "cell" and name_counts[name] == 1), } - for name, scope, defn in collect_named_slots(wb) + for name, scope, defn in raw_slots ] return { "sheet_names": list(sheet_details.keys()), diff --git a/agentoffice/tools/excel/slots.py b/agentoffice/tools/excel/slots.py index 29516c0..fdf0078 100644 --- a/agentoffice/tools/excel/slots.py +++ b/agentoffice/tools/excel/slots.py @@ -75,37 +75,59 @@ def classify_slot(defn: DefinedName) -> str: 'formula' - formula definition, not a grid reference 'multi' - resolves to more than one destination """ - try: - dests = list(defn.destinations) - except Exception: - return "formula" - - if len(dests) > 1: - return "multi" - if not dests: - attr = (defn.attr_text or defn.value or "").strip() - return "formula" if attr.startswith("=") else "constant" - raw = (defn.attr_text or defn.value or "").strip() + if not raw: + return "constant" + try: tok = Tokenizer("=" + raw.lstrip("=")) - if len(tok.items) > 1: - return "formula" except Exception: return "formula" - if not is_direct_grid_reference(defn): - return "formula" if raw.startswith("=") else "range" + 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" - _, coord = dests[0] - try: - min_col, min_row, max_col, max_row = range_boundaries(clean_coord(coord)) - except (ValueError, TypeError): - return "range" - - is_single_cell = ( - None not in (min_col, min_row, max_col, max_row) - and min_col == max_col - and min_row == max_row - ) - return "cell" if is_single_cell else "range" + return "formula" diff --git a/tests/test_agent.py b/tests/test_agent.py index afd44e9..1875583 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -148,3 +148,17 @@ def crashing_callback(name, args, res): 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_inspect.py b/tests/test_excel_inspect.py index 984cfa7..e424c73 100644 --- a/tests/test_excel_inspect.py +++ b/tests/test_excel_inspect.py @@ -102,6 +102,28 @@ def test_classify_slot_handles_formula_expressions_and_broken_refs(self): 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")) diff --git a/tests/test_memory.py b/tests/test_memory.py index 16abc41..ef98c2d 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -148,7 +148,7 @@ def test_compact_returns_none_and_keeps_history_when_summary_empty(): memory.add_user_message("Turn 2") memory.add_assistant_message({"role": "assistant", "content": "R2"}) - initial_len = len(memory.history) + initial_history = [dict(m) for m in memory.history] mock_client = MagicMock() mock_choice = MagicMock() @@ -158,5 +158,38 @@ def test_compact_returns_none_and_keeps_history_when_summary_empty(): summary = memory.compact(mock_client, model="mock-model", force=True) assert summary is None - assert len(memory.history) == initial_len - assert memory.history[1]["content"] == "Turn 1" + 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