feat(hooks): dsh-hook-protocol — shared Claude Code / Codex hook wire-protocol core

The two hook bridges (dsh-hooks-claude, dsh-hooks-codex) would otherwise duplicate
the bulk of the protocol — Codex deliberately reimplements a SUBSET of the Claude
Code protocol (same hooks.json shape, exit-code/stdout contract, command-hook
model). This library holds the genuinely-identical primitives; each bridge owns
only what differs (per-event stdin payload, env/substitution, decision mapping).

New packages/hooks/ group; hook-protocol is a LIBRARY (no plugin, registers/injects
nothing):
- matcher: matchesMatcher(pattern, query, mode) — the one dialect axis collapsed to
  a mode param (claude = literal-or-regex with pipe alternation; codex = always
  unanchored regex). Match-all on absent/''/'*'; invalid regex matches nothing.
- codec: parseHookOutput(exit, stdout, stderr) → dialect-neutral HookOutput. Exit 0
  → lenient JSON; exit 2 → blocking error (stderr = reason, surfaced as
  decision:'block'); other → non-blocking. Parses the CC superset
  (continue/stopReason/decision/hookSpecificOutput.{permissionDecision,
  additionalContext,updatedInput}/systemMessage); permissionDecision overrides the
  legacy top-level decision.
- runner: runHook(bash, hook, opts, now) — runs a command hook via ctx.bash (stdin
  payload + trusted-plugin env), honors timeoutSec, never throws (executor reject →
  non-blocking-error HookOutput). Injected clock for testable durations.
- merge: mergeHookOutputs — most-restrictive fold (deny>ask>allow, sticky stop,
  block reasons joined, context/system-messages accumulated).
- hook/* session events (declaration-merged into SessionEventMap, log-only like
  compact/*) + appendHookInvoked/appendHookResult helpers.

updatedInput is parsed but NOT honored (deferred pre-tool-input-rewrite RFC); a
bridge logs+warns. 47 unit tests at per-file 100% (matcher per-mode, codec per
exit-code/field, runner plumbing w/ stub executor, merge precedence, hook/*
helpers). RFC: implemented/feature/2026-06-30-hook-protocol-lib.md.
This commit is contained in:
Tianyi Cui
2026-07-01 00:38:06 +08:00
parent 93106b87b4
commit 65165b5d54
26 changed files with 1224 additions and 3 deletions

View File

@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest'
import { parseHookOutput } from '@deepseek-ai/dsh-hook-protocol'
describe('parseHookOutput — exit code semantics', () => {
it('exit 0 with no stdout is a neutral success', () => {
const out = parseHookOutput(0, '', '')
expect(out.exitCode).toBe(0)
expect(out.decision).toBeUndefined()
expect(out.continue).toBeUndefined()
})
it('exit 2 is a blocking error: stderr becomes the block decision + reason', () => {
const out = parseHookOutput(2, '', 'this command is not allowed')
expect(out.decision).toBe('block')
expect(out.reason).toBe('this command is not allowed')
expect(out.stderr).toBe('this command is not allowed')
})
it('exit 2 with empty stderr still blocks, with no reason', () => {
const out = parseHookOutput(2, '', ' ')
expect(out.decision).toBe('block')
expect(out.reason).toBeUndefined()
})
it('other non-zero exit is a non-blocking error (no decision, stderr recorded)', () => {
const out = parseHookOutput(1, '', 'some warning')
expect(out.decision).toBeUndefined()
expect(out.exitCode).toBe(1)
expect(out.stderr).toBe('some warning')
})
it('undefined exit (could not run) carries no decision', () => {
const out = parseHookOutput(undefined, '', 'spawn failed: ENOENT')
expect(out.exitCode).toBeUndefined()
expect(out.decision).toBeUndefined()
expect(out.stderr).toBe('spawn failed: ENOENT')
})
})
describe('parseHookOutput — structured stdout (exit 0 only)', () => {
it('parses top-level continue/stopReason/suppressOutput/systemMessage', () => {
const out = parseHookOutput(0, JSON.stringify({
continue: false, stopReason: 'budget exceeded', suppressOutput: true, systemMessage: 'heads up',
}), '')
expect(out.continue).toBe(false)
expect(out.stopReason).toBe('budget exceeded')
expect(out.suppressOutput).toBe(true)
expect(out.systemMessage).toBe('heads up')
})
it('parses legacy top-level decision + reason (approve/block)', () => {
expect(parseHookOutput(0, JSON.stringify({ decision: 'block', reason: 'nope' }), '').decision).toBe('block')
expect(parseHookOutput(0, JSON.stringify({ decision: 'approve' }), '').decision).toBe('approve')
})
it('hookSpecificOutput.permissionDecision OVERRIDES the legacy top-level decision', () => {
const out = parseHookOutput(0, JSON.stringify({
decision: 'approve',
hookSpecificOutput: { permissionDecision: 'deny', permissionDecisionReason: 'denied by policy' },
}), '')
expect(out.decision).toBe('deny')
expect(out.reason).toBe('denied by policy')
})
it('parses allow/ask permissionDecision (the bridge decides whether to honor)', () => {
expect(parseHookOutput(0, JSON.stringify({ hookSpecificOutput: { permissionDecision: 'allow' } }), '').decision).toBe('allow')
expect(parseHookOutput(0, JSON.stringify({ hookSpecificOutput: { permissionDecision: 'ask' } }), '').decision).toBe('ask')
})
it('parses additionalContext and updatedInput from hookSpecificOutput', () => {
const out = parseHookOutput(0, JSON.stringify({
hookSpecificOutput: { additionalContext: 'remember X', updatedInput: { command: 'safe' } },
}), '')
expect(out.additionalContext).toBe('remember X')
expect(out.updatedInput).toEqual({ command: 'safe' })
})
it('an unknown decision string is ignored (not coerced)', () => {
expect(parseHookOutput(0, JSON.stringify({ decision: 'maybe' }), '').decision).toBeUndefined()
})
it('malformed JSON on a clean exit is lenient (no structured output, no throw)', () => {
const out = parseHookOutput(0, '{ not valid json', '')
expect(out.decision).toBeUndefined()
expect(out.continue).toBeUndefined()
})
it('non-object stdout (plain text) on exit 0 is left for the bridge (no JSON attempt)', () => {
const out = parseHookOutput(0, 'just some text output', '')
expect(out.decision).toBeUndefined()
expect(out.continue).toBeUndefined()
})
it('a JSON array stdout parses but yields no fields (not an object)', () => {
// Starts with '{'? No — '[' — so it is not even attempted. Neutral.
const out = parseHookOutput(0, '[1,2,3]', '')
expect(out.decision).toBeUndefined()
})
it('structured stdout is IGNORED on a blocking (exit 2) run — stderr is authoritative', () => {
const out = parseHookOutput(2, JSON.stringify({ decision: 'approve' }), 'blocked')
// exit 2 forces block regardless of what stdout claims
expect(out.decision).toBe('block')
expect(out.reason).toBe('blocked')
})
})

View File

@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest'
import { Session, SessionId } from '@deepseek-ai/dsh-session'
import { appendHookInvoked, appendHookResult } from '@deepseek-ai/dsh-hook-protocol'
describe('hook/* session events', () => {
it('appendHookInvoked records a log-only hook/invoked (with matcher when present)', () => {
const session = new Session(SessionId('s'))
appendHookInvoked(session, { turn: 1, point: 'PreToolUse', dialect: 'claude', handlerId: 'h1', matcher: 'Bash' })
const ev = [...session.events].find(e => e.type === 'hook/invoked')
expect(ev?.type).toBe('hook/invoked')
if (ev?.type === 'hook/invoked') {
expect(ev.data).toMatchObject({ turn: 1, point: 'PreToolUse', dialect: 'claude', handlerId: 'h1', matcher: 'Bash' })
}
// Log-only: no surfaceOp on the event.
expect((ev as unknown as { surfaceOp?: unknown }).surfaceOp).toBeUndefined()
})
it('omits matcher when absent (match-all hook)', () => {
const session = new Session(SessionId('s'))
appendHookInvoked(session, { turn: 2, point: 'Stop', dialect: 'native', handlerId: 'h2' })
const ev = [...session.events].find(e => e.type === 'hook/invoked')
if (ev?.type === 'hook/invoked') {
expect('matcher' in ev.data).toBe(false)
}
})
it('appendHookResult records the decided outcome, omitting absent optionals', () => {
const session = new Session(SessionId('s'))
appendHookResult(session, {
turn: 1, point: 'PreToolUse', handlerId: 'h1', decision: 'deny',
exitCode: 2, stderrSummary: 'blocked', durationMs: 12,
})
const full = [...session.events].find(e => e.type === 'hook/result')
if (full?.type === 'hook/result') {
expect(full.data).toMatchObject({ turn: 1, point: 'PreToolUse', handlerId: 'h1', decision: 'deny', exitCode: 2, stderrSummary: 'blocked', durationMs: 12 })
}
// A result with no exit code / no stderr (e.g. a hook that could not run) omits both keys.
const session2 = new Session(SessionId('s2'))
appendHookResult(session2, { turn: 1, point: 'Stop', handlerId: 'h3', decision: 'allow', durationMs: 3 })
const sparse = [...session2.events].find(e => e.type === 'hook/result')
if (sparse?.type === 'hook/result') {
expect('exitCode' in sparse.data).toBe(false)
expect('stderrSummary' in sparse.data).toBe(false)
expect(sparse.data.durationMs).toBe(3)
}
})
it('an invoked/result pair correlates by handlerId', () => {
const session = new Session(SessionId('s'))
appendHookInvoked(session, { turn: 1, point: 'PreToolUse', dialect: 'claude', handlerId: 'pair-1' })
appendHookResult(session, { turn: 1, point: 'PreToolUse', handlerId: 'pair-1', decision: 'allow', exitCode: 0, durationMs: 7 })
const invoked = [...session.events].find(e => e.type === 'hook/invoked')
const result = [...session.events].find(e => e.type === 'hook/result')
expect(invoked?.type === 'hook/invoked' && invoked.data.handlerId).toBe('pair-1')
expect(result?.type === 'hook/result' && result.data.handlerId).toBe('pair-1')
})
})

View File

@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest'
import { matchesMatcher } from '@deepseek-ai/dsh-hook-protocol'
describe('matchesMatcher — match-all sentinels (both dialects)', () => {
for (const mode of ['claude', 'codex'] as const) {
it(`${mode}: absent / empty / '*' match everything`, () => {
expect(matchesMatcher(undefined, 'Bash', mode)).toBe(true)
expect(matchesMatcher('', 'anything', mode)).toBe(true)
expect(matchesMatcher('*', 'whatever', mode)).toBe(true)
})
}
})
describe('matchesMatcher — claude dialect (literal-or-regex)', () => {
it('a pure word-char pattern is a LITERAL exact match (not substring)', () => {
expect(matchesMatcher('Bash', 'Bash', 'claude')).toBe(true)
// literal exact: "Bash" must NOT match "BashOutput" (a regex would, substring)
expect(matchesMatcher('Bash', 'BashOutput', 'claude')).toBe(false)
})
it('a pipe pattern is literal ALTERNATION (exact match any alternative)', () => {
expect(matchesMatcher('Edit|Write', 'Edit', 'claude')).toBe(true)
expect(matchesMatcher('Edit|Write', 'Write', 'claude')).toBe(true)
expect(matchesMatcher('Edit|Write', 'Read', 'claude')).toBe(false)
// still exact per-alternative, not substring
expect(matchesMatcher('Edit|Write', 'EditFile', 'claude')).toBe(false)
})
it('a non-word pattern falls through to regex (unanchored)', () => {
expect(matchesMatcher('^Bash$', 'Bash', 'claude')).toBe(true)
expect(matchesMatcher('Bash.*', 'BashOutput', 'claude')).toBe(true)
expect(matchesMatcher('.*\\.ts$', 'foo.ts', 'claude')).toBe(true)
expect(matchesMatcher('.*\\.ts$', 'foo.js', 'claude')).toBe(false)
})
})
describe('matchesMatcher — codex dialect (always regex)', () => {
it('a word pattern is an unanchored regex (substring matches, unlike claude literal)', () => {
expect(matchesMatcher('Bash', 'Bash', 'codex')).toBe(true)
// codex has NO literal fast path: "Bash" is /Bash/, so it DOES match a substring
expect(matchesMatcher('Bash', 'BashOutput', 'codex')).toBe(true)
})
it('regex alternation and anchors work', () => {
expect(matchesMatcher('Edit|Write', 'Edit', 'codex')).toBe(true)
expect(matchesMatcher('^Bash$', 'Bash', 'codex')).toBe(true)
expect(matchesMatcher('^Bash$', 'BashOutput', 'codex')).toBe(false)
})
})
describe('matchesMatcher — invalid regex is a non-match (never throws)', () => {
it('an unbalanced pattern matches nothing rather than throwing', () => {
// '(' is not the claude-literal charset, so it goes to the regex path and is invalid.
expect(() => matchesMatcher('(', 'x', 'claude')).not.toThrow()
expect(matchesMatcher('(', 'x', 'claude')).toBe(false)
expect(matchesMatcher('[', 'x', 'codex')).toBe(false)
})
})

View File

@@ -0,0 +1,82 @@
import { describe, expect, it } from 'vitest'
import { mergeHookOutputs } from '@deepseek-ai/dsh-hook-protocol'
import type { HookOutput } from '@deepseek-ai/dsh-hook-protocol'
function out(over: Partial<HookOutput> = {}): HookOutput {
return { exitCode: 0, stderr: '', ...over }
}
describe('mergeHookOutputs — permission precedence deny > ask > allow', () => {
it('empty list yields a neutral outcome', () => {
const m = mergeHookOutputs([])
expect(m.decision).toBe('none')
expect(m.stop).toBe(false)
expect(m.additionalContext).toEqual([])
expect(m.systemMessages).toEqual([])
})
it('a single allow yields allow', () => {
expect(mergeHookOutputs([out({ decision: 'allow' })]).decision).toBe('allow')
expect(mergeHookOutputs([out({ decision: 'approve' })]).decision).toBe('allow')
})
it('deny beats ask beats allow regardless of order', () => {
expect(mergeHookOutputs([out({ decision: 'allow' }), out({ decision: 'ask' })]).decision).toBe('ask')
expect(mergeHookOutputs([out({ decision: 'ask' }), out({ decision: 'deny' })]).decision).toBe('deny')
expect(mergeHookOutputs([out({ decision: 'deny' }), out({ decision: 'allow' })]).decision).toBe('deny')
// block folds to deny
expect(mergeHookOutputs([out({ decision: 'allow' }), out({ decision: 'block' })]).decision).toBe('deny')
})
it('no decision anywhere yields none', () => {
expect(mergeHookOutputs([out(), out()]).decision).toBe('none')
})
})
describe('mergeHookOutputs — reasons, stop, context, systemMessages accumulate', () => {
it('joins block/deny reasons with a blank line (only from blocking hooks)', () => {
const m = mergeHookOutputs([
out({ decision: 'deny', reason: 'first objection' }),
out({ decision: 'allow', reason: 'this allow reason is NOT collected' }),
out({ decision: 'block', reason: 'second objection' }),
])
expect(m.reason).toBe('first objection\n\nsecond objection')
})
it('no reason when nothing blocked', () => {
expect(mergeHookOutputs([out({ decision: 'allow' })]).reason).toBeUndefined()
})
it('stop is sticky on the first continue:false, capturing its stopReason', () => {
const m = mergeHookOutputs([
out({ continue: true }),
out({ continue: false, stopReason: 'halt now' }),
out({ continue: false, stopReason: 'second halt — ignored' }),
])
expect(m.stop).toBe(true)
expect(m.stopReason).toBe('halt now')
})
it('no stop when every hook continues', () => {
const m = mergeHookOutputs([out({ continue: true }), out()])
expect(m.stop).toBe(false)
expect(m.stopReason).toBeUndefined()
})
it('a continue:false with no stopReason stops with an undefined reason', () => {
const m = mergeHookOutputs([out({ continue: false })])
expect(m.stop).toBe(true)
expect(m.stopReason).toBeUndefined()
})
it('collects additionalContext and systemMessages in hook order, skipping empties', () => {
const m = mergeHookOutputs([
out({ additionalContext: 'ctx-A', systemMessage: 'warn-A' }),
out({ additionalContext: '', systemMessage: '' }), // empties skipped
out({ additionalContext: 'ctx-B' }),
out({ systemMessage: 'warn-B' }),
])
expect(m.additionalContext).toEqual(['ctx-A', 'ctx-B'])
expect(m.systemMessages).toEqual(['warn-A', 'warn-B'])
})
})

View File

@@ -0,0 +1,134 @@
import { describe, expect, it } from 'vitest'
import type { BashExecRequest, BashExecSpec, BashExecutor, BashRunResult } from '@deepseek-ai/dsh-bash'
import { runHook } from '@deepseek-ai/dsh-hook-protocol'
/**
* A minimal stand-in for the bits of {@link BashExecutor} that {@link runHook}
* actually calls (`resolve` then `run`). `runHook` is pure plumbing over those
* two methods, so a duck-typed recorder is the right test seam — the REAL
* executor (dsh-bash-local) is exercised end-to-end by the bridge e2e tests in
* PR-F, not here.
*/
function recordingBash(run: (spec: BashExecSpec) => Promise<BashRunResult>): {
bash: BashExecutor
specs: BashExecSpec[]
} {
const specs: BashExecSpec[] = []
const bash = {
resolve(request: BashExecRequest): BashExecSpec {
// Carry the request through verbatim, defaulting the required spec fields —
// exactly what dsh-bash-local's resolve does for the fields runHook sets.
return {
command: request.command,
workdir: request.workdir ?? '/stub',
timeoutMs: request.timeoutMs ?? 0,
...request.signal ? { signal: request.signal } : {},
...request.stdin !== undefined ? { stdin: request.stdin } : {},
...request.env !== undefined ? { env: request.env } : {},
owner: request.owner,
}
},
async run(spec: BashExecSpec): Promise<BashRunResult> {
specs.push(spec)
return run(spec)
},
} as unknown as BashExecutor
return { bash, specs }
}
function result(over: Partial<BashRunResult> = {}): BashRunResult {
return {
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
timeoutMs: 1000,
stdout: { text: '', truncated: false },
stderr: { text: '', truncated: false },
...over,
}
}
const clock = () => { let t = 0; return () => (t += 5) } // +5ms per call → duration 5
describe('runHook — payload + env + stdin plumbing', () => {
it('serializes the payload to stdin (with trailing newline when requested)', async () => {
const { bash, specs } = recordingBash(async () => result({ stdout: { text: '', truncated: false } }))
await runHook(bash, { command: 'my-hook.sh' }, {
payload: { hook_event_name: 'PreToolUse', tool_name: 'Bash' },
defaultTimeoutMs: 60000,
trailingNewline: true,
}, clock())
expect(specs[0]!.stdin).toBe(JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Bash' }) + '\n')
expect(specs[0]!.command).toBe('my-hook.sh')
})
it('omits the trailing newline when trailingNewline is false (Codex)', async () => {
const { bash, specs } = recordingBash(async () => result())
await runHook(bash, { command: 'h' }, { payload: { a: 1 }, defaultTimeoutMs: 1000, trailingNewline: false }, clock())
expect(specs[0]!.stdin).toBe('{"a":1}')
})
it('threads env and cwd into the request', async () => {
const { bash, specs } = recordingBash(async () => result())
await runHook(bash, { command: 'h' }, {
payload: {}, env: { CLAUDE_PROJECT_DIR: '/proj' }, cwd: '/work',
defaultTimeoutMs: 1000, trailingNewline: true,
}, clock())
expect(specs[0]!.env).toEqual({ CLAUDE_PROJECT_DIR: '/proj' })
expect(specs[0]!.workdir).toBe('/work')
})
it('a per-hook timeoutSec (seconds) overrides the default (ms)', async () => {
const { bash, specs } = recordingBash(async () => result())
await runHook(bash, { command: 'h', timeoutSec: 3 }, { payload: {}, defaultTimeoutMs: 60000, trailingNewline: true }, clock())
expect(specs[0]!.timeoutMs).toBe(3000)
})
it('falls back to the default timeout when the hook sets none', async () => {
const { bash, specs } = recordingBash(async () => result())
await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 60000, trailingNewline: true }, clock())
expect(specs[0]!.timeoutMs).toBe(60000)
})
it('passes the abort signal through', async () => {
const controller = new AbortController()
const { bash, specs } = recordingBash(async () => result())
await runHook(bash, { command: 'h' }, { payload: {}, signal: controller.signal, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
expect(specs[0]!.signal).toBe(controller.signal)
})
})
describe('runHook — outcome decoding + duration', () => {
it('decodes a clean exit with structured stdout and reports a duration', async () => {
const { bash } = recordingBash(async () => result({
exitCode: 0, stdout: { text: JSON.stringify({ decision: 'block', reason: 'no' }), truncated: false },
}))
const { output, durationMs } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
expect(output.decision).toBe('block')
expect(output.reason).toBe('no')
expect(durationMs).toBe(5)
})
it('a signal death (exitCode null) decodes as undefined exit (non-blocking error)', async () => {
const { bash } = recordingBash(async () => result({ exitCode: null, signal: 'SIGKILL', stderr: { text: 'killed', truncated: false } }))
const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
expect(output.exitCode).toBeUndefined()
expect(output.decision).toBeUndefined()
expect(output.stderr).toBe('killed')
})
it('an executor rejection (infra fault) becomes a non-blocking error, never throws', async () => {
const { bash } = recordingBash(async () => { throw new Error('bad workdir: ENOENT') })
const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
expect(output.exitCode).toBeUndefined()
expect(output.stderr).toBe('bad workdir: ENOENT')
expect(output.decision).toBeUndefined()
})
it('a non-Error rejection is stringified onto stderr', async () => {
const { bash } = recordingBash(async () => { throw 'plain string fault' })
const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
expect(output.stderr).toBe('plain string fault')
})
})