timeplus-agentguard-codex-plugin 0.2.0__tar.gz → 0.3.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 (16) hide show
  1. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/PKG-INFO +92 -10
  2. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/README.md +91 -9
  3. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/agentguard_codex/__init__.py +1 -1
  4. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/agentguard_codex/cli.py +73 -21
  5. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/agentguard_codex/events.py +48 -7
  6. timeplus_agentguard_codex_plugin-0.3.0/agentguard_codex/hookevents.py +218 -0
  7. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/agentguard_codex/sink.py +4 -0
  8. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/pyproject.toml +1 -1
  9. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/tests/test_cli.py +23 -0
  10. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/tests/test_events.py +36 -14
  11. timeplus_agentguard_codex_plugin-0.3.0/tests/test_hookevents.py +360 -0
  12. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/.gitignore +0 -0
  13. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/Makefile +0 -0
  14. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/agentguard_codex/__main__.py +0 -0
  15. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.0}/hooks.json +0 -0
  16. {timeplus_agentguard_codex_plugin-0.2.0 → timeplus_agentguard_codex_plugin-0.3.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.2.0
3
+ Version: 0.3.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
@@ -24,16 +24,24 @@ Description-Content-Type: text/markdown
24
24
  AgentGuard monitoring plugin for [OpenAI Codex](https://github.com/openai/codex).
25
25
 
26
26
  Codex runs a command hook for each lifecycle event and writes one JSON object
27
- to stdin. This plugin reads that event, turns it into an OpenTelemetry span
28
- with the [AgentGuard Python SDK](../../../sdk/python), and exports it to
29
- the [AgentGuard Timeplus app](https://github.com/timeplus-io/apps/tree/main/apps/agentguard)'s
30
- OTLP/HTTP input (default `http://localhost:4318`).
27
+ to stdin. This plugin reads that event and sends it to the
28
+ [AgentGuard Timeplus app](https://github.com/timeplus-io/apps/tree/main/apps/agentguard)
29
+ on one of two export paths:
30
+
31
+ | Export | What is sent | Where | Needs |
32
+ |---|---|---|---|
33
+ | `otel` (default) | One OpenTelemetry span per hook, through the [AgentGuard Python SDK](../../../sdk/python) | The app's OTLP/HTTP input (default `http://localhost:4318`) | Port 4318 |
34
+ | `hooks` | One row per hook in the `agentguard_hook_events` stream, like the Claude Code, OpenClaw and Hermes plugins | Timeplus ingest (default `http://localhost:3218`) | Port 3218, or port 8000 with the Timeplus REST API |
35
+
36
+ Exactly one path is active. There is no setting that sends a session on both,
37
+ so the app never sees the same session twice. See
38
+ [Hook-event export](#hook-event-export) for the second path.
31
39
 
32
40
  ## Requirements
33
41
 
34
42
  - Python 3.10+
35
43
  - A Codex build with hooks enabled
36
- - The AgentGuard Python SDK ([`timeplus-agentguard`](https://pypi.org/project/timeplus-agentguard/) on PyPI, installed automatically as a dependency)
44
+ - The AgentGuard Python SDK ([`timeplus-agentguard`](https://pypi.org/project/timeplus-agentguard/) on PyPI, installed automatically as a dependency). Only the `otel` export uses it; the `hooks` export uses the standard library alone.
37
45
 
38
46
  ## Installation
39
47
 
@@ -112,8 +120,14 @@ configure the plugin.
112
120
  | `--agent-id` | `AGENTGUARD_AGENT_ID` | hostname |
113
121
  | `--deployment-id` | `AGENTGUARD_DEPLOYMENT_ID` | `local` |
114
122
  | `--deployment-name` | `AGENTGUARD_DEPLOYMENT_NAME` | `Local Dev` |
123
+ | `--export` | `AGENTGUARD_CODEX_EXPORT` | `otel` |
115
124
  | `--endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` |
116
125
 
126
+ `--export` is `otel` or `hooks`. Any other value (including `both`) is
127
+ reported on stderr and treated as `otel`. `--endpoint` applies to the `otel`
128
+ export only; the `hooks` export has its own settings, listed under
129
+ [Hook-event export](#hook-event-export).
130
+
117
131
  Flags take precedence over environment variables. The plugin resolves every
118
132
  setting (flag, then environment variable, then the default above) before
119
133
  constructing the SDK hooks, so each short-lived hook process sees the same
@@ -126,12 +140,80 @@ export AGENTGUARD_DEPLOYMENT_NAME="Production Codex"
126
140
  export OTEL_EXPORTER_OTLP_ENDPOINT=http://timeplus.example.com:4318
127
141
  ```
128
142
 
143
+ ## Hook-event export
144
+
145
+ Use this path when the app's OTLP input (port 4318) is not reachable from the
146
+ agent host, or when you want Codex in the same stream as the other plugins.
147
+
148
+ ```bash
149
+ export AGENTGUARD_CODEX_EXPORT=hooks
150
+ export AGENTGUARD_TIMEPLUS_URL=http://timeplus.example.com:3218
151
+ export AGENTGUARD_USERNAME=<timeplus-user>
152
+ export AGENTGUARD_PASSWORD=<timeplus-password>
153
+ ```
154
+
155
+ | Environment variable | Default | Purpose |
156
+ |---|---|---|
157
+ | `AGENTGUARD_TIMEPLUS_URL` | `http://localhost:3218` | Timeplus base URL |
158
+ | `AGENTGUARD_INGEST_API` | `timeplusd` | `timeplusd` (port 3218) or `rest` (the Timeplus REST API, port 8000) |
159
+ | `AGENTGUARD_WORKSPACE` | `default` | REST API workspace id; `default` is correct for self-hosted |
160
+ | `AGENTGUARD_DATABASE` | `ag` | Database of the AgentGuard app |
161
+ | `AGENTGUARD_STREAM` | `agentguard_hook_events` | Target stream |
162
+ | `AGENTGUARD_USERNAME` | `proton` | Timeplus username (Basic auth) |
163
+ | `AGENTGUARD_PASSWORD` | _(empty)_ | Timeplus password (Basic auth) |
164
+
165
+ These are the settings the other hook-event plugins use, with the same
166
+ meaning. They have no flags.
167
+
168
+ Each of the 14 hooks becomes one row:
169
+
170
+ | Column | Value |
171
+ |---|---|
172
+ | `hook_name` | The hook in snake case: `session_start`, `session_end`, `user_prompt_submit`, `pre_tool_use`, `post_tool_use`, `pre_model_request`, `post_model_request`, `stop`, `interrupt`, `subagent_start`, `permission_request`, `pre_compact`, `post_compact`. `SubagentStop` is written as `subagent_ended`, the name the stream already uses for it. |
173
+ | `agent_type` | `codex` |
174
+ | `session_id` | The Codex session id |
175
+ | `run_id` | The turn id, or the session id on hooks without a turn (`SessionStart`, `SessionEnd`) |
176
+ | `agent_id`, `deployment_id`, `deployment_name` | From the settings above |
177
+ | `tool_name` | The tool, on tool and permission hooks |
178
+ | `model`, `provider` | The model slug; the provider from the session transcript, or `openai` |
179
+ | `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 |
181
+
182
+ Two keys are added to `event_data`:
183
+
184
+ - `agentguard.export` is always `hooks`. On the `otel` path the app copies
185
+ some spans into `agentguard_hook_events` with the same `agent_type`; this
186
+ key is how a view tells a row written by the plugin from a copied one.
187
+ - `agentguard.duration_ms` is on closing events that had an opening event:
188
+ `post_tool_use`, `post_model_request`, `post_compact`, `subagent_ended` and
189
+ `session_end`. See [Pairing and timing](#pairing-and-timing).
190
+
191
+ The rows of one hook process go out in a single request with a 2 second
192
+ timeout, so `SessionEnd` and `Interrupt` finish inside Codex's 3 second limit.
193
+
194
+ Check what arrived with:
195
+
196
+ ```sql
197
+ SELECT event_time, hook_name, session_id, run_id, tool_name, model
198
+ FROM table(ag.agentguard_hook_events)
199
+ WHERE agent_type = 'codex' AND json_value(event_data, '$."agentguard.export"') = 'hooks'
200
+ ORDER BY event_time DESC
201
+ LIMIT 20;
202
+ ```
203
+
204
+ The app does not turn these rows into `agentguard_cim_event` and
205
+ `agentguard_cim_metrics` rows yet. That is
206
+ [timeplus-io/apps#71](https://github.com/timeplus-io/apps/issues/71); until it
207
+ ships, the `hooks` export fills `agentguard_hook_events` only.
208
+
129
209
  ## What gets captured
130
210
 
131
211
  The plugin handles all 14 events in the
132
- [Codex hooks reference](https://developers.openai.com/codex/hooks). Each event
133
- becomes one span, exported with the OTel service name `codex`, which the
134
- AgentGuard app reports as the agent type.
212
+ [Codex hooks reference](https://developers.openai.com/codex/hooks). On the
213
+ `otel` export, described in the rest of this section, each event becomes one
214
+ span, exported with the OTel service name `codex`, which the AgentGuard app
215
+ reports as the agent type. The `hooks` export handles the same 14 events; its
216
+ row format is under [Hook-event export](#hook-event-export).
135
217
 
136
218
  | Codex hook | Emitted span | What it carries |
137
219
  |---|---|---|
@@ -257,7 +339,7 @@ status and token usage.
257
339
  ## Development
258
340
 
259
341
  ```bash
260
- make test # unit tests; the end-to-end telemetry tests are skipped unless the SDK is installed
342
+ make test # unit tests; the end-to-end OTel tests are skipped unless the SDK is installed
261
343
  make build # sdist + wheel into dist/ (needs hatch)
262
344
  ```
263
345
 
@@ -3,16 +3,24 @@
3
3
  AgentGuard monitoring plugin for [OpenAI Codex](https://github.com/openai/codex).
4
4
 
5
5
  Codex runs a command hook for each lifecycle event and writes one JSON object
6
- to stdin. This plugin reads that event, turns it into an OpenTelemetry span
7
- with the [AgentGuard Python SDK](../../../sdk/python), and exports it to
8
- the [AgentGuard Timeplus app](https://github.com/timeplus-io/apps/tree/main/apps/agentguard)'s
9
- OTLP/HTTP input (default `http://localhost:4318`).
6
+ to stdin. This plugin reads that event and sends it to the
7
+ [AgentGuard Timeplus app](https://github.com/timeplus-io/apps/tree/main/apps/agentguard)
8
+ on one of two export paths:
9
+
10
+ | Export | What is sent | Where | Needs |
11
+ |---|---|---|---|
12
+ | `otel` (default) | One OpenTelemetry span per hook, through the [AgentGuard Python SDK](../../../sdk/python) | The app's OTLP/HTTP input (default `http://localhost:4318`) | Port 4318 |
13
+ | `hooks` | One row per hook in the `agentguard_hook_events` stream, like the Claude Code, OpenClaw and Hermes plugins | Timeplus ingest (default `http://localhost:3218`) | Port 3218, or port 8000 with the Timeplus REST API |
14
+
15
+ Exactly one path is active. There is no setting that sends a session on both,
16
+ so the app never sees the same session twice. See
17
+ [Hook-event export](#hook-event-export) for the second path.
10
18
 
11
19
  ## Requirements
12
20
 
13
21
  - Python 3.10+
14
22
  - A Codex build with hooks enabled
15
- - The AgentGuard Python SDK ([`timeplus-agentguard`](https://pypi.org/project/timeplus-agentguard/) on PyPI, installed automatically as a dependency)
23
+ - The AgentGuard Python SDK ([`timeplus-agentguard`](https://pypi.org/project/timeplus-agentguard/) on PyPI, installed automatically as a dependency). Only the `otel` export uses it; the `hooks` export uses the standard library alone.
16
24
 
17
25
  ## Installation
18
26
 
@@ -91,8 +99,14 @@ configure the plugin.
91
99
  | `--agent-id` | `AGENTGUARD_AGENT_ID` | hostname |
92
100
  | `--deployment-id` | `AGENTGUARD_DEPLOYMENT_ID` | `local` |
93
101
  | `--deployment-name` | `AGENTGUARD_DEPLOYMENT_NAME` | `Local Dev` |
102
+ | `--export` | `AGENTGUARD_CODEX_EXPORT` | `otel` |
94
103
  | `--endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` |
95
104
 
105
+ `--export` is `otel` or `hooks`. Any other value (including `both`) is
106
+ reported on stderr and treated as `otel`. `--endpoint` applies to the `otel`
107
+ export only; the `hooks` export has its own settings, listed under
108
+ [Hook-event export](#hook-event-export).
109
+
96
110
  Flags take precedence over environment variables. The plugin resolves every
97
111
  setting (flag, then environment variable, then the default above) before
98
112
  constructing the SDK hooks, so each short-lived hook process sees the same
@@ -105,12 +119,80 @@ export AGENTGUARD_DEPLOYMENT_NAME="Production Codex"
105
119
  export OTEL_EXPORTER_OTLP_ENDPOINT=http://timeplus.example.com:4318
106
120
  ```
107
121
 
122
+ ## Hook-event export
123
+
124
+ Use this path when the app's OTLP input (port 4318) is not reachable from the
125
+ agent host, or when you want Codex in the same stream as the other plugins.
126
+
127
+ ```bash
128
+ export AGENTGUARD_CODEX_EXPORT=hooks
129
+ export AGENTGUARD_TIMEPLUS_URL=http://timeplus.example.com:3218
130
+ export AGENTGUARD_USERNAME=<timeplus-user>
131
+ export AGENTGUARD_PASSWORD=<timeplus-password>
132
+ ```
133
+
134
+ | Environment variable | Default | Purpose |
135
+ |---|---|---|
136
+ | `AGENTGUARD_TIMEPLUS_URL` | `http://localhost:3218` | Timeplus base URL |
137
+ | `AGENTGUARD_INGEST_API` | `timeplusd` | `timeplusd` (port 3218) or `rest` (the Timeplus REST API, port 8000) |
138
+ | `AGENTGUARD_WORKSPACE` | `default` | REST API workspace id; `default` is correct for self-hosted |
139
+ | `AGENTGUARD_DATABASE` | `ag` | Database of the AgentGuard app |
140
+ | `AGENTGUARD_STREAM` | `agentguard_hook_events` | Target stream |
141
+ | `AGENTGUARD_USERNAME` | `proton` | Timeplus username (Basic auth) |
142
+ | `AGENTGUARD_PASSWORD` | _(empty)_ | Timeplus password (Basic auth) |
143
+
144
+ These are the settings the other hook-event plugins use, with the same
145
+ meaning. They have no flags.
146
+
147
+ Each of the 14 hooks becomes one row:
148
+
149
+ | Column | Value |
150
+ |---|---|
151
+ | `hook_name` | The hook in snake case: `session_start`, `session_end`, `user_prompt_submit`, `pre_tool_use`, `post_tool_use`, `pre_model_request`, `post_model_request`, `stop`, `interrupt`, `subagent_start`, `permission_request`, `pre_compact`, `post_compact`. `SubagentStop` is written as `subagent_ended`, the name the stream already uses for it. |
152
+ | `agent_type` | `codex` |
153
+ | `session_id` | The Codex session id |
154
+ | `run_id` | The turn id, or the session id on hooks without a turn (`SessionStart`, `SessionEnd`) |
155
+ | `agent_id`, `deployment_id`, `deployment_name` | From the settings above |
156
+ | `tool_name` | The tool, on tool and permission hooks |
157
+ | `model`, `provider` | The model slug; the provider from the session transcript, or `openai` |
158
+ | `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 |
160
+
161
+ Two keys are added to `event_data`:
162
+
163
+ - `agentguard.export` is always `hooks`. On the `otel` path the app copies
164
+ some spans into `agentguard_hook_events` with the same `agent_type`; this
165
+ key is how a view tells a row written by the plugin from a copied one.
166
+ - `agentguard.duration_ms` is on closing events that had an opening event:
167
+ `post_tool_use`, `post_model_request`, `post_compact`, `subagent_ended` and
168
+ `session_end`. See [Pairing and timing](#pairing-and-timing).
169
+
170
+ The rows of one hook process go out in a single request with a 2 second
171
+ timeout, so `SessionEnd` and `Interrupt` finish inside Codex's 3 second limit.
172
+
173
+ Check what arrived with:
174
+
175
+ ```sql
176
+ SELECT event_time, hook_name, session_id, run_id, tool_name, model
177
+ FROM table(ag.agentguard_hook_events)
178
+ WHERE agent_type = 'codex' AND json_value(event_data, '$."agentguard.export"') = 'hooks'
179
+ ORDER BY event_time DESC
180
+ LIMIT 20;
181
+ ```
182
+
183
+ The app does not turn these rows into `agentguard_cim_event` and
184
+ `agentguard_cim_metrics` rows yet. That is
185
+ [timeplus-io/apps#71](https://github.com/timeplus-io/apps/issues/71); until it
186
+ ships, the `hooks` export fills `agentguard_hook_events` only.
187
+
108
188
  ## What gets captured
109
189
 
110
190
  The plugin handles all 14 events in the
111
- [Codex hooks reference](https://developers.openai.com/codex/hooks). Each event
112
- becomes one span, exported with the OTel service name `codex`, which the
113
- AgentGuard app reports as the agent type.
191
+ [Codex hooks reference](https://developers.openai.com/codex/hooks). On the
192
+ `otel` export, described in the rest of this section, each event becomes one
193
+ span, exported with the OTel service name `codex`, which the AgentGuard app
194
+ reports as the agent type. The `hooks` export handles the same 14 events; its
195
+ row format is under [Hook-event export](#hook-event-export).
114
196
 
115
197
  | Codex hook | Emitted span | What it carries |
116
198
  |---|---|---|
@@ -236,7 +318,7 @@ status and token usage.
236
318
  ## Development
237
319
 
238
320
  ```bash
239
- make test # unit tests; the end-to-end telemetry tests are skipped unless the SDK is installed
321
+ make test # unit tests; the end-to-end OTel tests are skipped unless the SDK is installed
240
322
  make build # sdist + wheel into dist/ (needs hatch)
241
323
  ```
242
324
 
@@ -1,3 +1,3 @@
1
1
  """AgentGuard monitoring plugin for OpenAI Codex."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.3.0"
@@ -1,9 +1,11 @@
1
1
  """``agentguard-codex`` — Codex hook entry point for AgentGuard.
2
2
 
3
3
  Codex runs this command once per hook event. It reads the event JSON from
4
- stdin and hands it to :func:`agentguard_codex.events.dispatch`, which emits
5
- spans through the AgentGuard Python SDK. See ``hooks.json`` for a sample Codex hook
6
- configuration.
4
+ stdin and hands it to :func:`agentguard_codex.events.dispatch`, which exports
5
+ it on one of two paths: OpenTelemetry spans through the AgentGuard Python SDK
6
+ (``otel``, the default), or rows in the ``agentguard_hook_events`` stream
7
+ (``hooks``). Exactly one path is active. See ``hooks.json`` for a sample Codex
8
+ hook configuration.
7
9
  """
8
10
 
9
11
  from __future__ import annotations
@@ -21,6 +23,11 @@ DEFAULT_DEPLOYMENT_ID = "local"
21
23
  DEFAULT_DEPLOYMENT_NAME = "Local Dev"
22
24
  DEFAULT_ENDPOINT = "http://localhost:4318"
23
25
 
26
+ EXPORT_OTEL = "otel"
27
+ EXPORT_HOOKS = "hooks"
28
+ EXPORTS = (EXPORT_OTEL, EXPORT_HOOKS)
29
+ DEFAULT_EXPORT = EXPORT_OTEL
30
+
24
31
 
25
32
  def build_parser() -> argparse.ArgumentParser:
26
33
  parser = argparse.ArgumentParser(
@@ -28,10 +35,19 @@ def build_parser() -> argparse.ArgumentParser:
28
35
  description="Forward OpenAI Codex hook events to AgentGuard",
29
36
  formatter_class=argparse.RawDescriptionHelpFormatter,
30
37
  epilog=(
31
- "Reads one Codex hook event as JSON on stdin and exports\n"
32
- "OpenTelemetry spans to the AgentGuard Timeplus app's OTLP input."
38
+ "Reads one Codex hook event as JSON on stdin and exports it to the\n"
39
+ "AgentGuard Timeplus app: as OpenTelemetry spans to the app's OTLP\n"
40
+ "input (--export otel), or as rows in agentguard_hook_events\n"
41
+ "(--export hooks, configured with the AGENTGUARD_TIMEPLUS_URL,\n"
42
+ "AGENTGUARD_INGEST_API, AGENTGUARD_USERNAME and AGENTGUARD_PASSWORD\n"
43
+ "environment variables)."
33
44
  ),
34
45
  )
46
+ parser.add_argument(
47
+ "--export",
48
+ default=None,
49
+ help="Export path, 'otel' or 'hooks' (default: $AGENTGUARD_CODEX_EXPORT or 'otel')",
50
+ )
35
51
  parser.add_argument(
36
52
  "--agent-id",
37
53
  default=None,
@@ -50,7 +66,7 @@ def build_parser() -> argparse.ArgumentParser:
50
66
  parser.add_argument(
51
67
  "--endpoint",
52
68
  default=None,
53
- help="OTLP/HTTP endpoint (default: $OTEL_EXPORTER_OTLP_ENDPOINT or http://localhost:4318)",
69
+ help="OTLP/HTTP endpoint, used with --export otel (default: $OTEL_EXPORTER_OTLP_ENDPOINT or http://localhost:4318)",
54
70
  )
55
71
  return parser
56
72
 
@@ -91,6 +107,24 @@ def resolve_endpoint(endpoint: str | None) -> str:
91
107
  )
92
108
 
93
109
 
110
+ def resolve_export(export: str | None) -> str:
111
+ """Resolve the export path: flag, then env, then ``otel``.
112
+
113
+ An unknown value is reported on stderr and replaced by the default, so a
114
+ typo never stops telemetry and never selects both paths.
115
+ """
116
+ value = (export or os.environ.get("AGENTGUARD_CODEX_EXPORT") or "").strip().lower()
117
+ if not value:
118
+ return DEFAULT_EXPORT
119
+ if value not in EXPORTS:
120
+ print(
121
+ f"agentguard-codex: unknown export {value!r}, using {DEFAULT_EXPORT!r}",
122
+ file=sys.stderr,
123
+ )
124
+ return DEFAULT_EXPORT
125
+ return value
126
+
127
+
94
128
  def start_store_folder(agent_id: str) -> str:
95
129
  """Where the start times of open sessions, tools and requests live."""
96
130
  return os.path.join(os.path.expanduser("~"), ".agentguard", agent_id, "codex-starts")
@@ -100,23 +134,41 @@ def main(argv: list[str] | None = None) -> int:
100
134
  try:
101
135
  args = build_parser().parse_args(argv)
102
136
 
137
+ agent_id = resolve_agent_id(args.agent_id)
138
+ deployment_id = resolve_deployment_id(args.deployment_id)
139
+ deployment_name = resolve_deployment_name(args.deployment_name)
140
+
103
141
  # Imported lazily so ``import agentguard_codex.cli`` (and ``--help``)
104
142
  # works without the AgentGuard SDK, and a missing SDK is handled by
105
- # the same fail-safe path as any other plugin error.
106
- from agentguard import AgentGuard
107
-
108
- from agentguard_codex.sink import SdkSink, StartStore
109
-
110
- agent_id = resolve_agent_id(args.agent_id)
111
- client = AgentGuard(
112
- # The app reports the OTel service name as the agent type.
113
- service_name=AGENT_TYPE,
114
- agent_id=agent_id,
115
- deployment_id=resolve_deployment_id(args.deployment_id),
116
- deployment_name=resolve_deployment_name(args.deployment_name),
117
- otlp_endpoint=resolve_endpoint(args.endpoint),
118
- )
119
- sink = SdkSink(client, StartStore(start_store_folder(agent_id)))
143
+ # the same fail-safe path as any other plugin error. The hooks path
144
+ # never imports the SDK.
145
+ from agentguard_codex.sink import StartStore
146
+
147
+ starts = StartStore(start_store_folder(agent_id))
148
+ if resolve_export(args.export) == EXPORT_HOOKS:
149
+ from agentguard_codex.hookevents import HookEventSink, IngestConfig
150
+
151
+ sink = HookEventSink(
152
+ IngestConfig.from_env(),
153
+ starts,
154
+ agent_id=agent_id,
155
+ deployment_id=deployment_id,
156
+ deployment_name=deployment_name,
157
+ )
158
+ else:
159
+ from agentguard import AgentGuard
160
+
161
+ from agentguard_codex.sink import SdkSink
162
+
163
+ client = AgentGuard(
164
+ # The app reports the OTel service name as the agent type.
165
+ service_name=AGENT_TYPE,
166
+ agent_id=agent_id,
167
+ deployment_id=deployment_id,
168
+ deployment_name=deployment_name,
169
+ otlp_endpoint=resolve_endpoint(args.endpoint),
170
+ )
171
+ sink = SdkSink(client, starts)
120
172
 
121
173
  try:
122
174
  dispatch(json.loads(sys.stdin.read()), sink)
@@ -1,9 +1,15 @@
1
- """Translate Codex hook events into AgentGuard spans.
1
+ """Translate Codex hook events into AgentGuard telemetry.
2
2
 
3
3
  Codex invokes one short-lived command per hook event and writes a single
4
4
  JSON object to stdin. Every object carries ``hook_event_name`` and
5
5
  ``session_id``; turn-scoped events also carry ``turn_id``. This module only
6
- does the translation — the sink owns span export and start-time bookkeeping.
6
+ does the translation — the sink owns the export and start-time bookkeeping.
7
+
8
+ The translation is the same on both export paths; only the sink differs. The
9
+ OTel sink (:class:`agentguard_codex.sink.SdkSink`) turns each call into a span.
10
+ The hook-event sink (:class:`agentguard_codex.hookevents.HookEventSink`) turns
11
+ each call into one ``agentguard_hook_events`` row, including ``PreToolUse``,
12
+ which has no span of its own.
7
13
 
8
14
  Each event becomes at most one span. Three of them carry the kind attributes
9
15
  the AgentGuard app's OpenInference views key on:
@@ -31,7 +37,11 @@ DEFAULT_PROVIDER = "openai"
31
37
 
32
38
 
33
39
  class HookSink(Protocol):
34
- """What :func:`dispatch` needs: emit a span, and pair Pre/Post events."""
40
+ """What :func:`dispatch` needs: emit an event, and pair Pre/Post events.
41
+
42
+ ``payload`` is the Codex hook payload as received. A span sink ignores it;
43
+ the hook-event sink stores it as the row's ``event_data``.
44
+ """
35
45
 
36
46
  def emit_span(
37
47
  self,
@@ -43,8 +53,20 @@ class HookSink(Protocol):
43
53
  attributes: dict[str, Any] | None = None,
44
54
  start_time_ns: int | None = None,
45
55
  error: str | None = None,
56
+ payload: dict[str, Any] | None = None,
46
57
  ) -> None: ...
47
58
 
59
+ def emit_no_span(
60
+ self,
61
+ *,
62
+ session_id: str,
63
+ run_id: str | None = None,
64
+ attributes: dict[str, Any] | None = None,
65
+ payload: dict[str, Any] | None = None,
66
+ ) -> None:
67
+ """An event that opens a pair and has no span of its own (``PreToolUse``)."""
68
+ ...
69
+
48
70
  def mark_start(self, key: str) -> None: ...
49
71
 
50
72
  def take_start(self, key: str) -> int | None: ...
@@ -154,16 +176,27 @@ def _emit(
154
176
  task_id: str | None = None,
155
177
  start_time_ns: int | None = None,
156
178
  error: str | None = None,
179
+ span: bool = True,
157
180
  ) -> None:
158
181
  attributes = {**_common_attributes(event), **(extra or {})}
182
+ attributes = {k: v for k, v in attributes.items() if v is not None}
183
+ if not span:
184
+ hooks.emit_no_span(
185
+ session_id=event["session_id"],
186
+ run_id=event.get("turn_id"),
187
+ attributes=attributes,
188
+ payload=event,
189
+ )
190
+ return
159
191
  hooks.emit_span(
160
192
  HOOK_SPAN_NAMES[event["hook_event_name"]],
161
193
  session_id=event["session_id"],
162
194
  run_id=event.get("turn_id"),
163
195
  task_id=task_id,
164
- attributes={k: v for k, v in attributes.items() if v is not None},
196
+ attributes=attributes,
165
197
  start_time_ns=start_time_ns,
166
198
  error=error,
199
+ payload=event,
167
200
  )
168
201
 
169
202
 
@@ -217,8 +250,18 @@ def _tool_key(event: dict[str, Any]) -> str:
217
250
  return _pair_key("tool", event, event.get("tool_use_id"))
218
251
 
219
252
 
253
+ def _tool_attributes(event: dict[str, Any]) -> dict[str, Any]:
254
+ return {
255
+ "tool.name": event.get("tool_name"),
256
+ "tool.parameters": _as_string(event.get("tool_input")),
257
+ "tool_use_id": event.get("tool_use_id"),
258
+ }
259
+
260
+
220
261
  def _pre_tool_use(event: dict[str, Any], hooks: HookSink) -> None:
221
262
  hooks.mark_start(_tool_key(event))
263
+ # No span: the `tool` span of PostToolUse covers the call from here on.
264
+ _emit(event, hooks, _tool_attributes(event), span=False)
222
265
 
223
266
 
224
267
  def _post_tool_use(event: dict[str, Any], hooks: HookSink) -> None:
@@ -227,10 +270,8 @@ def _post_tool_use(event: dict[str, Any], hooks: HookSink) -> None:
227
270
  hooks,
228
271
  {
229
272
  "openinference.span.kind": "TOOL",
230
- "tool.name": event.get("tool_name"),
231
- "tool.parameters": _as_string(event.get("tool_input")),
273
+ **_tool_attributes(event),
232
274
  "output.value": _as_string(event.get("tool_response")),
233
- "tool_use_id": event.get("tool_use_id"),
234
275
  },
235
276
  task_id=event.get("tool_use_id"),
236
277
  start_time_ns=hooks.take_start(_tool_key(event)),
@@ -0,0 +1,218 @@
1
+ """Hook-event export: one ``agentguard_hook_events`` row per Codex hook.
2
+
3
+ The alternative to the OTel path (:mod:`agentguard_codex.sink`). It writes the
4
+ same stream, with the same columns and ingest settings, as the Claude Code,
5
+ OpenClaw and Hermes plugins, and needs only the standard library.
6
+
7
+ Ingest modes (``AGENTGUARD_INGEST_API``):
8
+
9
+ * ``timeplusd`` (default): ``POST {url}/timeplusd/v2/ingest/{db}/streams/{stream}``
10
+ * ``rest``: the Timeplus REST API,
11
+ ``POST {url}/{workspace}/api/v1beta2/streams/{stream}/ingest?db={db}``
12
+
13
+ Both take Basic auth and the same ``{"columns", "data"}`` body.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import time
21
+ import urllib.request
22
+ from base64 import b64encode
23
+ from dataclasses import dataclass
24
+ from datetime import datetime, timezone
25
+ from typing import Any
26
+
27
+ from agentguard_codex.sink import StartStore
28
+
29
+ AGENT_TYPE = "codex"
30
+
31
+ #: Must match the app's ``agentguard_hook_events`` DDL, in this order.
32
+ COLUMNS = [
33
+ "hook_name",
34
+ "event_time",
35
+ "session_id",
36
+ "run_id",
37
+ "agent_id",
38
+ "deployment_id",
39
+ "deployment_name",
40
+ "session_key",
41
+ "tool_name",
42
+ "provider",
43
+ "model",
44
+ "hook_decision",
45
+ "block_reason",
46
+ "event_data",
47
+ "agent_type",
48
+ ]
49
+
50
+ #: ``event_data`` key that marks a row as written by this path. On the OTel
51
+ #: path the app bridges some spans into the same stream with the same
52
+ #: ``agent_type``; the app's Codex hook views tell the two apart by this key.
53
+ EXPORT_MARKER = "agentguard.export"
54
+ EXPORT_MARKER_VALUE = "hooks"
55
+
56
+ #: ``event_data`` key for the time since the opening event of a pair.
57
+ DURATION_KEY = "agentguard.duration_ms"
58
+
59
+ #: ``agentguard.hook_name`` -> ``hook_name`` column, where the stream already
60
+ #: has a name for the event (the one the other plugins and the app's bridge use).
61
+ HOOK_NAME_OVERRIDES = {"subagent_stop": "subagent_ended"}
62
+
63
+ # Codex gives SessionEnd and Interrupt hooks 3 seconds, interpreter start
64
+ # included, so the request has to give up well before that.
65
+ INGEST_TIMEOUT_SECONDS = 2.0
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class IngestConfig:
70
+ """Where and how hook-event rows are written."""
71
+
72
+ url: str = "http://localhost:3218"
73
+ database: str = "ag"
74
+ stream: str = "agentguard_hook_events"
75
+ username: str = "proton"
76
+ password: str = ""
77
+ ingest_api: str = "timeplusd"
78
+ workspace: str = "default"
79
+
80
+ @classmethod
81
+ def from_env(cls, env: dict[str, str] | None = None) -> IngestConfig:
82
+ """Read the settings the other hook-event plugins use. Empty means unset."""
83
+ env = os.environ if env is None else env
84
+ default = cls()
85
+
86
+ def get(name: str, fallback: str) -> str:
87
+ return env.get(name) or fallback
88
+
89
+ return cls(
90
+ url=get("AGENTGUARD_TIMEPLUS_URL", default.url),
91
+ database=get("AGENTGUARD_DATABASE", default.database),
92
+ stream=get("AGENTGUARD_STREAM", default.stream),
93
+ username=get("AGENTGUARD_USERNAME", default.username),
94
+ password=env.get("AGENTGUARD_PASSWORD", default.password),
95
+ # Anything but "rest" is the default, as in the other plugins.
96
+ ingest_api=(
97
+ "rest"
98
+ if env.get("AGENTGUARD_INGEST_API", "").strip().lower() == "rest"
99
+ else "timeplusd"
100
+ ),
101
+ workspace=get("AGENTGUARD_WORKSPACE", default.workspace),
102
+ )
103
+
104
+ def ingest_url(self) -> str:
105
+ base = self.url.rstrip("/")
106
+ if self.ingest_api == "rest":
107
+ return (
108
+ f"{base}/{self.workspace}/api/v1beta2/streams/{self.stream}"
109
+ f"/ingest?db={self.database}"
110
+ )
111
+ return f"{base}/timeplusd/v2/ingest/{self.database}/streams/{self.stream}"
112
+
113
+ def headers(self) -> dict[str, str]:
114
+ headers = {"Content-Type": "application/json"}
115
+ if self.username:
116
+ token = b64encode(f"{self.username}:{self.password}".encode()).decode()
117
+ headers["Authorization"] = f"Basic {token}"
118
+ return headers
119
+
120
+
121
+ class HookEventSink:
122
+ """Adapts hook-event ingest to :class:`agentguard_codex.events.HookSink`.
123
+
124
+ Rows are collected and sent in one request by :meth:`close`.
125
+ """
126
+
127
+ def __init__(
128
+ self,
129
+ config: IngestConfig,
130
+ starts: StartStore,
131
+ *,
132
+ agent_id: str,
133
+ deployment_id: str,
134
+ deployment_name: str,
135
+ timeout: float = INGEST_TIMEOUT_SECONDS,
136
+ ) -> None:
137
+ self._config = config
138
+ self._starts = starts
139
+ self._agent_id = agent_id
140
+ self._deployment_id = deployment_id
141
+ self._deployment_name = deployment_name
142
+ self._timeout = timeout
143
+ self.rows: list[list[Any]] = []
144
+
145
+ def emit_span(
146
+ self,
147
+ name: str,
148
+ *,
149
+ session_id: str,
150
+ run_id: str | None = None,
151
+ task_id: str | None = None,
152
+ attributes: dict[str, Any] | None = None,
153
+ start_time_ns: int | None = None,
154
+ error: str | None = None,
155
+ payload: dict[str, Any] | None = None,
156
+ ) -> None:
157
+ self._add_row(session_id, run_id, attributes or {}, payload or {}, start_time_ns)
158
+
159
+ def emit_no_span(
160
+ self,
161
+ *,
162
+ session_id: str,
163
+ run_id: str | None = None,
164
+ attributes: dict[str, Any] | None = None,
165
+ payload: dict[str, Any] | None = None,
166
+ ) -> None:
167
+ self._add_row(session_id, run_id, attributes or {}, payload or {}, None)
168
+
169
+ def _add_row(
170
+ self,
171
+ session_id: str,
172
+ run_id: str | None,
173
+ attributes: dict[str, Any],
174
+ payload: dict[str, Any],
175
+ start_time_ns: int | None,
176
+ ) -> None:
177
+ hook_name = attributes.get("agentguard.hook_name") or ""
178
+ data = {**payload, EXPORT_MARKER: EXPORT_MARKER_VALUE}
179
+ if start_time_ns is not None:
180
+ data[DURATION_KEY] = max(0, (time.time_ns() - start_time_ns) // 1_000_000)
181
+
182
+ self.rows.append(
183
+ [
184
+ HOOK_NAME_OVERRIDES.get(hook_name, hook_name),
185
+ datetime.now(timezone.utc).isoformat(),
186
+ session_id,
187
+ run_id or session_id,
188
+ self._agent_id,
189
+ self._deployment_id,
190
+ self._deployment_name,
191
+ "", # session_key: Codex has none
192
+ attributes.get("tool.name") or "",
193
+ attributes.get("llm.provider") or "",
194
+ attributes.get("llm.model_name") or "",
195
+ "observe",
196
+ "",
197
+ json.dumps(data, ensure_ascii=False, default=str),
198
+ AGENT_TYPE,
199
+ ]
200
+ )
201
+
202
+ def mark_start(self, key: str) -> None:
203
+ self._starts.mark(key)
204
+
205
+ def take_start(self, key: str) -> int | None:
206
+ return self._starts.take(key)
207
+
208
+ def close(self) -> None:
209
+ """Send the collected rows; a hook process ends right after this."""
210
+ if not self.rows:
211
+ return
212
+ body = json.dumps({"columns": COLUMNS, "data": self.rows}).encode("utf-8")
213
+ self.rows = []
214
+ request = urllib.request.Request(
215
+ self._config.ingest_url(), data=body, method="POST", headers=self._config.headers()
216
+ )
217
+ with urllib.request.urlopen(request, timeout=self._timeout) as response:
218
+ response.read()
@@ -76,6 +76,7 @@ class SdkSink:
76
76
  attributes: dict[str, Any] | None = None,
77
77
  start_time_ns: int | None = None,
78
78
  error: str | None = None,
79
+ payload: dict[str, Any] | None = None,
79
80
  ) -> None:
80
81
  kwargs: dict[str, Any] = {}
81
82
  if start_time_ns is not None:
@@ -97,6 +98,9 @@ class SdkSink:
97
98
  finally:
98
99
  span.end()
99
100
 
101
+ def emit_no_span(self, **_: Any) -> None:
102
+ """Nothing to export: the closing event's span covers the pair."""
103
+
100
104
  def mark_start(self, key: str) -> None:
101
105
  self._starts.mark(key)
102
106
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "timeplus-agentguard-codex-plugin"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "AgentGuard monitoring plugin for OpenAI Codex"
9
9
  readme = "README.md"
10
10
  license = { text = "Apache-2.0" }
@@ -7,8 +7,10 @@ collector — a missing SDK is one of the failures the hook must swallow.
7
7
  an in-process OTLP/HTTP receiver.
8
8
  """
9
9
 
10
+ import contextlib
10
11
  import http.server
11
12
  import importlib.util
13
+ import io
12
14
  import json
13
15
  import os
14
16
  import socket
@@ -385,6 +387,7 @@ class ResolveTests(unittest.TestCase):
385
387
  "AGENTGUARD_DEPLOYMENT_ID",
386
388
  "AGENTGUARD_DEPLOYMENT_NAME",
387
389
  "OTEL_EXPORTER_OTLP_ENDPOINT",
390
+ "AGENTGUARD_CODEX_EXPORT",
388
391
  )
389
392
 
390
393
  def setUp(self) -> None:
@@ -436,6 +439,26 @@ class ResolveTests(unittest.TestCase):
436
439
  self.assertEqual(self.cli.resolve_deployment_name(None), "Local Dev")
437
440
  self.assertEqual(self.cli.resolve_endpoint(None), "http://localhost:4318")
438
441
 
442
+ def test_export_defaults_to_otel(self) -> None:
443
+ self.assertEqual(self.cli.resolve_export(None), "otel")
444
+ os.environ["AGENTGUARD_CODEX_EXPORT"] = ""
445
+ self.assertEqual(self.cli.resolve_export(None), "otel")
446
+
447
+ def test_export_flag_wins_over_env(self) -> None:
448
+ os.environ["AGENTGUARD_CODEX_EXPORT"] = "otel"
449
+ self.assertEqual(self.cli.resolve_export("hooks"), "hooks")
450
+ os.environ["AGENTGUARD_CODEX_EXPORT"] = " Hooks "
451
+ self.assertEqual(self.cli.resolve_export(None), "hooks")
452
+
453
+ def test_unknown_export_falls_back_to_otel_and_says_so(self) -> None:
454
+ # No value selects both paths: "both" is as unknown as a typo.
455
+ for value in ("both", "otel,hooks", "hook"):
456
+ with self.subTest(value=value):
457
+ stderr = io.StringIO()
458
+ with contextlib.redirect_stderr(stderr):
459
+ self.assertEqual(self.cli.resolve_export(value), "otel")
460
+ self.assertIn(value, stderr.getvalue())
461
+
439
462
 
440
463
  if __name__ == "__main__":
441
464
  unittest.main()
@@ -72,8 +72,10 @@ class SpanTestCase(unittest.TestCase):
72
72
  """Dispatch *event* and return the single ``emit_span`` call's kwargs."""
73
73
  hooks = hooks or self.hooks
74
74
  self.assertTrue(dispatch(event, hooks))
75
- self.assertEqual([name for name, _, _ in hooks.calls], ["emit_span"])
76
- _, args, kwargs = hooks.calls[0]
75
+ spans = [call for call in hooks.calls if call[0] == "emit_span"]
76
+ self.assertEqual(len(spans), 1, hooks.calls)
77
+ _, args, kwargs = spans[0]
78
+ self.assertIs(kwargs.pop("payload"), event)
77
79
  return {"name": args[0], **kwargs}
78
80
 
79
81
 
@@ -168,19 +170,39 @@ class CoreEventTests(SpanTestCase):
168
170
 
169
171
  self.assertEqual(span["attributes"], {"agentguard.hook_name": "user_prompt_submit"})
170
172
 
171
- def test_pre_tool_use_only_records_the_start(self) -> None:
172
- handled = dispatch(
173
- {
174
- **COMMON,
175
- "hook_event_name": "PreToolUse",
176
- "tool_use_id": "call_1",
177
- "tool_name": "Bash",
178
- },
179
- self.hooks,
180
- )
173
+ def test_pre_tool_use_records_the_start_and_emits_no_span(self) -> None:
174
+ event = {
175
+ **COMMON,
176
+ "hook_event_name": "PreToolUse",
177
+ "tool_use_id": "call_1",
178
+ "tool_name": "Bash",
179
+ "tool_input": {"command": "ls"},
180
+ }
181
181
 
182
- self.assertTrue(handled)
183
- self.assertEqual(self.hooks.calls, [])
182
+ self.assertTrue(dispatch(event, self.hooks))
183
+
184
+ # The span sink drops this call; the hook-event sink writes a row.
185
+ self.assertEqual(
186
+ self.hooks.calls,
187
+ [
188
+ (
189
+ "emit_no_span",
190
+ (),
191
+ {
192
+ "session_id": "s1",
193
+ "run_id": "t1",
194
+ "attributes": {
195
+ **COMMON_ATTRIBUTES,
196
+ "agentguard.hook_name": "pre_tool_use",
197
+ "tool.name": "Bash",
198
+ "tool.parameters": '{"command": "ls"}',
199
+ "tool_use_id": "call_1",
200
+ },
201
+ "payload": event,
202
+ },
203
+ )
204
+ ],
205
+ )
184
206
  self.assertEqual(len(self.hooks.marked), 1)
185
207
 
186
208
  def test_post_tool_use(self) -> None:
@@ -0,0 +1,360 @@
1
+ """Tests for the hook-event export path (``--export hooks``).
2
+
3
+ Standard library only: this path must work without the AgentGuard SDK.
4
+
5
+ Run: python3.12 -m unittest discover -s tests -v
6
+ """
7
+
8
+ import base64
9
+ import http.server
10
+ import json
11
+ import os
12
+ import socket
13
+ import socketserver
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import threading
18
+ import unittest
19
+
20
+ PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, PLUGIN_ROOT)
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+
24
+ import test_cli # noqa: E402
25
+
26
+ from agentguard_codex.events import SUPPORTED_EVENTS, dispatch # noqa: E402
27
+ from agentguard_codex.hookevents import COLUMNS, HookEventSink, IngestConfig # noqa: E402
28
+
29
+ #: One full session covering all 14 hooks, shared with the OTel path tests.
30
+ EVENTS = test_cli.TelemetryTests.EVENTS
31
+
32
+ #: The app's agentguard_hook_events columns (apps/agentguard/ddl in timeplus-io/apps).
33
+ STREAM_COLUMNS = [
34
+ "hook_name",
35
+ "event_time",
36
+ "session_id",
37
+ "run_id",
38
+ "agent_id",
39
+ "deployment_id",
40
+ "deployment_name",
41
+ "session_key",
42
+ "tool_name",
43
+ "provider",
44
+ "model",
45
+ "hook_decision",
46
+ "block_reason",
47
+ "event_data",
48
+ "agent_type",
49
+ ]
50
+
51
+ #: hook_name written for each Codex hook.
52
+ HOOK_NAMES = {
53
+ "SessionStart": "session_start",
54
+ "SessionEnd": "session_end",
55
+ "UserPromptSubmit": "user_prompt_submit",
56
+ "PreToolUse": "pre_tool_use",
57
+ "PostToolUse": "post_tool_use",
58
+ "PreModelRequest": "pre_model_request",
59
+ "PostModelRequest": "post_model_request",
60
+ "Stop": "stop",
61
+ "Interrupt": "interrupt",
62
+ "SubagentStart": "subagent_start",
63
+ "SubagentStop": "subagent_ended",
64
+ "PermissionRequest": "permission_request",
65
+ "PreCompact": "pre_compact",
66
+ "PostCompact": "post_compact",
67
+ }
68
+
69
+
70
+ class MemoryStarts:
71
+ def __init__(self) -> None:
72
+ self.values: dict[str, int] = {}
73
+
74
+ def mark(self, key: str) -> None:
75
+ self.values[key] = 1_000 # long ago, so every duration is positive
76
+
77
+ def take(self, key: str) -> int | None:
78
+ return self.values.pop(key, None)
79
+
80
+
81
+ def as_dicts(rows: list[list]) -> list[dict]:
82
+ return [dict(zip(COLUMNS, row)) for row in rows]
83
+
84
+
85
+ class IngestConfigTests(unittest.TestCase):
86
+ def test_defaults_match_the_other_plugins(self) -> None:
87
+ config = IngestConfig.from_env({})
88
+
89
+ self.assertEqual(
90
+ config.ingest_url(),
91
+ "http://localhost:3218/timeplusd/v2/ingest/ag/streams/agentguard_hook_events",
92
+ )
93
+
94
+ def test_rest_mode(self) -> None:
95
+ config = IngestConfig.from_env(
96
+ {"AGENTGUARD_TIMEPLUS_URL": "http://tp:8000/", "AGENTGUARD_INGEST_API": " REST "}
97
+ )
98
+
99
+ self.assertEqual(
100
+ config.ingest_url(),
101
+ "http://tp:8000/default/api/v1beta2/streams/agentguard_hook_events/ingest?db=ag",
102
+ )
103
+
104
+ def test_unknown_ingest_api_is_timeplusd(self) -> None:
105
+ self.assertEqual(
106
+ IngestConfig.from_env({"AGENTGUARD_INGEST_API": "cloud"}).ingest_api, "timeplusd"
107
+ )
108
+
109
+ def test_env_overrides(self) -> None:
110
+ config = IngestConfig.from_env(
111
+ {
112
+ "AGENTGUARD_TIMEPLUS_URL": "http://tp:3218",
113
+ "AGENTGUARD_DATABASE": "db1",
114
+ "AGENTGUARD_STREAM": "s1",
115
+ "AGENTGUARD_WORKSPACE": "ws1",
116
+ "AGENTGUARD_USERNAME": "alice",
117
+ "AGENTGUARD_PASSWORD": "secret",
118
+ }
119
+ )
120
+
121
+ self.assertEqual(config.ingest_url(), "http://tp:3218/timeplusd/v2/ingest/db1/streams/s1")
122
+ token = config.headers()["Authorization"].removeprefix("Basic ")
123
+ self.assertEqual(base64.b64decode(token).decode(), "alice:secret")
124
+
125
+ def test_empty_env_values_fall_back_to_defaults(self) -> None:
126
+ config = IngestConfig.from_env({"AGENTGUARD_TIMEPLUS_URL": "", "AGENTGUARD_DATABASE": ""})
127
+
128
+ self.assertEqual(config, IngestConfig())
129
+
130
+
131
+ class RowTests(unittest.TestCase):
132
+ """The HookEvent row each Codex hook becomes."""
133
+
134
+ @classmethod
135
+ def setUpClass(cls) -> None:
136
+ cls.sink = HookEventSink(
137
+ IngestConfig(),
138
+ MemoryStarts(),
139
+ agent_id="agent-1",
140
+ deployment_id="dep-1",
141
+ deployment_name="Dep One",
142
+ )
143
+ for event in EVENTS:
144
+ assert dispatch(event, cls.sink)
145
+ cls.rows = as_dicts(cls.sink.rows)
146
+
147
+ def row(self, hook_name: str) -> dict:
148
+ (row,) = [r for r in self.rows if r["hook_name"] == hook_name]
149
+ return {**row, "event_data": json.loads(row["event_data"])}
150
+
151
+ def test_columns_match_the_stream(self) -> None:
152
+ self.assertEqual(COLUMNS, STREAM_COLUMNS)
153
+ for row in self.sink.rows:
154
+ self.assertEqual(len(row), len(COLUMNS))
155
+ for value in row:
156
+ self.assertIsInstance(value, str)
157
+
158
+ def test_one_row_per_hook_for_all_14_hooks(self) -> None:
159
+ self.assertEqual({e["hook_event_name"] for e in EVENTS}, SUPPORTED_EVENTS)
160
+ self.assertEqual(set(HOOK_NAMES), SUPPORTED_EVENTS)
161
+ self.assertEqual(
162
+ [r["hook_name"] for r in self.rows],
163
+ [HOOK_NAMES[e["hook_event_name"]] for e in EVENTS],
164
+ )
165
+
166
+ def test_identity_columns(self) -> None:
167
+ for row in self.rows:
168
+ self.assertEqual(row["agent_type"], "codex")
169
+ self.assertEqual(row["agent_id"], "agent-1")
170
+ self.assertEqual(row["deployment_id"], "dep-1")
171
+ self.assertEqual(row["deployment_name"], "Dep One")
172
+ self.assertEqual(row["session_id"], "s1")
173
+ self.assertEqual(row["hook_decision"], "observe")
174
+ self.assertEqual(row["block_reason"], "")
175
+ self.assertEqual(row["model"], "gpt-5-codex")
176
+ self.assertEqual(row["provider"], "openai")
177
+
178
+ def test_run_id_is_the_turn_or_else_the_session(self) -> None:
179
+ self.assertEqual(self.row("user_prompt_submit")["run_id"], "t1")
180
+ self.assertEqual(self.row("session_start")["run_id"], "s1")
181
+ self.assertEqual(self.row("session_end")["run_id"], "s1")
182
+
183
+ def test_event_data_is_the_payload_plus_the_path_marker(self) -> None:
184
+ for event, row in zip(EVENTS, self.rows):
185
+ data = json.loads(row["event_data"])
186
+ with self.subTest(event=event["hook_event_name"]):
187
+ self.assertEqual(data.pop("agentguard.export"), "hooks")
188
+ data.pop("agentguard.duration_ms", None)
189
+ self.assertEqual(data, event)
190
+
191
+ def test_prompt_reply_and_working_directory(self) -> None:
192
+ self.assertEqual(self.row("user_prompt_submit")["event_data"]["prompt"], "fix the test")
193
+ self.assertEqual(self.row("stop")["event_data"]["last_assistant_message"], "Fixed.")
194
+ self.assertEqual(self.row("session_start")["event_data"]["cwd"], "/work/demo-repo")
195
+ self.assertEqual(self.row("session_start")["event_data"]["source"], "startup")
196
+
197
+ def test_tool_rows(self) -> None:
198
+ pre, post = self.row("pre_tool_use"), self.row("post_tool_use")
199
+
200
+ self.assertEqual((pre["tool_name"], post["tool_name"]), ("Bash", "Bash"))
201
+ self.assertEqual(post["event_data"]["tool_use_id"], "c1")
202
+ self.assertEqual(post["event_data"]["tool_input"], {"command": "make test"})
203
+ self.assertEqual(post["event_data"]["tool_response"], {"exit_code": 0})
204
+ self.assertNotIn("agentguard.duration_ms", pre["event_data"])
205
+ self.assertGreater(post["event_data"]["agentguard.duration_ms"], 0)
206
+
207
+ def test_model_request_rows_carry_usage_and_duration(self) -> None:
208
+ failed, completed = [
209
+ json.loads(r["event_data"]) for r in self.rows if r["hook_name"] == "post_model_request"
210
+ ]
211
+
212
+ self.assertEqual(failed["status"], "failed")
213
+ self.assertEqual(completed["token_usage"]["input_tokens"], 1200)
214
+ self.assertEqual(completed["token_usage"]["cached_input_tokens"], 800)
215
+ self.assertGreater(completed["agentguard.duration_ms"], 0)
216
+
217
+ def test_subagent_and_compaction_keys(self) -> None:
218
+ # The names Agent Rooms reads for these events.
219
+ ended = self.row("subagent_ended")["event_data"]
220
+
221
+ self.assertEqual((ended["agent_id"], ended["agent_type"]), ("agent_7", "explorer"))
222
+ self.assertEqual(self.row("pre_compact")["event_data"]["trigger"], "auto")
223
+ self.assertEqual(self.row("permission_request")["tool_name"], "Bash")
224
+
225
+
226
+ class _Receiver(http.server.BaseHTTPRequestHandler):
227
+ def do_POST(self) -> None: # noqa: N802 - http.server API
228
+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
229
+ self.server.requests.append((self.path, dict(self.headers), body))
230
+ self.send_response(200)
231
+ self.send_header("Content-Length", "0")
232
+ self.end_headers()
233
+
234
+ def log_message(self, *args) -> None:
235
+ pass
236
+
237
+
238
+ class _ReceiverServer(http.server.ThreadingHTTPServer):
239
+ def server_bind(self) -> None:
240
+ socketserver.TCPServer.server_bind(self) # skip the reverse DNS lookup
241
+
242
+
243
+ def run_hook(event: dict, env: dict, *args: str) -> subprocess.CompletedProcess:
244
+ return subprocess.run(
245
+ [sys.executable, "-m", "agentguard_codex", "--agent-id", "test-agent", *args],
246
+ cwd=PLUGIN_ROOT,
247
+ input=json.dumps(event),
248
+ capture_output=True,
249
+ text=True,
250
+ env=env,
251
+ timeout=60,
252
+ )
253
+
254
+
255
+ class CommandTests(unittest.TestCase):
256
+ """Run the real hook command against a local ingest endpoint."""
257
+
258
+ def setUp(self) -> None:
259
+ self.server = _ReceiverServer(("127.0.0.1", 0), _Receiver)
260
+ self.server.requests = []
261
+ thread = threading.Thread(target=self.server.serve_forever, daemon=True)
262
+ thread.start()
263
+ self.addCleanup(thread.join)
264
+ self.addCleanup(self.server.server_close)
265
+ self.addCleanup(self.server.shutdown)
266
+
267
+ home = tempfile.TemporaryDirectory()
268
+ self.addCleanup(home.cleanup)
269
+ self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
270
+ self.env = {
271
+ k: v
272
+ for k, v in os.environ.items()
273
+ if not k.startswith("AGENTGUARD_") and not k.startswith("OTEL_")
274
+ }
275
+ self.env.update(
276
+ HOME=home.name,
277
+ AGENTGUARD_TIMEPLUS_URL=self.url,
278
+ AGENTGUARD_USERNAME="alice",
279
+ AGENTGUARD_PASSWORD="secret",
280
+ # Any OTLP export would land here and fail the path check below.
281
+ OTEL_EXPORTER_OTLP_ENDPOINT=self.url,
282
+ )
283
+
284
+ def run_session(self, *args: str) -> list[dict]:
285
+ for event in EVENTS:
286
+ result = run_hook(event, self.env, *args)
287
+ with self.subTest(event=event["hook_event_name"]):
288
+ # Observe only: exit 0 and nothing on stdout.
289
+ self.assertEqual(result.returncode, 0, result.stderr)
290
+ self.assertEqual(result.stdout, "")
291
+ self.assertEqual(result.stderr, "")
292
+ rows = []
293
+ for _, _, body in self.server.requests:
294
+ payload = json.loads(body)
295
+ self.assertEqual(payload["columns"], STREAM_COLUMNS)
296
+ rows.extend(as_dicts(payload["data"]))
297
+ return rows
298
+
299
+ def test_timeplusd_ingest(self) -> None:
300
+ rows = self.run_session("--export", "hooks")
301
+
302
+ self.assertEqual(
303
+ {path for path, _, _ in self.server.requests},
304
+ {"/timeplusd/v2/ingest/ag/streams/agentguard_hook_events"},
305
+ )
306
+ self.assertEqual(
307
+ [r["hook_name"] for r in rows], [HOOK_NAMES[e["hook_event_name"]] for e in EVENTS]
308
+ )
309
+ self.assertEqual({r["agent_type"] for r in rows}, {"codex"})
310
+ self.assertEqual({r["agent_id"] for r in rows}, {"test-agent"})
311
+ for _, headers, _ in self.server.requests:
312
+ token = headers["Authorization"].removeprefix("Basic ")
313
+ self.assertEqual(base64.b64decode(token).decode(), "alice:secret")
314
+
315
+ def test_rest_ingest_selected_by_env(self) -> None:
316
+ self.env.update(AGENTGUARD_CODEX_EXPORT="hooks", AGENTGUARD_INGEST_API="rest")
317
+
318
+ rows = self.run_session()
319
+
320
+ self.assertEqual(
321
+ {path for path, _, _ in self.server.requests},
322
+ {"/default/api/v1beta2/streams/agentguard_hook_events/ingest?db=ag"},
323
+ )
324
+ self.assertEqual(len(rows), len(EVENTS))
325
+
326
+ def test_pre_and_post_events_are_paired_across_processes(self) -> None:
327
+ rows = self.run_session("--export", "hooks")
328
+
329
+ for name in ("post_tool_use", "post_model_request", "session_end", "post_compact"):
330
+ for row in rows:
331
+ if row["hook_name"] == name:
332
+ self.assertIn("agentguard.duration_ms", json.loads(row["event_data"]), name)
333
+
334
+ def test_failed_ingest_never_changes_the_turn(self) -> None:
335
+ with socket.socket() as closed:
336
+ closed.bind(("127.0.0.1", 0))
337
+ self.env["AGENTGUARD_TIMEPLUS_URL"] = f"http://127.0.0.1:{closed.getsockname()[1]}"
338
+
339
+ for event in EVENTS:
340
+ result = run_hook(event, self.env, "--export", "hooks")
341
+ with self.subTest(event=event["hook_event_name"]):
342
+ self.assertEqual(result.returncode, 0)
343
+ self.assertEqual(result.stdout, "")
344
+ self.assertIn("agentguard-codex:", result.stderr)
345
+ self.assertNotIn("Traceback", result.stderr)
346
+ self.assertEqual(self.server.requests, [])
347
+
348
+ def test_unknown_export_does_not_use_the_hook_path(self) -> None:
349
+ result = run_hook(EVENTS[0], self.env, "--export", "both")
350
+
351
+ self.assertEqual(result.returncode, 0)
352
+ self.assertEqual(result.stdout, "")
353
+ self.assertIn("unknown export 'both'", result.stderr)
354
+ self.assertEqual(
355
+ [p for p, _, _ in self.server.requests if "agentguard_hook_events" in p], []
356
+ )
357
+
358
+
359
+ if __name__ == "__main__":
360
+ unittest.main()