session-trail 0.2.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.
- agent_trail/__init__.py +1 -0
- agent_trail/__main__.py +3 -0
- agent_trail/adapters/__init__.py +26 -0
- agent_trail/adapters/base.py +39 -0
- agent_trail/adapters/claude_code.py +40 -0
- agent_trail/adapters/codebuddy.py +93 -0
- agent_trail/adapters/codex.py +165 -0
- agent_trail/adapters/deepseek_harness.py +179 -0
- agent_trail/adapters/jsonl_utils.py +53 -0
- agent_trail/adapters/kimi_code.py +112 -0
- agent_trail/adapters/minimax_code.py +152 -0
- agent_trail/adapters/opencode.py +169 -0
- agent_trail/adapters/pi.py +114 -0
- agent_trail/adapters/sqlite_utils.py +15 -0
- agent_trail/adapters/zcode.py +161 -0
- agent_trail/cli.py +134 -0
- agent_trail/launcher.py +114 -0
- agent_trail/models.py +86 -0
- agent_trail/scanner.py +103 -0
- agent_trail/server.py +260 -0
- agent_trail/static/app.js +525 -0
- agent_trail/static/i18n.js +248 -0
- agent_trail/static/index.html +134 -0
- agent_trail/static/styles.css +307 -0
- agent_trail/store.py +197 -0
- agent_trail/tray/__init__.py +6 -0
- agent_trail/tray/app.py +582 -0
- agent_trail/tray/desktop.template +10 -0
- agent_trail/tray/icon.png +0 -0
- agent_trail/tray/sni.py +384 -0
- agent_trail/watcher.py +307 -0
- session_trail-0.2.0.dist-info/METADATA +155 -0
- session_trail-0.2.0.dist-info/RECORD +37 -0
- session_trail-0.2.0.dist-info/WHEEL +5 -0
- session_trail-0.2.0.dist-info/entry_points.txt +2 -0
- session_trail-0.2.0.dist-info/licenses/LICENSE +21 -0
- session_trail-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from contextlib import closing
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from ..models import ActivitySession, AdapterStatus, ResumePlan, ScanResult
|
|
9
|
+
from .base import BaseAdapter
|
|
10
|
+
from .jsonl_utils import fingerprint_paths, to_utc_iso
|
|
11
|
+
from .sqlite_utils import connect_readonly
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ZCodeAdapter(BaseAdapter):
|
|
15
|
+
source = "zcode"
|
|
16
|
+
adapter_version = 1
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def cli_path(self) -> Path:
|
|
20
|
+
return self.home / ".zcode" / "cli" / "db" / "db.sqlite"
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def tasks_path(self) -> Path:
|
|
24
|
+
return self.home / ".zcode" / "v2" / "tasks-index.sqlite"
|
|
25
|
+
|
|
26
|
+
def watch_roots(self) -> list[tuple[Path, bool]]:
|
|
27
|
+
return [(self.cli_path.parent, False), (self.tasks_path.parent, False)]
|
|
28
|
+
|
|
29
|
+
def discover(self) -> AdapterStatus:
|
|
30
|
+
available = self.cli_path.is_file() or self.tasks_path.is_file()
|
|
31
|
+
return AdapterStatus(source=self.source, kind="ok" if available else "unavailable")
|
|
32
|
+
|
|
33
|
+
def scan(self, previous_fingerprint: str | None, now: datetime) -> ScanResult:
|
|
34
|
+
discovery = self.discover()
|
|
35
|
+
if discovery.kind == "unavailable":
|
|
36
|
+
return ScanResult(discovery, None, [], True)
|
|
37
|
+
databases = [path for path in (self.cli_path, self.tasks_path) if path.is_file()]
|
|
38
|
+
paths = [
|
|
39
|
+
path
|
|
40
|
+
for database in databases
|
|
41
|
+
for path in (database, Path(f"{database}-wal"))
|
|
42
|
+
if path.is_file()
|
|
43
|
+
]
|
|
44
|
+
fingerprint = fingerprint_paths(paths, self.adapter_version)
|
|
45
|
+
if fingerprint == previous_fingerprint:
|
|
46
|
+
return ScanResult(
|
|
47
|
+
AdapterStatus(source=self.source, kind="ok"), fingerprint, [], False
|
|
48
|
+
)
|
|
49
|
+
try:
|
|
50
|
+
cli_records = self._cli_records() if self.cli_path.is_file() else {}
|
|
51
|
+
task_records = self._task_records() if self.tasks_path.is_file() else {}
|
|
52
|
+
except sqlite3.Error as error:
|
|
53
|
+
return ScanResult(self._error_status(error), None, [], True)
|
|
54
|
+
sessions: list[ActivitySession] = []
|
|
55
|
+
error_count = 0
|
|
56
|
+
for session_id in sorted(set(cli_records) | set(task_records)):
|
|
57
|
+
try:
|
|
58
|
+
cli = cli_records.get(session_id, {})
|
|
59
|
+
task = task_records.get(session_id, {})
|
|
60
|
+
workdir = cli.get("workdir") or task.get("workdir")
|
|
61
|
+
updated = cli.get("updated_at") or task.get("updated_at")
|
|
62
|
+
if not workdir or not updated:
|
|
63
|
+
error_count += 1
|
|
64
|
+
continue
|
|
65
|
+
title = cli.get("title") or task.get("title")
|
|
66
|
+
created_values = [
|
|
67
|
+
value
|
|
68
|
+
for value in (cli.get("created_at"), task.get("created_at"))
|
|
69
|
+
if value is not None
|
|
70
|
+
]
|
|
71
|
+
sessions.append(
|
|
72
|
+
ActivitySession(
|
|
73
|
+
source=self.source,
|
|
74
|
+
session_id=session_id,
|
|
75
|
+
workdir=workdir,
|
|
76
|
+
title=title or None,
|
|
77
|
+
title_source="native" if title else "fallback",
|
|
78
|
+
created_at=min(created_values) if created_values else None,
|
|
79
|
+
updated_at=max(
|
|
80
|
+
value
|
|
81
|
+
for value in (cli.get("updated_at"), task.get("updated_at"))
|
|
82
|
+
if value is not None
|
|
83
|
+
),
|
|
84
|
+
additions=cli.get("additions"),
|
|
85
|
+
deletions=cli.get("deletions"),
|
|
86
|
+
files_changed=cli.get("files_changed"),
|
|
87
|
+
source_locator=str(self.cli_path if cli else self.tasks_path),
|
|
88
|
+
resume_kind="none",
|
|
89
|
+
archived=bool(cli.get("archived") or task.get("archived")),
|
|
90
|
+
adapter_version=self.adapter_version,
|
|
91
|
+
source_fingerprint=fingerprint,
|
|
92
|
+
last_scanned_at=now.isoformat(),
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
except (TypeError, ValueError, OverflowError, OSError):
|
|
96
|
+
error_count += 1
|
|
97
|
+
return ScanResult(
|
|
98
|
+
AdapterStatus(
|
|
99
|
+
source=self.source,
|
|
100
|
+
kind="ok",
|
|
101
|
+
record_count=len(sessions),
|
|
102
|
+
error_count=error_count,
|
|
103
|
+
),
|
|
104
|
+
fingerprint,
|
|
105
|
+
sessions,
|
|
106
|
+
True,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
def _cli_records(self) -> dict[str, dict]:
|
|
110
|
+
with closing(connect_readonly(self.cli_path)) as connection:
|
|
111
|
+
rows = connection.execute(
|
|
112
|
+
"SELECT id, directory, title, summary_additions, summary_deletions, "
|
|
113
|
+
"summary_files, time_created, time_updated, time_archived FROM session"
|
|
114
|
+
).fetchall()
|
|
115
|
+
records = {}
|
|
116
|
+
for row in rows:
|
|
117
|
+
records[str(row[0])] = {
|
|
118
|
+
"workdir": str(row[1]),
|
|
119
|
+
"title": row[2] or None,
|
|
120
|
+
"additions": row[3],
|
|
121
|
+
"deletions": row[4],
|
|
122
|
+
"files_changed": row[5],
|
|
123
|
+
"created_at": to_utc_iso(row[6]),
|
|
124
|
+
"updated_at": to_utc_iso(row[7]),
|
|
125
|
+
"archived": row[8] is not None,
|
|
126
|
+
}
|
|
127
|
+
return records
|
|
128
|
+
|
|
129
|
+
def _task_records(self) -> dict[str, dict]:
|
|
130
|
+
with closing(connect_readonly(self.tasks_path)) as connection:
|
|
131
|
+
rows = connection.execute(
|
|
132
|
+
"SELECT task_id, workspace_path, title, created_at, updated_at, "
|
|
133
|
+
"archived, deleted FROM tasks"
|
|
134
|
+
).fetchall()
|
|
135
|
+
records = {}
|
|
136
|
+
for row in rows:
|
|
137
|
+
records[str(row[0])] = {
|
|
138
|
+
"workdir": str(row[1]),
|
|
139
|
+
"title": row[2] or None,
|
|
140
|
+
"created_at": to_utc_iso(row[3]),
|
|
141
|
+
"updated_at": to_utc_iso(row[4]),
|
|
142
|
+
"archived": bool(row[5] or row[6]),
|
|
143
|
+
}
|
|
144
|
+
return records
|
|
145
|
+
|
|
146
|
+
def _error_status(self, error: sqlite3.Error) -> AdapterStatus:
|
|
147
|
+
temporary = isinstance(error, sqlite3.OperationalError) and any(
|
|
148
|
+
word in str(error).lower() for word in ("locked", "busy")
|
|
149
|
+
)
|
|
150
|
+
return AdapterStatus(
|
|
151
|
+
source=self.source,
|
|
152
|
+
kind="error" if temporary else "incompatible",
|
|
153
|
+
message="database temporarily unavailable" if temporary else "database schema incompatible",
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def resume_plan(self, session: ActivitySession) -> ResumePlan:
|
|
157
|
+
return ResumePlan(
|
|
158
|
+
kind="none",
|
|
159
|
+
workdir=session.workdir,
|
|
160
|
+
reason="ZCode resume route is not verified",
|
|
161
|
+
)
|
agent_trail/cli.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
import threading
|
|
7
|
+
import webbrowser
|
|
8
|
+
from dataclasses import asdict
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from time import monotonic
|
|
11
|
+
|
|
12
|
+
from .adapters import default_adapters
|
|
13
|
+
from .models import SessionFilter
|
|
14
|
+
from .scanner import ScanService
|
|
15
|
+
from .server import LocalServer
|
|
16
|
+
from .store import LocalStore
|
|
17
|
+
from .watcher import SourceWatcher
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
21
|
+
parser = argparse.ArgumentParser(prog="agent-trail")
|
|
22
|
+
parser.add_argument("--home", type=Path, default=Path.home())
|
|
23
|
+
parser.add_argument("--data-dir", type=Path, default=Path.home() / ".agent-trail")
|
|
24
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
25
|
+
commands.add_parser("scan")
|
|
26
|
+
commands.add_parser("list")
|
|
27
|
+
serve = commands.add_parser("serve")
|
|
28
|
+
serve.add_argument("--port", type=int, default=0)
|
|
29
|
+
serve.add_argument("--no-browser", action="store_true")
|
|
30
|
+
serve.add_argument("--interval", type=float, default=30)
|
|
31
|
+
serve.add_argument("--no-watch", action="store_true")
|
|
32
|
+
tray = commands.add_parser("tray", help="system tray app (Linux)")
|
|
33
|
+
tray.add_argument("--show", action="store_true", help="open the console window at startup")
|
|
34
|
+
tray.add_argument("--install", action="store_true", help="add an applications-menu entry")
|
|
35
|
+
tray.add_argument("--uninstall", action="store_true", help="remove the menu entry and autostart")
|
|
36
|
+
return parser
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(argv: list[str] | None = None) -> int:
|
|
40
|
+
parser = build_parser()
|
|
41
|
+
args = parser.parse_args(argv)
|
|
42
|
+
if args.command == "serve":
|
|
43
|
+
if not 0 <= args.port <= 65535:
|
|
44
|
+
parser.error("--port must be between 0 and 65535")
|
|
45
|
+
if args.interval <= 0:
|
|
46
|
+
parser.error("--interval must be positive")
|
|
47
|
+
if args.command == "tray":
|
|
48
|
+
# 托盘是独立子进程形态,不需要打开本地索引;当前解释器缺 GI
|
|
49
|
+
# 绑定时由 tray.main 内部重执行到带 gi 的系统 Python。
|
|
50
|
+
from .tray.app import main as tray_main
|
|
51
|
+
rest = list(argv) if argv is not None else sys.argv[1:]
|
|
52
|
+
if rest and rest[0] == "tray":
|
|
53
|
+
rest = rest[1:] # 子命令词由 cli 层消费,不传给 tray 解析器
|
|
54
|
+
return tray_main(rest)
|
|
55
|
+
index_path = args.data_dir.expanduser() / "index.sqlite"
|
|
56
|
+
with LocalStore(index_path) as store:
|
|
57
|
+
adapters = default_adapters(args.home.expanduser())
|
|
58
|
+
if args.command == "scan":
|
|
59
|
+
started = monotonic()
|
|
60
|
+
statuses = ScanService(store, adapters).scan_all()
|
|
61
|
+
for status in statuses:
|
|
62
|
+
print(json.dumps(asdict(status), ensure_ascii=False))
|
|
63
|
+
print(
|
|
64
|
+
json.dumps(
|
|
65
|
+
{
|
|
66
|
+
"event": "scan_complete",
|
|
67
|
+
"adapter_count": len(statuses),
|
|
68
|
+
"elapsed_ms": round((monotonic() - started) * 1000, 2),
|
|
69
|
+
},
|
|
70
|
+
ensure_ascii=False,
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
elif args.command == "list":
|
|
74
|
+
for session in store.list_sessions(SessionFilter()):
|
|
75
|
+
print(json.dumps(asdict(session), ensure_ascii=False))
|
|
76
|
+
elif args.command == "serve":
|
|
77
|
+
scanner = ScanService(store, adapters)
|
|
78
|
+
scanner.scan_all()
|
|
79
|
+
server = LocalServer(store, scanner, port=args.port)
|
|
80
|
+
url = server.start()
|
|
81
|
+
print(url, flush=True)
|
|
82
|
+
if not args.no_browser:
|
|
83
|
+
webbrowser.open(url)
|
|
84
|
+
watcher: SourceWatcher | None = None
|
|
85
|
+
if not args.no_watch:
|
|
86
|
+
roots: list[tuple[Path, bool]] = []
|
|
87
|
+
for adapter in adapters:
|
|
88
|
+
roots.extend(adapter.watch_roots())
|
|
89
|
+
watcher = SourceWatcher(roots, on_change=scanner.scan_all)
|
|
90
|
+
if watcher.start():
|
|
91
|
+
print(
|
|
92
|
+
json.dumps(
|
|
93
|
+
{"event": "watch_started", "watches": watcher.watch_count},
|
|
94
|
+
ensure_ascii=False,
|
|
95
|
+
),
|
|
96
|
+
flush=True,
|
|
97
|
+
)
|
|
98
|
+
else:
|
|
99
|
+
print(
|
|
100
|
+
json.dumps(
|
|
101
|
+
{"event": "watch_unavailable", "reason": watcher.last_error},
|
|
102
|
+
ensure_ascii=False,
|
|
103
|
+
),
|
|
104
|
+
flush=True,
|
|
105
|
+
)
|
|
106
|
+
watcher = None
|
|
107
|
+
|
|
108
|
+
def poll_interval() -> float:
|
|
109
|
+
# While the watcher is healthy the poll degrades to a slow
|
|
110
|
+
# safety net; if it dies we fall back to --interval.
|
|
111
|
+
if watcher is not None and watcher.healthy:
|
|
112
|
+
return max(args.interval, 300.0)
|
|
113
|
+
return args.interval
|
|
114
|
+
|
|
115
|
+
scheduler = threading.Thread(
|
|
116
|
+
target=scanner.run_forever,
|
|
117
|
+
args=(args.interval,),
|
|
118
|
+
kwargs={"effective_interval": poll_interval,
|
|
119
|
+
"after_scan": watcher.resync if watcher is not None else None},
|
|
120
|
+
name="agent-trail-scan",
|
|
121
|
+
daemon=True,
|
|
122
|
+
)
|
|
123
|
+
scheduler.start()
|
|
124
|
+
try:
|
|
125
|
+
threading.Event().wait()
|
|
126
|
+
except KeyboardInterrupt:
|
|
127
|
+
pass
|
|
128
|
+
finally:
|
|
129
|
+
scanner.stop()
|
|
130
|
+
scheduler.join(timeout=5)
|
|
131
|
+
if watcher is not None:
|
|
132
|
+
watcher.stop()
|
|
133
|
+
server.stop()
|
|
134
|
+
return 0
|
agent_trail/launcher.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .models import ResumePlan
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class LaunchResult:
|
|
15
|
+
ok: bool
|
|
16
|
+
message: str
|
|
17
|
+
pid: int | None = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TerminalLauncher:
|
|
21
|
+
_allowed_executables = frozenset(
|
|
22
|
+
{"kimi", "codebuddy", "mcode", "dst", "pi", "opencode", "codex"}
|
|
23
|
+
)
|
|
24
|
+
_terminals = (
|
|
25
|
+
("x-terminal-emulator", ("-e",)),
|
|
26
|
+
("gnome-terminal", ("--",)),
|
|
27
|
+
("wezterm", ("start", "--cwd", "{workdir}", "--")),
|
|
28
|
+
("konsole", ("-e",)),
|
|
29
|
+
("xfce4-terminal", ("-x",)),
|
|
30
|
+
("kitty", ("--",)),
|
|
31
|
+
("alacritty", ("-e",)),
|
|
32
|
+
("foot", ("--",)),
|
|
33
|
+
("xterm", ("-e",)),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
terminal: str | None = None,
|
|
39
|
+
args_template: tuple[str, ...] | None = None,
|
|
40
|
+
) -> None:
|
|
41
|
+
self.terminal = terminal
|
|
42
|
+
self.args_template = args_template
|
|
43
|
+
|
|
44
|
+
def launch(self, plan: ResumePlan) -> LaunchResult:
|
|
45
|
+
if (
|
|
46
|
+
plan.kind != "cli"
|
|
47
|
+
or not plan.executable
|
|
48
|
+
or plan.executable not in self._allowed_executables
|
|
49
|
+
):
|
|
50
|
+
return LaunchResult(False, "resume.no_verified_path")
|
|
51
|
+
if not plan.workdir or not Path(plan.workdir).is_dir():
|
|
52
|
+
return LaunchResult(False, "resume.workdir_missing")
|
|
53
|
+
if not shutil.which(plan.executable):
|
|
54
|
+
return LaunchResult(False, "resume.cli_not_found")
|
|
55
|
+
if not all(isinstance(argument, str) and "\0" not in argument for argument in plan.args):
|
|
56
|
+
return LaunchResult(False, "resume.invalid_args")
|
|
57
|
+
try:
|
|
58
|
+
terminal, template = self._terminal_command()
|
|
59
|
+
except ValueError:
|
|
60
|
+
return LaunchResult(False, "resume.terminal_config_invalid")
|
|
61
|
+
if terminal is None:
|
|
62
|
+
return LaunchResult(False, "resume.no_terminal")
|
|
63
|
+
command = [plan.executable, *plan.args]
|
|
64
|
+
arguments = [
|
|
65
|
+
argument
|
|
66
|
+
for item in template
|
|
67
|
+
for argument in (
|
|
68
|
+
command
|
|
69
|
+
if item == "{command}"
|
|
70
|
+
else [plan.workdir]
|
|
71
|
+
if item == "{workdir}"
|
|
72
|
+
else [item]
|
|
73
|
+
)
|
|
74
|
+
]
|
|
75
|
+
if "{command}" not in template:
|
|
76
|
+
arguments.extend(command)
|
|
77
|
+
try:
|
|
78
|
+
process = subprocess.Popen(
|
|
79
|
+
[terminal, *arguments],
|
|
80
|
+
cwd=plan.workdir,
|
|
81
|
+
stdin=subprocess.DEVNULL,
|
|
82
|
+
stdout=subprocess.DEVNULL,
|
|
83
|
+
stderr=subprocess.DEVNULL,
|
|
84
|
+
close_fds=True,
|
|
85
|
+
start_new_session=True,
|
|
86
|
+
)
|
|
87
|
+
except OSError:
|
|
88
|
+
return LaunchResult(False, "resume.launch_failed")
|
|
89
|
+
return LaunchResult(True, "resume.launch_ok", process.pid)
|
|
90
|
+
|
|
91
|
+
def _terminal_command(self) -> tuple[str | None, tuple[str, ...]]:
|
|
92
|
+
terminal_name = self.terminal or os.environ.get("AGENT_TRAIL_TERMINAL")
|
|
93
|
+
if terminal_name:
|
|
94
|
+
template = (
|
|
95
|
+
self.args_template
|
|
96
|
+
if self.args_template is not None
|
|
97
|
+
else self._environment_template()
|
|
98
|
+
)
|
|
99
|
+
if template.count("{command}") > 1:
|
|
100
|
+
raise ValueError("duplicate command placeholder")
|
|
101
|
+
return shutil.which(terminal_name), template
|
|
102
|
+
for name, arguments in self._terminals:
|
|
103
|
+
terminal = shutil.which(name)
|
|
104
|
+
if terminal:
|
|
105
|
+
return terminal, arguments
|
|
106
|
+
return None, ()
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _environment_template() -> tuple[str, ...]:
|
|
110
|
+
raw = os.environ.get("AGENT_TRAIL_TERMINAL_ARGS", "[]")
|
|
111
|
+
value = json.loads(raw)
|
|
112
|
+
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
|
113
|
+
raise ValueError("terminal arguments must be a string array")
|
|
114
|
+
return tuple(value)
|
agent_trail/models.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
TitleSource = Literal["native", "fallback", "missing"]
|
|
8
|
+
ResumeKind = Literal["cli", "deep_link", "none"]
|
|
9
|
+
AdapterStatusKind = Literal["ok", "unavailable", "experimental", "error", "incompatible"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class ActivitySession:
|
|
14
|
+
source: str
|
|
15
|
+
session_id: str
|
|
16
|
+
workdir: str
|
|
17
|
+
updated_at: str
|
|
18
|
+
workdir_normalized: str = ""
|
|
19
|
+
title: str | None = None
|
|
20
|
+
title_source: TitleSource = "missing"
|
|
21
|
+
created_at: str | None = None
|
|
22
|
+
additions: int | None = None
|
|
23
|
+
deletions: int | None = None
|
|
24
|
+
files_changed: int | None = None
|
|
25
|
+
source_locator: str = ""
|
|
26
|
+
resume_kind: ResumeKind = "none"
|
|
27
|
+
resume_ref: str | None = None
|
|
28
|
+
source_missing: bool = False
|
|
29
|
+
archived: bool = False
|
|
30
|
+
adapter_version: int = 1
|
|
31
|
+
source_fingerprint: str = ""
|
|
32
|
+
last_scanned_at: str = ""
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
if self.title_source not in {"native", "fallback", "missing"}:
|
|
36
|
+
raise ValueError("invalid title_source")
|
|
37
|
+
if self.resume_kind not in {"cli", "deep_link", "none"}:
|
|
38
|
+
raise ValueError("invalid resume_kind")
|
|
39
|
+
if not self.workdir_normalized:
|
|
40
|
+
object.__setattr__(
|
|
41
|
+
self,
|
|
42
|
+
"workdir_normalized",
|
|
43
|
+
os.path.normpath(os.path.expanduser(self.workdir)),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class AdapterStatus:
|
|
49
|
+
source: str
|
|
50
|
+
kind: AdapterStatusKind
|
|
51
|
+
message: str = ""
|
|
52
|
+
record_count: int = 0
|
|
53
|
+
error_count: int = 0
|
|
54
|
+
last_scanned_at: str | None = None
|
|
55
|
+
|
|
56
|
+
def __post_init__(self) -> None:
|
|
57
|
+
if self.kind not in {"ok", "unavailable", "experimental", "error", "incompatible"}:
|
|
58
|
+
raise ValueError("invalid adapter status")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class ScanResult:
|
|
63
|
+
status: AdapterStatus
|
|
64
|
+
fingerprint: str | None
|
|
65
|
+
sessions: list[ActivitySession] = field(default_factory=list)
|
|
66
|
+
changed: bool = True
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class ResumePlan:
|
|
71
|
+
kind: ResumeKind
|
|
72
|
+
workdir: str
|
|
73
|
+
executable: str | None = None
|
|
74
|
+
args: tuple[str, ...] = ()
|
|
75
|
+
reason: str = ""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class SessionFilter:
|
|
80
|
+
since: str | None = None
|
|
81
|
+
until: str | None = None
|
|
82
|
+
sources: tuple[str, ...] = ()
|
|
83
|
+
workdir: str | None = None
|
|
84
|
+
query: str | None = None
|
|
85
|
+
limit: int = 200
|
|
86
|
+
offset: int = 0
|
agent_trail/scanner.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
|
|
7
|
+
from .adapters.base import BaseAdapter
|
|
8
|
+
from .models import AdapterStatus
|
|
9
|
+
from .store import LocalStore
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ScanService:
|
|
13
|
+
def __init__(self, store: LocalStore, adapters: list[BaseAdapter]) -> None:
|
|
14
|
+
self.store = store
|
|
15
|
+
self.adapters = adapters
|
|
16
|
+
self._lock = threading.Lock()
|
|
17
|
+
self._stop = threading.Event()
|
|
18
|
+
self._statuses: dict[str, AdapterStatus] = {}
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def statuses(self) -> list[AdapterStatus]:
|
|
22
|
+
return [self._statuses[source] for source in sorted(self._statuses)]
|
|
23
|
+
|
|
24
|
+
def scan_all(self) -> list[AdapterStatus]:
|
|
25
|
+
with self._lock:
|
|
26
|
+
now = datetime.now(timezone.utc)
|
|
27
|
+
scanned_at = now.isoformat()
|
|
28
|
+
statuses: list[AdapterStatus] = []
|
|
29
|
+
for adapter in self.adapters:
|
|
30
|
+
previous = self.store.get_fingerprint(adapter.source)
|
|
31
|
+
try:
|
|
32
|
+
result = adapter.scan(previous, now)
|
|
33
|
+
status = AdapterStatus(
|
|
34
|
+
source=adapter.source,
|
|
35
|
+
kind=result.status.kind,
|
|
36
|
+
message=result.status.message,
|
|
37
|
+
record_count=len(result.sessions) if result.changed else result.status.record_count,
|
|
38
|
+
error_count=result.status.error_count,
|
|
39
|
+
last_scanned_at=scanned_at,
|
|
40
|
+
)
|
|
41
|
+
if status.kind in {"ok", "experimental"}:
|
|
42
|
+
if result.changed:
|
|
43
|
+
self.store.replace_source(
|
|
44
|
+
adapter.source, result.sessions, result.fingerprint, scanned_at
|
|
45
|
+
)
|
|
46
|
+
else:
|
|
47
|
+
self.store.mark_unchanged(
|
|
48
|
+
adapter.source, previous, scanned_at
|
|
49
|
+
)
|
|
50
|
+
if not result.changed:
|
|
51
|
+
status = AdapterStatus(
|
|
52
|
+
source=adapter.source,
|
|
53
|
+
kind=status.kind,
|
|
54
|
+
message=status.message,
|
|
55
|
+
record_count=result.status.record_count,
|
|
56
|
+
error_count=status.error_count,
|
|
57
|
+
last_scanned_at=scanned_at,
|
|
58
|
+
)
|
|
59
|
+
elif status.kind == "unavailable":
|
|
60
|
+
if previous is not None:
|
|
61
|
+
self.store.replace_source(
|
|
62
|
+
adapter.source, [], None, scanned_at
|
|
63
|
+
)
|
|
64
|
+
else:
|
|
65
|
+
self.store.mark_unchanged(adapter.source, None, scanned_at)
|
|
66
|
+
else:
|
|
67
|
+
self.store.mark_unchanged(adapter.source, previous, scanned_at)
|
|
68
|
+
except Exception as error:
|
|
69
|
+
status = AdapterStatus(
|
|
70
|
+
source=adapter.source,
|
|
71
|
+
kind="error",
|
|
72
|
+
message=f"scan failed: {type(error).__name__}",
|
|
73
|
+
last_scanned_at=scanned_at,
|
|
74
|
+
)
|
|
75
|
+
self.store.mark_unchanged(adapter.source, previous, scanned_at)
|
|
76
|
+
adapter._status = status
|
|
77
|
+
self._statuses[adapter.source] = status
|
|
78
|
+
statuses.append(status)
|
|
79
|
+
return statuses
|
|
80
|
+
|
|
81
|
+
def run_forever(
|
|
82
|
+
self,
|
|
83
|
+
interval_seconds: float = 30,
|
|
84
|
+
effective_interval: Callable[[], float] | None = None,
|
|
85
|
+
after_scan: Callable[[], None] | None = None,
|
|
86
|
+
) -> None:
|
|
87
|
+
while not self._stop.wait(
|
|
88
|
+
effective_interval() if effective_interval is not None else interval_seconds
|
|
89
|
+
):
|
|
90
|
+
try:
|
|
91
|
+
self.scan_all()
|
|
92
|
+
except Exception:
|
|
93
|
+
# Store-level failures must not kill the scheduler; adapter
|
|
94
|
+
# errors are already isolated inside scan_all.
|
|
95
|
+
continue
|
|
96
|
+
if after_scan is not None:
|
|
97
|
+
try:
|
|
98
|
+
after_scan()
|
|
99
|
+
except Exception:
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
def stop(self) -> None:
|
|
103
|
+
self._stop.set()
|