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,491 @@
1
+ """Session/actor presentation over evidence; never mutates the recorded graph."""
2
+
3
+ SESSION_FLOW_SCRIPT = r"""
4
+ function execweaveSessionFlow(display,raw){
5
+ const a=n=>n?.attributes||{},r=e=>String(e?.relation||'').toUpperCase(),enc=encodeURIComponent;
6
+ if(!display||!Array.isArray(display.nodes)||!Array.isArray(display.edges))return display;
7
+ const rawNodes=raw?.nodes||[],rawEdges=raw?.edges||[],sid=raw?.session_id;
8
+ const byId=new Map(rawNodes.map(n=>[n.id,n])),rawEdgeById=new Map(rawEdges.map(e=>[e.id,e]));
9
+ const rawSessions=rawNodes.filter(n=>n.type==='session');
10
+ // The recording session is the run being viewed. Never choose one by array order.
11
+ const R=byId.get(`session:${sid}`)?.type==='session'?`session:${sid}`:(rawSessions.length===1?rawSessions[0].id:null);
12
+ if(!R)return display;
13
+ const recordingId=sid!=null&&sid!==''?String(sid):String(R).replace(/^session:/,'');
14
+ let nodes=display.nodes.map(n=>({...n,attributes:{...a(n)}}));
15
+ let edges=display.edges.map(e=>({...e,attributes:{...a(e)}}));
16
+ const observed=e=>!!e&&e.inferred!==true&&e.viewer_only!==true&&a(e).inferred!==true;
17
+ const unique=items=>{const ids=[...new Set(items.filter(x=>x!=null&&x!==''))];return ids.length===1?ids[0]:null};
18
+ const group=(list,key)=>{const m=new Map();for(const x of list){const k=key(x);if(!m.has(k))m.set(k,[]);m.get(k).push(x)}return m};
19
+ const inRaw=group(rawEdges,e=>e.target),outRaw=group(rawEdges,e=>e.source);
20
+ const incoming=id=>inRaw.get(id)||[],outgoing=id=>outRaw.get(id)||[];
21
+ const OWNED=new Set(['provider_session','agent_turn','agent_execution','tool_call','tool_call_observation']);
22
+ const ownerWalk=(id,seen)=>{
23
+ const n=byId.get(id);if(!n||seen.has(id))return null;
24
+ if(n.type==='agent')return id;
25
+ if(!OWNED.has(n.type))return null;
26
+ seen.add(id);const owner=unique(incoming(id).filter(observed).map(e=>ownerWalk(e.source,seen)));seen.delete(id);
27
+ return owner;
28
+ };
29
+ const owners=new Map(),ownerOf=id=>{if(!owners.has(id))owners.set(id,ownerWalk(id,new Set()));return owners.get(id)};
30
+ let shown=new Map(nodes.map(n=>[n.id,n]));
31
+ const refresh=()=>{shown=new Map(nodes.map(n=>[n.id,n]))};
32
+ const info=id=>({...a(byId.get(id)),...a(shown.get(id))}),typeOf=id=>(shown.get(id)||byId.get(id))?.type;
33
+ const CHILD=new Set(['SPAWNED_AGENT','HAS_CHILD_AGENT_SESSION']);
34
+ const childTargets=new Set([...rawEdges,...edges].filter(e=>CHILD.has(r(e))).map(e=>e.target));
35
+ const isChild=id=>childTargets.has(id)||!!String(info(id).parent_agent_path||'').trim()||['subagent','child'].includes(String(info(id).agent_role||'').toLowerCase());
36
+ const isCarrier=id=>['provider_session_id','provider_conversation_id'].includes(String(info(id).identity_semantics||''));
37
+ const named=(id,name)=>byId.get(id)?.name===name||shown.get(id)?.name===name;
38
+ const rootMarked=id=>{const x=info(id);return x.agent_role==='root'||x.viewer_root===true||x.agent_path==='/root'||(x.root_agent_path==='/root'&&!isChild(id))||named(id,'/root')};
39
+ const eligible=id=>typeOf(id)==='agent'&&rootMarked(id)&&!isCarrier(id)&&!isChild(id);
40
+ const ALIAS={'claude code':'claude','openai codex':'codex','cursor agent':'cursor','cursor-agent':'cursor','agy':'antigravity'};
41
+ const tokens=id=>new Set([a(byId.get(id)).provider,byId.get(id)?.name,a(shown.get(id)).provider].map(x=>String(x||'').trim().toLowerCase()).filter(x=>x&&x!=='/root'&&x!=='root').map(x=>ALIAS[x]||x));
42
+ const sameProduct=(x,y)=>{const t=tokens(y);return [...tokens(x)].some(v=>t.has(v))};
43
+ const rawAgents=rawNodes.filter(n=>n.type==='agent').map(n=>n.id);
44
+ // The launcher of the recording session is its root actor unless the same
45
+ // product exposes an explicit root agent of its own.
46
+ const starts=incoming(R).filter(e=>r(e)==='STARTED_SESSION'&&byId.get(e.source)?.type==='agent');
47
+ const L=unique(starts.filter(observed).map(e=>e.source))||unique(starts.map(e=>e.source));
48
+ const root=L?(unique(rawAgents.filter(id=>id!==L&&eligible(id)&&sameProduct(id,L)))||L):(rawSessions.length===1?unique(rawAgents.filter(eligible)):null);
49
+ if(!root)return display;
50
+ // Without the run id, a lone session joins the flow only on observed membership
51
+ // evidence from the root itself, as before; a session that merely owns it does not.
52
+ if(R!==`session:${sid}`&&!rawEdges.some(e=>e.source===root&&e.target===R&&observed(e)))return display;
53
+ const PROVIDER_ROOTS=new Set(['agent:Claude Code','agent:OpenAI Codex','agent:Codex','agent:Cursor','agent:OpenCode','agent:Antigravity','agent:Ollama','agent:ollama']);
54
+ const ofRoot=id=>sameProduct(id,root)||(!!L&&sameProduct(id,L));
55
+ let D=null;
56
+ if(shown.has(root))D=root;
57
+ else{
58
+ const alias=unique(nodes.filter(n=>n.type==='agent'&&n.name==='/root'&&isCarrier(n.id)&&!isChild(n.id)&&ofRoot(n.id)).map(n=>n.id));
59
+ if(alias)D=alias;
60
+ else{
61
+ const source=byId.get(root);
62
+ nodes.push({...source,name:PROVIDER_ROOTS.has(root)||rootMarked(root)?'/root':source.name,attributes:{...a(source)}});
63
+ D=root;refresh();
64
+ }
65
+ }
66
+ // One actor: the root, its display alias, the launcher and the provider
67
+ // session/conversation carriers of the same product. Children stay separate.
68
+ const members=new Set([root,D,L].filter(Boolean));
69
+ for(const n of rawNodes)if(n.type==='agent'&&isCarrier(n.id)&&!isChild(n.id)&&ofRoot(n.id))members.add(n.id);
70
+ const psIds=new Set();
71
+ for(const m of members)for(const e of outgoing(m))if(byId.get(e.target)?.type==='provider_session')psIds.add(e.target);
72
+ const ownsPs=id=>outgoing(id).some(e=>psIds.has(e.target));
73
+ const unitIds=[...psIds,...[...members].filter(id=>byId.has(id)&&isCarrier(id)&&!ownsPs(id))];
74
+ const pointOf=(x,last)=>({seq:last?(x?.last_sequence??x?.first_sequence):x?.first_sequence,stamp:last?(x?.last_seen||x?.first_seen):x?.first_seen});
75
+ const cmp=(p,q)=>Number.isInteger(p.seq)&&Number.isInteger(q.seq)?p.seq-q.seq:String(p.stamp||'').localeCompare(String(q.stamp||''));
76
+ const startOf=id=>{
77
+ const items=[byId.get(id),...incoming(id),...outgoing(id)].filter(Boolean);
78
+ const seqs=items.map(x=>x.first_sequence).filter(Number.isInteger),stamps=items.map(x=>x.first_seen).filter(Boolean).map(String).sort();
79
+ return {seq:seqs.length?Math.min(...seqs):undefined,stamp:stamps[0]};
80
+ };
81
+ const psidOf=id=>{const n=byId.get(id),x=a(n);return String(x.session_id||x.conversation_id||x.provider_session_id||String(id).split(':').pop()||n?.name||'')};
82
+ const units=unitIds.map(id=>({id,start:startOf(id),psid:psidOf(id)})).sort((p,q)=>cmp(p.start,q.start)||String(p.id).localeCompare(String(q.id)));
83
+ const unitIndex=new Map(units.map((u,k)=>[u.id,k]));
84
+ const carrierUnits=new Map([...members].map(m=>[m,[...new Set([m,...outgoing(m).map(e=>e.target)].filter(id=>unitIndex.has(id)).map(id=>unitIndex.get(id)))]]));
85
+ const nativeUnit=(id,seen=new Set())=>{
86
+ if(id==null||seen.has(id))return null;
87
+ if(unitIndex.has(id))return unitIndex.get(id);
88
+ if(carrierUnits.get(id)?.length===1)return carrierUnits.get(id)[0];
89
+ seen.add(id);let k=null;
90
+ const e=rawEdgeById.get(id);
91
+ if(e){k=nativeUnit(e.source,seen);if(k==null&&OWNED.has(byId.get(e.target)?.type))k=nativeUnit(e.target,seen)}
92
+ else if(OWNED.has(byId.get(id)?.type)){const ks=[...new Set(incoming(id).filter(observed).map(x=>nativeUnit(x.source,seen)).filter(x=>x!=null))];k=ks.length===1?ks[0]:null}
93
+ seen.delete(id);return k;
94
+ };
95
+ const BASIS=['single_session','provider_session_evidence','provider_session_id','session_start_time','sequence_window','unresolved'];
96
+ const TIMED=new Set(['session_start_time','sequence_window','unresolved']);
97
+ const better=(x,y)=>BASIS.indexOf(x)<=BASIS.indexOf(y)?x:y;
98
+ // Which provider session an item belongs to: exact provider evidence first,
99
+ // then the provider session id, and only then the observed time window.
100
+ const unitOf=(point,ids=[])=>{
101
+ if(units.length<=1)return {k:0,basis:'single_session'};
102
+ const ks=[...new Set(ids.map(id=>nativeUnit(id)).filter(k=>k!=null))];
103
+ if(ks.length===1)return {k:ks[0],basis:'provider_session_evidence'};
104
+ const segments=new Set(ids.filter(id=>byId.has(id)||rawEdgeById.has(id)).flatMap(id=>String(id).split(':')));
105
+ const hits=units.map((u,k)=>u.psid&&segments.has(u.psid)?k:null).filter(k=>k!=null);
106
+ if(hits.length===1)return {k:hits[0],basis:'provider_session_id'};
107
+ if(!Number.isInteger(point?.seq)&&!point?.stamp)return null;
108
+ const exact=units.map((u,k)=>u.start.stamp&&u.start.stamp===point.stamp?k:null).filter(k=>k!=null);
109
+ if(exact.length===1)return {k:exact[0],basis:'session_start_time'};
110
+ let k=0;units.forEach((u,i)=>{if(cmp(u.start,point)<=0)k=i});
111
+ return {k,basis:'sequence_window'};
112
+ };
113
+ const sessionIds=units.length?units.map((u,k)=>k===0?R:`viewer:session:${enc(u.id)}`):[R];
114
+ const sessionSet=new Set(sessionIds);
115
+ const USE=new Set(['SERVED_BY_MODEL','INVOKES_MODEL','INVOKED_MODEL','USED_MODEL','REQUESTED_MODEL','ROUTED_TO_MODEL','INFERRED','REQUESTS_MODEL_CALL']);
116
+ const DONE=new Set(['MODEL_INVOCATION_COMPLETED','MODEL_CALL_RESPONDS','MODEL_CALL_FAILED']);
117
+ const isCtx=id=>!!a(shown.get(id)).viewer_model_context;
118
+ const isModel=id=>typeOf(id)==='model'&&!isCtx(id);
119
+ const usesModel=e=>USE.has(r(e))||DONE.has(r(e))||(r(e)==='SWITCHED_MODEL'&&typeOf(e.source)!=='model');
120
+ const uses=new Map(),seenUse=new Set();
121
+ const addUse=e=>{
122
+ const key=`${e.target}\0${e.first_sequence}\0${e.first_seen}\0${r(e)}`;
123
+ if(uses.has(e.id)||seenUse.has(key))return;
124
+ seenUse.add(key);
125
+ uses.set(e.id,{model:e.target,edge:e,done:DONE.has(r(e)),ids:[e.id,...(e.viewer_hidden_bridge_sources||[]),e.source],inferred:!observed(e)});
126
+ };
127
+ for(const e of rawEdges)if(usesModel(e)&&byId.get(e.target)?.type==='model'&&members.has(ownerOf(e.source)))addUse(e);
128
+ for(const e of edges)if(usesModel(e)&&isModel(e.target)&&(e.source===D||members.has(e.source)||psIds.has(e.source)))addUse(e);
129
+ // Framework agents that run inside the recorded program itself are the root's
130
+ // own work: the process it launched hosts them, or the run has no other actor.
131
+ // Their model calls are the root's model contexts, and a framework report and
132
+ // the wire call it caused, under the same model name, are one context.
133
+ const isFramework=id=>typeOf(id)==='agent'&&info(id).conversation_scope==='framework_agent';
134
+ const launched=new Set(outgoing(R).filter(e=>r(e)==='LAUNCHED'&&byId.get(e.target)?.type==='process').map(e=>e.target));
135
+ const hostOf=id=>unique(outgoing(id).filter(e=>r(e)==='CORRELATED_WITH_PROCESS'&&byId.get(e.target)?.type==='process').map(e=>e.target));
136
+ const programOnly=root===L&&!psIds.size&&rawAgents.every(id=>id===L||isFramework(id));
137
+ const hosted=id=>isFramework(id)&&(programOnly||launched.has(hostOf(id)));
138
+ const nameOf=id=>{const n=shown.get(id)||byId.get(id);return String(info(id).model_name||n?.name||'').trim().toLowerCase().replace(/:latest$/,'')};
139
+ const frameworkUses=edges.filter(e=>usesModel(e)&&isFramework(e.source)&&isModel(e.target));
140
+ const wire=[...new Set([...uses.values()].map(u=>u.model))],sameModel=new Map();
141
+ for(const e of frameworkUses){
142
+ if(!hosted(e.source))continue;
143
+ const m=e.target,same=nameOf(m)?unique(wire.filter(w=>w!==m&&nameOf(w)===nameOf(m))):null;
144
+ if(same)sameModel.set(m,same);else addUse(e);
145
+ }
146
+ for(const n of nodes){
147
+ const m=a(n).model_resource_id;
148
+ if(!a(n).viewer_model_context||!members.has(a(n).owner_agent_id)||!m||[...uses.values()].some(u=>u.model===m))continue;
149
+ uses.set(n.id,{model:m,edge:{id:n.id,first_sequence:n.first_sequence,first_seen:n.first_seen,last_sequence:n.last_sequence,last_seen:n.last_seen},done:false,pseudo:true,ids:[n.id],inferred:a(n).inferred===true||n.inferred===true});
150
+ }
151
+ const allUses=[...uses.values()];
152
+ for(const u of allUses){
153
+ u.basis=new Map();
154
+ for(const p of [pointOf(u.edge),pointOf(u.edge,true)]){
155
+ const x=unitOf(p,u.ids)||{k:0,basis:'unresolved'};
156
+ u.basis.set(x.k,u.basis.has(x.k)?better(u.basis.get(x.k),x.basis):x.basis);
157
+ }
158
+ u.units=[...u.basis.keys()];
159
+ }
160
+ // Fold the root's aliases and provider sessions into the root and its sessions.
161
+ const remap=new Map();
162
+ for(const m of members)if(m!==D)remap.set(m,D);
163
+ for(const [id,k] of unitIndex)if(psIds.has(id))remap.set(id,sessionIds[k]);
164
+ const ctxByModel=new Map();
165
+ const memberCtx=nodes.filter(n=>a(n).viewer_model_context&&members.has(a(n).owner_agent_id)&&a(n).model_resource_id);
166
+ for(const [model,list] of group(memberCtx,n=>a(n).model_resource_id)){
167
+ let keep=list.find(n=>a(n).owner_agent_id===D);
168
+ if(!keep){
169
+ const id=`viewer:model-context:${enc(D)}:${enc(model)}`;
170
+ keep=nodes.find(n=>n.id===id);
171
+ if(!keep){keep={...list[0],id,attributes:{...a(list[0])}};nodes.push(keep)}
172
+ }
173
+ keep.attributes.owner_agent_id=D;
174
+ for(const n of list)if(n.id!==keep.id)remap.set(n.id,keep.id);
175
+ ctxByModel.set(model,keep.id);
176
+ }
177
+ const moved=new Set();
178
+ edges=edges.flatMap(e=>{
179
+ const source=remap.get(e.source)??e.source,target=remap.get(e.target)??e.target;
180
+ if(source===e.source&&target===e.target)return [e];
181
+ if(source===target)return [];
182
+ moved.add(e.id);
183
+ return [{...e,source,target,viewer_original_source:e.viewer_original_source??e.source,viewer_original_target:e.viewer_original_target??e.target,...(r(e)==='STARTED_SESSION'?{causal:false}:{})}];
184
+ });
185
+ const merged=new Set(),list=items=>[...new Set(items.flatMap(x=>Array.isArray(x)?x:[]))];
186
+ for(const same of group(edges,e=>`${e.source}\0${r(e)}\0${e.target}`).values()){
187
+ if(same.length<2||!same.some(e=>moved.has(e.id)))continue;
188
+ const base=same.find(e=>!moved.has(e.id))||same[0],rest=same.filter(e=>e!==base),all=[base,...rest];
189
+ const firsts=all.map(e=>pointOf(e)).sort(cmp),lasts=all.map(e=>pointOf(e,true)).sort(cmp);
190
+ Object.assign(base,{
191
+ count:all.reduce((n,e)=>n+(Number(e.count)||1),0),
192
+ ...(all.some(e=>e.evidence_call_count!=null)?{evidence_call_count:all.reduce((n,e)=>n+(Number(e.evidence_call_count)||0),0)}:{}),
193
+ ...(all.some(e=>Array.isArray(e.viewer_tool_call_occurrences))?{viewer_tool_call_occurrences:all.flatMap(e=>e.viewer_tool_call_occurrences||[])}:{}),
194
+ ...(all.some(e=>Array.isArray(e.event_ids))?{event_ids:list(all.map(e=>e.event_ids))}:{}),
195
+ ...(all.some(e=>Array.isArray(e.evidence_ids))?{evidence_ids:list(all.map(e=>e.evidence_ids))}:{}),
196
+ first_sequence:firsts[0].seq??base.first_sequence,first_seen:firsts[0].stamp??base.first_seen,
197
+ last_sequence:lasts.at(-1).seq??base.last_sequence,last_seen:lasts.at(-1).stamp??base.last_seen,
198
+ inferred:all.every(e=>e.inferred===true),viewer_only:all.every(e=>e.viewer_only===true),
199
+ viewer_merged_edge_ids:list([base.viewer_merged_edge_ids||[],rest.map(e=>e.id)]),
200
+ });
201
+ for(const e of rest)merged.add(e);
202
+ }
203
+ edges=edges.filter(e=>!merged.has(e));
204
+ nodes=nodes.filter(n=>!remap.has(n.id)||remap.get(n.id)===n.id);
205
+ for(const n of nodes)for(const key of ['owner_agent_id','model_context_id'])if(remap.has(n.attributes[key]))n.attributes[key]=remap.get(n.attributes[key]);
206
+ const rootNode=nodes.find(n=>n.id===D);
207
+ rootNode.attributes.viewer_agent_member_ids=[...new Set([...(rootNode.attributes.viewer_agent_member_ids||[]),...members])].filter(id=>id!==D);
208
+ rootNode.attributes.viewer_merged_agent_ids=[...members].filter(id=>id!==D&&shown.has(id));
209
+ // Sessions: the recording session holds the first provider session; each later
210
+ // provider session the root opened becomes its own session node.
211
+ if(!nodes.some(n=>n.id===R)){const s=byId.get(R);nodes.push({...s,attributes:{...a(s)}})}
212
+ units.forEach((u,k)=>{
213
+ if(k===0)return;
214
+ const ps=byId.get(u.id);
215
+ nodes.push({id:sessionIds[k],type:'session',name:'Session',first_sequence:u.start.seq,first_seen:u.start.stamp,viewer_only:true,
216
+ attributes:{...a(ps),viewer_only:true,viewer_session_unit_id:u.id}});
217
+ });
218
+ sessionIds.forEach((id,k)=>{
219
+ const n=nodes.find(x=>x.id===id),u=units[k];
220
+ n.name=sessionIds.length===1?'Session':`Session ${k+1}`;
221
+ Object.assign(n.attributes,{viewer_flow_session:true,recording_session_id:recordingId,viewer_owner_agent_id:D,
222
+ ...(u?{provider_session_id:u.psid,viewer_session_unit_id:u.id,viewer_agent_member_ids:[...new Set([...(n.attributes.viewer_agent_member_ids||[]),u.id])]}:{})});
223
+ });
224
+ refresh();
225
+ // Root -> model context -> session. A model switch adds a context from the
226
+ // root that returns to the same session; a new provider session adds a session.
227
+ const firstPoint=list=>list.map(u=>pointOf(u.edge)).sort(cmp)[0]||{};
228
+ const models=[...group(allUses,u=>u.model)].sort(([,x],[,y])=>cmp(firstPoint(x),firstPoint(y))).map(([m])=>m);
229
+ const ctxFor=model=>{
230
+ if(ctxByModel.has(model))return ctxByModel.get(model);
231
+ const resource=shown.get(model)||byId.get(model);if(!resource)return null;
232
+ const id=`viewer:model-context:${enc(D)}:${enc(model)}`;
233
+ if(!shown.has(id)){
234
+ const {viewer_flow_rank,...attributes}=a(resource);
235
+ nodes.push({...resource,id,attributes:{...attributes,viewer_only:true,viewer_model_context:true,owner_agent_id:D,model_resource_id:model}});
236
+ }
237
+ ctxByModel.set(model,id);refresh();return id;
238
+ };
239
+ for(const model of models){
240
+ const ctx=ctxFor(model);if(!ctx)continue;
241
+ const mine=allUses.filter(u=>u.model===model),real=mine.filter(u=>!u.pseudo),first=firstPoint(mine);
242
+ const id=`viewer:${D}--MODEL_CONTEXT-->${ctx}`;
243
+ const old=edges.filter(e=>e.target===ctx&&r(e)==='MODEL_CONTEXT');
244
+ edges=edges.filter(e=>!old.includes(e));
245
+ edges.push({id,source:D,target:ctx,relation:'MODEL_CONTEXT',count:1,viewer_only:true,causal:false,inferred:mine.every(u=>u.inferred),
246
+ first_sequence:first.seq,first_seen:first.stamp,
247
+ attributes:{...Object.assign({},...old.map(a)),owner_agent_id:D,model_resource_id:model,evidence_edge_ids:real.map(u=>u.edge.id)}});
248
+ for(const k of [...new Set(mine.flatMap(u=>u.units))].sort((x,y)=>x-y)){
249
+ const here=mine.filter(u=>u.units.includes(k)),basis=here.map(u=>u.basis.get(k)).reduce(better,'unresolved');
250
+ const calls=here.filter(u=>!u.pseudo&&!u.done).length||here.filter(u=>!u.pseudo).length||1,at=firstPoint(here);
251
+ edges.push({id:`viewer:${ctx}--USED_IN_SESSION-->${sessionIds[k]}`,source:ctx,target:sessionIds[k],relation:'USED_IN_SESSION',
252
+ count:calls,viewer_only:true,causal:false,inferred:TIMED.has(basis),first_sequence:at.seq,first_seen:at.stamp,
253
+ attributes:{model_resource_id:model,recording_session_id:recordingId,...(units[k]?{provider_session_id:units[k].psid}:{}),
254
+ evidence_edge_ids:here.filter(u=>!u.pseudo).map(u=>u.edge.id),viewer_session_attribution:basis}});
255
+ }
256
+ }
257
+ for(const e of edges){
258
+ if(r(e)!=='SWITCHED_MODEL'||!ctxByModel.has(e.target)||!ctxByModel.has(e.source))continue;
259
+ const n=shown.get(ctxByModel.get(e.target));
260
+ n.attributes.viewer_switched_from=[...new Set([...(n.attributes.viewer_switched_from||[]),e.source])];
261
+ }
262
+ edges=edges.filter(e=>!(r(e)==='SWITCHED_MODEL'&&ctxByModel.has(e.target)&&ctxByModel.has(e.source)));
263
+ // One framework agent's requests, responses and failures for one model are one
264
+ // display edge. A root context serves the agent; any other model is called by it.
265
+ const folded=new Set(),counted=xs=>xs.reduce((k,e)=>k+(Number(e.count)||1),0);
266
+ const modelOf=e=>hosted(e.source)&&sameModel.get(e.target)||e.target;
267
+ for(const list of group(frameworkUses,e=>`${e.source}\0${modelOf(e)}`).values()){
268
+ const agent=list[0].source,model=modelOf(list[0]),ctx=hosted(agent)&&ctxByModel.get(model);
269
+ const source=ctx||agent,target=ctx?agent:model,relation=ctx?'USED_BY_AGENT':'CALLED_MODEL';
270
+ const asked=list.filter(e=>!DONE.has(r(e))),failed=list.filter(e=>r(e)==='MODEL_CALL_FAILED'),done=list.filter(e=>DONE.has(r(e))&&!failed.includes(e));
271
+ const firsts=list.map(e=>pointOf(e)).sort(cmp),lasts=list.map(e=>pointOf(e,true)).sort(cmp);
272
+ edges.push({id:`viewer:${source}--${relation}-->${target}`,source,target,relation,count:counted(asked)||counted(done)+counted(failed)||1,
273
+ viewer_only:true,causal:false,inferred:list.every(e=>!observed(e)),
274
+ first_sequence:firsts[0].seq,first_seen:firsts[0].stamp,last_sequence:lasts.at(-1).seq,last_seen:lasts.at(-1).stamp,
275
+ viewer_merged_edge_ids:list.map(e=>e.id),
276
+ attributes:{model_resource_id:model,framework_model_ids:[...new Set(list.map(e=>e.target))],request_count:counted(asked),
277
+ response_count:counted(done),failure_count:counted(failed),evidence_edge_ids:list.map(e=>e.id)}});
278
+ for(const e of list)folded.add(e.id);
279
+ }
280
+ edges=edges.filter(e=>!folded.has(e.id));
281
+ for(const [m,w] of sameModel)if(ctxByModel.has(w)){
282
+ edges=edges.map(e=>e.source===m||e.target===m?{...e,source:e.source===m?ctxByModel.get(w):e.source,target:e.target===m?ctxByModel.get(w):e.target,
283
+ viewer_original_source:e.viewer_original_source??e.source,viewer_original_target:e.viewer_original_target??e.target}:e);
284
+ const ctx=shown.get(ctxByModel.get(w));
285
+ ctx.attributes.viewer_framework_model_ids=[...new Set([...(ctx.attributes.viewer_framework_model_ids||[]),m])];
286
+ }
287
+ edges=edges.filter(e=>!(usesModel(e)&&ctxByModel.has(e.target)&&(e.source===D||sessionSet.has(e.source))));
288
+ for(const [model,ctx] of ctxByModel){
289
+ if(!edges.some(e=>e.source===model))continue;
290
+ const kept=edges.some(e=>e.target===model);
291
+ edges=edges.flatMap(e=>{
292
+ if(e.source!==model)return [e];
293
+ const copy={...e,source:ctx,viewer_original_source:e.viewer_original_source??model};
294
+ return kept?[e,{...copy,id:`viewer:${ctx}--${r(e)}-->${e.target}:${enc(e.id)}`,viewer_only:true,causal:false,viewer_original_edge_id:e.id}]:[copy];
295
+ });
296
+ }
297
+ for(const s of sessionIds){
298
+ const direct=edges.filter(e=>e.source===D&&e.target===s);
299
+ if(edges.some(e=>e.target===s&&r(e)==='USED_IN_SESSION')){
300
+ if(direct.length){
301
+ const n=shown.get(s);n.attributes.viewer_start_edge_ids=[...new Set([...(n.attributes.viewer_start_edge_ids||[]),...direct.map(e=>e.id)])];
302
+ edges=edges.filter(e=>!direct.includes(e));
303
+ }
304
+ }else if(!direct.length)edges.push({
305
+ id:`viewer:${D}--RECORDED_IN_SESSION-->${s}`,source:D,target:s,relation:'RECORDED_IN_SESSION',count:1,
306
+ viewer_only:true,causal:false,inferred:false,
307
+ attributes:{evidence_node_ids:[D,s],recording_session_id:recordingId,model_attribution:'not_observed'}});
308
+ }
309
+ // Tool calls and orchestration hang off the model context that was active at
310
+ // that moment in that provider session. A tool resource may be shared, but a
311
+ // call never inherits another actor's or another session's model.
312
+ const WORK=new Set(['CALLED_TOOL','REQUESTED_TOOL_CALL','REQUESTS_TOOL_CALL','USES_TOOL','PERFORMED_ORCHESTRATION','MESSAGE_SENT']);
313
+ const ownersOk=new Set([...members,...psIds,D]);
314
+ const workUses=allUses.filter(u=>!u.done&&!u.pseudo);
315
+ const modelAt=(k,item)=>{
316
+ const pool=units.length<=1||k==null?workUses:workUses.filter(u=>u.units.includes(k));
317
+ const hint=a(item).model||a(item).model_name||a(item).codex_model;
318
+ if(hint){
319
+ const match=list=>unique(list.filter(u=>u.model===hint||byId.get(u.model)?.name===hint||a(byId.get(u.model)).model_name===hint).map(u=>u.model));
320
+ return match(pool)||match(workUses);
321
+ }
322
+ const at=pointOf(item);
323
+ if(!Number.isInteger(at.seq)&&!at.stamp)return null;
324
+ // An aggregated model edge may have omitted intervening switches. Without
325
+ // an exact model hint, do not pretend its two endpoints are a complete log.
326
+ if(new Set(pool.map(u=>u.model)).size>1&&pool.some(u=>(Number(u.edge.count)||1)>2&&cmp(pointOf(u.edge),at)<0&&cmp(at,pointOf(u.edge,true))<0))return null;
327
+ const points=pool.flatMap(u=>{const f=pointOf(u.edge),l=pointOf(u.edge,true);return cmp(f,l)===0?[[u,f]]:[[u,f],[u,l]]}).filter(([,p])=>cmp(p,at)<=0);
328
+ if(!points.length)return null;
329
+ const best=points.reduce((b,[,p])=>!b||cmp(p,b)>0?p:b,null);
330
+ return unique(points.filter(([,p])=>cmp(p,best)===0).map(([u])=>u.model));
331
+ };
332
+ const routed=[];
333
+ for(const e of edges){
334
+ if(!WORK.has(r(e))||!(e.source===D||sessionSet.has(e.source))){routed.push(e);continue}
335
+ const target=shown.get(e.target);if(!target){routed.push(e);continue}
336
+ const occurrences=(e.viewer_tool_call_occurrences||a(target).viewer_tool_call_occurrences||[]).filter(o=>!o.owner_id||ownersOk.has(o.owner_id));
337
+ const buckets=new Map();
338
+ for(const item of occurrences.length?occurrences:[null]){
339
+ const native=item&&(item.call_ids||[]).map(id=>byId.get(id)).find(Boolean);
340
+ const probe=item?{...item,attributes:a(native)}:{...e,attributes:a(target)};
341
+ const ids=item?[...((item.call_ids||[]).length?item.call_ids:[e.id]),item.owner_id]:[e.id,...(e.viewer_hidden_bridge_sources||[])];
342
+ const model=modelAt(unitOf(pointOf(probe),ids)?.k??null,probe);
343
+ if(!buckets.has(model))buckets.set(model,[]);
344
+ if(item)buckets.get(model).push(item);
345
+ }
346
+ for(const [model,items] of buckets){
347
+ const ctx=model!=null&&ctxByModel.get(model);
348
+ const split=occurrences.length?{count:items.length,evidence_call_count:items.length,viewer_tool_call_occurrences:items}:{};
349
+ routed.push(ctx?{...e,...split,id:`viewer:${ctx}--${r(e)}-->${e.target}:${enc(e.id)}`,source:ctx,viewer_only:true,causal:false,
350
+ viewer_original_edge_id:e.id,viewer_original_source:e.viewer_original_source??e.source,attributes:{...a(e),model_resource_id:model}}
351
+ :{...e,...split,attributes:{...a(e),model_attribution:'not_observed'}});
352
+ }
353
+ }
354
+ edges=routed;
355
+ // Runtime work (processes, files, network, warnings) observed through the
356
+ // session belongs to that session, not directly to the root actor.
357
+ const SESSION_WORK=new Set(['process','file','directory','network_endpoint','observation_warning']);
358
+ const sessionSources=new Set([R,...psIds]);
359
+ edges=edges.map(e=>{
360
+ if(!SESSION_WORK.has(typeOf(e.target))||r(e)==='CORRELATED_WITH_PROCESS')return e;
361
+ const bridged=e.source===D&&!observed(e)&&e.viewer_hidden_bridge===true&&(e.viewer_hidden_bridge_sources||[]).some(id=>sessionSources.has(id));
362
+ if(!bridged&&!(e.source===R&&units.length>1))return e;
363
+ const unit=unitOf(pointOf(e),[e.id,...(e.viewer_hidden_bridge_sources||[])]),basis=unit?.basis||'unresolved',s=sessionIds[unit?.k??0];
364
+ if(s===e.source)return e;
365
+ return {...e,id:`viewer:${s}--${r(e)}-->${e.target}:${enc(e.id)}`,source:s,viewer_original_source:e.viewer_original_source??e.source,
366
+ viewer_original_edge_id:e.id,inferred:e.inferred===true||TIMED.has(basis),attributes:{...a(e),viewer_session_attribution:basis}};
367
+ });
368
+ // A framework agent runs inside its process: the process hosts the agent. A
369
+ // child hosted by its parent's process is already reached through its parent.
370
+ const hostEdges=edges.filter(e=>r(e)==='CORRELATED_WITH_PROCESS'&&isFramework(e.source)&&typeOf(e.target)==='process');
371
+ const hostsOf=group(hostEdges,e=>e.source),parentsOf=group(edges.filter(e=>r(e)==='PARENT_AGENT'),e=>e.target);
372
+ edges=edges.filter(e=>!hostEdges.includes(e));
373
+ for(const [agent,list] of hostsOf){
374
+ const n=shown.get(agent);
375
+ if(n)Object.assign(n.attributes,{viewer_host_process_ids:[...new Set(list.map(e=>e.target))],viewer_host_edge_ids:list.map(e=>e.id)});
376
+ for(const e of list){
377
+ if((parentsOf.get(agent)||[]).some(p=>(hostsOf.get(p.source)||[]).some(x=>x.target===e.target)))continue;
378
+ edges.push({...e,id:`viewer:${e.target}--HOSTS_AGENT-->${agent}`,source:e.target,target:agent,relation:'HOSTS_AGENT',viewer_only:true,causal:false,
379
+ viewer_original_edge_id:e.id,viewer_original_source:e.source,viewer_original_target:e.target,
380
+ attributes:{...a(e),correlation_kind:'logical_agent_to_process',viewer_original_edge_ids:[e.id]}});
381
+ }
382
+ }
383
+ // A framework agent's tool request, its result and its failure are one call edge.
384
+ const TOOL_CALL=new Set(['REQUESTS_TOOL_CALL','TOOL_CALL_RETURNS','TOOL_CALL_FAILED']);
385
+ const toolEdges=edges.filter(e=>TOOL_CALL.has(r(e))&&isFramework(e.source)&&typeOf(e.target)==='tool');
386
+ for(const list of group(toolEdges,e=>`${e.source}\0${e.target}`).values()){
387
+ const {source,target}=list[0],of=rel=>counted(list.filter(e=>r(e)===rel));
388
+ const firsts=list.map(e=>pointOf(e)).sort(cmp),lasts=list.map(e=>pointOf(e,true)).sort(cmp);
389
+ edges.push({id:`viewer:${source}--CALLED_TOOL-->${target}`,source,target,relation:'CALLED_TOOL',
390
+ count:of('REQUESTS_TOOL_CALL')||of('TOOL_CALL_RETURNS')+of('TOOL_CALL_FAILED')||1,viewer_only:true,causal:false,inferred:list.every(e=>!observed(e)),
391
+ first_sequence:firsts[0].seq,first_seen:firsts[0].stamp,last_sequence:lasts.at(-1).seq,last_seen:lasts.at(-1).stamp,
392
+ viewer_merged_edge_ids:list.map(e=>e.id),
393
+ attributes:{request_count:of('REQUESTS_TOOL_CALL'),result_count:of('TOOL_CALL_RETURNS'),failure_count:of('TOOL_CALL_FAILED'),evidence_edge_ids:list.map(e=>e.id)}});
394
+ }
395
+ edges=edges.filter(e=>!toolEdges.includes(e));
396
+ const spawned=new Set(edges.filter(e=>r(e)==='SPAWNED_AGENT').map(e=>e.target));
397
+ edges=edges.filter(e=>!(e.source===D&&r(e)==='HAS_CHILD_AGENT_SESSION'&&spawned.has(e.target)));
398
+ // A received message goes back to its actual recipient. The sender's model is
399
+ // a separate invocation, never a substitute destination for the reply.
400
+ for(const n of nodes){
401
+ if(!a(n).viewer_orchestration_action||a(n).orchestration_kind!=='send_input')continue;
402
+ const owner=a(n).owner_agent_id;
403
+ const returns=edges.filter(e=>e.source===n.id&&e.target===D&&e.target!==owner);
404
+ if(!returns.length)continue;
405
+ edges=edges.map(e=>e.target===n.id&&r(e)==='PERFORMED_ORCHESTRATION'?{...e,source:owner,relation:'SENT_AGENT_MESSAGE',viewer_original_source:e.source}:e);
406
+ n.attributes.viewer_return_message=true;
407
+ }
408
+ const usedIds=new Set(edges.flatMap(e=>[e.source,e.target]));
409
+ nodes=nodes.filter(n=>n.type!=='model'||usedIds.has(n.id));
410
+ nodes=[...new Map(nodes.map(n=>[n.id,n])).values()];refresh();
411
+ edges=[...new Map(edges.filter(e=>shown.has(e.source)&&shown.has(e.target)).map(e=>[e.id,e])).values()];
412
+ // Nothing floats: whatever the root cannot reach is attached to the session it
413
+ // was observed in, as a non-causal membership edge.
414
+ const INFRA=new Set(['model','model_runtime','inference_api','inference_gateway','inference_provider','network_endpoint','network_endpoint_cluster']);
415
+ for(;;){
416
+ const out=group(edges,e=>e.source),reached=new Set([D]),queue=[D];
417
+ while(queue.length)for(const e of out.get(queue.shift())||[])if(!reached.has(e.target)){reached.add(e.target);queue.push(e.target)}
418
+ const left=nodes.filter(n=>!reached.has(n.id));
419
+ if(!left.length)break;
420
+ const targets=new Set(edges.map(e=>e.target));
421
+ let heads=left.filter(n=>!targets.has(n.id));
422
+ if(!heads.length){
423
+ // A closed loop (actors messaging each other): enter it at the actor that
424
+ // was observed first, never at a derived message or resource node.
425
+ const touching=group(edges.flatMap(e=>[[e.source,e],[e.target,e]]),([id])=>id);
426
+ const when=n=>[pointOf(n),...(touching.get(n.id)||[]).map(([,e])=>pointOf(e))].filter(p=>Number.isInteger(p.seq)||p.stamp).sort(cmp)[0];
427
+ const pool=left.some(n=>n.type==='agent')?left.filter(n=>n.type==='agent'):left;
428
+ heads=[[...pool].sort((x,y)=>{const p=when(x),q=when(y);return (!p-!q)||(p&&q?cmp(p,q):0)||String(x.id).localeCompare(String(y.id))})[0]];
429
+ }
430
+ for(const n of heads){
431
+ const unit=unitOf(pointOf(n),[n.id]),basis=unit?.basis||'unresolved',source=sessionIds[unit?.k??0]===n.id?D:sessionIds[unit?.k??0];
432
+ const relation=n.type==='agent'?'SESSION_AGENT':INFRA.has(n.type)?'OBSERVED_INFRASTRUCTURE':'OBSERVED_IN_SESSION';
433
+ edges.push({id:`viewer:${source}--${relation}-->${n.id}`,source,target:n.id,relation,count:1,viewer_only:true,causal:false,
434
+ inferred:TIMED.has(basis),first_sequence:n.first_sequence,first_seen:n.first_seen,
435
+ attributes:{recording_session_id:recordingId,viewer_session_attribution:basis}});
436
+ }
437
+ }
438
+ // Root, contexts and sessions are the forward spine. Return edges stay in the
439
+ // graph as feedback and cannot push the root behind its children in layout.
440
+ const ownCtx=new Set(ctxByModel.values()),feedback=new Set();
441
+ for(const e of edges)if(e.target===D||r(e)==='SUBAGENT_STOPPED'||(sessionSet.has(e.target)&&e.source!==D&&!ownCtx.has(e.source)))feedback.add(e.id);
442
+ // Structure is walked before traffic, so a cycle closes on the message or call
443
+ // that returns to an agent rather than on the edge that placed the agent.
444
+ const SPINE=new Set(['MODEL_CONTEXT','USED_IN_SESSION','RECORDED_IN_SESSION','LAUNCHED','HOSTS_AGENT','PARENT_AGENT',
445
+ 'SPAWNED_AGENT','HAS_CHILD_AGENT_SESSION','SESSION_AGENT','SPAWNED']);
446
+ const forward=group(edges.filter(e=>!feedback.has(e.id)),e=>e.source);
447
+ for(const list of forward.values())list.sort((x,y)=>(SPINE.has(r(y))-SPINE.has(r(x)))||cmp(pointOf(x),pointOf(y))||String(x.id).localeCompare(String(y.id)));
448
+ const state=new Map([[D,1]]),stack=[[D,0]];
449
+ while(stack.length){
450
+ const top=stack.at(-1),next=(forward.get(top[0])||[])[top[1]++];
451
+ if(!next){state.set(top[0],2);stack.pop();continue}
452
+ if(state.get(next.target)===1){feedback.add(next.id);continue}
453
+ if(!state.has(next.target)){state.set(next.target,1);stack.push([next.target,0])}
454
+ }
455
+ const sessionRank=ownCtx.size?2:1;
456
+ const floor=id=>id===D?0:ownCtx.has(id)?1:sessionSet.has(id)?sessionRank:sessionRank+1;
457
+ const ranks=new Map(nodes.map(n=>[n.id,floor(n.id)])),indegree=new Map(nodes.map(n=>[n.id,0]));
458
+ const kept=edges.filter(e=>!feedback.has(e.id)&&e.source!==e.target);
459
+ for(const e of kept)indegree.set(e.target,indegree.get(e.target)+1);
460
+ const after=group(kept,e=>e.source),ready=nodes.filter(n=>!indegree.get(n.id)).map(n=>n.id);
461
+ while(ready.length){
462
+ const id=ready.shift();
463
+ for(const e of after.get(id)||[]){
464
+ ranks.set(e.target,Math.max(ranks.get(e.target),ranks.get(id)+1));
465
+ indegree.set(e.target,indegree.get(e.target)-1);
466
+ if(!indegree.get(e.target))ready.push(e.target);
467
+ }
468
+ }
469
+ edges=edges.map(e=>feedback.has(e.id)?{...e,viewer_flow_feedback:true}:e);
470
+ for(const n of nodes){
471
+ n.attributes.viewer_flow_rank=ranks.get(n.id);
472
+ if(n.id===D)n.attributes.viewer_session_flow=true;else delete n.attributes.viewer_session_flow;
473
+ }
474
+ return {...display,nodes,edges,node_count:nodes.length,edge_count:edges.length,
475
+ dashboard_projection:{...display.dashboard_projection,session_flow:true,unresolved_root_sessions:[],viewer_session_root:D}};
476
+ }
477
+ function execweaveExecutionFlowProjection(display,raw){
478
+ return execweaveSessionFlow(execweaveFrameworkMessages(execweaveExecutionFlowBeforeSession(display,raw),raw),raw);
479
+ }
480
+ """
481
+
482
+
483
+ def inject_session_flow(script: str) -> str:
484
+ from .viewer_framework_flow import FRAMEWORK_FLOW_SCRIPT
485
+
486
+ seam = " function execweaveExecutionFlowProjection(display,raw){"
487
+ anchor = " if(typeof execweaveDashboardGraph==='function'){"
488
+ if script.count(seam) != 1 or script.count(anchor) != 1:
489
+ raise RuntimeError("session flow projection seam changed")
490
+ script = script.replace(seam, " function execweaveExecutionFlowBeforeSession(display,raw){", 1)
491
+ return script.replace(anchor, FRAMEWORK_FLOW_SCRIPT + SESSION_FLOW_SCRIPT + "\n" + anchor, 1)
@@ -0,0 +1,132 @@
1
+ """Opt-in structural sharing through a strict output allowlist.
2
+
3
+ This is intentionally not a raw-run export or a promise of anonymization. All
4
+ names, original IDs, paths, hosts, bodies, timestamps and arbitrary metadata are
5
+ omitted. The original capture and archive hashes are never rewritten.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ STRUCTURE_SHARE_JS = r"""
10
+ (()=>{
11
+ 'use strict';if(window.__execweaveStructureShare)return;
12
+ const typeNames={agent:'Agent',session:'Session',task:'Task',agent_task:'Task',tool:'Tool',tool_call:'Tool call',model:'Model',
13
+ model_call:'Model call',inference_request:'Model request',process:'Process',file:'File',directory:'Directory',artifact:'Artifact',
14
+ network_endpoint:'Network endpoint',network_connection:'Network connection',observed_content:'Captured content',message:'Message'};
15
+ const relationNames={SPAWNED:'spawn',LAUNCHED:'launch',REQUESTED_TOOL_CALL:'tool request',REQUESTS_TOOL_CALL:'tool request',USES_TOOL:'tool use',
16
+ REQUESTS_MODEL_CALL:'model request',USED_MODEL:'model use',SENT_MESSAGE:'message send',MESSAGE_SENT:'message send',RECEIVED_MESSAGE:'message receipt',
17
+ MESSAGE_RECEIVED:'message receipt',ASSIGNED_TO:'assignment',HAS_CHILD_AGENT_SESSION:'child session',READ:'read',WROTE:'write',CONNECTED_TO:'network connection',
18
+ HAS_TOOL_INPUT:'tool input',HAS_TOOL_OUTPUT:'tool output',OBSERVED_INFERENCE_REQUEST:'model input',OBSERVED_INFERENCE_RESPONSE:'model output',
19
+ OBSERVED_FILE_CONTENT_BEFORE_READ:'file snapshot',CORRELATED_WITH_PROCESS:'process correlation'};
20
+ const make=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=String(text);return n};
21
+ const button=(label,fn)=>{const b=make('button',label);b.type='button';b.onclick=fn;return b};
22
+ const list=x=>Array.isArray(x)?x:[],own=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
23
+ const raw=()=>window.__execweaveCore?.getGraph?.()||window.__execweaveStaticGraph||{};
24
+ const scope=()=>JSON.stringify([raw().run_id??null,raw().session_id??null,raw().source_path??null]);
25
+ function project(graph){
26
+ if(!graph||!Array.isArray(graph.nodes)||!Array.isArray(graph.edges))throw new Error('No graph inventory is available.');
27
+ if(graph.live_payload_compact)throw new Error('A compact payload is not a complete shareable snapshot.');
28
+ if(graph.nodes.length>10000||graph.edges.length>20000)throw new Error('Structural export exceeds the safety limit (10,000 nodes / 20,000 edges).');
29
+ const source=new Map(),ambiguous=new Set();let invalid=0;
30
+ for(const n of graph.nodes){
31
+ if(!n||typeof n!=='object'||typeof n.id!=='string'||!n.id){invalid++;continue}
32
+ if(source.has(n.id))ambiguous.add(n.id);else source.set(n.id,n);
33
+ }
34
+ const identities=new Map(),nodes=[];
35
+ for(const [id,n] of source){if(ambiguous.has(id))continue;const key='node-'+(nodes.length+1),type=own(typeNames,n.type)?typeNames[n.type]:'Other';
36
+ identities.set(id,key);nodes.push({id:key,type,label:type+' '+(nodes.length+1)});
37
+ }
38
+ const edgeIds=new Set(),ambiguousEdges=new Set();
39
+ for(const e of graph.edges)if(typeof e?.id==='string'){if(edgeIds.has(e.id))ambiguousEdges.add(e.id);edgeIds.add(e.id)}
40
+ const edges=[];let omittedEdges=0;
41
+ for(const e of graph.edges){
42
+ if(!e||typeof e!=='object'||ambiguousEdges.has(e.id)||!identities.has(e.source)||!identities.has(e.target)){omittedEdges++;continue}
43
+ const inferred=e.inferred===true||e.attributes?.inferred===true;
44
+ const knownFlags=[e.inferred,e.attributes?.inferred,e.viewer_only,e.attributes?.viewer_only,e.causal,e.attributes?.causal].every(v=>v===undefined||v===null||typeof v==='boolean');
45
+ const presentation=e.viewer_only===true||e.attributes?.viewer_only===true;
46
+ const causal=knownFlags&&!inferred&&!presentation&&e.causal===true&&e.attributes?.causal!==false;
47
+ edges.push({id:'edge-'+(edges.length+1),source:identities.get(e.source),target:identities.get(e.target),
48
+ relation:own(relationNames,e.relation)?relationNames[e.relation]:'other recorded relationship',
49
+ evidence:presentation?'presentation only':inferred?'inferred correlation':causal?'recorded causal edge':'causality not established'});
50
+ }
51
+ return {schema_version:'1',scope:'structure_only_derived_summary',original_ids_included:false,content_included:false,
52
+ names_paths_hosts_timestamps_included:false,inventory_partial:!!graph.viewer_projection||invalid>0||ambiguous.size>0||omittedEdges>0,
53
+ omitted_nodes:graph.nodes.length-nodes.length,ambiguous_node_ids:ambiguous.size,omitted_edges:omittedEdges,nodes,edges,
54
+ limitation:'Topology and counts can still identify a sensitive workflow. Review before sharing. This is not the original archive, proof of completeness, or a guarantee of anonymity.'};
55
+ }
56
+ const escape=x=>String(x).replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;');
57
+ function renderDocument(data){
58
+ // Accept only freshly projected data in production; escape again for defense
59
+ // in depth. No raw graph object, external URL, script, or imported template.
60
+ return '<!doctype html><html lang="en"><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'"><title>ExecWeave structural summary</title>'+
61
+ '<style>body{font:16px/1.5 system-ui;max-width:1100px;margin:32px auto;padding:16px}table{border-collapse:collapse;width:100%}td,th{border:1px solid #888;text-align:left;padding:8px}p{overflow-wrap:anywhere}</style>'+
62
+ '<h1>ExecWeave structural summary</h1><p>'+escape(data.limitation)+'</p><p>Original content, names, IDs, paths, hosts and timestamps are not included.</p>'+
63
+ '<p>'+data.nodes.length+' nodes; '+data.edges.length+' relationships; inventory '+(data.inventory_partial?'partial':'derived from the selected published graph')+'.</p>'+
64
+ '<h2>Participants and resources</h2><table><tr><th>Pseudonymous ID</th><th>Category</th></tr>'+data.nodes.map(n=>'<tr><td>'+escape(n.id)+'</td><td>'+escape(n.type)+'</td></tr>').join('')+'</table>'+
65
+ '<h2>Recorded relationships</h2><table><tr><th>From</th><th>Relationship</th><th>To</th><th>Evidence boundary</th></tr>'+
66
+ data.edges.map(e=>'<tr><td>'+escape(e.source)+'</td><td>'+escape(e.relation)+'</td><td>'+escape(e.target)+'</td><td>'+escape(e.evidence)+'</td></tr>').join('')+'</table></html>';
67
+ }
68
+ let dialog=null,body,status,confirmation,downloads,prepareButton,invoker=null,currentScope=scope(),generation=0,prepared=null;
69
+ const urls=new Set();
70
+ function discard(){generation++;prepared=null;if(prepareButton)prepareButton.disabled=false;for(const url of urls)URL.revokeObjectURL(url);urls.clear();if(downloads)for(const b of downloads.children)b.disabled=true}
71
+ function close(){discard();dialog?.close();body?.replaceChildren();if(confirmation)confirmation.checked=false;invoker?.focus()}
72
+ function checkScope(){if(scope()===currentScope)return true;currentScope=scope();close();return false}
73
+ function save(name,value,type){
74
+ if(!checkScope()||!prepared||!confirmation.checked)return;
75
+ const link=make('a'),url=URL.createObjectURL(new Blob([value],{type}));urls.add(url);link.href=url;link.download=name;
76
+ document.body.append(link);link.click();link.remove();setTimeout(()=>{URL.revokeObjectURL(url);urls.delete(url)},1000);
77
+ }
78
+ async function prepare(){
79
+ if(!checkScope())return;discard();const token=generation,started=scope();body.replaceChildren();confirmation.checked=false;prepareButton.disabled=true;
80
+ status.textContent='Preparing a separate allowlisted summary; the original run is not changed.';
81
+ try{
82
+ if(document.getElementById('protective')?.hidden===false)throw new Error('Large-graph protection is active. A stale canvas cannot be exported as the current run.');
83
+ const data=project(raw()),json=JSON.stringify(data,null,2)+'\n',html=renderDocument(data);
84
+ if(!globalThis.crypto?.subtle)throw new Error('Native SHA-256 is unavailable in this browser context. No export was prepared.');
85
+ const digest=async s=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(s))),x=>x.toString(16).padStart(2,'0')).join('');
86
+ const jsonHash=await digest(json),htmlHash=await digest(html);
87
+ if(token!==generation||started!==scope()||!dialog.open)return;
88
+ prepared={json,html,checksum:jsonHash+' execweave-structure.json\n'+htmlHash+' execweave-structure.html\n'};
89
+ status.textContent=`Prepared ${data.nodes.length} pseudonymous nodes and ${data.edges.length} relationships. ${data.inventory_partial?'Partial inventory. ':''}These hashes cover the new derived files, not the source archive.`;
90
+ body.append(make('p','JSON SHA-256: '+jsonHash),make('p','HTML SHA-256: '+htmlHash),make('pre',json));
91
+ }catch(e){if(token===generation)status.textContent=String(e.message||'Unable to prepare summary.');}
92
+ finally{if(token===generation)prepareButton.disabled=false}
93
+ }
94
+ function ensure(){
95
+ if(dialog)return;dialog=make('dialog');dialog.id='execweave-share-dialog';dialog.setAttribute('aria-labelledby','execweave-share-title');
96
+ const header=make('header'),title=make('h2','Share structure only');title.id='execweave-share-title';header.append(title,button('Close structural sharing',close));
97
+ const warning=make('p','This mode omits all original names, IDs, paths, hosts, timestamps, conversation bodies, tool arguments/results and arbitrary metadata. It preserves only pseudonymous graph structure and fixed relationship categories. Topology and counts may still be sensitive. This is not an anonymization guarantee or a replacement for a full audit archive.');
98
+ status=make('p');status.id='execweave-share-status';status.setAttribute('role','status');
99
+ prepareButton=button('Prepare structural preview',prepare);
100
+ confirmation=make('input');confirmation.type='checkbox';confirmation.id='execweave-share-confirm';
101
+ const label=make('label');label.append(confirmation,document.createTextNode(' I reviewed the derived structure and accept that topology and counts may still be sensitive.'));
102
+ downloads=make('div');downloads.className='share-actions';
103
+ downloads.append(button('Save structural JSON',()=>save('execweave-structure.json',prepared?.json,'application/json')),
104
+ button('Save structural HTML',()=>save('execweave-structure.html',prepared?.html,'text/html')),
105
+ button('Save derived checksums',()=>save('execweave-structure.sha256',prepared?.checksum,'text/plain')));
106
+ confirmation.onchange=()=>{for(const b of downloads.children)b.disabled=!prepared||!confirmation.checked};
107
+ body=make('div');body.id='execweave-share-preview';dialog.append(header,warning,prepareButton,status,label,downloads,body);
108
+ dialog.addEventListener('keydown',e=>{if(e.key==='Escape')e.stopPropagation()});dialog.addEventListener('cancel',e=>{e.preventDefault();close()});document.body.append(dialog);discard();
109
+ }
110
+ function open(){checkScope();ensure();invoker=document.activeElement;status.textContent='Nothing is exported until you prepare, review, confirm and save.';dialog.showModal()}
111
+ const launch=button('Share structure',open);launch.id='execweave-share-launcher';const host=document.getElementById('execweave-workflow-controls');if(host)host.append(launch);else{const anchor=document.getElementById('theme-toggle');anchor?.parentElement?.insertBefore(launch,anchor)};
112
+ const prior=window.__execweaveDashboard||{};window.__execweaveDashboard={...prior,onPayload(...args){prior.onPayload?.(...args);checkScope()},onFinished(...args){prior.onFinished?.(...args);checkScope()}};
113
+ window.addEventListener('pagehide',close);window.__execweaveStructureShare={project,renderDocument,open,close};
114
+ })();
115
+ """.strip()
116
+
117
+ STRUCTURE_SHARE_CSS = """
118
+ #execweave-share-dialog{width:min(1000px,94vw);max-height:88vh;border:1px solid var(--border);border-radius:12px;padding:18px;background:var(--panel);color:var(--text)}
119
+ #execweave-share-dialog::backdrop{background:rgba(0,0,0,.45)}#execweave-share-dialog header,.share-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
120
+ #execweave-share-title{flex:1;font-size:20px}#execweave-share-dialog button{font:inherit;padding:7px}
121
+ #execweave-share-dialog p,#execweave-share-dialog label{font-size:13px;line-height:1.5;overflow-wrap:anywhere}
122
+ #execweave-share-preview{max-height:42vh;overflow:auto}#execweave-share-preview pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px}
123
+ #execweave-share-launcher{font:inherit;padding:6px 10px;cursor:pointer}.share-actions{margin:10px 0}
124
+ """.strip()
125
+
126
+
127
+ def inject_structure_share(html: str) -> str:
128
+ if 'id="execweave-structure-share-script"' in html:
129
+ return html
130
+ if "</body>" not in html:
131
+ raise RuntimeError("structural sharing requires a dashboard body")
132
+ return html.replace("</body>", "<style>" + STRUCTURE_SHARE_CSS + '</style><script id="execweave-structure-share-script">' + STRUCTURE_SHARE_JS + "</script></body>", 1)