gemini-chat-sync 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ """Dual-use incremental backup and sync for Google Gemini Web chats."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ try:
8
+ __version__ = version('gemini-chat-sync')
9
+ except PackageNotFoundError:
10
+ __version__ = '0.0.0-dev'
11
+
12
+ __all__ = ['__version__']
@@ -0,0 +1,182 @@
1
+ """Dual-use CLI for gemini-chat-sync (sync/export + multi-agent skill installer)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import fcntl
7
+ import json
8
+ import os
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import urllib.request
13
+ from pathlib import Path
14
+
15
+ from gemini_chat_sync import __version__
16
+ from gemini_chat_sync.sessions import parse_marked_deletions, rebuild_sessions
17
+
18
+ PROXY_VARS = ('http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'all_proxy', 'ALL_PROXY')
19
+
20
+
21
+ def find_browser_use_binary() -> str | None:
22
+ """Prefer browser-use installed alongside this Python/uv tool, then fall back to PATH."""
23
+ sibling = Path(sys.executable).resolve().parent / ('browser-use.exe' if os.name == 'nt' else 'browser-use')
24
+ if sibling.is_file() and os.access(sibling, os.X_OK):
25
+ return str(sibling)
26
+ return shutil.which('browser-use')
27
+
28
+
29
+ def clean_env(cdp_url: str | None, daemon: str | None) -> dict[str, str]:
30
+ env = {k: v for k, v in os.environ.items() if k not in PROXY_VARS}
31
+ if cdp_url:
32
+ env['BU_CDP_URL'] = cdp_url
33
+ if daemon:
34
+ env['BU_NAME'] = daemon
35
+ return env
36
+
37
+
38
+ def check_cdp_reachable(cdp_url: str) -> tuple[bool, str]:
39
+ url = cdp_url.rstrip('/') + '/json/version'
40
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
41
+ try:
42
+ with opener.open(url, timeout=3.0) as resp:
43
+ data = json.loads(resp.read().decode('utf-8'))
44
+ return True, f"{data.get('Browser', 'Chrome')} ({url})"
45
+ except Exception as e:
46
+ return False, f'{url}: {e}'
47
+
48
+
49
+ def run_doctor(out_dir: Path, cdp_url: str | None, daemon: str | None) -> int:
50
+ ok = True
51
+ bu_bin = find_browser_use_binary()
52
+ print(f"[{'OK' if bu_bin else 'FAIL'}] browser-use binary: {bu_bin or 'not found in PATH or tool venv'}")
53
+ if not bu_bin:
54
+ ok = False
55
+
56
+ if cdp_url:
57
+ cdp_ok, detail = check_cdp_reachable(cdp_url)
58
+ print(f"[{'OK' if cdp_ok else 'FAIL'}] CDP endpoint: {detail}")
59
+ if not cdp_ok:
60
+ ok = False
61
+ else:
62
+ print('[INFO] CDP endpoint: local default Chrome (no --cdp-url / BU_CDP_URL set)')
63
+
64
+ print(f"[INFO] Daemon name (BU_NAME): {daemon or '(default)'}")
65
+ print(f"[{'OK' if out_dir.exists() else 'WARN'}] Output directory: {out_dir}")
66
+
67
+ marked = parse_marked_deletions(out_dir / 'sessions.md')
68
+ print(f'[INFO] Marked for deletion in sessions.md: {len(marked)} {marked if marked else ""}'.strip())
69
+ return 0 if ok else 1
70
+
71
+
72
+ def parse_cids(raw_cids: list[str] | None) -> list[str]:
73
+ if not raw_cids:
74
+ return []
75
+ out: list[str] = []
76
+ for item in raw_cids:
77
+ for part in item.split(','):
78
+ p = part.strip()
79
+ if p and p not in out:
80
+ out.append(p)
81
+ return out
82
+
83
+
84
+ def _build_sync_parser() -> argparse.ArgumentParser:
85
+ default_out = Path(os.environ.get('GEMINI_SYNC_DIR') or Path.cwd())
86
+ parser = argparse.ArgumentParser(
87
+ prog='gemini-chat-sync',
88
+ description='Incremental backup, overview indexing, and bidirectional sync for Google Gemini Web chats. Run `gemini-chat-sync skill install` to install the Agent Skill.',
89
+ )
90
+ parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
91
+ parser.add_argument(
92
+ '--out-dir',
93
+ type=Path,
94
+ default=default_out,
95
+ help='Backup root directory (default: $GEMINI_SYNC_DIR or current working directory)',
96
+ )
97
+ parser.add_argument(
98
+ '--mode',
99
+ choices=['overview', 'sync', 'full'],
100
+ default='sync',
101
+ help='overview=sidebar index only, sync=backward-delta (default), full=full re-export',
102
+ )
103
+ parser.add_argument('--cid', action='append', help='Target specific chat ID(s); repeatable or comma-separated')
104
+ parser.add_argument('--no-canvas', action='store_true', help='Skip exporting Canvas documents and HTML demos')
105
+ parser.add_argument('--no-attachments', action='store_true', help='Skip exporting attachments and images')
106
+ parser.add_argument('--dry-run', action='store_true', help='Inspect changes and marked deletions without writing or deleting')
107
+ parser.add_argument('--apply-deletes', action='store_true', help='Execute deletions for chats marked `Löschen: [x]` in sessions.md')
108
+ parser.add_argument('--purge-local', action='store_true', help='With --apply-deletes: also remove local chat folder instead of archiving')
109
+ parser.add_argument('--rebuild-only', action='store_true', help='Only rebuild sessions.md from local metadata (no browser)')
110
+ parser.add_argument('--doctor', action='store_true', help='Run preflight checks (browser-use, CDP endpoint, out-dir)')
111
+ parser.add_argument('--cdp-url', default=os.environ.get('BU_CDP_URL'), help='Remote CDP URL (e.g. http://127.0.0.1:9223 for WSL2)')
112
+ parser.add_argument('--daemon', default=os.environ.get('BU_NAME'), help='browser-use daemon name (e.g. win-dev)')
113
+ return parser
114
+
115
+
116
+ def main(argv: list[str] | None = None) -> int:
117
+ args_list = list(sys.argv[1:] if argv is None else argv)
118
+
119
+ # Delegate `gemini-chat-sync skill ...` just like `browser-use skill ...`
120
+ if args_list and args_list[0] == 'skill':
121
+ from gemini_chat_sync.skills.install import handle
122
+
123
+ return handle(args_list[1:])
124
+
125
+ parser = _build_sync_parser()
126
+ args = parser.parse_args(args_list)
127
+ out_dir = args.out_dir.resolve()
128
+
129
+ if args.doctor:
130
+ return run_doctor(out_dir, args.cdp_url, args.daemon)
131
+
132
+ if args.rebuild_only:
133
+ stats = rebuild_sessions(out_dir)
134
+ print(json.dumps({'rebuilt': stats}, ensure_ascii=False, indent=2))
135
+ return 0
136
+
137
+ bu_bin = find_browser_use_binary()
138
+ if not bu_bin:
139
+ print('ERROR: `browser-use` not found. Install via `uv tool install gemini-chat-sync` or `uv tool install browser-use`.', file=sys.stderr)
140
+ return 1
141
+
142
+ if args.cdp_url:
143
+ cdp_ok, detail = check_cdp_reachable(args.cdp_url)
144
+ if not cdp_ok:
145
+ print(f'ERROR: CDP endpoint unreachable ({detail}). Start Chrome with remote debugging first.', file=sys.stderr)
146
+ return 1
147
+
148
+ out_dir.mkdir(parents=True, exist_ok=True)
149
+ lock_path = out_dir / '.sync.lock'
150
+ with lock_path.open('w', encoding='utf-8') as lock_f:
151
+ try:
152
+ fcntl.flock(lock_f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
153
+ except BlockingIOError:
154
+ print(f'ERROR: Another sync is already running (lock held: {lock_path}).', file=sys.stderr)
155
+ return 1
156
+
157
+ marked_deletes = parse_marked_deletions(out_dir / 'sessions.md')
158
+ pkg_src_dir = Path(__file__).resolve().parent.parent
159
+ cfg = {
160
+ 'out_dir': str(out_dir),
161
+ 'mode': args.mode,
162
+ 'cids': parse_cids(args.cid),
163
+ 'export_canvas': not args.no_canvas,
164
+ 'export_attachments': not args.no_attachments,
165
+ 'dry_run': args.dry_run,
166
+ 'apply_deletes': args.apply_deletes,
167
+ 'purge_local': args.purge_local,
168
+ 'marked_deletes': marked_deletes,
169
+ 'pkg_src_dir': str(pkg_src_dir),
170
+ }
171
+
172
+ env = clean_env(args.cdp_url, args.daemon)
173
+ env['GEMINI_SYNC_CONFIG_JSON'] = json.dumps(cfg, ensure_ascii=False)
174
+
175
+ engine_path = Path(__file__).resolve().parent / 'engine.py'
176
+ with engine_path.open('rb') as script_fh:
177
+ proc = subprocess.run([bu_bin], stdin=script_fh, env=env)
178
+ return proc.returncode
179
+
180
+
181
+ if __name__ == '__main__':
182
+ raise SystemExit(main())