execweave 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. execweave/__init__.py +3 -0
  2. execweave/__main__.py +5 -0
  3. execweave/_conversation_records_core.py +902 -0
  4. execweave/_dashboard_shell_base.py +148 -0
  5. execweave/_http_proxy_base.py +565 -0
  6. execweave/_http_proxy_bounded.py +560 -0
  7. execweave/_http_proxy_stage.py +509 -0
  8. execweave/acceptance_output.py +19 -0
  9. execweave/agent_bootstrap.py +395 -0
  10. execweave/agent_topology.py +313 -0
  11. execweave/agent_trace.py +1162 -0
  12. execweave/agy_preview_sanitize.py +102 -0
  13. execweave/analysis.py +427 -0
  14. execweave/anthropic.py +228 -0
  15. execweave/anthropic_cli.py +171 -0
  16. execweave/anthropic_full_fidelity.py +385 -0
  17. execweave/antigravity_adapter.py +112 -0
  18. execweave/antigravity_adapter_base.py +479 -0
  19. execweave/antigravity_full_fidelity.py +656 -0
  20. execweave/antigravity_full_fidelity_base.py +172 -0
  21. execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
  22. execweave/antigravity_hook_cli.py +209 -0
  23. execweave/antigravity_record.py +96 -0
  24. execweave/antigravity_subagent_linkage.py +449 -0
  25. execweave/antigravity_trace_capability.py +39 -0
  26. execweave/auto_specialized.py +547 -0
  27. execweave/backends.py +102 -0
  28. execweave/benchmark.py +80 -0
  29. execweave/claude_adapter.py +517 -0
  30. execweave/claude_child_transcript.py +314 -0
  31. execweave/claude_delegation.py +136 -0
  32. execweave/claude_full_fidelity.py +396 -0
  33. execweave/claude_hook_cli.py +209 -0
  34. execweave/claude_hook_contract.py +943 -0
  35. execweave/claude_model_observer.py +353 -0
  36. execweave/claude_record.py +106 -0
  37. execweave/cli.py +629 -0
  38. execweave/codex_adapter.py +455 -0
  39. execweave/codex_conversation.py +621 -0
  40. execweave/codex_full_fidelity.py +287 -0
  41. execweave/codex_hook_cli.py +301 -0
  42. execweave/codex_hook_entry.py +207 -0
  43. execweave/codex_hook_lifecycle.py +363 -0
  44. execweave/codex_message_diagnostics.py +322 -0
  45. execweave/codex_message_transport_diagnostics.py +399 -0
  46. execweave/codex_record.py +199 -0
  47. execweave/codex_rollout_structures.py +402 -0
  48. execweave/codex_rollout_trace.py +56 -0
  49. execweave/codex_rollout_trace_base.py +1509 -0
  50. execweave/collector.py +768 -0
  51. execweave/command.py +157 -0
  52. execweave/command_privacy.py +20 -0
  53. execweave/content_evidence.py +101 -0
  54. execweave/content_integrity.py +289 -0
  55. execweave/content_store.py +273 -0
  56. execweave/controlled_checks.py +561 -0
  57. execweave/conversation_archive.py +338 -0
  58. execweave/conversation_message_identity.py +264 -0
  59. execweave/conversation_preview.py +66 -0
  60. execweave/conversation_preview_antigravity.py +32 -0
  61. execweave/conversation_preview_claude.py +31 -0
  62. execweave/conversation_preview_codex.py +107 -0
  63. execweave/conversation_preview_common.py +180 -0
  64. execweave/conversation_preview_generic.py +188 -0
  65. execweave/conversation_preview_lines.py +133 -0
  66. execweave/conversation_preview_transcript.py +121 -0
  67. execweave/conversation_records.py +349 -0
  68. execweave/conversation_records_antigravity.py +370 -0
  69. execweave/conversation_records_codex.py +83 -0
  70. execweave/conversation_records_common.py +17 -0
  71. execweave/conversation_records_ollama.py +39 -0
  72. execweave/correlation.py +818 -0
  73. execweave/cursor_adapter.py +349 -0
  74. execweave/cursor_delegation.py +87 -0
  75. execweave/cursor_delegation_base.py +220 -0
  76. execweave/cursor_full_fidelity.py +489 -0
  77. execweave/cursor_hook_cli.py +195 -0
  78. execweave/cursor_hook_contract.py +439 -0
  79. execweave/cursor_lifecycle.py +159 -0
  80. execweave/cursor_record.py +96 -0
  81. execweave/dashboard_shell.py +283 -0
  82. execweave/delivery_status.py +94 -0
  83. execweave/entry.py +98 -0
  84. execweave/evidence_availability.py +113 -0
  85. execweave/evidence_grade.py +166 -0
  86. execweave/fidelity.py +304 -0
  87. execweave/filesystem.py +327 -0
  88. execweave/finalization.py +92 -0
  89. execweave/focus.py +118 -0
  90. execweave/framework_adapters/__init__.py +34 -0
  91. execweave/framework_adapters/autogen.py +398 -0
  92. execweave/framework_adapters/base.py +580 -0
  93. execweave/framework_adapters/camel.py +270 -0
  94. execweave/framework_adapters/camel_channel.py +71 -0
  95. execweave/framework_adapters/metagpt.py +315 -0
  96. execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
  97. execweave/framework_adapters/metagpt_recording.py +342 -0
  98. execweave/framework_adapters/registry.py +90 -0
  99. execweave/graph.py +590 -0
  100. execweave/graph_ops.py +472 -0
  101. execweave/hook_command.py +32 -0
  102. execweave/hook_delivery.py +32 -0
  103. execweave/hook_input.py +16 -0
  104. execweave/http_proxy.py +187 -0
  105. execweave/http_proxy_cli.py +84 -0
  106. execweave/inference_gateway.py +476 -0
  107. execweave/inference_gateway_cli.py +211 -0
  108. execweave/inference_gateway_full_fidelity.py +613 -0
  109. execweave/inference_identity.py +76 -0
  110. execweave/inference_identity_cli.py +60 -0
  111. execweave/integrity.py +235 -0
  112. execweave/integrity_cli.py +55 -0
  113. execweave/investigation_index.py +445 -0
  114. execweave/litellm_callback.py +211 -0
  115. execweave/litellm_callback_cli.py +42 -0
  116. execweave/live.py +445 -0
  117. execweave/live_core.py +972 -0
  118. execweave/live_view.py +109 -0
  119. execweave/live_view_extra_style.py +11 -0
  120. execweave/live_view_markup.py +29 -0
  121. execweave/live_view_process_layout.py +650 -0
  122. execweave/live_view_readability.py +502 -0
  123. execweave/live_view_script_a.py +59 -0
  124. execweave/live_view_script_b.py +97 -0
  125. execweave/live_view_script_c.py +59 -0
  126. execweave/live_view_script_d.py +40 -0
  127. execweave/live_view_style.py +34 -0
  128. execweave/model_runtime.py +560 -0
  129. execweave/model_runtime_cli.py +265 -0
  130. execweave/model_runtime_full_fidelity.py +519 -0
  131. execweave/observation.py +53 -0
  132. execweave/observation_demo.py +69 -0
  133. execweave/openai_agents.py +267 -0
  134. execweave/openai_agents_sdk.py +453 -0
  135. execweave/openai_compatible.py +239 -0
  136. execweave/openai_compatible_cli.py +189 -0
  137. execweave/openai_compatible_full_fidelity.py +438 -0
  138. execweave/opencode_adapter.py +325 -0
  139. execweave/opencode_event_contract.py +734 -0
  140. execweave/opencode_full_fidelity.py +198 -0
  141. execweave/opencode_hook_cli.py +119 -0
  142. execweave/opencode_plugin_cli.py +150 -0
  143. execweave/opencode_record.py +96 -0
  144. execweave/opencode_task_linkage.py +225 -0
  145. execweave/overhead_benchmark.py +440 -0
  146. execweave/privacy.py +84 -0
  147. execweave/private_io.py +465 -0
  148. execweave/provider_capability.py +578 -0
  149. execweave/provider_lifecycle.py +282 -0
  150. execweave/provider_record.py +290 -0
  151. execweave/reader_identity.py +13 -0
  152. execweave/redacted_archive.py +906 -0
  153. execweave/risk.py +106 -0
  154. execweave/rule_pack.py +359 -0
  155. execweave/rule_pack_cli.py +57 -0
  156. execweave/run_assessment.py +200 -0
  157. execweave/runtime_endpoint_availability.py +44 -0
  158. execweave/scalability_benchmark.py +195 -0
  159. execweave/schema.py +62 -0
  160. execweave/scope.py +85 -0
  161. execweave/semantic.py +453 -0
  162. execweave/session_summary.py +159 -0
  163. execweave/sink.py +71 -0
  164. execweave/strace_backend.py +927 -0
  165. execweave/stream_assembly.py +363 -0
  166. execweave/task_artifacts.py +192 -0
  167. execweave/task_validation.py +317 -0
  168. execweave/theme.py +40 -0
  169. execweave/top.py +599 -0
  170. execweave/top_cli.py +150 -0
  171. execweave/validate.py +196 -0
  172. execweave/vendor/dagre.min.js +815 -0
  173. execweave/view_cli.py +49 -0
  174. execweave/viewer.py +474 -0
  175. execweave/viewer_agent_panel.py +630 -0
  176. execweave/viewer_agent_panel_antigravity.py +31 -0
  177. execweave/viewer_agent_panel_claude.py +9 -0
  178. execweave/viewer_agent_panel_codex.py +50 -0
  179. execweave/viewer_agent_panel_cursor.py +9 -0
  180. execweave/viewer_agent_panel_default.py +79 -0
  181. execweave/viewer_agent_panel_ollama.py +20 -0
  182. execweave/viewer_agent_panel_opencode.py +9 -0
  183. execweave/viewer_agent_panel_registry.py +20 -0
  184. execweave/viewer_archive_verifier.py +178 -0
  185. execweave/viewer_background_files.py +86 -0
  186. execweave/viewer_content_browser.py +307 -0
  187. execweave/viewer_content_health.py +208 -0
  188. execweave/viewer_content_inspector.py +309 -0
  189. execweave/viewer_controlled_checks.py +258 -0
  190. execweave/viewer_conversation_sync.py +115 -0
  191. execweave/viewer_dashboard_clean.py +405 -0
  192. execweave/viewer_dashboard_focus.py +127 -0
  193. execweave/viewer_dashboard_hardening.py +264 -0
  194. execweave/viewer_dashboard_hardening_v2.py +62 -0
  195. execweave/viewer_dashboard_projection.py +261 -0
  196. execweave/viewer_delivery_status.py +155 -0
  197. execweave/viewer_edge_decross.py +117 -0
  198. execweave/viewer_execution_flow.py +611 -0
  199. execweave/viewer_execution_flow_provider_normalization.py +107 -0
  200. execweave/viewer_execution_flow_safety.py +349 -0
  201. execweave/viewer_external_endpoints.py +307 -0
  202. execweave/viewer_flow_canvas.py +1140 -0
  203. execweave/viewer_flow_layout.py +922 -0
  204. execweave/viewer_fold_state.py +31 -0
  205. execweave/viewer_framework_flow.py +68 -0
  206. execweave/viewer_framework_model_output.py +133 -0
  207. execweave/viewer_gif.py +278 -0
  208. execweave/viewer_history_browser.py +225 -0
  209. execweave/viewer_investigation.py +268 -0
  210. execweave/viewer_layout_geometry.py +192 -0
  211. execweave/viewer_layout_v2.py +429 -0
  212. execweave/viewer_layout_v2_detached.py +25 -0
  213. execweave/viewer_limits.py +93 -0
  214. execweave/viewer_live_layout.py +61 -0
  215. execweave/viewer_message_handoffs.py +114 -0
  216. execweave/viewer_projection.py +488 -0
  217. execweave/viewer_projection_base.py +522 -0
  218. execweave/viewer_projection_bridges.py +214 -0
  219. execweave/viewer_recorded_sources.py +146 -0
  220. execweave/viewer_run_assessment.py +274 -0
  221. execweave/viewer_run_guide.py +175 -0
  222. execweave/viewer_runtime_evidence.py +258 -0
  223. execweave/viewer_semantic_projection.py +641 -0
  224. execweave/viewer_session_flow.py +491 -0
  225. execweave/viewer_structure_share.py +132 -0
  226. execweave/viewer_task_validation.py +241 -0
  227. execweave/viewer_tool_mirror_identity.py +75 -0
  228. execweave/viewer_workflow_mode.py +127 -0
  229. execweave/workflow.py +183 -0
  230. execweave-1.0.0.dist-info/METADATA +462 -0
  231. execweave-1.0.0.dist-info/RECORD +234 -0
  232. execweave-1.0.0.dist-info/WHEEL +4 -0
  233. execweave-1.0.0.dist-info/entry_points.txt +30 -0
  234. execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
@@ -0,0 +1,621 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Any
7
+ from .agent_topology import (
8
+ EVIDENCE_CROSS_AGENT_ROUTING,
9
+ PATH_EXECWEAVE_DERIVED,
10
+ PATH_PROVIDER_DECLARED,
11
+ THREAD_ID_EXECWEAVE_DERIVED,
12
+ THREAD_ID_PROVIDER_NATIVE,
13
+ )
14
+
15
+ _MAX_IDENTITY_SCAN_LINES = 64
16
+ _MAX_PREVIEW_MESSAGES = 80
17
+ _MAX_PREVIEW_TEXT_CHARS = 6000
18
+
19
+
20
+ def _canonical_absolute_path(value: object) -> Path | None:
21
+ if not isinstance(value, str) or not value:
22
+ return None
23
+ try:
24
+ path = Path(value).expanduser()
25
+ if not path.is_absolute():
26
+ return None
27
+ return path.resolve(strict=False)
28
+ except (OSError, RuntimeError, ValueError):
29
+ return None
30
+
31
+
32
+ def _codex_sessions_root() -> Path:
33
+ configured = os.environ.get("CODEX_HOME")
34
+ home = Path(configured).expanduser() if configured else Path.home() / ".codex"
35
+ return (home / "sessions").resolve(strict=False)
36
+
37
+
38
+ def _inside_codex_sessions(path: Path) -> bool:
39
+ try:
40
+ path.relative_to(_codex_sessions_root())
41
+ except ValueError:
42
+ return False
43
+ return True
44
+
45
+
46
+ def _history_base_end_ordinal(payload: dict[str, Any]) -> int:
47
+ history_base = payload.get("history_base")
48
+ if not isinstance(history_base, dict):
49
+ return 0
50
+ value = history_base.get("end_ordinal_exclusive")
51
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
52
+
53
+
54
+ def _session_meta_identity(payload: dict[str, Any]) -> dict[str, Any] | None:
55
+ thread_id = payload.get("id") or payload.get("session_id")
56
+ if not isinstance(thread_id, str) or not thread_id:
57
+ return None
58
+ source = payload.get("source")
59
+ spawn: dict[str, Any] = {}
60
+ if isinstance(source, dict):
61
+ subagent = source.get("subagent")
62
+ if isinstance(subagent, dict):
63
+ candidate = subagent.get("thread_spawn")
64
+ if isinstance(candidate, dict):
65
+ spawn = candidate
66
+ agent_path = payload.get("agent_path") or spawn.get("agent_path")
67
+ nickname = payload.get("agent_nickname") or spawn.get("agent_nickname")
68
+ parent_thread_id = payload.get("parent_thread_id") or spawn.get("parent_thread_id")
69
+ history_start = payload.get("subagent_history_start_ordinal")
70
+ return {
71
+ "thread_id": thread_id,
72
+ "parent_thread_id": parent_thread_id if isinstance(parent_thread_id, str) else None,
73
+ "agent_path": agent_path if isinstance(agent_path, str) else None,
74
+ "agent_nickname": nickname if isinstance(nickname, str) else None,
75
+ "history_base_end_ordinal": _history_base_end_ordinal(payload),
76
+ "subagent_history_start_ordinal": (
77
+ history_start
78
+ if isinstance(history_start, int) and not isinstance(history_start, bool) and history_start >= 0
79
+ else None
80
+ ),
81
+ }
82
+
83
+
84
+ def _sanitize_path_leaf(value: str) -> str | None:
85
+ leaf = " ".join(value.replace("\\", "-").replace("/", "-").split())
86
+ return leaf or None
87
+
88
+
89
+ def _resolved_agent_path(identity: dict[str, Any]) -> tuple[str | None, str]:
90
+ """Prefer Codex's own path; otherwise /root/<nickname> when a parent exists.
91
+
92
+ Windows Codex sessions in the field have been observed to publish nickname and
93
+ parent_thread_id without agent_path. The dashboard child-round splitter addresses
94
+ messages by recipient === path, so a missing path drops every later fold.
95
+ """
96
+ declared = identity.get("agent_path")
97
+ if isinstance(declared, str) and declared:
98
+ return declared, PATH_PROVIDER_DECLARED
99
+ if identity.get("parent_thread_id") is None:
100
+ return "/root", PATH_EXECWEAVE_DERIVED
101
+ nickname = identity.get("agent_nickname")
102
+ if not isinstance(nickname, str):
103
+ return None, PATH_EXECWEAVE_DERIVED
104
+ leaf = _sanitize_path_leaf(nickname)
105
+ if leaf is None:
106
+ return None, PATH_EXECWEAVE_DERIVED
107
+ return f"/root/{leaf}", PATH_EXECWEAVE_DERIVED
108
+
109
+
110
+ def codex_rollout_identity(path: str | Path) -> dict[str, Any] | None:
111
+ """Read only leading Codex session metadata needed for exact thread identity."""
112
+ source = Path(path).expanduser().resolve(strict=False)
113
+ try:
114
+ with source.open("r", encoding="utf-8") as handle:
115
+ for index, line in enumerate(handle):
116
+ if index >= _MAX_IDENTITY_SCAN_LINES:
117
+ break
118
+ if not line.strip():
119
+ continue
120
+ try:
121
+ record = json.loads(line)
122
+ except json.JSONDecodeError:
123
+ return None
124
+ if record.get("type") != "session_meta":
125
+ continue
126
+ payload = record.get("payload")
127
+ return _session_meta_identity(payload) if isinstance(payload, dict) else None
128
+ except (OSError, RuntimeError, UnicodeError):
129
+ return None
130
+ return None
131
+
132
+
133
+ def _transcript_candidate(payload: dict[str, Any]) -> tuple[Path, str, str] | None:
134
+ """Select the rollout a Codex hook payload actually describes.
135
+
136
+ Codex reports a subagent stop with two different rollouts on one payload:
137
+ ``agent_transcript_path`` is the spawned child rollout while ``transcript_path``
138
+ keeps pointing at the parent session rollout. Selecting the parent for a child
139
+ stop silently drops every subagent conversation, so pick by observed agent id.
140
+ """
141
+ agent_id = payload.get("agent_id")
142
+ if isinstance(agent_id, str) and agent_id:
143
+ for field in ("agent_transcript_path", "transcript_path"):
144
+ path = _canonical_absolute_path(payload.get(field))
145
+ if path is not None and path.stem.endswith(f"-{agent_id}"):
146
+ return path, agent_id, field
147
+ return None
148
+ session_id = payload.get("session_id")
149
+ if not isinstance(session_id, str) or not session_id:
150
+ return None
151
+ path = _canonical_absolute_path(payload.get("transcript_path"))
152
+ if path is None or not path.stem.endswith(f"-{session_id}"):
153
+ return None
154
+ return path, session_id, "transcript_path"
155
+
156
+
157
+ def codex_transcript_observed_field(payload: dict[str, Any]) -> str | None:
158
+ """Name the payload field a validated Codex rollout was actually observed on."""
159
+ candidate = _transcript_candidate(payload)
160
+ return candidate[2] if candidate is not None else None
161
+
162
+
163
+ def validated_codex_transcript(payload: dict[str, Any]) -> tuple[Path, dict[str, Any]] | None:
164
+ """Validate a hook-supplied rollout path before ExecWeave reads or copies it."""
165
+ candidate = _transcript_candidate(payload)
166
+ if candidate is None:
167
+ return None
168
+ path, expected, _field = candidate
169
+ if path.suffix.lower() != ".jsonl" or not path.name.startswith("rollout-"):
170
+ return None
171
+ if not _inside_codex_sessions(path) or not path.is_file():
172
+ return None
173
+ identity = codex_rollout_identity(path)
174
+ if identity is None or identity.get("thread_id") != expected:
175
+ return None
176
+ agent_id = payload.get("agent_id")
177
+ session_id = payload.get("session_id")
178
+ if isinstance(agent_id, str) and agent_id and isinstance(session_id, str) and session_id:
179
+ parent = identity.get("parent_thread_id")
180
+ if isinstance(parent, str) and parent and parent != session_id:
181
+ return None
182
+ return path, identity
183
+
184
+
185
+ def codex_rollout_identity_from_payload(payload: dict[str, Any]) -> dict[str, Any] | None:
186
+ validated = validated_codex_transcript(payload)
187
+ return validated[1] if validated is not None else None
188
+
189
+
190
+ def _content_text(content: object) -> str:
191
+ if not isinstance(content, list):
192
+ return ""
193
+ parts: list[str] = []
194
+ for part in content:
195
+ if not isinstance(part, dict) or part.get("type") not in {"input_text", "output_text", "Text"}:
196
+ continue
197
+ text = part.get("text")
198
+ if isinstance(text, str) and text:
199
+ parts.append(text)
200
+ return "\n".join(parts).strip()
201
+
202
+
203
+ def _trim_text(value: str) -> str:
204
+ if len(value) <= _MAX_PREVIEW_TEXT_CHARS:
205
+ return value
206
+ return value[: _MAX_PREVIEW_TEXT_CHARS - 1] + "…"
207
+
208
+
209
+ def _agent_message_header(text: str) -> dict[str, str]:
210
+ """Parse Codex routing headers only from an explicit Payload envelope.
211
+
212
+ Plain agent output is free-form text and may legitimately quote lines such as
213
+ ``Sender:`` or ``Task name:``. Those strings are routing metadata only when a
214
+ standalone ``Payload:`` line terminates a recognized header block.
215
+ """
216
+ lines = text.splitlines()
217
+ try:
218
+ payload_index = next(index for index, line in enumerate(lines) if line.strip() == "Payload:")
219
+ except StopIteration:
220
+ return {}
221
+ result: dict[str, str] = {}
222
+ for line in lines[:payload_index]:
223
+ key, separator, value = line.partition(":")
224
+ if not separator:
225
+ continue
226
+ normalized = key.strip().lower().replace(" ", "_")
227
+ if normalized in {"message_type", "task_name", "sender"} and value.strip():
228
+ result[normalized] = value.strip()
229
+ if not result:
230
+ return {}
231
+ payload_text = "\n".join(lines[payload_index + 1 :]).strip()
232
+ if payload_text:
233
+ result["payload_text"] = payload_text
234
+ return result
235
+
236
+
237
+ def _agent_message_visible_text(text: str, header: dict[str, str]) -> str | None:
238
+ """Return provider plaintext while stripping only a validated routing envelope."""
239
+ payload = header.get("payload_text")
240
+ if isinstance(payload, str) and payload:
241
+ return _trim_text(payload)
242
+ return _trim_text(text) if text else None
243
+
244
+
245
+ def _message(timestamp: object, ordinal: object, **fields: Any) -> dict[str, Any]:
246
+ return {
247
+ "timestamp": timestamp if isinstance(timestamp, str) else None,
248
+ "ordinal": ordinal if isinstance(ordinal, int) and not isinstance(ordinal, bool) else None,
249
+ **fields,
250
+ }
251
+
252
+
253
+ def _parent_agent_path(identity: dict[str, Any], agent_path: str | None) -> str | None:
254
+ if identity.get("parent_thread_id") is None:
255
+ return None
256
+ if isinstance(agent_path, str) and agent_path.startswith("/root/"):
257
+ parent = agent_path.rsplit("/", 1)[0]
258
+ if parent:
259
+ return parent
260
+ return "/root"
261
+
262
+
263
+ def _rollout_ordinal(record: dict[str, Any], projected_ordinal: int) -> tuple[int, int]:
264
+ explicit = record.get("ordinal")
265
+ if isinstance(explicit, int) and not isinstance(explicit, bool) and explicit >= 0:
266
+ return explicit, explicit + 1
267
+ return projected_ordinal, projected_ordinal + 1
268
+
269
+
270
+ def _spawn_target_path(output: object) -> str | None:
271
+ """Read the agent path Codex returns from a collaboration spawn tool call."""
272
+ if isinstance(output, str):
273
+ try:
274
+ output = json.loads(output)
275
+ except json.JSONDecodeError:
276
+ return None
277
+ if not isinstance(output, dict):
278
+ return None
279
+ task_name = output.get("task_name")
280
+ if isinstance(task_name, str) and task_name.startswith("/root"):
281
+ return task_name
282
+ return None
283
+
284
+
285
+ def _subagent_activity(record: dict[str, Any]) -> dict[str, Any] | None:
286
+ """Return a Codex SubAgentActivity item, the exact agent id/agent path linkage."""
287
+ if record.get("type") != "event_msg":
288
+ return None
289
+ payload = record.get("payload")
290
+ if not isinstance(payload, dict) or payload.get("type") != "item_completed":
291
+ return None
292
+ item = payload.get("item")
293
+ if isinstance(item, dict) and item.get("type") == "SubAgentActivity":
294
+ return item
295
+ return None
296
+
297
+
298
+ def _encrypted_message_argument(arguments: object) -> tuple[str | None, bool]:
299
+ """Split a spawn payload into visible text and Codex's encrypted-envelope marker."""
300
+ if isinstance(arguments, str):
301
+ try:
302
+ arguments = json.loads(arguments)
303
+ except json.JSONDecodeError:
304
+ return None, False
305
+ if not isinstance(arguments, dict):
306
+ return None, False
307
+ value = arguments.get("message")
308
+ if not isinstance(value, str) or not value:
309
+ return None, False
310
+ if value.startswith("gAAAAA"):
311
+ return None, True
312
+ return _trim_text(value), False
313
+
314
+
315
+ class _DerivedThreads:
316
+ """Collect per-agent conversation records carried by explicit routing evidence.
317
+
318
+ A Codex parent rollout physically records the delegations it issues and the
319
+ returns its children send back. Those records are owned by the child agent's
320
+ execution context, so they materialize the child's own conversation instead of
321
+ being absorbed into the parent thread. Nothing is synthesized: an agent only
322
+ appears once the rollout names it on a real routing record.
323
+ """
324
+
325
+ def __init__(self, owner_thread_id: object, owner_agent_path: str | None) -> None:
326
+ self._owner_thread_id = owner_thread_id if isinstance(owner_thread_id, str) else None
327
+ self._owner_agent_path = owner_agent_path
328
+ self._delegated: set[str] = set()
329
+ self._messages: dict[str, list[dict[str, Any]]] = {}
330
+ self._thread_ids: dict[str, str] = {}
331
+ self._nicknames: dict[str, str] = {}
332
+
333
+ def delegate(self, agent_path: object, thread_id: object = None) -> None:
334
+ """Record that this rollout's own agent spawned ``agent_path``."""
335
+ if not isinstance(agent_path, str) or not agent_path.startswith("/root/"):
336
+ return
337
+ if agent_path == self._owner_agent_path:
338
+ return
339
+ self._delegated.add(agent_path)
340
+ if isinstance(thread_id, str) and thread_id:
341
+ self._thread_ids.setdefault(agent_path, thread_id)
342
+
343
+ def owns(self, agent_path: object) -> bool:
344
+ """Only an agent this rollout delegated to has a thread derivable from here.
345
+
346
+ A peer message merely names its sender. Treating that as the sender's thread
347
+ would invent an execution identity this rollout never observed, so inbound
348
+ peer routing stays a record of the receiving thread alone.
349
+ """
350
+ return isinstance(agent_path, str) and agent_path in self._delegated
351
+
352
+ def add(self, agent_path: object, message: dict[str, Any]) -> None:
353
+ if not self.owns(agent_path):
354
+ return
355
+ self._messages.setdefault(str(agent_path), []).append(message)
356
+
357
+ def previews(self, *, preserve_history: bool = False) -> list[dict[str, Any]]:
358
+ results: list[dict[str, Any]] = []
359
+ for agent_path in sorted(self._messages):
360
+ messages = sorted(
361
+ self._messages[agent_path],
362
+ key=lambda message: (
363
+ message.get("ordinal") if isinstance(message.get("ordinal"), int) else 2**63 - 1,
364
+ str(message.get("timestamp") or ""),
365
+ ),
366
+ )
367
+ truncated = not preserve_history and len(messages) > _MAX_PREVIEW_MESSAGES
368
+ if truncated:
369
+ messages = messages[:10] + messages[-(_MAX_PREVIEW_MESSAGES - 10) :]
370
+ thread_id = self._thread_ids.get(agent_path)
371
+ results.append(
372
+ {
373
+ "thread_id": thread_id or f"{self._owner_thread_id or 'codex'}::{agent_path}",
374
+ "thread_id_source": (
375
+ THREAD_ID_PROVIDER_NATIVE if thread_id else THREAD_ID_EXECWEAVE_DERIVED
376
+ ),
377
+ "parent_thread_id": self._owner_thread_id,
378
+ "agent_id": thread_id,
379
+ "agent_path": agent_path,
380
+ "agent_nickname": self._nicknames.get(agent_path),
381
+ "message_count": len(messages),
382
+ "messages_truncated": truncated,
383
+ "messages": messages,
384
+ "evidence_scope": EVIDENCE_CROSS_AGENT_ROUTING,
385
+ }
386
+ )
387
+ return results
388
+
389
+
390
+ def codex_rollout_preview(path: str | Path) -> dict[str, Any] | None:
391
+ """Extract only thread-owned visible conversation items from a Codex rollout."""
392
+ previews = codex_rollout_previews(path)
393
+ return previews[0] if previews else None
394
+
395
+
396
+ def codex_rollout_previews(
397
+ path: str | Path, *, preserve_history: bool = False,
398
+ ) -> list[dict[str, Any]]:
399
+ """Extract agent-local conversations a single Codex rollout provides evidence for.
400
+
401
+ ``preserve_history`` retains all normalized message records for the Dashboard;
402
+ the default remains the bounded preview used by existing callers. This does
403
+ not change per-message text limits or the provider visibility boundary.
404
+
405
+ The first result is the rollout's own thread. Codex subagent rollouts can
406
+ physically contain inherited parent history: newer paginated rollouts persist
407
+ ordinals on each line, while older compatible rollouts derive them from physical
408
+ valid-line order, so Codex's own subagent_history_start_ordinal boundary is
409
+ applied in either representation and inherited history is never rendered as if
410
+ it belonged to the child agent.
411
+
412
+ Any further results are agent-local threads for other agents this rollout carries
413
+ explicit routing evidence about — a delegation it issued, or a return it received.
414
+ Those records belong to the other agent's execution context, so they are attributed
415
+ there instead of being absorbed into this rollout's own conversation.
416
+ """
417
+ source = Path(path).expanduser().resolve(strict=False)
418
+ identity = codex_rollout_identity(source)
419
+ if identity is None:
420
+ return []
421
+ cutoff = identity.get("subagent_history_start_ordinal")
422
+ min_ordinal = cutoff if isinstance(cutoff, int) else 0
423
+ projected_ordinal = identity.get("history_base_end_ordinal")
424
+ if not isinstance(projected_ordinal, int) or projected_ordinal < 0:
425
+ projected_ordinal = 0
426
+ agent_path, agent_path_source = _resolved_agent_path(identity)
427
+ parent_agent_path = _parent_agent_path(identity, agent_path)
428
+ derived = _DerivedThreads(identity.get("thread_id"), agent_path)
429
+ messages: list[dict[str, Any]] = []
430
+ pending_spawns: dict[str, dict[str, Any]] = {}
431
+ try:
432
+ with source.open("r", encoding="utf-8") as handle:
433
+ for line in handle:
434
+ if not line.strip():
435
+ continue
436
+ try:
437
+ record = json.loads(line)
438
+ except json.JSONDecodeError:
439
+ continue
440
+ if not isinstance(record, dict):
441
+ continue
442
+ ordinal, projected_ordinal = _rollout_ordinal(record, projected_ordinal)
443
+ if ordinal < min_ordinal:
444
+ continue
445
+ activity = _subagent_activity(record)
446
+ if activity is not None:
447
+ derived.delegate(
448
+ activity.get("agent_path"), activity.get("agent_thread_id")
449
+ )
450
+ continue
451
+ if record.get("type") != "response_item":
452
+ continue
453
+ payload = record.get("payload")
454
+ if not isinstance(payload, dict):
455
+ continue
456
+ payload_type = payload.get("type")
457
+ if payload_type == "agent_message":
458
+ content = payload.get("content")
459
+ text = _content_text(content)
460
+ header = _agent_message_header(text)
461
+ encrypted = isinstance(content, list) and any(
462
+ isinstance(part, dict) and part.get("type") == "encrypted_content"
463
+ for part in content
464
+ )
465
+ sender = payload.get("author") or header.get("sender")
466
+ recipient = payload.get("recipient") or header.get("task_name")
467
+ routed = _message(
468
+ record.get("timestamp"),
469
+ ordinal,
470
+ kind=header.get("message_type", "agent_message").lower(),
471
+ sender=sender,
472
+ recipient=recipient,
473
+ text=(
474
+ None
475
+ if encrypted
476
+ else _agent_message_visible_text(text, header)
477
+ ),
478
+ content_state="provider_encrypted" if encrypted else "plaintext",
479
+ phase=None,
480
+ task_name=header.get("task_name"),
481
+ )
482
+ messages.append(routed)
483
+ derived.add(sender, dict(routed))
484
+ elif payload_type == "function_call" and payload.get("name") == "spawn_agent":
485
+ call_id = payload.get("call_id")
486
+ if isinstance(call_id, str) and call_id:
487
+ text, encrypted = _encrypted_message_argument(payload.get("arguments"))
488
+ pending_spawns[call_id] = {
489
+ "timestamp": record.get("timestamp"),
490
+ "ordinal": ordinal,
491
+ "text": text,
492
+ "encrypted": encrypted,
493
+ }
494
+ elif payload_type == "function_call_output" and isinstance(
495
+ payload.get("call_id"), str
496
+ ):
497
+ spawn = pending_spawns.pop(str(payload.get("call_id")), None)
498
+ target = _spawn_target_path(payload.get("output"))
499
+ if spawn is None or target is None:
500
+ continue
501
+ derived.delegate(target)
502
+ if not derived.owns(target):
503
+ continue
504
+ delegation = _message(
505
+ spawn["timestamp"],
506
+ spawn["ordinal"],
507
+ kind="task",
508
+ sender=agent_path,
509
+ recipient=target,
510
+ text=spawn["text"],
511
+ content_state=(
512
+ "provider_encrypted" if spawn["encrypted"] else "plaintext"
513
+ ),
514
+ phase="assignment",
515
+ task_name=target,
516
+ )
517
+ messages.append(delegation)
518
+ derived.add(target, dict(delegation))
519
+ elif payload_type == "message":
520
+ role = payload.get("role")
521
+ phase = payload.get("phase")
522
+ text = _content_text(payload.get("content"))
523
+ if role == "assistant" and text and phase in {"commentary", "final_answer"}:
524
+ is_subagent_final = phase == "final_answer" and parent_agent_path is not None
525
+ messages.append(
526
+ _message(
527
+ record.get("timestamp"),
528
+ ordinal,
529
+ kind=(
530
+ "subagent_final_response"
531
+ if is_subagent_final
532
+ else "assistant_message"
533
+ ),
534
+ sender=agent_path,
535
+ recipient=parent_agent_path if is_subagent_final else None,
536
+ text=_trim_text(text),
537
+ content_state="plaintext",
538
+ phase=phase,
539
+ task_name=None,
540
+ )
541
+ )
542
+ elif role == "user" and text:
543
+ metadata = payload.get("internal_chat_message_metadata_passthrough")
544
+ kinds = metadata.get("content_item_kinds") if isinstance(metadata, dict) else None
545
+ if isinstance(kinds, list) and "user.text" in kinds:
546
+ messages.append(
547
+ _message(
548
+ record.get("timestamp"),
549
+ ordinal,
550
+ kind="user_message",
551
+ sender="user",
552
+ recipient=agent_path,
553
+ text=_trim_text(text),
554
+ content_state="plaintext",
555
+ phase=None,
556
+ task_name=None,
557
+ )
558
+ )
559
+ elif parent_agent_path is not None:
560
+ messages.append(
561
+ _message(
562
+ record.get("timestamp"),
563
+ ordinal,
564
+ kind="task",
565
+ sender=parent_agent_path,
566
+ recipient=agent_path,
567
+ text=_trim_text(text),
568
+ content_state="plaintext",
569
+ phase="assignment",
570
+ task_name=None,
571
+ )
572
+ )
573
+ elif (
574
+ payload_type == "function_call"
575
+ and payload.get("namespace") == "collaboration"
576
+ and payload.get("name") == "send_message"
577
+ ):
578
+ arguments = payload.get("arguments")
579
+ try:
580
+ parsed = json.loads(arguments) if isinstance(arguments, str) else arguments
581
+ except json.JSONDecodeError:
582
+ parsed = None
583
+ if isinstance(parsed, dict):
584
+ target = parsed.get("target")
585
+ value = parsed.get("message")
586
+ encrypted = isinstance(value, str) and value.startswith("gAAAAA")
587
+ messages.append(
588
+ _message(
589
+ record.get("timestamp"),
590
+ ordinal,
591
+ kind="send_message",
592
+ sender=agent_path,
593
+ recipient=target if isinstance(target, str) else None,
594
+ text=(
595
+ _trim_text(value)
596
+ if isinstance(value, str) and value and not encrypted
597
+ else None
598
+ ),
599
+ content_state="provider_encrypted" if encrypted else "plaintext",
600
+ phase=None,
601
+ task_name=None,
602
+ )
603
+ )
604
+ except (OSError, RuntimeError, UnicodeError):
605
+ return []
606
+ truncated = not preserve_history and len(messages) > _MAX_PREVIEW_MESSAGES
607
+ if truncated:
608
+ messages = messages[:10] + messages[-(_MAX_PREVIEW_MESSAGES - 10) :]
609
+ owner = {
610
+ "thread_id": identity.get("thread_id"),
611
+ # Codex publishes this on rollout session_meta, so it is the agent's own id.
612
+ "thread_id_source": THREAD_ID_PROVIDER_NATIVE,
613
+ "parent_thread_id": identity.get("parent_thread_id"),
614
+ "agent_path": agent_path,
615
+ "agent_path_source": agent_path_source,
616
+ "agent_nickname": identity.get("agent_nickname"),
617
+ "message_count": len(messages),
618
+ "messages_truncated": truncated,
619
+ "messages": messages,
620
+ }
621
+ return [owner, *derived.previews(preserve_history=preserve_history)]