| 1 | # Copyright 2026 Google LLC |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | import datetime |
| 16 | import json |
| 17 | import os |
| 18 | from typing import Any, Dict, List |
| 19 | |
| 20 | |
| 21 | class HistoryLogger: |
| 22 | def __init__(self, log_dir: str = "~/.config/colab-cli/history"): |
| 23 | self.log_dir = os.path.expanduser(log_dir) |
| 24 | os.makedirs(self.log_dir, exist_ok=True) |
| 25 | |
| 26 | def _get_log_path(self, session_name: str) -> str: |
| 27 | return os.path.join(self.log_dir, f"{session_name}.jsonl") |
| 28 | |
| 29 | def log_event(self, session_name: str, event_type: str, data: Dict[str, Any]): |
| 30 | """ |
| 31 | Appends a structured event to the session's history file. |
| 32 | |
| 33 | event_types: |
| 34 | - session_created |
| 35 | - session_terminated |
| 36 | - execution (code + outputs) |
| 37 | - input_requested (stdin prompts/replies) |
| 38 | - file_operation (ls, rm, upload, download) |
| 39 | - automation (auth, install, drivemount) |
| 40 | """ |
| 41 | log_path = self._get_log_path(session_name) |
| 42 | event = { |
| 43 | "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(), |
| 44 | "event_type": event_type, |
| 45 | **data, |
| 46 | } |
| 47 | with open(log_path, "a", encoding="utf-8") as f: |
| 48 | f.write(json.dumps(event) + "\n") |
| 49 | |
| 50 | def list_sessions(self) -> List[str]: |
| 51 | if not os.path.exists(self.log_dir): |
| 52 | return [] |
| 53 | return [f[:-6] for f in os.listdir(self.log_dir) if f.endswith(".jsonl")] |
| 54 | |
| 55 | def get_history(self, session_name: str) -> List[Dict[str, Any]]: |
| 56 | log_path = self._get_log_path(session_name) |
| 57 | if not os.path.exists(log_path): |
| 58 | return [] |
| 59 | |
| 60 | history = [] |
| 61 | with open(log_path, "r", encoding="utf-8") as f: |
| 62 | for line in f: |
| 63 | if line.strip(): |
| 64 | history.append(json.loads(line)) |
| 65 | return history |