timeplus-agentguard-codex-plugin 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (18) hide show
  1. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/PKG-INFO +45 -3
  2. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/README.md +44 -2
  3. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/agentguard_codex/__init__.py +1 -1
  4. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/agentguard_codex/events.py +41 -2
  5. timeplus_agentguard_codex_plugin-0.4.0/agentguard_codex/transcript.py +226 -0
  6. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/pyproject.toml +1 -1
  7. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/tests/test_events.py +99 -0
  8. timeplus_agentguard_codex_plugin-0.4.0/tests/test_transcript.py +213 -0
  9. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/.gitignore +0 -0
  10. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/Makefile +0 -0
  11. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/agentguard_codex/__main__.py +0 -0
  12. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/agentguard_codex/cli.py +0 -0
  13. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/agentguard_codex/hookevents.py +0 -0
  14. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/agentguard_codex/sink.py +0 -0
  15. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/hooks.json +0 -0
  16. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/tests/test_cli.py +0 -0
  17. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/tests/test_hookevents.py +0 -0
  18. {timeplus_agentguard_codex_plugin-0.3.0 → timeplus_agentguard_codex_plugin-0.4.0}/tests/test_sink.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: timeplus-agentguard-codex-plugin
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: AgentGuard monitoring plugin for OpenAI Codex
5
5
  Project-URL: Homepage, https://github.com/timeplus-io/agentguard
6
6
  Project-URL: Repository, https://github.com/timeplus-io/agentguard
@@ -122,12 +122,20 @@ configure the plugin.
122
122
  | `--deployment-name` | `AGENTGUARD_DEPLOYMENT_NAME` | `Local Dev` |
123
123
  | `--export` | `AGENTGUARD_CODEX_EXPORT` | `otel` |
124
124
  | `--endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` |
125
+ | | `AGENTGUARD_LLM_CONTENT` | `true` |
126
+ | | `AGENTGUARD_LLM_CONTENT_CHARS` | `4000` |
125
127
 
126
128
  `--export` is `otel` or `hooks`. Any other value (including `both`) is
127
129
  reported on stderr and treated as `otel`. `--endpoint` applies to the `otel`
128
130
  export only; the `hooks` export has its own settings, listed under
129
131
  [Hook-event export](#hook-event-export).
130
132
 
133
+ `AGENTGUARD_LLM_CONTENT` and `AGENTGUARD_LLM_CONTENT_CHARS` apply to both
134
+ exports. They control the response text of a model request: `false` (or `0`,
135
+ `off`, `no`) leaves the text out and keeps its length, the tool calls and the
136
+ phase; the second is the number of characters the text is cut to. See
137
+ [The response of a model request](#the-response-of-a-model-request).
138
+
131
139
  Flags take precedence over environment variables. The plugin resolves every
132
140
  setting (flag, then environment variable, then the default above) before
133
141
  constructing the SDK hooks, so each short-lived hook process sees the same
@@ -177,9 +185,13 @@ Each of the 14 hooks becomes one row:
177
185
  | `tool_name` | The tool, on tool and permission hooks |
178
186
  | `model`, `provider` | The model slug; the provider from the session transcript, or `openai` |
179
187
  | `hook_decision` | `observe` |
180
- | `event_data` | The Codex hook payload as received (`prompt`, `last_assistant_message`, `tool_input`, `tool_response`, `tool_use_id`, `token_usage`, `cwd`, `source`, `trigger`, and the subagent's `agent_id` and `agent_type`), plus the two keys below |
188
+ | `event_data` | The Codex hook payload as received (`prompt`, `last_assistant_message`, `tool_input`, `tool_response`, `tool_use_id`, `token_usage`, `cwd`, `source`, `trigger`, and the subagent's `agent_id` and `agent_type`), plus the keys below |
189
+
190
+ These keys are added to `event_data`:
181
191
 
182
- Two keys are added to `event_data`:
192
+ - `response` and `request` are on `post_model_request`, when the request is
193
+ found in the session transcript. See
194
+ [The response of a model request](#the-response-of-a-model-request).
183
195
 
184
196
  - `agentguard.export` is always `hooks`. On the `otel` path the app copies
185
197
  some spans into `agentguard_hook_events` with the same `agent_type`; this
@@ -267,6 +279,8 @@ Per span:
267
279
  | `codex.request.id`, `codex.request.attempt`, `codex.request.kind`, `codex.thread_id` | model request spans | `request_id`, `attempt_number`, `kind`, `thread_id` |
268
280
  | `codex.request.status`, `codex.request.error` | `post_model_request` | `status` (`completed`, `failed`, `cancelled`), `error` |
269
281
  | `llm.token_count.prompt`, `.completion`, `.total`, `.prompt_details.cache_read`, `.prompt_details.cache_write`, `.completion_details.reasoning` | `post_model_request`, when Codex reports usage | `token_usage` |
282
+ | `agentguard.response.text`, `.text_chars`, `.tool_calls`, `.phase` | `post_model_request`, when the request is found in the session transcript | the response in the transcript; `tool_calls` is a JSON list of `{id, name}` |
283
+ | `agentguard.request.effort`, `agentguard.request.summary` | `post_model_request`, same condition | the turn's `turn_context` in the transcript |
270
284
  | `output.value` | `stop`, `subagent_stop` | `last_assistant_message` |
271
285
  | `codex.stop_hook_active` | `stop`, `subagent_stop` | `stop_hook_active` |
272
286
  | `codex.agent_transcript_path` | `subagent_stop` | `agent_transcript_path` |
@@ -296,6 +310,34 @@ These are three separate records, so counting one does not count another:
296
310
  Subagent hooks carry the parent's `session.id`; `agentguard.subagent.id`
297
311
  identifies the child.
298
312
 
313
+ ### The response of a model request
314
+
315
+ The `PostModelRequest` payload has the token usage of a request and none of
316
+ its content. The plugin reads the content from the session transcript
317
+ (`transcript_path`) and adds it to the `post_model_request` row or span:
318
+
319
+ | Hook-event row (`event_data`) | Span attribute | Content |
320
+ |---|---|---|
321
+ | `response.text` | `agentguard.response.text` | The assistant text of the response, cut to `AGENTGUARD_LLM_CONTENT_CHARS`. Left out when `AGENTGUARD_LLM_CONTENT=false`. |
322
+ | `response.text_chars` | `agentguard.response.text_chars` | Length of the text before the cut |
323
+ | `response.tool_calls` | `agentguard.response.tool_calls` | The tool calls the response asked for, as `{id, name}`. The id is the transcript's `call_id`. Inputs and results are on the tool events. |
324
+ | `response.phase` | `agentguard.response.phase` | `commentary` or `final_answer`, when Codex records it |
325
+ | `request.effort`, `request.summary` | `agentguard.request.effort`, `agentguard.request.summary` | The reasoning settings of the turn |
326
+
327
+ Notes:
328
+
329
+ - The request is found by its turn and its token counts, because the hook and
330
+ the transcript share no id that is known to match. When it is not found
331
+ (a failed or cancelled attempt, a transcript that cannot be read, a format
332
+ this version does not know), the row or span is sent without these fields.
333
+ - The transcript may not hold the response yet when the hook runs. The plugin
334
+ waits up to 0.5 seconds for it; Codex waits for the hook during that time.
335
+ - Reasoning content is not sent: the transcript holds it encrypted. Its size
336
+ is `reasoning_output_tokens` in the token usage.
337
+ - The span attributes are AgentGuard's own names, not OpenInference's
338
+ `llm.output_messages`, so the app does not show a line of commentary before
339
+ a tool call as the assistant's reply.
340
+
299
341
  ### What the AgentGuard app shows
300
342
 
301
343
  With the app's current OpenInference views (app 0.4.0), a Codex session gives:
@@ -101,12 +101,20 @@ configure the plugin.
101
101
  | `--deployment-name` | `AGENTGUARD_DEPLOYMENT_NAME` | `Local Dev` |
102
102
  | `--export` | `AGENTGUARD_CODEX_EXPORT` | `otel` |
103
103
  | `--endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` |
104
+ | | `AGENTGUARD_LLM_CONTENT` | `true` |
105
+ | | `AGENTGUARD_LLM_CONTENT_CHARS` | `4000` |
104
106
 
105
107
  `--export` is `otel` or `hooks`. Any other value (including `both`) is
106
108
  reported on stderr and treated as `otel`. `--endpoint` applies to the `otel`
107
109
  export only; the `hooks` export has its own settings, listed under
108
110
  [Hook-event export](#hook-event-export).
109
111
 
112
+ `AGENTGUARD_LLM_CONTENT` and `AGENTGUARD_LLM_CONTENT_CHARS` apply to both
113
+ exports. They control the response text of a model request: `false` (or `0`,
114
+ `off`, `no`) leaves the text out and keeps its length, the tool calls and the
115
+ phase; the second is the number of characters the text is cut to. See
116
+ [The response of a model request](#the-response-of-a-model-request).
117
+
110
118
  Flags take precedence over environment variables. The plugin resolves every
111
119
  setting (flag, then environment variable, then the default above) before
112
120
  constructing the SDK hooks, so each short-lived hook process sees the same
@@ -156,9 +164,13 @@ Each of the 14 hooks becomes one row:
156
164
  | `tool_name` | The tool, on tool and permission hooks |
157
165
  | `model`, `provider` | The model slug; the provider from the session transcript, or `openai` |
158
166
  | `hook_decision` | `observe` |
159
- | `event_data` | The Codex hook payload as received (`prompt`, `last_assistant_message`, `tool_input`, `tool_response`, `tool_use_id`, `token_usage`, `cwd`, `source`, `trigger`, and the subagent's `agent_id` and `agent_type`), plus the two keys below |
167
+ | `event_data` | The Codex hook payload as received (`prompt`, `last_assistant_message`, `tool_input`, `tool_response`, `tool_use_id`, `token_usage`, `cwd`, `source`, `trigger`, and the subagent's `agent_id` and `agent_type`), plus the keys below |
168
+
169
+ These keys are added to `event_data`:
160
170
 
161
- Two keys are added to `event_data`:
171
+ - `response` and `request` are on `post_model_request`, when the request is
172
+ found in the session transcript. See
173
+ [The response of a model request](#the-response-of-a-model-request).
162
174
 
163
175
  - `agentguard.export` is always `hooks`. On the `otel` path the app copies
164
176
  some spans into `agentguard_hook_events` with the same `agent_type`; this
@@ -246,6 +258,8 @@ Per span:
246
258
  | `codex.request.id`, `codex.request.attempt`, `codex.request.kind`, `codex.thread_id` | model request spans | `request_id`, `attempt_number`, `kind`, `thread_id` |
247
259
  | `codex.request.status`, `codex.request.error` | `post_model_request` | `status` (`completed`, `failed`, `cancelled`), `error` |
248
260
  | `llm.token_count.prompt`, `.completion`, `.total`, `.prompt_details.cache_read`, `.prompt_details.cache_write`, `.completion_details.reasoning` | `post_model_request`, when Codex reports usage | `token_usage` |
261
+ | `agentguard.response.text`, `.text_chars`, `.tool_calls`, `.phase` | `post_model_request`, when the request is found in the session transcript | the response in the transcript; `tool_calls` is a JSON list of `{id, name}` |
262
+ | `agentguard.request.effort`, `agentguard.request.summary` | `post_model_request`, same condition | the turn's `turn_context` in the transcript |
249
263
  | `output.value` | `stop`, `subagent_stop` | `last_assistant_message` |
250
264
  | `codex.stop_hook_active` | `stop`, `subagent_stop` | `stop_hook_active` |
251
265
  | `codex.agent_transcript_path` | `subagent_stop` | `agent_transcript_path` |
@@ -275,6 +289,34 @@ These are three separate records, so counting one does not count another:
275
289
  Subagent hooks carry the parent's `session.id`; `agentguard.subagent.id`
276
290
  identifies the child.
277
291
 
292
+ ### The response of a model request
293
+
294
+ The `PostModelRequest` payload has the token usage of a request and none of
295
+ its content. The plugin reads the content from the session transcript
296
+ (`transcript_path`) and adds it to the `post_model_request` row or span:
297
+
298
+ | Hook-event row (`event_data`) | Span attribute | Content |
299
+ |---|---|---|
300
+ | `response.text` | `agentguard.response.text` | The assistant text of the response, cut to `AGENTGUARD_LLM_CONTENT_CHARS`. Left out when `AGENTGUARD_LLM_CONTENT=false`. |
301
+ | `response.text_chars` | `agentguard.response.text_chars` | Length of the text before the cut |
302
+ | `response.tool_calls` | `agentguard.response.tool_calls` | The tool calls the response asked for, as `{id, name}`. The id is the transcript's `call_id`. Inputs and results are on the tool events. |
303
+ | `response.phase` | `agentguard.response.phase` | `commentary` or `final_answer`, when Codex records it |
304
+ | `request.effort`, `request.summary` | `agentguard.request.effort`, `agentguard.request.summary` | The reasoning settings of the turn |
305
+
306
+ Notes:
307
+
308
+ - The request is found by its turn and its token counts, because the hook and
309
+ the transcript share no id that is known to match. When it is not found
310
+ (a failed or cancelled attempt, a transcript that cannot be read, a format
311
+ this version does not know), the row or span is sent without these fields.
312
+ - The transcript may not hold the response yet when the hook runs. The plugin
313
+ waits up to 0.5 seconds for it; Codex waits for the hook during that time.
314
+ - Reasoning content is not sent: the transcript holds it encrypted. Its size
315
+ is `reasoning_output_tokens` in the token usage.
316
+ - The span attributes are AgentGuard's own names, not OpenInference's
317
+ `llm.output_messages`, so the app does not show a line of commentary before
318
+ a tool call as the assistant's reply.
319
+
278
320
  ### What the AgentGuard app shows
279
321
 
280
322
  With the app's current OpenInference views (app 0.4.0), a Codex session gives:
@@ -1,3 +1,3 @@
1
1
  """AgentGuard monitoring plugin for OpenAI Codex."""
2
2
 
3
- __version__ = "0.3.0"
3
+ __version__ = "0.4.0"
@@ -32,6 +32,8 @@ import json
32
32
  from collections.abc import Callable
33
33
  from typing import Any, Protocol
34
34
 
35
+ from agentguard_codex.transcript import ContentConfig, read_response
36
+
35
37
  #: Reported as the provider when the session transcript does not name one.
36
38
  DEFAULT_PROVIDER = "openai"
37
39
 
@@ -177,15 +179,19 @@ def _emit(
177
179
  start_time_ns: int | None = None,
178
180
  error: str | None = None,
179
181
  span: bool = True,
182
+ payload_extra: dict[str, Any] | None = None,
180
183
  ) -> None:
181
184
  attributes = {**_common_attributes(event), **(extra or {})}
182
185
  attributes = {k: v for k, v in attributes.items() if v is not None}
186
+ # What the plugin adds to the payload for the hook-event path. A span sink
187
+ # ignores the payload; it gets the same values as attributes.
188
+ payload = {**event, **payload_extra} if payload_extra else event
183
189
  if not span:
184
190
  hooks.emit_no_span(
185
191
  session_id=event["session_id"],
186
192
  run_id=event.get("turn_id"),
187
193
  attributes=attributes,
188
- payload=event,
194
+ payload=payload,
189
195
  )
190
196
  return
191
197
  hooks.emit_span(
@@ -196,7 +202,7 @@ def _emit(
196
202
  attributes=attributes,
197
203
  start_time_ns=start_time_ns,
198
204
  error=error,
199
- payload=event,
205
+ payload=payload,
200
206
  )
201
207
 
202
208
 
@@ -316,16 +322,49 @@ def _post_model_request(event: dict[str, Any], hooks: HookSink) -> None:
316
322
  if isinstance(value, int) and not isinstance(value, bool):
317
323
  extra[attribute] = value
318
324
 
325
+ payload_extra = _model_response(event, extra)
326
+
319
327
  _emit(
320
328
  event,
321
329
  hooks,
322
330
  extra,
331
+ payload_extra=payload_extra,
323
332
  task_id=event.get("request_id"),
324
333
  start_time_ns=hooks.take_start(_model_request_key(event)),
325
334
  error=(error or "model request failed") if status == "failed" else None,
326
335
  )
327
336
 
328
337
 
338
+ def _model_response(event: dict[str, Any], attributes: dict[str, Any]) -> dict[str, Any]:
339
+ """Add what the model answered, read from the rollout file.
340
+
341
+ Fills *attributes* (the span) and returns the ``response`` / ``request``
342
+ objects for the hook-event row. Both are empty when the request is not
343
+ found in the file. The span attributes are AgentGuard's own names, not
344
+ OpenInference's ``llm.output_messages``: this is the response of one
345
+ request, which may be a tool call with a line of commentary, and the app
346
+ decides separately whether to show it as an assistant message.
347
+ """
348
+ found = read_response(
349
+ event.get("transcript_path"), event.get("turn_id"), event.get("token_usage")
350
+ )
351
+ if found is None:
352
+ return {}
353
+ response = found.response_data(ContentConfig.from_env())
354
+ request = found.request_data()
355
+
356
+ attributes["agentguard.response.text"] = response.get("text")
357
+ attributes["agentguard.response.text_chars"] = response["text_chars"]
358
+ attributes["agentguard.response.tool_calls"] = json.dumps(
359
+ response["tool_calls"], ensure_ascii=False
360
+ )
361
+ attributes["agentguard.response.phase"] = response.get("phase")
362
+ attributes["agentguard.request.effort"] = request.get("effort")
363
+ attributes["agentguard.request.summary"] = request.get("summary")
364
+
365
+ return {"response": response, **({"request": request} if request else {})}
366
+
367
+
329
368
  def _stop(event: dict[str, Any], hooks: HookSink) -> None:
330
369
  _emit(
331
370
  event,
@@ -0,0 +1,226 @@
1
+ """Read what the model answered from a Codex rollout file.
2
+
3
+ The ``PostModelRequest`` hook payload has the token usage of a model request
4
+ and none of its content. The rollout file (``transcript_path``) has both: the
5
+ ``response_item`` lines of a response, followed by one ``token_usage_record``
6
+ line that closes the request::
7
+
8
+ response_item message (assistant, phase=commentary)
9
+ response_item custom_tool_call (call_id, name)
10
+ token_usage_record (turn_id, usage)
11
+
12
+ The hook and the file share no request id that is known to match, so a request
13
+ is found by its turn and its token counts. The file may not hold the lines of
14
+ the request yet when the hook fires, so :func:`read_response` polls for a short
15
+ time. The rollout format is not a stable interface: anything unexpected yields
16
+ ``None`` and the event is exported without the response.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import time
24
+ from collections.abc import Callable
25
+ from dataclasses import dataclass, field
26
+ from typing import Any
27
+
28
+ #: Token counts compared between the hook payload and a ``token_usage_record``.
29
+ USAGE_FIELDS = (
30
+ "input_tokens",
31
+ "output_tokens",
32
+ "total_tokens",
33
+ "cached_input_tokens",
34
+ "cache_write_input_tokens",
35
+ "reasoning_output_tokens",
36
+ )
37
+
38
+ #: Only the end of the file is read: the lines of the request that just
39
+ #: returned are the last ones written. In a turn longer than this the
40
+ #: ``turn_context`` line is out of reach and the request settings are left out.
41
+ TAIL_BYTES = 8 * 1024 * 1024
42
+
43
+ #: How long to wait for the lines of a request to reach the file. Codex waits
44
+ #: for the hook, so this is also the most the plugin can delay a model request.
45
+ WAIT_SECONDS = 0.5
46
+ POLL_SECONDS = 0.05
47
+
48
+ DEFAULT_CONTENT_CHARS = 4000
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class ContentConfig:
53
+ """Whether the response text is sent, and how much of it."""
54
+
55
+ content: bool = True
56
+ content_chars: int = DEFAULT_CONTENT_CHARS
57
+
58
+ @classmethod
59
+ def from_env(cls, env: dict[str, str] | None = None) -> ContentConfig:
60
+ """Read the settings the Claude Code plugin uses for the same thing."""
61
+ env = os.environ if env is None else env
62
+ switch = env.get("AGENTGUARD_LLM_CONTENT", "").strip().lower()
63
+ chars = env.get("AGENTGUARD_LLM_CONTENT_CHARS", "").strip()
64
+ return cls(
65
+ content=switch not in ("false", "0", "off", "no"),
66
+ # Digits only; anything else keeps the default.
67
+ content_chars=int(chars) if chars.isdigit() else DEFAULT_CONTENT_CHARS,
68
+ )
69
+
70
+
71
+ @dataclass
72
+ class ModelResponse:
73
+ """The response of one model request, and the settings it was sent with."""
74
+
75
+ text: str = ""
76
+ tool_calls: list[dict[str, str]] = field(default_factory=list)
77
+ phase: str | None = None
78
+ effort: str | None = None
79
+ summary: str | None = None
80
+
81
+ def response_data(self, config: ContentConfig) -> dict[str, Any]:
82
+ """The ``response`` object of a hook-event row."""
83
+ data: dict[str, Any] = {}
84
+ if config.content:
85
+ data["text"] = self.text[: config.content_chars]
86
+ data["text_chars"] = len(self.text)
87
+ data["tool_calls"] = self.tool_calls
88
+ if self.phase:
89
+ data["phase"] = self.phase
90
+ return data
91
+
92
+ def request_data(self) -> dict[str, Any]:
93
+ """The ``request`` object of a hook-event row; empty when nothing is known."""
94
+ data = {"effort": self.effort, "summary": self.summary}
95
+ return {k: v for k, v in data.items() if v}
96
+
97
+
98
+ def _count(value: Any) -> int | None:
99
+ # bool is an int subclass; a stray true/false is not a token count.
100
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
101
+
102
+
103
+ def _same_usage(hook_usage: dict[str, Any], record_usage: Any) -> bool:
104
+ """True when every count both sides have is equal, and they share at least one."""
105
+ if not isinstance(record_usage, dict):
106
+ return False
107
+ compared = 0
108
+ for name in USAGE_FIELDS:
109
+ a, b = _count(hook_usage.get(name)), _count(record_usage.get(name))
110
+ if a is None or b is None:
111
+ continue
112
+ if a != b:
113
+ return False
114
+ compared += 1
115
+ return compared > 0
116
+
117
+
118
+ def _read_tail(path: str) -> list[dict[str, Any]]:
119
+ """The records at the end of the file; lines that are not JSON objects are skipped."""
120
+ with open(path, "rb") as f:
121
+ f.seek(0, os.SEEK_END)
122
+ size = f.tell()
123
+ start = max(0, size - TAIL_BYTES)
124
+ f.seek(start)
125
+ data = f.read()
126
+ lines = data.split(b"\n")
127
+ if start > 0:
128
+ lines = lines[1:] # the first line is cut somewhere in the middle
129
+ records = []
130
+ for line in lines:
131
+ if not line.strip():
132
+ continue
133
+ try:
134
+ record = json.loads(line)
135
+ except ValueError:
136
+ continue # includes a last line that is still being written
137
+ if isinstance(record, dict):
138
+ records.append(record)
139
+ return records
140
+
141
+
142
+ def _add_item(response: ModelResponse, item: dict[str, Any]) -> None:
143
+ kind = item.get("type")
144
+ if kind == "message":
145
+ if item.get("role") != "assistant":
146
+ return
147
+ content = item.get("content")
148
+ parts = [
149
+ block["text"]
150
+ for block in (content if isinstance(content, list) else [])
151
+ if isinstance(block, dict)
152
+ and block.get("type") == "output_text"
153
+ and isinstance(block.get("text"), str)
154
+ ]
155
+ if parts:
156
+ text = "\n".join(parts)
157
+ response.text = f"{response.text}\n{text}" if response.text else text
158
+ if isinstance(item.get("phase"), str):
159
+ response.phase = item["phase"]
160
+ return
161
+ # function_call, custom_tool_call, local_shell_call, ...: the call id is
162
+ # what the tool hooks carry as tool_use_id. Inputs are in the tool events.
163
+ call_id = item.get("call_id")
164
+ if isinstance(kind, str) and kind.endswith("_call") and isinstance(call_id, str) and call_id:
165
+ name = item.get("name")
166
+ response.tool_calls.append({"id": call_id, "name": name if isinstance(name, str) else kind})
167
+
168
+
169
+ def find_response(
170
+ records: list[dict[str, Any]], turn_id: Any, token_usage: dict[str, Any]
171
+ ) -> ModelResponse | None:
172
+ """Find the request with these token counts in *records*; the last one wins."""
173
+ found: ModelResponse | None = None
174
+ settings: dict[Any, tuple[Any, Any]] = {}
175
+ current = ModelResponse()
176
+ for record in records:
177
+ payload = record.get("payload")
178
+ if not isinstance(payload, dict):
179
+ continue
180
+ kind = record.get("type")
181
+ if kind == "turn_context":
182
+ settings[payload.get("turn_id")] = (payload.get("effort"), payload.get("summary"))
183
+ elif kind == "event_msg" and payload.get("type") == "task_started":
184
+ current = ModelResponse() # nothing before a turn belongs to its first request
185
+ elif kind == "response_item":
186
+ _add_item(current, payload)
187
+ elif kind == "token_usage_record":
188
+ record_turn = payload.get("turn_id")
189
+ same_turn = turn_id is None or record_turn is None or record_turn == turn_id
190
+ if same_turn and _same_usage(token_usage, payload.get("usage")):
191
+ effort, summary = settings.get(record_turn, (None, None))
192
+ current.effort = effort if isinstance(effort, str) else None
193
+ current.summary = summary if isinstance(summary, str) else None
194
+ found = current
195
+ current = ModelResponse()
196
+ return found
197
+
198
+
199
+ def read_response(
200
+ transcript_path: Any,
201
+ turn_id: Any,
202
+ token_usage: Any,
203
+ *,
204
+ wait_seconds: float | None = None,
205
+ sleep: Callable[[float], None] = time.sleep,
206
+ ) -> ModelResponse | None:
207
+ """The response of the model request that reported *token_usage*, or ``None``.
208
+
209
+ Without token counts (a failed or cancelled attempt) there is nothing to
210
+ match on and the file is not read.
211
+ """
212
+ if not isinstance(transcript_path, str) or not transcript_path:
213
+ return None
214
+ if not isinstance(token_usage, dict) or not any(
215
+ _count(token_usage.get(name)) is not None for name in USAGE_FIELDS
216
+ ):
217
+ return None
218
+ deadline = time.monotonic() + (WAIT_SECONDS if wait_seconds is None else wait_seconds)
219
+ while True:
220
+ try:
221
+ found = find_response(_read_tail(transcript_path), turn_id, token_usage)
222
+ except OSError:
223
+ return None # no file: waiting will not help
224
+ if found is not None or time.monotonic() >= deadline:
225
+ return found
226
+ sleep(POLL_SECONDS)
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "timeplus-agentguard-codex-plugin"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "AgentGuard monitoring plugin for OpenAI Codex"
9
9
  readme = "README.md"
10
10
  license = { text = "Apache-2.0" }
@@ -11,6 +11,7 @@ import os
11
11
  import sys
12
12
  import tempfile
13
13
  import unittest
14
+ from unittest import mock
14
15
 
15
16
  PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
17
  sys.path.insert(0, PLUGIN_ROOT)
@@ -715,5 +716,103 @@ class CoverageTests(unittest.TestCase):
715
716
  self.assertLessEqual(hook["timeout"], 3)
716
717
 
717
718
 
719
+
720
+ class ModelResponseTests(unittest.TestCase):
721
+ """PostModelRequest with a rollout file that holds the response."""
722
+
723
+ USAGE = {"input_tokens": 100, "output_tokens": 38, "total_tokens": 138}
724
+
725
+ def setUp(self) -> None:
726
+ folder = tempfile.TemporaryDirectory()
727
+ self.addCleanup(folder.cleanup)
728
+ self.path = os.path.join(folder.name, "rollout.jsonl")
729
+ records = [
730
+ {"type": "turn_context", "payload": {"turn_id": "t1", "effort": "high"}},
731
+ {
732
+ "type": "response_item",
733
+ "payload": {
734
+ "type": "message",
735
+ "role": "assistant",
736
+ "phase": "commentary",
737
+ "content": [{"type": "output_text", "text": "Running the tests."}],
738
+ },
739
+ },
740
+ {
741
+ "type": "response_item",
742
+ "payload": {"type": "function_call", "call_id": "call_1", "name": "shell"},
743
+ },
744
+ {"type": "token_usage_record", "payload": {"turn_id": "t1", "usage": self.USAGE}},
745
+ ]
746
+ with open(self.path, "w", encoding="utf-8") as f:
747
+ f.writelines(json.dumps(record) + "\n" for record in records)
748
+ self.event = {
749
+ **COMMON,
750
+ "transcript_path": self.path,
751
+ "hook_event_name": "PostModelRequest",
752
+ "request_id": "req_1",
753
+ "status": "completed",
754
+ "token_usage": self.USAGE,
755
+ }
756
+
757
+ def emit(self, event: dict) -> dict:
758
+ hooks = RecordingHooks()
759
+ dispatch(event, hooks)
760
+ (_, _, kwargs), = hooks.calls
761
+ return kwargs
762
+
763
+ def test_response_and_request_on_span_and_payload(self) -> None:
764
+ span = self.emit(self.event)
765
+
766
+ attributes = span["attributes"]
767
+ self.assertEqual(attributes["agentguard.response.text"], "Running the tests.")
768
+ self.assertEqual(attributes["agentguard.response.text_chars"], 18)
769
+ self.assertEqual(
770
+ json.loads(attributes["agentguard.response.tool_calls"]),
771
+ [{"id": "call_1", "name": "shell"}],
772
+ )
773
+ self.assertEqual(attributes["agentguard.response.phase"], "commentary")
774
+ self.assertEqual(attributes["agentguard.request.effort"], "high")
775
+ self.assertNotIn("agentguard.request.summary", attributes)
776
+ # Not the OpenInference name the app reads as the assistant message.
777
+ self.assertNotIn("llm.output_messages.0.message.content", attributes)
778
+
779
+ self.assertEqual(
780
+ span["payload"],
781
+ {
782
+ **self.event,
783
+ "response": {
784
+ "text": "Running the tests.",
785
+ "text_chars": 18,
786
+ "tool_calls": [{"id": "call_1", "name": "shell"}],
787
+ "phase": "commentary",
788
+ },
789
+ "request": {"effort": "high"},
790
+ },
791
+ )
792
+
793
+ def test_content_switch_and_limit(self) -> None:
794
+ saved = dict(os.environ)
795
+ self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
796
+
797
+ os.environ["AGENTGUARD_LLM_CONTENT_CHARS"] = "7"
798
+ span = self.emit(self.event)
799
+ self.assertEqual(span["attributes"]["agentguard.response.text"], "Running")
800
+ self.assertEqual(span["payload"]["response"]["text"], "Running")
801
+
802
+ os.environ["AGENTGUARD_LLM_CONTENT"] = "false"
803
+ span = self.emit(self.event)
804
+ self.assertNotIn("agentguard.response.text", span["attributes"])
805
+ self.assertNotIn("text", span["payload"]["response"])
806
+ self.assertEqual(span["attributes"]["agentguard.response.text_chars"], 18)
807
+
808
+ def test_request_not_in_the_file_is_exported_as_before(self) -> None:
809
+ event = {**self.event, "token_usage": {"input_tokens": 1, "output_tokens": 1}}
810
+ with mock.patch("agentguard_codex.transcript.WAIT_SECONDS", 0):
811
+ span = self.emit(event)
812
+
813
+ self.assertIs(span["payload"], event)
814
+ self.assertFalse([k for k in span["attributes"] if k.startswith("agentguard.re")])
815
+
816
+
718
817
  if __name__ == "__main__":
719
818
  unittest.main()
@@ -0,0 +1,213 @@
1
+ """Unit tests for reading a model response from a Codex rollout file.
2
+
3
+ Run: python3.12 -m unittest discover -s tests -v
4
+ """
5
+
6
+ import json
7
+ import os
8
+ import sys
9
+ import tempfile
10
+ import unittest
11
+
12
+ PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
+ sys.path.insert(0, PLUGIN_ROOT)
14
+
15
+ from agentguard_codex.transcript import ( # noqa: E402
16
+ ContentConfig,
17
+ ModelResponse,
18
+ find_response,
19
+ read_response,
20
+ )
21
+
22
+ USAGE_1 = {"input_tokens": 100, "cached_input_tokens": 40, "output_tokens": 38, "total_tokens": 138}
23
+ USAGE_2 = {"input_tokens": 180, "cached_input_tokens": 100, "output_tokens": 12, "total_tokens": 192}
24
+
25
+
26
+ def line(kind: str, payload: dict) -> dict:
27
+ return {"timestamp": "2026-11-30T18:21:50.000Z", "type": kind, "payload": payload}
28
+
29
+
30
+ def message(text: str, *, role: str = "assistant", phase: str | None = None) -> dict:
31
+ block = "output_text" if role == "assistant" else "input_text"
32
+ payload = {"type": "message", "role": role, "content": [{"type": block, "text": text}]}
33
+ if phase:
34
+ payload["phase"] = phase
35
+ return line("response_item", payload)
36
+
37
+
38
+ def usage(turn_id: str, counts: dict) -> dict:
39
+ return line("token_usage_record", {"turn_id": turn_id, "response_id": "resp_1", "usage": counts})
40
+
41
+
42
+ def turn(turn_id: str = "t1") -> list[dict]:
43
+ """One turn: a commentary line with a tool call, then the final answer."""
44
+ return [
45
+ line("event_msg", {"type": "task_started", "turn_id": turn_id}),
46
+ line("turn_context", {"turn_id": turn_id, "effort": "medium", "summary": "auto"}),
47
+ message("run echo", role="user"),
48
+ message("I'll run the command now.", phase="commentary"),
49
+ line(
50
+ "response_item",
51
+ {"type": "custom_tool_call", "call_id": "call_1", "name": "exec", "input": "echo 1"},
52
+ ),
53
+ usage(turn_id, USAGE_1),
54
+ line("response_item", {"type": "custom_tool_call_output", "call_id": "call_1", "output": "1"}),
55
+ line("response_item", {"type": "reasoning", "summary": [], "encrypted_content": "xxxx"}),
56
+ message("The command printed 1.", phase="final_answer"),
57
+ usage(turn_id, USAGE_2),
58
+ line("event_msg", {"type": "task_complete", "turn_id": turn_id}),
59
+ ]
60
+
61
+
62
+ class FindResponseTests(unittest.TestCase):
63
+ def test_request_with_a_tool_call(self) -> None:
64
+ found = find_response(turn(), "t1", USAGE_1)
65
+
66
+ self.assertEqual(found.text, "I'll run the command now.")
67
+ self.assertEqual(found.tool_calls, [{"id": "call_1", "name": "exec"}])
68
+ self.assertEqual(found.phase, "commentary")
69
+ self.assertEqual((found.effort, found.summary), ("medium", "auto"))
70
+
71
+ def test_final_answer_has_no_tool_calls_and_no_earlier_text(self) -> None:
72
+ found = find_response(turn(), "t1", USAGE_2)
73
+
74
+ # Neither the user's prompt nor the tool output is part of the response.
75
+ self.assertEqual(found.text, "The command printed 1.")
76
+ self.assertEqual(found.tool_calls, [])
77
+ self.assertEqual(found.phase, "final_answer")
78
+
79
+ def test_text_blocks_and_messages_are_joined(self) -> None:
80
+ records = [message("one"), message("two"), usage("t1", USAGE_1)]
81
+
82
+ self.assertEqual(find_response(records, "t1", USAGE_1).text, "one\ntwo")
83
+
84
+ def test_function_call_without_a_name_uses_its_type(self) -> None:
85
+ records = [
86
+ line("response_item", {"type": "local_shell_call", "call_id": "call_9"}),
87
+ line("response_item", {"type": "web_search_call", "id": "ws_1"}), # no call id
88
+ usage("t1", USAGE_1),
89
+ ]
90
+
91
+ self.assertEqual(
92
+ find_response(records, "t1", USAGE_1).tool_calls,
93
+ [{"id": "call_9", "name": "local_shell_call"}],
94
+ )
95
+
96
+ def test_no_match_on_other_counts_or_another_turn(self) -> None:
97
+ self.assertIsNone(find_response(turn(), "t1", {**USAGE_1, "output_tokens": 39}))
98
+ self.assertIsNone(find_response(turn(), "t2", USAGE_1))
99
+ self.assertIsNone(find_response(turn(), "t1", {"unknown": 1}))
100
+
101
+ def test_hook_without_a_turn_id_matches_on_counts(self) -> None:
102
+ self.assertEqual(find_response(turn(), None, USAGE_2).phase, "final_answer")
103
+
104
+ def test_same_counts_twice_takes_the_last(self) -> None:
105
+ records = [message("first"), usage("t1", USAGE_1), message("second"), usage("t1", USAGE_1)]
106
+
107
+ self.assertEqual(find_response(records, "t1", USAGE_1).text, "second")
108
+
109
+ def test_previous_turn_does_not_leak_into_the_next(self) -> None:
110
+ # An interrupted turn leaves a response without a usage record.
111
+ records = [message("left over"), *turn("t2")]
112
+
113
+ self.assertEqual(find_response(records, "t2", USAGE_1).text, "I'll run the command now.")
114
+
115
+ def test_unexpected_shapes_are_skipped(self) -> None:
116
+ records = [
117
+ {"type": "response_item"},
118
+ {"type": "response_item", "payload": "text"},
119
+ line("response_item", {"type": "message", "role": "assistant", "content": "plain"}),
120
+ line("response_item", {"type": "message", "role": "assistant", "content": [None, {}]}),
121
+ usage("t1", USAGE_1),
122
+ ]
123
+
124
+ found = find_response(records, "t1", USAGE_1)
125
+ self.assertEqual((found.text, found.tool_calls), ("", []))
126
+
127
+
128
+ class ReadResponseTests(unittest.TestCase):
129
+ def setUp(self) -> None:
130
+ folder = tempfile.TemporaryDirectory()
131
+ self.addCleanup(folder.cleanup)
132
+ self.path = os.path.join(folder.name, "rollout.jsonl")
133
+
134
+ def write(self, records: list[dict], *, tail: str = "") -> None:
135
+ with open(self.path, "w", encoding="utf-8") as f:
136
+ for record in records:
137
+ f.write(json.dumps(record) + "\n")
138
+ f.write(tail)
139
+
140
+ def test_reads_the_request_from_the_file(self) -> None:
141
+ self.write(turn(), tail='{"type": "response_item", "payl') # a line still being written
142
+
143
+ found = read_response(self.path, "t1", USAGE_2, wait_seconds=0)
144
+ self.assertEqual(found.text, "The command printed 1.")
145
+
146
+ def test_waits_for_lines_that_are_not_written_yet(self) -> None:
147
+ records = turn()
148
+ self.write(records[:9]) # the final answer and its usage record are missing
149
+ sleeps = []
150
+
151
+ def sleep(seconds: float) -> None:
152
+ sleeps.append(seconds)
153
+ self.write(records)
154
+
155
+ found = read_response(self.path, "t1", USAGE_2, wait_seconds=5, sleep=sleep)
156
+ self.assertEqual(found.text, "The command printed 1.")
157
+ self.assertEqual(len(sleeps), 1)
158
+
159
+ def test_gives_up_when_the_request_never_appears(self) -> None:
160
+ self.write(turn())
161
+
162
+ self.assertIsNone(read_response(self.path, "t1", {"input_tokens": 7}, wait_seconds=0))
163
+
164
+ def test_no_file_no_path_or_no_counts_returns_at_once(self) -> None:
165
+ def sleep(_: float) -> None:
166
+ self.fail("must not wait")
167
+
168
+ self.write(turn())
169
+ self.assertIsNone(read_response(self.path + ".missing", "t1", USAGE_1, sleep=sleep))
170
+ self.assertIsNone(read_response(None, "t1", USAGE_1, sleep=sleep))
171
+ self.assertIsNone(read_response(self.path, "t1", None, sleep=sleep))
172
+ self.assertIsNone(read_response(self.path, "t1", {"input_tokens": True}, sleep=sleep))
173
+
174
+
175
+ class ResponseDataTests(unittest.TestCase):
176
+ RESPONSE = ModelResponse(
177
+ text="x" * 50, tool_calls=[{"id": "c", "name": "exec"}], phase="commentary", effort="high"
178
+ )
179
+
180
+ def test_text_is_cut_and_its_full_length_kept(self) -> None:
181
+ data = self.RESPONSE.response_data(ContentConfig(content_chars=10))
182
+
183
+ self.assertEqual(data["text"], "x" * 10)
184
+ self.assertEqual(data["text_chars"], 50)
185
+ self.assertEqual(data["tool_calls"], [{"id": "c", "name": "exec"}])
186
+ self.assertEqual(data["phase"], "commentary")
187
+
188
+ def test_content_off_drops_only_the_text(self) -> None:
189
+ data = self.RESPONSE.response_data(ContentConfig(content=False))
190
+
191
+ self.assertNotIn("text", data)
192
+ self.assertEqual(data["text_chars"], 50)
193
+ self.assertEqual(data["tool_calls"], [{"id": "c", "name": "exec"}])
194
+
195
+ def test_request_data_leaves_out_what_is_unknown(self) -> None:
196
+ self.assertEqual(self.RESPONSE.request_data(), {"effort": "high"})
197
+ self.assertEqual(ModelResponse().request_data(), {})
198
+
199
+ def test_config_from_env(self) -> None:
200
+ self.assertEqual(ContentConfig.from_env({}), ContentConfig(True, 4000))
201
+ for value in ("false", "0", "OFF", " no "):
202
+ self.assertFalse(ContentConfig.from_env({"AGENTGUARD_LLM_CONTENT": value}).content)
203
+ self.assertTrue(ContentConfig.from_env({"AGENTGUARD_LLM_CONTENT": "true"}).content)
204
+ self.assertEqual(
205
+ ContentConfig.from_env({"AGENTGUARD_LLM_CONTENT_CHARS": "200"}).content_chars, 200
206
+ )
207
+ self.assertEqual(
208
+ ContentConfig.from_env({"AGENTGUARD_LLM_CONTENT_CHARS": "-5"}).content_chars, 4000
209
+ )
210
+
211
+
212
+ if __name__ == "__main__":
213
+ unittest.main()