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.
- execweave/__init__.py +3 -0
- execweave/__main__.py +5 -0
- execweave/_conversation_records_core.py +902 -0
- execweave/_dashboard_shell_base.py +148 -0
- execweave/_http_proxy_base.py +565 -0
- execweave/_http_proxy_bounded.py +560 -0
- execweave/_http_proxy_stage.py +509 -0
- execweave/acceptance_output.py +19 -0
- execweave/agent_bootstrap.py +395 -0
- execweave/agent_topology.py +313 -0
- execweave/agent_trace.py +1162 -0
- execweave/agy_preview_sanitize.py +102 -0
- execweave/analysis.py +427 -0
- execweave/anthropic.py +228 -0
- execweave/anthropic_cli.py +171 -0
- execweave/anthropic_full_fidelity.py +385 -0
- execweave/antigravity_adapter.py +112 -0
- execweave/antigravity_adapter_base.py +479 -0
- execweave/antigravity_full_fidelity.py +656 -0
- execweave/antigravity_full_fidelity_base.py +172 -0
- execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
- execweave/antigravity_hook_cli.py +209 -0
- execweave/antigravity_record.py +96 -0
- execweave/antigravity_subagent_linkage.py +449 -0
- execweave/antigravity_trace_capability.py +39 -0
- execweave/auto_specialized.py +547 -0
- execweave/backends.py +102 -0
- execweave/benchmark.py +80 -0
- execweave/claude_adapter.py +517 -0
- execweave/claude_child_transcript.py +314 -0
- execweave/claude_delegation.py +136 -0
- execweave/claude_full_fidelity.py +396 -0
- execweave/claude_hook_cli.py +209 -0
- execweave/claude_hook_contract.py +943 -0
- execweave/claude_model_observer.py +353 -0
- execweave/claude_record.py +106 -0
- execweave/cli.py +629 -0
- execweave/codex_adapter.py +455 -0
- execweave/codex_conversation.py +621 -0
- execweave/codex_full_fidelity.py +287 -0
- execweave/codex_hook_cli.py +301 -0
- execweave/codex_hook_entry.py +207 -0
- execweave/codex_hook_lifecycle.py +363 -0
- execweave/codex_message_diagnostics.py +322 -0
- execweave/codex_message_transport_diagnostics.py +399 -0
- execweave/codex_record.py +199 -0
- execweave/codex_rollout_structures.py +402 -0
- execweave/codex_rollout_trace.py +56 -0
- execweave/codex_rollout_trace_base.py +1509 -0
- execweave/collector.py +768 -0
- execweave/command.py +157 -0
- execweave/command_privacy.py +20 -0
- execweave/content_evidence.py +101 -0
- execweave/content_integrity.py +289 -0
- execweave/content_store.py +273 -0
- execweave/controlled_checks.py +561 -0
- execweave/conversation_archive.py +338 -0
- execweave/conversation_message_identity.py +264 -0
- execweave/conversation_preview.py +66 -0
- execweave/conversation_preview_antigravity.py +32 -0
- execweave/conversation_preview_claude.py +31 -0
- execweave/conversation_preview_codex.py +107 -0
- execweave/conversation_preview_common.py +180 -0
- execweave/conversation_preview_generic.py +188 -0
- execweave/conversation_preview_lines.py +133 -0
- execweave/conversation_preview_transcript.py +121 -0
- execweave/conversation_records.py +349 -0
- execweave/conversation_records_antigravity.py +370 -0
- execweave/conversation_records_codex.py +83 -0
- execweave/conversation_records_common.py +17 -0
- execweave/conversation_records_ollama.py +39 -0
- execweave/correlation.py +818 -0
- execweave/cursor_adapter.py +349 -0
- execweave/cursor_delegation.py +87 -0
- execweave/cursor_delegation_base.py +220 -0
- execweave/cursor_full_fidelity.py +489 -0
- execweave/cursor_hook_cli.py +195 -0
- execweave/cursor_hook_contract.py +439 -0
- execweave/cursor_lifecycle.py +159 -0
- execweave/cursor_record.py +96 -0
- execweave/dashboard_shell.py +283 -0
- execweave/delivery_status.py +94 -0
- execweave/entry.py +98 -0
- execweave/evidence_availability.py +113 -0
- execweave/evidence_grade.py +166 -0
- execweave/fidelity.py +304 -0
- execweave/filesystem.py +327 -0
- execweave/finalization.py +92 -0
- execweave/focus.py +118 -0
- execweave/framework_adapters/__init__.py +34 -0
- execweave/framework_adapters/autogen.py +398 -0
- execweave/framework_adapters/base.py +580 -0
- execweave/framework_adapters/camel.py +270 -0
- execweave/framework_adapters/camel_channel.py +71 -0
- execweave/framework_adapters/metagpt.py +315 -0
- execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
- execweave/framework_adapters/metagpt_recording.py +342 -0
- execweave/framework_adapters/registry.py +90 -0
- execweave/graph.py +590 -0
- execweave/graph_ops.py +472 -0
- execweave/hook_command.py +32 -0
- execweave/hook_delivery.py +32 -0
- execweave/hook_input.py +16 -0
- execweave/http_proxy.py +187 -0
- execweave/http_proxy_cli.py +84 -0
- execweave/inference_gateway.py +476 -0
- execweave/inference_gateway_cli.py +211 -0
- execweave/inference_gateway_full_fidelity.py +613 -0
- execweave/inference_identity.py +76 -0
- execweave/inference_identity_cli.py +60 -0
- execweave/integrity.py +235 -0
- execweave/integrity_cli.py +55 -0
- execweave/investigation_index.py +445 -0
- execweave/litellm_callback.py +211 -0
- execweave/litellm_callback_cli.py +42 -0
- execweave/live.py +445 -0
- execweave/live_core.py +972 -0
- execweave/live_view.py +109 -0
- execweave/live_view_extra_style.py +11 -0
- execweave/live_view_markup.py +29 -0
- execweave/live_view_process_layout.py +650 -0
- execweave/live_view_readability.py +502 -0
- execweave/live_view_script_a.py +59 -0
- execweave/live_view_script_b.py +97 -0
- execweave/live_view_script_c.py +59 -0
- execweave/live_view_script_d.py +40 -0
- execweave/live_view_style.py +34 -0
- execweave/model_runtime.py +560 -0
- execweave/model_runtime_cli.py +265 -0
- execweave/model_runtime_full_fidelity.py +519 -0
- execweave/observation.py +53 -0
- execweave/observation_demo.py +69 -0
- execweave/openai_agents.py +267 -0
- execweave/openai_agents_sdk.py +453 -0
- execweave/openai_compatible.py +239 -0
- execweave/openai_compatible_cli.py +189 -0
- execweave/openai_compatible_full_fidelity.py +438 -0
- execweave/opencode_adapter.py +325 -0
- execweave/opencode_event_contract.py +734 -0
- execweave/opencode_full_fidelity.py +198 -0
- execweave/opencode_hook_cli.py +119 -0
- execweave/opencode_plugin_cli.py +150 -0
- execweave/opencode_record.py +96 -0
- execweave/opencode_task_linkage.py +225 -0
- execweave/overhead_benchmark.py +440 -0
- execweave/privacy.py +84 -0
- execweave/private_io.py +465 -0
- execweave/provider_capability.py +578 -0
- execweave/provider_lifecycle.py +282 -0
- execweave/provider_record.py +290 -0
- execweave/reader_identity.py +13 -0
- execweave/redacted_archive.py +906 -0
- execweave/risk.py +106 -0
- execweave/rule_pack.py +359 -0
- execweave/rule_pack_cli.py +57 -0
- execweave/run_assessment.py +200 -0
- execweave/runtime_endpoint_availability.py +44 -0
- execweave/scalability_benchmark.py +195 -0
- execweave/schema.py +62 -0
- execweave/scope.py +85 -0
- execweave/semantic.py +453 -0
- execweave/session_summary.py +159 -0
- execweave/sink.py +71 -0
- execweave/strace_backend.py +927 -0
- execweave/stream_assembly.py +363 -0
- execweave/task_artifacts.py +192 -0
- execweave/task_validation.py +317 -0
- execweave/theme.py +40 -0
- execweave/top.py +599 -0
- execweave/top_cli.py +150 -0
- execweave/validate.py +196 -0
- execweave/vendor/dagre.min.js +815 -0
- execweave/view_cli.py +49 -0
- execweave/viewer.py +474 -0
- execweave/viewer_agent_panel.py +630 -0
- execweave/viewer_agent_panel_antigravity.py +31 -0
- execweave/viewer_agent_panel_claude.py +9 -0
- execweave/viewer_agent_panel_codex.py +50 -0
- execweave/viewer_agent_panel_cursor.py +9 -0
- execweave/viewer_agent_panel_default.py +79 -0
- execweave/viewer_agent_panel_ollama.py +20 -0
- execweave/viewer_agent_panel_opencode.py +9 -0
- execweave/viewer_agent_panel_registry.py +20 -0
- execweave/viewer_archive_verifier.py +178 -0
- execweave/viewer_background_files.py +86 -0
- execweave/viewer_content_browser.py +307 -0
- execweave/viewer_content_health.py +208 -0
- execweave/viewer_content_inspector.py +309 -0
- execweave/viewer_controlled_checks.py +258 -0
- execweave/viewer_conversation_sync.py +115 -0
- execweave/viewer_dashboard_clean.py +405 -0
- execweave/viewer_dashboard_focus.py +127 -0
- execweave/viewer_dashboard_hardening.py +264 -0
- execweave/viewer_dashboard_hardening_v2.py +62 -0
- execweave/viewer_dashboard_projection.py +261 -0
- execweave/viewer_delivery_status.py +155 -0
- execweave/viewer_edge_decross.py +117 -0
- execweave/viewer_execution_flow.py +611 -0
- execweave/viewer_execution_flow_provider_normalization.py +107 -0
- execweave/viewer_execution_flow_safety.py +349 -0
- execweave/viewer_external_endpoints.py +307 -0
- execweave/viewer_flow_canvas.py +1140 -0
- execweave/viewer_flow_layout.py +922 -0
- execweave/viewer_fold_state.py +31 -0
- execweave/viewer_framework_flow.py +68 -0
- execweave/viewer_framework_model_output.py +133 -0
- execweave/viewer_gif.py +278 -0
- execweave/viewer_history_browser.py +225 -0
- execweave/viewer_investigation.py +268 -0
- execweave/viewer_layout_geometry.py +192 -0
- execweave/viewer_layout_v2.py +429 -0
- execweave/viewer_layout_v2_detached.py +25 -0
- execweave/viewer_limits.py +93 -0
- execweave/viewer_live_layout.py +61 -0
- execweave/viewer_message_handoffs.py +114 -0
- execweave/viewer_projection.py +488 -0
- execweave/viewer_projection_base.py +522 -0
- execweave/viewer_projection_bridges.py +214 -0
- execweave/viewer_recorded_sources.py +146 -0
- execweave/viewer_run_assessment.py +274 -0
- execweave/viewer_run_guide.py +175 -0
- execweave/viewer_runtime_evidence.py +258 -0
- execweave/viewer_semantic_projection.py +641 -0
- execweave/viewer_session_flow.py +491 -0
- execweave/viewer_structure_share.py +132 -0
- execweave/viewer_task_validation.py +241 -0
- execweave/viewer_tool_mirror_identity.py +75 -0
- execweave/viewer_workflow_mode.py +127 -0
- execweave/workflow.py +183 -0
- execweave-1.0.0.dist-info/METADATA +462 -0
- execweave-1.0.0.dist-info/RECORD +234 -0
- execweave-1.0.0.dist-info/WHEEL +4 -0
- execweave-1.0.0.dist-info/entry_points.txt +30 -0
- execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
"""Reassemble streamed inference responses into one canonical response.
|
|
2
|
+
|
|
3
|
+
A streamed response arrives as many partial frames. The canonical record must look
|
|
4
|
+
like the non-streaming response for the same exchange, because everything
|
|
5
|
+
downstream — conversation materialization, tool-call evidence, usage — reads that
|
|
6
|
+
one object. Handing it a single frame loses the body: in an OpenAI-style stream the
|
|
7
|
+
final frame carries an empty delta, so the assistant text never reaches the record
|
|
8
|
+
even though the raw frames were archived.
|
|
9
|
+
|
|
10
|
+
Assemblers are keyed by **wire format**, not by provider. ``openai_chat_delta`` is a
|
|
11
|
+
format shared by many upstreams, and ``ollama_ndjson`` is another. A new provider
|
|
12
|
+
speaking an existing format reuses its assembler and adds nothing here, which is why
|
|
13
|
+
this lives in its own module rather than inside a provider adapter or inside the
|
|
14
|
+
common conversation layer.
|
|
15
|
+
|
|
16
|
+
The assembler reports what it observed and never repairs what it did not see. A
|
|
17
|
+
stream that stopped without a terminator, or that carried a frame this code could not
|
|
18
|
+
parse, is reported as ``capture_interrupted`` with counts, not silently completed.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from .evidence_availability import AVAILABLE, CAPTURE_INTERRUPTED
|
|
28
|
+
|
|
29
|
+
OPENAI_CHAT_DELTA = "openai_chat_delta"
|
|
30
|
+
OLLAMA_NDJSON = "ollama_ndjson"
|
|
31
|
+
|
|
32
|
+
WIRE_FORMATS = (OPENAI_CHAT_DELTA, OLLAMA_NDJSON)
|
|
33
|
+
|
|
34
|
+
_REASONING_DELTA_KEYS = ("reasoning_content", "reasoning", "thinking")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class AssembledStream:
|
|
39
|
+
"""One canonical response rebuilt from streamed frames, plus what was observed."""
|
|
40
|
+
|
|
41
|
+
response: dict[str, Any]
|
|
42
|
+
wire_format: str
|
|
43
|
+
chunk_count: int
|
|
44
|
+
malformed_chunks: int
|
|
45
|
+
terminated: bool
|
|
46
|
+
availability: str
|
|
47
|
+
notes: str | None = None
|
|
48
|
+
|
|
49
|
+
def attributes(self) -> dict[str, Any]:
|
|
50
|
+
"""Observation facts to attach to emitted events."""
|
|
51
|
+
return {
|
|
52
|
+
"stream_assembled": True,
|
|
53
|
+
"stream_wire_format": self.wire_format,
|
|
54
|
+
"stream_chunk_count": self.chunk_count,
|
|
55
|
+
"stream_malformed_chunks": self.malformed_chunks,
|
|
56
|
+
"stream_terminated": self.terminated,
|
|
57
|
+
"response_availability": self.availability,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class _ToolCallAccumulator:
|
|
63
|
+
"""One tool call rebuilt across frames.
|
|
64
|
+
|
|
65
|
+
Both the name and the JSON argument string may arrive split across frames, so
|
|
66
|
+
each is concatenated rather than overwritten. Arguments stay a string because
|
|
67
|
+
that is what the non-streaming response carries; parsing here would make the
|
|
68
|
+
streamed record a different shape from its non-streamed twin.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
index: int
|
|
72
|
+
call_id: str | None = None
|
|
73
|
+
call_type: str | None = None
|
|
74
|
+
name_parts: list[str] = field(default_factory=list)
|
|
75
|
+
argument_parts: list[str] = field(default_factory=list)
|
|
76
|
+
|
|
77
|
+
def absorb(self, payload: dict[str, Any]) -> None:
|
|
78
|
+
identifier = payload.get("id")
|
|
79
|
+
if isinstance(identifier, str) and identifier and self.call_id is None:
|
|
80
|
+
self.call_id = identifier
|
|
81
|
+
call_type = payload.get("type")
|
|
82
|
+
if isinstance(call_type, str) and call_type and self.call_type is None:
|
|
83
|
+
self.call_type = call_type
|
|
84
|
+
function = payload.get("function")
|
|
85
|
+
if not isinstance(function, dict):
|
|
86
|
+
return
|
|
87
|
+
name = function.get("name")
|
|
88
|
+
if isinstance(name, str) and name:
|
|
89
|
+
self.name_parts.append(name)
|
|
90
|
+
arguments = function.get("arguments")
|
|
91
|
+
if isinstance(arguments, str) and arguments:
|
|
92
|
+
self.argument_parts.append(arguments)
|
|
93
|
+
|
|
94
|
+
def to_dict(self) -> dict[str, Any]:
|
|
95
|
+
call: dict[str, Any] = {
|
|
96
|
+
"index": self.index,
|
|
97
|
+
"type": self.call_type or "function",
|
|
98
|
+
"function": {
|
|
99
|
+
"name": "".join(self.name_parts),
|
|
100
|
+
"arguments": "".join(self.argument_parts),
|
|
101
|
+
},
|
|
102
|
+
}
|
|
103
|
+
if self.call_id is not None:
|
|
104
|
+
call["id"] = self.call_id
|
|
105
|
+
return call
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass
|
|
109
|
+
class _ChoiceAccumulator:
|
|
110
|
+
index: int
|
|
111
|
+
role: str | None = None
|
|
112
|
+
content_parts: list[str] = field(default_factory=list)
|
|
113
|
+
reasoning_parts: list[str] = field(default_factory=list)
|
|
114
|
+
finish_reason: Any = None
|
|
115
|
+
tool_calls: dict[int, _ToolCallAccumulator] = field(default_factory=dict)
|
|
116
|
+
saw_content: bool = False
|
|
117
|
+
saw_reasoning: bool = False
|
|
118
|
+
|
|
119
|
+
def absorb_delta(self, delta: dict[str, Any]) -> None:
|
|
120
|
+
role = delta.get("role")
|
|
121
|
+
if isinstance(role, str) and role and self.role is None:
|
|
122
|
+
self.role = role
|
|
123
|
+
|
|
124
|
+
content = delta.get("content")
|
|
125
|
+
if isinstance(content, str):
|
|
126
|
+
self.content_parts.append(content)
|
|
127
|
+
self.saw_content = True
|
|
128
|
+
elif isinstance(content, list):
|
|
129
|
+
# Some upstreams stream structured content parts instead of plain text.
|
|
130
|
+
for part in content:
|
|
131
|
+
if isinstance(part, dict) and isinstance(part.get("text"), str):
|
|
132
|
+
self.content_parts.append(part["text"])
|
|
133
|
+
self.saw_content = True
|
|
134
|
+
|
|
135
|
+
for key in _REASONING_DELTA_KEYS:
|
|
136
|
+
value = delta.get(key)
|
|
137
|
+
if isinstance(value, str):
|
|
138
|
+
self.reasoning_parts.append(value)
|
|
139
|
+
self.saw_reasoning = True
|
|
140
|
+
|
|
141
|
+
calls = delta.get("tool_calls")
|
|
142
|
+
if isinstance(calls, list):
|
|
143
|
+
for position, call in enumerate(calls):
|
|
144
|
+
if not isinstance(call, dict):
|
|
145
|
+
continue
|
|
146
|
+
raw_index = call.get("index")
|
|
147
|
+
index = raw_index if isinstance(raw_index, int) else position
|
|
148
|
+
self.tool_calls.setdefault(index, _ToolCallAccumulator(index=index)).absorb(call)
|
|
149
|
+
|
|
150
|
+
def to_dict(self) -> dict[str, Any]:
|
|
151
|
+
message: dict[str, Any] = {"role": self.role or "assistant"}
|
|
152
|
+
message["content"] = "".join(self.content_parts) if self.saw_content else None
|
|
153
|
+
if self.saw_reasoning:
|
|
154
|
+
message["reasoning_content"] = "".join(self.reasoning_parts)
|
|
155
|
+
if self.tool_calls:
|
|
156
|
+
message["tool_calls"] = [
|
|
157
|
+
self.tool_calls[index].to_dict() for index in sorted(self.tool_calls)
|
|
158
|
+
]
|
|
159
|
+
return {
|
|
160
|
+
"index": self.index,
|
|
161
|
+
"message": message,
|
|
162
|
+
"finish_reason": self.finish_reason,
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _split_frames(chunks: list[Any]) -> tuple[list[dict[str, Any]], int]:
|
|
167
|
+
"""Separate parseable frames from ones the relay could not decode."""
|
|
168
|
+
frames: list[dict[str, Any]] = []
|
|
169
|
+
malformed = 0
|
|
170
|
+
for chunk in chunks:
|
|
171
|
+
if isinstance(chunk, dict):
|
|
172
|
+
frames.append(chunk)
|
|
173
|
+
else:
|
|
174
|
+
malformed += 1
|
|
175
|
+
return frames, malformed
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _availability(*, terminated: bool, malformed: int) -> tuple[str, str | None]:
|
|
179
|
+
reasons: list[str] = []
|
|
180
|
+
if not terminated:
|
|
181
|
+
reasons.append("stream ended without a terminating frame")
|
|
182
|
+
if malformed:
|
|
183
|
+
reasons.append(f"{malformed} unparseable frame(s) observed")
|
|
184
|
+
if reasons:
|
|
185
|
+
return CAPTURE_INTERRUPTED, "; ".join(reasons)
|
|
186
|
+
return AVAILABLE, None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def assemble_openai_chat_stream(chunks: list[Any]) -> AssembledStream:
|
|
190
|
+
"""Rebuild an OpenAI-compatible chat completion from its delta frames."""
|
|
191
|
+
frames, malformed = _split_frames(chunks)
|
|
192
|
+
choices: dict[int, _ChoiceAccumulator] = {}
|
|
193
|
+
envelope: dict[str, Any] = {}
|
|
194
|
+
usage: Any = None
|
|
195
|
+
terminated = False
|
|
196
|
+
|
|
197
|
+
for frame in frames:
|
|
198
|
+
for key in ("id", "model", "system_fingerprint", "created"):
|
|
199
|
+
value = frame.get(key)
|
|
200
|
+
if key not in envelope and value is not None:
|
|
201
|
+
envelope[key] = value
|
|
202
|
+
frame_usage = frame.get("usage")
|
|
203
|
+
if isinstance(frame_usage, dict) and frame_usage:
|
|
204
|
+
usage = frame_usage
|
|
205
|
+
|
|
206
|
+
raw_choices = frame.get("choices")
|
|
207
|
+
if not isinstance(raw_choices, list):
|
|
208
|
+
continue
|
|
209
|
+
for position, raw_choice in enumerate(raw_choices):
|
|
210
|
+
if not isinstance(raw_choice, dict):
|
|
211
|
+
continue
|
|
212
|
+
raw_index = raw_choice.get("index")
|
|
213
|
+
index = raw_index if isinstance(raw_index, int) else position
|
|
214
|
+
choice = choices.setdefault(index, _ChoiceAccumulator(index=index))
|
|
215
|
+
delta = raw_choice.get("delta")
|
|
216
|
+
if isinstance(delta, dict):
|
|
217
|
+
choice.absorb_delta(delta)
|
|
218
|
+
finish_reason = raw_choice.get("finish_reason")
|
|
219
|
+
if finish_reason is not None:
|
|
220
|
+
choice.finish_reason = finish_reason
|
|
221
|
+
terminated = True
|
|
222
|
+
|
|
223
|
+
response: dict[str, Any] = dict(envelope)
|
|
224
|
+
response["object"] = "chat.completion"
|
|
225
|
+
response["choices"] = [choices[index].to_dict() for index in sorted(choices)]
|
|
226
|
+
if usage is not None:
|
|
227
|
+
response["usage"] = usage
|
|
228
|
+
|
|
229
|
+
availability, notes = _availability(terminated=terminated, malformed=malformed)
|
|
230
|
+
return AssembledStream(
|
|
231
|
+
response=response,
|
|
232
|
+
wire_format=OPENAI_CHAT_DELTA,
|
|
233
|
+
chunk_count=len(chunks),
|
|
234
|
+
malformed_chunks=malformed,
|
|
235
|
+
terminated=terminated,
|
|
236
|
+
availability=availability,
|
|
237
|
+
notes=notes,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def assemble_ollama_stream(chunks: list[Any]) -> AssembledStream:
|
|
242
|
+
"""Rebuild an Ollama chat or generate response from its ndjson frames."""
|
|
243
|
+
frames, malformed = _split_frames(chunks)
|
|
244
|
+
response: dict[str, Any] = {}
|
|
245
|
+
message_content: list[str] = []
|
|
246
|
+
message_thinking: list[str] = []
|
|
247
|
+
generate_parts: list[str] = []
|
|
248
|
+
tool_calls: list[Any] = []
|
|
249
|
+
role: str | None = None
|
|
250
|
+
saw_message = False
|
|
251
|
+
saw_generate = False
|
|
252
|
+
terminated = False
|
|
253
|
+
|
|
254
|
+
for frame in frames:
|
|
255
|
+
for key in ("model", "created_at"):
|
|
256
|
+
value = frame.get(key)
|
|
257
|
+
if key not in response and value is not None:
|
|
258
|
+
response[key] = value
|
|
259
|
+
|
|
260
|
+
message = frame.get("message")
|
|
261
|
+
if isinstance(message, dict):
|
|
262
|
+
saw_message = True
|
|
263
|
+
frame_role = message.get("role")
|
|
264
|
+
if isinstance(frame_role, str) and frame_role and role is None:
|
|
265
|
+
role = frame_role
|
|
266
|
+
content = message.get("content")
|
|
267
|
+
if isinstance(content, str):
|
|
268
|
+
message_content.append(content)
|
|
269
|
+
thinking = message.get("thinking")
|
|
270
|
+
if isinstance(thinking, str):
|
|
271
|
+
message_thinking.append(thinking)
|
|
272
|
+
calls = message.get("tool_calls")
|
|
273
|
+
if isinstance(calls, list):
|
|
274
|
+
# Ollama emits whole tool calls rather than argument fragments.
|
|
275
|
+
tool_calls.extend(calls)
|
|
276
|
+
|
|
277
|
+
generated = frame.get("response")
|
|
278
|
+
if isinstance(generated, str):
|
|
279
|
+
saw_generate = True
|
|
280
|
+
generate_parts.append(generated)
|
|
281
|
+
|
|
282
|
+
if frame.get("done") is True:
|
|
283
|
+
terminated = True
|
|
284
|
+
for key, value in frame.items():
|
|
285
|
+
if key in {"message", "response", "model", "created_at"}:
|
|
286
|
+
continue
|
|
287
|
+
response[key] = value
|
|
288
|
+
|
|
289
|
+
if saw_message:
|
|
290
|
+
message_payload: dict[str, Any] = {
|
|
291
|
+
"role": role or "assistant",
|
|
292
|
+
"content": "".join(message_content),
|
|
293
|
+
}
|
|
294
|
+
if message_thinking:
|
|
295
|
+
message_payload["thinking"] = "".join(message_thinking)
|
|
296
|
+
if tool_calls:
|
|
297
|
+
message_payload["tool_calls"] = tool_calls
|
|
298
|
+
response["message"] = message_payload
|
|
299
|
+
if saw_generate:
|
|
300
|
+
response["response"] = "".join(generate_parts)
|
|
301
|
+
response.setdefault("done", terminated)
|
|
302
|
+
|
|
303
|
+
availability, notes = _availability(terminated=terminated, malformed=malformed)
|
|
304
|
+
return AssembledStream(
|
|
305
|
+
response=response,
|
|
306
|
+
wire_format=OLLAMA_NDJSON,
|
|
307
|
+
chunk_count=len(chunks),
|
|
308
|
+
malformed_chunks=malformed,
|
|
309
|
+
terminated=terminated,
|
|
310
|
+
availability=availability,
|
|
311
|
+
notes=notes,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def assemble_stream(chunks: list[Any], *, wire_format: str) -> AssembledStream:
|
|
316
|
+
if wire_format == OPENAI_CHAT_DELTA:
|
|
317
|
+
return assemble_openai_chat_stream(chunks)
|
|
318
|
+
if wire_format == OLLAMA_NDJSON:
|
|
319
|
+
return assemble_ollama_stream(chunks)
|
|
320
|
+
raise ValueError(f"unsupported stream wire format: {wire_format}")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def assembled_tool_calls(response: dict[str, Any]) -> list[Any]:
|
|
324
|
+
"""Return whole tool calls from an assembled response.
|
|
325
|
+
|
|
326
|
+
Walking raw frames instead would publish one fragment per frame, so a single
|
|
327
|
+
call split across frames would surface as several partial calls.
|
|
328
|
+
"""
|
|
329
|
+
|
|
330
|
+
calls: list[Any] = []
|
|
331
|
+
for choice in response.get("choices") or []:
|
|
332
|
+
if not isinstance(choice, dict):
|
|
333
|
+
continue
|
|
334
|
+
message = choice.get("message")
|
|
335
|
+
if isinstance(message, dict) and isinstance(message.get("tool_calls"), list):
|
|
336
|
+
calls.extend(message["tool_calls"])
|
|
337
|
+
message = response.get("message")
|
|
338
|
+
if isinstance(message, dict) and isinstance(message.get("tool_calls"), list):
|
|
339
|
+
calls.extend(message["tool_calls"])
|
|
340
|
+
return calls
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def arguments_parse_cleanly(response: dict[str, Any]) -> bool:
|
|
344
|
+
"""Whether every assembled tool-call argument string is valid JSON.
|
|
345
|
+
|
|
346
|
+
Reported as an observation. A stream that ended early leaves a truncated
|
|
347
|
+
argument string, and that fact belongs in the record rather than being hidden.
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
for call in assembled_tool_calls(response):
|
|
351
|
+
if not isinstance(call, dict):
|
|
352
|
+
continue
|
|
353
|
+
function = call.get("function")
|
|
354
|
+
if not isinstance(function, dict):
|
|
355
|
+
continue
|
|
356
|
+
arguments = function.get("arguments")
|
|
357
|
+
if not isinstance(arguments, str) or not arguments:
|
|
358
|
+
continue
|
|
359
|
+
try:
|
|
360
|
+
json.loads(arguments)
|
|
361
|
+
except json.JSONDecodeError:
|
|
362
|
+
return False
|
|
363
|
+
return True
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Operator-selected artifact versions associated with an external report.
|
|
2
|
+
|
|
3
|
+
Only explicit NAME=FILE arguments authorize reads. Names inside imported reports
|
|
4
|
+
are never filesystem capabilities. This is neither an execution attestation nor
|
|
5
|
+
an atomic snapshot of a directory changing concurrently with these reads.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import stat
|
|
16
|
+
import unicodedata
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from typing import Any, Iterator, BinaryIO
|
|
20
|
+
|
|
21
|
+
FORMAT = "execweave.selected-artifact-versions.v1"
|
|
22
|
+
RECEIPT_FORMAT = "execweave.external-task-report.v2"
|
|
23
|
+
MAX_FILES = 100
|
|
24
|
+
MAX_FILE_BYTES = 8 * 1024 * 1024
|
|
25
|
+
MAX_TOTAL_BYTES = 64 * 1024 * 1024
|
|
26
|
+
_RESERVED = re.compile(r"^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)", re.I)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def artifact_name(value: Any) -> str:
|
|
30
|
+
"""Require an unambiguous portable relative name, never normalize silently."""
|
|
31
|
+
if not isinstance(value, str) or not value or len(value) > 512:
|
|
32
|
+
raise ValueError("artifact name must contain 1 to 512 characters")
|
|
33
|
+
if (
|
|
34
|
+
unicodedata.normalize("NFC", value) != value
|
|
35
|
+
or any(ord(c) < 32 or ord(c) == 127 or 0xD800 <= ord(c) <= 0xDFFF for c in value)
|
|
36
|
+
or any(c in value for c in '\\:*?"<>|')
|
|
37
|
+
):
|
|
38
|
+
raise ValueError("artifact name is not portable NFC text")
|
|
39
|
+
if any(
|
|
40
|
+
not p or p in (".", "..") or p.endswith((" ", ".")) or _RESERVED.match(p)
|
|
41
|
+
for p in value.split("/")
|
|
42
|
+
):
|
|
43
|
+
raise ValueError("artifact name must be a portable relative path")
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def manifest_bytes(entries: list[dict[str, Any]]) -> bytes:
|
|
48
|
+
"""Stable array encoding shared with the browser; no object key ordering."""
|
|
49
|
+
return json.dumps(
|
|
50
|
+
[[r["path"], r["size_bytes"], r["sha256"]] for r in entries],
|
|
51
|
+
ensure_ascii=False,
|
|
52
|
+
allow_nan=False,
|
|
53
|
+
separators=(",", ":"),
|
|
54
|
+
).encode("utf-8")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def validate_manifest(value: Any) -> dict[str, Any]:
|
|
58
|
+
if not isinstance(value, dict) or value.get("format") != FORMAT:
|
|
59
|
+
raise ValueError("unsupported artifact manifest")
|
|
60
|
+
entries = value.get("entries")
|
|
61
|
+
if not isinstance(entries, list) or not 1 <= len(entries) <= MAX_FILES:
|
|
62
|
+
raise ValueError("artifact manifest requires 1 to 100 explicit files")
|
|
63
|
+
seen: set[str] = set()
|
|
64
|
+
clean = []
|
|
65
|
+
total = 0
|
|
66
|
+
for item in entries:
|
|
67
|
+
if not isinstance(item, dict):
|
|
68
|
+
raise ValueError("invalid artifact entry")
|
|
69
|
+
name = artifact_name(item.get("path"))
|
|
70
|
+
folded = name.lower()
|
|
71
|
+
if folded in seen:
|
|
72
|
+
raise ValueError("duplicate or case-colliding artifact name")
|
|
73
|
+
seen.add(folded)
|
|
74
|
+
size, digest = item.get("size_bytes"), item.get("sha256")
|
|
75
|
+
if type(size) is not int or not 0 <= size <= MAX_FILE_BYTES:
|
|
76
|
+
raise ValueError("artifact file exceeds 8 MiB or has an invalid size")
|
|
77
|
+
if not isinstance(digest, str) or not re.fullmatch("[a-f0-9]{64}", digest):
|
|
78
|
+
raise ValueError("invalid artifact digest")
|
|
79
|
+
total += size
|
|
80
|
+
if total > MAX_TOTAL_BYTES:
|
|
81
|
+
raise ValueError("artifact inventory exceeds 64 MiB")
|
|
82
|
+
clean.append({"path": name, "size_bytes": size, "sha256": digest})
|
|
83
|
+
expected = hashlib.sha256(manifest_bytes(clean)).hexdigest()
|
|
84
|
+
if value.get("manifest_sha256") != expected:
|
|
85
|
+
raise ValueError("artifact manifest hash mismatch")
|
|
86
|
+
return {"format": FORMAT, "entries": clean, "manifest_sha256": expected}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _signature(s: os.stat_result) -> tuple[int, ...]:
|
|
90
|
+
return (s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@contextmanager
|
|
94
|
+
def _selected_handle(path: str) -> Iterator[BinaryIO]:
|
|
95
|
+
"""Open only an explicitly selected regular, non-reparse leaf."""
|
|
96
|
+
info = os.lstat(path)
|
|
97
|
+
if not stat.S_ISREG(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
|
|
98
|
+
raise ValueError("selected artifact must be a regular file without links")
|
|
99
|
+
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
|
100
|
+
flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
101
|
+
fd = os.open(path, flags)
|
|
102
|
+
try:
|
|
103
|
+
handle = os.fdopen(fd, "rb")
|
|
104
|
+
except BaseException:
|
|
105
|
+
os.close(fd)
|
|
106
|
+
raise
|
|
107
|
+
with handle:
|
|
108
|
+
yield handle
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _capture_selected(handle: BinaryIO) -> tuple[os.stat_result, bytes]:
|
|
112
|
+
"""Bound one read and check exact descriptor metadata on both sides."""
|
|
113
|
+
before = os.fstat(handle.fileno())
|
|
114
|
+
if not stat.S_ISREG(before.st_mode) or getattr(before, "st_file_attributes", 0) & 0x400:
|
|
115
|
+
raise ValueError("selected artifact must be a regular file without links")
|
|
116
|
+
if before.st_size < 0 or before.st_size > MAX_FILE_BYTES:
|
|
117
|
+
raise ValueError("selected artifact must be at most 8 MiB")
|
|
118
|
+
payload = handle.read(MAX_FILE_BYTES + 1)
|
|
119
|
+
after = os.fstat(handle.fileno())
|
|
120
|
+
if len(payload) != before.st_size or _signature(before) != _signature(after):
|
|
121
|
+
raise ValueError("selected artifact changed while reading")
|
|
122
|
+
return before, payload
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _read_selected(path: str) -> bytes:
|
|
126
|
+
# Metadata alone cannot reveal every same-size rewrite on coarse/overlay
|
|
127
|
+
# filesystems. Compare actual bounded observations as well, never silently
|
|
128
|
+
# retry a changed file and certify its latest contents instead.
|
|
129
|
+
with _selected_handle(path) as initial:
|
|
130
|
+
before, payload = _capture_selected(initial)
|
|
131
|
+
with _selected_handle(path) as handle:
|
|
132
|
+
opened, observed = _capture_selected(handle)
|
|
133
|
+
if _signature(before) != _signature(opened) or payload != observed:
|
|
134
|
+
raise ValueError("selected artifact changed before reading")
|
|
135
|
+
del observed
|
|
136
|
+
# Reopen the name while the data handle stays alive. The archive helper
|
|
137
|
+
# remains unchanged; this extra read is only for explicitly selected files.
|
|
138
|
+
with _selected_handle(path) as final:
|
|
139
|
+
reopened, observed = _capture_selected(final)
|
|
140
|
+
if (
|
|
141
|
+
_signature(before) != _signature(reopened)
|
|
142
|
+
or _signature(opened) != _signature(os.fstat(handle.fileno()))
|
|
143
|
+
or payload != observed
|
|
144
|
+
):
|
|
145
|
+
raise ValueError("selected artifact changed while reading")
|
|
146
|
+
# Equal observations are not an atomic snapshot or proof of no transient
|
|
147
|
+
# changes between reads. The caller hashes/evaluates this exact byte buffer.
|
|
148
|
+
return payload
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def bind_artifacts(receipt: dict[str, Any], selections: list[str]) -> dict[str, Any]:
|
|
152
|
+
"""Associate selected bytes without claiming the report tested those bytes."""
|
|
153
|
+
if receipt.get("format") != "execweave.external-task-report.v1":
|
|
154
|
+
raise ValueError("expected an unbound v1 external report receipt")
|
|
155
|
+
if not 1 <= len(selections) <= MAX_FILES:
|
|
156
|
+
raise ValueError("select 1 to 100 artifacts")
|
|
157
|
+
parsed = []
|
|
158
|
+
seen = set()
|
|
159
|
+
for selection in selections:
|
|
160
|
+
if not isinstance(selection, str) or "=" not in selection:
|
|
161
|
+
raise ValueError("use --artifact RELATIVE_NAME=LOCAL_FILE")
|
|
162
|
+
name, path = selection.split("=", 1)
|
|
163
|
+
artifact_name(name)
|
|
164
|
+
if not path or name.lower() in seen:
|
|
165
|
+
raise ValueError("empty artifact path or duplicate/case-colliding name")
|
|
166
|
+
seen.add(name.lower())
|
|
167
|
+
parsed.append((name, path))
|
|
168
|
+
# Validate the whole selection first. Never infer further files from XML.
|
|
169
|
+
entries = []
|
|
170
|
+
total = 0
|
|
171
|
+
for name, path in sorted(parsed, key=lambda pair: pair[0].encode("utf-8")):
|
|
172
|
+
payload = _read_selected(str(Path(path)))
|
|
173
|
+
total += len(payload)
|
|
174
|
+
if total > MAX_TOTAL_BYTES:
|
|
175
|
+
raise ValueError("selected artifacts exceed 64 MiB")
|
|
176
|
+
entries.append(
|
|
177
|
+
{
|
|
178
|
+
"path": name,
|
|
179
|
+
"size_bytes": len(payload),
|
|
180
|
+
"sha256": hashlib.sha256(payload).hexdigest(),
|
|
181
|
+
}
|
|
182
|
+
)
|
|
183
|
+
manifest = {
|
|
184
|
+
"format": FORMAT,
|
|
185
|
+
"entries": entries,
|
|
186
|
+
"manifest_sha256": hashlib.sha256(manifest_bytes(entries)).hexdigest(),
|
|
187
|
+
}
|
|
188
|
+
validate_manifest(manifest)
|
|
189
|
+
result = copy.deepcopy(receipt)
|
|
190
|
+
result["format"] = RECEIPT_FORMAT
|
|
191
|
+
result["artifacts"] = manifest
|
|
192
|
+
return result
|