feat(hooks): dsh-hooks-claude + dsh-hooks-codex bridges (hooks stack PR-F)

The two bridge plugins that run a user's existing Claude Code / Codex hook
config on the harness's typed interception seams, built on the shared
dsh-hook-protocol library. A bridge is a faithfulness adapter, not a power
tool: anything it does a native cordis plugin does more powerfully — the
bridge exists only to run UNMODIFIED external hooks.

- dsh-hooks-claude: CC dialect. Seven hook points (SessionStart,
  UserPromptSubmit, PreToolUse, PostToolUse, Stop, SubagentStart,
  SubagentStop), CC per-event stdin payloads, env + ${CLAUDE_PLUGIN_ROOT}/
  ${CLAUDE_PROJECT_DIR} substitution, literal-or-regex matcher.
- dsh-hooks-codex: Codex dialect — a deliberate subset. Five hook points,
  always-regex matcher, snake_case payloads (turn_id/model, no trailing
  newline), no env/substitution, block-only decisions.

Both map the neutral merged outcome onto the seam's typed Decision and stamp
an explicit {kind:'plugin'} source on injected context (so it is never
mislabeled as a user prompt). Config parse-failure is contained; only command
hooks run. updatedInput is logged+warned (input rewrite deferred); the Stop
loop-guard is deferred (TODO).

Tests: per-file 100% — config-parse unit branches + per-seam mappings
end-to-end through the REAL loop + REAL bash + REAL shell scripts (scripted
mock model only) + a real-Loader export-shape guard. A keyless ACP snapshot
scenario (hook-prompt-block) proves a UserPromptSubmit hook blocks a prompt
end-to-end (rejected turn -> ACP cancelled, hook/* events in the log); a
with-key e2e (hooks.e2e.ts) proves a PreToolUse hook blocks real bash
(verified on disk). The snapshot normalizer now scrubs hook/result.durationMs.

RFC: docs/rfc/implemented/feature/2026-06-30-hook-bridges.md
This commit is contained in:
Tianyi Cui
2026-07-01 04:22:00 +08:00
parent c28d6b837b
commit 8adcbceeed
35 changed files with 2714 additions and 7 deletions
+100
View File
@@ -0,0 +1,100 @@
/**
* Parse a Claude Code hook config file into the shared {@link MatcherGroup}
* shape, faithfully to CC's `hooks.json` / settings `hooks` key format.
*
* A CC config maps each event name to an array of matcher groups, each holding
* an array of typed hooks. Only `type: 'command'` hooks run here; other types
* (`prompt`/`agent`/`http`) are PARSED but skipped with a warning (faithful-but-
* degraded — the same stance Codex takes). The `command` string undergoes
* `${CLAUDE_PLUGIN_ROOT}` substitution at parse time so the runner sees a literal.
*
* @module @deepseek-ai/dsh-hooks-claude/config
*/
import type { MatcherGroup } from '@deepseek-ai/dsh-hook-protocol'
/** A parsed CC config: event name → its matcher groups (command hooks only). */
export type ClaudeHookConfig = Record<string, MatcherGroup[]>
/** A skipped non-command hook, surfaced so the bridge can warn about it. */
export interface SkippedHook {
event: string
type: string
}
/** The outcome of parsing one config file: the runnable groups + what was skipped. */
export interface ParsedClaudeConfig {
config: ClaudeHookConfig
skipped: SkippedHook[]
}
/** Substitution variables applied to each `command` string at parse time. */
export interface SubstitutionVars {
/** Replaces `${CLAUDE_PLUGIN_ROOT}` — the plugin's root dir. */
pluginRoot?: string
/** Replaces `${CLAUDE_PROJECT_DIR}` — the project root. */
projectDir?: string
}
/** A plain (non-null, non-array) object, else undefined. */
function asObject(value: unknown): Record<string, unknown> | undefined {
return typeof value === 'object' && value !== null && !Array.isArray(value)
? value as Record<string, unknown>
: undefined
}
/** Apply `${CLAUDE_PLUGIN_ROOT}` / `${CLAUDE_PROJECT_DIR}` substitution to a command string. */
export function substituteCommand(command: string, vars: SubstitutionVars): string {
let out = command
if (vars.pluginRoot !== undefined) out = out.split('${CLAUDE_PLUGIN_ROOT}').join(vars.pluginRoot)
if (vars.projectDir !== undefined) out = out.split('${CLAUDE_PROJECT_DIR}').join(vars.projectDir)
return out
}
/**
* Parse a raw Claude Code config object (the value under the `hooks` key, or a
* `hooks.json` whose top level IS that map) into runnable {@link MatcherGroup}s.
* Non-command hooks and malformed entries are dropped (recorded in `skipped` /
* silently ignored) rather than throwing — a bad hook config must not crash boot.
* `vars` are substituted into every surviving `command`.
*/
export function parseClaudeConfig(raw: unknown, vars: SubstitutionVars = {}): ParsedClaudeConfig {
const config: ClaudeHookConfig = {}
const skipped: SkippedHook[] = []
// Accept either `{ hooks: { … } }` (a settings file) or the bare event map.
const root = asObject(raw)
const hooksMap = root ? asObject(root.hooks) ?? root : undefined
if (!hooksMap) return { config, skipped }
for (const [event, rawGroups] of Object.entries(hooksMap)) {
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, type })
continue
}
if (typeof hook.command !== 'string') continue
commands.push({
command: substituteCommand(hook.command, vars),
...typeof hook.timeout === 'number' ? { timeoutSec: hook.timeout } : {},
})
}
if (commands.length === 0) continue
groups.push({
...typeof group.matcher === 'string' ? { matcher: group.matcher } : {},
hooks: commands,
})
}
if (groups.length > 0) config[event] = groups
}
return { config, skipped }
}
+300
View File
@@ -0,0 +1,300 @@
/**
* `dsh-hooks-claude` — a bridge plugin that runs a user's existing Claude Code
* hook config (`hooks.json` / a settings file's `hooks` key) on the harness's
* canonical interception seams. It is the CC DIALECT half of the hooks
* subsystem: it owns CC's per-event stdin payloads, CC's env +
* `${CLAUDE_PLUGIN_ROOT}` substitution, and the mapping from a hook's neutral
* outcome onto the harness's typed Decisions. The dialect-agnostic primitives
* (matcher, exit-code/stdout codec, `ctx.bash` execution, most-restrictive
* merge, the `hook/*` events) come from `@deepseek-ai/dsh-hook-protocol`.
*
* A native cordis plugin could do everything this bridge does — more powerfully,
* with typed returns and no serialization boundary. The bridge exists only to
* run UNMODIFIED external CC hooks faithfully; anything bespoke should be a
* native plugin on the same seams.
*
* Scope: the seven in-scope hook points (`SessionStart`, `UserPromptSubmit`,
* `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`, `SubagentStop`). Only
* `type: 'command'` hooks run; the matcher group config + exit-code/stdout
* protocol are byte-faithful to CC. `updatedInput` (tool-input rewrite) is
* logged + warned, not honored (deferred — see the interception-seams RFC).
*
* @module @deepseek-ai/dsh-hooks-claude
*/
import { readFileSync } from 'node:fs'
import type { Context } from 'cordis'
import z from 'schemastery'
import type { Agent, ContinuationDecision, HookContext, PromptDecision } from '@deepseek-ai/dsh-agent'
import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
import type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
import {
appendHookInvoked,
appendHookResult,
matchesMatcher,
mergeHookOutputs,
runHook,
type HookOutput,
type MatcherGroup,
type MergedHookOutcome,
} from '@deepseek-ai/dsh-hook-protocol'
// Side-effect type import: pulls in the `subagent/start` + `subagent/end` event
// declarations (declaration-merged into cordis `Events` by dsh-subagent) so the
// SubagentStart/SubagentStop listeners below type-check.
import type {} from '@deepseek-ai/dsh-subagent'
import { parseClaudeConfig, type ClaudeHookConfig } from './config.ts'
export const name = 'hooks-claude'
// `bash` is required to run hooks; the rest are read opportunistically via
// ctx.get so a deployment can load this bridge without every seam present.
export const inject = ['bash']
/** Plugin config: where the CC hook config lives + substitution roots. */
export interface Config {
/** Path to a `hooks.json` or a settings file whose `hooks` key holds the config. */
configPath: string
/** Replaces `${CLAUDE_PLUGIN_ROOT}` in command strings (the plugin's root dir). */
pluginRoot?: string
/** Replaces `${CLAUDE_PROJECT_DIR}` in command strings + set as the hook env var. */
projectDir?: string
/** Default per-hook timeout in ms when a hook sets none (CC default: 600000). */
defaultTimeoutMs?: number
}
export const Config: z<Config> = z.object({
configPath: z.string().required(),
pluginRoot: z.string(),
projectDir: z.string(),
defaultTimeoutMs: z.number().default(600_000),
})
/** A stable per-handler id so an invoked/result pair correlates in the log. */
let handlerCounter = 0
function nextHandlerId(point: string): string {
return `claude:${point}:${++handlerCounter}`
}
/** The `{kind:'plugin'}` source stamped on every context this bridge injects. */
const PLUGIN_SOURCE: MessageSource = { kind: 'plugin', plugin: 'hooks-claude' }
/** Truncate a stderr blob for the `hook/result` summary field. */
function summarize(stderr: string): string | undefined {
const t = stderr.trim()
if (t.length === 0) return undefined
return t.length > 500 ? t.slice(0, 500) + '…' : t
}
export function apply(ctx: Context, config: Config): void {
// --- Parse the config ONCE at load. A read/parse failure is contained: the
// bridge logs and registers nothing rather than crashing boot (a typo'd path
// must not take the agent down). ---
let parsed: ClaudeHookConfig = {}
try {
const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
const result = parseClaudeConfig(raw, {
...config.pluginRoot !== undefined ? { pluginRoot: config.pluginRoot } : {},
...config.projectDir !== undefined ? { projectDir: config.projectDir } : {},
})
parsed = result.config
for (const s of result.skipped) {
ctx.logger.warn(`hooks-claude: skipping unsupported "${s.type}" hook on ${s.event} (only command hooks run)`)
}
} catch (error: unknown) {
ctx.logger.warn(`hooks-claude: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
return
}
const defaultTimeoutMs = config.defaultTimeoutMs ?? 600_000
const hookEnv = config.projectDir !== undefined ? { CLAUDE_PROJECT_DIR: config.projectDir } : undefined
/**
* Run every command hook configured for `point` whose matcher selects
* `matchQuery`, with the per-event `payload` on stdin, and fold the results.
* Writes a `hook/invoked`/`hook/result` pair per hook into the session when one
* is available (the mid-turn points always have an open turn). Returns the
* merged outcome (a neutral, already-most-restrictive view) for the caller to
* map onto its seam decision. `matchQuery` is the event's matcher subject
* (tool name, session source, …); `''` for events that ignore matchers.
*/
async function runPoint(
point: string,
matchQuery: string,
payload: unknown,
opts: { agent?: Agent; turn?: number; signal?: AbortSignal },
): Promise<MergedHookOutcome> {
const groups: MatcherGroup[] = parsed[point] ?? []
const outputs: HookOutput[] = []
for (const group of groups) {
if (!matchesMatcher(group.matcher, matchQuery, 'claude')) continue
for (const hook of group.hooks) {
const handlerId = nextHandlerId(point)
const session = opts.agent?.session
if (session && opts.turn !== undefined) {
appendHookInvoked(session, {
turn: opts.turn, point, dialect: 'claude', handlerId,
...group.matcher !== undefined ? { matcher: group.matcher } : {},
})
}
const { output, durationMs } = await runHook(ctx.bash, hook, {
payload,
...hookEnv ? { env: hookEnv } : {},
...opts.signal ? { signal: opts.signal } : {},
defaultTimeoutMs,
trailingNewline: true,
}, () => performance.now())
outputs.push(output)
if (output.updatedInput !== undefined) {
ctx.logger.warn(`hooks-claude: ${point} hook requested updatedInput, which is not yet honored (ignored)`)
}
if (session && opts.turn !== undefined) {
const stderrSummary = summarize(output.stderr)
appendHookResult(session, {
turn: opts.turn, point, handlerId,
decision: output.decision ?? (output.continue === false ? 'stop' : 'pass'),
...output.exitCode !== undefined ? { exitCode: output.exitCode } : {},
...stderrSummary !== undefined ? { stderrSummary } : {},
durationMs,
})
}
}
}
return mergeHookOutputs(outputs)
}
/** Build a HookContext from accumulated additionalContext strings, or undefined when none. */
function contextFrom(merged: MergedHookOutcome): HookContext | undefined {
if (merged.additionalContext.length === 0) return undefined
const content: ContentBlock[] = merged.additionalContext.map(text => ({ type: 'text', text }))
return { content, source: PLUGIN_SOURCE }
}
// --- SessionStart: emit (cannot block). Inject any additionalContext into the
// agent so the first request sees it. The matcher subject is the source. ---
ctx.on('agent/session-start', (agent, source) => {
void runPoint('SessionStart', source, sessionStartPayload(agent, source), { agent })
.then((merged) => {
const context = contextFrom(merged)
if (context) agent.inject(context.content, { source: context.source })
})
.catch((error: unknown) => {
ctx.logger.warn(`hooks-claude: SessionStart hook failed: ${String(error)}`)
})
})
// --- UserPromptSubmit → PromptDecision. The prompt text is the payload; no
// matcher subject (CC ignores matchers for this event). ---
ctx.on('agent/prompt-submit', async (agent, content, _source, next): Promise<PromptDecision> => {
const turn = lastTurn(agent)
const merged = await runPoint('UserPromptSubmit', '', promptPayload(agent, content), { agent, turn })
if (merged.decision === 'deny') {
return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' }
}
const context = contextFrom(merged)
if (context) return { kind: 'allow', additionalContext: context }
return next()
})
// --- PreToolUse → PreToolDecision. Matcher subject is the tool name. ---
ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
const turn = lastTurn(exec.agent)
const merged = await runPoint('PreToolUse', exec.name, preToolPayload(exec), { ...exec.agent ? { agent: exec.agent } : {}, turn, ...exec.signal ? { signal: exec.signal } : {} })
if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' }
if (merged.decision === 'ask') return { kind: 'ask', ...merged.reason !== undefined ? { reason: merged.reason } : {} }
return next()
})
// --- PostToolUse → PostToolDecision. Matcher subject is the tool name. ---
ctx.on('tools/post-execute', async (exec, result, next): Promise<PostToolDecision> => {
const turn = lastTurn(exec.agent)
const merged = await runPoint('PostToolUse', exec.name, postToolPayload(exec, result), { ...exec.agent ? { agent: exec.agent } : {}, turn, ...exec.signal ? { signal: exec.signal } : {} })
const context = contextFrom(merged)
if (merged.decision === 'deny') {
return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContext: context } : {} }
}
if (context) return { kind: 'accept', additionalContext: context }
return next()
})
// --- Stop → ContinuationDecision. CC's Stop hook can force the conversation to
// CONTINUE (block the stop) with stderr/reason as the continuation. No matcher.
// TODO(stop-loop-guard): CC breaks an infinite force-continue with
// `stop_hook_active` (set true once a Stop hook has already fired this run) plus
// a max-consecutive cap; both are deferred. Today `stop_hook_active` is always
// false, so a Stop hook that unconditionally blocks would force-continue every
// step — a hook author must self-limit until the guard lands. ---
ctx.on('agent/turn-continuation', async (agent, turn, _default, next): Promise<ContinuationDecision> => {
const merged = await runPoint('Stop', '', stopPayload(agent), { agent, turn })
if (merged.decision === 'deny' && merged.reason !== undefined) {
// A blocking Stop hook forces continuation, feeding its reason as next-step steering.
return { action: 'continue', reason: { content: [{ type: 'text', text: merged.reason }], source: PLUGIN_SOURCE } }
}
return next()
})
// --- SubagentStart / SubagentStop: observe-only emits (the subagent seam is
// observe-only this cut). A SubagentStart hook's additionalContext is injected
// into the live child; SubagentStop only observes. No matcher subject. ---
ctx.on('subagent/start', (info) => {
const child = ctx.get('agents')?.get(info.id)
void runPoint('SubagentStart', info.agentType ?? '', subagentStartPayload(info), { ...child ? { agent: child } : {} })
.then((merged) => {
const context = contextFrom(merged)
if (context && child) child.inject(context.content, { source: context.source })
})
.catch((error: unknown) => { ctx.logger.warn(`hooks-claude: SubagentStart hook failed: ${String(error)}`) })
})
ctx.on('subagent/end', (info) => {
// No `.then`/inject here (SubagentStop only observes) and no session is
// passed, so runPoint cannot reject — no `.catch` is needed (one would be
// dead code). The observe-only run is fire-and-forget.
void runPoint('SubagentStop', info.agentType ?? '', subagentStopPayload(info), {})
})
}
// --- Per-event stdin payloads (the CC DIALECT shape). Field names match CC's
// hook input schema; this is the part a bridge owns. ---
/** The last (open or just-closed) turn number in the agent's log, or 0. */
function lastTurn(agent: Agent | undefined): number {
if (!agent) return 0
const last = [...agent.session.events].findLast(e => e.type === 'turn/start')
/* v8 ignore next -- the `: 0` arm is a defensive fallback: lastTurn is only
called from the mid-turn seams (prompt-submit/pre-/post-execute/continuation),
which always run inside an open turn, so `last` is always a turn/start here. */
return last?.type === 'turn/start' ? last.data.turn : 0
}
/** Flatten content blocks to the text a hook payload carries (the common case). */
function blocksToText(content: ContentBlock[]): string {
return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
}
function base(agent: Agent | undefined, event: string): Record<string, unknown> {
return {
session_id: agent?.session.header.id ?? '',
cwd: agent?.session.header.cwd ?? process.cwd(),
hook_event_name: event,
}
}
function sessionStartPayload(agent: Agent, source: string): Record<string, unknown> {
return { ...base(agent, 'SessionStart'), source }
}
function promptPayload(agent: Agent, content: ContentBlock[]): Record<string, unknown> {
return { ...base(agent, 'UserPromptSubmit'), prompt: blocksToText(content) }
}
function preToolPayload(exec: ToolExecution): Record<string, unknown> {
return { ...base(exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId }
}
function postToolPayload(exec: ToolExecution, result: ToolExecutionResult): Record<string, unknown> {
return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) }
}
function stopPayload(agent: Agent): Record<string, unknown> {
return { ...base(agent, 'Stop'), stop_hook_active: false }
}
function subagentStartPayload(info: { id: string; agentType?: string }): Record<string, unknown> {
return { hook_event_name: 'SubagentStart', agent_id: info.id, ...info.agentType !== undefined ? { agent_type: info.agentType } : {} }
}
function subagentStopPayload(info: { id: string; agentType?: string }): Record<string, unknown> {
return { hook_event_name: 'SubagentStop', agent_id: info.id, stop_hook_active: false, ...info.agentType !== undefined ? { agent_type: info.agentType } : {} }
}