fix(hooks): remove speculative regex runtime

This commit is contained in:
Tianyi Cui
2026-07-29 23:14:31 +08:00
parent cfe77b3a35
commit 99daef69ef
31 changed files with 174 additions and 633 deletions
+36 -52
View File
@@ -5,11 +5,7 @@
* @module @deepseek-ai/dsh-hooks-codex/config
*/
import {
compileMatchers,
type CompiledMatchers,
type MatcherGroup,
} from '@deepseek-ai/dsh-hook-protocol'
import { matcherDiagnostic, type MatcherGroup } from '@deepseek-ai/dsh-hook-protocol'
/** The five Codex hook points this bridge supports. */
export const CODEX_EVENTS = ['PreToolUse', 'PostToolUse', 'SessionStart', 'UserPromptSubmit', 'Stop'] as const
@@ -27,8 +23,6 @@ export interface SkippedHook {
export interface ParsedCodexConfig {
config: CodexHookConfig
skipped: SkippedHook[]
/** Config-scoped matcher registry; the caller owns and must dispose it. */
matchers: CompiledMatchers
}
function asObject(value: unknown): Record<string, unknown> | undefined {
@@ -42,8 +36,7 @@ function asObject(value: unknown): Record<string, unknown> | undefined {
* than failing boot; unsupported or asynchronous hooks are returned in `skipped`. Matcher fields on
* UserPromptSubmit and Stop are discarded because those events have no matcher subject. A
* matcher-bearing runnable group with an invalid regex throws a `SyntaxError`, allowing the bridge
* to reject the complete config before listener registration. Validation and runtime matching
* share the returned compiled registry; its caller must dispose it.
* to reject the complete config before listener registration.
* @param raw - the parsed JSON config: a `{ hooks: … }` wrapper or the bare event map.
* @returns the runnable per-event groups plus the skipped hooks with their reasons.
*/
@@ -52,51 +45,42 @@ export function parseCodexConfig(raw: unknown): ParsedCodexConfig {
const skipped: SkippedHook[] = []
const root = asObject(raw)
const hooksMap = root ? asObject(root.hooks) ?? root : undefined
if (hooksMap) {
for (const event of CODEX_EVENTS) {
const rawGroups = hooksMap[event]
// Matcher-group parsing remains dialect-local because the supported hook
// shapes and skip reasons differ from Claude Code's.
/* jscpd:ignore-start */
if (!Array.isArray(rawGroups)) continue
const groups: MatcherGroup[] = []
for (const rawGroup of rawGroups) {
const group = asObject(rawGroup)
if (!group || !Array.isArray(group.hooks)) continue
const commands: MatcherGroup['hooks'] = []
for (const rawHook of group.hooks) {
const hook = asObject(rawHook)
if (!hook) continue
const type = typeof hook.type === 'string' ? hook.type : 'command'
if (type !== 'command') { skipped.push({ event, reason: `unsupported "${type}" hook` }); continue }
/* jscpd:ignore-end */
if (hook.async === true) { skipped.push({ event, reason: 'async hook' }); continue }
if (typeof hook.command !== 'string') continue
// Codex accepts `timeout` or the `timeoutSec` alias.
const timeout = typeof hook.timeout === 'number' ? hook.timeout
: typeof hook.timeoutSec === 'number' ? hook.timeoutSec : undefined
commands.push({ command: hook.command, ...timeout !== undefined ? { timeoutSec: timeout } : {} })
}
if (commands.length === 0) continue
const matcher = event === 'UserPromptSubmit' || event === 'Stop'
? undefined
: typeof group.matcher === 'string' ? group.matcher : undefined
groups.push({ ...matcher !== undefined ? { matcher } : {}, hooks: commands })
if (!hooksMap) return { config, skipped }
for (const event of CODEX_EVENTS) {
const rawGroups = hooksMap[event]
// Matcher-group parsing remains dialect-local because the supported hook
// shapes and skip reasons differ from Claude Code's.
/* jscpd:ignore-start */
if (!Array.isArray(rawGroups)) continue
const groups: MatcherGroup[] = []
for (const rawGroup of rawGroups) {
const group = asObject(rawGroup)
if (!group || !Array.isArray(group.hooks)) continue
const commands: MatcherGroup['hooks'] = []
for (const rawHook of group.hooks) {
const hook = asObject(rawHook)
if (!hook) continue
const type = typeof hook.type === 'string' ? hook.type : 'command'
if (type !== 'command') { skipped.push({ event, reason: `unsupported "${type}" hook` }); continue }
/* jscpd:ignore-end */
if (hook.async === true) { skipped.push({ event, reason: 'async hook' }); continue }
if (typeof hook.command !== 'string') continue
// Codex accepts `timeout` or the `timeoutSec` alias.
const timeout = typeof hook.timeout === 'number' ? hook.timeout
: typeof hook.timeoutSec === 'number' ? hook.timeoutSec : undefined
commands.push({ command: hook.command, ...timeout !== undefined ? { timeoutSec: timeout } : {} })
}
if (groups.length > 0) config[event] = groups
if (commands.length === 0) continue
const matcher = event === 'UserPromptSubmit' || event === 'Stop'
? undefined
: typeof group.matcher === 'string' ? group.matcher : undefined
const diagnostic = matcherDiagnostic(matcher, 'codex')
if (diagnostic !== undefined) throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`)
groups.push({ ...matcher !== undefined ? { matcher } : {}, hooks: commands })
}
if (groups.length > 0) config[event] = groups
}
const entries = Object.entries(config).flatMap(([event, groups]) => (
groups.map(group => ({ event, matcher: group.matcher }))
))
const matchers = compileMatchers(new Set(entries.map(entry => entry.matcher)), 'codex')
for (const { event, matcher } of entries) {
const diagnostic = matchers.diagnostic(matcher)
if (diagnostic === undefined) continue
matchers.dispose()
throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`)
}
return { config, skipped, matchers }
return { config, skipped }
}
+16 -30
View File
@@ -1,10 +1,9 @@
/**
* Bridge for unmodified Codex command hooks on harness interception seams. It
* supports five points (SessionStart, prompt/tool pre/post, Stop), native
* literal-or-Rust-regex matchers, snake_case payloads without a trailing
* newline, no hook environment or command substitution, and no pre-tool
* approval or rewrite path; only blocking decisions are honored. Shared
* execution and parsing live in
* supports five points (SessionStart, prompt/tool pre/post, Stop), regex-only
* matchers, snake_case payloads without a trailing newline, no hook environment
* or command substitution, and no pre-tool approval or rewrite path; only
* blocking decisions are honored. Shared execution and parsing live in
* `dsh-hook-protocol`; see the
* [hook-bridges Agent Note](../../../../.agents/notes/implemented/feature/2026-06-30-hook-bridges.md).
* @module @deepseek-ai/dsh-hooks-codex
@@ -28,13 +27,14 @@ import {
createDetachedRuns,
DEFAULT_HOOK_TIMEOUT_MS,
DEFAULT_STDERR_SUMMARY_MAX_CHARS,
matchesMatcher,
mergeHookOutputs,
runHook,
type HookOutput,
type MatcherGroup,
type MergedHookOutcome,
} from '@deepseek-ai/dsh-hook-protocol'
import { parseCodexConfig, type ParsedCodexConfig } from './config.ts'
import { parseCodexConfig, type CodexHookConfig } from './config.ts'
/* jscpd:ignore-end */
export const name = 'hooks-codex'
@@ -83,37 +83,26 @@ export function apply(ctx: Context, config: Config): void {
const stderrSummaryMaxChars = config.stderrSummaryMaxChars ?? DEFAULT_STDERR_SUMMARY_MAX_CHARS
assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
let result: ParsedCodexConfig
let parsed: CodexHookConfig = {}
try {
const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
result = parseCodexConfig(raw)
const result = parseCodexConfig(raw)
parsed = result.config
for (const s of result.skipped) {
ctx.logger.warn(`hooks-codex: skipping ${s.reason} on ${s.event} (only sync command hooks run)`)
}
} catch (error: unknown) {
ctx.logger.warn(`hooks-codex: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
return
}
const parsed = result.config
const model = config.model ?? ''
// Parsing validates through this same registry, so no native regex is rebuilt
// between config admission and runtime matching.
const matchers = result.matchers
// SessionStart is the one emit-shaped (detached) point Codex has: track its
// run chains so disposal aborts a still-running hook process and drains the
// continuation before releasing matchers (docs/defensive-patterns.md:
// dispose must reach quiescence).
// continuation (docs/defensive-patterns.md: dispose must reach quiescence).
const detached = createDetachedRuns()
ctx.effect(() => async () => {
try {
await detached.drain()
} finally {
matchers.dispose()
}
}, 'hooks-codex: drain detached hook runs and dispose matchers')
for (const s of result.skipped) {
ctx.logger.warn(`hooks-codex: skipping ${s.reason} on ${s.event} (only sync command hooks run)`)
}
ctx.effect(() => () => detached.drain(), 'hooks-codex: drain detached hook runs')
/**
* Run and fold one configured Codex hook point.
@@ -137,11 +126,9 @@ export function apply(ctx: Context, config: Config): void {
// Run hooks in the agent's session workspace so relative paths address the
// user's project rather than the server launch directory.
const workdir = opts.agent?.session.header.cwd
// Keep each dialect's audit stamping readable beside its payload mapping.
/* jscpd:ignore-start */
for (const group of groups) {
// The protocol library owns Codex's exact-literal/Rust-regex split.
if (!matchers.matches(group.matcher, matchQuery)) continue
// Codex always interprets matchers as regexes; it has no literal fast path.
if (!matchesMatcher(group.matcher, matchQuery, 'codex')) continue
for (const hook of group.hooks) {
const handlerId = nextHandlerId(point)
const session = opts.agent?.session
@@ -151,7 +138,6 @@ export function apply(ctx: Context, config: Config): void {
...group.matcher !== undefined ? { matcher: group.matcher } : {},
})
}
/* jscpd:ignore-end */
const { output, durationMs } = await runHook(ctx.bash, hook, {
payload,
defaultTimeoutMs,