scope-agent-workbench 0.2.0 → 0.2.3

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.
Files changed (88) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/bridge/agent-email-relay.mjs +160 -160
  3. package/bridge/app-server-websocket-transport.mjs +219 -219
  4. package/bridge/archive/service.mjs +130 -130
  5. package/bridge/auth-profile-failover.mjs +58 -58
  6. package/bridge/auth-profile-manager.mjs +215 -215
  7. package/bridge/capacity-recovery.mjs +90 -90
  8. package/bridge/gpu-usage-history.mjs +322 -322
  9. package/bridge/local/history.mjs +20 -5
  10. package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
  11. package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
  12. package/bridge/private-gateway.mjs +371 -371
  13. package/bridge/private-start.mjs +22 -22
  14. package/bridge/probes/app-server-handoff-probe.mjs +87 -87
  15. package/bridge/probes/app-server-writer-probe.mjs +69 -69
  16. package/bridge/probes/assistant-search-probe.mjs +321 -321
  17. package/bridge/probes/dialogue-probe.mjs +462 -462
  18. package/bridge/probes/history-probe.mjs +430 -345
  19. package/bridge/probes/new-session-preflight.mjs +14 -14
  20. package/bridge/probes/profile-cancel-probe.mjs +17 -17
  21. package/bridge/probes/profile-delete-probe.mjs +26 -26
  22. package/bridge/probes/profile-list-probe.mjs +114 -114
  23. package/bridge/probes/profile-write-probe.mjs +109 -109
  24. package/bridge/probes/raw-context-probe.mjs +51 -51
  25. package/bridge/probes/remote-probe.mjs +627 -626
  26. package/bridge/probes/submission-probe.mjs +2 -2
  27. package/bridge/probes/takeover-probe.mjs +326 -326
  28. package/bridge/probes/vscode-open-preflight.mjs +21 -21
  29. package/bridge/providers/claude-interactive.py +463 -341
  30. package/bridge/providers/cli-command.mjs +103 -103
  31. package/bridge/providers/conversations.mjs +231 -231
  32. package/bridge/providers/native-commands.py +38 -38
  33. package/bridge/providers/native-session-state.mjs +14 -14
  34. package/bridge/providers/native-session-state.py +96 -96
  35. package/bridge/providers/remote-job.py +130 -130
  36. package/bridge/remote-app-server-command.mjs +121 -121
  37. package/bridge/remote-directory-listing.mjs +148 -148
  38. package/bridge/rollout-summary.mjs +20 -2
  39. package/bridge/routes/dialogue.mjs +48 -3
  40. package/bridge/routes/models.mjs +312 -312
  41. package/bridge/server.mjs +3357 -3332
  42. package/bridge/session-attachments.mjs +150 -150
  43. package/bridge/session-catalog/agy-history.py +141 -2
  44. package/bridge/session-catalog/catalog.mjs +17 -0
  45. package/bridge/session-catalog/probe.py +1207 -331
  46. package/bridge/session-catalog/routes.mjs +6 -0
  47. package/bridge/start.mjs +205 -205
  48. package/bridge/state-persistence.mjs +9 -1
  49. package/bridge/tmux-session-control.mjs +29 -29
  50. package/bridge/vscode-opener.mjs +157 -157
  51. package/bridge/web-terminal.mjs +52 -52
  52. package/bridge/workbench/manager-context.mjs +51 -51
  53. package/bridge/workbench/service.mjs +301 -301
  54. package/dist/client/.vite/manifest.json +4 -4
  55. package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
  56. package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
  57. package/dist/client/assets/page-CJqXlhDs.js +551 -0
  58. package/dist/client/assets/page-LYzRz6_S.css +1 -0
  59. package/dist/client/favicon.svg +6 -6
  60. package/dist/server/__vite_rsc_assets_manifest.js +8 -8
  61. package/dist/server/index.js +7 -7
  62. package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
  63. package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
  64. package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
  65. package/dist/server/ssr/index.js +1 -1
  66. package/dist/server/ssr/vinext-server.json +1 -1
  67. package/dist/server/vinext-server.json +1 -1
  68. package/dist/server/wrangler.json +1 -1
  69. package/lib/browser-snapshot-cache.js +53 -53
  70. package/lib/formula-preview.js +1 -1
  71. package/lib/incremental-snapshot.js +300 -300
  72. package/lib/markdown-math.js +151 -151
  73. package/lib/remote-links.js +95 -95
  74. package/lib/runtime-config.js +70 -70
  75. package/lib/session-filters.js +38 -38
  76. package/lib/ssh-config.js +26 -26
  77. package/lib/stable-order.js +39 -39
  78. package/lib/subagent-display-prefs.ts +130 -0
  79. package/package.json +1 -1
  80. package/scripts/agent-email-relay.mjs +104 -104
  81. package/scripts/email-notification-cli.mjs +28 -28
  82. package/scripts/enable-private-access.ps1 +109 -109
  83. package/scripts/fixtures/native-conversations.mjs +164 -6
  84. package/scripts/fixtures/workbench-conversations.mjs +475 -352
  85. package/scripts/preview-workbench.mjs +669 -669
  86. package/dist/client/assets/page-COBv6VWj.css +0 -1
  87. package/dist/client/assets/page-DVjU6VG_.js +0 -550
  88. package/dist/server/ssr/assets/page-COBv6VWj.css +0 -1
@@ -1,331 +1,1207 @@
1
- """Read metadata for native CLI histories. No agent process is started."""
2
- import base64
3
- import glob
4
- import json
5
- import os
6
- from pathlib import Path
7
- import re
8
- import sqlite3
9
- import sys
10
- import time
11
- from urllib.parse import unquote, urlparse
12
-
13
- config = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "=="))
14
- roots = {
15
- "codex": os.path.join(os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex")), "sessions"),
16
- "claude": os.path.join(os.environ.get("CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")), "projects"),
17
- "antigravity": os.path.expanduser("~/.gemini/antigravity-cli"),
18
- }
19
-
20
- def text(content):
21
- if isinstance(content, str):
22
- return content
23
- if not isinstance(content, list):
24
- return ""
25
- return "\n".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in ("text", "input_text", "output_text"))
26
-
27
- def records(filename, full=False):
28
- with open(filename, "rb") as handle:
29
- if full:
30
- # Conversation pages read only a bounded tail; never load an entire log into memory.
31
- size = os.fstat(handle.fileno()).st_size
32
- handle.seek(max(0, size - 2_000_000))
33
- if handle.tell():
34
- handle.readline()
35
- data = handle.read(2_000_000)
36
- else:
37
- data = handle.read(24_000)
38
- size = os.fstat(handle.fileno()).st_size
39
- if size > 24_000:
40
- data = data.rsplit(b"\n", 1)[0] + b"\n"
41
- handle.seek(max(24_000, size - 24_000))
42
- handle.readline()
43
- data += handle.read(24_000)
44
- for line in data.splitlines():
45
- try:
46
- value = json.loads(line)
47
- if isinstance(value, dict):
48
- yield value
49
- except (ValueError, UnicodeError):
50
- pass
51
-
52
- def metadata(provider, filename):
53
- item = {"provider": provider, "sessionId": Path(filename).stem, "path": filename,
54
- "cwd": "", "title": "", "model": "", "updatedAt": int(os.path.getmtime(filename) * 1000)}
55
- for row in records(filename):
56
- if provider == "codex":
57
- payload = row.get("payload") if isinstance(row.get("payload"), dict) else {}
58
- if row.get("type") == "session_meta":
59
- item.update(sessionId=payload.get("id") or item["sessionId"], cwd=payload.get("cwd") or item["cwd"])
60
- if row.get("type") == "turn_context":
61
- item["model"] = payload.get("model") or item["model"]
62
- if row.get("type") == "response_item" and payload.get("role") == "user":
63
- value = text(payload.get("content"))
64
- if value and not value.lstrip().startswith(("<", "# AGENTS", "# Instructions")):
65
- item["title"] = item["title"] or value[:160]
66
- else:
67
- item["cwd"] = row.get("cwd") or item["cwd"]
68
- item["sessionId"] = row.get("sessionId") or item["sessionId"]
69
- message = row.get("message") if isinstance(row.get("message"), dict) else {}
70
- item["model"] = message.get("model") or item["model"]
71
- if row.get("type") == "user" and not row.get("isMeta"):
72
- value = text(message.get("content"))
73
- if value and not value.lstrip().startswith("<"):
74
- item["title"] = item["title"] or value[:160]
75
- if row.get("type") == "summary":
76
- item["title"] = (row.get("summary") or item["title"])[:160]
77
- item["title"] = item["title"] or f"{provider} · {item['sessionId'][:8]}"
78
- return item
79
-
80
- CREATED_SUBAGENT_RE = re.compile(r'Created the following subagent:\s*\{\s*"conversationId"\s*:\s*"([a-zA-Z0-9][a-zA-Z0-9_-]{0,127})"')
81
- SENDER_RE = re.compile(r'sender=([a-zA-Z0-9][a-zA-Z0-9_-]{0,127})')
82
-
83
- def claude_subagents(filename, now_ts):
84
- sub_dir = Path(filename).with_suffix("") / "subagents"
85
- if not sub_dir.is_dir():
86
- return []
87
- files = []
88
- for child in sub_dir.glob("agent-*.jsonl"):
89
- try:
90
- files.append((child.stat().st_mtime, child))
91
- except OSError:
92
- continue
93
- files.sort(key=lambda item: item[0])
94
- result = []
95
- for mtime, child in files[-24:]:
96
- role = ""
97
- last_action = ""
98
- stop_reason = None
99
- last_type = ""
100
- try:
101
- with child.open("rb") as handle:
102
- size = os.fstat(handle.fileno()).st_size
103
- head = handle.read(min(8_192, size))
104
- tail = head if size <= 16_384 else (handle.seek(max(0, size - 16_384)) and False) or handle.read(16_384)
105
- if size > 16_384 and b"\n" in tail:
106
- tail = tail.split(b"\n", 1)[1]
107
- for raw_line in head.splitlines():
108
- try:
109
- row = json.loads(raw_line)
110
- except (ValueError, UnicodeError):
111
- continue
112
- if isinstance(row, dict) and row.get("type") == "user":
113
- val = text((row.get("message") or {}).get("content")).strip()
114
- if val:
115
- role = val.splitlines()[0][:120]
116
- break
117
- for raw_line in tail.splitlines():
118
- try:
119
- row = json.loads(raw_line)
120
- except (ValueError, UnicodeError):
121
- continue
122
- if not isinstance(row, dict):
123
- continue
124
- last_type = row.get("type") or last_type
125
- msg = row.get("message") if isinstance(row.get("message"), dict) else {}
126
- if "stop_reason" in msg:
127
- stop_reason = msg.get("stop_reason")
128
- if isinstance(msg.get("content"), list):
129
- for blk in msg["content"]:
130
- if isinstance(blk, dict) and blk.get("type") == "tool_use" and blk.get("name"):
131
- last_action = str(blk["name"])[:80]
132
- except OSError:
133
- continue
134
- working = (now_ts - mtime < 180) and (stop_reason != "end_turn")
135
- result.append({
136
- "id": child.stem,
137
- "role": role or f"Subagent {child.stem[:10]}",
138
- "typeName": "subagent",
139
- "background": True,
140
- "status": "working" if working else "completed",
141
- "lastAction": last_action or ("运行中" if working else "已完成"),
142
- "updatedAt": int(mtime * 1000),
143
- })
144
- return result
145
-
146
- def agy_active_subagents(brain_root, transcript_file, now_ts):
147
- try:
148
- size = transcript_file.stat().st_size
149
- start = max(0, size - 131_072)
150
- with transcript_file.open("rb") as h:
151
- h.seek(start)
152
- data = h.read(131_072)
153
- if start > 0 and b"\n" in data:
154
- data = data.split(b"\n", 1)[1]
155
- cids, done = [], set()
156
- for line in data.splitlines():
157
- try:
158
- row = json.loads(line)
159
- except (ValueError, UnicodeError):
160
- continue
161
- if not isinstance(row, dict):
162
- continue
163
- if row.get("type") == "GENERIC" and isinstance(row.get("content"), str):
164
- for m in CREATED_SUBAGENT_RE.finditer(row["content"]):
165
- cid = m.group(1)
166
- if cid not in cids:
167
- cids.append(cid)
168
- elif row.get("type") == "SYSTEM_MESSAGE" and isinstance(row.get("content"), str):
169
- m = SENDER_RE.search(row["content"])
170
- if m:
171
- done.add(m.group(1))
172
- count = 0
173
- for cid in cids[-24:]:
174
- if cid in done:
175
- continue
176
- logs = brain_root / cid / ".system_generated/logs"
177
- cf = next((p for p in (logs / "transcript_full.jsonl", logs / "transcript.jsonl") if p.is_file()), None)
178
- if cf is not None and (now_ts - cf.stat().st_mtime) < 180:
179
- count += 1
180
- return count
181
- except OSError:
182
- return 0
183
-
184
- def agy_entries():
185
- filename = os.path.join(roots["antigravity"], "conversation_summaries.db")
186
- if not os.path.exists(filename):
187
- return []
188
- connection = sqlite3.connect(Path(filename).resolve().as_uri() + "?mode=ro", uri=True, timeout=2)
189
- try:
190
- rows = connection.execute("SELECT conversation_id,title,preview,workspace_uris,last_modified_time FROM conversation_summaries").fetchall()
191
- result = []
192
- now_ts = time.time()
193
- brain_root = (Path(roots["antigravity"]) / "brain").resolve()
194
- for sid, title, preview, workspaces, updated in rows:
195
- try:
196
- workspaces = json.loads(workspaces or "[]")
197
- except ValueError:
198
- workspaces = [workspaces] if workspaces else []
199
- if isinstance(workspaces, str):
200
- workspaces = [workspaces]
201
- workspace = next((value for value in workspaces if isinstance(value, str)), "")
202
- cwd = unquote(urlparse(workspace).path) if workspace.startswith("file:") else workspace
203
- if os.name == "nt" and len(cwd) > 2 and cwd[0] == "/" and cwd[2] == ":":
204
- cwd = cwd[1:]
205
- item = {"provider": "antigravity", "sessionId": sid, "cwd": cwd, "title": (title or preview or sid)[:160], "preview": (preview or "")[:1000], "model": "", "updatedAt": str(updated or ""), "path": filename}
206
- # Metadata only: scans never transfer conversation bodies.
207
- if isinstance(sid, str) and sid and all(c.isalnum() or c in "-_" for c in sid):
208
- folder = Path(roots["antigravity"]) / "brain" / sid / ".system_generated/logs"
209
- for name in ("transcript_full.jsonl", "transcript.jsonl"):
210
- try:
211
- tf = folder / name
212
- stat = tf.stat()
213
- item["historyVersion"] = f"{name}:{stat.st_mtime_ns}:{stat.st_size}"
214
- if now_ts - stat.st_mtime < 600:
215
- active = agy_active_subagents(brain_root, tf, now_ts)
216
- if active > 0:
217
- item["activeSubagents"] = active
218
- break
219
- except OSError:
220
- continue
221
- result.append(item)
222
- return result
223
- finally:
224
- connection.close()
225
-
226
- def codex_labels():
227
- root = Path(roots["codex"]).parent
228
- labels = {}
229
- database = root / "state_5.sqlite"
230
- if database.exists():
231
- connection = None
232
- try:
233
- connection = sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True, timeout=2)
234
- columns = {row[1] for row in connection.execute("PRAGMA table_info(threads)")}
235
- selected = [name for name in ("id", "title", "name", "model", "cwd") if name in columns]
236
- if "id" in selected:
237
- for row in connection.execute("SELECT " + ",".join(selected) + " FROM threads"):
238
- item = dict(zip(selected, row))
239
- labels[item["id"]] = item
240
- except sqlite3.Error:
241
- pass # The index is optional; JSONL remains the source of discoverable records.
242
- finally:
243
- if connection:
244
- connection.close()
245
- try:
246
- with (root / "session_index.jsonl").open(encoding="utf-8") as handle:
247
- for line in handle:
248
- try:
249
- item = json.loads(line)
250
- if item.get("id") and item.get("thread_name"):
251
- labels.setdefault(item["id"], {})["name"] = item["thread_name"]
252
- except ValueError:
253
- pass
254
- except OSError:
255
- pass
256
- return labels
257
-
258
- if config.get("operation") == "dialogue":
259
- provider, filename = config["provider"], os.path.realpath(config["path"])
260
- root = os.path.realpath(roots.get(provider, ""))
261
- if provider not in ("codex", "claude") or os.path.commonpath([root, filename]) != root or not filename.endswith(".jsonl"):
262
- raise ValueError("不支持读取这个会话路径")
263
- messages = []
264
- for row in records(filename, full=True):
265
- message = row.get("payload", {}) if provider == "codex" and row.get("type") == "response_item" else row.get("message", {}) if provider == "claude" else {}
266
- if not isinstance(message, dict):
267
- continue
268
- role = message.get("role")
269
- value = text(message.get("content"))
270
- if role in ("user", "assistant") and value:
271
- messages.append({"role": role, "text": value[:30_000]})
272
- payload = {"messages": messages[-100:], "limited": os.path.getsize(filename) > 2_000_000 or len(messages) > 100}
273
- if provider == "claude":
274
- payload["subagents"] = claude_subagents(filename, time.time())
275
- print(json.dumps(payload, ensure_ascii=False))
276
- else:
277
- cache_file = Path.home() / ".cache" / "scope" / "session-catalog-v1.json"
278
- try:
279
- cache = json.loads(cache_file.read_text(encoding="utf-8"))
280
- except (OSError, ValueError):
281
- cache = {}
282
- entries, errors, next_cache = [], [], {}
283
- now_ts = time.time()
284
- for provider in ("codex", "claude"):
285
- for filename in glob.iglob(os.path.join(roots[provider], "**", "*.jsonl"), recursive=True):
286
- if provider == "claude" and "subagents" in Path(filename).parts:
287
- continue # Child transcripts share the parent sessionId; they are not resumable sessions.
288
- try:
289
- stat = os.stat(filename)
290
- sub_dir = Path(filename).with_suffix("") / "subagents" if provider == "claude" else None
291
- sub_mtime = os.stat(sub_dir).st_mtime if sub_dir and sub_dir.is_dir() else 0
292
- recent = (now_ts - max(stat.st_mtime, sub_mtime)) < 600
293
- stamp = [stat.st_mtime_ns, stat.st_size]
294
- saved = cache.get(filename)
295
- item = dict(saved["item"]) if saved and saved.get("stamp") == stamp else metadata(provider, filename)
296
- next_cache[filename] = {"stamp": stamp, "item": item}
297
- if provider == "claude" and recent and sub_dir and sub_dir.is_dir():
298
- active = sum(1 for sub in claude_subagents(filename, now_ts) if sub["status"] == "working")
299
- if active > 0:
300
- item = {**item, "activeSubagents": active}
301
- entries.append(item)
302
- except (OSError, ValueError, TypeError) as error:
303
- errors.append(f"{provider}: {type(error).__name__}")
304
- labels = codex_labels()
305
- for item in entries:
306
- if item["provider"] != "codex":
307
- continue
308
- label = labels.get(item["sessionId"], {})
309
- item["title"] = (label.get("name") or label.get("title") or item["title"])[:160]
310
- item["cwd"] = label.get("cwd") or item["cwd"]
311
- item["model"] = label.get("model") or item["model"]
312
- try:
313
- entries.extend(agy_entries())
314
- except (sqlite3.Error, ValueError, TypeError) as error:
315
- errors.append("antigravity: " + str(error))
316
- for item in entries:
317
- if item["provider"] in ("claude", "antigravity"):
318
- try:
319
- state = json.loads((Path.home() / ".local/state/scope" / (item["provider"] + "-sessions") / (item["sessionId"] + ".json")).read_text())
320
- item["phase"] = state.get("phase", "active")
321
- except FileNotFoundError:
322
- item["phase"] = "active"
323
- try:
324
- cache_file.parent.mkdir(parents=True, exist_ok=True)
325
- temporary = cache_file.with_suffix(f".{os.getpid()}.tmp")
326
- temporary.write_text(json.dumps(next_cache, ensure_ascii=False), encoding="utf-8")
327
- os.chmod(temporary, 0o600)
328
- os.replace(temporary, cache_file)
329
- except OSError:
330
- pass
331
- print(json.dumps({"entries": entries, "errors": list(dict.fromkeys(errors)), "roots": roots}, ensure_ascii=False))
1
+ """Read metadata for native CLI histories. No agent process is started."""
2
+ import base64
3
+ import glob
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import re
8
+ import sqlite3
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ from urllib.parse import unquote, urlparse
13
+
14
+ try:
15
+ import fcntl
16
+ except ImportError:
17
+ fcntl = None
18
+
19
+ if hasattr(sys.stdout, "reconfigure"):
20
+ sys.stdout.reconfigure(encoding="utf-8")
21
+
22
+ config = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "=="))
23
+ roots = {
24
+ "codex": os.path.join(os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex")), "sessions"),
25
+ "claude": os.path.join(os.environ.get("CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")), "projects"),
26
+ "antigravity": os.path.expanduser("~/.gemini/antigravity-cli"),
27
+ }
28
+
29
+ def text(content):
30
+ if isinstance(content, str):
31
+ return content
32
+ if not isinstance(content, list):
33
+ return ""
34
+ return "\n".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in ("text", "input_text", "output_text"))
35
+
36
+ def records(filename, full=False, max_bytes=2_000_000):
37
+ with open(filename, "rb") as handle:
38
+ size = os.fstat(handle.fileno()).st_size
39
+ if full:
40
+ # Stream line-by-line over a bounded tail; skip oversized debug/request blobs before json.loads.
41
+ if size > max_bytes:
42
+ handle.seek(size - max_bytes)
43
+ handle.readline()
44
+ for line in handle:
45
+ if not line.strip():
46
+ continue
47
+ head = line[:160]
48
+ if b'"type":"api-request' in head or b'"type": "api-request' in head or b'"type":"data-flow-records' in head or b'"type": "data-flow-records' in head:
49
+ continue
50
+ try:
51
+ value = json.loads(line)
52
+ if isinstance(value, dict):
53
+ yield value
54
+ except (ValueError, UnicodeError):
55
+ pass
56
+ return
57
+ data = handle.read(24_000)
58
+ if size > 24_000:
59
+ data = data.rsplit(b"\n", 1)[0] + b"\n"
60
+ handle.seek(max(24_000, size - 24_000))
61
+ handle.readline()
62
+ data += handle.read(24_000)
63
+ for line in data.splitlines():
64
+ try:
65
+ value = json.loads(line)
66
+ if isinstance(value, dict):
67
+ yield value
68
+ except (ValueError, UnicodeError):
69
+ pass
70
+
71
+ def metadata(provider, filename):
72
+ item = {"provider": provider, "sessionId": Path(filename).stem, "path": filename,
73
+ "cwd": "", "title": "", "model": "", "updatedAt": int(os.path.getmtime(filename) * 1000)}
74
+ for row in records(filename):
75
+ if provider == "codex":
76
+ payload = row.get("payload") if isinstance(row.get("payload"), dict) else {}
77
+ if row.get("type") == "session_meta":
78
+ item.update(sessionId=payload.get("id") or item["sessionId"], cwd=payload.get("cwd") or item["cwd"])
79
+ if row.get("type") == "turn_context":
80
+ item["model"] = payload.get("model") or item["model"]
81
+ if row.get("type") == "response_item" and payload.get("role") == "user":
82
+ value = text(payload.get("content"))
83
+ if value and not value.lstrip().startswith(("<", "# AGENTS", "# Instructions")):
84
+ item["title"] = item["title"] or value[:160]
85
+ else:
86
+ item["cwd"] = row.get("cwd") or item["cwd"]
87
+ item["sessionId"] = row.get("sessionId") or item["sessionId"]
88
+ message = row.get("message") if isinstance(row.get("message"), dict) else {}
89
+ item["model"] = message.get("model") or item["model"]
90
+ if row.get("type") == "user" and not row.get("isMeta"):
91
+ value = text(message.get("content"))
92
+ if value and not value.lstrip().startswith("<"):
93
+ item["title"] = item["title"] or value[:160]
94
+ if row.get("type") == "summary":
95
+ item["title"] = (row.get("summary") or item["title"])[:160]
96
+ item["title"] = item["title"] or f"{provider} · {item['sessionId'][:8]}"
97
+ return item
98
+
99
+ CREATED_SUBAGENT_RE = re.compile(r'Created the following subagent:\s*\{\s*"conversationId"\s*:\s*"([a-zA-Z0-9][a-zA-Z0-9_-]{0,127})"')
100
+ SENDER_RE = re.compile(r'sender=([a-zA-Z0-9][a-zA-Z0-9_-]{0,127})')
101
+ CLAUDE_AGENT_ID_RE = re.compile(r'^agent-[a-zA-Z0-9_-]{1,64}$')
102
+ CLAUDE_LOOKUP_ID_RE = re.compile(r'^[a-zA-Z0-9_-]{4,96}$')
103
+
104
+ def read_claude_subagent_meta(jsonl_path):
105
+ meta_path = jsonl_path.with_suffix(".meta.json")
106
+ try:
107
+ if not meta_path.is_file():
108
+ return {}, 0
109
+ st = meta_path.stat()
110
+ with meta_path.open("rb") as h:
111
+ raw = h.read(16_384)
112
+ data = json.loads(raw.decode("utf-8", errors="replace"))
113
+ return (data if isinstance(data, dict) else {}), st.st_mtime_ns
114
+ except (OSError, ValueError):
115
+ return {}, 0
116
+
117
+ def summarize_tool_input(name, raw_input):
118
+ if isinstance(raw_input, dict):
119
+ for key in ("description", "file_path", "path", "command", "cmd", "pattern", "query", "url", "glob", "notebook_path", "prompt"):
120
+ val = raw_input.get(key)
121
+ if isinstance(val, str) and val.strip():
122
+ line = val.strip().splitlines()[0].strip()
123
+ if key in ("file_path", "path", "notebook_path") and ("/" in line or "\\" in line):
124
+ short = line.replace("\\", "/").split("/")[-1] or line
125
+ return short[:90]
126
+ return line[:90]
127
+ if isinstance(raw_input, str) and raw_input.strip():
128
+ return raw_input.strip().splitlines()[0][:90]
129
+ return ""
130
+
131
+ def clip_text(value, limit):
132
+ if len(value) <= limit:
133
+ return value, False
134
+ omitted = len(value) - limit
135
+ return value[:limit] + f"\n\n… [已截断 {omitted} 个字符]", True
136
+
137
+ def extract_tool_result_text(content, limit=6000):
138
+ if isinstance(content, str):
139
+ return clip_text(content.replace("\x00", ""), limit)
140
+ if isinstance(content, list):
141
+ parts = []
142
+ for part in content:
143
+ if isinstance(part, str):
144
+ parts.append(part)
145
+ elif isinstance(part, dict):
146
+ ptype = part.get("type")
147
+ if ptype in ("text", "input_text", "output_text") and isinstance(part.get("text"), str):
148
+ parts.append(part["text"])
149
+ elif ptype == "image":
150
+ parts.append("[image]")
151
+ elif isinstance(part.get("content"), str):
152
+ parts.append(part["content"])
153
+ return clip_text("\n".join(parts).replace("\x00", ""), limit)
154
+ if isinstance(content, dict):
155
+ return clip_text(json.dumps(content, ensure_ascii=False).replace("\x00", ""), limit)
156
+ return "", False
157
+
158
+ AGENT_MSG_RE = re.compile(r'<agent-message\s+from="([^"]+)"[^>]*>([\s\S]*?)</agent-message>')
159
+ TASK_NOTIF_RE = re.compile(r'<task-notification>([\s\S]*?)</task-notification>')
160
+
161
+ def _xml_tag(body, tag):
162
+ m = re.search(rf'<{tag}>([\s\S]*?)</{tag}>', body)
163
+ return m.group(1).strip() if m else ""
164
+
165
+ def parse_claude_agent_message(raw_text):
166
+ if not isinstance(raw_text, str) or "<agent-message" not in raw_text:
167
+ return None
168
+ m = AGENT_MSG_RE.search(raw_text)
169
+ if not m:
170
+ return None
171
+ sender = m.group(1).strip()[:120]
172
+ body = m.group(2).strip()
173
+ is_handback = "[Subagent hand-back]" in body[:200]
174
+ if is_handback:
175
+ marker = "The report follows:"
176
+ idx = body.find(marker)
177
+ if idx >= 0:
178
+ body = body[idx + len(marker):].lstrip("\r\n")
179
+ body = "\n".join(line[2:] if line.startswith(" ") else line for line in body.splitlines()).strip()
180
+ first_line = next((ln.strip().lstrip("#*- ").strip() for ln in body.splitlines() if ln.strip()), "")[:110]
181
+ return {
182
+ "from": sender,
183
+ "kind": "handback" if is_handback else "message",
184
+ "summary": first_line,
185
+ "text": body[:16_000],
186
+ }
187
+
188
+ def parse_claude_task_notification(raw_text):
189
+ if not isinstance(raw_text, str) or "<task-notification>" not in raw_text:
190
+ return None
191
+ m = TASK_NOTIF_RE.search(raw_text)
192
+ if not m:
193
+ return None
194
+ inner = m.group(1)
195
+ task_id = _xml_tag(inner, "task-id")
196
+ tool_use_id = _xml_tag(inner, "tool-use-id")
197
+ status = _xml_tag(inner, "status") or "completed"
198
+ summary = _xml_tag(inner, "summary")
199
+ result = _xml_tag(inner, "result")
200
+ return {
201
+ "taskId": task_id,
202
+ "toolUseId": tool_use_id,
203
+ "status": status,
204
+ "summary": summary[:160],
205
+ "text": (result or summary)[:12_000],
206
+ }
207
+
208
+ UUID_RE = re.compile(r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$")
209
+
210
+ def collect_tmux_ttys():
211
+ if os.name == "nt":
212
+ return set()
213
+ try:
214
+ proc = subprocess.run(
215
+ ["tmux", "list-panes", "-a", "-F", "#{pane_tty}"],
216
+ stdout=subprocess.PIPE,
217
+ stderr=subprocess.DEVNULL,
218
+ text=True,
219
+ timeout=1.5,
220
+ )
221
+ if proc.returncode == 0 and proc.stdout:
222
+ return {line.strip() for line in proc.stdout.splitlines() if line.strip()}
223
+ except (OSError, subprocess.SubprocessError):
224
+ pass
225
+ return set()
226
+
227
+ def scope_lock_active(provider, sid):
228
+ if fcntl is None or not sid:
229
+ return False
230
+ lock_file = Path.home() / ".local/state/scope" / f"{provider}-sessions" / f"{sid}.lock"
231
+ if not lock_file.is_file():
232
+ return False
233
+ try:
234
+ with lock_file.open("r") as handle:
235
+ try:
236
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
237
+ except BlockingIOError:
238
+ return True
239
+ else:
240
+ fcntl.flock(handle, fcntl.LOCK_UN)
241
+ return False
242
+ except OSError:
243
+ return False
244
+
245
+ def _read_proc_cmdline(pid):
246
+ try:
247
+ raw = Path(f"/proc/{pid}/cmdline").read_bytes()
248
+ return [part for part in raw.decode("utf-8", errors="replace").split("\0") if part]
249
+ except OSError:
250
+ return []
251
+
252
+ def _read_proc_ppid(pid):
253
+ try:
254
+ stat_txt = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace")
255
+ rparen = stat_txt.rfind(")")
256
+ if rparen < 0:
257
+ return 0
258
+ fields = stat_txt[rparen + 2:].split()
259
+ return int(fields[1]) if len(fields) > 1 else 0
260
+ except (OSError, ValueError):
261
+ return 0
262
+
263
+ def pid_tty_and_scope(pid, tmux_ttys):
264
+ if os.name == "nt" or not pid or pid <= 0:
265
+ return "", False, False
266
+ args = _read_proc_cmdline(pid)
267
+ is_scope = False
268
+ if "--input-format" in args and "stream-json" in args:
269
+ is_scope = True
270
+ elif len(args) >= 2 and Path(args[0]).name == "agy" and args[1] == "acp":
271
+ is_scope = True
272
+ if not is_scope:
273
+ cur = pid
274
+ for _ in range(5):
275
+ ppid = _read_proc_ppid(cur)
276
+ if ppid <= 1 or ppid == cur:
277
+ break
278
+ pargs = " ".join(_read_proc_cmdline(ppid))
279
+ if (
280
+ ".local/state/scope/runs" in pargs
281
+ or "claude-interactive" in pargs
282
+ or "antigravity-interactive" in pargs
283
+ or "native-session-state" in pargs
284
+ ):
285
+ is_scope = True
286
+ break
287
+ cur = ppid
288
+ full_tty = ""
289
+ short_tty = ""
290
+ try:
291
+ link = os.readlink(f"/proc/{pid}/fd/0")
292
+ if link.startswith("/dev/pts/") or link.startswith("/dev/tty"):
293
+ full_tty = link
294
+ short_tty = link[len("/dev/"):]
295
+ except OSError:
296
+ pass
297
+ return short_tty, bool(full_tty and full_tty in tmux_ttys), is_scope
298
+
299
+ def _format_lock_reason(tty, pid, in_tmux):
300
+ where = f"tmux ({tty})" if (in_tmux and tty) else (tty or "远端终端")
301
+ return f"外部终端占用 ({where} · PID {pid})" if pid else f"外部终端占用 ({where})"
302
+
303
+ def detect_claude_external_locks(tmux_ttys, target_sid=None):
304
+ if os.name == "nt":
305
+ return {}
306
+ locks = {}
307
+ registry = Path(roots["claude"]).parent / "sessions"
308
+ if registry.is_dir():
309
+ for entry in registry.glob("*.json"):
310
+ try:
311
+ record = json.loads(entry.read_text(encoding="utf-8", errors="replace"))
312
+ except (OSError, ValueError):
313
+ continue
314
+ if not isinstance(record, dict):
315
+ continue
316
+ sid = str(record.get("sessionId") or "")
317
+ if not sid or (target_sid and sid != target_sid):
318
+ continue
319
+ try:
320
+ pid = int(record.get("pid") or 0)
321
+ except (TypeError, ValueError):
322
+ continue
323
+ if pid <= 0:
324
+ continue
325
+ try:
326
+ os.kill(pid, 0)
327
+ except OSError:
328
+ continue
329
+ if scope_lock_active("claude", sid):
330
+ continue
331
+ tty, in_tmux, is_scope = pid_tty_and_scope(pid, tmux_ttys)
332
+ if is_scope:
333
+ continue
334
+ locks[sid] = {
335
+ "locked": True,
336
+ "pid": pid,
337
+ "tty": tty,
338
+ "inTmux": in_tmux,
339
+ "entrypoint": str(record.get("entrypoint") or "cli")[:40],
340
+ "status": str(record.get("status") or "active")[:40],
341
+ "name": str(record.get("name") or "")[:80],
342
+ "reason": _format_lock_reason(tty, pid, in_tmux),
343
+ }
344
+ proc_root = Path("/proc")
345
+ if proc_root.is_dir():
346
+ for cmd_file in proc_root.glob("[0-9]*/cmdline"):
347
+ try:
348
+ pid = int(cmd_file.parent.name)
349
+ args = [p for p in cmd_file.read_bytes().decode("utf-8", errors="replace").split("\0") if p]
350
+ except (OSError, ValueError):
351
+ continue
352
+ if not args or not any("claude" in Path(a).name for a in args[:2]):
353
+ continue
354
+ for idx, arg in enumerate(args):
355
+ if arg in ("--resume", "--session-id", "-r") and idx + 1 < len(args):
356
+ sid = args[idx + 1]
357
+ if not UUID_RE.fullmatch(sid) or sid in locks or (target_sid and sid != target_sid):
358
+ continue
359
+ if scope_lock_active("claude", sid):
360
+ continue
361
+ tty, in_tmux, is_scope = pid_tty_and_scope(pid, tmux_ttys)
362
+ if is_scope:
363
+ continue
364
+ locks[sid] = {
365
+ "locked": True,
366
+ "pid": pid,
367
+ "tty": tty,
368
+ "inTmux": in_tmux,
369
+ "entrypoint": "cli",
370
+ "status": "active",
371
+ "reason": _format_lock_reason(tty, pid, in_tmux),
372
+ }
373
+ return locks
374
+
375
+ def detect_agy_external_locks(tmux_ttys, target_sid=None):
376
+ if os.name == "nt":
377
+ return {}
378
+ locks = {}
379
+ locked_sids = set()
380
+ presence_dir = Path(roots["antigravity"]) / "presence"
381
+ if fcntl is not None and presence_dir.is_dir():
382
+ candidates = [presence_dir / f"{target_sid}.lock"] if target_sid else list(presence_dir.glob("*.lock"))
383
+ for lock_file in candidates:
384
+ if not lock_file.is_file():
385
+ continue
386
+ sid = lock_file.stem
387
+ try:
388
+ with lock_file.open("r") as handle:
389
+ try:
390
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
391
+ except BlockingIOError:
392
+ locked_sids.add(sid)
393
+ else:
394
+ fcntl.flock(handle, fcntl.LOCK_UN)
395
+ except OSError:
396
+ continue
397
+ pid_by_sid = {}
398
+ proc_root = Path("/proc")
399
+ if proc_root.is_dir():
400
+ for cmd_file in proc_root.glob("[0-9]*/cmdline"):
401
+ try:
402
+ pid = int(cmd_file.parent.name)
403
+ args = [p for p in cmd_file.read_bytes().decode("utf-8", errors="replace").split("\0") if p]
404
+ except (OSError, ValueError):
405
+ continue
406
+ if not args or not any(Path(a).name == "agy" or "antigravity" in Path(a).name for a in args[:2]):
407
+ continue
408
+ for idx, arg in enumerate(args):
409
+ if arg in ("--conversation", "-c") and idx + 1 < len(args):
410
+ sid = args[idx + 1]
411
+ if (not target_sid or sid == target_sid) and sid not in pid_by_sid:
412
+ pid_by_sid[sid] = pid
413
+ locked_sids.add(sid)
414
+ fd_dir = cmd_file.parent / "fd"
415
+ try:
416
+ for fd_link in fd_dir.iterdir():
417
+ try:
418
+ target = os.readlink(str(fd_link))
419
+ except OSError:
420
+ continue
421
+ if "/antigravity-cli/presence/" in target and target.endswith(".lock"):
422
+ sid = Path(target).stem
423
+ if not target_sid or sid == target_sid:
424
+ pid_by_sid[sid] = pid
425
+ locked_sids.add(sid)
426
+ except OSError:
427
+ continue
428
+ for sid in locked_sids:
429
+ if scope_lock_active("antigravity", sid):
430
+ continue
431
+ pid = pid_by_sid.get(sid, 0)
432
+ tty, in_tmux, is_scope = pid_tty_and_scope(pid, tmux_ttys) if pid else ("", False, False)
433
+ if is_scope:
434
+ continue
435
+ locks[sid] = {
436
+ "locked": True,
437
+ "pid": pid or None,
438
+ "tty": tty,
439
+ "inTmux": in_tmux,
440
+ "entrypoint": "cli",
441
+ "status": "active",
442
+ "reason": _format_lock_reason(tty, pid, in_tmux),
443
+ }
444
+ return locks
445
+
446
+ def claude_subagents(filename, now_ts, limit=60):
447
+ sub_dir = Path(filename).with_suffix("") / "subagents"
448
+ if not sub_dir.is_dir():
449
+ return [], 0
450
+ files = []
451
+ for child in sub_dir.glob("agent-*.jsonl"):
452
+ try:
453
+ st = child.stat()
454
+ files.append((st.st_mtime, st.st_size, child))
455
+ except OSError:
456
+ continue
457
+ total_count = len(files)
458
+ files.sort(key=lambda item: item[0])
459
+ result = []
460
+ for mtime, size, child in files[-limit:]:
461
+ meta, _ = read_claude_subagent_meta(child)
462
+ role = str(meta.get("description") or "").strip()[:120]
463
+ type_name = str(meta.get("agentType") or "subagent")[:60]
464
+ tool_use_id = str(meta.get("toolUseId") or "")[:96]
465
+ model = str(meta.get("pickedEffortModel") or meta.get("model") or "")[:80]
466
+ spawn_depth = meta.get("spawnDepth") if isinstance(meta.get("spawnDepth"), int) else None
467
+ finished = meta.get("finished") if isinstance(meta.get("finished"), bool) else None
468
+ background = meta.get("requestShape") != "foreground"
469
+ last_action = ""
470
+ stop_reason = None
471
+ need_tail = (not role) or (finished is not True) or (not model)
472
+ if need_tail:
473
+ try:
474
+ with child.open("rb") as handle:
475
+ head = handle.read(min(8_192, size)) if not role else b""
476
+ if size <= 16_384:
477
+ handle.seek(0)
478
+ tail = handle.read(16_384)
479
+ else:
480
+ handle.seek(max(0, size - 16_384))
481
+ tail = handle.read(16_384)
482
+ if size > 16_384 and b"\n" in tail:
483
+ tail = tail.split(b"\n", 1)[1]
484
+ if not role and head:
485
+ for raw_line in head.splitlines():
486
+ try:
487
+ row = json.loads(raw_line)
488
+ except (ValueError, UnicodeError):
489
+ continue
490
+ if isinstance(row, dict) and row.get("type") == "user":
491
+ val = text((row.get("message") or {}).get("content")).strip()
492
+ if val:
493
+ role = val.splitlines()[0][:120]
494
+ break
495
+ for raw_line in tail.splitlines():
496
+ if b'"type":"api-request' in raw_line or b'"type": "api-request' in raw_line:
497
+ continue
498
+ try:
499
+ row = json.loads(raw_line)
500
+ except (ValueError, UnicodeError):
501
+ continue
502
+ if not isinstance(row, dict):
503
+ continue
504
+ msg = row.get("message") if isinstance(row.get("message"), dict) else {}
505
+ if "stop_reason" in msg:
506
+ stop_reason = msg.get("stop_reason")
507
+ if not model and isinstance(msg.get("model"), str):
508
+ model = msg["model"][:80]
509
+ if isinstance(msg.get("content"), list):
510
+ for blk in msg["content"]:
511
+ if isinstance(blk, dict) and blk.get("type") == "tool_use" and blk.get("name"):
512
+ summary = summarize_tool_input(blk["name"], blk.get("input"))
513
+ last_action = f"{blk['name']} · {summary}"[:96] if summary else str(blk["name"])[:80]
514
+ except OSError:
515
+ continue
516
+ if finished is True:
517
+ working = False
518
+ elif finished is False:
519
+ working = (now_ts - mtime) < 300
520
+ else:
521
+ working = (now_ts - mtime < 180) and (stop_reason != "end_turn")
522
+ entry = {
523
+ "id": child.stem,
524
+ "agentId": child.stem,
525
+ "role": role or f"Subagent {child.stem[:10]}",
526
+ "typeName": type_name,
527
+ "background": background,
528
+ "status": "working" if working else "completed",
529
+ "lastAction": last_action or ("运行中" if working else "已完成"),
530
+ "updatedAt": int(mtime * 1000),
531
+ "sizeBytes": size,
532
+ "hasWorkflow": True,
533
+ }
534
+ if tool_use_id:
535
+ entry["toolUseId"] = tool_use_id
536
+ if model:
537
+ entry["model"] = model
538
+ if spawn_depth is not None:
539
+ entry["spawnDepth"] = spawn_depth
540
+ result.append(entry)
541
+ return result, total_count
542
+
543
+ def resolve_claude_subagent_file(sub_dir, subagent_id):
544
+ if not isinstance(subagent_id, str) or not subagent_id:
545
+ raise ValueError("缺少子代理标识")
546
+ sub_root = os.path.realpath(str(sub_dir))
547
+ candidate = None
548
+ if CLAUDE_AGENT_ID_RE.fullmatch(subagent_id):
549
+ candidate = sub_dir / f"{subagent_id}.jsonl"
550
+ elif CLAUDE_LOOKUP_ID_RE.fullmatch(subagent_id):
551
+ direct = sub_dir / f"agent-{subagent_id}.jsonl"
552
+ if direct.is_file():
553
+ candidate = direct
554
+ else:
555
+ for meta_file in sub_dir.glob("*.meta.json"):
556
+ try:
557
+ data = json.loads(meta_file.read_bytes()[:16_384].decode("utf-8", errors="replace"))
558
+ except (OSError, ValueError):
559
+ continue
560
+ if isinstance(data, dict) and data.get("toolUseId") == subagent_id:
561
+ stem = meta_file.name[:-len(".meta.json")]
562
+ if CLAUDE_AGENT_ID_RE.fullmatch(stem):
563
+ candidate = sub_dir / f"{stem}.jsonl"
564
+ break
565
+ else:
566
+ raise ValueError("子代理标识无效")
567
+ if candidate is None or not candidate.is_file():
568
+ return None
569
+ resolved = os.path.realpath(str(candidate))
570
+ if os.path.commonpath([sub_root, resolved]) != sub_root:
571
+ raise ValueError("子代理路径超出允许范围")
572
+ return Path(resolved)
573
+
574
+ def claude_subagent_workflow(parent_filename, subagent_id, known_version=None):
575
+ sub_dir = Path(parent_filename).with_suffix("") / "subagents"
576
+ if not sub_dir.is_dir():
577
+ return {"found": False, "steps": [], "status": "unknown"}
578
+ target = resolve_claude_subagent_file(sub_dir, subagent_id)
579
+ if target is None:
580
+ return {"found": False, "steps": [], "status": "unknown"}
581
+ st = target.stat()
582
+ meta, meta_mtime_ns = read_claude_subagent_meta(target)
583
+ version = f"{st.st_mtime_ns}:{st.st_size}:{meta_mtime_ns}"
584
+ if known_version and known_version == version:
585
+ return {"found": True, "notModified": True, "version": version}
586
+
587
+ steps = []
588
+ tools_by_id = {}
589
+ prompt_captured = False
590
+ stop_reason = None
591
+ model = str(meta.get("pickedEffortModel") or meta.get("model") or "")[:80]
592
+ role = str(meta.get("description") or "").strip()[:160]
593
+ step_seq = 0
594
+
595
+ with target.open("rb") as handle:
596
+ for raw_line in handle:
597
+ if not raw_line.strip():
598
+ continue
599
+ if (
600
+ b'"type":"api-request' in raw_line
601
+ or b'"type": "api-request' in raw_line
602
+ or b'"type":"data-flow-records' in raw_line
603
+ or b'"type": "data-flow-records' in raw_line
604
+ ):
605
+ continue
606
+ try:
607
+ row = json.loads(raw_line.decode("utf-8", errors="replace"))
608
+ except ValueError:
609
+ continue
610
+ if not isinstance(row, dict):
611
+ continue
612
+ rtype = row.get("type")
613
+ if rtype not in ("user", "assistant"):
614
+ continue
615
+ ts = row.get("timestamp")
616
+ msg = row.get("message") if isinstance(row.get("message"), dict) else {}
617
+ if not model and isinstance(msg.get("model"), str):
618
+ model = msg["model"][:80]
619
+ if "stop_reason" in msg:
620
+ stop_reason = msg.get("stop_reason")
621
+ content = msg.get("content")
622
+
623
+ if rtype == "user":
624
+ if isinstance(content, str):
625
+ val = content.strip()
626
+ if val and not row.get("isMeta"):
627
+ is_first = not prompt_captured
628
+ prompt_captured = True
629
+ if is_first and not role:
630
+ role = val.splitlines()[0][:160]
631
+ clipped, trunc = clip_text(val, 16_000)
632
+ step_seq += 1
633
+ steps.append({
634
+ "id": f"prompt-{step_seq}",
635
+ "kind": "prompt",
636
+ "title": "子代理任务" if is_first else "主会话追加指令",
637
+ "text": clipped,
638
+ "truncated": trunc,
639
+ "timestamp": ts,
640
+ })
641
+ elif isinstance(content, list):
642
+ plain_parts = []
643
+ for blk in content:
644
+ if not isinstance(blk, dict):
645
+ continue
646
+ btype = blk.get("type")
647
+ if btype == "tool_result":
648
+ tid = str(blk.get("tool_use_id") or "")
649
+ out_text, out_trunc = extract_tool_result_text(blk.get("content"), 6000)
650
+ is_err = bool(blk.get("is_error"))
651
+ tool_step = tools_by_id.get(tid)
652
+ if tool_step is not None:
653
+ tool_step["output"] = out_text
654
+ tool_step["outputTruncated"] = out_trunc
655
+ tool_step["isError"] = is_err
656
+ tool_step["status"] = "failed" if is_err else "completed"
657
+ elif out_text:
658
+ step_seq += 1
659
+ steps.append({
660
+ "id": f"tool-out-{step_seq}",
661
+ "kind": "tool",
662
+ "toolName": "tool_result",
663
+ "title": "工具输出",
664
+ "summary": "",
665
+ "output": out_text,
666
+ "outputTruncated": out_trunc,
667
+ "isError": is_err,
668
+ "status": "failed" if is_err else "completed",
669
+ "timestamp": ts,
670
+ })
671
+ elif btype in ("text", "input_text") and isinstance(blk.get("text"), str):
672
+ plain_parts.append(blk["text"])
673
+ if plain_parts and not row.get("isMeta"):
674
+ val = "\n".join(plain_parts).strip()
675
+ if val:
676
+ is_first = not prompt_captured
677
+ prompt_captured = True
678
+ if is_first and not role:
679
+ role = val.splitlines()[0][:160]
680
+ clipped, trunc = clip_text(val, 16_000)
681
+ step_seq += 1
682
+ steps.append({
683
+ "id": f"prompt-{step_seq}",
684
+ "kind": "prompt",
685
+ "title": "子代理任务" if is_first else "主会话追加指令",
686
+ "text": clipped,
687
+ "truncated": trunc,
688
+ "timestamp": ts,
689
+ })
690
+ elif rtype == "assistant" and isinstance(content, list):
691
+ thinking_ms = row.get("thinkingDurationMs") if isinstance(row.get("thinkingDurationMs"), (int, float)) else None
692
+ for blk in content:
693
+ if not isinstance(blk, dict):
694
+ continue
695
+ btype = blk.get("type")
696
+ if btype == "thinking":
697
+ tval = str(blk.get("thinking") or blk.get("text") or "").strip()
698
+ if tval:
699
+ clipped, trunc = clip_text(tval, 6000)
700
+ step_seq += 1
701
+ steps.append({
702
+ "id": f"think-{step_seq}",
703
+ "kind": "thinking",
704
+ "title": "思考过程",
705
+ "text": clipped,
706
+ "truncated": trunc,
707
+ "durationMs": int(thinking_ms) if thinking_ms is not None else None,
708
+ "timestamp": ts,
709
+ })
710
+ elif btype == "text":
711
+ tval = str(blk.get("text") or "").strip()
712
+ if tval:
713
+ clipped, trunc = clip_text(tval, 24_000)
714
+ step_seq += 1
715
+ steps.append({
716
+ "id": f"asst-{step_seq}",
717
+ "kind": "assistant",
718
+ "title": "回复",
719
+ "text": clipped,
720
+ "truncated": trunc,
721
+ "timestamp": ts,
722
+ })
723
+ elif btype == "tool_use":
724
+ tname = str(blk.get("name") or "Tool")[:80]
725
+ tid = str(blk.get("id") or f"tool-{step_seq + 1}")
726
+ raw_in = blk.get("input")
727
+ summary = summarize_tool_input(tname, raw_in)
728
+ try:
729
+ in_str = json.dumps(raw_in, ensure_ascii=False, indent=2) if raw_in is not None else ""
730
+ except (TypeError, ValueError):
731
+ in_str = str(raw_in)
732
+ in_clipped, in_trunc = clip_text(in_str, 4000)
733
+ step_seq += 1
734
+ tstep = {
735
+ "id": tid,
736
+ "kind": "tool",
737
+ "toolName": tname,
738
+ "title": tname,
739
+ "summary": summary,
740
+ "inputPreview": in_clipped,
741
+ "inputTruncated": in_trunc,
742
+ "output": "",
743
+ "outputTruncated": False,
744
+ "isError": False,
745
+ "status": "running",
746
+ "timestamp": ts,
747
+ }
748
+ steps.append(tstep)
749
+ tools_by_id[tid] = tstep
750
+
751
+ finished = meta.get("finished") if isinstance(meta.get("finished"), bool) else None
752
+ now_ts = time.time()
753
+ if finished is True:
754
+ working = False
755
+ elif finished is False:
756
+ working = (now_ts - st.st_mtime) < 300
757
+ else:
758
+ working = (now_ts - st.st_mtime < 180) and (stop_reason != "end_turn")
759
+
760
+ if not working:
761
+ for s in steps:
762
+ if s.get("kind") == "tool" and s.get("status") == "running":
763
+ s["status"] = "completed"
764
+
765
+ total_steps = len(steps)
766
+ truncated = False
767
+ MAX_STEPS = 160
768
+ if total_steps > MAX_STEPS:
769
+ truncated = True
770
+ if steps and steps[0].get("kind") == "prompt":
771
+ steps = [steps[0]] + steps[-(MAX_STEPS - 1):]
772
+ else:
773
+ steps = steps[-MAX_STEPS:]
774
+
775
+ return {
776
+ "found": True,
777
+ "provider": "claude",
778
+ "subagentId": target.stem,
779
+ "toolUseId": str(meta.get("toolUseId") or ""),
780
+ "role": role or f"Subagent {target.stem[:10]}",
781
+ "typeName": str(meta.get("agentType") or "subagent")[:60],
782
+ "model": model,
783
+ "spawnDepth": meta.get("spawnDepth") if isinstance(meta.get("spawnDepth"), int) else None,
784
+ "background": meta.get("requestShape") != "foreground",
785
+ "status": "working" if working else "completed",
786
+ "updatedAt": int(st.st_mtime * 1000),
787
+ "sizeBytes": st.st_size,
788
+ "version": version,
789
+ "totalSteps": total_steps,
790
+ "truncated": truncated,
791
+ "steps": steps,
792
+ }
793
+
794
+ def agy_active_subagents(brain_root, transcript_file, now_ts):
795
+ try:
796
+ size = transcript_file.stat().st_size
797
+ start = max(0, size - 131_072)
798
+ with transcript_file.open("rb") as h:
799
+ h.seek(start)
800
+ data = h.read(131_072)
801
+ if start > 0 and b"\n" in data:
802
+ data = data.split(b"\n", 1)[1]
803
+ cids, done = [], set()
804
+ for line in data.splitlines():
805
+ try:
806
+ row = json.loads(line)
807
+ except (ValueError, UnicodeError):
808
+ continue
809
+ if not isinstance(row, dict):
810
+ continue
811
+ if row.get("type") == "GENERIC" and isinstance(row.get("content"), str):
812
+ for m in CREATED_SUBAGENT_RE.finditer(row["content"]):
813
+ cid = m.group(1)
814
+ if cid not in cids:
815
+ cids.append(cid)
816
+ elif row.get("type") == "SYSTEM_MESSAGE" and isinstance(row.get("content"), str):
817
+ m = SENDER_RE.search(row["content"])
818
+ if m:
819
+ done.add(m.group(1))
820
+ count = 0
821
+ for cid in cids[-24:]:
822
+ if cid in done:
823
+ continue
824
+ logs = brain_root / cid / ".system_generated/logs"
825
+ cf = next((p for p in (logs / "transcript_full.jsonl", logs / "transcript.jsonl") if p.is_file()), None)
826
+ if cf is not None and (now_ts - cf.stat().st_mtime) < 180:
827
+ count += 1
828
+ return count
829
+ except OSError:
830
+ return 0
831
+
832
+ def agy_entries():
833
+ filename = os.path.join(roots["antigravity"], "conversation_summaries.db")
834
+ if not os.path.exists(filename):
835
+ return []
836
+ connection = sqlite3.connect(Path(filename).resolve().as_uri() + "?mode=ro", uri=True, timeout=2)
837
+ try:
838
+ rows = connection.execute("SELECT conversation_id,title,preview,workspace_uris,last_modified_time FROM conversation_summaries").fetchall()
839
+ result = []
840
+ now_ts = time.time()
841
+ brain_root = (Path(roots["antigravity"]) / "brain").resolve()
842
+ for sid, title, preview, workspaces, updated in rows:
843
+ try:
844
+ workspaces = json.loads(workspaces or "[]")
845
+ except ValueError:
846
+ workspaces = [workspaces] if workspaces else []
847
+ if isinstance(workspaces, str):
848
+ workspaces = [workspaces]
849
+ workspace = next((value for value in workspaces if isinstance(value, str)), "")
850
+ cwd = unquote(urlparse(workspace).path) if workspace.startswith("file:") else workspace
851
+ if os.name == "nt" and len(cwd) > 2 and cwd[0] == "/" and cwd[2] == ":":
852
+ cwd = cwd[1:]
853
+ item = {"provider": "antigravity", "sessionId": sid, "cwd": cwd, "title": (title or preview or sid)[:160], "preview": (preview or "")[:1000], "model": "", "updatedAt": str(updated or ""), "path": filename}
854
+ # Metadata only: scans never transfer conversation bodies.
855
+ if isinstance(sid, str) and sid and all(c.isalnum() or c in "-_" for c in sid):
856
+ folder = Path(roots["antigravity"]) / "brain" / sid / ".system_generated/logs"
857
+ for name in ("transcript_full.jsonl", "transcript.jsonl"):
858
+ try:
859
+ tf = folder / name
860
+ stat = tf.stat()
861
+ item["historyVersion"] = f"{name}:{stat.st_mtime_ns}:{stat.st_size}"
862
+ if now_ts - stat.st_mtime < 600:
863
+ active = agy_active_subagents(brain_root, tf, now_ts)
864
+ if active > 0:
865
+ item["activeSubagents"] = active
866
+ break
867
+ except OSError:
868
+ continue
869
+ result.append(item)
870
+ return result
871
+ finally:
872
+ connection.close()
873
+
874
+ def codex_labels():
875
+ root = Path(roots["codex"]).parent
876
+ labels = {}
877
+ database = root / "state_5.sqlite"
878
+ if database.exists():
879
+ connection = None
880
+ try:
881
+ connection = sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True, timeout=2)
882
+ columns = {row[1] for row in connection.execute("PRAGMA table_info(threads)")}
883
+ selected = [name for name in ("id", "title", "name", "model", "cwd") if name in columns]
884
+ if "id" in selected:
885
+ for row in connection.execute("SELECT " + ",".join(selected) + " FROM threads"):
886
+ item = dict(zip(selected, row))
887
+ labels[item["id"]] = item
888
+ except sqlite3.Error:
889
+ pass # The index is optional; JSONL remains the source of discoverable records.
890
+ finally:
891
+ if connection:
892
+ connection.close()
893
+ try:
894
+ with (root / "session_index.jsonl").open(encoding="utf-8") as handle:
895
+ for line in handle:
896
+ try:
897
+ item = json.loads(line)
898
+ if item.get("id") and item.get("thread_name"):
899
+ labels.setdefault(item["id"], {})["name"] = item["thread_name"]
900
+ except ValueError:
901
+ pass
902
+ except OSError:
903
+ pass
904
+ return labels
905
+
906
+ if config.get("operation") == "subagent_workflow":
907
+ provider, filename = config["provider"], os.path.realpath(config["path"])
908
+ root = os.path.realpath(roots.get(provider, ""))
909
+ if provider != "claude" or os.path.commonpath([root, filename]) != root or not filename.endswith(".jsonl"):
910
+ raise ValueError("不支持读取这个子代理工作流路径")
911
+ payload = claude_subagent_workflow(filename, config.get("subagentId"), config.get("version"))
912
+ print(json.dumps(payload, ensure_ascii=False))
913
+ elif config.get("operation") == "dialogue":
914
+ provider, filename = config["provider"], os.path.realpath(config["path"])
915
+ root = os.path.realpath(roots.get(provider, ""))
916
+ if provider not in ("codex", "claude") or os.path.commonpath([root, filename]) != root or not filename.endswith(".jsonl"):
917
+ raise ValueError("不支持读取这个会话路径")
918
+ messages = []
919
+ subs = []
920
+ total_subs = 0
921
+ subs_by_tool = {}
922
+ subs_by_agent = {}
923
+ seen_agent_msgs = set()
924
+ spawned_tool_meta = {}
925
+ session_id = Path(filename).stem
926
+ if provider == "claude":
927
+ subs, total_subs = claude_subagents(filename, time.time(), limit=60)
928
+ for s in subs:
929
+ if s.get("toolUseId"):
930
+ subs_by_tool[s["toolUseId"]] = s
931
+ aid = s.get("agentId") or s.get("id") or ""
932
+ if aid:
933
+ subs_by_agent[aid] = s
934
+ if aid.startswith("agent-"):
935
+ subs_by_agent[aid[len("agent-"):]] = s
936
+ current_task = ""
937
+ turn_index = 0
938
+ max_tail = 24_000_000 if provider == "claude" else 2_000_000
939
+
940
+ def emit_claude_agent_message(raw_str, ts_val):
941
+ parsed = parse_claude_agent_message(raw_str)
942
+ if not parsed:
943
+ return False
944
+ dedup_key = (parsed["from"], parsed["text"][:140])
945
+ if dedup_key in seen_agent_msgs:
946
+ return True
947
+ seen_agent_msgs.add(dedup_key)
948
+ matched = subs_by_agent.get(parsed["from"]) or subs_by_agent.get(f"agent-{parsed['from']}")
949
+ peer_name = matched.get("role") if matched else parsed["from"]
950
+ sub_id = (matched.get("agentId") or matched.get("id")) if matched else ""
951
+ messages.append({
952
+ "id": f"agent-in-{len(messages)}-{parsed['from'][:16]}",
953
+ "role": "agent_interaction",
954
+ "direction": "inbound",
955
+ "interactionKind": parsed["kind"],
956
+ "peerId": parsed["from"],
957
+ "peerName": peer_name,
958
+ "subagentId": sub_id,
959
+ "summary": parsed["summary"],
960
+ "text": parsed["text"],
961
+ **({"createdAt": ts_val} if ts_val else {}),
962
+ })
963
+ return True
964
+
965
+ for row in records(filename, full=True, max_bytes=max_tail):
966
+ if provider == "claude" and isinstance(row.get("sessionId"), str) and row.get("sessionId"):
967
+ session_id = row["sessionId"]
968
+ ts = row.get("timestamp")
969
+ rtype = row.get("type")
970
+ if provider == "claude":
971
+ if rtype == "queue-operation" and row.get("operation") == "enqueue":
972
+ emit_claude_agent_message(row.get("content"), ts)
973
+ continue
974
+ if rtype == "attachment":
975
+ att = row.get("attachment")
976
+ if isinstance(att, dict) and att.get("type") == "queued_command":
977
+ emit_claude_agent_message(att.get("prompt"), ts)
978
+ continue
979
+ message = row.get("payload", {}) if provider == "codex" and rtype == "response_item" else row.get("message", {}) if provider == "claude" else {}
980
+ if not isinstance(message, dict):
981
+ continue
982
+ role = message.get("role")
983
+ content = message.get("content")
984
+ value = text(content)
985
+ if role == "user":
986
+ if provider == "claude":
987
+ if value and emit_claude_agent_message(value, ts):
988
+ continue
989
+ if value:
990
+ notif = parse_claude_task_notification(value)
991
+ if notif:
992
+ matched = subs_by_tool.get(notif["toolUseId"]) if notif.get("toolUseId") else None
993
+ messages.append({
994
+ "id": f"task-notif-{len(messages)}-{notif['taskId'] or notif['toolUseId']}",
995
+ "role": "agent_interaction",
996
+ "direction": "inbound",
997
+ "interactionKind": "notification",
998
+ "peerId": notif["taskId"] or notif["toolUseId"],
999
+ "peerName": (matched.get("role") if matched else "") or notif["taskId"] or "后台任务",
1000
+ "subagentId": (matched.get("agentId") or matched.get("id")) if matched else "",
1001
+ "status": notif["status"],
1002
+ "summary": notif["summary"],
1003
+ "text": notif["text"],
1004
+ **({"createdAt": ts} if ts else {}),
1005
+ })
1006
+ continue
1007
+ if isinstance(content, list):
1008
+ for blk in content:
1009
+ if not isinstance(blk, dict) or blk.get("type") != "tool_result":
1010
+ continue
1011
+ tid = str(blk.get("tool_use_id") or "")
1012
+ if tid not in spawned_tool_meta and tid not in subs_by_tool:
1013
+ continue
1014
+ out_txt, _ = extract_tool_result_text(blk.get("content"), 12_000)
1015
+ if not out_txt.strip():
1016
+ continue
1017
+ if "was delivered to you as a message from" in out_txt[:260]:
1018
+ continue
1019
+ matched = subs_by_tool.get(tid) or spawned_tool_meta.get(tid) or {}
1020
+ sub_id = matched.get("agentId") or matched.get("id") or ""
1021
+ peer_name = matched.get("role") or "Subagent"
1022
+ first_ln = next((ln.strip().lstrip("#*- ").strip() for ln in out_txt.splitlines() if ln.strip()), "")[:110]
1023
+ messages.append({
1024
+ "id": f"agent-res-{len(messages)}-{tid[:16]}",
1025
+ "role": "agent_interaction",
1026
+ "direction": "inbound",
1027
+ "interactionKind": "handback",
1028
+ "peerId": sub_id or tid,
1029
+ "peerName": peer_name,
1030
+ "subagentId": sub_id,
1031
+ "status": "failed" if blk.get("is_error") else "completed",
1032
+ "summary": first_ln,
1033
+ "text": out_txt,
1034
+ **({"createdAt": ts} if ts else {}),
1035
+ })
1036
+ if value:
1037
+ if provider == "claude" and not row.get("isMeta") and not value.lstrip().startswith("<"):
1038
+ turn_index += 1
1039
+ current_task = value.strip().splitlines()[0][:90]
1040
+ messages.append({"role": role, "text": value[:30_000], **({"createdAt": ts} if ts else {})})
1041
+ elif role == "assistant":
1042
+ if value:
1043
+ messages.append({"role": role, "text": value[:30_000], **({"createdAt": ts} if ts else {})})
1044
+ if provider == "claude" and isinstance(content, list):
1045
+ spawned = []
1046
+ outbound_msgs = []
1047
+ for blk in content:
1048
+ if not isinstance(blk, dict) or blk.get("type") != "tool_use":
1049
+ continue
1050
+ bname = blk.get("name")
1051
+ tid = str(blk.get("id") or "")
1052
+ inp = blk.get("input") if isinstance(blk.get("input"), dict) else {}
1053
+ if bname == "SendMessage":
1054
+ to_target = str(inp.get("to") or inp.get("recipient") or "").strip()[:120]
1055
+ msg_body = str(inp.get("message") or inp.get("content") or "").strip()
1056
+ msg_summary = str(inp.get("summary") or "").strip()[:120]
1057
+ if to_target or msg_body:
1058
+ matched = subs_by_agent.get(to_target) or subs_by_agent.get(f"agent-{to_target}")
1059
+ outbound_msgs.append({
1060
+ "id": f"agent-out-{len(messages)}-{tid or len(outbound_msgs)}",
1061
+ "role": "agent_interaction",
1062
+ "direction": "outbound",
1063
+ "interactionKind": "message",
1064
+ "peerId": to_target,
1065
+ "peerName": (matched.get("role") if matched else "") or to_target,
1066
+ "subagentId": (matched.get("agentId") or matched.get("id")) if matched else "",
1067
+ "summary": msg_summary or (msg_body.splitlines()[0][:100] if msg_body else ""),
1068
+ "text": msg_body[:12_000],
1069
+ **({"createdAt": ts} if ts else {}),
1070
+ })
1071
+ continue
1072
+ if bname not in ("Agent", "Task"):
1073
+ continue
1074
+ matched = subs_by_tool.get(tid)
1075
+ s_name = str(inp.get("name") or inp.get("description") or "").strip()[:120]
1076
+ s_type = str(inp.get("subagent_type") or "subagent")[:60]
1077
+ s_model = str(inp.get("model") or "")[:80]
1078
+ s_prompt = str(inp.get("prompt") or "").strip()[:480]
1079
+ if matched is not None:
1080
+ if current_task and not matched.get("taskTitle"):
1081
+ matched["taskTitle"] = current_task
1082
+ if turn_index and not matched.get("turnIndex"):
1083
+ matched["turnIndex"] = turn_index
1084
+ if ts and not matched.get("spawnedAt"):
1085
+ matched["spawnedAt"] = ts
1086
+ item_ref = dict(matched)
1087
+ if s_name and item_ref.get("role", "").startswith("Subagent "):
1088
+ item_ref["role"] = s_name
1089
+ if s_prompt:
1090
+ item_ref["promptPreview"] = s_prompt
1091
+ spawned.append(item_ref)
1092
+ if tid:
1093
+ spawned_tool_meta[tid] = item_ref
1094
+ elif tid or s_name:
1095
+ item_ref = {
1096
+ "id": tid or f"spawn-{turn_index}-{len(spawned)}",
1097
+ "toolUseId": tid,
1098
+ "role": s_name or "Subagent",
1099
+ "typeName": s_type,
1100
+ "model": s_model,
1101
+ "background": bool(inp.get("run_in_background", True)),
1102
+ "status": "completed",
1103
+ "lastAction": "已完成",
1104
+ "hasWorkflow": bool(tid),
1105
+ "taskTitle": current_task,
1106
+ "turnIndex": turn_index,
1107
+ "spawnedAt": ts,
1108
+ **({"promptPreview": s_prompt} if s_prompt else {}),
1109
+ }
1110
+ spawned.append(item_ref)
1111
+ if tid:
1112
+ spawned_tool_meta[tid] = item_ref
1113
+ if spawned:
1114
+ if messages and messages[-1].get("role") == "subagent_group" and messages[-1].get("turnIndex") == turn_index:
1115
+ existing_ids = {s.get("toolUseId") or s.get("id") for s in messages[-1]["subagents"]}
1116
+ for sp in spawned:
1117
+ k = sp.get("toolUseId") or sp.get("id")
1118
+ if k not in existing_ids:
1119
+ messages[-1]["subagents"].append(sp)
1120
+ existing_ids.add(k)
1121
+ else:
1122
+ messages.append({
1123
+ "id": f"subgrp-{turn_index}-{spawned[0].get('id', '')}",
1124
+ "role": "subagent_group",
1125
+ "text": "",
1126
+ "taskTitle": current_task,
1127
+ "turnIndex": turn_index,
1128
+ "subagents": spawned,
1129
+ **({"createdAt": ts} if ts else {}),
1130
+ })
1131
+ messages.extend(outbound_msgs)
1132
+ payload = {"messages": messages[-120:], "limited": os.path.getsize(filename) > max_tail or len(messages) > 120}
1133
+ if provider == "claude":
1134
+ payload["subagents"] = list(reversed(subs))
1135
+ payload["totalSubagents"] = total_subs
1136
+ tmux_ttys = collect_tmux_ttys()
1137
+ ext_lock = detect_claude_external_locks(tmux_ttys, target_sid=session_id).get(session_id)
1138
+ payload["externalLock"] = ext_lock
1139
+ print(json.dumps(payload, ensure_ascii=False))
1140
+ else:
1141
+ cache_file = Path.home() / ".cache" / "scope" / "session-catalog-v1.json"
1142
+ try:
1143
+ cache = json.loads(cache_file.read_text(encoding="utf-8"))
1144
+ except (OSError, ValueError):
1145
+ cache = {}
1146
+ entries, errors, next_cache = [], [], {}
1147
+ now_ts = time.time()
1148
+ tmux_ttys = collect_tmux_ttys()
1149
+ claude_locks = detect_claude_external_locks(tmux_ttys)
1150
+ agy_locks = detect_agy_external_locks(tmux_ttys)
1151
+ for provider in ("codex", "claude"):
1152
+ for filename in glob.iglob(os.path.join(roots[provider], "**", "*.jsonl"), recursive=True):
1153
+ if provider == "claude" and "subagents" in Path(filename).parts:
1154
+ continue # Child transcripts share the parent sessionId; they are not resumable sessions.
1155
+ try:
1156
+ stat = os.stat(filename)
1157
+ sub_dir = Path(filename).with_suffix("") / "subagents" if provider == "claude" else None
1158
+ sub_mtime = os.stat(sub_dir).st_mtime if sub_dir and sub_dir.is_dir() else 0
1159
+ recent = (now_ts - max(stat.st_mtime, sub_mtime)) < 600
1160
+ stamp = [stat.st_mtime_ns, stat.st_size]
1161
+ saved = cache.get(filename)
1162
+ item = dict(saved["item"]) if saved and saved.get("stamp") == stamp else metadata(provider, filename)
1163
+ next_cache[filename] = {"stamp": stamp, "item": item}
1164
+ if provider == "claude":
1165
+ if recent and sub_dir and sub_dir.is_dir():
1166
+ sub_list, _ = claude_subagents(filename, now_ts, limit=32)
1167
+ active = sum(1 for sub in sub_list if sub["status"] == "working")
1168
+ if active > 0:
1169
+ item = {**item, "activeSubagents": active}
1170
+ ext = claude_locks.get(item.get("sessionId"))
1171
+ if ext:
1172
+ item = {**item, "externalLock": ext}
1173
+ entries.append(item)
1174
+ except (OSError, ValueError, TypeError) as error:
1175
+ errors.append(f"{provider}: {type(error).__name__}")
1176
+ labels = codex_labels()
1177
+ for item in entries:
1178
+ if item["provider"] != "codex":
1179
+ continue
1180
+ label = labels.get(item["sessionId"], {})
1181
+ item["title"] = (label.get("name") or label.get("title") or item["title"])[:160]
1182
+ item["cwd"] = label.get("cwd") or item["cwd"]
1183
+ item["model"] = label.get("model") or item["model"]
1184
+ try:
1185
+ for agy_item in agy_entries():
1186
+ ext = agy_locks.get(agy_item.get("sessionId"))
1187
+ if ext:
1188
+ agy_item["externalLock"] = ext
1189
+ entries.append(agy_item)
1190
+ except (sqlite3.Error, ValueError, TypeError) as error:
1191
+ errors.append("antigravity: " + str(error))
1192
+ for item in entries:
1193
+ if item["provider"] in ("claude", "antigravity"):
1194
+ try:
1195
+ state = json.loads((Path.home() / ".local/state/scope" / (item["provider"] + "-sessions") / (item["sessionId"] + ".json")).read_text())
1196
+ item["phase"] = state.get("phase", "active")
1197
+ except FileNotFoundError:
1198
+ item["phase"] = "active"
1199
+ try:
1200
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
1201
+ temporary = cache_file.with_suffix(f".{os.getpid()}.tmp")
1202
+ temporary.write_text(json.dumps(next_cache, ensure_ascii=False), encoding="utf-8")
1203
+ os.chmod(temporary, 0o600)
1204
+ os.replace(temporary, cache_file)
1205
+ except OSError:
1206
+ pass
1207
+ print(json.dumps({"entries": entries, "errors": list(dict.fromkeys(errors)), "roots": roots}, ensure_ascii=False))