timeplus-agentguard-codex-plugin 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,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,8 @@
1
+ agentguard_codex/__init__.py,sha256=Ygs9JE5IvpztMgqyFsbDeAbVM3XIdcpBeLiTCbFJyag,76
2
+ agentguard_codex/__main__.py,sha256=BxJWAnJd3KnV32_S5SHnOu4-9DpQDhVbru5ojhg5Qpw,136
3
+ agentguard_codex/cli.py,sha256=NjlgFZRqmLyDLYxz2g1p8x2dzOy7IpmzzTcugDo08a8,4174
4
+ agentguard_codex/events.py,sha256=Y-GGhYKGMBqO0My3znq6u1NODhJd1BoH9YjoFGE7n7Y,3477
5
+ timeplus_agentguard_codex_plugin-0.1.1.dist-info/METADATA,sha256=OhxwHUNlXDu7DFbxIFUmXidOMjDxCKzYwMM6-XBcaRg,5865
6
+ timeplus_agentguard_codex_plugin-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ timeplus_agentguard_codex_plugin-0.1.1.dist-info/entry_points.txt,sha256=wcA8TDn8Gsk7Ajk2vvQO3lHa4stqMqBMkrlL6dkRhrg,63
8
+ timeplus_agentguard_codex_plugin-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ agentguard-codex = agentguard_codex.cli:main