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,464 +1,464 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const DIALOGUE_PROBE = String.raw`
3
- import json
4
- import os
5
- import sys
6
-
7
- MAX_TOOL_EVENTS = 300
8
- MAX_TOOL_TEXT = 6000
9
- MAX_DIALOGUE_TEXT = 200000
10
-
11
- path = os.path.realpath(sys.argv[1])
12
- page_limit = max(1, min(100, int(sys.argv[2]) if len(sys.argv) > 2 else 10))
13
- dialogue_only = len(sys.argv) > 4 and sys.argv[4] == "dialogue-only"
14
- file_size = os.path.getsize(path)
15
- before_byte = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else file_size
16
- scan_end = max(0, min(file_size, before_byte))
17
- scan_start = max(0, scan_end - (8000000 if dialogue_only else 2000000))
18
- events = []
19
- call_events = {}
20
- last_dialogue_line = {}
21
- event_ordinals = {}
22
- hidden_reasoning_count = 0
23
- tool_event_count = 0
24
- line_count = 0
25
- current_byte = scan_start
26
-
27
- def readable_text(value):
28
- if isinstance(value, str):
29
- return value
30
- if isinstance(value, list):
31
- parts = []
32
- for item in value:
33
- if isinstance(item, str):
34
- parts.append(item)
35
- continue
36
- if not isinstance(item, dict):
37
- continue
38
- if item.get("type") == "encrypted_content":
39
- continue
40
- for key in ("text", "content", "output"):
41
- candidate = item.get(key)
42
- if isinstance(candidate, str):
43
- parts.append(candidate)
44
- break
45
- return "\n".join(parts)
46
- if isinstance(value, dict):
47
- for key in ("text", "content", "output", "message"):
48
- candidate = value.get(key)
49
- if isinstance(candidate, str):
50
- return candidate
51
- return json.dumps(value, ensure_ascii=False)
52
- if value is None:
53
- return ""
54
- return str(value)
55
-
56
- def clean_text(value, limit):
57
- text = readable_text(value).replace("\x00", "")
58
- if len(text) <= limit:
59
- return text
60
- omitted = len(text) - limit
61
- return text[:limit] + f"\n\n… [已压缩 {omitted} 个字符]"
62
-
63
- def parse_subagent_notification(value):
64
- text = readable_text(value).strip()
65
- markers = ("<subagent_notification>", "{subagent_notification}")
66
- marker = next((item for item in markers if text.startswith(item)), None)
67
- if not marker:
68
- return None
69
- encoded = text[len(marker):].strip()
70
- try:
71
- notification, _ = json.JSONDecoder().raw_decode(encoded)
72
- except Exception:
73
- return None
74
- if not isinstance(notification, dict):
75
- return None
76
- status = notification.get("status")
77
- if not isinstance(status, dict):
78
- return None
79
- state = next(
80
- (key for key in ("completed", "failed", "errored", "cancelled") if key in status),
81
- "updated",
82
- )
83
- content = status.get(state)
84
- if not isinstance(content, str):
85
- content = json.dumps(content, ensure_ascii=False) if content is not None else ""
86
- return {
87
- "agentPath": str(notification.get("agent_path") or ""),
88
- "state": state,
89
- "text": content,
90
- }
91
-
92
- def is_context_message(value):
93
- if not isinstance(value, str):
94
- return True
95
- stripped = value.lstrip()
96
- return stripped.startswith((
97
- "<environment_context>",
98
- "<permissions",
99
- "<INSTRUCTIONS>",
100
- "<collaboration_mode>",
101
- "<apps_instructions>",
102
- "<plugins_instructions>",
103
- "<skills_instructions>",
104
- "<recommended_plugins>",
105
- "<in-app-browser-context",
106
- "# AGENTS.md instructions",
107
- "A previous agent produced",
108
- "You are Codex",
109
- ))
110
-
111
- def add_event(kind, title, text="", timestamp=None, **extra):
112
- global tool_event_count
113
- category = extra.pop("category", None)
114
- if category is None:
115
- if kind == "user":
116
- category = "dialogue"
117
- elif kind == "assistant":
118
- category = "reasoning" if extra.get("phase") == "commentary" else "dialogue"
119
- elif kind in ("reasoning", "intermediate"):
120
- category = "reasoning"
121
- else:
122
- category = "operations"
123
- text_limit = MAX_TOOL_TEXT if kind in ("command", "tool") else MAX_DIALOGUE_TEXT
124
- ordinal = event_ordinals.get(current_byte, 0)
125
- event_ordinals[current_byte] = ordinal + 1
126
- record = {
127
- "id": f"byte-{current_byte}-{ordinal}",
128
- "kind": kind,
129
- "category": category,
130
- "title": title,
131
- "text": clean_text(text, text_limit),
132
- "timestamp": timestamp,
133
- "_sourceByte": current_byte,
134
- }
135
- for key, value in extra.items():
136
- if value not in (None, ""):
137
- record[key] = value
138
- events.append(record)
139
- if kind in ("command", "tool"):
140
- tool_event_count += 1
141
- return record
142
-
143
- def add_dialogue(kind, title, text, timestamp=None, **extra):
144
- candidate = clean_text(text, MAX_DIALOGUE_TEXT)
145
- if not candidate or (kind == "user" and is_context_message(candidate)):
146
- return None
147
- signature = (kind, candidate)
148
- previous_line = last_dialogue_line.get(signature)
149
- if previous_line is not None and line_count - previous_line <= 4:
150
- return None
151
- last_dialogue_line[signature] = line_count
152
- return add_event(kind, title, candidate, timestamp, **extra)
153
-
154
- def reasoning_summary(payload):
155
- summary = payload.get("summary")
156
- if not isinstance(summary, list):
157
- return readable_text(summary)
158
- parts = []
159
- for item in summary:
160
- if isinstance(item, str):
161
- parts.append(item)
162
- elif isinstance(item, dict):
163
- text = item.get("text") or item.get("summary_text")
164
- if isinstance(text, str):
165
- parts.append(text)
166
- return "\n\n".join(parts)
167
-
168
- def call_input(payload):
169
- value = payload.get("arguments")
170
- if value in (None, ""):
171
- value = payload.get("input")
172
- return readable_text(value)
173
-
174
- def command_from_call(name, value):
175
- lowered = str(name).lower()
176
- parsed = None
177
- if isinstance(value, str):
178
- try:
179
- parsed = json.loads(value)
180
- except Exception:
181
- parsed = None
182
- elif isinstance(value, dict):
183
- parsed = value
184
- if isinstance(parsed, dict):
185
- command = parsed.get("cmd") or parsed.get("command")
186
- if isinstance(command, list):
187
- command = " ".join(str(part) for part in command)
188
- if isinstance(command, str):
189
- return command
190
- if any(token in lowered for token in ("exec", "shell", "terminal", "write_stdin")):
191
- return readable_text(value)
192
- return ""
193
-
194
- with open(path, "rb") as handle:
195
- handle.seek(scan_start)
196
- window = handle.read(scan_end - scan_start)
197
-
198
- if scan_start > 0:
199
- boundary = window.find(b"\n")
200
- if boundary < 0:
201
- window = b""
202
- scan_start = scan_end
203
- else:
204
- scan_start += boundary + 1
205
- window = window[boundary + 1:]
206
-
207
- cursor = scan_start
208
- for raw_bytes in window.splitlines(keepends=True):
209
- current_byte = cursor
210
- cursor += len(raw_bytes)
211
- raw = raw_bytes.decode("utf-8", errors="replace")
212
- line_count += 1
213
- try:
214
- event = json.loads(raw)
215
- except Exception:
216
- continue
217
-
218
- timestamp = event.get("timestamp")
219
- event_type = event.get("type")
220
- payload = event.get("payload")
221
- if not isinstance(payload, dict):
222
- payload = {}
223
-
224
- if event_type == "event_msg":
225
- kind = payload.get("type")
226
- if kind in ("user_message", "user_input"):
227
- content = payload.get("message") or payload.get("text") or payload.get("content")
228
- notification = parse_subagent_notification(content)
229
- if notification:
230
- agent_label = notification["agentPath"][:8] or "Subagent"
231
- add_dialogue(
232
- "intermediate",
233
- f"Subagent {agent_label} · {notification['state']}",
234
- notification["text"],
235
- timestamp,
236
- category="subagent",
237
- agentPath=notification["agentPath"],
238
- )
239
- else:
240
- add_dialogue("user", "User", content, timestamp)
241
- elif kind == "agent_message":
242
- phase = payload.get("phase") or ""
243
- title = "Codex · 中间汇报" if phase == "commentary" else "Codex · 回复"
244
- add_dialogue(
245
- "assistant",
246
- title,
247
- payload.get("message") or payload.get("text"),
248
- timestamp,
249
- phase=phase,
250
- )
251
- elif kind in ("agent_reasoning", "reasoning"):
252
- summary = payload.get("summary") or payload.get("text") or payload.get("message")
253
- if summary:
254
- add_dialogue("reasoning", "Reasoning summary", summary, timestamp)
255
- else:
256
- hidden_reasoning_count += 1
257
- elif kind == "task_started":
258
- add_event("system", "Turn 开始", "", timestamp, turnId=payload.get("turn_id"))
259
- elif kind in ("task_complete", "turn_complete", "task_completed"):
260
- add_dialogue(
261
- "assistant",
262
- "Codex · 最终回复",
263
- payload.get("last_agent_message"),
264
- timestamp,
265
- phase="final_answer",
266
- )
267
- add_event("system", "Turn 完成", "", timestamp, turnId=payload.get("turn_id"))
268
- elif kind == "turn_aborted":
269
- add_event(
270
- "error",
271
- "Turn 中止",
272
- payload.get("reason") or "该轮已中止",
273
- timestamp,
274
- turnId=payload.get("turn_id"),
275
- )
276
- elif kind in ("error", "stream_error"):
277
- add_event(
278
- "error",
279
- "会话错误",
280
- payload.get("message") or payload.get("error") or payload,
281
- timestamp,
282
- )
283
- elif kind == "sub_agent_activity":
284
- detail = " · ".join(
285
- str(part)
286
- for part in (payload.get("agent_path"), payload.get("kind"))
287
- if part
288
- )
289
- add_event(
290
- "intermediate",
291
- "子代理活动",
292
- detail,
293
- timestamp,
294
- category="subagent",
295
- )
296
- elif kind == "context_compacted":
297
- add_event("system", "上下文已压缩", "", timestamp)
298
- elif kind == "patch_apply_end" and not payload.get("success", True):
299
- add_event(
300
- "error",
301
- "补丁应用失败",
302
- payload.get("stderr") or payload.get("stdout") or payload,
303
- timestamp,
304
- )
305
- continue
306
-
307
- if event_type == "compacted":
308
- add_event(
309
- "intermediate",
310
- "上下文压缩摘要",
311
- payload.get("message") or "",
312
- timestamp,
313
- category="reasoning",
314
- )
315
- continue
316
-
317
- if event_type != "response_item":
318
- continue
319
-
320
- kind = payload.get("type")
321
- role = payload.get("role")
322
- if kind == "message" and role == "user":
323
- content = payload.get("content")
324
- notification = parse_subagent_notification(content)
325
- if notification:
326
- agent_label = notification["agentPath"][:8] or "Subagent"
327
- add_dialogue(
328
- "intermediate",
329
- f"Subagent {agent_label} · {notification['state']}",
330
- notification["text"],
331
- timestamp,
332
- category="subagent",
333
- agentPath=notification["agentPath"],
334
- )
335
- else:
336
- add_dialogue("user", "User", content, timestamp)
337
- elif kind == "message" and role == "assistant":
338
- phase = payload.get("phase") or ""
339
- title = "Codex · 中间汇报" if phase == "commentary" else "Codex · 回复"
340
- add_dialogue(
341
- "assistant",
342
- title,
343
- payload.get("content"),
344
- timestamp,
345
- phase=phase,
346
- )
347
- elif kind == "agent_message":
348
- author = payload.get("author") or "Codex"
349
- recipient = payload.get("recipient")
350
- title = f"{author} → {recipient}" if recipient else str(author)
351
- add_dialogue(
352
- "intermediate",
353
- title,
354
- payload.get("content"),
355
- timestamp,
356
- category="subagent",
357
- )
358
- elif kind == "reasoning":
359
- summary = reasoning_summary(payload)
360
- if summary:
361
- add_dialogue("reasoning", "Reasoning summary", summary, timestamp)
362
- else:
363
- hidden_reasoning_count += 1
364
- elif kind in ("function_call", "custom_tool_call"):
365
- name = payload.get("name") or "tool"
366
- raw_input = payload.get("arguments")
367
- if raw_input in (None, ""):
368
- raw_input = payload.get("input")
369
- command = command_from_call(name, raw_input)
370
- event_kind = "command" if command else "tool"
371
- record = add_event(
372
- event_kind,
373
- f"{'命令' if command else '工具'} · {name}",
374
- call_input(payload),
375
- timestamp,
376
- toolName=name,
377
- command=clean_text(command, MAX_TOOL_TEXT),
378
- status=payload.get("status") or "started",
379
- )
380
- call_id = payload.get("call_id") or payload.get("id")
381
- if call_id:
382
- call_events[str(call_id)] = record
383
- elif kind in ("function_call_output", "custom_tool_call_output"):
384
- call_id = payload.get("call_id") or payload.get("id")
385
- output = clean_text(payload.get("output"), MAX_TOOL_TEXT)
386
- record = call_events.get(str(call_id)) if call_id else None
387
- if record is not None:
388
- record["output"] = output
389
- record["status"] = "completed"
390
- else:
391
- add_event(
392
- "tool",
393
- "工具输出",
394
- "",
395
- timestamp,
396
- output=output,
397
- status="completed",
398
- )
399
-
400
- tool_positions = [
401
- index for index, event in enumerate(events)
402
- if event["kind"] in ("command", "tool")
403
- ]
404
- omitted_tool_events = max(0, len(tool_positions) - MAX_TOOL_EVENTS)
405
- if omitted_tool_events:
406
- keep_tool_positions = set(tool_positions[-MAX_TOOL_EVENTS:])
407
- events = [
408
- event for index, event in enumerate(events)
409
- if event["kind"] not in ("command", "tool") or index in keep_tool_positions
410
- ]
411
-
412
- dialogue_positions = [
413
- index for index, event in enumerate(events)
414
- if event["category"] == "dialogue"
415
- ]
416
- if dialogue_positions:
417
- selected_positions = dialogue_positions[-page_limit:]
418
- first_source = events[selected_positions[0]]["_sourceByte"]
419
- if dialogue_only:
420
- page_events = [
421
- event for event in events
422
- if event["category"] == "dialogue"
423
- and event["_sourceByte"] >= first_source
424
- ]
425
- else:
426
- page_events = [
427
- event for event in events if event["_sourceByte"] >= first_source
428
- ]
429
- elif events and not dialogue_only:
430
- page_start = max(0, len(events) - page_limit)
431
- first_source = events[page_start]["_sourceByte"]
432
- page_events = [event for event in events if event["_sourceByte"] >= first_source]
433
- else:
434
- first_source = scan_start
435
- page_events = []
436
- has_more = scan_start > 0 or any(
437
- event["_sourceByte"] < first_source
438
- and (not dialogue_only or event["category"] == "dialogue")
439
- for event in events
440
- )
441
- next_before = first_source if has_more and page_events else None
442
-
443
- counts = {}
444
- for event in page_events:
445
- counts[event["kind"]] = counts.get(event["kind"], 0) + 1
446
- event.pop("_sourceByte", None)
447
-
448
- print(json.dumps({
449
- "path": path,
450
- "totalLines": line_count,
451
- "totalBytes": file_size,
452
- "scannedBytes": scan_end - scan_start,
453
- "events": page_events,
454
- "counts": counts,
455
- "toolEventCount": sum(
456
- 1 for event in page_events if event["kind"] in ("command", "tool")
457
- ),
458
- "omittedToolEvents": omitted_tool_events,
459
- "hiddenReasoningCount": hidden_reasoning_count,
460
- "pageSize": page_limit,
461
- "hasMore": has_more,
462
- "nextBefore": next_before,
463
- }, ensure_ascii=False, separators=(",", ":")))
2
+ export const DIALOGUE_PROBE = String.raw`
3
+ import json
4
+ import os
5
+ import sys
6
+
7
+ MAX_TOOL_EVENTS = 300
8
+ MAX_TOOL_TEXT = 6000
9
+ MAX_DIALOGUE_TEXT = 200000
10
+
11
+ path = os.path.realpath(sys.argv[1])
12
+ page_limit = max(1, min(100, int(sys.argv[2]) if len(sys.argv) > 2 else 10))
13
+ dialogue_only = len(sys.argv) > 4 and sys.argv[4] == "dialogue-only"
14
+ file_size = os.path.getsize(path)
15
+ before_byte = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else file_size
16
+ scan_end = max(0, min(file_size, before_byte))
17
+ scan_start = max(0, scan_end - (8000000 if dialogue_only else 2000000))
18
+ events = []
19
+ call_events = {}
20
+ last_dialogue_line = {}
21
+ event_ordinals = {}
22
+ hidden_reasoning_count = 0
23
+ tool_event_count = 0
24
+ line_count = 0
25
+ current_byte = scan_start
26
+
27
+ def readable_text(value):
28
+ if isinstance(value, str):
29
+ return value
30
+ if isinstance(value, list):
31
+ parts = []
32
+ for item in value:
33
+ if isinstance(item, str):
34
+ parts.append(item)
35
+ continue
36
+ if not isinstance(item, dict):
37
+ continue
38
+ if item.get("type") == "encrypted_content":
39
+ continue
40
+ for key in ("text", "content", "output"):
41
+ candidate = item.get(key)
42
+ if isinstance(candidate, str):
43
+ parts.append(candidate)
44
+ break
45
+ return "\n".join(parts)
46
+ if isinstance(value, dict):
47
+ for key in ("text", "content", "output", "message"):
48
+ candidate = value.get(key)
49
+ if isinstance(candidate, str):
50
+ return candidate
51
+ return json.dumps(value, ensure_ascii=False)
52
+ if value is None:
53
+ return ""
54
+ return str(value)
55
+
56
+ def clean_text(value, limit):
57
+ text = readable_text(value).replace("\x00", "")
58
+ if len(text) <= limit:
59
+ return text
60
+ omitted = len(text) - limit
61
+ return text[:limit] + f"\n\n… [已压缩 {omitted} 个字符]"
62
+
63
+ def parse_subagent_notification(value):
64
+ text = readable_text(value).strip()
65
+ markers = ("<subagent_notification>", "{subagent_notification}")
66
+ marker = next((item for item in markers if text.startswith(item)), None)
67
+ if not marker:
68
+ return None
69
+ encoded = text[len(marker):].strip()
70
+ try:
71
+ notification, _ = json.JSONDecoder().raw_decode(encoded)
72
+ except Exception:
73
+ return None
74
+ if not isinstance(notification, dict):
75
+ return None
76
+ status = notification.get("status")
77
+ if not isinstance(status, dict):
78
+ return None
79
+ state = next(
80
+ (key for key in ("completed", "failed", "errored", "cancelled") if key in status),
81
+ "updated",
82
+ )
83
+ content = status.get(state)
84
+ if not isinstance(content, str):
85
+ content = json.dumps(content, ensure_ascii=False) if content is not None else ""
86
+ return {
87
+ "agentPath": str(notification.get("agent_path") or ""),
88
+ "state": state,
89
+ "text": content,
90
+ }
91
+
92
+ def is_context_message(value):
93
+ if not isinstance(value, str):
94
+ return True
95
+ stripped = value.lstrip()
96
+ return stripped.startswith((
97
+ "<environment_context>",
98
+ "<permissions",
99
+ "<INSTRUCTIONS>",
100
+ "<collaboration_mode>",
101
+ "<apps_instructions>",
102
+ "<plugins_instructions>",
103
+ "<skills_instructions>",
104
+ "<recommended_plugins>",
105
+ "<in-app-browser-context",
106
+ "# AGENTS.md instructions",
107
+ "A previous agent produced",
108
+ "You are Codex",
109
+ ))
110
+
111
+ def add_event(kind, title, text="", timestamp=None, **extra):
112
+ global tool_event_count
113
+ category = extra.pop("category", None)
114
+ if category is None:
115
+ if kind == "user":
116
+ category = "dialogue"
117
+ elif kind == "assistant":
118
+ category = "reasoning" if extra.get("phase") == "commentary" else "dialogue"
119
+ elif kind in ("reasoning", "intermediate"):
120
+ category = "reasoning"
121
+ else:
122
+ category = "operations"
123
+ text_limit = MAX_TOOL_TEXT if kind in ("command", "tool") else MAX_DIALOGUE_TEXT
124
+ ordinal = event_ordinals.get(current_byte, 0)
125
+ event_ordinals[current_byte] = ordinal + 1
126
+ record = {
127
+ "id": f"byte-{current_byte}-{ordinal}",
128
+ "kind": kind,
129
+ "category": category,
130
+ "title": title,
131
+ "text": clean_text(text, text_limit),
132
+ "timestamp": timestamp,
133
+ "_sourceByte": current_byte,
134
+ }
135
+ for key, value in extra.items():
136
+ if value not in (None, ""):
137
+ record[key] = value
138
+ events.append(record)
139
+ if kind in ("command", "tool"):
140
+ tool_event_count += 1
141
+ return record
142
+
143
+ def add_dialogue(kind, title, text, timestamp=None, **extra):
144
+ candidate = clean_text(text, MAX_DIALOGUE_TEXT)
145
+ if not candidate or (kind == "user" and is_context_message(candidate)):
146
+ return None
147
+ signature = (kind, candidate)
148
+ previous_line = last_dialogue_line.get(signature)
149
+ if previous_line is not None and line_count - previous_line <= 4:
150
+ return None
151
+ last_dialogue_line[signature] = line_count
152
+ return add_event(kind, title, candidate, timestamp, **extra)
153
+
154
+ def reasoning_summary(payload):
155
+ summary = payload.get("summary")
156
+ if not isinstance(summary, list):
157
+ return readable_text(summary)
158
+ parts = []
159
+ for item in summary:
160
+ if isinstance(item, str):
161
+ parts.append(item)
162
+ elif isinstance(item, dict):
163
+ text = item.get("text") or item.get("summary_text")
164
+ if isinstance(text, str):
165
+ parts.append(text)
166
+ return "\n\n".join(parts)
167
+
168
+ def call_input(payload):
169
+ value = payload.get("arguments")
170
+ if value in (None, ""):
171
+ value = payload.get("input")
172
+ return readable_text(value)
173
+
174
+ def command_from_call(name, value):
175
+ lowered = str(name).lower()
176
+ parsed = None
177
+ if isinstance(value, str):
178
+ try:
179
+ parsed = json.loads(value)
180
+ except Exception:
181
+ parsed = None
182
+ elif isinstance(value, dict):
183
+ parsed = value
184
+ if isinstance(parsed, dict):
185
+ command = parsed.get("cmd") or parsed.get("command")
186
+ if isinstance(command, list):
187
+ command = " ".join(str(part) for part in command)
188
+ if isinstance(command, str):
189
+ return command
190
+ if any(token in lowered for token in ("exec", "shell", "terminal", "write_stdin")):
191
+ return readable_text(value)
192
+ return ""
193
+
194
+ with open(path, "rb") as handle:
195
+ handle.seek(scan_start)
196
+ window = handle.read(scan_end - scan_start)
197
+
198
+ if scan_start > 0:
199
+ boundary = window.find(b"\n")
200
+ if boundary < 0:
201
+ window = b""
202
+ scan_start = scan_end
203
+ else:
204
+ scan_start += boundary + 1
205
+ window = window[boundary + 1:]
206
+
207
+ cursor = scan_start
208
+ for raw_bytes in window.splitlines(keepends=True):
209
+ current_byte = cursor
210
+ cursor += len(raw_bytes)
211
+ raw = raw_bytes.decode("utf-8", errors="replace")
212
+ line_count += 1
213
+ try:
214
+ event = json.loads(raw)
215
+ except Exception:
216
+ continue
217
+
218
+ timestamp = event.get("timestamp")
219
+ event_type = event.get("type")
220
+ payload = event.get("payload")
221
+ if not isinstance(payload, dict):
222
+ payload = {}
223
+
224
+ if event_type == "event_msg":
225
+ kind = payload.get("type")
226
+ if kind in ("user_message", "user_input"):
227
+ content = payload.get("message") or payload.get("text") or payload.get("content")
228
+ notification = parse_subagent_notification(content)
229
+ if notification:
230
+ agent_label = notification["agentPath"][:8] or "Subagent"
231
+ add_dialogue(
232
+ "intermediate",
233
+ f"Subagent {agent_label} · {notification['state']}",
234
+ notification["text"],
235
+ timestamp,
236
+ category="subagent",
237
+ agentPath=notification["agentPath"],
238
+ )
239
+ else:
240
+ add_dialogue("user", "User", content, timestamp)
241
+ elif kind == "agent_message":
242
+ phase = payload.get("phase") or ""
243
+ title = "Codex · 中间汇报" if phase == "commentary" else "Codex · 回复"
244
+ add_dialogue(
245
+ "assistant",
246
+ title,
247
+ payload.get("message") or payload.get("text"),
248
+ timestamp,
249
+ phase=phase,
250
+ )
251
+ elif kind in ("agent_reasoning", "reasoning"):
252
+ summary = payload.get("summary") or payload.get("text") or payload.get("message")
253
+ if summary:
254
+ add_dialogue("reasoning", "Reasoning summary", summary, timestamp)
255
+ else:
256
+ hidden_reasoning_count += 1
257
+ elif kind == "task_started":
258
+ add_event("system", "Turn 开始", "", timestamp, turnId=payload.get("turn_id"))
259
+ elif kind in ("task_complete", "turn_complete", "task_completed"):
260
+ add_dialogue(
261
+ "assistant",
262
+ "Codex · 最终回复",
263
+ payload.get("last_agent_message"),
264
+ timestamp,
265
+ phase="final_answer",
266
+ )
267
+ add_event("system", "Turn 完成", "", timestamp, turnId=payload.get("turn_id"))
268
+ elif kind == "turn_aborted":
269
+ add_event(
270
+ "error",
271
+ "Turn 中止",
272
+ payload.get("reason") or "该轮已中止",
273
+ timestamp,
274
+ turnId=payload.get("turn_id"),
275
+ )
276
+ elif kind in ("error", "stream_error"):
277
+ add_event(
278
+ "error",
279
+ "会话错误",
280
+ payload.get("message") or payload.get("error") or payload,
281
+ timestamp,
282
+ )
283
+ elif kind == "sub_agent_activity":
284
+ detail = " · ".join(
285
+ str(part)
286
+ for part in (payload.get("agent_path"), payload.get("kind"))
287
+ if part
288
+ )
289
+ add_event(
290
+ "intermediate",
291
+ "子代理活动",
292
+ detail,
293
+ timestamp,
294
+ category="subagent",
295
+ )
296
+ elif kind == "context_compacted":
297
+ add_event("system", "上下文已压缩", "", timestamp)
298
+ elif kind == "patch_apply_end" and not payload.get("success", True):
299
+ add_event(
300
+ "error",
301
+ "补丁应用失败",
302
+ payload.get("stderr") or payload.get("stdout") or payload,
303
+ timestamp,
304
+ )
305
+ continue
306
+
307
+ if event_type == "compacted":
308
+ add_event(
309
+ "intermediate",
310
+ "上下文压缩摘要",
311
+ payload.get("message") or "",
312
+ timestamp,
313
+ category="reasoning",
314
+ )
315
+ continue
316
+
317
+ if event_type != "response_item":
318
+ continue
319
+
320
+ kind = payload.get("type")
321
+ role = payload.get("role")
322
+ if kind == "message" and role == "user":
323
+ content = payload.get("content")
324
+ notification = parse_subagent_notification(content)
325
+ if notification:
326
+ agent_label = notification["agentPath"][:8] or "Subagent"
327
+ add_dialogue(
328
+ "intermediate",
329
+ f"Subagent {agent_label} · {notification['state']}",
330
+ notification["text"],
331
+ timestamp,
332
+ category="subagent",
333
+ agentPath=notification["agentPath"],
334
+ )
335
+ else:
336
+ add_dialogue("user", "User", content, timestamp)
337
+ elif kind == "message" and role == "assistant":
338
+ phase = payload.get("phase") or ""
339
+ title = "Codex · 中间汇报" if phase == "commentary" else "Codex · 回复"
340
+ add_dialogue(
341
+ "assistant",
342
+ title,
343
+ payload.get("content"),
344
+ timestamp,
345
+ phase=phase,
346
+ )
347
+ elif kind == "agent_message":
348
+ author = payload.get("author") or "Codex"
349
+ recipient = payload.get("recipient")
350
+ title = f"{author} → {recipient}" if recipient else str(author)
351
+ add_dialogue(
352
+ "intermediate",
353
+ title,
354
+ payload.get("content"),
355
+ timestamp,
356
+ category="subagent",
357
+ )
358
+ elif kind == "reasoning":
359
+ summary = reasoning_summary(payload)
360
+ if summary:
361
+ add_dialogue("reasoning", "Reasoning summary", summary, timestamp)
362
+ else:
363
+ hidden_reasoning_count += 1
364
+ elif kind in ("function_call", "custom_tool_call"):
365
+ name = payload.get("name") or "tool"
366
+ raw_input = payload.get("arguments")
367
+ if raw_input in (None, ""):
368
+ raw_input = payload.get("input")
369
+ command = command_from_call(name, raw_input)
370
+ event_kind = "command" if command else "tool"
371
+ record = add_event(
372
+ event_kind,
373
+ f"{'命令' if command else '工具'} · {name}",
374
+ call_input(payload),
375
+ timestamp,
376
+ toolName=name,
377
+ command=clean_text(command, MAX_TOOL_TEXT),
378
+ status=payload.get("status") or "started",
379
+ )
380
+ call_id = payload.get("call_id") or payload.get("id")
381
+ if call_id:
382
+ call_events[str(call_id)] = record
383
+ elif kind in ("function_call_output", "custom_tool_call_output"):
384
+ call_id = payload.get("call_id") or payload.get("id")
385
+ output = clean_text(payload.get("output"), MAX_TOOL_TEXT)
386
+ record = call_events.get(str(call_id)) if call_id else None
387
+ if record is not None:
388
+ record["output"] = output
389
+ record["status"] = "completed"
390
+ else:
391
+ add_event(
392
+ "tool",
393
+ "工具输出",
394
+ "",
395
+ timestamp,
396
+ output=output,
397
+ status="completed",
398
+ )
399
+
400
+ tool_positions = [
401
+ index for index, event in enumerate(events)
402
+ if event["kind"] in ("command", "tool")
403
+ ]
404
+ omitted_tool_events = max(0, len(tool_positions) - MAX_TOOL_EVENTS)
405
+ if omitted_tool_events:
406
+ keep_tool_positions = set(tool_positions[-MAX_TOOL_EVENTS:])
407
+ events = [
408
+ event for index, event in enumerate(events)
409
+ if event["kind"] not in ("command", "tool") or index in keep_tool_positions
410
+ ]
411
+
412
+ dialogue_positions = [
413
+ index for index, event in enumerate(events)
414
+ if event["category"] == "dialogue"
415
+ ]
416
+ if dialogue_positions:
417
+ selected_positions = dialogue_positions[-page_limit:]
418
+ first_source = events[selected_positions[0]]["_sourceByte"]
419
+ if dialogue_only:
420
+ page_events = [
421
+ event for event in events
422
+ if event["category"] == "dialogue"
423
+ and event["_sourceByte"] >= first_source
424
+ ]
425
+ else:
426
+ page_events = [
427
+ event for event in events if event["_sourceByte"] >= first_source
428
+ ]
429
+ elif events and not dialogue_only:
430
+ page_start = max(0, len(events) - page_limit)
431
+ first_source = events[page_start]["_sourceByte"]
432
+ page_events = [event for event in events if event["_sourceByte"] >= first_source]
433
+ else:
434
+ first_source = scan_start
435
+ page_events = []
436
+ has_more = scan_start > 0 or any(
437
+ event["_sourceByte"] < first_source
438
+ and (not dialogue_only or event["category"] == "dialogue")
439
+ for event in events
440
+ )
441
+ next_before = first_source if has_more and page_events else None
442
+
443
+ counts = {}
444
+ for event in page_events:
445
+ counts[event["kind"]] = counts.get(event["kind"], 0) + 1
446
+ event.pop("_sourceByte", None)
447
+
448
+ print(json.dumps({
449
+ "path": path,
450
+ "totalLines": line_count,
451
+ "totalBytes": file_size,
452
+ "scannedBytes": scan_end - scan_start,
453
+ "events": page_events,
454
+ "counts": counts,
455
+ "toolEventCount": sum(
456
+ 1 for event in page_events if event["kind"] in ("command", "tool")
457
+ ),
458
+ "omittedToolEvents": omitted_tool_events,
459
+ "hiddenReasoningCount": hidden_reasoning_count,
460
+ "pageSize": page_limit,
461
+ "hasMore": has_more,
462
+ "nextBefore": next_before,
463
+ }, ensure_ascii=False, separators=(",", ":")))
464
464
  `;