@oked/codex 0.0.0-stage → 0.6.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # @oked/codex
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/@oked/codex.svg)](https://www.npmjs.com/package/@oked/codex)
4
+ [![License: Apache-2.0](https://img.shields.io/npm/l/@oked/codex.svg)](./LICENSE)
5
+
6
+ Codex CLI hook. Sensitive actions wait for a person in Telegram or on the [web dashboard](https://oked.ai/dashboard) before Codex continues. The iPhone app is coming soon. Questions: [contact@oked.ai](mailto:contact@oked.ai).
7
+
8
+ Safe actions are allowed by the hook, with no notification. Warning actions are allowed and logged. OKed asks only for `review` and `high_stakes`.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install -g @oked/codex
14
+ oked-codex init
15
+ ```
16
+
17
+ `oked-codex init` writes `.codex/hooks.json` in the current project and stores the API key in `~/.oked/config.json`. The file it writes:
18
+
19
+ ```json
20
+ {
21
+ "hooks": {
22
+ "PreToolUse": [
23
+ {
24
+ "matcher": "*",
25
+ "hooks": [
26
+ { "type": "command", "command": "oked-codex-hook", "timeout": 690 }
27
+ ]
28
+ }
29
+ ]
30
+ }
31
+ }
32
+ ```
33
+
34
+ The matcher is `*`, so every local tool is included. Other hooks already in that file are kept. A second init does not add a second copy. It raises a timeout below 690 and removes `async: true`. The binary is `oked-codex`, not `oked`, so it can sit next to `@oked/claude-code`.
35
+
36
+ Then, in Codex, run `/hooks` and trust the hook. Codex remembers that trust against the hook hash. Run `/hooks` again after `oked-codex init` changes the timeout or the command.
37
+
38
+ The approval window is 10 minutes. The hook process is allowed 690 seconds, and the SDK client waits 630 seconds, so a timeout becomes a deny instead of Codex killing the hook first.
39
+
40
+ ## Commands
41
+
42
+ | Command | What it does |
43
+ |---|---|
44
+ | `oked-codex init` | Install or update the project hook and pair this device. Run it again after you update the package. |
45
+ | `oked-codex init --no-browser` | Print the pairing link. Do not open a browser, and do not touch the clipboard. |
46
+ | `oked-codex init --yes` (or `-y`) | Skip the "press Enter to open the browser" prompt. For a non-interactive shell. |
47
+ | `oked-codex status` | Show install state and ping `GET /health` on the backend. |
48
+ | `oked-codex uninstall` | Remove the project hook entry. Other hooks in `.codex/hooks.json` are kept. |
49
+
50
+ ## What gets intercepted
51
+
52
+ The hook uses the same four-tier classifier as `@oked/claude-code`. Classification is effect-based. Reads and commands with no detected side effect are `safe`. Reversible local changes are `warning` (allowed, and logged). Destructive, irreversible, or outward-facing actions are `review` or `high_stakes` and wait for a person.
53
+
54
+ Codex tool names are mapped onto that classifier before the decision:
55
+
56
+ | Codex tool | OKed sees | Notes |
57
+ |---|---|---|
58
+ | `Bash`, `exec_command`, `shell_command`, `local_shell` | `Bash` | Shell, network, and deploy commands use the bash rules. `ls` and `git status` are safe. `rm` of a real file, a force push, and a production deploy wait. |
59
+ | `apply_patch` | `Write` or `rm` | A delete in the patch is classified as `rm`. A write is `warning` unless the path is sensitive (`/etc`, `~/.ssh`, shell rc, OKed config), which is `review`. |
60
+ | `mcp__server__tool` | the same name | `list_*` and `get_*` are safe. `create_*`, `send_*`, and `update_*` are `review`. `delete_*`, `drop_*`, and `remove_*` are `high_stakes`. |
61
+ | `spawn_agent` | `Agent` | Starting a sub-agent is safe. Its own tool calls are gated on their own. |
62
+ | anything else | the same name | Unknown tools are `review`. They wait for approval. |
63
+
64
+ Hosted tools such as web search do not run this hook. Codex does not send them through `PreToolUse`.
65
+
66
+ ## How it works
67
+
68
+ 1. Codex runs `oked-codex-hook` before the tool call. The hook is a separate process. The matcher is `*`, so every local tool is included.
69
+ 2. The hook classifies the action locally. `safe` and `warning` do not wait on the network, unless a cached user rule matches.
70
+ 3. For `review` and `high_stakes`, it sends an approval request.
71
+ 4. You decide in Telegram or on the web dashboard. Web push is optional.
72
+ 5. Approve, and the hook prints nothing. Codex treats empty output as success and continues. Deny or time out, and the hook prints `permissionDecision: "deny"` with the reason.
73
+
74
+ An explicit `permissionDecision: "allow"` without `updatedInput` is not a normal allow in Codex. The current source marks it unsupported and still runs the tool (`permission_decision_allow_without_updated_input_fails_open` in `codex-rs/hooks/src/events/pre_tool_use.rs`). This hook never prints `allow`, and it never prints `ask`. `ask` is unsupported in the same way, and the tool would continue.
75
+
76
+ If this device is not paired, the hook denies. The reason is `Pair first: run oked-codex init`. It does not fail open.
77
+
78
+ ## Timeout
79
+
80
+ Codex measures `timeout` in seconds. The default is 600. In `normalize_command_hook` (`codex-rs/hooks/src/engine/discovery.rs`) every event except `SessionEnd` and `Interrupt` uses `timeout_sec.unwrap_or(600).max(1)`. There is no upper cap. `SessionEnd` and `Interrupt` are capped at 3 seconds. This package does not install those events.
81
+
82
+ `oked-codex init` sets `timeout` to 690. It raises a lower value. A higher value you set yourself is left alone. It also removes `async: true`. An async hook runs in the background and does not wait for the decision.
83
+
84
+ Docs: [developers.openai.com/codex/hooks](https://developers.openai.com/codex/hooks). Source checked on 2026-10-28: [discovery.rs](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs) and [pre_tool_use.rs](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/events/pre_tool_use.rs).
85
+
86
+ ## Limits
87
+
88
+ Codex describes hooks as a useful guardrail, not a complete enforcement boundary. A callback error, a timeout, or malformed output fails open: the tool runs. The 690 second timeout is what keeps the SDK's own deny inside the window Codex will wait. If a future Codex build caps the timeout below 630 seconds, that deny would not be written, and the call would fail open. No such cap is in the source above.
89
+
90
+ Command hooks do not run in Codex cloud. `write_stdin` on a shell that already passed `PreToolUse` does not run the hook again.
91
+
92
+ ## Environment
93
+
94
+ | Var | Required | Description |
95
+ |---|---|---|
96
+ | `OKED_API_KEY` | no, after pairing | Optional override. `oked-codex init` stores the paired key in `~/.oked/config.json`. |
97
+ | `OKED_STRICT_FAIL_CLOSED` | no | `1` or `true` denies every sensitive action when the backend is unreachable. |
98
+ | `OKED_REQUIRE_RECEIPT` | no | `0` allows an approval with no receipt. On by default since 0.6.0. |
99
+ | `OKED_HOOK_LOG` | no | Decision log path. Default `~/.oked/hook.log`. |
100
+
101
+ ## Receipts
102
+
103
+ Every decision comes with a receipt signed by OKed. The hook verifies it before allowing the action and keeps a copy in `~/.oked/receipts.jsonl`. Since 0.6.0 the hook denies an approval that has no valid receipt. Set `OKED_REQUIRE_RECEIPT=0` only for a backend that does not sign receipts.
104
+
105
+ You can paste one receipt at [oked.ai/docs/#verify](https://oked.ai/docs#verify), or check an export with `npx @oked/verify`. `oked receipts verify` from `@oked/claude-code` checks the same file. See [docs/receipts.md](../../docs/receipts.md).
106
+
107
+ ## Degraded-mode behavior
108
+
109
+ Explicit denials, invalid API keys, and receipts that do not verify deny the action. If the backend is unreachable, OKed denies `high_stakes` and, by default, allows lower tiers. Set `OKED_STRICT_FAIL_CLOSED=1` to deny every sensitive action during an outage.
110
+
111
+ HTTP 429 (too many approvals already waiting) is not an outage: the action is denied until those are decided in Telegram or on the dashboard.
112
+
113
+ If the hook cannot parse its stdin, it denies. A bad payload must not become a silent allow.
114
+
115
+ ## Decision log
116
+
117
+ The hook writes one JSON line to `~/.oked/hook.log` (mode 600) for each deny, and for each degraded allow. The log never holds the tool input or the command.
118
+
119
+ ## Double prompts
120
+
121
+ Codex does not load `~/.claude/settings.json` or a project `.claude/settings.json`. There is no `--native` flag, because a Claude Code hook does not also run inside Codex. Installing both packages asks once in each tool, not twice in Codex.
122
+
123
+ ## Uninstall
124
+
125
+ `oked-codex uninstall` removes only the `oked-codex-hook` entry. Other hooks in `.codex/hooks.json` stay. If that was the only content, the file is deleted. The API key in `~/.oked/config.json` stays, so Claude Code and the other hooks keep working. Run `/hooks` in Codex if it still lists a hook you removed. Trust is stored by Codex, not by this file alone.
126
+
127
+ ## Troubleshooting
128
+
129
+ - Nothing happens: the hook is not trusted yet. Run `/hooks` in Codex and trust it. A changed timeout changes the hash, so trust it again.
130
+ - Risky command ran with no card: the hook timed out, crashed, or printed bad JSON. Codex fails open in those cases. Confirm `timeout` is 690. Do not set `async`.
131
+ - `Pair first: run oked-codex init`: this machine has no API key. Run that command. It does not silently allow the call.
132
+ - Backend down: `high_stakes` is denied. Lower tiers are allowed unless `OKED_STRICT_FAIL_CLOSED=1`. A decision of `timeout` (nobody answered in 10 minutes) is a deny.
133
+ - Codex cloud: command hooks do not run there. Hosted tools such as web search are not sent to `PreToolUse`.
134
+ - Still stuck: [contact@oked.ai](mailto:contact@oked.ai).
135
+
136
+ ## License
137
+
138
+ [Apache-2.0](./LICENSE)
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/hook.js";
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/cli.js";
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from "fs";
3
+ import { maskKey, pairDevice, writeOkedConfig } from "@oked/hook-core";
4
+ import { OKedClient, OKED_CONFIG_PATH } from "@oked/sdk";
5
+ import { codexHookInstalled, hooksPath, installCodexHook, uninstallCodexHook } from "./install.js";
6
+ import { CLIENT_VERSION, PAIR_COMMAND } from "./version.js";
7
+ const BACKEND = process.env.OKED_BACKEND_URL || "https://api.oked.ai";
8
+ const NO_BROWSER = process.argv.includes("--no-browser");
9
+ function footer(uri) {
10
+ return [` (Or visit ${uri} and enter the code above.)`, " The iPhone app is coming soon."];
11
+ }
12
+ async function init() {
13
+ const cwd = process.cwd();
14
+ const result = installCodexHook(cwd);
15
+ if (result.action === "unreadable") {
16
+ console.log(`OKed could not read ${result.path}. It was not changed.`);
17
+ }
18
+ else if (result.action === "installed") {
19
+ console.log("OKed hook installed.");
20
+ console.log(` Config: ${result.path}`);
21
+ }
22
+ else if (result.action === "updated") {
23
+ console.log("OKed hook updated.");
24
+ console.log(` Config: ${result.path}`);
25
+ }
26
+ else {
27
+ console.log("OKed hook already configured.");
28
+ console.log(` Config: ${result.path}`);
29
+ }
30
+ console.log(" After this, run /hooks in Codex and trust the hook.");
31
+ console.log(" Trust follows the hook hash. A changed timeout asks again.");
32
+ const existing = new OKedClient();
33
+ if (existing.apiKey) {
34
+ const ok = await existing.ping();
35
+ console.log("");
36
+ console.log(` API key: ${maskKey(existing.apiKey)} (already paired)`);
37
+ console.log(` Backend: ${existing.backendUrl} (${ok ? "connected" : "not reachable"})`);
38
+ console.log("");
39
+ console.log("Codex in this project now asks before a risky tool call.");
40
+ return;
41
+ }
42
+ const apiKey = await pairDevice({
43
+ backendUrl: BACKEND,
44
+ clientType: "codex",
45
+ clientVersion: CLIENT_VERSION,
46
+ noBrowser: NO_BROWSER,
47
+ retryCommand: PAIR_COMMAND,
48
+ scanLine: " Or scan this with your phone camera. It opens the pairing page in the browser.",
49
+ footerLines: footer,
50
+ });
51
+ if (!apiKey)
52
+ return;
53
+ writeOkedConfig(apiKey, BACKEND);
54
+ console.log("");
55
+ console.log(` Paired. Key saved to ${OKED_CONFIG_PATH}`);
56
+ console.log("");
57
+ console.log("Codex in this project now asks before a risky tool call.");
58
+ console.log("Open a new Codex session, then trust the hook with /hooks.");
59
+ }
60
+ async function status() {
61
+ const path = hooksPath(process.cwd());
62
+ const client = new OKedClient();
63
+ console.log("OKed status:");
64
+ console.log(` Hook: ${codexHookInstalled(process.cwd()) ? "installed" : "not installed"}`);
65
+ console.log(` Project config: ${existsSync(path) ? path : "not found"}`);
66
+ console.log(` API key: ${client.apiKey ? maskKey(client.apiKey) : "not paired"}`);
67
+ console.log(` User config: ${existsSync(OKED_CONFIG_PATH) ? OKED_CONFIG_PATH : "not found"}`);
68
+ if (client.apiKey) {
69
+ const ok = await client.ping();
70
+ console.log(` Backend: ${client.backendUrl} (${ok ? "connected" : "not reachable"})`);
71
+ }
72
+ }
73
+ function uninstall() {
74
+ const result = uninstallCodexHook(process.cwd());
75
+ if (result.action === "unreadable") {
76
+ console.log(`OKed could not read ${result.path}. It was not changed.`);
77
+ return;
78
+ }
79
+ if (result.action === "absent") {
80
+ console.log("OKed hook was not installed in this project.");
81
+ return;
82
+ }
83
+ console.log("OKed hook removed from this project.");
84
+ console.log(` Config: ${result.path}`);
85
+ }
86
+ const command = process.argv[2];
87
+ switch (command) {
88
+ case "init":
89
+ init().catch(console.error);
90
+ break;
91
+ case "status":
92
+ status().catch(console.error);
93
+ break;
94
+ case "uninstall":
95
+ uninstall();
96
+ break;
97
+ default:
98
+ console.log("Usage: oked-codex <command>");
99
+ console.log("");
100
+ console.log("Commands:");
101
+ console.log(" init Install the Codex PreToolUse hook and pair this device");
102
+ console.log(" --no-browser Print the pairing link. Open no browser, use no clipboard.");
103
+ console.log(" status Show the hook and the connection");
104
+ console.log(" uninstall Remove the OKed hook from this project");
105
+ break;
106
+ }
package/dist/hook.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/hook.js ADDED
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ import { decide, errorInfo, logDecision } from "@oked/hook-core";
3
+ import { mapCodexTool } from "./map.js";
4
+ import { writeDecision } from "./output.js";
5
+ import { CLIENT_ID, PAIR_COMMAND, UNINSTALL_COMMAND } from "./version.js";
6
+ function invalidKeyReason(status) {
7
+ return `OKed: invalid API key (HTTP ${status}). Pair first: run \`${PAIR_COMMAND}\` to pair again, or \`${UNINSTALL_COMMAND}\` to remove OKed.`;
8
+ }
9
+ const UNPAIRED = `OKed: this device is not paired. Pair first: run ${PAIR_COMMAND}`;
10
+ function denyUnreadable(reason) {
11
+ writeDecision({ decision: "deny", reason });
12
+ logDecision({
13
+ decision: "deny",
14
+ reason,
15
+ tool: "unknown",
16
+ tier: null,
17
+ client: CLIENT_ID,
18
+ });
19
+ }
20
+ async function main() {
21
+ let raw = "";
22
+ for await (const chunk of process.stdin)
23
+ raw += chunk;
24
+ let input;
25
+ try {
26
+ const parsed = JSON.parse(raw);
27
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
28
+ throw new Error("not an object");
29
+ input = parsed;
30
+ }
31
+ catch {
32
+ denyUnreadable(`OKed: the hook input could not be read. Pair first: run ${PAIR_COMMAND}`);
33
+ return;
34
+ }
35
+ const toolName = typeof input.tool_name === "string" ? input.tool_name : "";
36
+ if (!toolName) {
37
+ denyUnreadable(`OKed: the hook input had no tool name. Pair first: run ${PAIR_COMMAND}`);
38
+ return;
39
+ }
40
+ const mapped = mapCodexTool(toolName, input.tool_input);
41
+ const decision = await decide({
42
+ toolName: mapped.toolName,
43
+ toolInput: mapped.toolInput,
44
+ cwd: typeof input.cwd === "string" ? input.cwd : undefined,
45
+ sessionId: typeof input.session_id === "string" ? input.session_id : undefined,
46
+ }, {
47
+ clientId: CLIENT_ID,
48
+ source: "codex",
49
+ unpaired: "deny",
50
+ unpairedReason: UNPAIRED,
51
+ unpairedLog: `not paired - pair first: run ${PAIR_COMMAND}`,
52
+ invalidKeyReason,
53
+ });
54
+ writeDecision(decision);
55
+ }
56
+ main().catch((err) => {
57
+ const info = errorInfo(err);
58
+ const reason = `OKed: internal error (fail-safe): ${info.name}: ${info.message}`;
59
+ process.stderr.write(`[OKed] Fatal: ${err}\n`);
60
+ writeDecision({ decision: "deny", reason });
61
+ logDecision({
62
+ decision: "deny",
63
+ reason,
64
+ tool: "unknown",
65
+ tier: null,
66
+ client: CLIENT_ID,
67
+ error: info,
68
+ });
69
+ process.exit(0);
70
+ });
@@ -0,0 +1,28 @@
1
+ export declare const HOOK_COMMAND = "oked-codex-hook";
2
+ /** `*` matches every tool, including ones this package does not know by name. */
3
+ export declare const HOOK_MATCHER = "*";
4
+ export type InstallAction = "installed" | "updated" | "unchanged" | "unreadable";
5
+ export declare function hooksPath(cwd: string): string;
6
+ /**
7
+ * Add the OKed PreToolUse hook, or raise a short timeout on the one already
8
+ * there. A longer timeout is left alone. `async` is removed: a background
9
+ * hook does not wait for the person. Other hooks in the file stay.
10
+ */
11
+ export declare function upsertCodexHooks(doc: Record<string, unknown>): {
12
+ doc: Record<string, unknown>;
13
+ changed: boolean;
14
+ };
15
+ /** Remove only the OKed hook. Other hooks stay. */
16
+ export declare function removeCodexHooks(doc: Record<string, unknown>): {
17
+ doc: Record<string, unknown>;
18
+ changed: boolean;
19
+ };
20
+ export declare function codexHookInstalled(cwd: string): boolean;
21
+ export declare function installCodexHook(cwd: string): {
22
+ action: InstallAction;
23
+ path: string;
24
+ };
25
+ export declare function uninstallCodexHook(cwd: string): {
26
+ action: "removed" | "absent" | "unreadable";
27
+ path: string;
28
+ };
@@ -0,0 +1,152 @@
1
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
2
+ import { dirname, join } from "path";
3
+ import { HOOK_TIMEOUT_SECONDS } from "@oked/hook-core";
4
+ export const HOOK_COMMAND = "oked-codex-hook";
5
+ /** `*` matches every tool, including ones this package does not know by name. */
6
+ export const HOOK_MATCHER = "*";
7
+ export function hooksPath(cwd) {
8
+ return join(cwd, ".codex", "hooks.json");
9
+ }
10
+ function isOurs(hook) {
11
+ return !!hook && typeof hook === "object" && hook.command === HOOK_COMMAND;
12
+ }
13
+ function readDoc(path) {
14
+ if (!existsSync(path))
15
+ return { doc: {}, state: "absent" };
16
+ try {
17
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
18
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
19
+ return { doc: {}, state: "unreadable" };
20
+ return { doc: parsed, state: "ok" };
21
+ }
22
+ catch {
23
+ return { doc: {}, state: "unreadable" };
24
+ }
25
+ }
26
+ function preGroups(doc) {
27
+ const hooks = doc.hooks;
28
+ if (!hooks || typeof hooks !== "object")
29
+ return [];
30
+ const pre = hooks.PreToolUse;
31
+ if (!Array.isArray(pre))
32
+ return [];
33
+ return pre.filter((group) => group && typeof group === "object");
34
+ }
35
+ function documentHasOurs(doc) {
36
+ return preGroups(doc).some((group) => (group.hooks ?? []).some(isOurs));
37
+ }
38
+ /**
39
+ * Add the OKed PreToolUse hook, or raise a short timeout on the one already
40
+ * there. A longer timeout is left alone. `async` is removed: a background
41
+ * hook does not wait for the person. Other hooks in the file stay.
42
+ */
43
+ export function upsertCodexHooks(doc) {
44
+ const next = structuredClone(doc);
45
+ const hooks = (next.hooks && typeof next.hooks === "object" ? next.hooks : {});
46
+ const groups = preGroups(next);
47
+ let changed = false;
48
+ let found = false;
49
+ for (const group of groups) {
50
+ const list = Array.isArray(group.hooks) ? group.hooks : [];
51
+ group.hooks = list;
52
+ for (const hook of list) {
53
+ if (!isOurs(hook))
54
+ continue;
55
+ found = true;
56
+ if (hook.type !== "command") {
57
+ hook.type = "command";
58
+ changed = true;
59
+ }
60
+ if (hook.async === true) {
61
+ delete hook.async;
62
+ changed = true;
63
+ }
64
+ if (typeof hook.timeout !== "number" || hook.timeout < HOOK_TIMEOUT_SECONDS) {
65
+ hook.timeout = HOOK_TIMEOUT_SECONDS;
66
+ changed = true;
67
+ }
68
+ }
69
+ }
70
+ if (!found) {
71
+ groups.push({
72
+ matcher: HOOK_MATCHER,
73
+ hooks: [{ type: "command", command: HOOK_COMMAND, timeout: HOOK_TIMEOUT_SECONDS }],
74
+ });
75
+ changed = true;
76
+ }
77
+ if (!changed)
78
+ return { doc, changed: false };
79
+ hooks.PreToolUse = groups;
80
+ next.hooks = hooks;
81
+ return { doc: next, changed: true };
82
+ }
83
+ /** Remove only the OKed hook. Other hooks stay. */
84
+ export function removeCodexHooks(doc) {
85
+ const next = structuredClone(doc);
86
+ const hooks = next.hooks;
87
+ if (!hooks || typeof hooks !== "object" || !Array.isArray(hooks.PreToolUse)) {
88
+ return { doc: next, changed: false };
89
+ }
90
+ const record = hooks;
91
+ let changed = false;
92
+ const groups = [];
93
+ for (const group of record.PreToolUse) {
94
+ if (!group || typeof group !== "object") {
95
+ groups.push(group);
96
+ continue;
97
+ }
98
+ const list = Array.isArray(group.hooks) ? group.hooks : [];
99
+ const kept = list.filter((hook) => !isOurs(hook));
100
+ if (kept.length !== list.length)
101
+ changed = true;
102
+ if (kept.length > 0)
103
+ groups.push({ ...group, hooks: kept });
104
+ else if (list.length === 0)
105
+ groups.push(group);
106
+ }
107
+ if (!changed)
108
+ return { doc: next, changed: false };
109
+ if (groups.length > 0)
110
+ record.PreToolUse = groups;
111
+ else
112
+ delete hooks.PreToolUse;
113
+ if (Object.keys(hooks).length === 0)
114
+ delete next.hooks;
115
+ return { doc: next, changed: true };
116
+ }
117
+ function writeDoc(path, doc) {
118
+ mkdirSync(dirname(path), { recursive: true });
119
+ writeFileSync(path, JSON.stringify(doc, null, 2) + "\n");
120
+ }
121
+ export function codexHookInstalled(cwd) {
122
+ const { doc, state } = readDoc(hooksPath(cwd));
123
+ return state === "ok" && documentHasOurs(doc);
124
+ }
125
+ export function installCodexHook(cwd) {
126
+ const path = hooksPath(cwd);
127
+ const { doc, state } = readDoc(path);
128
+ if (state === "unreadable")
129
+ return { action: "unreadable", path };
130
+ const had = documentHasOurs(doc);
131
+ const next = upsertCodexHooks(doc);
132
+ if (!next.changed)
133
+ return { action: "unchanged", path };
134
+ writeDoc(path, next.doc);
135
+ return { action: had ? "updated" : "installed", path };
136
+ }
137
+ export function uninstallCodexHook(cwd) {
138
+ const path = hooksPath(cwd);
139
+ const { doc, state } = readDoc(path);
140
+ if (state === "absent")
141
+ return { action: "absent", path };
142
+ if (state === "unreadable")
143
+ return { action: "unreadable", path };
144
+ const next = removeCodexHooks(doc);
145
+ if (!next.changed)
146
+ return { action: "absent", path };
147
+ if (Object.keys(next.doc).length === 0)
148
+ unlinkSync(path);
149
+ else
150
+ writeDoc(path, next.doc);
151
+ return { action: "removed", path };
152
+ }
package/dist/map.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export interface MappedCall {
2
+ toolName: string;
3
+ toolInput: Record<string, unknown>;
4
+ }
5
+ /** `MCP:server:tool` or `mcp:server:tool` becomes `mcp__server__tool`. */
6
+ export declare function toMcpToolName(name: string): string;
7
+ /**
8
+ * Map a Codex PreToolUse call onto a name and input `classify()` understands.
9
+ * Unknown tools are left unknown, which the classifier sends to approval.
10
+ */
11
+ export declare function mapCodexTool(toolName: string, rawInput: unknown): MappedCall;
package/dist/map.js ADDED
@@ -0,0 +1,42 @@
1
+ import { asToolInput, mapPatch, stringField, withNormalizedFields } from "@oked/hook-core";
2
+ const SHELL_NAMES = new Set([
3
+ "bash",
4
+ "shell",
5
+ "exec",
6
+ "exec_command",
7
+ "shell_command",
8
+ "local_shell",
9
+ "container.exec",
10
+ ]);
11
+ /** `MCP:server:tool` or `mcp:server:tool` becomes `mcp__server__tool`. */
12
+ export function toMcpToolName(name) {
13
+ if (name.startsWith("mcp__"))
14
+ return name;
15
+ const rest = name.replace(/^(?:MCP|mcp):/, "");
16
+ const parts = rest.split(":").filter(Boolean);
17
+ if (parts.length >= 2)
18
+ return `mcp__${parts[0]}__${parts.slice(1).join("__")}`;
19
+ return `mcp__mcp__${parts[0] || "tool"}`;
20
+ }
21
+ /**
22
+ * Map a Codex PreToolUse call onto a name and input `classify()` understands.
23
+ * Unknown tools are left unknown, which the classifier sends to approval.
24
+ */
25
+ export function mapCodexTool(toolName, rawInput) {
26
+ const input = withNormalizedFields(asToolInput(rawInput));
27
+ if (toolName === "apply_patch" || toolName === "ApplyPatch") {
28
+ const patch = stringField(input, ["command", "patch", "input"]) ??
29
+ (typeof rawInput === "string" ? rawInput : "");
30
+ return mapPatch(patch);
31
+ }
32
+ if (toolName === "spawn_agent" || toolName === "Agent") {
33
+ return { toolName: "Agent", toolInput: input };
34
+ }
35
+ if (toolName === "Bash" || SHELL_NAMES.has(toolName)) {
36
+ return { toolName: "Bash", toolInput: input };
37
+ }
38
+ if (toolName.startsWith("mcp__") || /^(?:MCP|mcp):/.test(toolName)) {
39
+ return { toolName: toMcpToolName(toolName), toolInput: input };
40
+ }
41
+ return { toolName, toolInput: input };
42
+ }
@@ -0,0 +1,8 @@
1
+ import type { GateDecision } from "@oked/hook-core";
2
+ /**
3
+ * Codex continues when a PreToolUse hook prints nothing.
4
+ * `permissionDecision: "allow"` without `updatedInput` is an unsupported
5
+ * decision: Codex logs it and still runs the tool. `ask` is unsupported the
6
+ * same way. Deny is the only decision this hook prints.
7
+ */
8
+ export declare function writeDecision(decision: GateDecision): void;
package/dist/output.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Codex continues when a PreToolUse hook prints nothing.
3
+ * `permissionDecision: "allow"` without `updatedInput` is an unsupported
4
+ * decision: Codex logs it and still runs the tool. `ask` is unsupported the
5
+ * same way. Deny is the only decision this hook prints.
6
+ */
7
+ export function writeDecision(decision) {
8
+ if (decision.decision === "allow")
9
+ return;
10
+ const reason = decision.reason || "OKed denied this action.";
11
+ process.stdout.write(JSON.stringify({
12
+ hookSpecificOutput: {
13
+ hookEventName: "PreToolUse",
14
+ permissionDecision: "deny",
15
+ permissionDecisionReason: reason,
16
+ },
17
+ }));
18
+ }
@@ -0,0 +1,4 @@
1
+ export declare const CLIENT_VERSION: string;
2
+ export declare const CLIENT_ID: string;
3
+ export declare const PAIR_COMMAND = "oked-codex init";
4
+ export declare const UNINSTALL_COMMAND = "oked-codex uninstall";
@@ -0,0 +1,15 @@
1
+ import { readFileSync } from "fs";
2
+ import { dirname, join } from "path";
3
+ import { fileURLToPath } from "url";
4
+ export const CLIENT_VERSION = (() => {
5
+ try {
6
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
7
+ return JSON.parse(readFileSync(pkgPath, "utf-8")).version ?? "0.0.0";
8
+ }
9
+ catch {
10
+ return "0.0.0";
11
+ }
12
+ })();
13
+ export const CLIENT_ID = `@oked/codex@${CLIENT_VERSION}`;
14
+ export const PAIR_COMMAND = "oked-codex init";
15
+ export const UNINSTALL_COMMAND = "oked-codex uninstall";
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@oked/codex",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.23",
4
+ "description": "OKed for Codex CLI. A PreToolUse hook that holds risky tool calls for a human decision.",
5
+ "type": "module",
6
+ "bin": {
7
+ "oked-codex": "./bin/oked-codex.js",
8
+ "oked-codex-hook": "./bin/oked-codex-hook.js"
9
+ },
10
+ "scripts": {
11
+ "prebuild": "npm run build --workspace=@oked/hook-core",
12
+ "build": "tsc",
13
+ "test": "npm run build && node src/map.test.mjs && node src/install.test.mjs && node src/hook.test.mjs && node src/fixture.test.mjs",
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "bin",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "keywords": [
23
+ "oked",
24
+ "codex",
25
+ "ai-agent",
26
+ "approval",
27
+ "human-in-the-loop",
28
+ "hooks",
29
+ "openai"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/oked-ai/oked-sdk.git",
34
+ "directory": "packages/codex"
35
+ },
36
+ "bugs": {
37
+ "url": "https://github.com/oked-ai/oked-sdk/issues"
38
+ },
39
+ "homepage": "https://oked.ai",
40
+ "license": "Apache-2.0",
41
+ "engines": {
42
+ "node": ">=18"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "dependencies": {
48
+ "@oked/hook-core": "0.6.23",
49
+ "@oked/sdk": "0.6.23"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^26.6.5",
53
+ "typescript": "^7.0.2"
54
+ }
55
+ }