agent-bios 0.19.4 → 0.20.0
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.
- package/DEPENDENCIES.md +19 -5
- package/README.md +14 -19
- package/claude/agents/frontier.md +1 -1
- package/claude/guides/claude-prompting.md +475 -234
- package/claude/guides/cli-multi-model-workflow.md +4 -3
- package/claude/guides/gpt-prompting.md +235 -136
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +4 -3
- package/codex/guides/gpt-prompting.md +235 -136
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/docs/advanced-launch.md +4 -0
- package/docs/releases/0.20.0.md +102 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +17 -7
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +36 -3
- package/provenance.json +1 -1
- package/session-cost.py +80 -9
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7939 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +38 -7
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,1199 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The capture mode of codex-run.sh: what one `codex exec` call showed about itself, kept
|
|
3
|
+
without the prompt or the output.
|
|
4
|
+
|
|
5
|
+
codex-cli 0.163.0 reports the model that answered only on its websocket frames, and those
|
|
6
|
+
appear only on stderr under `RUST_LOG=tungstenite::protocol=trace` (unsupported and
|
|
7
|
+
version-bound); the per-request usage arrives there and on the `codex_otel.log_only` INFO
|
|
8
|
+
rows, and retries on `codex_core::responses_retry` warnings. This helper keeps an allow-list
|
|
9
|
+
of that evidence and drops everything else, so the capture holds no prompt or output text.
|
|
10
|
+
|
|
11
|
+
filter codex's stderr on stdin. Every line passes through to stderr unchanged (the
|
|
12
|
+
adapter's channel, which a supervisor may read live); the reduced records go to
|
|
13
|
+
--frames: the root thread, each client `response.create` frame's turn metadata
|
|
14
|
+
(request kind, thread, agent, parent, previous response, cache key, model,
|
|
15
|
+
effort), each server frame that carries a response (id, model, status, generate,
|
|
16
|
+
incomplete_details, error, reasoning effort, usage), rate-limit, error and
|
|
17
|
+
refusal frames by type, the otel request, websocket and `codex.sse_event`
|
|
18
|
+
created/completed rows (token counts, thread, model, status, attempt,
|
|
19
|
+
endpoint), and each responses_retry warning by its instant.
|
|
20
|
+
events codex's `--json` stdout on stdin; keeps the thread and turn events and the
|
|
21
|
+
top-level errors, drops every item event (they carry the answer).
|
|
22
|
+
context before the call, with the call's own homes, working directory and overrides:
|
|
23
|
+
the working directory's listing, `codex debug prompt-input` (prompt-input.txt)
|
|
24
|
+
and `codex app-server` thread/start's instruction sources
|
|
25
|
+
(instruction-sources.json). A rendering that fails refuses the call.
|
|
26
|
+
finish after the call: host.json (the effective context, profile, flag-set hash,
|
|
27
|
+
working directory, thread id), usage.json (the requests joined to the otel
|
|
28
|
+
completion ledger, the attempts per thread, the observed seats), and the
|
|
29
|
+
receipt evidence as key=value lines on stdout.
|
|
30
|
+
|
|
31
|
+
The reduction and the capture-side summary have one owner, this file. A reader of a capture
|
|
32
|
+
imports these rather than re-deriving them: reduce_lines (trace -> records), reduce_event
|
|
33
|
+
(--json event -> kept form), summarize (usage.json's requests, attempts, observed seats and what
|
|
34
|
+
cannot be attested), attempts, responses, completions, join.
|
|
35
|
+
|
|
36
|
+
codex_frame_filter.py --self-test
|
|
37
|
+
"""
|
|
38
|
+
import argparse
|
|
39
|
+
import hashlib
|
|
40
|
+
import json
|
|
41
|
+
import os
|
|
42
|
+
import pathlib
|
|
43
|
+
import re
|
|
44
|
+
import shutil
|
|
45
|
+
import subprocess
|
|
46
|
+
import sys
|
|
47
|
+
import time
|
|
48
|
+
import zlib
|
|
49
|
+
|
|
50
|
+
RECV = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+TRACE tungstenite::protocol: Received message (\{.*\})\s*$')
|
|
51
|
+
WRITE = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+TRACE tungstenite::protocol::frame: writing frame')
|
|
52
|
+
STAMPED = re.compile(r'^\d{4}-\d\d-\d\dT[\d:.]+Z\s')
|
|
53
|
+
OTEL = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+INFO\s+.*?codex_otel\.log_only: (.*)$')
|
|
54
|
+
# a warning is printed inside the turn's spans (`WARN session_loop{..}:turn{..}: codex_core::...`)
|
|
55
|
+
RETRY = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+WARN\s+.*?codex_core::responses_retry: ')
|
|
56
|
+
# key=value pairs, a quoted value read to its closing quote past any escaped one
|
|
57
|
+
KV = re.compile(r'([A-Za-z_.]+)=("(?:[^"\\]|\\.)*"|[^\s"]+)')
|
|
58
|
+
ROOT_THREAD = re.compile(r'codex\.exec\{[^}]*thread\.id="([0-9a-f-]{36})"')
|
|
59
|
+
OTEL_KEYS = ("event.name", "event.kind", "input_token_count", "output_token_count", "cached_token_count",
|
|
60
|
+
"cache_write_token_count", "conversation.id", "model", "http.response.status_code", "attempt", "endpoint")
|
|
61
|
+
# The shape each kept otel value must have; a value of any other shape is not kept.
|
|
62
|
+
_COUNT, _NAME = re.compile(r"^\d{1,12}$"), re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,79}$")
|
|
63
|
+
OTEL_SHAPES = {"event.name": _NAME, "event.kind": _NAME, "input_token_count": _COUNT, "output_token_count": _COUNT,
|
|
64
|
+
"cached_token_count": _COUNT, "cache_write_token_count": _COUNT, "conversation.id": re.compile(r"^[0-9a-f-]{8,64}$"),
|
|
65
|
+
"model": _NAME, "http.response.status_code": _COUNT, "attempt": _COUNT,
|
|
66
|
+
"endpoint": re.compile(r"^/[A-Za-z0-9/_.-]{0,79}$")}
|
|
67
|
+
OTEL_KEPT = {"codex.websocket_request", "codex.websocket_connect", "codex.api_request"}
|
|
68
|
+
SSE_KINDS = ("response.created", "response.completed")
|
|
69
|
+
RESP_KEYS = ("id", "model", "status", "generate", "previous_response_id", "prompt_cache_key", "incomplete_details", "error")
|
|
70
|
+
EVENT_TYPES = ("thread.started", "turn.started", "turn.completed", "turn.failed", "error")
|
|
71
|
+
# The channel each RUST_LOG directive opens, and the level it needs.
|
|
72
|
+
CHANNELS = (("frames", "tungstenite::protocol", "trace"), ("otel", "codex_otel.log_only", "info"),
|
|
73
|
+
("responses_retry", "codex_core::responses_retry", "warn"))
|
|
74
|
+
LEVELS = ("off", "error", "warn", "info", "debug", "trace")
|
|
75
|
+
# The receipt evidence a call carries (the gate's key set; the launcher owns the top-level fields).
|
|
76
|
+
EVIDENCE_KEYS = ("call_id", "schema_sha256", "payload_sha256", "seat_observed", "profile", "profile_flags_sha256",
|
|
77
|
+
"cwd", "manifest_sha256", "context_observed_sha256", "usage_state", "usage_totals",
|
|
78
|
+
"capture_sha256", "session_id", "hermeticity")
|
|
79
|
+
# What a Codex capture states for the receipt's hermeticity (contract record 2026-11-02, F-31): the
|
|
80
|
+
# assessment of managed and server-delivered settings is the hermetic Claude call's; a Codex call's
|
|
81
|
+
# context evidence is its prompt-input rendering and instructionSources.
|
|
82
|
+
HERMETICITY = {"assessed": False, "reason": "hermeticity is assessed for hermetic Claude calls (D-20261102-252c92); a "
|
|
83
|
+
"Codex call's context evidence is its prompt-input rendering and "
|
|
84
|
+
"instructionSources"}
|
|
85
|
+
PAYLOAD_MARKER = "=== PAYLOAD ==="
|
|
86
|
+
TOKEN_KEYS = ("input", "output", "cache_read", "cache_creation")
|
|
87
|
+
CONTEXT_SETS = ("instructions", "appended_prompts", "skills", "agents", "hooks")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def canonical(obj):
|
|
91
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def canonical_sha256(obj):
|
|
95
|
+
return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def file_sha256(path):
|
|
99
|
+
with open(path, "rb") as handle:
|
|
100
|
+
return hashlib.sha256(handle.read()).hexdigest()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def channels(rust_log):
|
|
104
|
+
"""The capture channels a RUST_LOG value opens: a directive for the target (or a parent
|
|
105
|
+
module of it), or a bare default level, at the level the channel needs or finer."""
|
|
106
|
+
directives = [d.strip() for d in (rust_log or "").split(",") if d.strip()]
|
|
107
|
+
opened = []
|
|
108
|
+
for name, target, need in CHANNELS:
|
|
109
|
+
level = None
|
|
110
|
+
for d in directives:
|
|
111
|
+
where, _, what = d.rpartition("=")
|
|
112
|
+
if not where and what in LEVELS:
|
|
113
|
+
level = level or what
|
|
114
|
+
elif where and (target == where or target.startswith(where + "::")) and what in LEVELS:
|
|
115
|
+
level = what
|
|
116
|
+
if level is not None and LEVELS.index(level) >= LEVELS.index(need):
|
|
117
|
+
opened.append(name)
|
|
118
|
+
return opened
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# --- filter: codex stderr -> reduced records ----------------------------------------------
|
|
122
|
+
|
|
123
|
+
class SentDecoder:
|
|
124
|
+
"""Client frames are permessage-deflate with context takeover, one raw-deflate stream per
|
|
125
|
+
websocket connection, and the trace does not say which connection wrote a frame: a frame
|
|
126
|
+
is inflated against every live context and a fresh one; the context whose last response
|
|
127
|
+
is the frame's previous_response_id wins, else a fresh context for a warm-up or another
|
|
128
|
+
thread, else the context of the same thread."""
|
|
129
|
+
|
|
130
|
+
def __init__(self):
|
|
131
|
+
self.ctx = []
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def meta(j):
|
|
135
|
+
try:
|
|
136
|
+
return json.loads((j.get("client_metadata") or {}).get("x-codex-turn-metadata") or "{}")
|
|
137
|
+
except ValueError:
|
|
138
|
+
return {}
|
|
139
|
+
|
|
140
|
+
def decode(self, payload):
|
|
141
|
+
data = payload + b"\x00\x00\xff\xff"
|
|
142
|
+
candidates = []
|
|
143
|
+
for i, c in enumerate(self.ctx):
|
|
144
|
+
try:
|
|
145
|
+
copy = c["obj"].copy()
|
|
146
|
+
candidates.append((i, copy, json.loads(copy.decompress(data))))
|
|
147
|
+
except (zlib.error, ValueError):
|
|
148
|
+
continue
|
|
149
|
+
fresh = None
|
|
150
|
+
try:
|
|
151
|
+
copy = zlib.decompressobj(-15)
|
|
152
|
+
fresh = (None, copy, json.loads(copy.decompress(data)))
|
|
153
|
+
except (zlib.error, ValueError):
|
|
154
|
+
pass
|
|
155
|
+
exact = [c for c in candidates if c[2].get("previous_response_id") and c[2]["previous_response_id"] == self.ctx[c[0]]["last"]]
|
|
156
|
+
pick = exact[0] if exact else None
|
|
157
|
+
if pick is None and fresh is not None:
|
|
158
|
+
m = self.meta(fresh[2])
|
|
159
|
+
same = [c for c in candidates if self.ctx[c[0]]["thread"] and self.ctx[c[0]]["thread"] == m.get("thread_id")]
|
|
160
|
+
pick = fresh if m.get("request_kind") == "prewarm" or not same else same[0]
|
|
161
|
+
if pick is None and candidates:
|
|
162
|
+
pick = candidates[0]
|
|
163
|
+
if pick is None:
|
|
164
|
+
return None, None
|
|
165
|
+
i, copy, j = pick
|
|
166
|
+
if i is None:
|
|
167
|
+
self.ctx.append({"obj": copy, "thread": self.meta(j).get("thread_id"), "last": None})
|
|
168
|
+
i = len(self.ctx) - 1
|
|
169
|
+
else:
|
|
170
|
+
self.ctx[i]["obj"] = copy
|
|
171
|
+
return j, i
|
|
172
|
+
|
|
173
|
+
def note(self, i, response_id):
|
|
174
|
+
if i is not None and 0 <= i < len(self.ctx):
|
|
175
|
+
self.ctx[i]["last"] = response_id
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class Reducer:
|
|
179
|
+
"""Trace lines in, whitelisted records out (`emit`)."""
|
|
180
|
+
|
|
181
|
+
def __init__(self, emit):
|
|
182
|
+
self.emit, self.dec, self.pending, self.root, self.by_cache = emit, SentDecoder(), None, None, {}
|
|
183
|
+
|
|
184
|
+
def line(self, text):
|
|
185
|
+
text = text.rstrip("\n")
|
|
186
|
+
if self.root is None and ROOT_THREAD.search(text):
|
|
187
|
+
self.root = ROOT_THREAD.search(text).group(1)
|
|
188
|
+
self.emit({"dir": "info", "type": "root_thread", "thread": self.root})
|
|
189
|
+
if self.pending is not None:
|
|
190
|
+
if text.startswith("opcode:"):
|
|
191
|
+
self.pending["opcode"] = text.split(":", 1)[1].strip()
|
|
192
|
+
return
|
|
193
|
+
if text.startswith("reserved:"):
|
|
194
|
+
self.pending["deflated"] = text.split(":", 1)[1].split()[:1] == ["true"]
|
|
195
|
+
return
|
|
196
|
+
if text.startswith("payload: 0x"):
|
|
197
|
+
held, self.pending = self.pending, None
|
|
198
|
+
if held.get("opcode", "TEXT") == "TEXT":
|
|
199
|
+
try:
|
|
200
|
+
self.sent(held, bytes.fromhex(text[len("payload: 0x"):]))
|
|
201
|
+
except ValueError:
|
|
202
|
+
self.emit({"dir": "info", "type": "undecodable_frame", "ts": held["ts"]})
|
|
203
|
+
return
|
|
204
|
+
if STAMPED.match(text):
|
|
205
|
+
self.truncated()
|
|
206
|
+
else:
|
|
207
|
+
return
|
|
208
|
+
if WRITE.match(text):
|
|
209
|
+
self.pending = {"ts": WRITE.match(text).group(1)}
|
|
210
|
+
elif OTEL.match(text):
|
|
211
|
+
m = OTEL.match(text)
|
|
212
|
+
kv = {}
|
|
213
|
+
for k, v in KV.findall(m.group(2)):
|
|
214
|
+
v = v[1:-1] if v.startswith('"') else v
|
|
215
|
+
if k in OTEL_KEYS and OTEL_SHAPES[k].match(v):
|
|
216
|
+
kv[k] = v
|
|
217
|
+
if kv.get("event.name") in OTEL_KEPT or (kv.get("event.name") == "codex.sse_event" and kv.get("event.kind") in SSE_KINDS):
|
|
218
|
+
self.emit({"dir": "otel", "ts": m.group(1), **kv})
|
|
219
|
+
elif RETRY.match(text):
|
|
220
|
+
self.emit({"dir": "warn", "type": "responses_retry", "ts": RETRY.match(text).group(1)})
|
|
221
|
+
elif RECV.match(text):
|
|
222
|
+
m = RECV.match(text)
|
|
223
|
+
try:
|
|
224
|
+
self.received(m.group(1), json.loads(m.group(2)))
|
|
225
|
+
except ValueError:
|
|
226
|
+
self.emit({"dir": "recv", "type": "unparsable", "ts": m.group(1)})
|
|
227
|
+
|
|
228
|
+
def truncated(self):
|
|
229
|
+
"""A client frame header whose payload never followed: kept as evidence of a write."""
|
|
230
|
+
held, self.pending = self.pending, None
|
|
231
|
+
if held is not None and held.get("opcode", "TEXT") == "TEXT":
|
|
232
|
+
self.emit({"dir": "info", "type": "truncated_frame", "ts": held["ts"]})
|
|
233
|
+
|
|
234
|
+
def sent(self, held, payload):
|
|
235
|
+
if held.get("deflated", True):
|
|
236
|
+
j, ctx = self.dec.decode(payload)
|
|
237
|
+
else: # no permessage-deflate negotiated
|
|
238
|
+
try:
|
|
239
|
+
j, ctx = json.loads(payload), None
|
|
240
|
+
except ValueError:
|
|
241
|
+
j, ctx = None, None
|
|
242
|
+
if not isinstance(j, dict):
|
|
243
|
+
self.emit({"dir": "info", "type": "undecodable_frame", "ts": held["ts"]})
|
|
244
|
+
return
|
|
245
|
+
if j.get("type") != "response.create":
|
|
246
|
+
return
|
|
247
|
+
m = SentDecoder.meta(j)
|
|
248
|
+
self.by_cache[(j.get("prompt_cache_key"), j.get("previous_response_id"))] = ctx
|
|
249
|
+
self.emit({"dir": "send", "type": "response.create", "ts": held["ts"], "thread_id": m.get("thread_id"),
|
|
250
|
+
"agent_name": m.get("agent_name"), "request_kind": m.get("request_kind"),
|
|
251
|
+
"parent_thread_id": m.get("parent_thread_id"), "previous_response_id": j.get("previous_response_id"),
|
|
252
|
+
"prompt_cache_key": j.get("prompt_cache_key"), "model": j.get("model"),
|
|
253
|
+
"reasoning_effort": (j.get("reasoning") or {}).get("effort")})
|
|
254
|
+
|
|
255
|
+
def received(self, ts, j):
|
|
256
|
+
kind, resp = j.get("type"), j.get("response")
|
|
257
|
+
rec = {"dir": "recv", "type": kind, "ts": ts}
|
|
258
|
+
if isinstance(resp, dict):
|
|
259
|
+
rec["response"] = {k: resp.get(k) for k in RESP_KEYS}
|
|
260
|
+
rec["response"]["error"] = codes(resp.get("error"), ("code", "type"))
|
|
261
|
+
rec["response"]["incomplete_details"] = codes(resp.get("incomplete_details"), ("reason",))
|
|
262
|
+
rec["response"]["reasoning_effort"] = (resp.get("reasoning") or {}).get("effort")
|
|
263
|
+
u = resp.get("usage") if isinstance(resp.get("usage"), dict) else None
|
|
264
|
+
rec["response"]["usage"] = None if u is None else {
|
|
265
|
+
"input_tokens": u.get("input_tokens"), "cached_tokens": (u.get("input_tokens_details") or {}).get("cached_tokens"),
|
|
266
|
+
"cache_write_tokens": (u.get("input_tokens_details") or {}).get("cache_write_tokens"),
|
|
267
|
+
"output_tokens": u.get("output_tokens"), "reasoning_tokens": (u.get("output_tokens_details") or {}).get("reasoning_tokens"),
|
|
268
|
+
"total_tokens": u.get("total_tokens")}
|
|
269
|
+
if kind == "response.created":
|
|
270
|
+
key = (resp.get("prompt_cache_key"), resp.get("previous_response_id"))
|
|
271
|
+
self.dec.note(self.by_cache.get(key), resp.get("id"))
|
|
272
|
+
elif kind == "codex.rate_limits":
|
|
273
|
+
rl = j.get("rate_limits") or {}
|
|
274
|
+
rec["rate_limits"] = {"allowed": rl.get("allowed"), "limit_reached": rl.get("limit_reached")}
|
|
275
|
+
elif kind == "error":
|
|
276
|
+
err = j.get("error") if isinstance(j.get("error"), dict) else {}
|
|
277
|
+
status = j.get("status")
|
|
278
|
+
rec["detail"] = {"status": status if isinstance(status, int) and not isinstance(status, bool) else None,
|
|
279
|
+
"error": codes(err, ("code", "type")) or {}}
|
|
280
|
+
elif not (isinstance(kind, str) and "refusal" in kind):
|
|
281
|
+
return
|
|
282
|
+
self.emit(rec)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
CODE = re.compile(r"^[a-z][a-z0-9_.-]{0,47}$")
|
|
286
|
+
DROPPED = "<dropped>"
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def codes(value, keys):
|
|
290
|
+
"""A diagnostic object reduced to its structured codes: an integer, or a lower-case code of
|
|
291
|
+
a closed shape (no whitespace, path or upper case, at most 48 characters). Any other value
|
|
292
|
+
present is replaced by DROPPED, so the failure stays visible while a message, a path or a
|
|
293
|
+
credential, which may quote the prompt or the output, never survives."""
|
|
294
|
+
if not isinstance(value, dict):
|
|
295
|
+
return None
|
|
296
|
+
out = {}
|
|
297
|
+
for k in keys:
|
|
298
|
+
if k not in value or value[k] is None:
|
|
299
|
+
continue
|
|
300
|
+
v = value[k]
|
|
301
|
+
out[k] = v if (isinstance(v, int) and not isinstance(v, bool)) or (isinstance(v, str) and CODE.match(v)) else DROPPED
|
|
302
|
+
return out
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def reduce_lines(lines, rust_log):
|
|
306
|
+
"""The reduced records of a trace: what `filter` stores, for any reader of a capture."""
|
|
307
|
+
out = [{"dir": "info", "type": "channels", "channels": channels(rust_log)}]
|
|
308
|
+
reducer = Reducer(out.append)
|
|
309
|
+
for line in lines:
|
|
310
|
+
reducer.line(line)
|
|
311
|
+
reducer.truncated()
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def reduce_event(event):
|
|
316
|
+
"""One `--json` event as the capture keeps it, or None: the thread id, the turn usage
|
|
317
|
+
counts, and the type of a failure — never an item, never a message."""
|
|
318
|
+
if not isinstance(event, dict) or event.get("type") not in EVENT_TYPES:
|
|
319
|
+
return None
|
|
320
|
+
kept = {"type": event["type"]}
|
|
321
|
+
if event["type"] == "thread.started":
|
|
322
|
+
kept["thread_id"] = event.get("thread_id")
|
|
323
|
+
elif event["type"] == "turn.completed" and isinstance(event.get("usage"), dict):
|
|
324
|
+
kept["usage"] = {k: v for k, v in event["usage"].items() if isinstance(v, int) and not isinstance(v, bool)}
|
|
325
|
+
return kept
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def run_filter(args):
|
|
329
|
+
out = open(args.frames, "a", encoding="utf-8", buffering=1)
|
|
330
|
+
err = sys.stderr.buffer
|
|
331
|
+
|
|
332
|
+
def emit(rec):
|
|
333
|
+
out.write(json.dumps(rec, sort_keys=True, ensure_ascii=False) + "\n")
|
|
334
|
+
emit({"dir": "info", "type": "channels", "channels": channels(args.rust_log)})
|
|
335
|
+
reducer = Reducer(emit)
|
|
336
|
+
for raw in iter(sys.stdin.buffer.readline, b""):
|
|
337
|
+
err.write(raw)
|
|
338
|
+
err.flush()
|
|
339
|
+
reducer.line(raw.decode("utf-8", "replace"))
|
|
340
|
+
reducer.truncated()
|
|
341
|
+
out.close()
|
|
342
|
+
return 0
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def run_events(args):
|
|
346
|
+
with open(args.out, "w", encoding="utf-8") as out:
|
|
347
|
+
for line in sys.stdin:
|
|
348
|
+
try:
|
|
349
|
+
kept = reduce_event(json.loads(line))
|
|
350
|
+
except ValueError:
|
|
351
|
+
continue
|
|
352
|
+
if kept is not None:
|
|
353
|
+
out.write(json.dumps(kept, sort_keys=True, ensure_ascii=False) + "\n")
|
|
354
|
+
return 0
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
# --- context: the effective context before the call ---------------------------------------
|
|
358
|
+
|
|
359
|
+
def listing(root):
|
|
360
|
+
"""[{path, sha256}] of every file under the working directory, symlinks not followed."""
|
|
361
|
+
out = []
|
|
362
|
+
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
|
363
|
+
dirnames.sort()
|
|
364
|
+
for name in sorted(filenames) + sorted(d for d in dirnames if os.path.islink(os.path.join(dirpath, d))):
|
|
365
|
+
path = os.path.join(dirpath, name)
|
|
366
|
+
rel = os.path.relpath(path, root)
|
|
367
|
+
out.append({"path": rel, "sha256": None if os.path.islink(path) else file_sha256(path)})
|
|
368
|
+
return sorted(out, key=lambda e: e["path"])
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def text_of(message):
|
|
372
|
+
content = message.get("content")
|
|
373
|
+
if isinstance(content, list):
|
|
374
|
+
return "".join(part.get("text") or "" for part in content if isinstance(part, dict))
|
|
375
|
+
return str(content)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def normaliser(**roots):
|
|
379
|
+
"""Replace each root, as given and as the host may print it (normalised, symlinks
|
|
380
|
+
resolved), with @NAME, the longest first."""
|
|
381
|
+
pairs = sorted({(form, name) for name, path in roots.items() if path
|
|
382
|
+
for form in (path, os.path.normpath(path), os.path.realpath(path))}, key=lambda p: -len(p[0]))
|
|
383
|
+
|
|
384
|
+
def norm(text):
|
|
385
|
+
for path, name in pairs:
|
|
386
|
+
text = text.replace(path, "@" + name)
|
|
387
|
+
return text
|
|
388
|
+
return norm
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def rendering_facts(messages, norm):
|
|
392
|
+
"""The instruction-bearing facts of a `codex debug prompt-input` rendering."""
|
|
393
|
+
agents = [m for m in messages if m.get("role") == "user" and text_of(m).startswith("# AGENTS.md instructions for")]
|
|
394
|
+
roots, skills = [], []
|
|
395
|
+
for m in messages:
|
|
396
|
+
text = text_of(m)
|
|
397
|
+
if m.get("role") == "developer" and "<skills_instructions>" in text:
|
|
398
|
+
roots += [norm(p) for _, p in re.findall(r"^- `(r\d+)` = `([^`]*)`", text, re.M)]
|
|
399
|
+
skills += re.findall(r"^- ([A-Za-z0-9:_.-]+): .*\(file: r\d+/", text, re.M)
|
|
400
|
+
return {"messages": len(messages), "agents_messages": [{"for": norm(text_of(m).splitlines()[0][len("# AGENTS.md instructions for "):]),
|
|
401
|
+
"sha256": hashlib.sha256(text_of(m).encode()).hexdigest()} for m in agents],
|
|
402
|
+
"skill_roots": sorted(set(roots)), "skills": sorted(set(skills))}
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
PROTOCOL = pathlib.Path(__file__).resolve().parent / "codex_protocol.py"
|
|
406
|
+
_protocol = None
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def codex_protocol():
|
|
410
|
+
"""wrappers/codex_protocol.py, loaded from beside this file, where every install puts the two
|
|
411
|
+
together: the app-server client, the per-version schema check and the result shapes."""
|
|
412
|
+
global _protocol
|
|
413
|
+
if _protocol is None:
|
|
414
|
+
import importlib.util
|
|
415
|
+
spec = importlib.util.spec_from_file_location("agent_bios_codex_protocol", PROTOCOL)
|
|
416
|
+
module = importlib.util.module_from_spec(spec)
|
|
417
|
+
spec.loader.exec_module(module)
|
|
418
|
+
_protocol = module
|
|
419
|
+
return _protocol
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def app_server_sources(codex, env, cwd, overrides, timeout=60):
|
|
423
|
+
"""`codex app-server` thread/start (ephemeral): the host's own list of instruction files. The
|
|
424
|
+
installed Codex's protocol schema is checked first (its verdict kept in the agent-bios state
|
|
425
|
+
directory when that exists), and the answer's shape before it is read. The server is read on a
|
|
426
|
+
thread: a select() on the text stream missed a response that arrived in one write with a
|
|
427
|
+
notification, and waited out the whole timeout."""
|
|
428
|
+
try:
|
|
429
|
+
protocol = codex_protocol()
|
|
430
|
+
except OSError as exc:
|
|
431
|
+
return {"instructionSources": None, "error": f"the app-server protocol module is missing beside the helper "
|
|
432
|
+
f"({PROTOCOL}): {exc}"}
|
|
433
|
+
config = {key: override_value(value) for key, _, value in (kv.partition("=") for kv in overrides)}
|
|
434
|
+
state = os.environ.get("AGENT_BIOS_STATE_DIR") or os.path.join(os.path.expanduser("~"), ".local", "share", "agent-bios")
|
|
435
|
+
try:
|
|
436
|
+
protocol.ensure_schema(codex, env, os.path.join(state, "codex-protocol"))
|
|
437
|
+
client = protocol.Client([codex, "app-server", "--listen", "stdio://"], cwd=cwd, env=env)
|
|
438
|
+
try:
|
|
439
|
+
client.call("initialize", {"clientInfo": {"name": "codex-run-capture", "title": "codex-run", "version": "1"},
|
|
440
|
+
"capabilities": {"experimentalApi": True}}, timeout)
|
|
441
|
+
client.notify("initialized")
|
|
442
|
+
result = protocol.check_result("thread/start", client.call(
|
|
443
|
+
"thread/start", {"cwd": cwd, "ephemeral": True, "approvalPolicy": "never", "sandbox": "read-only",
|
|
444
|
+
"config": config or None}, timeout), "thread/start#sources")
|
|
445
|
+
finally:
|
|
446
|
+
client.close()
|
|
447
|
+
except protocol.ProtocolError as exc:
|
|
448
|
+
return {"instructionSources": None, "model": None, "cwd": None, "reasoningEffort": None, "error": str(exc)}
|
|
449
|
+
return {"instructionSources": result.get("instructionSources"), "model": result.get("model"), "cwd": result.get("cwd"),
|
|
450
|
+
"reasoningEffort": result.get("reasoningEffort"), "error": None}
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def override_value(value):
|
|
454
|
+
"""What a `-c key=value` value denotes, decoded once for every place the helper uses it (the
|
|
455
|
+
instruction hash and the app-server config), by codex's own rule: the value is parsed as
|
|
456
|
+
TOML, and one that does not parse is the raw string itself."""
|
|
457
|
+
import tomllib
|
|
458
|
+
try:
|
|
459
|
+
return tomllib.loads("v = " + value)["v"]
|
|
460
|
+
except tomllib.TOMLDecodeError:
|
|
461
|
+
return value
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
INSTRUCTION_KEY = re.compile(r"(?:^|\.)(?:developer_|base_)?instructions$")
|
|
465
|
+
INSTRUCTION_FILE_KEY = re.compile(r"instructions_file$")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def instruction_overrides(overrides):
|
|
469
|
+
"""The -c overrides that put instruction text before the model, as the context contract's
|
|
470
|
+
appended_prompts ({name, sha256} of the text, in order), and the refusals: an override
|
|
471
|
+
naming an instruction file, a value that is not a TOML string, and a key set twice (which
|
|
472
|
+
one codex keeps is its precedence, not reproduced here). A value is decoded as TOML, so a
|
|
473
|
+
basic, literal or multi-line string is hashed as the text it denotes."""
|
|
474
|
+
import tomllib
|
|
475
|
+
appended, problems, seen = [], [], set()
|
|
476
|
+
for kv in overrides:
|
|
477
|
+
key, _, value = kv.partition("=")
|
|
478
|
+
if INSTRUCTION_FILE_KEY.search(key):
|
|
479
|
+
problems.append(f"CODEX_INSTRUCTION_OVERRIDE_UNSUPPORTED {key}: an instruction file cannot be hashed as the call saw it")
|
|
480
|
+
elif INSTRUCTION_KEY.search(key):
|
|
481
|
+
if key in seen:
|
|
482
|
+
problems.append(f"CODEX_INSTRUCTION_OVERRIDE_REPEATED {key}: set more than once")
|
|
483
|
+
continue
|
|
484
|
+
seen.add(key)
|
|
485
|
+
try:
|
|
486
|
+
text = tomllib.loads("v = " + value)["v"] # a raw unparsed string is codex's, not a declared text
|
|
487
|
+
except tomllib.TOMLDecodeError:
|
|
488
|
+
text = None
|
|
489
|
+
if not isinstance(text, str) or override_value(value) != text:
|
|
490
|
+
problems.append(f"CODEX_INSTRUCTION_OVERRIDE_UNSUPPORTED {key}: the value is not a TOML string")
|
|
491
|
+
continue
|
|
492
|
+
appended.append({"name": key, "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest()})
|
|
493
|
+
return appended, problems
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def run_context(args):
|
|
497
|
+
"""The effective context, rendered by the one codex executable the call will run. The
|
|
498
|
+
rendering and the host's instruction sources are stored with the call's roots replaced by
|
|
499
|
+
@CWD, @CODEX_HOME and @HOME. They are the evidence of what reaches the model, so the
|
|
500
|
+
instruction text that does reach it is kept; the packet never is (the rendering's prompt
|
|
501
|
+
is a fixed placeholder). Evidence that cannot be had refuses the call."""
|
|
502
|
+
codex = args.codex
|
|
503
|
+
env = dict(os.environ, CODEX_HOME=args.codex_home, HOME=args.child_home)
|
|
504
|
+
env.pop("RUST_LOG", None)
|
|
505
|
+
overrides = []
|
|
506
|
+
for kv in args.config:
|
|
507
|
+
overrides += ["-c", kv]
|
|
508
|
+
norm = normaliser(CWD=args.cwd, CODEX_HOME=args.codex_home, HOME=args.child_home)
|
|
509
|
+
appended, refused = instruction_overrides(args.config)
|
|
510
|
+
for refusal in refused:
|
|
511
|
+
sys.stderr.write(f"codex-run: {refusal}\n")
|
|
512
|
+
if refused:
|
|
513
|
+
return 2
|
|
514
|
+
workdir_files = listing(args.cwd) # before any codex process runs in it
|
|
515
|
+
rendered = subprocess.run([codex, "debug", "prompt-input", *overrides, "PROMPT"], cwd=args.cwd, env=env,
|
|
516
|
+
capture_output=True, text=True, timeout=120)
|
|
517
|
+
try:
|
|
518
|
+
messages = json.loads(rendered.stdout) if rendered.returncode == 0 else None
|
|
519
|
+
except ValueError:
|
|
520
|
+
messages = None
|
|
521
|
+
if not isinstance(messages, list):
|
|
522
|
+
sys.stderr.write(f"codex-run: CONTEXT_EVIDENCE_MISSING codex debug prompt-input exited {rendered.returncode} "
|
|
523
|
+
f"without a rendering\n")
|
|
524
|
+
return 3
|
|
525
|
+
sources = app_server_sources(codex, env, args.cwd, args.config)
|
|
526
|
+
listed = sources.get("instructionSources")
|
|
527
|
+
if sources.get("error") or not isinstance(listed, list) or not all(isinstance(path, str) for path in listed):
|
|
528
|
+
# an empty list is the host saying it loads nothing; a missing one says nothing at all
|
|
529
|
+
sys.stderr.write(f"codex-run: CONTEXT_EVIDENCE_MISSING app-server thread/start named no instruction sources "
|
|
530
|
+
f"({sources.get('error')!r})\n")
|
|
531
|
+
return 3
|
|
532
|
+
with open(os.path.join(args.capture, "prompt-input.txt"), "w", encoding="utf-8") as out:
|
|
533
|
+
out.write(norm(rendered.stdout))
|
|
534
|
+
with open(os.path.join(args.capture, "instruction-sources.json"), "w", encoding="utf-8") as out:
|
|
535
|
+
out.write(norm(json.dumps(sources, indent=1, sort_keys=True)) + "\n")
|
|
536
|
+
facts = rendering_facts(messages, norm)
|
|
537
|
+
instructions = [{"path": norm(path), "kind": os.path.basename(path),
|
|
538
|
+
"sha256": file_sha256(path) if os.path.isfile(path) else None} for path in listed]
|
|
539
|
+
agents_dir = os.path.join(args.codex_home, "agents")
|
|
540
|
+
context = {"instructions": instructions, "appended_prompts": appended, "skills": facts["skills"],
|
|
541
|
+
"agents": sorted(n for n in os.listdir(agents_dir) if n.endswith(".toml")) if os.path.isdir(agents_dir) else [],
|
|
542
|
+
"hooks": ["@CODEX_HOME/hooks.json"] if os.path.isfile(os.path.join(args.codex_home, "hooks.json")) else []}
|
|
543
|
+
with open(os.path.join(args.work, "context.json"), "w", encoding="utf-8") as out:
|
|
544
|
+
json.dump({"workdir_files": workdir_files, "context": context, "codex_path": codex, "codex_version": args.version,
|
|
545
|
+
"rendering": {k: facts[k] for k in ("messages", "agents_messages", "skill_roots")}}, out, sort_keys=True)
|
|
546
|
+
return 0
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
# --- finish: usage, attestation, host record, evidence ------------------------------------
|
|
550
|
+
|
|
551
|
+
def read_jsonl(path):
|
|
552
|
+
rows = []
|
|
553
|
+
if os.path.isfile(path):
|
|
554
|
+
with open(path, encoding="utf-8") as handle:
|
|
555
|
+
for line in handle:
|
|
556
|
+
try:
|
|
557
|
+
row = json.loads(line)
|
|
558
|
+
except ValueError:
|
|
559
|
+
continue
|
|
560
|
+
if isinstance(row, dict):
|
|
561
|
+
rows.append(row)
|
|
562
|
+
return rows
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def responses(frames):
|
|
566
|
+
"""Each server response joined to the client frame that asked for it (same cache key and
|
|
567
|
+
previous response, the first unbound, only when unique), with its role and thread."""
|
|
568
|
+
sends, out, by_id = [], [], {}
|
|
569
|
+
for rec in frames:
|
|
570
|
+
if rec.get("dir") == "send" and rec.get("type") == "response.create":
|
|
571
|
+
sends.append(dict(rec, bound=False))
|
|
572
|
+
continue
|
|
573
|
+
resp = rec.get("response") if rec.get("dir") == "recv" else None
|
|
574
|
+
if not isinstance(resp, dict) or not resp.get("id"):
|
|
575
|
+
continue
|
|
576
|
+
entry = by_id.get(resp["id"])
|
|
577
|
+
if entry is None:
|
|
578
|
+
candidates = [s for s in sends if not s["bound"] and s.get("prompt_cache_key") == resp.get("prompt_cache_key")
|
|
579
|
+
and s.get("previous_response_id") == resp.get("previous_response_id")]
|
|
580
|
+
send = candidates[0] if len(candidates) == 1 else None
|
|
581
|
+
if send is not None:
|
|
582
|
+
send["bound"] = True
|
|
583
|
+
child = bool(send and (send.get("parent_thread_id") or (send.get("agent_name") or "/root") != "/root"))
|
|
584
|
+
role = None if send is None else {"prewarm": "warmup", "compaction": "compaction"}.get(
|
|
585
|
+
send.get("request_kind"), "child" if child else "main")
|
|
586
|
+
entry = {"id": resp["id"], "send": send, "ambiguous": len(candidates) > 1, "role": role,
|
|
587
|
+
"thread": (send or {}).get("thread_id") or resp.get("prompt_cache_key"), "model": None,
|
|
588
|
+
"effort": None, "terminal": None, "incomplete": None, "usage": None, "joined": False}
|
|
589
|
+
by_id[resp["id"]] = entry
|
|
590
|
+
out.append(entry)
|
|
591
|
+
entry["model"] = resp.get("model") or entry["model"]
|
|
592
|
+
entry["effort"] = resp.get("reasoning_effort") or entry["effort"]
|
|
593
|
+
if rec.get("type") in ("response.completed", "response.incomplete", "response.failed"):
|
|
594
|
+
entry["terminal"] = rec["type"].split(".", 1)[1]
|
|
595
|
+
entry["incomplete"] = resp.get("incomplete_details")
|
|
596
|
+
entry["usage"] = resp.get("usage")
|
|
597
|
+
return out
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
OTEL_PAIRS = (("input_token_count", "input_tokens"), ("output_token_count", "output_tokens"),
|
|
601
|
+
("cached_token_count", "cached_tokens"), ("cache_write_token_count", "cache_write_tokens"))
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def same_usage(comp, usage):
|
|
605
|
+
return isinstance(usage, dict) and all(
|
|
606
|
+
comp.get(otel) is None and usage.get(frame) in (None, 0) or str(usage.get(frame) or 0) == str(comp.get(otel))
|
|
607
|
+
for otel, frame in OTEL_PAIRS)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def completions(frames):
|
|
611
|
+
"""The completion ledger: otel's usage-bearing response.completed rows (the usage-less
|
|
612
|
+
row of the same name is an HTTPS stream's lifecycle row, not a completion)."""
|
|
613
|
+
return [r for r in frames if r.get("dir") == "otel" and r.get("event.name") == "codex.sse_event"
|
|
614
|
+
and r.get("event.kind") == "response.completed" and r.get("input_token_count") is not None]
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def join(frames, answered):
|
|
618
|
+
"""Per thread, the next completion joins the next completed frame response when every
|
|
619
|
+
token count agrees: (unjoined completions, ambiguous ones, completed responses no
|
|
620
|
+
completion joined)."""
|
|
621
|
+
unjoined, ambiguous, queues = [], [], {}
|
|
622
|
+
for r in answered:
|
|
623
|
+
if r["terminal"] == "completed" and isinstance(r["usage"], dict):
|
|
624
|
+
queues.setdefault(r["thread"], []).append(r)
|
|
625
|
+
for comp in completions(frames):
|
|
626
|
+
queue = [r for r in queues.get(comp.get("conversation.id"), []) if not r["joined"]]
|
|
627
|
+
if queue and same_usage(comp, queue[0]["usage"]):
|
|
628
|
+
queue[0]["joined"] = True
|
|
629
|
+
elif any(same_usage(comp, r["usage"]) for r in queues.get(comp.get("conversation.id"), [])):
|
|
630
|
+
ambiguous.append(comp)
|
|
631
|
+
else:
|
|
632
|
+
unjoined.append(comp)
|
|
633
|
+
return unjoined, ambiguous, [r for rs in queues.values() for r in rs if not r["joined"]]
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def attempts(frames):
|
|
637
|
+
"""Attempts per thread from the otel rows in order: a websocket attempt starts at
|
|
638
|
+
codex.websocket_request, an HTTPS one at its stream's response.created; a usage-bearing
|
|
639
|
+
completion completes the oldest open attempt; a usage-less one ends a websocket attempt
|
|
640
|
+
as interrupted; an HTTPS stream followed by the next start, or any attempt open at the
|
|
641
|
+
end, is interrupted. A codex.api_request row to the responses endpoint shows the HTTP
|
|
642
|
+
transport in use on its thread, or on every thread when it names none. A responses_retry warning names no thread: in a call of one thread
|
|
643
|
+
each is a failed post there, otherwise every thread's coverage is unknown. A thread's
|
|
644
|
+
coverage is complete only when every completion had its start and the thread is wholly on
|
|
645
|
+
the websocket transport: over HTTP nothing records the posts themselves, and a post that
|
|
646
|
+
failed before streaming can leave no warning at all (probe 9, an HTTP 500 retried
|
|
647
|
+
silently), so warnings are counted but never prove an HTTPS thread complete."""
|
|
648
|
+
root = next((r.get("thread") for r in frames if r.get("dir") == "info" and r.get("type") == "root_thread"), None)
|
|
649
|
+
warnings = sum(1 for r in frames if r.get("dir") == "warn" and r.get("type") == "responses_retry")
|
|
650
|
+
threads, http_unnamed = {}, 0
|
|
651
|
+
for rec in frames:
|
|
652
|
+
# a request to the responses endpoint is HTTP-transport evidence (never a ledger of posts);
|
|
653
|
+
# /models and the other endpoints are not requests of the call
|
|
654
|
+
if rec.get("dir") == "otel" and rec.get("event.name") == "codex.api_request" \
|
|
655
|
+
and rec.get("endpoint") in (None, "/responses", "/v1/responses"):
|
|
656
|
+
if rec.get("conversation.id") is None:
|
|
657
|
+
http_unnamed += 1
|
|
658
|
+
else:
|
|
659
|
+
threads.setdefault(rec["conversation.id"], {"attempts": [], "unstarted": 0, "http": 0})["http"] = 1
|
|
660
|
+
continue
|
|
661
|
+
if rec.get("dir") != "otel" or rec.get("conversation.id") is None:
|
|
662
|
+
continue
|
|
663
|
+
name, kind = rec.get("event.name"), rec.get("event.kind")
|
|
664
|
+
th = threads.setdefault(rec["conversation.id"], {"attempts": [], "unstarted": 0, "http": 0})
|
|
665
|
+
live = [a for a in th["attempts"] if a["state"] == "open"]
|
|
666
|
+
if name == "codex.websocket_request":
|
|
667
|
+
th["attempts"].append({"transport": "websocket", "state": "open", "ts": rec.get("ts"), "post": False})
|
|
668
|
+
elif name == "codex.sse_event" and kind == "response.created":
|
|
669
|
+
for a in live:
|
|
670
|
+
if a["transport"] == "https":
|
|
671
|
+
a["state"] = "interrupted"
|
|
672
|
+
th["attempts"].append({"transport": "https", "state": "open", "ts": rec.get("ts"), "post": False})
|
|
673
|
+
elif name == "codex.sse_event" and kind == "response.completed":
|
|
674
|
+
target = live[0] if live else None
|
|
675
|
+
if rec.get("input_token_count") is not None:
|
|
676
|
+
if target is None:
|
|
677
|
+
th["unstarted"] += 1
|
|
678
|
+
else:
|
|
679
|
+
target["state"] = "completed"
|
|
680
|
+
elif target is not None and target["transport"] == "websocket":
|
|
681
|
+
target["state"] = "interrupted"
|
|
682
|
+
lifetime, unnamed = set(threads) | ({root} if root else set()), 0
|
|
683
|
+
for rec in frames:
|
|
684
|
+
if rec.get("dir") == "send" and rec.get("type") == "response.create":
|
|
685
|
+
named = {rec.get(k) for k in ("thread_id", "prompt_cache_key", "parent_thread_id")} - {None}
|
|
686
|
+
lifetime |= named
|
|
687
|
+
unnamed += not named or (rec.get("agent_name") or "/root") != "/root"
|
|
688
|
+
elif rec.get("dir") == "recv" and isinstance(rec.get("response"), dict) and rec["response"].get("prompt_cache_key"):
|
|
689
|
+
lifetime.add(rec["response"]["prompt_cache_key"])
|
|
690
|
+
single = len(lifetime) == 1 and not unnamed
|
|
691
|
+
if http_unnamed: # an HTTP request no thread is named for: no thread of the call is shown complete
|
|
692
|
+
for name in lifetime or {"(no thread named)"}:
|
|
693
|
+
threads.setdefault(name, {"attempts": [], "unstarted": 0, "http": 0})["http"] = 1
|
|
694
|
+
if warnings and single:
|
|
695
|
+
threads.setdefault(next(iter(lifetime)), {"attempts": [], "unstarted": 0, "http": 0})["attempts"] += [
|
|
696
|
+
{"transport": "https", "state": "interrupted", "ts": None, "post": True} for _ in range(warnings)]
|
|
697
|
+
elif warnings:
|
|
698
|
+
for name in lifetime or {"(no thread named)"}:
|
|
699
|
+
threads.setdefault(name, {"attempts": [], "unstarted": 0, "http": 0})
|
|
700
|
+
out = {}
|
|
701
|
+
for thread, th in threads.items():
|
|
702
|
+
for a in th["attempts"]:
|
|
703
|
+
if a["state"] == "open":
|
|
704
|
+
a["state"] = "interrupted"
|
|
705
|
+
transports = {a["transport"] for a in th["attempts"] if not a["post"]} | ({"https"} if th["http"] else set())
|
|
706
|
+
interrupted = [a for a in th["attempts"] if a["state"] == "interrupted"]
|
|
707
|
+
why = ("a completion without its start" if th["unstarted"] else
|
|
708
|
+
f"{warnings} retry warnings name no thread, and the call has more than one" if warnings and not single else
|
|
709
|
+
"HTTPS streams: the HTTP transport keeps no record of its posts, so no count of retry warnings "
|
|
710
|
+
"shows every post was seen" if "https" in transports else None)
|
|
711
|
+
out[thread] = {"transports": sorted(transports), "completed": sum(1 for a in th["attempts"] if a["state"] == "completed"),
|
|
712
|
+
"interrupted": len(interrupted), "interrupted_at": [a["ts"] for a in interrupted if a["ts"]],
|
|
713
|
+
"failed_posts": sum(1 for a in th["attempts"] if a["post"]), "unstarted_completions": th["unstarted"],
|
|
714
|
+
"coverage": "unknown" if why else "complete", "unknown_because": why}
|
|
715
|
+
return out
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def tokens(input_tokens, cached, written, output):
|
|
719
|
+
input_tokens, cached, written = int(input_tokens or 0), int(cached or 0), int(written or 0)
|
|
720
|
+
return {"input": max(input_tokens - cached - written, 0), "output": int(output or 0), "cache_read": cached,
|
|
721
|
+
"cache_creation": written}
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def summarize(frames):
|
|
725
|
+
"""usage.json, facts only: the measured requests (frame responses joined to the completion
|
|
726
|
+
ledger, and completions no frame answers — frames_blind, kind unknown, usage from otel),
|
|
727
|
+
every interrupted attempt (unresolved: the capture keeps no content to estimate it from),
|
|
728
|
+
the attempts per thread, what each thread's responses reported (role, model, effort,
|
|
729
|
+
warm-up), and what the capture cannot attest at all. Whether an observed model or effort is
|
|
730
|
+
the declared seat's is the gate's (WP-02 gate.codex_seats and gate.effort_provenance, which
|
|
731
|
+
hold the root and child seats); nothing here compares against a seat."""
|
|
732
|
+
answered = responses(frames)
|
|
733
|
+
has_otel = any(r.get("dir") == "otel" for r in frames)
|
|
734
|
+
unjoined, ambiguous, leftover = join(frames, answered)
|
|
735
|
+
problems, rows = [], []
|
|
736
|
+
|
|
737
|
+
def measured(rid, role, thread, usage):
|
|
738
|
+
rows.append({"id": rid, "role": role or "unknown", "thread": thread, "state": "measured", "estimate": None, **usage})
|
|
739
|
+
if not answered:
|
|
740
|
+
problems.append("MODEL_UNATTESTED frames silent: no server frame carries a response, so no model is observed")
|
|
741
|
+
for r in answered:
|
|
742
|
+
if r["ambiguous"]:
|
|
743
|
+
problems.append(f"MODEL_UNATTESTED {r['id']}: more than one client frame could have asked for it")
|
|
744
|
+
elif r["send"] is None:
|
|
745
|
+
problems.append(f"MODEL_UNATTESTED {r['id']}: no client frame names its role")
|
|
746
|
+
elif not r["model"]:
|
|
747
|
+
problems.append(f"MODEL_UNATTESTED {r['id']} ({r['role']}): the frame carries no model")
|
|
748
|
+
if (r["joined"] or not has_otel) and r["terminal"] == "completed" and isinstance(r["usage"], dict):
|
|
749
|
+
u = r["usage"]
|
|
750
|
+
measured(r["id"], r["role"], r["thread"], tokens(u.get("input_tokens"), u.get("cached_tokens"),
|
|
751
|
+
u.get("cache_write_tokens"), u.get("output_tokens")))
|
|
752
|
+
if not has_otel:
|
|
753
|
+
problems.append("MODEL_UNATTESTED completions: the capture carries no otel channel, so there is no completion ledger")
|
|
754
|
+
for comp in unjoined:
|
|
755
|
+
problems.append(f"frames_blind {comp.get('conversation.id')} completion at {comp.get('ts')} joins no frame response; "
|
|
756
|
+
f"its usage comes from otel and its request kind is unknown")
|
|
757
|
+
problems.append(f"MODEL_UNATTESTED completion at {comp.get('ts')} ({comp.get('input_token_count')} input tokens) "
|
|
758
|
+
f"has no observed model")
|
|
759
|
+
for comp in ambiguous:
|
|
760
|
+
problems.append(f"MODEL_UNATTESTED completion at {comp.get('ts')}: its in-order frame response disagrees in usage "
|
|
761
|
+
f"while another agrees, an ambiguous join")
|
|
762
|
+
for r in leftover if has_otel else []:
|
|
763
|
+
problems.append(f"MODEL_UNATTESTED {r['id']}: a completed frame response no completion in the ledger joins")
|
|
764
|
+
for comp in unjoined + ambiguous:
|
|
765
|
+
measured(f"otel-{comp.get('ts')}", None, comp.get("conversation.id"),
|
|
766
|
+
tokens(comp.get("input_token_count"), comp.get("cached_token_count"), comp.get("cache_write_token_count"),
|
|
767
|
+
comp.get("output_token_count")))
|
|
768
|
+
tried = attempts(frames) if has_otel else {}
|
|
769
|
+
for thread, th in sorted(tried.items()):
|
|
770
|
+
if th["coverage"] != "complete":
|
|
771
|
+
problems.append(f"USAGE_ATTRIBUTION_UNKNOWN {thread}: attempt coverage is unknown ({th['unknown_because']})")
|
|
772
|
+
for n in range(th["interrupted"]):
|
|
773
|
+
rows.append(attempt_row(f"interrupted-{thread[-6:]}-{n + 1}", thread))
|
|
774
|
+
if not has_otel: # without a ledger, a response that never completed is the only trace of its attempt
|
|
775
|
+
for r in answered:
|
|
776
|
+
if r["terminal"] is None:
|
|
777
|
+
rows.append(attempt_row(f"interrupted-{r['id']}", r["thread"]))
|
|
778
|
+
seen = {}
|
|
779
|
+
for r in answered:
|
|
780
|
+
if r["model"]:
|
|
781
|
+
seen.setdefault(r["role"] or "unknown", set()).add(r["model"])
|
|
782
|
+
threads = {}
|
|
783
|
+
for r in answered:
|
|
784
|
+
threads.setdefault(r["thread"] or "(no thread named)", []).append(
|
|
785
|
+
{"id": r["id"], "role": r["role"], "child": bool(r["send"] and (r["send"].get("parent_thread_id")
|
|
786
|
+
or (r["send"].get("agent_name") or "/root") != "/root")),
|
|
787
|
+
"warmup": (r["send"] or {}).get("request_kind") == "prewarm", "model": r["model"], "effort": r["effort"],
|
|
788
|
+
"terminal": r["terminal"], "joined": r["joined"]})
|
|
789
|
+
reconciled = has_otel and bool(answered) and not problems and all(row["state"] == "measured" for row in rows)
|
|
790
|
+
return {"requests": rows, "attempts": tried, "reconciled": reconciled, "unattested": problems,
|
|
791
|
+
"frames_seen": sum(1 for r in frames if r.get("dir") == "recv" and isinstance(r.get("response"), dict)),
|
|
792
|
+
"seat_observed": {role: sorted(models) for role, models in sorted(seen.items())}, "threads": threads}
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def attempt_row(rid, thread):
|
|
796
|
+
"""An attempt whose usage never arrived. Design §13.3's estimate needs the same agent's
|
|
797
|
+
previous request and the content added since it; the capture keeps no content, so the
|
|
798
|
+
attempt is unresolved, never estimated from another request's usage."""
|
|
799
|
+
return {"id": rid, "role": "unknown", "thread": thread, "state": "unresolved", "estimate": None,
|
|
800
|
+
**{k: None for k in TOKEN_KEYS}}
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
def totals(summary):
|
|
804
|
+
rows = summary["requests"]
|
|
805
|
+
measured = sum(sum(r[k] for k in TOKEN_KEYS) for r in rows if r["state"] == "measured")
|
|
806
|
+
provisional = sum(r["estimate"] for r in rows if r["state"] == "provisional")
|
|
807
|
+
unresolved = sum(1 for r in rows if r["state"] == "unresolved")
|
|
808
|
+
complete = bool(summary["reconciled"]) and provisional == 0 and unresolved == 0
|
|
809
|
+
return {"complete": complete, "measured": measured, "provisional": provisional, "unresolved": unresolved}
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def usage_state(summed):
|
|
813
|
+
if summed["complete"]:
|
|
814
|
+
return "measured"
|
|
815
|
+
return "unresolved" if summed["unresolved"] else "provisional"
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def capture_sha256(capture):
|
|
819
|
+
"""One digest over every file under the capture: its relative path and its bytes' sha256."""
|
|
820
|
+
listed = []
|
|
821
|
+
for dirpath, _, filenames in os.walk(capture):
|
|
822
|
+
for name in filenames:
|
|
823
|
+
path = os.path.join(dirpath, name)
|
|
824
|
+
listed.append([os.path.relpath(path, capture), file_sha256(path)])
|
|
825
|
+
return canonical_sha256(sorted(listed))
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def payload_sha256(packet):
|
|
829
|
+
marker = ("\n" + PAYLOAD_MARKER + "\n").encode("utf-8")
|
|
830
|
+
at = packet.find(marker)
|
|
831
|
+
return hashlib.sha256(packet if at < 0 else packet[at + len(marker):]).hexdigest()
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
def run_finish(args):
|
|
835
|
+
frames = read_jsonl(os.path.join(args.capture, "frames.jsonl"))
|
|
836
|
+
events = read_jsonl(os.path.join(args.capture, "events.jsonl"))
|
|
837
|
+
with open(os.path.join(args.work, "context.json"), encoding="utf-8") as handle:
|
|
838
|
+
pre = json.load(handle)
|
|
839
|
+
root = next((r.get("thread") for r in frames if r.get("dir") == "info" and r.get("type") == "root_thread"), None)
|
|
840
|
+
thread = next((e.get("thread_id") for e in events if e.get("type") == "thread.started"), None) or root
|
|
841
|
+
summary = summarize(frames)
|
|
842
|
+
summed = totals(summary)
|
|
843
|
+
host = {"host": "codex", "call_id": args.call_id, "profile": args.profile,
|
|
844
|
+
"profile_flags_sha256": canonical_sha256(args.flag), "cwd": args.cwd, "session_id": thread,
|
|
845
|
+
"workdir_files": pre["workdir_files"], "context": pre["context"], "codex_path": pre["codex_path"],
|
|
846
|
+
"codex_version": pre["codex_version"], "rendering": pre["rendering"],
|
|
847
|
+
"exit_status": args.exit_status, "wall_ms": args.wall_ms, "hermeticity": HERMETICITY}
|
|
848
|
+
usage = {"schema": "CodexCaptureUsage/v1", "call_id": args.call_id, "seat_requested": f"{args.model}/{args.effort}",
|
|
849
|
+
**summary, "totals": summed, "usage_state": usage_state(summed)}
|
|
850
|
+
for name, obj in (("host.json", host), ("usage.json", usage)):
|
|
851
|
+
with open(os.path.join(args.capture, name), "w", encoding="utf-8") as out:
|
|
852
|
+
json.dump(obj, out, indent=1, sort_keys=True, ensure_ascii=False)
|
|
853
|
+
out.write("\n")
|
|
854
|
+
with open(args.packet, "rb") as handle:
|
|
855
|
+
packet = handle.read()
|
|
856
|
+
manifest = "none"
|
|
857
|
+
if args.manifest:
|
|
858
|
+
with open(args.manifest, encoding="utf-8") as handle:
|
|
859
|
+
manifest = canonical_sha256(json.load(handle))
|
|
860
|
+
values = {"call_id": args.call_id, "schema_sha256": file_sha256(args.schema) if args.schema else "none",
|
|
861
|
+
"payload_sha256": payload_sha256(packet), "seat_observed": canonical(summary["seat_observed"]),
|
|
862
|
+
"profile": args.profile, "profile_flags_sha256": host["profile_flags_sha256"], "cwd": args.cwd,
|
|
863
|
+
"manifest_sha256": manifest, "context_observed_sha256": canonical_sha256(pre["context"]),
|
|
864
|
+
"usage_state": usage["usage_state"], "usage_totals": canonical(summed),
|
|
865
|
+
"capture_sha256": capture_sha256(args.capture), "session_id": thread or "",
|
|
866
|
+
"hermeticity": canonical(host["hermeticity"])}
|
|
867
|
+
for key in EVIDENCE_KEYS:
|
|
868
|
+
print(f"{key}={values[key]}")
|
|
869
|
+
return 0
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
# --- self-test ------------------------------------------------------------------------------
|
|
873
|
+
|
|
874
|
+
def self_test():
|
|
875
|
+
import tempfile
|
|
876
|
+
failures, ran = [], []
|
|
877
|
+
|
|
878
|
+
def control(name, errors, *needles):
|
|
879
|
+
ran.append(name)
|
|
880
|
+
if not needles and errors:
|
|
881
|
+
failures.append(f"{name}: expected no violation, got {errors}")
|
|
882
|
+
for needle in needles:
|
|
883
|
+
if not any(needle in line for line in errors):
|
|
884
|
+
failures.append(f"{name}: expected {needle!r} in {errors}")
|
|
885
|
+
|
|
886
|
+
root, kid = "01a15879-0000-7000-8000-000000000001", "01a15879-0000-7000-8000-000000000002"
|
|
887
|
+
secret = "PROMPT-BODY-CANARY"
|
|
888
|
+
deflaters = {}
|
|
889
|
+
|
|
890
|
+
def send(ts, kind, thread, prev=None, agent="/root", parent=None):
|
|
891
|
+
create = {"type": "response.create", "model": "m-1", "previous_response_id": prev, "prompt_cache_key": root,
|
|
892
|
+
"reasoning": {"effort": "low"}, "instructions": secret, "input": [{"type": "message", "content": secret}],
|
|
893
|
+
"client_metadata": {"x-codex-turn-metadata": json.dumps({"thread_id": thread, "agent_name": agent,
|
|
894
|
+
"request_kind": kind, "parent_thread_id": parent})}}
|
|
895
|
+
deflate = deflaters.setdefault(thread, zlib.compressobj(wbits=-15))
|
|
896
|
+
data = (deflate.compress(json.dumps(create).encode()) + deflate.flush(zlib.Z_SYNC_FLUSH))[:-4]
|
|
897
|
+
return [f"{ts} TRACE tungstenite::protocol::frame: writing frame", "opcode: TEXT", "reserved: true false false",
|
|
898
|
+
"payload: 0x" + data.hex()]
|
|
899
|
+
|
|
900
|
+
def recv(ts, kind, rid, prev=None, usage=None, effort="low", model="m-1"):
|
|
901
|
+
resp = {"id": rid, "model": model, "status": kind.split(".")[1], "previous_response_id": prev, "prompt_cache_key": root,
|
|
902
|
+
"reasoning": {"effort": effort}, "output": [{"type": "message", "content": [{"text": "OUTPUT-BODY-CANARY"}]}],
|
|
903
|
+
"instructions": secret}
|
|
904
|
+
if usage:
|
|
905
|
+
resp["usage"] = {"input_tokens": usage[0], "output_tokens": usage[1], "total_tokens": sum(usage),
|
|
906
|
+
"input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}}
|
|
907
|
+
return [f"{ts} TRACE tungstenite::protocol: Received message " + json.dumps({"type": kind, "response": resp})]
|
|
908
|
+
|
|
909
|
+
def otel(ts, fields):
|
|
910
|
+
return [f"{ts} INFO session_loop: codex_otel.log_only: {fields}"]
|
|
911
|
+
|
|
912
|
+
def trace(model="m-1", effort="low", blind=False):
|
|
913
|
+
t = "2026-10-20T08:42:0"
|
|
914
|
+
deflaters.clear() # one websocket connection per trace
|
|
915
|
+
lines = [f'{t}0.000000Z INFO codex.exec{{thread.id="{root}"}}: started', "a progress line"]
|
|
916
|
+
lines += otel(f"{t}1.000000Z", f'event.name="codex.websocket_request" conversation.id={root}')
|
|
917
|
+
lines += send(f"{t}1.100000Z", "prewarm", root)
|
|
918
|
+
lines += recv(f"{t}1.200000Z", "response.created", "resp_w", effort=effort, model=model)
|
|
919
|
+
lines += recv(f"{t}1.300000Z", "response.completed", "resp_w", usage=(1000, 0), effort=effort, model=model)
|
|
920
|
+
lines += otel(f"{t}1.300000Z", f'event.name="codex.sse_event" event.kind=response.completed conversation.id={root} '
|
|
921
|
+
f'input_token_count=1000 output_token_count=0 cached_token_count=0 cache_write_token_count=0')
|
|
922
|
+
lines += otel(f"{t}2.000000Z", f'event.name="codex.websocket_request" conversation.id={root}')
|
|
923
|
+
lines += send(f"{t}2.100000Z", "turn", root, prev="resp_w")
|
|
924
|
+
lines += [f"{t}2.150000Z TRACE tungstenite::protocol: Received message " + json.dumps(
|
|
925
|
+
{"type": "response.output_text.delta", "delta": "OUTPUT-BODY-CANARY"})]
|
|
926
|
+
lines += recv(f"{t}2.200000Z", "response.created", "resp_m", prev="resp_w", effort=effort, model=model)
|
|
927
|
+
if not blind:
|
|
928
|
+
lines += recv(f"{t}2.300000Z", "response.completed", "resp_m", prev="resp_w", usage=(1002, 7), effort=effort, model=model)
|
|
929
|
+
lines += otel(f"{t}2.300000Z", f'event.name="codex.sse_event" event.kind=response.completed conversation.id={root} '
|
|
930
|
+
f'input_token_count=1002 output_token_count=7 cached_token_count=0 cache_write_token_count=0')
|
|
931
|
+
return lines
|
|
932
|
+
|
|
933
|
+
def reduce(lines, rust_log="tungstenite::protocol=trace,codex_otel.log_only=info,codex_core::responses_retry=warn"):
|
|
934
|
+
return reduce_lines(lines, rust_log)
|
|
935
|
+
|
|
936
|
+
clean = reduce(trace())
|
|
937
|
+
summary = summarize(clean)
|
|
938
|
+
control("clean-capture-attested-and-reconciled", summary["unattested"] + ([] if summary["reconciled"] else ["not reconciled"]))
|
|
939
|
+
control("warmup-and-main-measured", [] if sorted((r["role"], r["input"], r["output"]) for r in summary["requests"])
|
|
940
|
+
== [("main", 1002, 7), ("warmup", 1000, 0)] else [f"rows {summary['requests']}"])
|
|
941
|
+
control("efforts-and-warmups-reported-per-thread", [] if [(f["role"], f["warmup"], f["model"], f["effort"], f["child"])
|
|
942
|
+
for f in summary["threads"][root]]
|
|
943
|
+
== [("warmup", True, "m-1", "low", False), ("main", False, "m-1", "low", False)] else [f"{summary['threads']}"])
|
|
944
|
+
control("seat-observed-per-role", [] if summary["seat_observed"] == {"main": ["m-1"], "warmup": ["m-1"]}
|
|
945
|
+
else [f"{summary['seat_observed']}"])
|
|
946
|
+
blob = json.dumps(clean)
|
|
947
|
+
control("no-prompt-or-output-body-survives", [line for line in ("PROMPT-BODY-CANARY", "OUTPUT-BODY-CANARY", "progress line")
|
|
948
|
+
if line in blob])
|
|
949
|
+
sent = [r for r in clean if r.get("dir") == "send"]
|
|
950
|
+
control("turn-metadata-kept", [] if [(r["request_kind"], r["thread_id"], r["agent_name"]) for r in sent]
|
|
951
|
+
== [("prewarm", root, "/root"), ("turn", root, "/root")] else [f"sends {sent}"])
|
|
952
|
+
# The kept inventory, copied once from plan WP-04 "Files" (codex_frame_filter.py: frame type,
|
|
953
|
+
# response.model, usage, ids, status, generate (warm-up), incomplete_details, error,
|
|
954
|
+
# reasoning.effort, refusal markers, and the sent frame's turn metadata: request_kind, thread
|
|
955
|
+
# and agent ids), each populated with a distinguishing value and asserted exactly as retained.
|
|
956
|
+
meta = {"thread_id": "0000aaaa-0007", "agent_name": "/root/kid", "request_kind": "turn", "parent_thread_id": "th-root"}
|
|
957
|
+
create = {"type": "response.create", "model": "m-sent", "previous_response_id": "resp_prev", "prompt_cache_key": "pck-9",
|
|
958
|
+
"reasoning": {"effort": "xhigh"}, "input": [{"content": "PROMPT-BODY-CANARY"}],
|
|
959
|
+
"client_metadata": {"x-codex-turn-metadata": json.dumps(meta)}}
|
|
960
|
+
response = {"id": "resp_9", "model": "m-served", "status": "incomplete", "generate": False, "previous_response_id": "resp_prev",
|
|
961
|
+
"prompt_cache_key": "pck-9", "reasoning": {"effort": "xhigh"},
|
|
962
|
+
"incomplete_details": {"reason": "max_output_tokens", "note": "OUTPUT-BODY-CANARY"},
|
|
963
|
+
"error": {"code": "server_error", "type": "api_error", "message": "PROMPT-BODY-CANARY sk-CANARY"},
|
|
964
|
+
"output": [{"content": [{"text": "OUTPUT-BODY-CANARY"}]}],
|
|
965
|
+
"usage": {"input_tokens": 41, "output_tokens": 43, "total_tokens": 84,
|
|
966
|
+
"input_tokens_details": {"cached_tokens": 5, "cache_write_tokens": 3},
|
|
967
|
+
"output_tokens_details": {"reasoning_tokens": 11}}}
|
|
968
|
+
t = "2026-10-20T09:00:00.000000Z"
|
|
969
|
+
payload = zlib.compressobj(wbits=-15)
|
|
970
|
+
data = (payload.compress(json.dumps(create).encode()) + payload.flush(zlib.Z_SYNC_FLUSH))[:-4]
|
|
971
|
+
every = reduce([f"{t} TRACE tungstenite::protocol::frame: writing frame", "opcode: TEXT", "reserved: true false false",
|
|
972
|
+
"payload: 0x" + data.hex(),
|
|
973
|
+
f"{t} TRACE tungstenite::protocol: Received message " + json.dumps({"type": "response.incomplete", "response": response}),
|
|
974
|
+
f"{t} TRACE tungstenite::protocol: Received message " + json.dumps({"type": "response.refusal.done", "refusal": "OUTPUT-BODY-CANARY"}),
|
|
975
|
+
f"{t} TRACE tungstenite::protocol: Received message " + json.dumps(
|
|
976
|
+
{"type": "error", "status": 429, "error": {"code": "usage_limit_reached", "type": "t", "message": "sk-CANARY"}}),
|
|
977
|
+
f"{t} INFO session_loop: codex_otel.log_only: event.name=\"codex.api_request\" conversation.id=0000aaaa-0007 "
|
|
978
|
+
f"http.response.status_code=500 attempt=1 endpoint=/responses error.message=\"PROMPT-BODY-CANARY\"",
|
|
979
|
+
f"{t} INFO session_loop: codex_otel.log_only: event.name=\"codex.api_request\" "
|
|
980
|
+
f'error.message="quoted \\" model=PROMPT-BODY-CANARY endpoint=/x" model="has space sk-CANARY"',
|
|
981
|
+
f"{t} TRACE tungstenite::protocol: Received message " + json.dumps(
|
|
982
|
+
{"type": "error", "status": "PROMPT-BODY-CANARY", "error": {"code": {"message": "sk-CANARY"}, "type": True}})])
|
|
983
|
+
want = [{"dir": "info", "type": "channels", "channels": ["frames", "otel", "responses_retry"]},
|
|
984
|
+
{"dir": "send", "type": "response.create", "ts": t, "thread_id": "0000aaaa-0007", "agent_name": "/root/kid",
|
|
985
|
+
"request_kind": "turn", "parent_thread_id": "th-root", "previous_response_id": "resp_prev",
|
|
986
|
+
"prompt_cache_key": "pck-9", "model": "m-sent", "reasoning_effort": "xhigh"},
|
|
987
|
+
{"dir": "recv", "type": "response.incomplete", "ts": t, "response": {
|
|
988
|
+
"id": "resp_9", "model": "m-served", "status": "incomplete", "generate": False, "previous_response_id": "resp_prev",
|
|
989
|
+
"prompt_cache_key": "pck-9", "incomplete_details": {"reason": "max_output_tokens"},
|
|
990
|
+
"error": {"code": "server_error", "type": "api_error"}, "reasoning_effort": "xhigh",
|
|
991
|
+
"usage": {"input_tokens": 41, "cached_tokens": 5, "cache_write_tokens": 3, "output_tokens": 43,
|
|
992
|
+
"reasoning_tokens": 11, "total_tokens": 84}}},
|
|
993
|
+
{"dir": "recv", "type": "response.refusal.done", "ts": t},
|
|
994
|
+
{"dir": "recv", "type": "error", "ts": t, "detail": {"status": 429, "error": {"code": "usage_limit_reached", "type": "t"}}},
|
|
995
|
+
{"dir": "otel", "ts": t, "event.name": "codex.api_request", "conversation.id": "0000aaaa-0007",
|
|
996
|
+
"http.response.status_code": "500", "attempt": "1", "endpoint": "/responses"},
|
|
997
|
+
{"dir": "otel", "ts": t, "event.name": "codex.api_request"},
|
|
998
|
+
{"dir": "recv", "type": "error", "ts": t, "detail": {"status": None, "error": {"code": DROPPED, "type": DROPPED}}}]
|
|
999
|
+
control("kept-inventory-exact", [] if every == want else [f"retained {every}"])
|
|
1000
|
+
token = "sk-proj-" + "Ab3" * 14
|
|
1001
|
+
control("diagnostics-are-codes-or-dropped", [] if codes(
|
|
1002
|
+
{"code": "server_error", "type": "prompt body text", "reason": "/Users/canary/private-value", "param": token,
|
|
1003
|
+
"status": 500, "flag": True, "missing": None}, ("code", "type", "reason", "param", "status", "flag", "missing"))
|
|
1004
|
+
== {"code": "server_error", "type": DROPPED, "reason": DROPPED, "param": DROPPED, "status": 500, "flag": DROPPED}
|
|
1005
|
+
else ["a free-form, path or credential value was kept"])
|
|
1006
|
+
control("no-canary-in-a-nested-error-or-field", [c for c in ("PROMPT-BODY-CANARY", "OUTPUT-BODY-CANARY", "sk-CANARY")
|
|
1007
|
+
if c in json.dumps(every)])
|
|
1008
|
+
child = summarize([r for r in every if r.get("dir") != "otel"] + [
|
|
1009
|
+
{"dir": "otel", "event.name": "codex.websocket_request", "conversation.id": "0000aaaa-0007", "ts": t}])
|
|
1010
|
+
control("child-metadata-gives-the-role", [] if child["seat_observed"] == {"child": ["m-served"]} else [f"{child['seat_observed']}"])
|
|
1011
|
+
control("channels-from-rust-log", [] if channels("tungstenite::protocol=trace,codex_otel.log_only=info") == ["frames", "otel"]
|
|
1012
|
+
and channels("") == [] and channels("trace") == ["frames", "otel", "responses_retry"]
|
|
1013
|
+
and channels("tungstenite=trace") == ["frames"] and channels("tungstenite::protocol=debug") == []
|
|
1014
|
+
else ["channel parse"])
|
|
1015
|
+
|
|
1016
|
+
control("rust-log-is-the-callers", [] if channels("") == [] else ["an empty RUST_LOG opened a channel"])
|
|
1017
|
+
control("frames-silent-is-unattested", summarize([r for r in clean if r.get("dir") not in ("recv", "send")])
|
|
1018
|
+
["unattested"], "MODEL_UNATTESTED frames silent")
|
|
1019
|
+
control("frames-blind-completion", summarize(reduce(trace(blind=True)))["unattested"],
|
|
1020
|
+
f"frames_blind {root} completion at", "MODEL_UNATTESTED completion at")
|
|
1021
|
+
other = summarize(reduce(trace(model="m-2", effort="high")))
|
|
1022
|
+
control("another-model-is-a-fact-not-a-verdict", [] if not other["unattested"] and other["seat_observed"]
|
|
1023
|
+
== {"main": ["m-2"], "warmup": ["m-2"]} and {f["effort"] for f in other["threads"][root]} == {"high"}
|
|
1024
|
+
else [f"{other['unattested']} {other['seat_observed']}"])
|
|
1025
|
+
sends = [r for r in clean if r.get("dir") == "send"]
|
|
1026
|
+
completed = [r for r in clean if r.get("dir") == "otel" and r.get("input_token_count")]
|
|
1027
|
+
control("two-sends-could-have-asked", summarize([sends[0]] + clean)["unattested"],
|
|
1028
|
+
"MODEL_UNATTESTED resp_w: more than one client frame could have asked for it")
|
|
1029
|
+
control("no-send-names-the-role", summarize([r for r in clean if r.get("dir") != "send"])["unattested"],
|
|
1030
|
+
"MODEL_UNATTESTED resp_w: no client frame names its role")
|
|
1031
|
+
control("frame-without-a-model", summarize([dict(r, response=dict(r["response"], model=None)) if r.get("dir") == "recv"
|
|
1032
|
+
else r for r in clean])["unattested"],
|
|
1033
|
+
"MODEL_UNATTESTED resp_w (warmup): the frame carries no model")
|
|
1034
|
+
control("completions-out-of-order", summarize([r for r in clean if r not in completed] + completed[::-1])
|
|
1035
|
+
["unattested"], "an ambiguous join")
|
|
1036
|
+
control("framed-response-without-its-completion", summarize([r for r in clean if r is not completed[1]])
|
|
1037
|
+
["unattested"], "MODEL_UNATTESTED resp_m: a completed frame response no completion in the ledger joins")
|
|
1038
|
+
control("no-otel-channel", summarize([r for r in clean if r.get("dir") != "otel"])["unattested"],
|
|
1039
|
+
"MODEL_UNATTESTED completions: the capture carries no otel channel")
|
|
1040
|
+
spanned = reduce(trace() + ['2026-10-20T08:42:02.250000Z WARN session_loop{thread_id=x}:turn{otel.name="t"}: '
|
|
1041
|
+
'codex_core::responses_retry: stream disconnected - retrying sampling request (1/5)'])
|
|
1042
|
+
retried = [r for r in spanned if not (r.get("dir") == "info" and r.get("type") == "truncated_frame")]
|
|
1043
|
+
control("retry-warning-read-inside-spans", [] if any(r.get("dir") == "warn" for r in retried) else ["the warning was not read"])
|
|
1044
|
+
one = summarize(retried)
|
|
1045
|
+
control("single-thread-retry-is-an-unresolved-post", [] if one["attempts"][root]["failed_posts"] == 1
|
|
1046
|
+
and [r["state"] for r in one["requests"] if r["role"] == "unknown"] == ["unresolved"] else [f"{one}"])
|
|
1047
|
+
two = summarize(retried + [{"dir": "send", "type": "response.create", "thread_id": kid, "agent_name": "/root/kid",
|
|
1048
|
+
"request_kind": "turn", "parent_thread_id": root, "prompt_cache_key": root}])
|
|
1049
|
+
control("retry-warning-in-a-call-of-two-threads", two["unattested"], "USAGE_ATTRIBUTION_UNKNOWN")
|
|
1050
|
+
https = [{"dir": "info", "type": "channels", "channels": ["otel"]}, {"dir": "info", "type": "root_thread", "thread": root},
|
|
1051
|
+
{"dir": "otel", "event.name": "codex.sse_event", "event.kind": "response.created", "conversation.id": root, "ts": "t1"},
|
|
1052
|
+
{"dir": "otel", "event.name": "codex.sse_event", "event.kind": "response.created", "conversation.id": root, "ts": "t2"},
|
|
1053
|
+
{"dir": "otel", "event.name": "codex.sse_event", "event.kind": "response.completed", "conversation.id": root, "ts": "t3",
|
|
1054
|
+
"input_token_count": "1000", "output_token_count": "2"}]
|
|
1055
|
+
dropped = summarize(https)
|
|
1056
|
+
control("https-drop-is-unknown", dropped["unattested"], "frames_blind", "USAGE_ATTRIBUTION_UNKNOWN",
|
|
1057
|
+
"HTTPS streams: the HTTP transport keeps no record of its posts")
|
|
1058
|
+
clean_https = [dict(r, channels=["otel", "responses_retry"]) if r.get("type") == "channels" else r
|
|
1059
|
+
for r in https if r.get("ts") != "t1"]
|
|
1060
|
+
control("https-without-a-warning-is-unknown", summarize(clean_https)["unattested"],
|
|
1061
|
+
"HTTPS streams: the HTTP transport keeps no record of its posts")
|
|
1062
|
+
# an HTTP request that failed before any response.created, on a websocket thread: unknown;
|
|
1063
|
+
# a /models request is not one of the call's requests
|
|
1064
|
+
failed_post = {"dir": "otel", "event.name": "codex.api_request", "conversation.id": root, "endpoint": "/responses",
|
|
1065
|
+
"http.response.status_code": "500", "attempt": "0", "ts": "2026-10-20T08:42:01.050000Z"}
|
|
1066
|
+
control("http-failure-before-created-is-unknown", summarize(clean + [failed_post])["unattested"],
|
|
1067
|
+
f"USAGE_ATTRIBUTION_UNKNOWN {root}")
|
|
1068
|
+
control("http-failure-naming-no-thread-is-unknown", summarize(clean + [{k: v for k, v in failed_post.items()
|
|
1069
|
+
if k != "conversation.id"}])["unattested"],
|
|
1070
|
+
f"USAGE_ATTRIBUTION_UNKNOWN {root}")
|
|
1071
|
+
models = summarize(clean + [dict(failed_post, endpoint="/models", **{"http.response.status_code": "200"})])
|
|
1072
|
+
control("models-request-leaves-coverage-complete", models["unattested"] + ([] if models["reconciled"] else ["unreconciled"]))
|
|
1073
|
+
control("instruction-overrides-are-appended-prompts", [] if instruction_overrides(
|
|
1074
|
+
['model_reasoning_effort="low"', 'developer_instructions="Be terse."', "profiles.x.instructions='Be terse.'"])
|
|
1075
|
+
== ([{"name": "developer_instructions", "sha256": hashlib.sha256(b"Be terse.").hexdigest()},
|
|
1076
|
+
{"name": "profiles.x.instructions", "sha256": hashlib.sha256(b"Be terse.").hexdigest()}], [])
|
|
1077
|
+
and instruction_overrides(['developer_instructions="""a\\tb"""'])[0][0]["sha256"] == hashlib.sha256(b"a\tb").hexdigest()
|
|
1078
|
+
and instruction_overrides(['model="m"']) == ([], []) else [f"instruction overrides"])
|
|
1079
|
+
control("override-values-decode-as-codex-reads-them", [] if override_value("'C:\\x'") == "C:\\x"
|
|
1080
|
+
and override_value('"a\\tb"') == "a\tb" and override_value("0") == 0 and override_value("raw text") == "raw text"
|
|
1081
|
+
else ["override decoding"])
|
|
1082
|
+
control("instruction-file-override-refused", instruction_overrides(['model_instructions_file="/x"'])[1],
|
|
1083
|
+
"CODEX_INSTRUCTION_OVERRIDE_UNSUPPORTED model_instructions_file")
|
|
1084
|
+
control("instruction-override-set-twice-refused", instruction_overrides(
|
|
1085
|
+
['developer_instructions="a"', "developer_instructions='b'"])[1], "CODEX_INSTRUCTION_OVERRIDE_REPEATED developer_instructions")
|
|
1086
|
+
control("instruction-override-not-a-string-refused", instruction_overrides(['developer_instructions=42'])[1]
|
|
1087
|
+
+ instruction_overrides(["instructions=raw text"])[1],
|
|
1088
|
+
"CODEX_INSTRUCTION_OVERRIDE_UNSUPPORTED developer_instructions: the value is not a TOML string",
|
|
1089
|
+
"CODEX_INSTRUCTION_OVERRIDE_UNSUPPORTED instructions: the value is not a TOML string")
|
|
1090
|
+
# a warning for one retry beside a post that failed silently: the inputs are those of a
|
|
1091
|
+
# warning that accounts for everything, so no warning count may make the thread complete
|
|
1092
|
+
warned = summarize(https + [{"dir": "warn", "type": "responses_retry", "ts": "t2b"}])
|
|
1093
|
+
control("https-with-warnings-is-still-unknown", warned["unattested"], "HTTPS streams: the HTTP transport keeps no record")
|
|
1094
|
+
# an interrupted attempt followed by a differently sized success: never estimated from it
|
|
1095
|
+
control("interrupted-attempt-is-unresolved", [] if [(r["role"], r["state"], r["estimate"], r["input"]) for r in dropped["requests"]]
|
|
1096
|
+
== [("unknown", "measured", None, 1000), ("unknown", "unresolved", None, None)] else [f"{dropped['requests']}"])
|
|
1097
|
+
control("usage-state-follows-the-rows", [] if usage_state(totals(summary)) == "measured"
|
|
1098
|
+
and usage_state(totals(dropped)) == "unresolved" else ["state"])
|
|
1099
|
+
|
|
1100
|
+
# the events whitelist and the filter process: every stderr line passes through, the records are kept apart
|
|
1101
|
+
scratch = tempfile.mkdtemp(prefix="codex-frame-filter-")
|
|
1102
|
+
|
|
1103
|
+
def run_child(argv, text_in, name):
|
|
1104
|
+
"""A child's stdin, stdout and stderr are files, never pipes: a child fed and drained through pipes
|
|
1105
|
+
deadlocked here under the commit hook (parent blocked writing stdin, child blocked writing stderr)."""
|
|
1106
|
+
paths = {stream: os.path.join(scratch, f"{name}.{stream}") for stream in ("in", "out", "err")}
|
|
1107
|
+
with open(paths["in"], "w") as handle:
|
|
1108
|
+
handle.write(text_in)
|
|
1109
|
+
with open(paths["in"]) as stdin, open(paths["out"], "w") as stdout, open(paths["err"], "w") as stderr:
|
|
1110
|
+
code = subprocess.run(argv, stdin=stdin, stdout=stdout, stderr=stderr).returncode
|
|
1111
|
+
with open(paths["out"]) as out, open(paths["err"]) as err:
|
|
1112
|
+
return code, out.read(), err.read()
|
|
1113
|
+
|
|
1114
|
+
try:
|
|
1115
|
+
frames_path = os.path.join(scratch, "frames.jsonl")
|
|
1116
|
+
_, out, err = run_child([sys.executable, os.path.abspath(__file__), "filter", "--frames", frames_path, "--rust-log",
|
|
1117
|
+
"tungstenite::protocol=trace,codex_otel.log_only=info"],
|
|
1118
|
+
"\n".join(trace()) + "\n", "filter")
|
|
1119
|
+
control("filter-passes-stderr-through", [] if out == "" and err == "\n".join(trace()) + "\n"
|
|
1120
|
+
else ["the stderr channel was changed"])
|
|
1121
|
+
stored = read_jsonl(frames_path)
|
|
1122
|
+
control("filter-stores-the-reduction", [] if stored == [json.loads(json.dumps(r, sort_keys=True)) for r in reduce(
|
|
1123
|
+
trace(), rust_log="tungstenite::protocol=trace,codex_otel.log_only=info")] else ["stored records differ"])
|
|
1124
|
+
events_path = os.path.join(scratch, "events.jsonl")
|
|
1125
|
+
json_events = [{"type": "thread.started", "thread_id": root}, {"type": "turn.started"},
|
|
1126
|
+
{"type": "item.completed", "item": {"type": "agent_message", "text": "OUTPUT-BODY-CANARY"}},
|
|
1127
|
+
{"type": "error", "message": "Reconnecting PROMPT-BODY-CANARY"},
|
|
1128
|
+
{"type": "turn.failed", "error": {"message": "sk-CANARY"}},
|
|
1129
|
+
{"type": "turn.completed", "usage": {"input_tokens": 1002, "output_tokens": 7}}]
|
|
1130
|
+
run_child([sys.executable, os.path.abspath(__file__), "events", "--out", events_path],
|
|
1131
|
+
"".join(json.dumps(e) + "\n" for e in json_events), "events")
|
|
1132
|
+
kept = read_jsonl(events_path)
|
|
1133
|
+
control("events-keep-turns-and-drop-items", [] if kept == [
|
|
1134
|
+
{"type": "thread.started", "thread_id": root}, {"type": "turn.started"}, {"type": "error"}, {"type": "turn.failed"},
|
|
1135
|
+
{"type": "turn.completed", "usage": {"input_tokens": 1002, "output_tokens": 7}}] else [f"{kept}"])
|
|
1136
|
+
finally:
|
|
1137
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
1138
|
+
# structural: no child the self-test starts is handed a pipe (the words are assembled so this
|
|
1139
|
+
# control does not match its own text)
|
|
1140
|
+
import inspect
|
|
1141
|
+
body = inspect.getsource(self_test)
|
|
1142
|
+
piped = [w for w in ("capture" + "_output", "input" + "=", "subprocess." + "PIPE") if w in body]
|
|
1143
|
+
control("self-test-hands-no-child-a-pipe", [f"self_test uses {piped}"] if piped else [])
|
|
1144
|
+
# copied once from design §3.2 step 1's evidence list with plan WP-02's payload_sha256
|
|
1145
|
+
# (session-distill/runlib/receipts.py EVIDENCE_KEYS on wp/02-gate-supervisor) and the contract-fix
|
|
1146
|
+
# record's hermeticity (design/contract-fix/, 2026-11-02, F-31)
|
|
1147
|
+
control("evidence-keys-are-the-gates", [] if EVIDENCE_KEYS == (
|
|
1148
|
+
"call_id", "schema_sha256", "payload_sha256", "seat_observed", "profile", "profile_flags_sha256", "cwd",
|
|
1149
|
+
"manifest_sha256", "context_observed_sha256", "usage_state", "usage_totals", "capture_sha256", "session_id",
|
|
1150
|
+
"hermeticity") else [f"evidence keys {EVIDENCE_KEYS}"])
|
|
1151
|
+
control("payload-hash-after-the-marker", [] if payload_sha256(b"HEAD\n=== PAYLOAD ===\nbody")
|
|
1152
|
+
== hashlib.sha256(b"body").hexdigest() and payload_sha256(b"plain") == hashlib.sha256(b"plain").hexdigest()
|
|
1153
|
+
else ["payload hash"])
|
|
1154
|
+
|
|
1155
|
+
for failure in failures:
|
|
1156
|
+
print(f"codex_frame_filter --self-test [FAIL] {failure}")
|
|
1157
|
+
if failures:
|
|
1158
|
+
return 1
|
|
1159
|
+
print(f"codex_frame_filter --self-test: OK ({len(ran)} controls: " + ", ".join(ran) + ")")
|
|
1160
|
+
return 0
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def main(argv):
|
|
1164
|
+
if argv[1:] == ["--self-test"]:
|
|
1165
|
+
return self_test()
|
|
1166
|
+
parser = argparse.ArgumentParser(prog="codex_frame_filter.py")
|
|
1167
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
1168
|
+
p = sub.add_parser("filter")
|
|
1169
|
+
p.add_argument("--frames", required=True)
|
|
1170
|
+
p.add_argument("--rust-log", default="")
|
|
1171
|
+
p = sub.add_parser("events")
|
|
1172
|
+
p.add_argument("--out", required=True)
|
|
1173
|
+
p = sub.add_parser("context")
|
|
1174
|
+
for name in ("--codex", "--version", "--codex-home", "--child-home", "--cwd", "--capture", "--work"):
|
|
1175
|
+
p.add_argument(name, required=True)
|
|
1176
|
+
p.add_argument("-c", dest="config", action="append", default=[])
|
|
1177
|
+
p = sub.add_parser("finish")
|
|
1178
|
+
for name in ("--capture", "--work", "--call-id", "--profile", "--cwd", "--packet"):
|
|
1179
|
+
p.add_argument(name, required=True)
|
|
1180
|
+
p.add_argument("--model", default="")
|
|
1181
|
+
p.add_argument("--effort", default="")
|
|
1182
|
+
p.add_argument("--exit-status", type=int, required=True)
|
|
1183
|
+
p.add_argument("--wall-ms", type=int)
|
|
1184
|
+
p.add_argument("--schema")
|
|
1185
|
+
p.add_argument("--manifest")
|
|
1186
|
+
p.add_argument("--flag", action="append", default=[])
|
|
1187
|
+
args = parser.parse_args(argv[1:])
|
|
1188
|
+
if args.command == "context":
|
|
1189
|
+
# the app-server it asks runs in a group of its own: a SIGTERM or SIGHUP ends that group before
|
|
1190
|
+
# this process ends by the signal (a missing protocol module is the context's own error to report)
|
|
1191
|
+
try:
|
|
1192
|
+
codex_protocol().raise_on_termination()
|
|
1193
|
+
except OSError:
|
|
1194
|
+
pass
|
|
1195
|
+
return {"filter": run_filter, "events": run_events, "context": run_context, "finish": run_finish}[args.command](args)
|
|
1196
|
+
|
|
1197
|
+
|
|
1198
|
+
if __name__ == "__main__":
|
|
1199
|
+
sys.exit(main(sys.argv))
|