agyscope 0.2.1__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.
- agyscope/__init__.py +3 -0
- agyscope/__main__.py +7 -0
- agyscope/agentdb.py +221 -0
- agyscope/app.py +291 -0
- agyscope/cli.py +153 -0
- agyscope/config.py +162 -0
- agyscope/discovery.py +137 -0
- agyscope/integrations/__init__.py +1 -0
- agyscope/integrations/rex/__init__.py +1 -0
- agyscope/integrations/rex/focus.py +41 -0
- agyscope/integrations/rex/hook.py +280 -0
- agyscope/integrations/rex/pointer.py +45 -0
- agyscope/keymap.py +126 -0
- agyscope/pager.py +46 -0
- agyscope/resolve.py +143 -0
- agyscope/textview.py +7 -0
- agyscope/themes.py +167 -0
- agyscope/transcript.py +482 -0
- agyscope/viewstate.py +173 -0
- agyscope/widgets.py +668 -0
- agyscope-0.2.1.dist-info/METADATA +489 -0
- agyscope-0.2.1.dist-info/RECORD +25 -0
- agyscope-0.2.1.dist-info/WHEEL +4 -0
- agyscope-0.2.1.dist-info/entry_points.txt +3 -0
- agyscope-0.2.1.dist-info/licenses/LICENSE +21 -0
agyscope/__init__.py
ADDED
agyscope/__main__.py
ADDED
agyscope/agentdb.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Read-only SQLite + minimal protobuf reader for Antigravity model & child metadata.
|
|
2
|
+
|
|
3
|
+
Reads `<app_dir>/conversations/<id>.db` (`gen_metadata`) for resolved model labels
|
|
4
|
+
and `<app_dir>/conversation_summaries.db` (`parent_conversation_id`) as a fallback
|
|
5
|
+
when a parent transcript omits or compacts a child subagent. All database opens use
|
|
6
|
+
`?mode=ro` URIs and cache by `(db_stat, wal_stat)` so unchanged 1s UI refreshes do
|
|
7
|
+
zero redundant SQLite reads while uncheckpointed WAL writes invalidate immediately.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import sqlite3
|
|
14
|
+
import urllib.parse
|
|
15
|
+
|
|
16
|
+
EFFORT_RE = re.compile(r"\s*\((?:Minimal|Low|Medium|High|Max)\)\s*$", re.I)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _read_varint(buf, i, n):
|
|
20
|
+
val = 0
|
|
21
|
+
shift = 0
|
|
22
|
+
while i < n and shift <= 63:
|
|
23
|
+
b = buf[i]
|
|
24
|
+
i += 1
|
|
25
|
+
val |= (b & 0x7F) << shift
|
|
26
|
+
if not (b & 0x80):
|
|
27
|
+
return val, i
|
|
28
|
+
shift += 7
|
|
29
|
+
return None, n
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def pb_fields(buf):
|
|
33
|
+
"""Parses top-level protobuf fields into {field_num: [values...]} without schema deps."""
|
|
34
|
+
if isinstance(buf, memoryview):
|
|
35
|
+
buf = bytes(buf)
|
|
36
|
+
if not isinstance(buf, (bytes, bytearray)) or not buf:
|
|
37
|
+
return {}
|
|
38
|
+
out = {}
|
|
39
|
+
i, n = 0, len(buf)
|
|
40
|
+
while i < n:
|
|
41
|
+
tag, i = _read_varint(buf, i, n)
|
|
42
|
+
if tag is None:
|
|
43
|
+
break
|
|
44
|
+
field, wt = tag >> 3, tag & 7
|
|
45
|
+
if field == 0:
|
|
46
|
+
break
|
|
47
|
+
if wt == 0:
|
|
48
|
+
val, i = _read_varint(buf, i, n)
|
|
49
|
+
if val is None:
|
|
50
|
+
break
|
|
51
|
+
out.setdefault(field, []).append(val)
|
|
52
|
+
elif wt == 2:
|
|
53
|
+
ln, i = _read_varint(buf, i, n)
|
|
54
|
+
if ln is None or ln < 0 or i + ln > n:
|
|
55
|
+
break
|
|
56
|
+
out.setdefault(field, []).append(bytes(buf[i:i + ln]))
|
|
57
|
+
i += ln
|
|
58
|
+
elif wt == 1:
|
|
59
|
+
if i + 8 > n:
|
|
60
|
+
break
|
|
61
|
+
i += 8
|
|
62
|
+
elif wt == 5:
|
|
63
|
+
if i + 4 > n:
|
|
64
|
+
break
|
|
65
|
+
i += 4
|
|
66
|
+
else:
|
|
67
|
+
break
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _pb_str(fields, num):
|
|
72
|
+
vals = fields.get(num)
|
|
73
|
+
if not vals or not isinstance(vals[-1], (bytes, bytearray)):
|
|
74
|
+
return ""
|
|
75
|
+
return vals[-1].decode("utf-8", "replace").strip()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _pb_int(fields, num):
|
|
79
|
+
vals = fields.get(num)
|
|
80
|
+
if not vals or not isinstance(vals[-1], int) or isinstance(vals[-1], bool):
|
|
81
|
+
return None
|
|
82
|
+
return vals[-1]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def normalize_model(display_name, slug):
|
|
86
|
+
"""Formats model label like `agy /agents`: display name minus effort suffix, else slug."""
|
|
87
|
+
if isinstance(display_name, str) and display_name.strip():
|
|
88
|
+
cleaned = EFFORT_RE.sub("", display_name).strip()
|
|
89
|
+
if cleaned:
|
|
90
|
+
return cleaned
|
|
91
|
+
if isinstance(slug, str) and slug.strip():
|
|
92
|
+
return slug.strip()
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _one_stat(path):
|
|
97
|
+
try:
|
|
98
|
+
st = os.stat(path)
|
|
99
|
+
return (st.st_mtime_ns, st.st_size)
|
|
100
|
+
except OSError:
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _stat_sig(path):
|
|
105
|
+
return (_one_stat(path), _one_stat(path + "-wal"))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _ro_connect(path):
|
|
109
|
+
uri = "file:" + urllib.parse.quote(os.path.abspath(path), safe="/:") + "?mode=ro"
|
|
110
|
+
return contextlib.closing(sqlite3.connect(uri, uri=True, timeout=0.2))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _is_busy(err):
|
|
114
|
+
msg = str(err).lower()
|
|
115
|
+
return "locked" in msg or "busy" in msg
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _decode_gen_metadata(blob):
|
|
119
|
+
top = pb_fields(blob)
|
|
120
|
+
f1 = pb_fields(top[1][-1]) if top.get(1) else {}
|
|
121
|
+
f3 = pb_fields(top[3][-1]) if top.get(3) else {}
|
|
122
|
+
display = _pb_str(f1, 21)
|
|
123
|
+
slug = _pb_str(f1, 19) or _pb_str(f3, 28)
|
|
124
|
+
return normalize_model(display, slug)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class AgentDB:
|
|
128
|
+
"""Per-app_dir read-only cache over conversations/<id>.db and conversation_summaries.db."""
|
|
129
|
+
|
|
130
|
+
def __init__(self, app_dir):
|
|
131
|
+
self.app_dir = app_dir
|
|
132
|
+
self._models = {} # conv_id -> (sig, resolved_or_none)
|
|
133
|
+
self._summaries_sig = None
|
|
134
|
+
self._children = {} # parent_id -> [child_dict, ...]
|
|
135
|
+
|
|
136
|
+
def model_of(self, conv_id, fallback=None):
|
|
137
|
+
fb = fallback.strip() if isinstance(fallback, str) and fallback.strip() else "-"
|
|
138
|
+
if not self.app_dir or not conv_id or not isinstance(conv_id, str):
|
|
139
|
+
return fb
|
|
140
|
+
if os.sep in conv_id or (os.altsep and os.altsep in conv_id):
|
|
141
|
+
return fb
|
|
142
|
+
path = os.path.join(self.app_dir, "conversations", conv_id + ".db")
|
|
143
|
+
sig = _stat_sig(path)
|
|
144
|
+
if sig[0] is None:
|
|
145
|
+
return fb
|
|
146
|
+
cached = self._models.get(conv_id)
|
|
147
|
+
if cached is not None and cached[0] == sig:
|
|
148
|
+
return cached[1] or fb
|
|
149
|
+
resolved = None
|
|
150
|
+
try:
|
|
151
|
+
with _ro_connect(path) as con:
|
|
152
|
+
row = con.execute("SELECT data FROM gen_metadata ORDER BY idx DESC LIMIT 1").fetchone()
|
|
153
|
+
if row and row[0]:
|
|
154
|
+
resolved = _decode_gen_metadata(row[0])
|
|
155
|
+
except sqlite3.Error as err:
|
|
156
|
+
if _is_busy(err):
|
|
157
|
+
return fb
|
|
158
|
+
except OSError:
|
|
159
|
+
return fb
|
|
160
|
+
except Exception:
|
|
161
|
+
resolved = None
|
|
162
|
+
self._models[conv_id] = (sig, resolved)
|
|
163
|
+
return resolved or fb
|
|
164
|
+
|
|
165
|
+
def children_of(self, parent_id):
|
|
166
|
+
if not self.app_dir or not parent_id or not isinstance(parent_id, str):
|
|
167
|
+
return []
|
|
168
|
+
path = os.path.join(self.app_dir, "conversation_summaries.db")
|
|
169
|
+
sig = _stat_sig(path)
|
|
170
|
+
if sig[0] is None:
|
|
171
|
+
return []
|
|
172
|
+
if sig != self._summaries_sig:
|
|
173
|
+
self._children = {}
|
|
174
|
+
self._summaries_sig = sig
|
|
175
|
+
if parent_id in self._children:
|
|
176
|
+
return [dict(c) for c in self._children[parent_id]]
|
|
177
|
+
try:
|
|
178
|
+
with _ro_connect(path) as con:
|
|
179
|
+
rows = con.execute(
|
|
180
|
+
"SELECT conversation_id, agent_name, raw_summary "
|
|
181
|
+
"FROM conversation_summaries WHERE parent_conversation_id = ?",
|
|
182
|
+
(parent_id,),
|
|
183
|
+
).fetchall()
|
|
184
|
+
except sqlite3.Error as err:
|
|
185
|
+
if _is_busy(err):
|
|
186
|
+
self._summaries_sig = None
|
|
187
|
+
return []
|
|
188
|
+
self._children[parent_id] = []
|
|
189
|
+
return []
|
|
190
|
+
except OSError:
|
|
191
|
+
self._summaries_sig = None
|
|
192
|
+
return []
|
|
193
|
+
items = []
|
|
194
|
+
for idx, (cid, agent_name, raw) in enumerate(rows):
|
|
195
|
+
if not cid or not isinstance(cid, str):
|
|
196
|
+
continue
|
|
197
|
+
try:
|
|
198
|
+
top = pb_fields(raw or b"")
|
|
199
|
+
f7 = pb_fields(top[7][-1]) if top.get(7) else {}
|
|
200
|
+
ts = _pb_int(f7, 1)
|
|
201
|
+
f17 = pb_fields(top[17][-1]) if top.get(17) else {}
|
|
202
|
+
f8 = pb_fields(f17[8][-1]) if f17.get(8) else {}
|
|
203
|
+
sub_type = _pb_str(f8, 1) or (agent_name.strip() if isinstance(agent_name, str) else "")
|
|
204
|
+
role = _pb_str(f8, 2)
|
|
205
|
+
model = _pb_str(f8, 12)
|
|
206
|
+
except Exception:
|
|
207
|
+
sub_type = agent_name.strip() if isinstance(agent_name, str) else ""
|
|
208
|
+
role, model, ts = "", "", None
|
|
209
|
+
items.append((idx, {
|
|
210
|
+
"id": cid,
|
|
211
|
+
"role": role or None,
|
|
212
|
+
"type": sub_type or None,
|
|
213
|
+
"model": model or None,
|
|
214
|
+
"parent": parent_id,
|
|
215
|
+
"ts": ts,
|
|
216
|
+
"transcript": None,
|
|
217
|
+
}))
|
|
218
|
+
items.sort(key=lambda pair: (pair[1]["ts"] or 0, pair[0]))
|
|
219
|
+
out = [rec for _, rec in items]
|
|
220
|
+
self._children[parent_id] = out
|
|
221
|
+
return [dict(c) for c in out]
|
agyscope/app.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""The Textual panel: a full-screen subagent list; `open` shows one subagent's steps full screen.
|
|
2
|
+
|
|
3
|
+
Started by agyscope.cli.main through run(). The panel only reads files; closing it stops
|
|
4
|
+
nothing but the panel.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import copy
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from rich.text import Text
|
|
11
|
+
from textual.app import App, InvalidThemeError, SuspendNotSupported
|
|
12
|
+
from textual.binding import Binding
|
|
13
|
+
from textual.screen import Screen
|
|
14
|
+
from textual.widgets import Static
|
|
15
|
+
|
|
16
|
+
from . import config, discovery, keymap, pager, textview, themes
|
|
17
|
+
from .themes import FALLBACK_STYLES
|
|
18
|
+
from .viewstate import ViewState
|
|
19
|
+
from .widgets import MARQUEE_STEP_S, ColumnHeader, ColumnsChanged, StepView, SubagentTree
|
|
20
|
+
|
|
21
|
+
REFRESH_S = 1.0
|
|
22
|
+
_HINT_FIRST = {"open": "Enter", "back": "Esc"} # action -> key the hints show when it is bound
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ListScreen(Screen):
|
|
26
|
+
"""The subagent tree, full width, under a key hint row and the column titles."""
|
|
27
|
+
|
|
28
|
+
def compose(self):
|
|
29
|
+
yield Static(Text(self.app.list_hints()), id="listhint")
|
|
30
|
+
yield ColumnHeader(id="colhead")
|
|
31
|
+
yield Static(id="empty")
|
|
32
|
+
yield SubagentTree(id="tree", state_styles=self.app.state_styles, cols=self.app.settings["columns"])
|
|
33
|
+
yield Static(id="status")
|
|
34
|
+
|
|
35
|
+
def on_mount(self) -> None:
|
|
36
|
+
"""Starts the panel: this screen is composed after App.on_mount, so the first refresh is here."""
|
|
37
|
+
self.query_one("#tree", SubagentTree).focus()
|
|
38
|
+
self.app.show_status()
|
|
39
|
+
self.app.refresh_data()
|
|
40
|
+
self.app.set_interval(REFRESH_S, self.app.refresh_data)
|
|
41
|
+
if self.app.settings["marquee"]:
|
|
42
|
+
self.set_interval(MARQUEE_STEP_S, self.tick_marquee)
|
|
43
|
+
|
|
44
|
+
def tick_marquee(self) -> None:
|
|
45
|
+
if self.app.screen is not self or not self.app.settings["marquee"]:
|
|
46
|
+
return
|
|
47
|
+
self.query_one("#tree", SubagentTree).tick_marquee()
|
|
48
|
+
|
|
49
|
+
def on_resize(self, event) -> None:
|
|
50
|
+
self.call_after_refresh(self.show_colhead)
|
|
51
|
+
|
|
52
|
+
def show_colhead(self) -> None:
|
|
53
|
+
"""Column titles for the tree's current content width, so they line up with the rows."""
|
|
54
|
+
tree = self.query_one("#tree", SubagentTree)
|
|
55
|
+
width = tree.scrollable_content_region.width
|
|
56
|
+
if width:
|
|
57
|
+
self.query_one("#colhead", ColumnHeader).show(width, tree.cols)
|
|
58
|
+
|
|
59
|
+
def on_columns_changed(self, message: ColumnsChanged) -> None:
|
|
60
|
+
tree = self.query_one("#tree", SubagentTree)
|
|
61
|
+
tree.cols = dict(message.cols)
|
|
62
|
+
tree.relabel()
|
|
63
|
+
self.show_colhead()
|
|
64
|
+
|
|
65
|
+
def on_screen_suspend(self, _event) -> None:
|
|
66
|
+
colhead = self.query_one_optional("#colhead", ColumnHeader)
|
|
67
|
+
if colhead is not None:
|
|
68
|
+
colhead.cancel_drag()
|
|
69
|
+
|
|
70
|
+
def action(self, name: str) -> None:
|
|
71
|
+
"""close exits with True, open views the subagent under the cursor; the rest go to the tree."""
|
|
72
|
+
tree = self.query_one("#tree", SubagentTree)
|
|
73
|
+
sid = tree.selected_id()
|
|
74
|
+
if name == "close":
|
|
75
|
+
self.app.exit(True)
|
|
76
|
+
elif name == "pager":
|
|
77
|
+
self.app.open_pager(sid)
|
|
78
|
+
elif name == "open" and sid is not None:
|
|
79
|
+
self.app.open_view(sid)
|
|
80
|
+
else:
|
|
81
|
+
tree.action(name)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ViewScreen(Screen):
|
|
85
|
+
"""One subagent's steps, full screen; back and close return to the list."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, row_id: str) -> None:
|
|
88
|
+
super().__init__()
|
|
89
|
+
self.row_id = row_id
|
|
90
|
+
|
|
91
|
+
def compose(self):
|
|
92
|
+
yield StepView(id="steps")
|
|
93
|
+
yield Static(id="status")
|
|
94
|
+
yield Static(Text(self.app.view_hints()), id="hints")
|
|
95
|
+
|
|
96
|
+
def on_mount(self) -> None:
|
|
97
|
+
steps = self.query_one("#steps", StepView)
|
|
98
|
+
steps.state_styles = self.app.state_styles
|
|
99
|
+
steps.focus()
|
|
100
|
+
self.app.show_status()
|
|
101
|
+
self.app.show_view()
|
|
102
|
+
|
|
103
|
+
def action(self, name: str) -> None:
|
|
104
|
+
if name in ("back", "close"):
|
|
105
|
+
self.app.close_view()
|
|
106
|
+
elif name == "pager":
|
|
107
|
+
self.app.open_pager(self.row_id)
|
|
108
|
+
else:
|
|
109
|
+
self.query_one("#steps", StepView).action(name)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class AgyscopeApp(App):
|
|
113
|
+
"""One root conversation's subagents, refreshed every second: a list screen and a view screen."""
|
|
114
|
+
|
|
115
|
+
CSS = """
|
|
116
|
+
#listhint { height: 1; background: $panel; }
|
|
117
|
+
#colhead { height: 1; text-style: bold; }
|
|
118
|
+
#empty { height: 1; color: $text-muted; }
|
|
119
|
+
#tree { height: 1fr; }
|
|
120
|
+
#steps { height: 1fr; }
|
|
121
|
+
#status { height: 1; color: $error; text-style: bold; }
|
|
122
|
+
#hints { height: 1; background: $panel; }
|
|
123
|
+
"""
|
|
124
|
+
BINDINGS = [
|
|
125
|
+
Binding("ctrl+c", "exit_false", show=False, priority=True),
|
|
126
|
+
Binding("ctrl+q", "exit_false", show=False, priority=True),
|
|
127
|
+
]
|
|
128
|
+
ENABLE_COMMAND_PALETTE = False # its ctrl+p binding would shadow emacs `up`
|
|
129
|
+
|
|
130
|
+
def __init__(self, tree, resolver, settings, warnings=(), clock=time.time, themes_dir=None):
|
|
131
|
+
super().__init__()
|
|
132
|
+
self.agents = tree # discovery.Tree (App.tree is taken by Textual)
|
|
133
|
+
self.resolver = resolver
|
|
134
|
+
self.settings = {**copy.deepcopy(config.DEFAULTS), **settings}
|
|
135
|
+
self.clock = clock
|
|
136
|
+
self.themes_dir = themes_dir
|
|
137
|
+
self.state_styles = FALLBACK_STYLES
|
|
138
|
+
self.status = list(warnings)
|
|
139
|
+
try:
|
|
140
|
+
self.keys = keymap.build(self.settings["keymap"], self.settings["keys"])
|
|
141
|
+
except ValueError as e:
|
|
142
|
+
self.status.append("keys: %s; using defaults" % e)
|
|
143
|
+
self.keys = keymap.build("emacs")
|
|
144
|
+
for k in keymap.unreachable(self.keys):
|
|
145
|
+
self.status.append("keys: the terminal can't send %s; use another key" % k)
|
|
146
|
+
self.views = {} # subagent id -> ViewState
|
|
147
|
+
self.rows = {} # subagent id -> row from the last refresh
|
|
148
|
+
|
|
149
|
+
def on_mount(self) -> None:
|
|
150
|
+
if self.themes_dir:
|
|
151
|
+
loaded, warnings = themes.load_user_themes(self.themes_dir)
|
|
152
|
+
for theme in loaded:
|
|
153
|
+
self.register_theme(theme)
|
|
154
|
+
self.status.extend(warnings)
|
|
155
|
+
self.theme_changed_signal.subscribe(self, self._on_theme_changed)
|
|
156
|
+
name = self.settings["theme"]
|
|
157
|
+
try:
|
|
158
|
+
self.theme = name
|
|
159
|
+
except InvalidThemeError:
|
|
160
|
+
self.status.append("theme %r not found; using %s" % (name, self.theme))
|
|
161
|
+
self.state_styles = themes.styles_from(self.get_css_variables())
|
|
162
|
+
|
|
163
|
+
def _on_theme_changed(self, _theme) -> None:
|
|
164
|
+
self.state_styles = themes.styles_from(self.get_css_variables())
|
|
165
|
+
self.apply_state_styles()
|
|
166
|
+
|
|
167
|
+
def apply_state_styles(self) -> None:
|
|
168
|
+
if hasattr(self, "list_screen") and self.list_screen.is_mounted:
|
|
169
|
+
tree = self.list_screen.query_one("#tree", SubagentTree)
|
|
170
|
+
tree.state_styles = self.state_styles
|
|
171
|
+
tree.relabel()
|
|
172
|
+
if isinstance(self.screen, ViewScreen):
|
|
173
|
+
steps = self.screen.query_one_optional("#steps", StepView)
|
|
174
|
+
if steps is not None:
|
|
175
|
+
steps.state_styles = self.state_styles
|
|
176
|
+
steps.refresh()
|
|
177
|
+
|
|
178
|
+
def get_default_screen(self) -> Screen:
|
|
179
|
+
self.list_screen = ListScreen() # stays at the bottom of the stack while a view is shown
|
|
180
|
+
return self.list_screen
|
|
181
|
+
|
|
182
|
+
def hint(self, action: str) -> str:
|
|
183
|
+
"""The key to show for an action in the hints: Enter for open, Esc for back, else a preset key."""
|
|
184
|
+
keys = keymap.keys_for(self.keys, action)
|
|
185
|
+
if _HINT_FIRST.get(action) in keys:
|
|
186
|
+
return _HINT_FIRST[action]
|
|
187
|
+
always = set(k for ks in keymap.ALWAYS.values() for k in ks)
|
|
188
|
+
preferred = [k for k in keys if k not in always] or keys
|
|
189
|
+
return preferred[0] if preferred else "?"
|
|
190
|
+
|
|
191
|
+
def list_hints(self) -> str:
|
|
192
|
+
h = self.hint
|
|
193
|
+
return " Subagents %s/%s move %s view %s close" % (h("down"), h("up"), h("open"), h("close"))
|
|
194
|
+
|
|
195
|
+
def view_hints(self) -> str:
|
|
196
|
+
h = self.hint
|
|
197
|
+
return " %s fold %s all %s follow %s pager %s back %s back" % (
|
|
198
|
+
h("open"), h("fold_all"), h("last"), h("pager"), h("back"), h("close"))
|
|
199
|
+
|
|
200
|
+
def show_status(self) -> None:
|
|
201
|
+
"""Shows the newest status message (if any) on every screen's status line."""
|
|
202
|
+
for screen in self.screen_stack:
|
|
203
|
+
for status in screen.query("#status").results(Static):
|
|
204
|
+
status.display = bool(self.status)
|
|
205
|
+
status.update(Text(" ! " + self.status[-1]) if self.status else "")
|
|
206
|
+
|
|
207
|
+
def refresh_data(self) -> None:
|
|
208
|
+
"""Re-reads the root and its subagents, then updates the list and the open view."""
|
|
209
|
+
tree = self.list_screen.query_one("#tree", SubagentTree)
|
|
210
|
+
root = self.resolver.current()
|
|
211
|
+
app_dir = getattr(self.resolver, "app_dir", None)
|
|
212
|
+
if root != self.agents.root or (app_dir and app_dir != self.agents.app_dir):
|
|
213
|
+
self.agents.set_root(root, app_dir)
|
|
214
|
+
tree.reset()
|
|
215
|
+
self.views, self.rows = {}, {}
|
|
216
|
+
self.close_view()
|
|
217
|
+
groups = self.agents.rows(now=self.clock())
|
|
218
|
+
self.rows = {r["id"]: r for r in discovery.flat(groups)}
|
|
219
|
+
tree.update_groups(groups)
|
|
220
|
+
empty = self.list_screen.query_one("#empty", Static)
|
|
221
|
+
empty.display = not self.rows
|
|
222
|
+
empty.update(" " + (StepView.NO_SUBAGENTS if self.agents.root else StepView.NO_CONVERSATION))
|
|
223
|
+
self.list_screen.show_colhead()
|
|
224
|
+
if isinstance(self.screen, ViewScreen):
|
|
225
|
+
if self.screen.row_id in self.rows:
|
|
226
|
+
self.show_view()
|
|
227
|
+
else:
|
|
228
|
+
self.close_view() # the viewed subagent is gone
|
|
229
|
+
|
|
230
|
+
def open_view(self, row_id: str) -> None:
|
|
231
|
+
"""Shows subagent `row_id` full screen (its remembered ViewState, else a new one that follows)."""
|
|
232
|
+
if row_id in self.rows and not isinstance(self.screen, ViewScreen):
|
|
233
|
+
self.push_screen(ViewScreen(row_id))
|
|
234
|
+
|
|
235
|
+
def close_view(self) -> None:
|
|
236
|
+
"""Returns to the list, which kept its folds and cursor."""
|
|
237
|
+
if isinstance(self.screen, ViewScreen):
|
|
238
|
+
self.pop_screen()
|
|
239
|
+
|
|
240
|
+
def show_view(self) -> None:
|
|
241
|
+
"""Shows the viewed subagent's current steps in the view screen."""
|
|
242
|
+
screen = self.screen
|
|
243
|
+
steps = screen.query_one_optional("#steps", StepView) if isinstance(screen, ViewScreen) else None
|
|
244
|
+
row = self.rows.get(screen.row_id) if steps is not None else None
|
|
245
|
+
if row is not None:
|
|
246
|
+
steps.show(row, self.agents.items(row), self.views.setdefault(screen.row_id, ViewState()))
|
|
247
|
+
|
|
248
|
+
def action_exit_false(self) -> None:
|
|
249
|
+
self.exit(False)
|
|
250
|
+
|
|
251
|
+
def on_key(self, event) -> None:
|
|
252
|
+
"""Maps a key to an action and hands it to the shown screen."""
|
|
253
|
+
act = self.keys.get(keymap.from_textual(event.key, event.character))
|
|
254
|
+
if act is None:
|
|
255
|
+
return
|
|
256
|
+
event.stop()
|
|
257
|
+
event.prevent_default() # keeps App._on_key from also running Screen bindings (Tab)
|
|
258
|
+
if isinstance(self.screen, (ListScreen, ViewScreen)):
|
|
259
|
+
self.screen.action(act)
|
|
260
|
+
|
|
261
|
+
def open_pager(self, row_id) -> None:
|
|
262
|
+
"""Shows subagent `row_id`'s unfolded text in the pager; errors go to the status line."""
|
|
263
|
+
row = self.rows.get(row_id)
|
|
264
|
+
if row is None:
|
|
265
|
+
return
|
|
266
|
+
try:
|
|
267
|
+
with self.suspend():
|
|
268
|
+
err = pager.show(self.settings["pager"], textview.plain(self.agents, row), row["role"])
|
|
269
|
+
except SuspendNotSupported:
|
|
270
|
+
err = "pager: this terminal can't be suspended"
|
|
271
|
+
if err:
|
|
272
|
+
self.status.append(err)
|
|
273
|
+
self.show_status()
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def run(setup) -> int:
|
|
277
|
+
"""0 after `close` (then setup.on_close runs, if set), 1 after ctrl+c/ctrl+q, 2 when the panel crashed.
|
|
278
|
+
|
|
279
|
+
Textual returns None with return_code 1 on an uncaught exception; that must not look like
|
|
280
|
+
ctrl+c, so it becomes 2. Exceptions raised here propagate to cli.main.
|
|
281
|
+
"""
|
|
282
|
+
app = AgyscopeApp(setup.tree, setup.resolver, setup.settings, setup.warnings,
|
|
283
|
+
themes_dir=getattr(setup, "themes_dir", None))
|
|
284
|
+
result = app.run()
|
|
285
|
+
if app.return_code:
|
|
286
|
+
return 2
|
|
287
|
+
if result is not True:
|
|
288
|
+
return 1
|
|
289
|
+
if setup.on_close is not None:
|
|
290
|
+
setup.on_close()
|
|
291
|
+
return 0
|
agyscope/cli.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""agyscope: read-only viewer for the subagents of an Antigravity agent (agy) session.
|
|
2
|
+
|
|
3
|
+
agyscope [--pid PID] [--conversation ID] [settings...]
|
|
4
|
+
Textual panel (refreshes every second)
|
|
5
|
+
agyscope --once ... print the list once as plain text
|
|
6
|
+
agyscope --view CHILD ... print one subagent's view, fully unfolded (CHILD may be a prefix)
|
|
7
|
+
|
|
8
|
+
Which conversation: --pid (the agent process; followed through the presence lock it holds
|
|
9
|
+
open, found with lsof or /proc), then the Rex block pointer for --rex-block, then
|
|
10
|
+
--conversation. The data directory comes from that lock (or the pointer) when there is one;
|
|
11
|
+
--app-dir and the other settings are the fallback.
|
|
12
|
+
|
|
13
|
+
Settings come from flags, then the TOML config file ($AGYSCOPE_CONFIG or
|
|
14
|
+
${XDG_CONFIG_HOME:-~/.config}/agyscope/config.toml):
|
|
15
|
+
--app-dir DIR agent data directory (default ~/.gemini/antigravity-cli)
|
|
16
|
+
--keymap emacs|vim panel keys (default emacs)
|
|
17
|
+
--keys-json JSON extra keys: {"down": ["J"], ...}
|
|
18
|
+
--pager-json JSON pager argv: ["bat", "--paging=always"]
|
|
19
|
+
--theme NAME Textual or user theme name (default textual-dark)
|
|
20
|
+
--marquee / --no-marquee scroll the highlighted row's Last step (default on)
|
|
21
|
+
|
|
22
|
+
Rex integration:
|
|
23
|
+
--rex-block BLOCK follow the Rex block pointer and focus BLOCK after `close`
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import collections
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import sys
|
|
31
|
+
import traceback
|
|
32
|
+
|
|
33
|
+
from . import config, discovery, resolve, textview
|
|
34
|
+
|
|
35
|
+
Setup = collections.namedtuple("Setup", ("args", "settings", "warnings", "resolver", "tree", "on_close",
|
|
36
|
+
"themes_dir"))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse(argv):
|
|
40
|
+
p = argparse.ArgumentParser(prog="agyscope", add_help=True, description=__doc__,
|
|
41
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
42
|
+
p.add_argument("--pid", type=int)
|
|
43
|
+
p.add_argument("--rex-block", metavar="BLOCK")
|
|
44
|
+
p.add_argument("--conversation")
|
|
45
|
+
p.add_argument("--once", action="store_true")
|
|
46
|
+
p.add_argument("--view", metavar="CHILD")
|
|
47
|
+
p.add_argument("--app-dir")
|
|
48
|
+
p.add_argument("--keymap")
|
|
49
|
+
p.add_argument("--keys-json")
|
|
50
|
+
p.add_argument("--pager-json")
|
|
51
|
+
p.add_argument("--theme")
|
|
52
|
+
p.add_argument("--marquee", action=argparse.BooleanOptionalAction, default=None)
|
|
53
|
+
return p.parse_args(argv)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def flags_of(args):
|
|
57
|
+
warnings = []
|
|
58
|
+
flags = {"app_dir": args.app_dir, "keymap": args.keymap, "theme": args.theme, "marquee": args.marquee}
|
|
59
|
+
for name, raw in (("keys", args.keys_json), ("pager", args.pager_json)):
|
|
60
|
+
if raw is None:
|
|
61
|
+
continue
|
|
62
|
+
try:
|
|
63
|
+
flags[name] = json.loads(raw)
|
|
64
|
+
except ValueError:
|
|
65
|
+
warnings.append("flag --%s-json must be JSON; ignored" % name)
|
|
66
|
+
return flags, warnings
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def setup(argv, env=None):
|
|
70
|
+
"""Parsed args, settings and the resolver. Rex code is imported only for --rex-block."""
|
|
71
|
+
args = parse(argv)
|
|
72
|
+
flags, warnings = flags_of(args)
|
|
73
|
+
settings, more = config.load(flags, env=env)
|
|
74
|
+
all_warnings = list(warnings) + list(more)
|
|
75
|
+
fallback = on_close = None
|
|
76
|
+
if args.rex_block:
|
|
77
|
+
from .integrations.rex import focus, pointer
|
|
78
|
+
|
|
79
|
+
def fallback():
|
|
80
|
+
return pointer.read_pointer_full(args.rex_block, env)
|
|
81
|
+
|
|
82
|
+
def on_close():
|
|
83
|
+
return focus.focus_block(args.rex_block, env)
|
|
84
|
+
resolver = resolve.Resolver(settings["app_dir"], pid=args.pid, conversation=args.conversation,
|
|
85
|
+
fallback=fallback)
|
|
86
|
+
tree = discovery.Tree(settings["app_dir"])
|
|
87
|
+
themes_dir = config.themes_dir(os.environ if env is None else env)
|
|
88
|
+
return Setup(args, settings, all_warnings, resolver, tree, on_close, themes_dir)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def run_text(setup):
|
|
92
|
+
args = setup.args
|
|
93
|
+
warnings = setup.warnings
|
|
94
|
+
resolver = setup.resolver
|
|
95
|
+
tree = setup.tree
|
|
96
|
+
|
|
97
|
+
for w in warnings:
|
|
98
|
+
sys.stderr.write("agyscope: %s\n" % w)
|
|
99
|
+
root = resolver.current()
|
|
100
|
+
if not root:
|
|
101
|
+
print("No conversation found for this pane.")
|
|
102
|
+
return 1
|
|
103
|
+
tree.set_root(root, resolver.app_dir)
|
|
104
|
+
groups = tree.rows()
|
|
105
|
+
if args.view:
|
|
106
|
+
for row in discovery.flat(groups):
|
|
107
|
+
if row["id"].startswith(args.view):
|
|
108
|
+
print("\n".join(textview.plain(tree, row)))
|
|
109
|
+
return 0
|
|
110
|
+
sys.stderr.write("agyscope: no subagent %s under %s\n" % (args.view, root))
|
|
111
|
+
return 1
|
|
112
|
+
if not discovery.flat(groups):
|
|
113
|
+
print("No subagents yet.")
|
|
114
|
+
for name, rows in groups:
|
|
115
|
+
if rows:
|
|
116
|
+
print(name)
|
|
117
|
+
for row in rows:
|
|
118
|
+
print(discovery.row_text(row))
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _pause():
|
|
123
|
+
"""On a terminal, keep the pane open so the traceback stays readable."""
|
|
124
|
+
try:
|
|
125
|
+
isatty = getattr(sys.stdin, "isatty", None)
|
|
126
|
+
if isatty is None or not isatty():
|
|
127
|
+
return
|
|
128
|
+
print("agyscope: crashed; press Enter to close")
|
|
129
|
+
input()
|
|
130
|
+
except (EOFError, KeyboardInterrupt, OSError, ValueError):
|
|
131
|
+
pass
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def main(argv=None):
|
|
135
|
+
"""Console entry point: 0 ok/closed, 1 nothing found or ctrl+c, 2 crashed.
|
|
136
|
+
|
|
137
|
+
--once and --view print text without importing Textual. A crash prints the traceback and,
|
|
138
|
+
on a terminal, waits for Enter, so a Rex pane doesn't close before it can be read.
|
|
139
|
+
"""
|
|
140
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
141
|
+
try:
|
|
142
|
+
args = parse(argv)
|
|
143
|
+
if args.once or args.view:
|
|
144
|
+
return run_text(setup(argv))
|
|
145
|
+
from . import app
|
|
146
|
+
rc = app.run(setup(argv))
|
|
147
|
+
except Exception:
|
|
148
|
+
traceback.print_exc()
|
|
149
|
+
_pause()
|
|
150
|
+
return 2
|
|
151
|
+
if rc == 2:
|
|
152
|
+
_pause()
|
|
153
|
+
return rc
|