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,636 +1,637 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const REMOTE_PROBE = String.raw`
3
- set +e
4
- printf 'META\t'
5
- hostname
6
-
7
- ps -eo pid=,etimes=,stat=,tty=,comm= 2>/dev/null | awk '$5 ~ /^(codex|node)$/ {print}' | while read pid etimes stat tty comm; do
8
- if [ "$comm" = "node" ]; then
9
- cmdline=$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null)
10
- case "$cmdline" in
11
- *"/codex "*|*"/codex --"*) ;;
12
- *) continue ;;
13
- esac
14
- fi
15
- cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null)
16
- printf 'PROC\t%s\t%s\t%s\t%s\t%s\t%s\n' "$pid" "$etimes" "$stat" "$tty" "$comm" "$cwd"
17
- done
18
-
19
- nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used,memory.total --format=csv,noheader,nounits 2>/dev/null | while IFS= read -r gpu; do
20
- printf 'GPU\t%s\n' "$gpu"
21
- done
22
-
23
- python3 - <<'PY' 2>/dev/null
24
- import ast
25
- import base64
26
- import glob
27
- import json
28
- import os
29
- import re
30
- import subprocess
31
- import time
32
-
33
- try:
34
- encoded_fingerprints = os.environ.get("SCOPE_SESSION_FINGERPRINTS_B64", "")
35
- encoded_fingerprints += "=" * (-len(encoded_fingerprints) % 4)
36
- cached_fingerprints = json.loads(
37
- base64.urlsafe_b64decode(encoded_fingerprints).decode("utf-8")
38
- ) if encoded_fingerprints else {}
39
- if not isinstance(cached_fingerprints, dict):
40
- cached_fingerprints = {}
41
- except Exception:
42
- cached_fingerprints = {}
43
-
44
- def text_from_content(content):
45
- if isinstance(content, str):
46
- return content
47
- if not isinstance(content, list):
48
- return ""
49
- parts = []
50
- for item in content:
51
- if not isinstance(item, dict):
52
- continue
53
- text = item.get("text")
54
- if isinstance(text, str):
55
- parts.append(text)
56
- return "\n".join(parts)
57
-
58
- def tool_output_text(value):
59
- parsed = value
60
- if isinstance(value, str):
61
- stripped = value.strip()
62
- for parser in (json.loads, ast.literal_eval):
63
- try:
64
- parsed = parser(stripped)
65
- break
66
- except Exception:
67
- parsed = value
68
- if isinstance(parsed, dict):
69
- parsed = parsed.get("content") or parsed.get("output") or parsed
70
- if isinstance(parsed, list):
71
- extracted = text_from_content(parsed)
72
- if extracted:
73
- return extracted
74
- return value if isinstance(value, str) else str(value or "")
75
-
76
- def clean(value, limit=260):
77
- if not isinstance(value, str):
78
- return ""
79
- value = " ".join(value.replace("\x00", "").split())
80
- return value[:limit]
81
-
82
- def parse_subagent_notification(value):
83
- text = text_from_content(value) if not isinstance(value, str) else value
84
- if not isinstance(text, str):
85
- return None
86
- stripped = text.strip()
87
- markers = ("<subagent_notification>", "{subagent_notification}")
88
- marker = next((item for item in markers if stripped.startswith(item)), None)
89
- if not marker:
90
- return None
91
- encoded = stripped[len(marker):].strip()
92
- try:
93
- notification, _ = json.JSONDecoder().raw_decode(encoded)
94
- except Exception:
95
- return None
96
- if not isinstance(notification, dict):
97
- return None
98
- status = notification.get("status")
99
- if not isinstance(status, dict):
100
- return None
101
- state = next(
102
- (key for key in ("completed", "failed", "errored", "cancelled") if key in status),
103
- "updated",
104
- )
105
- content = status.get(state)
106
- if not isinstance(content, str):
107
- content = json.dumps(content, ensure_ascii=False) if content is not None else ""
108
- return {
109
- "agentPath": str(notification.get("agent_path") or ""),
110
- "state": state,
111
- "text": content,
112
- }
113
-
114
- def is_context_message(value):
115
- if not isinstance(value, str):
116
- return True
117
- return value.startswith(
118
- (
119
- "<environment_context>",
120
- "<permissions",
121
- "<INSTRUCTIONS>",
122
- "<collaboration_mode>",
123
- "<apps_instructions>",
124
- "<plugins_instructions>",
125
- "<skills_instructions>",
126
- "<recommended_plugins>",
127
- "<in-app-browser-context",
128
- "# AGENTS.md instructions",
129
- "A previous agent produced",
130
- "You are Codex",
131
- )
132
- )
133
-
134
- training_command_pattern = re.compile(
135
- r"(?i)(?:\btorchrun\b|\bdeepspeed\b|\baccelerate\s+launch\b|"
136
- r"(?:^|[\s/_.-])(?:train|eval|evaluate|rollout|benchmark|inference)"
137
- r"(?:[\s/_.-]|$)|\blibero\b|\beval_suite\b)"
138
- )
139
-
140
- def command_values(value):
141
- if isinstance(value, str):
142
- try:
143
- parsed = json.loads(value)
144
- except Exception:
145
- parsed = None
146
- if parsed is not None and parsed != value:
147
- return command_values(parsed)
148
- commands = []
149
- for match in re.finditer(
150
- r'(?:"(?:cmd|command)"|(?<![\w])(?:cmd|command))\s*:\s*'
151
- r'("(?:\\.|[^"\\])*")',
152
- value,
153
- ):
154
- try:
155
- commands.append(json.loads(match.group(1)))
156
- except Exception:
157
- pass
158
- return commands or [value]
159
- if isinstance(value, dict):
160
- commands = []
161
- for key in ("cmd", "command"):
162
- candidate = value.get(key)
163
- if isinstance(candidate, str):
164
- commands.append(candidate)
165
- for key, nested in value.items():
166
- if key not in ("cmd", "command"):
167
- commands.extend(command_values(nested))
168
- return commands
169
- if isinstance(value, list):
170
- commands = []
171
- for nested in value:
172
- commands.extend(command_values(nested))
173
- return commands
174
- return []
175
-
176
- all_paths = glob.glob(
2
+ export const REMOTE_PROBE = String.raw`
3
+ set +e
4
+ printf 'META\t'
5
+ hostname
6
+
7
+ ps -eo pid=,etimes=,stat=,tty=,comm= 2>/dev/null | awk '$5 ~ /^(codex|node)$/ {print}' | while read pid etimes stat tty comm; do
8
+ if [ "$comm" = "node" ]; then
9
+ cmdline=$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null)
10
+ case "$cmdline" in
11
+ *"/codex "*|*"/codex --"*) ;;
12
+ *) continue ;;
13
+ esac
14
+ fi
15
+ cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null)
16
+ printf 'PROC\t%s\t%s\t%s\t%s\t%s\t%s\n' "$pid" "$etimes" "$stat" "$tty" "$comm" "$cwd"
17
+ done
18
+
19
+ nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used,memory.total --format=csv,noheader,nounits 2>/dev/null | while IFS= read -r gpu; do
20
+ printf 'GPU\t%s\n' "$gpu"
21
+ done
22
+
23
+ python3 - <<'PY' 2>/dev/null
24
+ import ast
25
+ import base64
26
+ import glob
27
+ import json
28
+ import os
29
+ import re
30
+ import subprocess
31
+ import time
32
+
33
+ try:
34
+ encoded_fingerprints = os.environ.get("SCOPE_SESSION_FINGERPRINTS_B64", "")
35
+ encoded_fingerprints += "=" * (-len(encoded_fingerprints) % 4)
36
+ cached_fingerprints = json.loads(
37
+ base64.urlsafe_b64decode(encoded_fingerprints).decode("utf-8")
38
+ ) if encoded_fingerprints else {}
39
+ if not isinstance(cached_fingerprints, dict):
40
+ cached_fingerprints = {}
41
+ except Exception:
42
+ cached_fingerprints = {}
43
+
44
+ def text_from_content(content):
45
+ if isinstance(content, str):
46
+ return content
47
+ if not isinstance(content, list):
48
+ return ""
49
+ parts = []
50
+ for item in content:
51
+ if not isinstance(item, dict):
52
+ continue
53
+ text = item.get("text")
54
+ if isinstance(text, str):
55
+ parts.append(text)
56
+ return "\n".join(parts)
57
+
58
+ def tool_output_text(value):
59
+ parsed = value
60
+ if isinstance(value, str):
61
+ stripped = value.strip()
62
+ for parser in (json.loads, ast.literal_eval):
63
+ try:
64
+ parsed = parser(stripped)
65
+ break
66
+ except Exception:
67
+ parsed = value
68
+ if isinstance(parsed, dict):
69
+ parsed = parsed.get("content") or parsed.get("output") or parsed
70
+ if isinstance(parsed, list):
71
+ extracted = text_from_content(parsed)
72
+ if extracted:
73
+ return extracted
74
+ return value if isinstance(value, str) else str(value or "")
75
+
76
+ def clean(value, limit=260):
77
+ if not isinstance(value, str):
78
+ return ""
79
+ value = " ".join(value.replace("\x00", "").split())
80
+ return value[:limit]
81
+
82
+ def parse_subagent_notification(value):
83
+ text = text_from_content(value) if not isinstance(value, str) else value
84
+ if not isinstance(text, str):
85
+ return None
86
+ stripped = text.strip()
87
+ markers = ("<subagent_notification>", "{subagent_notification}")
88
+ marker = next((item for item in markers if stripped.startswith(item)), None)
89
+ if not marker:
90
+ return None
91
+ encoded = stripped[len(marker):].strip()
92
+ try:
93
+ notification, _ = json.JSONDecoder().raw_decode(encoded)
94
+ except Exception:
95
+ return None
96
+ if not isinstance(notification, dict):
97
+ return None
98
+ status = notification.get("status")
99
+ if not isinstance(status, dict):
100
+ return None
101
+ state = next(
102
+ (key for key in ("completed", "failed", "errored", "cancelled") if key in status),
103
+ "updated",
104
+ )
105
+ content = status.get(state)
106
+ if not isinstance(content, str):
107
+ content = json.dumps(content, ensure_ascii=False) if content is not None else ""
108
+ return {
109
+ "agentPath": str(notification.get("agent_path") or ""),
110
+ "state": state,
111
+ "text": content,
112
+ }
113
+
114
+ def is_context_message(value):
115
+ if not isinstance(value, str):
116
+ return True
117
+ return value.startswith(
118
+ (
119
+ "<environment_context>",
120
+ "<permissions",
121
+ "<INSTRUCTIONS>",
122
+ "<collaboration_mode>",
123
+ "<apps_instructions>",
124
+ "<plugins_instructions>",
125
+ "<skills_instructions>",
126
+ "<recommended_plugins>",
127
+ "<in-app-browser-context",
128
+ "# AGENTS.md instructions",
129
+ "A previous agent produced",
130
+ "You are Codex",
131
+ )
132
+ )
133
+
134
+ training_command_pattern = re.compile(
135
+ r"(?i)(?:\btorchrun\b|\bdeepspeed\b|\baccelerate\s+launch\b|"
136
+ r"(?:^|[\s/_.-])(?:train|eval|evaluate|rollout|benchmark|inference)"
137
+ r"(?:[\s/_.-]|$)|\blibero\b|\beval_suite\b)"
138
+ )
139
+
140
+ def command_values(value):
141
+ if isinstance(value, str):
142
+ try:
143
+ parsed = json.loads(value)
144
+ except Exception:
145
+ parsed = None
146
+ if parsed is not None and parsed != value:
147
+ return command_values(parsed)
148
+ commands = []
149
+ for match in re.finditer(
150
+ r'(?:"(?:cmd|command)"|(?<![\w])(?:cmd|command))\s*:\s*'
151
+ r'("(?:\\.|[^"\\])*")',
152
+ value,
153
+ ):
154
+ try:
155
+ commands.append(json.loads(match.group(1)))
156
+ except Exception:
157
+ pass
158
+ return commands or [value]
159
+ if isinstance(value, dict):
160
+ commands = []
161
+ for key in ("cmd", "command"):
162
+ candidate = value.get(key)
163
+ if isinstance(candidate, str):
164
+ commands.append(candidate)
165
+ for key, nested in value.items():
166
+ if key not in ("cmd", "command"):
167
+ commands.extend(command_values(nested))
168
+ return commands
169
+ if isinstance(value, list):
170
+ commands = []
171
+ for nested in value:
172
+ commands.extend(command_values(nested))
173
+ return commands
174
+ return []
175
+
176
+ all_paths = glob.glob(
177
177
  os.path.join(os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex")), "sessions", "**", "*.jsonl"), recursive=True
178
- )
178
+ )
179
179
  all_paths = list(dict.fromkeys(os.path.realpath(filename) for filename in all_paths))
180
- all_paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
181
-
182
- active_paths = set()
183
- for proc_name in os.listdir("/proc"):
184
- if not proc_name.isdigit():
185
- continue
186
- proc_root = os.path.join("/proc", proc_name)
187
- try:
188
- with open(os.path.join(proc_root, "comm"), "r") as handle:
189
- command = handle.read().strip()
190
- with open(os.path.join(proc_root, "cmdline"), "rb") as handle:
191
- cmdline = handle.read().replace(b"\x00", b" ").decode(
192
- "utf-8", errors="replace"
193
- ).strip()
194
- except Exception:
195
- continue
196
- if command != "codex" and not (
197
- command == "node" and re.search(r"(?:^|\s)(?:\S*/)?codex(?:\s|$)", cmdline)
198
- ):
199
- continue
200
-
201
- session_paths = []
202
- try:
203
- for fd in os.listdir(os.path.join(proc_root, "fd")):
204
- try:
205
- target = os.readlink(os.path.join(proc_root, "fd", fd))
206
- except Exception:
207
- continue
180
+ all_paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
181
+
182
+ active_paths = set()
183
+ for proc_name in os.listdir("/proc"):
184
+ if not proc_name.isdigit():
185
+ continue
186
+ proc_root = os.path.join("/proc", proc_name)
187
+ try:
188
+ with open(os.path.join(proc_root, "comm"), "r") as handle:
189
+ command = handle.read().strip()
190
+ with open(os.path.join(proc_root, "cmdline"), "rb") as handle:
191
+ cmdline = handle.read().replace(b"\x00", b" ").decode(
192
+ "utf-8", errors="replace"
193
+ ).strip()
194
+ except Exception:
195
+ continue
196
+ if command != "codex" and not (
197
+ command == "node" and re.search(r"(?:^|\s)(?:\S*/)?codex(?:\s|$)", cmdline)
198
+ ):
199
+ continue
200
+
201
+ session_paths = []
202
+ try:
203
+ for fd in os.listdir(os.path.join(proc_root, "fd")):
204
+ try:
205
+ target = os.readlink(os.path.join(proc_root, "fd", fd))
206
+ except Exception:
207
+ continue
208
208
  # /proc exposes the real path, which need not contain '.codex':
209
209
  # CODEX_HOME, symlinked homes and account profiles all relocate it.
210
210
  target = os.path.realpath(target)
211
211
  if "/sessions/" in target and os.path.basename(target).startswith("rollout-") and target.endswith(".jsonl"):
212
- session_paths.append(target)
213
- active_paths.add(target)
214
- except Exception:
215
- pass
216
-
217
- process_record = {
218
- "pid": int(proc_name),
219
- "cmdline": cmdline,
220
- "sessionPaths": sorted(set(session_paths)),
221
- }
222
- encoded_process = base64.urlsafe_b64encode(
223
- json.dumps(process_record, ensure_ascii=False).encode("utf-8")
224
- ).decode("ascii")
225
- print("PROCESS_META\t" + encoded_process)
226
-
227
- gpu_processes = {}
228
- try:
229
- uuid_rows = subprocess.check_output(
230
- [
231
- "nvidia-smi",
232
- "--query-gpu=index,uuid",
233
- "--format=csv,noheader,nounits",
234
- ],
235
- stderr=subprocess.DEVNULL,
236
- text=True,
237
- ).splitlines()
238
- gpu_indices = {}
239
- for row in uuid_rows:
240
- fields = [field.strip() for field in row.split(",", 1)]
241
- if len(fields) == 2:
242
- gpu_indices[fields[1]] = int(fields[0])
243
- process_rows = subprocess.check_output(
244
- [
245
- "nvidia-smi",
246
- "--query-compute-apps=pid,gpu_uuid,used_gpu_memory",
247
- "--format=csv,noheader,nounits",
248
- ],
249
- stderr=subprocess.DEVNULL,
250
- text=True,
251
- ).splitlines()
252
- for row in process_rows:
253
- fields = [field.strip() for field in row.split(",", 2)]
254
- if len(fields) != 3 or not fields[0].isdigit():
255
- continue
256
- gpu_processes.setdefault(int(fields[0]), []).append({
257
- "index": gpu_indices.get(fields[1]),
258
- "memoryMiB": int(fields[2]) if fields[2].isdigit() else 0,
259
- })
260
- except Exception:
261
- pass
262
-
263
- process_table = {}
264
- try:
265
- rows = subprocess.check_output(
266
- [
267
- "ps",
268
- "-eo",
269
- "pid=,ppid=,pgid=,sid=,etimes=,tty=,stat=,args=",
270
- ],
271
- stderr=subprocess.DEVNULL,
272
- text=True,
273
- ).splitlines()
274
- except Exception:
275
- rows = []
276
-
277
- for row in rows:
278
- fields = row.strip().split(None, 7)
279
- if len(fields) < 8:
280
- continue
281
- try:
282
- pid, ppid, pgid, sid, elapsed = map(int, fields[:5])
283
- except Exception:
284
- continue
285
- try:
286
- cwd = os.readlink(f"/proc/{pid}/cwd")
287
- except Exception:
288
- cwd = ""
289
- try:
290
- with open(f"/proc/{pid}/comm", "r") as handle:
291
- command = handle.read().strip()
292
- except Exception:
293
- command = os.path.basename(fields[7].split(None, 1)[0])
294
- process_table[pid] = {
295
- "pid": pid,
296
- "ppid": ppid,
297
- "pgid": pgid,
298
- "sid": sid,
299
- "elapsedSeconds": elapsed,
300
- "tty": fields[5].replace("/dev/", ""),
301
- "stat": fields[6],
302
- "command": command,
303
- "cmdline": fields[7],
304
- "cwd": cwd,
305
- "gpus": gpu_processes.get(pid, []),
306
- }
307
-
308
- workload_candidates = {}
309
- for pid, process in process_table.items():
310
- command = process["command"].lower()
311
- cmdline = process["cmdline"]
312
- if command in ("codex", "ssh", "sshd", "tmux: server", "tmux"):
313
- continue
314
- if "monitor_" in cmdline and not process["gpus"]:
315
- continue
316
- if process["gpus"] or training_command_pattern.search(cmdline):
317
- workload_candidates[pid] = process
318
-
319
- workload_groups = {}
320
- for process in workload_candidates.values():
321
- group_id = process["sid"] if process["sid"] > 1 else process["pgid"]
322
- if group_id <= 1:
323
- group_id = process["pid"]
324
- workload_groups.setdefault(group_id, []).append(process)
325
-
326
- for group_id, members in workload_groups.items():
327
- member_ids = {member["pid"] for member in members}
328
- roots = [member for member in members if member["ppid"] not in member_ids]
329
- root = sorted(
330
- roots or members,
331
- key=lambda item: (-item["elapsedSeconds"], item["pid"]),
332
- )[0]
333
- ancestor_pids = []
334
- cursor = root["ppid"]
335
- seen = set()
336
- while cursor > 1 and cursor not in seen and len(ancestor_pids) < 40:
337
- seen.add(cursor)
338
- ancestor_pids.append(cursor)
339
- parent = process_table.get(cursor)
340
- if not parent:
341
- break
342
- cursor = parent["ppid"]
343
- gpu_entries = []
344
- for member in members:
345
- for gpu in member["gpus"]:
346
- gpu_entries.append({
347
- **gpu,
348
- "pid": member["pid"],
349
- })
350
- record = {
351
- **root,
352
- "groupId": group_id,
353
- "workerPids": sorted(member_ids),
354
- "ancestorPids": ancestor_pids,
355
- "gpus": gpu_entries,
356
- "gpuMemoryMiB": sum(gpu["memoryMiB"] for gpu in gpu_entries),
357
- "kind": (
358
- "evaluation"
359
- if re.search(r"(?i)(?:eval|evaluate|benchmark|rollout|libero|eval_suite)", root["cmdline"])
360
- else "training"
361
- ),
362
- }
363
- encoded_workload = base64.urlsafe_b64encode(
364
- json.dumps(record, ensure_ascii=False).encode("utf-8")
365
- ).decode("ascii")
366
- print("WORKLOAD\t" + encoded_workload)
367
-
368
- paths = list(dict.fromkeys(all_paths[:10] + list(active_paths)))
369
- paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
370
-
371
- try:
372
- panes = subprocess.check_output(
373
- [
374
- "tmux",
375
- "list-panes",
376
- "-a",
377
- "-F",
378
- "#{session_name}\t#{window_index}.#{pane_index}\t#{pane_current_command}\t#{pane_current_path}\t#{pane_tty}\t#{pane_pid}\t#{session_activity}\t#{pane_dead}\t#{pane_dead_status}",
379
- ],
380
- stderr=subprocess.DEVNULL,
381
- text=True,
382
- ).splitlines()
383
- for line in panes:
384
- fields = line.split("\t")
385
- if len(fields) != 9:
386
- continue
387
- target = f"{fields[0]}:{fields[1]}"
388
- try:
389
- preview = subprocess.check_output(
390
- ["tmux", "capture-pane", "-p", "-S", "-24", "-t", target],
391
- stderr=subprocess.DEVNULL,
392
- )
393
- except Exception:
394
- preview = b""
395
- encoded_preview = base64.b64encode(preview).decode("ascii")
396
- print("PANE\t" + "\t".join(fields) + "\t" + encoded_preview)
397
- except Exception:
398
- pass
399
-
400
- def bounded_session_lines(filename, active):
401
- head_bytes = 2 * 1024 * 1024
402
- tail_bytes = (8 if active else 2) * 1024 * 1024
403
- tail_lines = 5000 if active else 500
404
- with open(filename, "rb") as handle:
405
- first = handle.readline(1024 * 1024).decode("utf-8", errors="replace")
406
- head_blob = handle.read(head_bytes)
407
- size = os.fstat(handle.fileno()).st_size
408
- handle.seek(max(0, size - tail_bytes))
409
- tail_blob = handle.read(tail_bytes)
410
- head = head_blob.decode("utf-8", errors="replace").splitlines(keepends=True)[:400]
411
- tail = tail_blob.decode("utf-8", errors="replace").splitlines(keepends=True)
412
- if size > tail_bytes and tail:
413
- # The first entry begins in the middle of a JSONL record.
414
- tail = tail[1:]
415
- return first, head, tail[-tail_lines:]
416
-
417
- for filename in paths:
418
- try:
419
- stat = os.stat(filename)
420
- mtime_ms = int(stat.st_mtime * 1000)
421
- size_bytes = int(stat.st_size)
422
- cached = cached_fingerprints.get(filename)
423
- if (
424
- isinstance(cached, list)
425
- and len(cached) == 2
426
- and cached[0] == mtime_ms
427
- and cached[1] == size_bytes
428
- ):
429
- encoded_path = base64.urlsafe_b64encode(
430
- filename.encode("utf-8")
431
- ).decode("ascii")
432
- print("SESSION_REF\t" + encoded_path)
433
- continue
434
- first, head, tail = bounded_session_lines(
435
- filename, filename in active_paths
436
- )
437
- first_obj = json.loads(first)
438
- meta = first_obj.get("payload", {}) if first_obj.get("type") == "session_meta" else {}
439
- except Exception:
440
- continue
441
-
442
- source = meta.get("source")
443
- subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
444
- spawn = subagent.get("thread_spawn", {}) if isinstance(subagent, dict) else {}
445
- record = {
446
- "id": meta.get("id") or meta.get("session_id") or os.path.basename(filename),
447
- "rootSessionId": meta.get("session_id") or meta.get("id") or "",
448
- "parentThreadId": meta.get("parent_thread_id")
449
- or spawn.get("parent_thread_id")
450
- or "",
451
- "agentPath": spawn.get("agent_path") or "",
452
- "agentNickname": spawn.get("agent_nickname") or "",
453
- "isSubagent": bool(spawn or meta.get("parent_thread_id")),
454
- "cwd": meta.get("cwd") or "",
455
- "startedAt": meta.get("timestamp") or first_obj.get("timestamp"),
456
- "cliVersion": meta.get("cli_version") or "",
457
- "path": filename,
458
- "mtimeMs": mtime_ms,
459
- "sizeBytes": size_bytes,
460
- "firstUser": "",
461
- "lastUser": "",
462
- "lastAssistant": "",
463
- "lastAction": "",
464
- "lastError": "",
465
- "launches": [],
466
- "userMessages": [],
467
- "assistantMessages": [],
468
- "model": "",
469
- "reasoningEffort": "",
470
- "approvalPolicy": "",
471
- "sandboxPolicy": "",
472
- "collaborationMode": "",
473
- "account": None,
474
- "tokenUsage": None,
475
- "turnState": "idle",
476
- "lastEventAt": first_obj.get("timestamp"),
477
- }
478
-
479
- seen_lines = set()
480
- for raw in head + tail:
481
- if raw in seen_lines:
482
- continue
483
- seen_lines.add(raw)
484
- try:
485
- event = json.loads(raw)
486
- except Exception:
487
- continue
488
- payload = event.get("payload", {})
489
- event_type = event.get("type")
490
- record["lastEventAt"] = event.get("timestamp") or record["lastEventAt"]
491
-
492
- if event_type == "turn_context":
493
- record["model"] = payload.get("model") or record["model"]
494
- record["reasoningEffort"] = (
495
- payload.get("effort")
496
- or payload.get("reasoning_effort")
497
- or record["reasoningEffort"]
498
- )
499
- record["approvalPolicy"] = (
500
- payload.get("approval_policy") or record["approvalPolicy"]
501
- )
502
- sandbox = payload.get("sandbox_policy")
503
- if isinstance(sandbox, dict):
504
- record["sandboxPolicy"] = (
505
- sandbox.get("type")
506
- or sandbox.get("mode")
507
- or record["sandboxPolicy"]
508
- )
509
- elif isinstance(sandbox, str):
510
- record["sandboxPolicy"] = sandbox
511
- collaboration = payload.get("collaboration_mode")
512
- if isinstance(collaboration, dict):
513
- record["collaborationMode"] = (
514
- collaboration.get("mode")
515
- or collaboration.get("name")
516
- or record["collaborationMode"]
517
- )
518
- elif isinstance(collaboration, str):
519
- record["collaborationMode"] = collaboration
520
-
521
- if event_type == "event_msg":
522
- kind = payload.get("type")
523
- if kind == "task_started":
524
- record["turnState"] = "working"
525
- elif kind in ("task_complete", "turn_complete", "task_completed"):
526
- record["turnState"] = "idle"
527
- candidate = clean(payload.get("last_agent_message"), 1600)
528
- if candidate:
529
- record["lastAssistant"] = candidate
530
- record["assistantMessages"].append(candidate)
531
- record["assistantMessages"] = record["assistantMessages"][-6:]
532
- elif kind == "agent_message":
533
- candidate = clean(
534
- payload.get("message") or payload.get("text"),
535
- 1600,
536
- )
537
- if candidate:
538
- record["lastAssistant"] = candidate
539
- record["assistantMessages"].append(candidate)
540
- record["assistantMessages"] = record["assistantMessages"][-6:]
541
- elif kind in ("user_message", "user_input"):
542
- raw_candidate = (
543
- payload.get("message") or payload.get("text") or payload.get("content")
544
- )
545
- notification = parse_subagent_notification(raw_candidate)
546
- if notification:
547
- candidate = clean(notification["text"], 1600)
548
- if candidate:
549
- record["lastAssistant"] = candidate
550
- record["assistantMessages"].append(candidate)
551
- record["assistantMessages"] = record["assistantMessages"][-6:]
552
- else:
553
- candidate = clean(raw_candidate, 1200)
554
- if candidate and not is_context_message(candidate):
555
- record["firstUser"] = record["firstUser"] or candidate
556
- record["lastUser"] = clean(candidate)
557
- record["userMessages"].append(candidate)
558
- record["userMessages"] = record["userMessages"][-8:]
559
- elif kind == "token_count":
560
- info = payload.get("info")
561
- if isinstance(info, dict):
562
- record["tokenUsage"] = {
563
- "modelContextWindow": info.get("model_context_window"),
564
- "total": info.get("total_token_usage"),
565
- "last": info.get("last_token_usage"),
566
- }
567
- rate_limits = payload.get("rate_limits")
568
- if isinstance(rate_limits, dict):
212
+ session_paths.append(target)
213
+ active_paths.add(target)
214
+ except Exception:
215
+ pass
216
+
217
+ process_record = {
218
+ "pid": int(proc_name),
219
+ "cmdline": cmdline,
220
+ "sessionPaths": sorted(set(session_paths)),
221
+ }
222
+ encoded_process = base64.urlsafe_b64encode(
223
+ json.dumps(process_record, ensure_ascii=False).encode("utf-8")
224
+ ).decode("ascii")
225
+ print("PROCESS_META\t" + encoded_process)
226
+
227
+ gpu_processes = {}
228
+ try:
229
+ uuid_rows = subprocess.check_output(
230
+ [
231
+ "nvidia-smi",
232
+ "--query-gpu=index,uuid",
233
+ "--format=csv,noheader,nounits",
234
+ ],
235
+ stderr=subprocess.DEVNULL,
236
+ text=True,
237
+ ).splitlines()
238
+ gpu_indices = {}
239
+ for row in uuid_rows:
240
+ fields = [field.strip() for field in row.split(",", 1)]
241
+ if len(fields) == 2:
242
+ gpu_indices[fields[1]] = int(fields[0])
243
+ process_rows = subprocess.check_output(
244
+ [
245
+ "nvidia-smi",
246
+ "--query-compute-apps=pid,gpu_uuid,used_gpu_memory",
247
+ "--format=csv,noheader,nounits",
248
+ ],
249
+ stderr=subprocess.DEVNULL,
250
+ text=True,
251
+ ).splitlines()
252
+ for row in process_rows:
253
+ fields = [field.strip() for field in row.split(",", 2)]
254
+ if len(fields) != 3 or not fields[0].isdigit():
255
+ continue
256
+ gpu_processes.setdefault(int(fields[0]), []).append({
257
+ "index": gpu_indices.get(fields[1]),
258
+ "memoryMiB": int(fields[2]) if fields[2].isdigit() else 0,
259
+ })
260
+ except Exception:
261
+ pass
262
+
263
+ process_table = {}
264
+ try:
265
+ rows = subprocess.check_output(
266
+ [
267
+ "ps",
268
+ "-eo",
269
+ "pid=,ppid=,pgid=,sid=,etimes=,tty=,stat=,args=",
270
+ ],
271
+ stderr=subprocess.DEVNULL,
272
+ text=True,
273
+ ).splitlines()
274
+ except Exception:
275
+ rows = []
276
+
277
+ for row in rows:
278
+ fields = row.strip().split(None, 7)
279
+ if len(fields) < 8:
280
+ continue
281
+ try:
282
+ pid, ppid, pgid, sid, elapsed = map(int, fields[:5])
283
+ except Exception:
284
+ continue
285
+ try:
286
+ cwd = os.readlink(f"/proc/{pid}/cwd")
287
+ except Exception:
288
+ cwd = ""
289
+ try:
290
+ with open(f"/proc/{pid}/comm", "r") as handle:
291
+ command = handle.read().strip()
292
+ except Exception:
293
+ command = os.path.basename(fields[7].split(None, 1)[0])
294
+ process_table[pid] = {
295
+ "pid": pid,
296
+ "ppid": ppid,
297
+ "pgid": pgid,
298
+ "sid": sid,
299
+ "elapsedSeconds": elapsed,
300
+ "tty": fields[5].replace("/dev/", ""),
301
+ "stat": fields[6],
302
+ "command": command,
303
+ "cmdline": fields[7],
304
+ "cwd": cwd,
305
+ "gpus": gpu_processes.get(pid, []),
306
+ }
307
+
308
+ workload_candidates = {}
309
+ for pid, process in process_table.items():
310
+ command = process["command"].lower()
311
+ cmdline = process["cmdline"]
312
+ if command in ("codex", "ssh", "sshd", "tmux: server", "tmux"):
313
+ continue
314
+ if "monitor_" in cmdline and not process["gpus"]:
315
+ continue
316
+ if process["gpus"] or training_command_pattern.search(cmdline):
317
+ workload_candidates[pid] = process
318
+
319
+ workload_groups = {}
320
+ for process in workload_candidates.values():
321
+ group_id = process["sid"] if process["sid"] > 1 else process["pgid"]
322
+ if group_id <= 1:
323
+ group_id = process["pid"]
324
+ workload_groups.setdefault(group_id, []).append(process)
325
+
326
+ for group_id, members in workload_groups.items():
327
+ member_ids = {member["pid"] for member in members}
328
+ roots = [member for member in members if member["ppid"] not in member_ids]
329
+ root = sorted(
330
+ roots or members,
331
+ key=lambda item: (-item["elapsedSeconds"], item["pid"]),
332
+ )[0]
333
+ ancestor_pids = []
334
+ cursor = root["ppid"]
335
+ seen = set()
336
+ while cursor > 1 and cursor not in seen and len(ancestor_pids) < 40:
337
+ seen.add(cursor)
338
+ ancestor_pids.append(cursor)
339
+ parent = process_table.get(cursor)
340
+ if not parent:
341
+ break
342
+ cursor = parent["ppid"]
343
+ gpu_entries = []
344
+ for member in members:
345
+ for gpu in member["gpus"]:
346
+ gpu_entries.append({
347
+ **gpu,
348
+ "pid": member["pid"],
349
+ })
350
+ record = {
351
+ **root,
352
+ "groupId": group_id,
353
+ "workerPids": sorted(member_ids),
354
+ "ancestorPids": ancestor_pids,
355
+ "gpus": gpu_entries,
356
+ "gpuMemoryMiB": sum(gpu["memoryMiB"] for gpu in gpu_entries),
357
+ "kind": (
358
+ "evaluation"
359
+ if re.search(r"(?i)(?:eval|evaluate|benchmark|rollout|libero|eval_suite)", root["cmdline"])
360
+ else "training"
361
+ ),
362
+ }
363
+ encoded_workload = base64.urlsafe_b64encode(
364
+ json.dumps(record, ensure_ascii=False).encode("utf-8")
365
+ ).decode("ascii")
366
+ print("WORKLOAD\t" + encoded_workload)
367
+
368
+ paths = list(dict.fromkeys(all_paths[:10] + list(active_paths)))
369
+ paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
370
+
371
+ try:
372
+ panes = subprocess.check_output(
373
+ [
374
+ "tmux",
375
+ "list-panes",
376
+ "-a",
377
+ "-F",
378
+ "#{session_name}\t#{window_index}.#{pane_index}\t#{pane_current_command}\t#{pane_current_path}\t#{pane_tty}\t#{pane_pid}\t#{session_activity}\t#{pane_dead}\t#{pane_dead_status}",
379
+ ],
380
+ stderr=subprocess.DEVNULL,
381
+ text=True,
382
+ ).splitlines()
383
+ for line in panes:
384
+ fields = line.split("\t")
385
+ if len(fields) != 9:
386
+ continue
387
+ target = f"{fields[0]}:{fields[1]}"
388
+ try:
389
+ preview = subprocess.check_output(
390
+ ["tmux", "capture-pane", "-p", "-S", "-24", "-t", target],
391
+ stderr=subprocess.DEVNULL,
392
+ )
393
+ except Exception:
394
+ preview = b""
395
+ encoded_preview = base64.b64encode(preview).decode("ascii")
396
+ print("PANE\t" + "\t".join(fields) + "\t" + encoded_preview)
397
+ except Exception:
398
+ pass
399
+
400
+ def bounded_session_lines(filename, active):
401
+ head_bytes = 2 * 1024 * 1024
402
+ tail_bytes = (8 if active else 2) * 1024 * 1024
403
+ tail_lines = 5000 if active else 500
404
+ with open(filename, "rb") as handle:
405
+ first = handle.readline(1024 * 1024).decode("utf-8", errors="replace")
406
+ head_blob = handle.read(head_bytes)
407
+ size = os.fstat(handle.fileno()).st_size
408
+ handle.seek(max(0, size - tail_bytes))
409
+ tail_blob = handle.read(tail_bytes)
410
+ head = head_blob.decode("utf-8", errors="replace").splitlines(keepends=True)[:400]
411
+ tail = tail_blob.decode("utf-8", errors="replace").splitlines(keepends=True)
412
+ if size > tail_bytes and tail:
413
+ # The first entry begins in the middle of a JSONL record.
414
+ tail = tail[1:]
415
+ return first, head, tail[-tail_lines:]
416
+
417
+ for filename in paths:
418
+ try:
419
+ stat = os.stat(filename)
420
+ mtime_ms = int(stat.st_mtime * 1000)
421
+ size_bytes = int(stat.st_size)
422
+ cached = cached_fingerprints.get(filename)
423
+ if (
424
+ isinstance(cached, list)
425
+ and len(cached) == 2
426
+ and cached[0] == mtime_ms
427
+ and cached[1] == size_bytes
428
+ ):
429
+ encoded_path = base64.urlsafe_b64encode(
430
+ filename.encode("utf-8")
431
+ ).decode("ascii")
432
+ print("SESSION_REF\t" + encoded_path)
433
+ continue
434
+ first, head, tail = bounded_session_lines(
435
+ filename, filename in active_paths
436
+ )
437
+ first_obj = json.loads(first)
438
+ meta = first_obj.get("payload", {}) if first_obj.get("type") == "session_meta" else {}
439
+ except Exception:
440
+ continue
441
+
442
+ source = meta.get("source")
443
+ subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
444
+ spawn = subagent.get("thread_spawn", {}) if isinstance(subagent, dict) else {}
445
+ record = {
446
+ "id": meta.get("id") or meta.get("session_id") or os.path.basename(filename),
447
+ "rootSessionId": meta.get("session_id") or meta.get("id") or "",
448
+ "parentThreadId": meta.get("parent_thread_id")
449
+ or spawn.get("parent_thread_id")
450
+ or "",
451
+ "agentPath": spawn.get("agent_path") or "",
452
+ "agentNickname": spawn.get("agent_nickname") or meta.get("agent_nickname") or "",
453
+ "agentRole": spawn.get("agent_role") or meta.get("agent_role") or "",
454
+ "isSubagent": bool(spawn or meta.get("parent_thread_id")),
455
+ "cwd": meta.get("cwd") or "",
456
+ "startedAt": meta.get("timestamp") or first_obj.get("timestamp"),
457
+ "cliVersion": meta.get("cli_version") or "",
458
+ "path": filename,
459
+ "mtimeMs": mtime_ms,
460
+ "sizeBytes": size_bytes,
461
+ "firstUser": "",
462
+ "lastUser": "",
463
+ "lastAssistant": "",
464
+ "lastAction": "",
465
+ "lastError": "",
466
+ "launches": [],
467
+ "userMessages": [],
468
+ "assistantMessages": [],
469
+ "model": "",
470
+ "reasoningEffort": "",
471
+ "approvalPolicy": "",
472
+ "sandboxPolicy": "",
473
+ "collaborationMode": "",
474
+ "account": None,
475
+ "tokenUsage": None,
476
+ "turnState": "idle",
477
+ "lastEventAt": first_obj.get("timestamp"),
478
+ }
479
+
480
+ seen_lines = set()
481
+ for raw in head + tail:
482
+ if raw in seen_lines:
483
+ continue
484
+ seen_lines.add(raw)
485
+ try:
486
+ event = json.loads(raw)
487
+ except Exception:
488
+ continue
489
+ payload = event.get("payload", {})
490
+ event_type = event.get("type")
491
+ record["lastEventAt"] = event.get("timestamp") or record["lastEventAt"]
492
+
493
+ if event_type == "turn_context":
494
+ record["model"] = payload.get("model") or record["model"]
495
+ record["reasoningEffort"] = (
496
+ payload.get("effort")
497
+ or payload.get("reasoning_effort")
498
+ or record["reasoningEffort"]
499
+ )
500
+ record["approvalPolicy"] = (
501
+ payload.get("approval_policy") or record["approvalPolicy"]
502
+ )
503
+ sandbox = payload.get("sandbox_policy")
504
+ if isinstance(sandbox, dict):
505
+ record["sandboxPolicy"] = (
506
+ sandbox.get("type")
507
+ or sandbox.get("mode")
508
+ or record["sandboxPolicy"]
509
+ )
510
+ elif isinstance(sandbox, str):
511
+ record["sandboxPolicy"] = sandbox
512
+ collaboration = payload.get("collaboration_mode")
513
+ if isinstance(collaboration, dict):
514
+ record["collaborationMode"] = (
515
+ collaboration.get("mode")
516
+ or collaboration.get("name")
517
+ or record["collaborationMode"]
518
+ )
519
+ elif isinstance(collaboration, str):
520
+ record["collaborationMode"] = collaboration
521
+
522
+ if event_type == "event_msg":
523
+ kind = payload.get("type")
524
+ if kind == "task_started":
525
+ record["turnState"] = "working"
526
+ elif kind in ("task_complete", "turn_complete", "task_completed"):
527
+ record["turnState"] = "idle"
528
+ candidate = clean(payload.get("last_agent_message"), 1600)
529
+ if candidate:
530
+ record["lastAssistant"] = candidate
531
+ record["assistantMessages"].append(candidate)
532
+ record["assistantMessages"] = record["assistantMessages"][-6:]
533
+ elif kind == "agent_message":
534
+ candidate = clean(
535
+ payload.get("message") or payload.get("text"),
536
+ 1600,
537
+ )
538
+ if candidate:
539
+ record["lastAssistant"] = candidate
540
+ record["assistantMessages"].append(candidate)
541
+ record["assistantMessages"] = record["assistantMessages"][-6:]
542
+ elif kind in ("user_message", "user_input"):
543
+ raw_candidate = (
544
+ payload.get("message") or payload.get("text") or payload.get("content")
545
+ )
546
+ notification = parse_subagent_notification(raw_candidate)
547
+ if notification:
548
+ candidate = clean(notification["text"], 1600)
549
+ if candidate:
550
+ record["lastAssistant"] = candidate
551
+ record["assistantMessages"].append(candidate)
552
+ record["assistantMessages"] = record["assistantMessages"][-6:]
553
+ else:
554
+ candidate = clean(raw_candidate, 1200)
555
+ if candidate and not is_context_message(candidate):
556
+ record["firstUser"] = record["firstUser"] or candidate
557
+ record["lastUser"] = clean(candidate)
558
+ record["userMessages"].append(candidate)
559
+ record["userMessages"] = record["userMessages"][-8:]
560
+ elif kind == "token_count":
561
+ info = payload.get("info")
562
+ if isinstance(info, dict):
563
+ record["tokenUsage"] = {
564
+ "modelContextWindow": info.get("model_context_window"),
565
+ "total": info.get("total_token_usage"),
566
+ "last": info.get("last_token_usage"),
567
+ }
568
+ rate_limits = payload.get("rate_limits")
569
+ if isinstance(rate_limits, dict):
569
570
  primary = rate_limits.get("primary")
570
- secondary = rate_limits.get("secondary")
571
- credits = rate_limits.get("credits")
572
- record["account"] = {
573
- "planType": rate_limits.get("plan_type") or "",
571
+ secondary = rate_limits.get("secondary")
572
+ credits = rate_limits.get("credits")
573
+ record["account"] = {
574
+ "planType": rate_limits.get("plan_type") or "",
574
575
  "primary": primary if isinstance(primary, dict) else None,
575
- "secondary": secondary if isinstance(secondary, dict) else None,
576
- "credits": credits if isinstance(credits, dict) else None,
577
- }
578
-
579
- if event_type != "response_item":
580
- continue
581
-
582
- kind = payload.get("type")
583
- role = payload.get("role")
584
- if kind == "message" and role == "user":
585
- raw_candidate = text_from_content(payload.get("content"))
586
- notification = parse_subagent_notification(raw_candidate)
587
- if notification:
588
- candidate = clean(notification["text"], 1600)
589
- if candidate:
590
- record["lastAssistant"] = candidate
591
- record["assistantMessages"].append(candidate)
592
- record["assistantMessages"] = record["assistantMessages"][-6:]
593
- else:
594
- candidate = clean(raw_candidate)
595
- is_context = is_context_message(candidate)
596
- if candidate and not is_context:
597
- record["firstUser"] = record["firstUser"] or candidate
598
- record["lastUser"] = candidate
599
- record["userMessages"].append(clean(candidate, 1200))
600
- record["userMessages"] = record["userMessages"][-8:]
601
- elif kind == "message" and role == "assistant":
602
- candidate = clean(text_from_content(payload.get("content")), 1600)
603
- if candidate:
604
- record["lastAssistant"] = candidate
605
- record["assistantMessages"].append(candidate)
606
- record["assistantMessages"] = record["assistantMessages"][-6:]
607
- elif kind in ("function_call", "custom_tool_call"):
608
- name = payload.get("name") or "tool"
609
- arguments = payload.get("arguments") or payload.get("input") or ""
610
- record["lastAction"] = clean(f"{name}: {arguments}", 300)
611
- record["turnState"] = "working"
612
- for command in command_values(arguments):
613
- if (
614
- training_command_pattern.search(command)
615
- or re.search(r"(?i)\btmux\s+(?:new-session|new)\b", command)
616
- ):
617
- record["launches"].append({
618
- "timestamp": event.get("timestamp"),
619
- "command": clean(command, 2400),
620
- })
621
- record["launches"] = record["launches"][-80:]
622
- elif kind in ("function_call_output", "custom_tool_call_output"):
623
- output = clean(tool_output_text(payload.get("output")), 300)
624
- if (
625
- "exit code 1" in output.lower()
626
- or "process exited with code 1" in output.lower()
627
- or "traceback" in output.lower()
628
- ):
629
- record["lastError"] = output
630
-
631
- encoded = base64.urlsafe_b64encode(
632
- json.dumps(record, ensure_ascii=False).encode("utf-8")
633
- ).decode("ascii")
634
- print("SESSION\t" + encoded)
635
- PY
576
+ "secondary": secondary if isinstance(secondary, dict) else None,
577
+ "credits": credits if isinstance(credits, dict) else None,
578
+ }
579
+
580
+ if event_type != "response_item":
581
+ continue
582
+
583
+ kind = payload.get("type")
584
+ role = payload.get("role")
585
+ if kind == "message" and role == "user":
586
+ raw_candidate = text_from_content(payload.get("content"))
587
+ notification = parse_subagent_notification(raw_candidate)
588
+ if notification:
589
+ candidate = clean(notification["text"], 1600)
590
+ if candidate:
591
+ record["lastAssistant"] = candidate
592
+ record["assistantMessages"].append(candidate)
593
+ record["assistantMessages"] = record["assistantMessages"][-6:]
594
+ else:
595
+ candidate = clean(raw_candidate)
596
+ is_context = is_context_message(candidate)
597
+ if candidate and not is_context:
598
+ record["firstUser"] = record["firstUser"] or candidate
599
+ record["lastUser"] = candidate
600
+ record["userMessages"].append(clean(candidate, 1200))
601
+ record["userMessages"] = record["userMessages"][-8:]
602
+ elif kind == "message" and role == "assistant":
603
+ candidate = clean(text_from_content(payload.get("content")), 1600)
604
+ if candidate:
605
+ record["lastAssistant"] = candidate
606
+ record["assistantMessages"].append(candidate)
607
+ record["assistantMessages"] = record["assistantMessages"][-6:]
608
+ elif kind in ("function_call", "custom_tool_call"):
609
+ name = payload.get("name") or "tool"
610
+ arguments = payload.get("arguments") or payload.get("input") or ""
611
+ record["lastAction"] = clean(f"{name}: {arguments}", 300)
612
+ record["turnState"] = "working"
613
+ for command in command_values(arguments):
614
+ if (
615
+ training_command_pattern.search(command)
616
+ or re.search(r"(?i)\btmux\s+(?:new-session|new)\b", command)
617
+ ):
618
+ record["launches"].append({
619
+ "timestamp": event.get("timestamp"),
620
+ "command": clean(command, 2400),
621
+ })
622
+ record["launches"] = record["launches"][-80:]
623
+ elif kind in ("function_call_output", "custom_tool_call_output"):
624
+ output = clean(tool_output_text(payload.get("output")), 300)
625
+ if (
626
+ "exit code 1" in output.lower()
627
+ or "process exited with code 1" in output.lower()
628
+ or "traceback" in output.lower()
629
+ ):
630
+ record["lastError"] = output
631
+
632
+ encoded = base64.urlsafe_b64encode(
633
+ json.dumps(record, ensure_ascii=False).encode("utf-8")
634
+ ).decode("ascii")
635
+ print("SESSION\t" + encoded)
636
+ PY
636
637
  `;