-
Notifications
You must be signed in to change notification settings - Fork 628
Expand file tree
/
Copy pathpre_compact.py
More file actions
executable file
·103 lines (81 loc) · 3.21 KB
/
Copy pathpre_compact.py
File metadata and controls
executable file
·103 lines (81 loc) · 3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "python-dotenv",
# ]
# ///
import argparse
import json
import os
import sys
from pathlib import Path
from datetime import datetime
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # dotenv is optional
from _log_common import append_log_data, get_log_path
def backup_transcript(transcript_path, trigger):
"""Create a backup of the transcript before compaction."""
try:
if not os.path.exists(transcript_path):
return
# Create backup directory
backup_dir = get_log_path() / "transcript_backups"
backup_dir.mkdir(parents=True, exist_ok=True)
# Generate backup filename with timestamp and trigger type
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
session_name = Path(transcript_path).stem
backup_name = f"{session_name}_pre_compact_{trigger}_{timestamp}.jsonl"
backup_path = backup_dir / backup_name
# Copy transcript to backup
import shutil
shutil.copy2(transcript_path, backup_path)
return str(backup_path)
except Exception:
return None
def main():
try:
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--backup', action='store_true',
help='Create backup of transcript before compaction')
parser.add_argument('--verbose', action='store_true',
help='Print verbose output')
args = parser.parse_args()
# Read JSON input from stdin
input_data = json.loads(sys.stdin.read())
# Extract fields
session_id = input_data.get('session_id', 'unknown')
transcript_path = input_data.get('transcript_path', '')
trigger = input_data.get('trigger', 'unknown') # "manual" or "auto"
custom_instructions = input_data.get('custom_instructions', '')
# Log the pre-compact event
append_log_data("pre_compact.json", input_data)
# Create backup if requested
backup_path = None
if args.backup and transcript_path:
backup_path = backup_transcript(transcript_path, trigger)
# Provide feedback based on trigger type
if args.verbose:
if trigger == "manual":
message = f"Preparing for manual compaction (session: {session_id[:8]}...)"
if custom_instructions:
message += f"\nCustom instructions: {custom_instructions[:100]}..."
else: # auto
message = f"Auto-compaction triggered due to full context window (session: {session_id[:8]}...)"
if backup_path:
message += f"\nTranscript backed up to: {backup_path}"
print(message)
# Success - compaction will proceed
sys.exit(0)
except json.JSONDecodeError:
# Handle JSON decode errors gracefully
sys.exit(0)
except Exception:
# Handle any other errors gracefully
sys.exit(0)
if __name__ == '__main__':
main()