Repository navigation
Expand file tree
/
Copy pathcodex.ts
More file actions
119 lines (106 loc) · 7.11 KB
/
Copy pathcodex.ts
File metadata and controls
119 lines (106 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/** Codex CLI bridge. Codex fires hooks from `config.toml` much like Claude Code, but its output schemas are stricter: every schema declares `additionalProperties: false`, and every `hookSpecificOutput` shape requires a typed `hookEventName` const. The shim therefore post-processes `token-goat hook` output before relaying it: it drops internal `_tg_*` keys (which would trip `additionalProperties`) and injects `hookEventName` into `hookSpecificOutput` when absent. Wire-format references: Codex 0.137.0+ expects `hookSpecificOutput.hookEventName` in Claude Code's PascalCase spelling (e.g. `PreToolUse`, not the raw `pre_tool_use` argv event name) -- matching CLAUDE_CODE_EVENT_NAMES in src/hook_registry.ts, the convention the live/wired `token-goat hook <event>` path already emits. */
/** Node source for the Codex hook shim. Behavior matches the Claude Code shim (validate `eventName` against the closed set of known hook events, then stdin → `token-goat hook <event>` → stdout) with two Codex-specific fixups applied to the child's JSON output: 1. strip top-level and nested `_tg_*` keys (additionalProperties: false), and 2. ensure `hookSpecificOutput.hookEventName` is set, defaulting to the PascalCase-mapped event name (HOOK_EVENT_NAME_MAP below, kept in sync with CLAUDE_CODE_EVENT_NAMES in src/hook_registry.ts) when the handler omitted it -- never the raw snake_case argv event name. `eventName` is concatenated into a shell command string below (`shell: true` is required on Windows to resolve the token-goat `.cmd`/`.bat` shim), so it is validated against `VALID_HOOK_EVENTS` first — a closed set that must be kept in sync with `HOOK_EVENTS` in src/types.ts. On any error the shim prints `{}` so the tool call proceeds unchanged. The shim also injects `TOKEN_GOAT_HARNESS_OVERRIDE=codex` before dispatching, the way kimi.ts and pi.ts do. Codex publishes no ambient per-session env var identifying its own hook subprocesses, so detectHarness() (./registry.ts) could only reach the codex branch through CODEX_SESSION_ID/CODEX_SESSION, which codex-cli 0.155.0 does not set, or through an OPENAI_API_KEY with no ANTHROPIC_API_KEY beside it. Absent would be survivable; the real hazard is the mis-hit. Two branches sit ahead of the codex one and both test variables a parent shell hands down, so a Codex launched from a Claude Code terminal (TERM_PROGRAM=claude-code, or CLAUDE_CODE_VERSION set) resolved 'claudecode', and every harness-scoped decision -- wire-format translation, PRE_COMPACT_CONTEXT_DROPPED -- was then taken for the wrong harness with nothing failing. The override is consulted before any sniffing, so injecting it settles the question rather than biasing it. This comment lives here rather than beside that line because everything inside CODEX_HOOK_SCRIPT is a template string: esbuild strips comments from module source, but shim comments are payload, and the bundle-size guard in tests/guards/dist_chunks_deduped.test.ts measures them. */
import { shimFallbackTimeoutConst, SHIM_MAX_BUFFER_CONST, SHIM_REQUIRES, SHIM_SPAWN_LADDER, SHIM_TRY_IN_PROCESS, SHIM_TRY_SERVER, SHIM_VALID_HOOK_EVENTS } from './shim_common.js'
// A second copy of this logic lives in src/hook_adapters.ts, which the resident hook server runs for a harness-aware (v2) client; tests/native_hook_adapter_equivalence.test.ts drives this installed shim and a server request with the same payloads and fails unless both print the same bytes and exit code.
export const CODEX_HOOK_SCRIPT = `#!/usr/bin/env node
// token-goat Codex hook shim. Forwards the hook payload to \`token-goat hook <event>\`, then strips _tg_* keys and injects hookEventName so the response satisfies Codex's strict (additionalProperties:false) schema.
'use strict'
${SHIM_REQUIRES}
${SHIM_VALID_HOOK_EVENTS}
// Codex sets no env var of its own identifying a hook subprocess; see this module's docblock.
process.env.TOKEN_GOAT_HARNESS_OVERRIDE = 'codex'
// Keep in sync with CLAUDE_CODE_EVENT_NAMES in src/hook_registry.ts -- the
// live/wired 'token-goat hook <event>' path (src/relay.ts) always emits this
// PascalCase spelling for hookSpecificOutput.hookEventName, never the raw
// snake_case event name.
const HOOK_EVENT_NAME_MAP = {
pre_tool_use: 'PreToolUse',
post_tool_use: 'PostToolUse',
notification: 'Notification',
stop: 'Stop',
pre_compact: 'PreCompact',
post_compact: 'PostCompact',
user_prompt_submit: 'UserPromptSubmit',
subagent_stop: 'SubagentStop',
subagent_start: 'SubagentStart',
session_start: 'SessionStart',
post_tool_use_failure: 'PostToolUseFailure',
}
function stripTg(value) {
if (Array.isArray(value)) return value.map(stripTg)
if (value && typeof value === 'object') {
const out = {}
for (const [k, v] of Object.entries(value)) {
if (k.startsWith('_tg_')) continue
out[k] = stripTg(v)
}
return out
}
return value
}
${SHIM_TRY_SERVER}
${SHIM_TRY_IN_PROCESS}
${SHIM_MAX_BUFFER_CONST}
${shimFallbackTimeoutConst('codex')}
async function main() {
const eventName = process.argv[2] || ''
if (!VALID_HOOK_EVENTS.has(eventName)) {
process.stdout.write('{}')
return
}
let input = ''
try {
input = require('node:fs').readFileSync(0, 'utf8')
} catch {
process.stdout.write('{}')
return
}
// process.argv[3], when present, is the absolute path to the token-goat CLI entry
// that ran 'token-goat install --codex' (baked in by hookCommandFor in
// codex_install.ts). Try the in-process hook lib first (tryInProcess above) --
// this avoids spawning a second node process altogether. If that's unavailable,
// invoking the entry directly via process.execPath sidesteps PATH/shell resolution
// for this inner call, the same single-point-of-failure class fixed for the Copilot
// CLI bridge's inner hook call (a bare 'token-goat' on PATH failing to resolve
// crashes this call, and Codex -- like Copilot -- fails closed on a non-zero-exit
// hook). Falls back further to the old PATH-based shell:true invocation when argv[3]
// is absent (an older cached hook config). A SHIM_FALLBACK_TIMEOUT_MS timeout/killSignal on both
// spawnSync fallbacks bounds them well under Codex's own hook timeout budget, so
// token-goat degrades to its own fail-open '{}' rather than being force-killed by
// Codex first.
const entryPath = process.argv[3]
let stdout = await tryInProcess(entryPath, eventName, input)
if (stdout === undefined) {
${SHIM_SPAWN_LADDER}
: spawnSync('token-goat hook ' + eventName, {
input,
encoding: 'utf8',
shell: true,
timeout: SHIM_FALLBACK_TIMEOUT_MS,
killSignal: 'SIGKILL',
maxBuffer: SHIM_MAX_BUFFER_BYTES,
})
if (res.status !== 0 || !res.stdout) {
process.stdout.write('{}')
return
}
stdout = res.stdout
}
let parsed
try {
parsed = JSON.parse(stdout)
} catch {
process.stdout.write('{}')
return
}
parsed = stripTg(parsed)
const hso = parsed && parsed.hookSpecificOutput
if (hso && typeof hso === 'object' && !hso.hookEventName) {
hso.hookEventName = HOOK_EVENT_NAME_MAP[eventName] || eventName
}
process.stdout.write(JSON.stringify(parsed))
}
main().catch(() => {
process.stdout.write('{}')
})
`