-
-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathopencode-find-session
More file actions
executable file
·132 lines (108 loc) · 4.05 KB
/
opencode-find-session
File metadata and controls
executable file
·132 lines (108 loc) · 4.05 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/usr/bin/env python3
"""
Find OpenCode session IDs by title search using the OpenCode database.
Returns matching session IDs ordered by last usage time.
Usage: opencode-find-session <search-term> [--exact] [--json]
"""
import json
import argparse
from datetime import datetime
from opencode_api import APIError, add_api_arguments, create_client_from_args, list_sessions_across_projects
def get_all_sessions(client, session_list_limit: int) -> list[dict]:
"""Get all sessions with normalized metadata."""
api_sessions = list_sessions_across_projects(client, per_project_limit=session_list_limit)
sessions = []
for session in api_sessions:
time_data = session.get("time", {})
updated_ms = time_data.get("updated") or time_data.get("created") or 0
last_used = updated_ms / 1000 if updated_ms else 0
sessions.append(
{
"id": session.get("id", ""),
"title": session.get("title", "Untitled"),
"created_at": time_data.get("created"),
"last_used": last_used,
"last_used_iso": datetime.fromtimestamp(last_used).isoformat() if last_used else None,
}
)
return sessions
def search_sessions(sessions: list[dict], search_term: str, exact: bool = False) -> list[dict]:
"""Search sessions by title."""
results = []
search_lower = search_term.lower()
for session in sessions:
title = session.get("title", "")
title_lower = title.lower()
if exact:
if title_lower == search_lower:
results.append(session)
else:
if search_lower in title_lower:
results.append(session)
# Sort by last used time, most recent first
results.sort(key=lambda s: s["last_used"], reverse=True)
return results
def print_results(results: list[dict], search_term: str):
"""Print search results."""
if not results:
print(f"No sessions found matching: {search_term}")
return
if len(results) == 1:
# Single result - just print the ID for easy piping
print(results[0]["id"])
else:
# Multiple results - show a table
print(f"Found {len(results)} sessions matching: {search_term}")
print()
print(f"{'Session ID':<32} {'Last Used':<20} {'Title'}")
print("-" * 100)
for r in results:
last_used = datetime.fromtimestamp(r["last_used"]).strftime("%Y-%m-%d %H:%M")
title = r["title"][:50] if len(r["title"]) > 50 else r["title"]
print(f"{r['id']:<32} {last_used:<20} {title}")
def main():
parser = argparse.ArgumentParser(
description="Find OpenCode session IDs by title search"
)
parser.add_argument(
"search_term",
nargs="?",
type=str,
help="Text to search for in session titles"
)
parser.add_argument(
"--exact", "-e",
action="store_true",
help="Require exact title match (case-insensitive)"
)
parser.add_argument(
"--json", "-j",
action="store_true",
help="Output as JSON"
)
parser.add_argument(
"--all", "-a",
action="store_true",
help="Show all sessions (ignore search term)"
)
add_api_arguments(parser)
args = parser.parse_args()
if not args.all and not args.search_term:
parser.error("search_term is required unless --all is used")
try:
with create_client_from_args(args) as client:
sessions = get_all_sessions(client, args.session_list_limit)
except APIError as err:
print(f"Error: {err}")
return 1
if args.all:
results = sorted(sessions, key=lambda s: s["last_used"], reverse=True)
else:
results = search_sessions(sessions, args.search_term, args.exact)
if args.json:
print(json.dumps(results, indent=2, default=str))
else:
print_results(results, args.search_term if not args.all else "(all)")
return 0
if __name__ == "__main__":
exit(main())