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,347 +1,432 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const HISTORY_PROBE = String.raw`
3
- import ast
4
- import collections
5
- import datetime
6
- import glob
7
- import json
8
- import os
9
- import sys
10
-
11
- limit = max(1, min(300, int(sys.argv[1])))
12
- order = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] == "oldest" else "recent"
13
-
14
- def text_from_content(content):
15
- if isinstance(content, str):
16
- return content
17
- if not isinstance(content, list):
18
- return ""
19
- parts = []
20
- for item in content:
21
- if not isinstance(item, dict) or item.get("type") == "encrypted_content":
22
- continue
23
- text = item.get("text")
24
- if isinstance(text, str):
25
- parts.append(text)
26
- return "\n".join(parts)
27
-
28
- def tool_output_text(value):
29
- parsed = value
30
- if isinstance(value, str):
31
- stripped = value.strip()
32
- for parser in (json.loads, ast.literal_eval):
33
- try:
34
- parsed = parser(stripped)
35
- break
36
- except Exception:
37
- parsed = value
38
- if isinstance(parsed, dict):
39
- parsed = parsed.get("content") or parsed.get("output") or parsed
40
- if isinstance(parsed, list):
41
- extracted = text_from_content(parsed)
42
- if extracted:
43
- return extracted
44
- return value if isinstance(value, str) else str(value or "")
45
-
46
- def clean(value, limit=600):
47
- if not isinstance(value, str):
48
- return ""
49
- value = " ".join(value.replace("\x00", "").split())
50
- return value[:limit]
51
-
52
- def parse_subagent_notification(value):
53
- text = text_from_content(value) if not isinstance(value, str) else value
54
- if not isinstance(text, str):
55
- return None
56
- stripped = text.strip()
57
- markers = ("<subagent_notification>", "{subagent_notification}")
58
- marker = next((item for item in markers if stripped.startswith(item)), None)
59
- if not marker:
60
- return None
61
- try:
62
- notification, _ = json.JSONDecoder().raw_decode(
63
- stripped[len(marker):].strip()
64
- )
65
- except Exception:
66
- return None
67
- status = notification.get("status") if isinstance(notification, dict) else None
68
- if not isinstance(status, dict):
69
- return None
70
- state = next(
71
- (key for key in ("completed", "failed", "errored", "cancelled") if key in status),
72
- "updated",
73
- )
74
- content = status.get(state)
75
- if not isinstance(content, str):
76
- content = json.dumps(content, ensure_ascii=False) if content is not None else ""
77
- return content
78
-
79
- def is_context_message(value):
80
- if not isinstance(value, str):
81
- return True
82
- return value.lstrip().startswith((
83
- "<environment_context>",
84
- "<permissions",
85
- "<INSTRUCTIONS>",
86
- "<collaboration_mode>",
87
- "<apps_instructions>",
88
- "<plugins_instructions>",
89
- "<skills_instructions>",
90
- "<recommended_plugins>",
91
- "<in-app-browser-context",
92
- "# AGENTS.md instructions",
93
- "A previous agent produced",
94
- "You are Codex",
95
- ))
96
-
97
- def sampled_lines(filename):
98
- size = os.path.getsize(filename)
99
- with open(filename, "rb") as handle:
100
- first = handle.readline()
101
- head = handle.read(64000)
102
- if size > 256000:
103
- handle.seek(max(0, size - 192000))
104
- tail = handle.read()
105
- chunks = (first + head + b"\n" + tail).decode("utf-8", errors="replace")
106
- seen = set()
107
- for line in chunks.splitlines():
108
- if line in seen:
109
- continue
110
- seen.add(line)
111
- yield line
112
-
113
- def timestamp_epoch(value):
114
- if not isinstance(value, str) or not value:
115
- return 0.0
116
- try:
117
- return datetime.datetime.fromisoformat(
118
- value.replace("Z", "+00:00")
119
- ).timestamp()
120
- except Exception:
121
- return 0.0
122
-
123
- def latest_event(filename):
124
- try:
125
- size = os.path.getsize(filename)
126
- with open(filename, "rb") as handle:
127
- # The final event normally fits in a few KiB. This keeps ordering
128
- # based on the true event timestamp without reading 256 KiB from
129
- # every rollout as the previous implementation did.
130
- handle.seek(max(0, size - 16384))
131
- tail = handle.read().decode("utf-8", errors="replace")
132
- for raw in reversed(tail.splitlines()):
133
- try:
134
- event = json.loads(raw)
135
- except Exception:
136
- continue
137
- value = event.get("timestamp")
138
- epoch = timestamp_epoch(value)
139
- if epoch:
140
- return epoch, value
141
- except Exception:
142
- pass
143
- try:
144
- return os.path.getmtime(filename), ""
145
- except Exception:
146
- return 0.0, ""
147
-
148
- paths = list(dict.fromkeys(
149
- glob.glob(os.path.expanduser("~/.codex/sessions/**/*.jsonl"), recursive=True)
150
- + glob.glob(
151
- os.path.expanduser("~/.codex/archived_sessions/**/*.jsonl"),
152
- recursive=True,
153
- )
154
- ))
155
- path_mtimes = {}
156
- path_activity = {}
157
- for filename in paths:
158
- try:
159
- path_mtimes[filename] = os.path.getmtime(filename)
160
- except Exception:
161
- path_mtimes[filename] = 0.0
162
- path_activity[filename] = latest_event(filename)
163
- paths.sort(
164
- key=lambda item: (path_activity[item][0], path_mtimes[item]),
165
- reverse=order == "recent",
166
- )
167
- records = []
168
-
169
- for filename in paths:
170
- if len(records) >= limit:
171
- break
172
- try:
173
- with open(filename, "r", encoding="utf-8", errors="replace") as handle:
174
- first_obj = json.loads(handle.readline())
175
- meta = (
176
- first_obj.get("payload", {})
177
- if first_obj.get("type") == "session_meta"
178
- else {}
179
- )
180
- except Exception:
181
- continue
182
-
183
- source = meta.get("source")
184
- subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
185
- spawn = subagent.get("thread_spawn", {}) if isinstance(subagent, dict) else {}
186
- if spawn or meta.get("parent_thread_id"):
187
- continue
188
-
189
- record = {
190
- "id": meta.get("id") or meta.get("session_id") or os.path.basename(filename),
191
- "rootSessionId": meta.get("session_id") or meta.get("id") or "",
192
- "parentThreadId": "",
193
- "agentPath": "",
194
- "agentNickname": "",
195
- "isSubagent": False,
196
- "cwd": meta.get("cwd") or "",
197
- "startedAt": meta.get("timestamp") or first_obj.get("timestamp"),
198
- "cliVersion": meta.get("cli_version") or "",
199
- "path": filename,
200
- "archived": "/.codex/archived_sessions/" in filename.replace("\\", "/"),
201
- "mtimeMs": int(path_mtimes.get(filename, 0.0) * 1000),
202
- "firstUser": "",
203
- "lastUser": "",
204
- "lastAssistant": "",
205
- "lastAction": "",
206
- "lastError": "",
207
- "userMessages": [],
208
- "assistantMessages": [],
209
- "model": "",
210
- "reasoningEffort": "",
211
- "approvalPolicy": "",
212
- "sandboxPolicy": "",
213
- "collaborationMode": "",
214
- "account": None,
215
- "tokenUsage": None,
216
- "turnState": "idle",
217
- "lastEventAt": path_activity.get(filename, (0, ""))[1]
218
- or first_obj.get("timestamp"),
219
- }
220
-
221
- for raw in sampled_lines(filename):
222
- try:
223
- event = json.loads(raw)
224
- except Exception:
225
- continue
226
- payload = event.get("payload", {})
227
- if not isinstance(payload, dict):
228
- payload = {}
229
- event_type = event.get("type")
230
- event_timestamp = event.get("timestamp")
231
- if timestamp_epoch(event_timestamp) >= timestamp_epoch(record["lastEventAt"]):
232
- record["lastEventAt"] = event_timestamp or record["lastEventAt"]
233
-
234
- if event_type == "turn_context":
235
- record["model"] = payload.get("model") or record["model"]
236
- record["reasoningEffort"] = (
237
- payload.get("effort")
238
- or payload.get("reasoning_effort")
239
- or record["reasoningEffort"]
240
- )
241
- record["approvalPolicy"] = (
242
- payload.get("approval_policy") or record["approvalPolicy"]
243
- )
244
- sandbox = payload.get("sandbox_policy")
245
- if isinstance(sandbox, dict):
246
- record["sandboxPolicy"] = (
247
- sandbox.get("type")
248
- or sandbox.get("mode")
249
- or record["sandboxPolicy"]
250
- )
251
- elif isinstance(sandbox, str):
252
- record["sandboxPolicy"] = sandbox
253
- collaboration = payload.get("collaboration_mode")
254
- if isinstance(collaboration, dict):
255
- record["collaborationMode"] = (
256
- collaboration.get("mode")
257
- or collaboration.get("name")
258
- or record["collaborationMode"]
259
- )
260
- elif isinstance(collaboration, str):
261
- record["collaborationMode"] = collaboration
262
-
263
- if event_type == "event_msg":
264
- kind = payload.get("type")
265
- if kind in ("user_message", "user_input"):
266
- raw_candidate = (
267
- payload.get("message") or payload.get("text") or payload.get("content")
268
- )
269
- notification = parse_subagent_notification(raw_candidate)
270
- if notification is not None:
271
- candidate = clean(notification, 1200)
272
- if candidate:
273
- record["lastAssistant"] = candidate
274
- record["assistantMessages"].append(candidate)
275
- record["assistantMessages"] = record["assistantMessages"][-4:]
276
- else:
277
- candidate = clean(raw_candidate)
278
- if candidate and not is_context_message(candidate):
279
- record["firstUser"] = record["firstUser"] or candidate
280
- record["lastUser"] = candidate
281
- record["userMessages"].append(candidate)
282
- record["userMessages"] = record["userMessages"][-4:]
283
- elif kind == "agent_message":
284
- candidate = clean(
285
- payload.get("message") or payload.get("text"),
286
- 1200,
287
- )
288
- if candidate:
289
- record["lastAssistant"] = candidate
290
- record["assistantMessages"].append(candidate)
291
- record["assistantMessages"] = record["assistantMessages"][-4:]
292
- elif kind in ("task_complete", "turn_complete", "task_completed"):
293
- candidate = clean(payload.get("last_agent_message"), 1200)
294
- if candidate:
295
- record["lastAssistant"] = candidate
296
- record["assistantMessages"].append(candidate)
297
- record["assistantMessages"] = record["assistantMessages"][-4:]
298
- continue
299
-
300
- if event_type != "response_item":
301
- continue
302
- kind = payload.get("type")
303
- role = payload.get("role")
304
- if kind == "message" and role == "user":
305
- raw_candidate = text_from_content(payload.get("content"))
306
- notification = parse_subagent_notification(raw_candidate)
307
- if notification is not None:
308
- candidate = clean(notification, 1200)
309
- if candidate:
310
- record["lastAssistant"] = candidate
311
- record["assistantMessages"].append(candidate)
312
- record["assistantMessages"] = record["assistantMessages"][-4:]
313
- else:
314
- candidate = clean(raw_candidate)
315
- if candidate and not is_context_message(candidate):
316
- record["firstUser"] = record["firstUser"] or candidate
317
- record["lastUser"] = candidate
318
- record["userMessages"].append(candidate)
319
- record["userMessages"] = record["userMessages"][-4:]
320
- elif kind == "message" and role == "assistant":
321
- candidate = clean(text_from_content(payload.get("content")), 1200)
322
- if candidate:
323
- record["lastAssistant"] = candidate
324
- record["assistantMessages"].append(candidate)
325
- record["assistantMessages"] = record["assistantMessages"][-4:]
326
- elif kind in ("function_call", "custom_tool_call"):
327
- name = payload.get("name") or "tool"
328
- arguments = payload.get("arguments") or payload.get("input") or ""
329
- record["lastAction"] = clean(f"{name}: {arguments}", 500)
330
- elif kind in ("function_call_output", "custom_tool_call_output"):
331
- output = clean(tool_output_text(payload.get("output")), 500)
332
- if (
333
- "exit code 1" in output.lower()
334
- or "process exited with code 1" in output.lower()
335
- or "traceback" in output.lower()
336
- ):
337
- record["lastError"] = output
338
-
339
- records.append(record)
340
-
341
- print(json.dumps({
342
- "totalFiles": len(paths),
343
- "limit": limit,
344
- "truncated": len(records) >= limit,
345
- "sessions": records,
346
- }, ensure_ascii=False, separators=(",", ":")))
2
+ export const HISTORY_PROBE = String.raw`
3
+ import ast
4
+ import collections
5
+ import datetime
6
+ import glob
7
+ import json
8
+ import os
9
+ import sys
10
+
11
+ limit = max(1, min(300, int(sys.argv[1])))
12
+ order = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] == "oldest" else "recent"
13
+
14
+ def text_from_content(content):
15
+ if isinstance(content, str):
16
+ return content
17
+ if not isinstance(content, list):
18
+ return ""
19
+ parts = []
20
+ for item in content:
21
+ if not isinstance(item, dict) or item.get("type") == "encrypted_content":
22
+ continue
23
+ text = item.get("text")
24
+ if isinstance(text, str):
25
+ parts.append(text)
26
+ return "\n".join(parts)
27
+
28
+ def tool_output_text(value):
29
+ parsed = value
30
+ if isinstance(value, str):
31
+ stripped = value.strip()
32
+ for parser in (json.loads, ast.literal_eval):
33
+ try:
34
+ parsed = parser(stripped)
35
+ break
36
+ except Exception:
37
+ parsed = value
38
+ if isinstance(parsed, dict):
39
+ parsed = parsed.get("content") or parsed.get("output") or parsed
40
+ if isinstance(parsed, list):
41
+ extracted = text_from_content(parsed)
42
+ if extracted:
43
+ return extracted
44
+ return value if isinstance(value, str) else str(value or "")
45
+
46
+ def clean(value, limit=600):
47
+ if not isinstance(value, str):
48
+ return ""
49
+ value = " ".join(value.replace("\x00", "").split())
50
+ return value[:limit]
51
+
52
+ def parse_subagent_notification(value):
53
+ text = text_from_content(value) if not isinstance(value, str) else value
54
+ if not isinstance(text, str):
55
+ return None
56
+ stripped = text.strip()
57
+ markers = ("<subagent_notification>", "{subagent_notification}")
58
+ marker = next((item for item in markers if stripped.startswith(item)), None)
59
+ if not marker:
60
+ return None
61
+ try:
62
+ notification, _ = json.JSONDecoder().raw_decode(
63
+ stripped[len(marker):].strip()
64
+ )
65
+ except Exception:
66
+ return None
67
+ status = notification.get("status") if isinstance(notification, dict) else None
68
+ if not isinstance(status, dict):
69
+ return None
70
+ state = next(
71
+ (key for key in ("completed", "failed", "errored", "cancelled") if key in status),
72
+ "updated",
73
+ )
74
+ content = status.get(state)
75
+ if not isinstance(content, str):
76
+ content = json.dumps(content, ensure_ascii=False) if content is not None else ""
77
+ return content
78
+
79
+ def is_context_message(value):
80
+ if not isinstance(value, str):
81
+ return True
82
+ return value.lstrip().startswith((
83
+ "<environment_context>",
84
+ "<permissions",
85
+ "<INSTRUCTIONS>",
86
+ "<collaboration_mode>",
87
+ "<apps_instructions>",
88
+ "<plugins_instructions>",
89
+ "<skills_instructions>",
90
+ "<recommended_plugins>",
91
+ "<in-app-browser-context",
92
+ "# AGENTS.md instructions",
93
+ "A previous agent produced",
94
+ "You are Codex",
95
+ ))
96
+
97
+ def sampled_lines(filename):
98
+ size = os.path.getsize(filename)
99
+ with open(filename, "rb") as handle:
100
+ first = handle.readline()
101
+ head = handle.read(64000)
102
+ if size > 256000:
103
+ handle.seek(max(0, size - 192000))
104
+ tail = handle.read()
105
+ chunks = (first + head + b"\n" + tail).decode("utf-8", errors="replace")
106
+ seen = set()
107
+ for line in chunks.splitlines():
108
+ if line in seen:
109
+ continue
110
+ seen.add(line)
111
+ yield line
112
+
113
+ def timestamp_epoch(value):
114
+ if not isinstance(value, str) or not value:
115
+ return 0.0
116
+ try:
117
+ return datetime.datetime.fromisoformat(
118
+ value.replace("Z", "+00:00")
119
+ ).timestamp()
120
+ except Exception:
121
+ return 0.0
122
+
123
+ def latest_event(filename):
124
+ try:
125
+ size = os.path.getsize(filename)
126
+ with open(filename, "rb") as handle:
127
+ # The final event normally fits in a few KiB. This keeps ordering
128
+ # based on the true event timestamp without reading 256 KiB from
129
+ # every rollout as the previous implementation did.
130
+ handle.seek(max(0, size - 16384))
131
+ tail = handle.read().decode("utf-8", errors="replace")
132
+ for raw in reversed(tail.splitlines()):
133
+ try:
134
+ event = json.loads(raw)
135
+ except Exception:
136
+ continue
137
+ value = event.get("timestamp")
138
+ epoch = timestamp_epoch(value)
139
+ if epoch:
140
+ return epoch, value
141
+ except Exception:
142
+ pass
143
+ try:
144
+ return os.path.getmtime(filename), ""
145
+ except Exception:
146
+ return 0.0, ""
147
+
148
+ paths = list(dict.fromkeys(
149
+ glob.glob(os.path.expanduser("~/.codex/sessions/**/*.jsonl"), recursive=True)
150
+ + glob.glob(
151
+ os.path.expanduser("~/.codex/archived_sessions/**/*.jsonl"),
152
+ recursive=True,
153
+ )
154
+ ))
155
+ path_mtimes = {}
156
+ path_activity = {}
157
+ for filename in paths:
158
+ try:
159
+ path_mtimes[filename] = os.path.getmtime(filename)
160
+ except Exception:
161
+ path_mtimes[filename] = 0.0
162
+ path_activity[filename] = latest_event(filename)
163
+ paths.sort(
164
+ key=lambda item: (path_activity[item][0], path_mtimes[item]),
165
+ reverse=order == "recent",
166
+ )
167
+ records = []
168
+ subagents_by_parent = {}
169
+ scanned_index = 0
170
+
171
+ def parse_subagent_summary(filename, first_obj, meta, spawn, parent_thread_id):
172
+ sub_record = {
173
+ "id": meta.get("id") or meta.get("session_id") or os.path.basename(filename),
174
+ "rootSessionId": meta.get("session_id") or meta.get("id") or "",
175
+ "parentThreadId": parent_thread_id,
176
+ "agentPath": spawn.get("agent_path") or "",
177
+ "agentNickname": spawn.get("agent_nickname") or meta.get("agent_nickname") or "",
178
+ "agentRole": spawn.get("agent_role") or meta.get("agent_role") or "",
179
+ "isSubagent": True,
180
+ "cwd": meta.get("cwd") or "",
181
+ "startedAt": meta.get("timestamp") or first_obj.get("timestamp"),
182
+ "path": filename,
183
+ "mtimeMs": int(path_mtimes.get(filename, 0.0) * 1000),
184
+ "lastUser": "",
185
+ "lastAssistant": "",
186
+ "lastAction": "",
187
+ "model": "",
188
+ "turnState": "idle",
189
+ "lastEventAt": path_activity.get(filename, (0, ""))[1]
190
+ or first_obj.get("timestamp"),
191
+ }
192
+ for raw in sampled_lines(filename):
193
+ try:
194
+ ev = json.loads(raw)
195
+ except Exception:
196
+ continue
197
+ pl = ev.get("payload", {})
198
+ if not isinstance(pl, dict):
199
+ continue
200
+ et = ev.get("type")
201
+ if et == "turn_context":
202
+ sub_record["model"] = pl.get("model") or sub_record["model"]
203
+ elif et == "response_item":
204
+ k = pl.get("type")
205
+ r = pl.get("role")
206
+ if k == "message" and r == "user":
207
+ cand = clean(text_from_content(pl.get("content")), 240)
208
+ if cand and not is_context_message(cand):
209
+ sub_record["lastUser"] = sub_record["lastUser"] or cand
210
+ elif k == "message" and r == "assistant":
211
+ cand = clean(text_from_content(pl.get("content")), 300)
212
+ if cand:
213
+ sub_record["lastAssistant"] = cand
214
+ elif k in ("function_call", "custom_tool_call"):
215
+ nm = pl.get("name") or "tool"
216
+ arg = pl.get("arguments") or pl.get("input") or ""
217
+ sub_record["lastAction"] = clean(f"{nm}: {arg}", 200)
218
+ return sub_record
219
+
220
+ for idx, filename in enumerate(paths):
221
+ scanned_index = idx + 1
222
+ if len(records) >= limit:
223
+ break
224
+ try:
225
+ with open(filename, "r", encoding="utf-8", errors="replace") as handle:
226
+ first_obj = json.loads(handle.readline())
227
+ meta = (
228
+ first_obj.get("payload", {})
229
+ if first_obj.get("type") == "session_meta"
230
+ else {}
231
+ )
232
+ except Exception:
233
+ continue
234
+
235
+ source = meta.get("source")
236
+ subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
237
+ spawn = subagent.get("thread_spawn", {}) if isinstance(subagent, dict) else {}
238
+ parent_thread_id = spawn.get("parent_thread_id") or meta.get("parent_thread_id") or ""
239
+ if spawn or parent_thread_id:
240
+ if parent_thread_id:
241
+ subagents_by_parent.setdefault(parent_thread_id, []).append(
242
+ parse_subagent_summary(filename, first_obj, meta, spawn, parent_thread_id)
243
+ )
244
+ continue
245
+
246
+ record = {
247
+ "id": meta.get("id") or meta.get("session_id") or os.path.basename(filename),
248
+ "rootSessionId": meta.get("session_id") or meta.get("id") or "",
249
+ "parentThreadId": "",
250
+ "agentPath": "",
251
+ "agentNickname": "",
252
+ "isSubagent": False,
253
+ "cwd": meta.get("cwd") or "",
254
+ "startedAt": meta.get("timestamp") or first_obj.get("timestamp"),
255
+ "cliVersion": meta.get("cli_version") or "",
256
+ "path": filename,
257
+ "archived": "/.codex/archived_sessions/" in filename.replace("\\", "/"),
258
+ "mtimeMs": int(path_mtimes.get(filename, 0.0) * 1000),
259
+ "firstUser": "",
260
+ "lastUser": "",
261
+ "lastAssistant": "",
262
+ "lastAction": "",
263
+ "lastError": "",
264
+ "userMessages": [],
265
+ "assistantMessages": [],
266
+ "model": "",
267
+ "reasoningEffort": "",
268
+ "approvalPolicy": "",
269
+ "sandboxPolicy": "",
270
+ "collaborationMode": "",
271
+ "account": None,
272
+ "tokenUsage": None,
273
+ "turnState": "idle",
274
+ "lastEventAt": path_activity.get(filename, (0, ""))[1]
275
+ or first_obj.get("timestamp"),
276
+ }
277
+
278
+ for raw in sampled_lines(filename):
279
+ try:
280
+ event = json.loads(raw)
281
+ except Exception:
282
+ continue
283
+ payload = event.get("payload", {})
284
+ if not isinstance(payload, dict):
285
+ payload = {}
286
+ event_type = event.get("type")
287
+ event_timestamp = event.get("timestamp")
288
+ if timestamp_epoch(event_timestamp) >= timestamp_epoch(record["lastEventAt"]):
289
+ record["lastEventAt"] = event_timestamp or record["lastEventAt"]
290
+
291
+ if event_type == "turn_context":
292
+ record["model"] = payload.get("model") or record["model"]
293
+ record["reasoningEffort"] = (
294
+ payload.get("effort")
295
+ or payload.get("reasoning_effort")
296
+ or record["reasoningEffort"]
297
+ )
298
+ record["approvalPolicy"] = (
299
+ payload.get("approval_policy") or record["approvalPolicy"]
300
+ )
301
+ sandbox = payload.get("sandbox_policy")
302
+ if isinstance(sandbox, dict):
303
+ record["sandboxPolicy"] = (
304
+ sandbox.get("type")
305
+ or sandbox.get("mode")
306
+ or record["sandboxPolicy"]
307
+ )
308
+ elif isinstance(sandbox, str):
309
+ record["sandboxPolicy"] = sandbox
310
+ collaboration = payload.get("collaboration_mode")
311
+ if isinstance(collaboration, dict):
312
+ record["collaborationMode"] = (
313
+ collaboration.get("mode")
314
+ or collaboration.get("name")
315
+ or record["collaborationMode"]
316
+ )
317
+ elif isinstance(collaboration, str):
318
+ record["collaborationMode"] = collaboration
319
+
320
+ if event_type == "event_msg":
321
+ kind = payload.get("type")
322
+ if kind in ("user_message", "user_input"):
323
+ raw_candidate = (
324
+ payload.get("message") or payload.get("text") or payload.get("content")
325
+ )
326
+ notification = parse_subagent_notification(raw_candidate)
327
+ if notification is not None:
328
+ candidate = clean(notification, 1200)
329
+ if candidate:
330
+ record["lastAssistant"] = candidate
331
+ record["assistantMessages"].append(candidate)
332
+ record["assistantMessages"] = record["assistantMessages"][-4:]
333
+ else:
334
+ candidate = clean(raw_candidate)
335
+ if candidate and not is_context_message(candidate):
336
+ record["firstUser"] = record["firstUser"] or candidate
337
+ record["lastUser"] = candidate
338
+ record["userMessages"].append(candidate)
339
+ record["userMessages"] = record["userMessages"][-4:]
340
+ elif kind == "agent_message":
341
+ candidate = clean(
342
+ payload.get("message") or payload.get("text"),
343
+ 1200,
344
+ )
345
+ if candidate:
346
+ record["lastAssistant"] = candidate
347
+ record["assistantMessages"].append(candidate)
348
+ record["assistantMessages"] = record["assistantMessages"][-4:]
349
+ elif kind in ("task_complete", "turn_complete", "task_completed"):
350
+ candidate = clean(payload.get("last_agent_message"), 1200)
351
+ if candidate:
352
+ record["lastAssistant"] = candidate
353
+ record["assistantMessages"].append(candidate)
354
+ record["assistantMessages"] = record["assistantMessages"][-4:]
355
+ continue
356
+
357
+ if event_type != "response_item":
358
+ continue
359
+ kind = payload.get("type")
360
+ role = payload.get("role")
361
+ if kind == "message" and role == "user":
362
+ raw_candidate = text_from_content(payload.get("content"))
363
+ notification = parse_subagent_notification(raw_candidate)
364
+ if notification is not None:
365
+ candidate = clean(notification, 1200)
366
+ if candidate:
367
+ record["lastAssistant"] = candidate
368
+ record["assistantMessages"].append(candidate)
369
+ record["assistantMessages"] = record["assistantMessages"][-4:]
370
+ else:
371
+ candidate = clean(raw_candidate)
372
+ if candidate and not is_context_message(candidate):
373
+ record["firstUser"] = record["firstUser"] or candidate
374
+ record["lastUser"] = candidate
375
+ record["userMessages"].append(candidate)
376
+ record["userMessages"] = record["userMessages"][-4:]
377
+ elif kind == "message" and role == "assistant":
378
+ candidate = clean(text_from_content(payload.get("content")), 1200)
379
+ if candidate:
380
+ record["lastAssistant"] = candidate
381
+ record["assistantMessages"].append(candidate)
382
+ record["assistantMessages"] = record["assistantMessages"][-4:]
383
+ elif kind in ("function_call", "custom_tool_call"):
384
+ name = payload.get("name") or "tool"
385
+ arguments = payload.get("arguments") or payload.get("input") or ""
386
+ record["lastAction"] = clean(f"{name}: {arguments}", 500)
387
+ elif kind in ("function_call_output", "custom_tool_call_output"):
388
+ output = clean(tool_output_text(payload.get("output")), 500)
389
+ if (
390
+ "exit code 1" in output.lower()
391
+ or "process exited with code 1" in output.lower()
392
+ or "traceback" in output.lower()
393
+ ):
394
+ record["lastError"] = output
395
+
396
+ records.append(record)
397
+
398
+ record_ids = {rec["id"] for rec in records if rec.get("id")}
399
+ if record_ids and scanned_index < len(paths):
400
+ for filename in paths[scanned_index:scanned_index + 400]:
401
+ try:
402
+ with open(filename, "r", encoding="utf-8", errors="replace") as handle:
403
+ first_obj = json.loads(handle.readline())
404
+ meta = (
405
+ first_obj.get("payload", {})
406
+ if first_obj.get("type") == "session_meta"
407
+ else {}
408
+ )
409
+ except Exception:
410
+ continue
411
+ source = meta.get("source")
412
+ subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
413
+ spawn = subagent.get("thread_spawn", {}) if isinstance(subagent, dict) else {}
414
+ parent_thread_id = spawn.get("parent_thread_id") or meta.get("parent_thread_id") or ""
415
+ if parent_thread_id and parent_thread_id in record_ids:
416
+ subagents_by_parent.setdefault(parent_thread_id, []).append(
417
+ parse_subagent_summary(filename, first_obj, meta, spawn, parent_thread_id)
418
+ )
419
+
420
+ for rec in records:
421
+ subs = subagents_by_parent.get(rec["id"])
422
+ if subs:
423
+ subs.sort(key=lambda item: item.get("mtimeMs", 0), reverse=True)
424
+ rec["subagents"] = subs[:24]
425
+
426
+ print(json.dumps({
427
+ "totalFiles": len(paths),
428
+ "limit": limit,
429
+ "truncated": len(records) >= limit,
430
+ "sessions": records,
431
+ }, ensure_ascii=False, separators=(",", ":")))
347
432
  `;