timeplus-agentguard-codex-plugin 0.1.1__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.
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.egg-info/
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+
8
+ dist/
9
+ .hatch/
@@ -0,0 +1,19 @@
1
+ PYTHON ?= python3.12
2
+
3
+ .PHONY: test build check clean
4
+
5
+ ## test: run the plugin unit tests (stdlib only, no SDK needed)
6
+ test:
7
+ $(PYTHON) -m unittest discover -s tests -v
8
+
9
+ ## build: build sdist + wheel into dist/ from a clean dist/ (needs hatch)
10
+ build: clean
11
+ $(PYTHON) -m hatch build
12
+
13
+ ## check: validate the built distributions' metadata and README rendering (needs twine)
14
+ check: build
15
+ $(PYTHON) -m twine check --strict dist/*
16
+
17
+ ## clean: remove build artifacts
18
+ clean:
19
+ rm -rf dist/ *.egg-info agentguard_codex.egg-info .hatch .ruff_cache .pytest_cache
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.5
2
+ Name: timeplus-agentguard-codex-plugin
3
+ Version: 0.1.1
4
+ Summary: AgentGuard monitoring plugin for OpenAI Codex
5
+ Project-URL: Homepage, https://github.com/timeplus-io/agentguard
6
+ Project-URL: Repository, https://github.com/timeplus-io/agentguard
7
+ License: Apache-2.0
8
+ Keywords: agentguard,ai-agent,codex,monitoring,observability,security
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: timeplus-agentguard>=0.3.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # agentguard-codex
23
+
24
+ AgentGuard monitoring plugin for [OpenAI Codex](https://github.com/openai/codex).
25
+
26
+ Codex runs a command hook for each lifecycle event and writes one JSON object
27
+ to stdin. This plugin reads that event, translates it with the
28
+ [AgentGuard Python SDK](../../../sdk/python), and exports OpenTelemetry spans 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`).
31
+
32
+ ## Requirements
33
+
34
+ - Python 3.10+
35
+ - 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)
37
+
38
+ ## Installation
39
+
40
+ From the repository root:
41
+
42
+ ```bash
43
+ pip install -e agents/codex/agentguard-plugin
44
+ ```
45
+
46
+ ## Configure Codex hooks
47
+
48
+ Merge [`hooks.json`](hooks.json) into your Codex hook configuration —
49
+ `~/.codex/hooks.json`, or the equivalent `[hooks]` table in
50
+ `~/.codex/config.toml`:
51
+
52
+ ```json
53
+ {
54
+ "hooks": {
55
+ "SessionStart": [
56
+ { "hooks": [ { "type": "command", "command": "agentguard-codex" } ] }
57
+ ]
58
+ }
59
+ }
60
+ ```
61
+
62
+ Codex skips a new or changed user-level hook until you review it. Run `/hooks`
63
+ in Codex once and approve the AgentGuard entries. Managed (system/MDM) hooks are
64
+ trusted by policy and skip this step.
65
+
66
+ If the plugin is not installed as a console script, use
67
+ `python -m agentguard_codex` as the command instead.
68
+
69
+ ## Configuration
70
+
71
+ Hooks run in a fresh process, so environment variables are the usual way to
72
+ configure the plugin.
73
+
74
+ | Flag | Environment variable | Default |
75
+ |---|---|---|
76
+ | `--agent-id` | `AGENTGUARD_AGENT_ID` | hostname |
77
+ | `--deployment-id` | `AGENTGUARD_DEPLOYMENT_ID` | `local` |
78
+ | `--deployment-name` | `AGENTGUARD_DEPLOYMENT_NAME` | `Local Dev` |
79
+ | `--endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` |
80
+
81
+ Flags take precedence over environment variables. The plugin resolves every
82
+ setting (flag, then environment variable, then the default above) before
83
+ constructing the SDK hooks, so each short-lived hook process sees the same
84
+ values — including the agent id, which keys the on-disk Pre/Post-tool timing
85
+ store to match the spans. For example:
86
+
87
+ ```bash
88
+ export AGENTGUARD_DEPLOYMENT_ID=production
89
+ export AGENTGUARD_DEPLOYMENT_NAME="Production Codex"
90
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://timeplus.example.com:4318
91
+ ```
92
+
93
+ ## What gets captured
94
+
95
+ | Codex hook | SDK call | Emitted span |
96
+ |---|---|---|
97
+ | `SessionStart` | `on_session_start` | `session` (start time recorded) |
98
+ | `SessionEnd` | `on_session_end` | `session` (duration) |
99
+ | `UserPromptSubmit` | `on_llm_end` | `llm` |
100
+ | `PreToolUse` | `on_pre_tool` | start time recorded |
101
+ | `PostToolUse` | `on_post_tool` | `tool` |
102
+
103
+ `PreToolUse` and `PostToolUse` are paired through the SDK's on-disk store,
104
+ keyed by session, turn (`turn_id`), and tool call (`tool_use_id`), so
105
+ overlapping tool calls in one session do not overwrite each other's start
106
+ time. Other hook events are ignored for now, so a newer Codex can emit hooks
107
+ this plugin does not know about without breaking.
108
+
109
+ ## Development
110
+
111
+ ```bash
112
+ make test # unit tests (stdlib only — no SDK or collector needed)
113
+ make build # sdist + wheel into dist/ (needs hatch)
114
+ ```
115
+
116
+ The plugin writes nothing to stdout and returns 0 even when it fails — any
117
+ error goes to stderr — so hook output cannot alter a Codex turn.
118
+
119
+ ### Local end-to-end test
120
+
121
+ ```bash
122
+ cd /path/to/AgentGuard
123
+
124
+ # 1. venv with the plugin and the in-repo SDK (drop `-e sdk/python` to use the PyPI release)
125
+ uv venv ~/venvs/agentguard-codex --python 3.12
126
+ uv pip install --python ~/venvs/agentguard-codex/bin/python \
127
+ -e sdk/python -e agents/codex/agentguard-plugin
128
+
129
+ # 2. merge this package's hooks.json into ~/.codex/hooks.json, replacing
130
+ # "command" with the venv's absolute path plus the plugin's env vars:
131
+ # "command": "env AGENTGUARD_AGENT_ID=codex-local \
132
+ # OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
133
+ # /Users/you/venvs/agentguard-codex/bin/agentguard-codex"
134
+
135
+ # 3. start Codex, run /hooks, review and trust the AgentGuard entries, quit
136
+ codex
137
+
138
+ # 4. run a turn
139
+ codex exec --skip-git-repo-check -s workspace-write \
140
+ "Run pwd, then create done.txt containing ok."
141
+
142
+ # 5. inspect the exported spans at the configured OTLP endpoint (the app's
143
+ # otel_traces, or any local OTLP collector), then remove the AgentGuard
144
+ # entries from ~/.codex/hooks.json
145
+ ```
146
+
147
+ ## Publishing
148
+
149
+ Releases are published to PyPI by CI:
150
+
151
+ 1. Bump `version` in `pyproject.toml` and `__version__` in `agentguard_codex/__init__.py`, and merge.
152
+ 2. Publish a GitHub Release tagged `codex-plugin-v<version>` (for example `codex-plugin-v0.1.1`).
153
+
154
+ The `Publish Codex plugin` workflow tests, builds and uploads `timeplus-agentguard-codex-plugin`. It fails if the tag does not match the package version. Running it manually builds and validates without uploading; `make check` does the same locally (needs `hatch` and `twine`).
@@ -0,0 +1,133 @@
1
+ # agentguard-codex
2
+
3
+ AgentGuard monitoring plugin for [OpenAI Codex](https://github.com/openai/codex).
4
+
5
+ Codex runs a command hook for each lifecycle event and writes one JSON object
6
+ to stdin. This plugin reads that event, translates it with the
7
+ [AgentGuard Python SDK](../../../sdk/python), and exports OpenTelemetry spans 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`).
10
+
11
+ ## Requirements
12
+
13
+ - Python 3.10+
14
+ - 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)
16
+
17
+ ## Installation
18
+
19
+ From the repository root:
20
+
21
+ ```bash
22
+ pip install -e agents/codex/agentguard-plugin
23
+ ```
24
+
25
+ ## Configure Codex hooks
26
+
27
+ Merge [`hooks.json`](hooks.json) into your Codex hook configuration —
28
+ `~/.codex/hooks.json`, or the equivalent `[hooks]` table in
29
+ `~/.codex/config.toml`:
30
+
31
+ ```json
32
+ {
33
+ "hooks": {
34
+ "SessionStart": [
35
+ { "hooks": [ { "type": "command", "command": "agentguard-codex" } ] }
36
+ ]
37
+ }
38
+ }
39
+ ```
40
+
41
+ Codex skips a new or changed user-level hook until you review it. Run `/hooks`
42
+ in Codex once and approve the AgentGuard entries. Managed (system/MDM) hooks are
43
+ trusted by policy and skip this step.
44
+
45
+ If the plugin is not installed as a console script, use
46
+ `python -m agentguard_codex` as the command instead.
47
+
48
+ ## Configuration
49
+
50
+ Hooks run in a fresh process, so environment variables are the usual way to
51
+ configure the plugin.
52
+
53
+ | Flag | Environment variable | Default |
54
+ |---|---|---|
55
+ | `--agent-id` | `AGENTGUARD_AGENT_ID` | hostname |
56
+ | `--deployment-id` | `AGENTGUARD_DEPLOYMENT_ID` | `local` |
57
+ | `--deployment-name` | `AGENTGUARD_DEPLOYMENT_NAME` | `Local Dev` |
58
+ | `--endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` |
59
+
60
+ Flags take precedence over environment variables. The plugin resolves every
61
+ setting (flag, then environment variable, then the default above) before
62
+ constructing the SDK hooks, so each short-lived hook process sees the same
63
+ values — including the agent id, which keys the on-disk Pre/Post-tool timing
64
+ store to match the spans. For example:
65
+
66
+ ```bash
67
+ export AGENTGUARD_DEPLOYMENT_ID=production
68
+ export AGENTGUARD_DEPLOYMENT_NAME="Production Codex"
69
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://timeplus.example.com:4318
70
+ ```
71
+
72
+ ## What gets captured
73
+
74
+ | Codex hook | SDK call | Emitted span |
75
+ |---|---|---|
76
+ | `SessionStart` | `on_session_start` | `session` (start time recorded) |
77
+ | `SessionEnd` | `on_session_end` | `session` (duration) |
78
+ | `UserPromptSubmit` | `on_llm_end` | `llm` |
79
+ | `PreToolUse` | `on_pre_tool` | start time recorded |
80
+ | `PostToolUse` | `on_post_tool` | `tool` |
81
+
82
+ `PreToolUse` and `PostToolUse` are paired through the SDK's on-disk store,
83
+ keyed by session, turn (`turn_id`), and tool call (`tool_use_id`), so
84
+ overlapping tool calls in one session do not overwrite each other's start
85
+ time. Other hook events are ignored for now, so a newer Codex can emit hooks
86
+ this plugin does not know about without breaking.
87
+
88
+ ## Development
89
+
90
+ ```bash
91
+ make test # unit tests (stdlib only — no SDK or collector needed)
92
+ make build # sdist + wheel into dist/ (needs hatch)
93
+ ```
94
+
95
+ The plugin writes nothing to stdout and returns 0 even when it fails — any
96
+ error goes to stderr — so hook output cannot alter a Codex turn.
97
+
98
+ ### Local end-to-end test
99
+
100
+ ```bash
101
+ cd /path/to/AgentGuard
102
+
103
+ # 1. venv with the plugin and the in-repo SDK (drop `-e sdk/python` to use the PyPI release)
104
+ uv venv ~/venvs/agentguard-codex --python 3.12
105
+ uv pip install --python ~/venvs/agentguard-codex/bin/python \
106
+ -e sdk/python -e agents/codex/agentguard-plugin
107
+
108
+ # 2. merge this package's hooks.json into ~/.codex/hooks.json, replacing
109
+ # "command" with the venv's absolute path plus the plugin's env vars:
110
+ # "command": "env AGENTGUARD_AGENT_ID=codex-local \
111
+ # OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
112
+ # /Users/you/venvs/agentguard-codex/bin/agentguard-codex"
113
+
114
+ # 3. start Codex, run /hooks, review and trust the AgentGuard entries, quit
115
+ codex
116
+
117
+ # 4. run a turn
118
+ codex exec --skip-git-repo-check -s workspace-write \
119
+ "Run pwd, then create done.txt containing ok."
120
+
121
+ # 5. inspect the exported spans at the configured OTLP endpoint (the app's
122
+ # otel_traces, or any local OTLP collector), then remove the AgentGuard
123
+ # entries from ~/.codex/hooks.json
124
+ ```
125
+
126
+ ## Publishing
127
+
128
+ Releases are published to PyPI by CI:
129
+
130
+ 1. Bump `version` in `pyproject.toml` and `__version__` in `agentguard_codex/__init__.py`, and merge.
131
+ 2. Publish a GitHub Release tagged `codex-plugin-v<version>` (for example `codex-plugin-v0.1.1`).
132
+
133
+ The `Publish Codex plugin` workflow tests, builds and uploads `timeplus-agentguard-codex-plugin`. It fails if the tag does not match the package version. Running it manually builds and validates without uploading; `make check` does the same locally (needs `hatch` and `twine`).
@@ -0,0 +1,3 @@
1
+ """AgentGuard monitoring plugin for OpenAI Codex."""
2
+
3
+ __version__ = "0.1.1"
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m agentguard_codex`` to act as the hook command."""
2
+
3
+ from agentguard_codex.cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,125 @@
1
+ """``agentguard-codex`` — Codex hook entry point for AgentGuard.
2
+
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 drives
5
+ the AgentGuard Python SDK. See ``hooks.json`` for a sample Codex hook
6
+ configuration.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import socket
15
+ import sys
16
+
17
+ from agentguard_codex.events import dispatch
18
+
19
+ DEFAULT_DEPLOYMENT_ID = "local"
20
+ DEFAULT_DEPLOYMENT_NAME = "Local Dev"
21
+ DEFAULT_ENDPOINT = "http://localhost:4318"
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ parser = argparse.ArgumentParser(
26
+ prog="agentguard-codex",
27
+ description="Forward OpenAI Codex hook events to AgentGuard",
28
+ formatter_class=argparse.RawDescriptionHelpFormatter,
29
+ epilog=(
30
+ "Reads one Codex hook event as JSON on stdin and exports\n"
31
+ "OpenTelemetry spans to the AgentGuard Timeplus app's OTLP input."
32
+ ),
33
+ )
34
+ parser.add_argument(
35
+ "--agent-id",
36
+ default=None,
37
+ help="Unique agent identifier (default: $AGENTGUARD_AGENT_ID or hostname)",
38
+ )
39
+ parser.add_argument(
40
+ "--deployment-id",
41
+ default=None,
42
+ help="Deployment identifier (default: $AGENTGUARD_DEPLOYMENT_ID or 'local')",
43
+ )
44
+ parser.add_argument(
45
+ "--deployment-name",
46
+ default=None,
47
+ help="Human-readable deployment name (default: $AGENTGUARD_DEPLOYMENT_NAME or 'Local Dev')",
48
+ )
49
+ parser.add_argument(
50
+ "--endpoint",
51
+ default=None,
52
+ help="OTLP/HTTP endpoint (default: $OTEL_EXPORTER_OTLP_ENDPOINT or http://localhost:4318)",
53
+ )
54
+ return parser
55
+
56
+
57
+ def resolve_agent_id(agent_id: str | None) -> str:
58
+ """Resolve the agent id the SDK also uses to key its on-disk store.
59
+
60
+ The SDK's ``AgentGuardHooks`` falls back to the literal folder name
61
+ ``hostname`` when ``agent_id`` is ``None``, so resolve the env-var fallback
62
+ here and pass the result through; otherwise agents that omit ``--agent-id``
63
+ would all share one Pre/Post-tool timing store.
64
+ """
65
+ return agent_id or os.environ.get("AGENTGUARD_AGENT_ID") or socket.gethostname()
66
+
67
+
68
+ def resolve_deployment_id(deployment_id: str | None) -> str:
69
+ """Resolve the deployment id: flag, then env, then ``local``."""
70
+ return (
71
+ deployment_id
72
+ or os.environ.get("AGENTGUARD_DEPLOYMENT_ID")
73
+ or DEFAULT_DEPLOYMENT_ID
74
+ )
75
+
76
+
77
+ def resolve_deployment_name(deployment_name: str | None) -> str:
78
+ """Resolve the deployment name: flag, then env, then ``Local Dev``."""
79
+ return (
80
+ deployment_name
81
+ or os.environ.get("AGENTGUARD_DEPLOYMENT_NAME")
82
+ or DEFAULT_DEPLOYMENT_NAME
83
+ )
84
+
85
+
86
+ def resolve_endpoint(endpoint: str | None) -> str:
87
+ """Resolve the OTLP/HTTP endpoint: flag, then env, then localhost:4318."""
88
+ return (
89
+ endpoint
90
+ or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
91
+ or DEFAULT_ENDPOINT
92
+ )
93
+
94
+
95
+ def main(argv: list[str] | None = None) -> int:
96
+ try:
97
+ args = build_parser().parse_args(argv)
98
+
99
+ # Imported lazily so ``import agentguard_codex.cli`` (and ``--help``)
100
+ # works without the AgentGuard SDK, and a missing SDK is handled by
101
+ # the same fail-safe path as any other plugin error.
102
+ from agentguard.hook import AgentGuardHooks
103
+
104
+ hooks = AgentGuardHooks(
105
+ agent_id=resolve_agent_id(args.agent_id),
106
+ deployment_id=resolve_deployment_id(args.deployment_id),
107
+ deployment_name=resolve_deployment_name(args.deployment_name),
108
+ endpoint=resolve_endpoint(args.endpoint),
109
+ )
110
+
111
+ event = json.loads(sys.stdin.read())
112
+ dispatch(event, hooks)
113
+ except SystemExit:
114
+ # argparse raises SystemExit for --help (0) and bad flags (2). A bad
115
+ # flag must not change the Codex turn, so report success either way.
116
+ return 0
117
+ except Exception as exc:
118
+ # Never let a plugin failure take down (or change) the Codex turn.
119
+ print(f"agentguard-codex: {exc}", file=sys.stderr)
120
+
121
+ return 0
122
+
123
+
124
+ if __name__ == "__main__":
125
+ raise SystemExit(main())
@@ -0,0 +1,115 @@
1
+ """Translate Codex hook events into AgentGuard SDK calls.
2
+
3
+ Codex invokes one short-lived command per hook event and writes a single
4
+ JSON object to stdin. Every object carries ``hook_event_name`` and
5
+ ``session_id``; turn-scoped events also carry ``turn_id``. This module only
6
+ does the translation — the SDK owns session bookkeeping and span export.
7
+
8
+ Codex hooks reference: https://learn.chatgpt.com/docs/hooks
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from typing import Any, Protocol
15
+
16
+
17
+ class HookSink(Protocol):
18
+ """The subset of ``agentguard.hook.AgentGuardHooks`` this plugin uses."""
19
+
20
+ def on_session_start(self, session_id: str) -> None: ...
21
+
22
+ def on_session_end(self, session_id: str) -> None: ...
23
+
24
+ def on_llm_end(
25
+ self,
26
+ session_id: str,
27
+ *,
28
+ task_id: str | None = None,
29
+ model_name: str | None = None,
30
+ user_message: str | None = None,
31
+ ) -> None: ...
32
+
33
+ def on_pre_tool(
34
+ self,
35
+ session_id: str,
36
+ *,
37
+ run_id: str | None = None,
38
+ task_id: str | None = None,
39
+ ) -> None: ...
40
+
41
+ def on_post_tool(
42
+ self,
43
+ *,
44
+ session_id: str,
45
+ run_id: str | None = None,
46
+ task_id: str | None = None,
47
+ tool_name: str | None = None,
48
+ tool_input: str | None = None,
49
+ tool_result: str | None = None,
50
+ ) -> None: ...
51
+
52
+
53
+ def _as_string(value: Any) -> str | None:
54
+ """Render a Codex payload field for a span attribute.
55
+
56
+ Strings pass through unchanged; dicts/lists become JSON (not Python
57
+ ``repr``) so the Timeplus-side JSON functions can parse ``tool.parameters``
58
+ and ``output.value``. ``None`` stays ``None`` so the SDK omits the
59
+ attribute.
60
+ """
61
+ if value is None:
62
+ return None
63
+ if isinstance(value, str):
64
+ return value
65
+ return json.dumps(value, ensure_ascii=False)
66
+
67
+
68
+ def dispatch(event: dict[str, Any], hooks: HookSink) -> bool:
69
+ """Handle one Codex hook *event*.
70
+
71
+ Returns ``True`` when the event was handled and ``False`` for events this
72
+ plugin does not observe yet. Unrecognised events are ignored so a newer
73
+ Codex can add hooks without breaking the plugin. Optional payload fields
74
+ are read with ``.get`` because the exact per-hook shapes are still being
75
+ verified (see ``docs/todo.md``).
76
+ """
77
+ event_name = event.get("hook_event_name")
78
+ if not event_name:
79
+ return False
80
+
81
+ if event_name == "SessionStart":
82
+ hooks.on_session_start(event["session_id"])
83
+
84
+ elif event_name == "SessionEnd":
85
+ hooks.on_session_end(event["session_id"])
86
+
87
+ elif event_name == "UserPromptSubmit":
88
+ hooks.on_llm_end(
89
+ session_id=event["session_id"],
90
+ task_id=event.get("turn_id"),
91
+ model_name=event.get("model"),
92
+ user_message=event.get("prompt"),
93
+ )
94
+
95
+ elif event_name == "PreToolUse":
96
+ hooks.on_pre_tool(
97
+ session_id=event["session_id"],
98
+ run_id=event.get("turn_id"),
99
+ task_id=event.get("tool_use_id"),
100
+ )
101
+
102
+ elif event_name == "PostToolUse":
103
+ hooks.on_post_tool(
104
+ session_id=event["session_id"],
105
+ run_id=event.get("turn_id"),
106
+ task_id=event.get("tool_use_id"),
107
+ tool_name=event.get("tool_name"),
108
+ tool_input=_as_string(event.get("tool_input")),
109
+ tool_result=_as_string(event.get("tool_response")),
110
+ )
111
+
112
+ else:
113
+ return False
114
+
115
+ return True
@@ -0,0 +1,20 @@
1
+ {
2
+ "description": "Sample Codex hooks for AgentGuard. See README.md.",
3
+ "hooks": {
4
+ "SessionStart": [
5
+ { "hooks": [ { "type": "command", "command": "agentguard-codex", "timeout": 10 } ] }
6
+ ],
7
+ "SessionEnd": [
8
+ { "hooks": [ { "type": "command", "command": "agentguard-codex", "timeout": 10 } ] }
9
+ ],
10
+ "UserPromptSubmit": [
11
+ { "hooks": [ { "type": "command", "command": "agentguard-codex", "timeout": 10 } ] }
12
+ ],
13
+ "PreToolUse": [
14
+ { "hooks": [ { "type": "command", "command": "agentguard-codex", "timeout": 10 } ] }
15
+ ],
16
+ "PostToolUse": [
17
+ { "hooks": [ { "type": "command", "command": "agentguard-codex", "timeout": 10 } ] }
18
+ ]
19
+ }
20
+ }
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "timeplus-agentguard-codex-plugin"
7
+ version = "0.1.1"
8
+ description = "AgentGuard monitoring plugin for OpenAI Codex"
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ requires-python = ">=3.10"
12
+ keywords = ["agentguard", "codex", "security", "ai-agent", "monitoring", "observability"]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Topic :: Security",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ ]
24
+ dependencies = [
25
+ "timeplus-agentguard>=0.3.0",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/timeplus-io/agentguard"
30
+ Repository = "https://github.com/timeplus-io/agentguard"
31
+
32
+ [project.scripts]
33
+ agentguard-codex = "agentguard_codex.cli:main"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["agentguard_codex"]
37
+
38
+ [tool.ruff]
39
+ line-length = 100
40
+ target-version = "py310"
41
+
42
+ [tool.ruff.lint]
43
+ select = ["E", "F", "I", "N", "W", "UP"]
@@ -0,0 +1,119 @@
1
+ """Tests for the ``agentguard-codex`` entry point.
2
+
3
+ These cover the module wiring the dispatch tests miss: ``cli.py`` imports and
4
+ ``python -m agentguard_codex`` runs. They do not need the AgentGuard SDK or a
5
+ collector — a missing SDK is one of the failures the hook must swallow.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import socket
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import unittest
15
+
16
+ PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ sys.path.insert(0, PLUGIN_ROOT)
18
+
19
+
20
+ class CliTests(unittest.TestCase):
21
+ def test_cli_module_imports(self) -> None:
22
+ # Regression guard: a broken import in cli.py fails every hook, while
23
+ # the events-only tests keep passing.
24
+ from agentguard_codex import cli
25
+
26
+ self.assertTrue(callable(cli.main))
27
+
28
+ def test_help_exits_zero(self) -> None:
29
+ result = subprocess.run(
30
+ [sys.executable, "-m", "agentguard_codex", "--help"],
31
+ cwd=PLUGIN_ROOT,
32
+ capture_output=True,
33
+ text=True,
34
+ timeout=30,
35
+ )
36
+
37
+ self.assertEqual(result.returncode, 0, result.stderr)
38
+ self.assertIn("agentguard-codex", result.stdout)
39
+
40
+ def test_module_entry_point_never_fails_the_hook(self) -> None:
41
+ event = {"hook_event_name": "SessionStart", "session_id": "s1"}
42
+ with tempfile.TemporaryDirectory() as home:
43
+ env = {**os.environ, "HOME": home}
44
+ result = subprocess.run(
45
+ [sys.executable, "-m", "agentguard_codex", "--agent-id", "test-agent"],
46
+ cwd=PLUGIN_ROOT,
47
+ input=json.dumps(event),
48
+ capture_output=True,
49
+ text=True,
50
+ env=env,
51
+ timeout=30,
52
+ )
53
+
54
+ self.assertEqual(result.returncode, 0, result.stderr)
55
+ self.assertNotIn("Traceback", result.stderr)
56
+
57
+
58
+ class ResolveTests(unittest.TestCase):
59
+ """Flag beats env beats default, for every configurable value."""
60
+
61
+ ENV_VARS = (
62
+ "AGENTGUARD_AGENT_ID",
63
+ "AGENTGUARD_DEPLOYMENT_ID",
64
+ "AGENTGUARD_DEPLOYMENT_NAME",
65
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
66
+ )
67
+
68
+ def setUp(self) -> None:
69
+ from agentguard_codex import cli
70
+
71
+ self.cli = cli
72
+ self._saved = {name: os.environ.pop(name, None) for name in self.ENV_VARS}
73
+
74
+ def tearDown(self) -> None:
75
+ for name, value in self._saved.items():
76
+ if value is None:
77
+ os.environ.pop(name, None)
78
+ else:
79
+ os.environ[name] = value
80
+
81
+ def test_flag_wins_over_env(self) -> None:
82
+ os.environ["AGENTGUARD_AGENT_ID"] = "env-agent"
83
+ os.environ["AGENTGUARD_DEPLOYMENT_ID"] = "env-deployment"
84
+ os.environ["AGENTGUARD_DEPLOYMENT_NAME"] = "Env Deployment"
85
+ os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "http://env:4318"
86
+
87
+ self.assertEqual(self.cli.resolve_agent_id("flag-agent"), "flag-agent")
88
+ self.assertEqual(self.cli.resolve_deployment_id("flag-deployment"), "flag-deployment")
89
+ self.assertEqual(self.cli.resolve_deployment_name("Flag Deployment"), "Flag Deployment")
90
+ self.assertEqual(self.cli.resolve_endpoint("http://flag:4318"), "http://flag:4318")
91
+
92
+ def test_env_wins_over_default(self) -> None:
93
+ os.environ["AGENTGUARD_AGENT_ID"] = "env-agent"
94
+ os.environ["AGENTGUARD_DEPLOYMENT_ID"] = "env-deployment"
95
+ os.environ["AGENTGUARD_DEPLOYMENT_NAME"] = "Env Deployment"
96
+ os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "http://env:4318"
97
+
98
+ self.assertEqual(self.cli.resolve_agent_id(None), "env-agent")
99
+ self.assertEqual(self.cli.resolve_deployment_id(None), "env-deployment")
100
+ self.assertEqual(self.cli.resolve_deployment_name(None), "Env Deployment")
101
+ self.assertEqual(self.cli.resolve_endpoint(None), "http://env:4318")
102
+
103
+ def test_empty_env_falls_through_to_default(self) -> None:
104
+ for name in self.ENV_VARS:
105
+ os.environ[name] = ""
106
+
107
+ self.assertEqual(self.cli.resolve_agent_id(None), socket.gethostname())
108
+ self.assertEqual(self.cli.resolve_deployment_id(None), self.cli.DEFAULT_DEPLOYMENT_ID)
109
+ self.assertEqual(self.cli.resolve_deployment_name(None), self.cli.DEFAULT_DEPLOYMENT_NAME)
110
+ self.assertEqual(self.cli.resolve_endpoint(None), self.cli.DEFAULT_ENDPOINT)
111
+
112
+ def test_defaults(self) -> None:
113
+ self.assertEqual(self.cli.resolve_deployment_id(None), "local")
114
+ self.assertEqual(self.cli.resolve_deployment_name(None), "Local Dev")
115
+ self.assertEqual(self.cli.resolve_endpoint(None), "http://localhost:4318")
116
+
117
+
118
+ if __name__ == "__main__":
119
+ unittest.main()
@@ -0,0 +1,188 @@
1
+ """Unit tests for Codex hook event translation.
2
+
3
+ The tests use a recording sink instead of the real AgentGuard SDK, so they
4
+ need no dependencies and no running collector.
5
+
6
+ Run: python3.12 -m unittest discover -s tests -v
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import unittest
12
+
13
+ PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
+ sys.path.insert(0, PLUGIN_ROOT)
15
+
16
+ from agentguard_codex.events import dispatch # noqa: E402
17
+
18
+
19
+ class RecordingHooks:
20
+ """Records every SDK call made by :func:`dispatch`."""
21
+
22
+ def __init__(self) -> None:
23
+ self.calls: list[tuple[str, tuple, dict]] = []
24
+
25
+ def __getattr__(self, name: str):
26
+ def record(*args, **kwargs):
27
+ self.calls.append((name, args, kwargs))
28
+
29
+ return record
30
+
31
+
32
+ class DispatchTests(unittest.TestCase):
33
+ def setUp(self) -> None:
34
+ self.hooks = RecordingHooks()
35
+
36
+ def test_session_start(self) -> None:
37
+ handled = dispatch({"hook_event_name": "SessionStart", "session_id": "s1"}, self.hooks)
38
+
39
+ self.assertTrue(handled)
40
+ self.assertEqual(self.hooks.calls, [("on_session_start", ("s1",), {})])
41
+
42
+ def test_session_end(self) -> None:
43
+ handled = dispatch({"hook_event_name": "SessionEnd", "session_id": "s1"}, self.hooks)
44
+
45
+ self.assertTrue(handled)
46
+ self.assertEqual(self.hooks.calls, [("on_session_end", ("s1",), {})])
47
+
48
+ def test_user_prompt_submit(self) -> None:
49
+ handled = dispatch(
50
+ {
51
+ "hook_event_name": "UserPromptSubmit",
52
+ "session_id": "s1",
53
+ "turn_id": "t1",
54
+ "model": "gpt-5-codex",
55
+ "prompt": "fix the failing test",
56
+ },
57
+ self.hooks,
58
+ )
59
+
60
+ self.assertTrue(handled)
61
+ self.assertEqual(
62
+ self.hooks.calls,
63
+ [
64
+ (
65
+ "on_llm_end",
66
+ (),
67
+ {
68
+ "session_id": "s1",
69
+ "task_id": "t1",
70
+ "model_name": "gpt-5-codex",
71
+ "user_message": "fix the failing test",
72
+ },
73
+ )
74
+ ],
75
+ )
76
+
77
+ def test_user_prompt_submit_without_optional_fields(self) -> None:
78
+ handled = dispatch(
79
+ {"hook_event_name": "UserPromptSubmit", "session_id": "s1"}, self.hooks
80
+ )
81
+
82
+ self.assertTrue(handled)
83
+ self.assertEqual(
84
+ self.hooks.calls,
85
+ [
86
+ (
87
+ "on_llm_end",
88
+ (),
89
+ {"session_id": "s1", "task_id": None, "model_name": None, "user_message": None},
90
+ )
91
+ ],
92
+ )
93
+
94
+ def test_pre_tool_use(self) -> None:
95
+ handled = dispatch(
96
+ {
97
+ "hook_event_name": "PreToolUse",
98
+ "session_id": "s1",
99
+ "turn_id": "t1",
100
+ "tool_use_id": "call_1",
101
+ "tool_name": "Bash",
102
+ },
103
+ self.hooks,
104
+ )
105
+
106
+ self.assertTrue(handled)
107
+ self.assertEqual(
108
+ self.hooks.calls,
109
+ [("on_pre_tool", (), {"session_id": "s1", "run_id": "t1", "task_id": "call_1"})],
110
+ )
111
+
112
+ def test_post_tool_use_json_encodes_inputs(self) -> None:
113
+ handled = dispatch(
114
+ {
115
+ "hook_event_name": "PostToolUse",
116
+ "session_id": "s1",
117
+ "turn_id": "t1",
118
+ "tool_use_id": "call_1",
119
+ "tool_name": "Bash",
120
+ "tool_input": {"command": "ls"},
121
+ "tool_response": {"stdout": "README.md"},
122
+ },
123
+ self.hooks,
124
+ )
125
+
126
+ self.assertTrue(handled)
127
+ self.assertEqual(
128
+ self.hooks.calls,
129
+ [
130
+ (
131
+ "on_post_tool",
132
+ (),
133
+ {
134
+ "session_id": "s1",
135
+ "run_id": "t1",
136
+ "task_id": "call_1",
137
+ "tool_name": "Bash",
138
+ "tool_input": '{"command": "ls"}',
139
+ "tool_result": '{"stdout": "README.md"}',
140
+ },
141
+ )
142
+ ],
143
+ )
144
+
145
+ def test_post_tool_use_passes_strings_through(self) -> None:
146
+ handled = dispatch(
147
+ {
148
+ "hook_event_name": "PostToolUse",
149
+ "session_id": "s1",
150
+ "tool_name": "Bash",
151
+ "tool_input": "ls -la",
152
+ "tool_response": "total 0",
153
+ },
154
+ self.hooks,
155
+ )
156
+
157
+ self.assertTrue(handled)
158
+ self.assertEqual(
159
+ self.hooks.calls,
160
+ [
161
+ (
162
+ "on_post_tool",
163
+ (),
164
+ {
165
+ "session_id": "s1",
166
+ "run_id": None,
167
+ "task_id": None,
168
+ "tool_name": "Bash",
169
+ "tool_input": "ls -la",
170
+ "tool_result": "total 0",
171
+ },
172
+ )
173
+ ],
174
+ )
175
+
176
+ def test_unknown_event_is_ignored(self) -> None:
177
+ handled = dispatch({"hook_event_name": "PreModelRequest", "session_id": "s1"}, self.hooks)
178
+
179
+ self.assertFalse(handled)
180
+ self.assertEqual(self.hooks.calls, [])
181
+
182
+ def test_event_without_name_is_ignored(self) -> None:
183
+ self.assertFalse(dispatch({"session_id": "s1"}, self.hooks))
184
+ self.assertEqual(self.hooks.calls, [])
185
+
186
+
187
+ if __name__ == "__main__":
188
+ unittest.main()