docs: trim generated prose
This commit is contained in:
@@ -1,20 +1,6 @@
|
||||
/**
|
||||
* Parse a finished hook command's process outcome (exit code + stdout + stderr)
|
||||
* into the dialect-neutral {@link HookOutput} both bridges map from.
|
||||
*
|
||||
* The exit-code contract is shared by Claude Code and Codex:
|
||||
* - exit 0 → success; if stdout is structured JSON, parse it; else the plain
|
||||
* stdout is available to the bridge (some events treat it as `additionalContext`).
|
||||
* - exit 2 → BLOCKING error; stderr is the block reason fed back to the model.
|
||||
* We surface this as `decision: 'block'` with `reason = stderr` so a bridge
|
||||
* needs no separate exit-code branch — the neutral output already says "block".
|
||||
* - other → non-blocking error; recorded (exitCode + stderr) but no decision.
|
||||
*
|
||||
* Structured-stdout fields are a SUPERSET across dialects (CC is richest); we
|
||||
* parse every field we recognize and leave it to the bridge to honor only the
|
||||
* subset meaningful for its dialect/hook point (Codex, e.g., ignores
|
||||
* `allow`/`ask`/`updatedInput`).
|
||||
*
|
||||
* Parse a finished hook command's process outcome (exit code + stdout + stderr) into the
|
||||
* dialect-neutral {@link HookOutput} both bridges map from.
|
||||
* @module @deepseek-ai/dsh-hook-protocol/codec
|
||||
*/
|
||||
|
||||
@@ -58,49 +44,26 @@ function permissionDecisionOf(value: string | undefined): HookOutput['decision']
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one finished hook command into a {@link HookOutput}. `stdout`/`stderr`
|
||||
* are the captured streams; `exitCode` is the process exit (`undefined` when the
|
||||
* hook could not be spawned at all). Pure and total — never throws; malformed
|
||||
* JSON on a 0 exit is treated as "no structured output" (the plain stdout is
|
||||
* still on the bridge to use), matching both reference engines' lenient parse of
|
||||
* non-JSON stdout.
|
||||
*
|
||||
* `expectedEventName` is the event the hook is FIRING for (e.g. `'PreToolUse'`).
|
||||
* The reference schemas key the `hookSpecificOutput` block by `hookEventName`,
|
||||
* so a block whose `hookEventName` names a DIFFERENT event is malformed and its
|
||||
* event-scoped fields (`permissionDecision`/`permissionDecisionReason`/
|
||||
* `additionalContext`/`updatedInput`) are DISCARDED — a `PreToolUse` block on a
|
||||
* `Stop` hook must not deny the `Stop`. The block's `hookEventName` is still
|
||||
* surfaced (for the log/diagnostics), and the event-agnostic top-level fields
|
||||
* (`decision`/`reason`/`continue`/`stopReason`/`systemMessage`)
|
||||
* are unaffected. Omit `expectedEventName` (or pass a matching one) to apply the
|
||||
* block as-is — a caller that doesn't key by event opts out of the check.
|
||||
*
|
||||
* @param exitCode - the process exit code; `undefined` when the hook could not be spawned at all.
|
||||
* @param stdout - the captured stdout stream; consulted for structured JSON only on a 0 exit.
|
||||
* Decode process output into the dialect-neutral hook outcome.
|
||||
* @param exitCode - process exit, or `undefined` when spawn failed.
|
||||
* @param stdout - output parsed as structured JSON only on exit 0.
|
||||
* @param stderr - the captured stderr stream; becomes the blocking `reason` on exit 2.
|
||||
* @param expectedEventName - the event the hook is firing for; omit to apply a `hookSpecificOutput` block as-is.
|
||||
* @param expectedEventName - optional event guard for hook-specific output.
|
||||
* @returns the dialect-neutral decoded outcome.
|
||||
*/
|
||||
export function parseHookOutput(exitCode: number | undefined, stdout: string, stderr: string, expectedEventName?: string): HookOutput {
|
||||
const trimmedErr = stderr.trim()
|
||||
const trimmedOut = stdout.trim()
|
||||
// Keep the raw stdout verbatim: a clean-exit hook may emit PLAIN text the
|
||||
// protocol renders/uses (CC output; Codex SessionStart/UserPromptSubmit
|
||||
// additionalContext), so the bridge needs it even when there's no JSON.
|
||||
// Plain stdout remains available even when it is not JSON.
|
||||
const output: HookOutput = { exitCode, stderr: trimmedErr, stdout: trimmedOut }
|
||||
|
||||
// Exit 2 is a blocking error in both dialects: stderr is the reason. Surface
|
||||
// it as a `block` decision so the bridge maps it uniformly with a structured
|
||||
// `decision:'block'` — the exit code and the JSON channel converge here.
|
||||
// Both dialects treat exit 2 as a block with stderr as its reason.
|
||||
if (exitCode === BLOCKING_EXIT_CODE) {
|
||||
output.decision = 'block'
|
||||
if (trimmedErr.length > 0) output.reason = trimmedErr
|
||||
}
|
||||
|
||||
// Structured stdout is only consulted on a clean (0) exit; on a blocking exit
|
||||
// the stderr channel is authoritative. A non-zero/undefined exit other than 2
|
||||
// carries no decision (the bridge records it as a non-blocking error).
|
||||
// Structured stdout is valid only for a clean exit.
|
||||
if (exitCode === 0) {
|
||||
// Only attempt JSON when stdout looks like a JSON object — matches the
|
||||
// reference engines, which treat other stdout as plain text, not an error.
|
||||
@@ -151,12 +114,7 @@ function applyStructured(output: HookOutput, parsed: Record<string, unknown>, ex
|
||||
// mismatch — the record should show what the malformed block claimed.
|
||||
if (eventName !== undefined) output.hookEventName = eventName
|
||||
// The schemas key this block by event: when a caller passes the firing event
|
||||
// (`expectedEventName`), the block's `hookEventName` MUST name it. A different
|
||||
// name — or a MISSING one — is malformed under the keyed schema, so discard the
|
||||
// event-scoped fields (a PreToolUse block must not deny a Stop hook; nor may a
|
||||
// discriminator-less block silently apply PreToolUse-scoped permission fields to
|
||||
// whatever event is firing). A caller that passes no expectedEventName opts out
|
||||
// of the check (applies the block as-is).
|
||||
// (`expectedEventName`), the block's `hookEventName` must name it.
|
||||
if (expectedEventName !== undefined && eventName !== expectedEventName) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
/**
|
||||
* Quiescence tracking for a bridge's DETACHED hook runs. The waterfall-shaped
|
||||
* hook points (`UserPromptSubmit`, `PreToolUse`, …) are awaited by their seams,
|
||||
* but the emit-shaped points (`SessionStart`, `SubagentStart`, `SubagentStop`)
|
||||
* run fire-and-forget: no seam awaits them, so without tracking a bridge's
|
||||
* disposal could strand a live hook process and let a late continuation fire
|
||||
* into a disposed context (docs/defensive-patterns.md: dispose must reach
|
||||
* quiescence). A bridge creates one tracker in `apply()`, passes
|
||||
* {@link DetachedRuns.signal} to each detached {@link runHook} call, wraps the
|
||||
* full run chain (the hook run PLUS its `.then` continuation) in
|
||||
* {@link DetachedRuns.track}, and registers {@link DetachedRuns.drain} as its
|
||||
* disposer.
|
||||
*
|
||||
* Quiescence tracking for a bridge's DETACHED hook runs.
|
||||
* @module @deepseek-ai/dsh-hook-protocol/detached
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,17 +1,8 @@
|
||||
/**
|
||||
* Append helpers for the log-only `hook/*` session events — the durable record
|
||||
* that a hook ran and what it decided. Thin wrappers over `session.append` so a
|
||||
* bridge does not hand-build the payloads (and so the `turn`-enclosure +
|
||||
* invoked/result pairing stay consistent across both bridges).
|
||||
*
|
||||
* `hook/*` events are log-only (not {@link SurfaceEventType}), so they carry no
|
||||
* `surfaceOp` and append with no surface intent — but, like every event, they
|
||||
* must sit inside an OPEN turn (the invariants oracle rejects an un-enclosed
|
||||
* event). The mid-turn hook points (`PreToolUse`/`PostToolUse`/`UserPromptSubmit`/
|
||||
* `Stop`) fire inside the loop's open turn by construction; `SessionStart` is the
|
||||
* exception (its injected `context/message` is the durable evidence instead), so
|
||||
* a bridge does NOT write `hook/*` for session-start — see the hooks RFC.
|
||||
*
|
||||
* Append helpers for the log-only `hook/*` session events — the durable record that a hook ran
|
||||
* and what it decided. Thin wrappers over `session.append` so a bridge does not hand-build the
|
||||
* payloads (and so the `turn`-enclosure + invoked/result pairing stay consistent across both
|
||||
* bridges).
|
||||
* @module @deepseek-ai/dsh-hook-protocol/events
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,27 +1,8 @@
|
||||
/**
|
||||
* `@deepseek-ai/dsh-hook-protocol` — the shared core of the Claude Code / Codex
|
||||
* hook wire protocol. NOT a cordis plugin: it registers nothing and injects
|
||||
* nothing. It is a LIBRARY of dialect-neutral primitives the two bridge plugins
|
||||
* (`dsh-hooks-claude`, `dsh-hooks-codex`) import to avoid re-implementing the
|
||||
* identical halves of the protocol:
|
||||
*
|
||||
* - {@link matchesMatcher} — the matcher primitive (literal-or-regex by dialect).
|
||||
* - {@link runHook} + {@link parseHookOutput} — run a command hook via `ctx.bash`
|
||||
* (stdin payload + env) and decode its exit-code/stdout/stderr into a neutral
|
||||
* {@link HookOutput}.
|
||||
* - {@link mergeHookOutputs} — fold multiple matched hooks into one
|
||||
* most-restrictive {@link MergedHookOutcome} (deny > ask > allow).
|
||||
* - {@link appendHookInvoked} / {@link appendHookResult} — the log-only `hook/*`
|
||||
* session-event helpers (declaration-merged into `SessionEventMap`);
|
||||
* `appendHookResult` derives the durable `decision`/`stderrSummary` from the
|
||||
* {@link HookOutput} so the shared event's semantics live in one place.
|
||||
* - {@link createDetachedRuns} — quiescence tracking for the fire-and-forget
|
||||
* hook points: disposal aborts and drains a bridge's detached runs.
|
||||
*
|
||||
* Each bridge owns what genuinely DIFFERS: building the per-event stdin payload
|
||||
* (CC vs Codex field sets), the dialect's env/substitution, and mapping the
|
||||
* neutral outcome onto the harness's seam-specific typed Decisions.
|
||||
*
|
||||
* `@deepseek-ai/dsh-hook-protocol` — the shared core of the Claude Code / Codex hook wire
|
||||
* protocol. not a cordis plugin: it registers nothing and injects nothing. It is a LIBRARY of
|
||||
* dialect-neutral primitives the two bridge plugins (`dsh-hooks-claude`, `dsh-hooks-codex`)
|
||||
* import to avoid re-implementing the identical halves of the protocol.
|
||||
* @module @deepseek-ai/dsh-hook-protocol
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,20 +1,6 @@
|
||||
/**
|
||||
* The matcher primitive shared by both hook dialects: decide whether a matcher
|
||||
* pattern selects a given query (a tool name, a session source, …).
|
||||
*
|
||||
* The two dialects differ ONLY in how a non-empty pattern is interpreted, so
|
||||
* that single axis is the {@link MatcherMode} parameter:
|
||||
* - `claude`: a pattern of purely `[A-Za-z0-9_|]+` is a LITERAL (pipe =
|
||||
* exact-match alternation, e.g. `Edit|Write`); anything else is a regex.
|
||||
* - `codex`: every pattern is an unanchored regex (no literal fast path).
|
||||
*
|
||||
* Both treat an absent / empty / `'*'` pattern as match-all, and both treat an
|
||||
* invalid regex as a non-match: a broken matcher selects nothing rather than
|
||||
* throwing into the loop. This is SILENT — the boolean return cannot distinguish
|
||||
* "did not match" from "failed to compile", so a typo'd pattern (e.g. `[`)
|
||||
* quietly disables that matcher with no warning. Surfacing bad config would need
|
||||
* a diagnostic-returning variant or parse-time validation (`TODO(matcher-diagnostics)`).
|
||||
*
|
||||
* The matcher primitive shared by both hook dialects: decide whether a matcher pattern selects
|
||||
* a given query (a tool name, a session source, …).
|
||||
* @module @deepseek-ai/dsh-hook-protocol/matcher
|
||||
*/
|
||||
|
||||
@@ -30,14 +16,12 @@ const CLAUDE_LITERAL = /^[A-Za-z0-9_|]+$/
|
||||
|
||||
/**
|
||||
* Whether `matcher` selects `query` under the given dialect {@link MatcherMode}.
|
||||
* Match-all sentinels (absent/`''`/`'*'`) always match. A `claude` literal
|
||||
* pattern exact-matches the query (splitting `|` into alternatives); every other
|
||||
* `claude` pattern and ALL `codex` patterns are tested as an unanchored regex.
|
||||
* An invalid regex matches nothing (never throws).
|
||||
*
|
||||
* @param matcher - the configured pattern; absent/empty/`'*'` are the match-all sentinels.
|
||||
* @param query - the candidate value (a tool name, a session source, …).
|
||||
* @param mode - the dialect deciding literal-vs-regex interpretation of the pattern.
|
||||
* @returns `true` when the pattern selects the query; `false` on a non-match or an invalid regex.
|
||||
* @returns `true` when the pattern selects the query; `false` on a non-match or an invalid
|
||||
* regex.
|
||||
*/
|
||||
export function matchesMatcher(matcher: string | undefined, query: string, mode: MatcherMode): boolean {
|
||||
if (isMatchAll(matcher)) return true
|
||||
|
||||
@@ -1,23 +1,6 @@
|
||||
/**
|
||||
* Merge the outcomes of MULTIPLE hooks that matched one hook point into a single
|
||||
* most-restrictive {@link MergedHookOutcome}. Both reference engines run matched
|
||||
* hooks concurrently and fold their results; the precedence rules here are the
|
||||
* intersection both dialects agree on (and the strictest interpretation where
|
||||
* they differ), so a bridge gets one decision to map onto its seam:
|
||||
*
|
||||
* - **permission precedence `deny > ask > allow`**: any `deny`/`block` wins; an
|
||||
* `ask` overrides `allow`; `allow`/`approve` only stands if nothing stricter
|
||||
* appeared. (Claude Code's explicit precedence; Codex only ever blocks, so the
|
||||
* rule degenerates correctly for it.)
|
||||
* - **halt is sticky**: the first hook with `continue:false` sets `stop` and its
|
||||
* `stopReason`.
|
||||
* - **reasons accumulate**: block/deny reasons are joined with `\n\n` (Codex's
|
||||
* `join_text_chunks`), so the model sees every objection, not just the first.
|
||||
* - **context accumulates**: `additionalContext` from every hook is collected in
|
||||
* order (CC concatenates; Codex keeps them as separate developer messages —
|
||||
* either way the bridge gets the ordered list).
|
||||
* - **systemMessages accumulate** likewise.
|
||||
*
|
||||
* most-restrictive {@link MergedHookOutcome}.
|
||||
* @module @deepseek-ai/dsh-hook-protocol/merge
|
||||
*/
|
||||
|
||||
@@ -76,10 +59,9 @@ function decisionForRank(maxRank: number): MergedDecision {
|
||||
*/
|
||||
export function mergeHookOutputs(outputs: HookOutput[]): MergedHookOutcome {
|
||||
let maxRank = 0
|
||||
// Reasons collected PER RANK, so the merged reason can be the one explaining
|
||||
// the WINNING decision (a deny-winning outcome surfaces deny reasons; an
|
||||
// ask-winning outcome surfaces ask reasons). An `allow`'s reason is never an
|
||||
// objection the model needs, so rank 1 collects none.
|
||||
// Reasons collected per RANK, so the merged reason can be the one explaining the WINNING
|
||||
// decision (a deny-winning outcome surfaces deny reasons; an ask-winning outcome surfaces ask
|
||||
// reasons).
|
||||
const reasonsByRank = new Map<number, string[]>()
|
||||
let stop = false
|
||||
let stopReason: string | undefined
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
/**
|
||||
* Run one configured command hook through the `ctx.bash` executor seam and parse
|
||||
* its outcome into a {@link HookOutput}. This is where the wire protocol's
|
||||
* EXECUTION half lives: feed the hook its JSON payload on stdin, hand it the
|
||||
* dialect's env vars, honor its timeout, capture stdout/stderr/exit, and decode.
|
||||
*
|
||||
* It runs hooks through `ctx.bash` (not a bespoke `spawn`) deliberately — the
|
||||
* bash seam already provides the scrubbed-but-overridable env, process-group
|
||||
* kills, and timeout the protocol needs, and `dsh-bash`'s `stdin`/`env` fields
|
||||
* are the trusted-plugin surface (added for exactly this) that a hook bridge —
|
||||
* an in-process plugin, not model output — is allowed to use.
|
||||
*
|
||||
* Run one configured command hook through the `ctx.bash` executor seam and parse its outcome
|
||||
* into a {@link HookOutput}. This is where the wire protocol's EXECUTION half lives: feed the
|
||||
* hook its JSON payload on stdin, hand it the dialect's env vars, honor its timeout, capture
|
||||
* stdout/stderr/exit, and decode.
|
||||
* @module @deepseek-ai/dsh-hook-protocol/runner
|
||||
*/
|
||||
|
||||
@@ -61,15 +54,9 @@ export interface RunHookResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `hook` via `bash` with `options.payload` serialized to its stdin, then
|
||||
* decode the result into a {@link HookOutput}. The hook's configured
|
||||
* `timeoutSec` (wire unit: seconds) overrides `options.defaultTimeoutMs`.
|
||||
* The command runs with the dialect's `env` merged after the executor's
|
||||
* credential scrub (the trusted-plugin path). NEVER throws: an infrastructure
|
||||
* failure (the executor rejecting) is surfaced as a {@link HookOutput} with
|
||||
* `exitCode: undefined`, so the caller's merge logic treats it as a
|
||||
* non-blocking error rather than crashing the turn. `now` is injected for
|
||||
* testable durations.
|
||||
* Run `hook` via `bash` with `options.payload` serialized to its stdin, then decode the result
|
||||
* into a {@link HookOutput}.
|
||||
*
|
||||
* @param bash - the executor seam the command runs through.
|
||||
* @param hook - the configured command; its `timeoutSec` (wire unit: seconds) overrides the default timeout.
|
||||
* @param options - the invocation's payload, env, cwd, signal, stdin framing, and default timeout.
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
/**
|
||||
* Dialect-neutral vocabulary for the Claude Code / Codex hook wire protocol,
|
||||
* plus the log-only `hook/*` session events. Types only — runtime helpers live
|
||||
* in the sibling modules (`matcher`, `codec`, `runner`, `merge`, `events`).
|
||||
*
|
||||
* This package is the SHARED CORE: the truly-identical primitives both the
|
||||
* `dsh-hooks-claude` and `dsh-hooks-codex` bridges build on. Each bridge owns
|
||||
* its own per-dialect stdin-payload construction and decision mapping on top of
|
||||
* these primitives — the divergences (which events exist, literal-vs-regex
|
||||
* matching, env/substitution, snake_case extras, allow/ask support) are the
|
||||
* BRIDGE's concern, not this lib's.
|
||||
*
|
||||
* Dialect-neutral vocabulary for the Claude Code / Codex hook wire protocol, plus the log-only
|
||||
* `hook/*` session events. Types only — runtime helpers live in the sibling modules
|
||||
* (`matcher`, `codec`, `runner`, `merge`, `events`).
|
||||
* @module @deepseek-ai/dsh-hook-protocol/types
|
||||
*/
|
||||
|
||||
@@ -31,17 +23,7 @@ declare module '@deepseek-ai/dsh-session' {
|
||||
matcher?: string
|
||||
handlerId: string
|
||||
}
|
||||
/**
|
||||
* A hook command's outcome — log-only, paired with a prior `hook/invoked`
|
||||
* (same `handlerId`). `decision` is the dialect-neutral outcome derived by
|
||||
* `appendHookResult` (which owns the rule): the hook's parsed decision
|
||||
* (`approve`/`allow`/`block`/`deny`/`ask`), else `'stop'` when it asked to
|
||||
* halt via `continue:false`, else `'pass'`. `exitCode` is the process exit
|
||||
* (absent if it never ran), `stderrSummary` the trimmed stderr truncated to
|
||||
* the bridge's configured cap (the block reason source on exit 2),
|
||||
* `durationMs` the wall-clock runtime (audit timing; snapshot replay
|
||||
* normalizes it). `turn` matches the `hook/invoked`.
|
||||
*/
|
||||
/** Log-only hook outcome paired to `hook/invoked` by `handlerId`. */
|
||||
'hook/result': {
|
||||
turn: number
|
||||
point: string
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* Parse a Claude Code hook config file into the shared {@link MatcherGroup} shape, faithfully
|
||||
* to CC's `hooks.json` / settings `hooks` key format.
|
||||
* @module @deepseek-ai/dsh-hooks-claude/config
|
||||
*/
|
||||
|
||||
@@ -57,13 +50,13 @@ export function substituteCommand(command: string, vars: SubstitutionVars): stri
|
||||
}
|
||||
|
||||
/**
|
||||
* 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`.
|
||||
* @param raw - the parsed JSON config: a settings object with a `hooks` key, or the bare event map.
|
||||
* @param vars - substitution values applied to every surviving `command` (defaults to none).
|
||||
* 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.
|
||||
*
|
||||
* @param raw - the parsed JSON config: a settings object with a `hooks` key, or the bare
|
||||
* event map.
|
||||
* @param vars - substitution values applied to every surviving `command` (defaults to
|
||||
* none).
|
||||
* @returns the runnable per-event groups plus the skipped non-command hooks.
|
||||
*/
|
||||
export function parseClaudeConfig(raw: unknown, vars: SubstitutionVars = {}): ParsedClaudeConfig {
|
||||
|
||||
@@ -1,24 +1,7 @@
|
||||
/**
|
||||
* `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).
|
||||
*
|
||||
* `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.
|
||||
* @module @deepseek-ai/dsh-hooks-claude
|
||||
*/
|
||||
|
||||
@@ -129,11 +112,10 @@ export function apply(ctx: Context, config: Config): void {
|
||||
return
|
||||
}
|
||||
|
||||
// --- The emit-shaped points (SessionStart, SubagentStart, SubagentStop) run
|
||||
// detached — no seam awaits them — so every run chain is tracked and disposal
|
||||
// aborts still-running hook processes, then drains the continuations
|
||||
// (docs/defensive-patterns.md: dispose must reach quiescence). After the parse
|
||||
// gate: a bridge that registered nothing has nothing to drain. ---
|
||||
// --- The emit-shaped points (SessionStart, SubagentStart, SubagentStop) run detached — no
|
||||
// seam awaits them — so every run chain is tracked and disposal aborts still-running hook
|
||||
// processes, then drains the continuations (docs/defensive-patterns.md: dispose must reach
|
||||
// quiescence).
|
||||
const detached = createDetachedRuns()
|
||||
ctx.effect(() => () => detached.drain(), 'hooks-claude: drain detached hook runs')
|
||||
|
||||
@@ -154,19 +136,11 @@ export function apply(ctx: Context, config: Config): void {
|
||||
): Promise<MergedHookOutcome> {
|
||||
const groups: MatcherGroup[] = parsed[point] ?? []
|
||||
const outputs: HookOutput[] = []
|
||||
// Run the hook in the AGENT'S session workspace (the `session/new` cwd on the
|
||||
// session header), not the executor default (the ACP server's launch dir).
|
||||
// A hook that does `pwd`, reads a relative file, or writes a marker must
|
||||
// operate in the user's project tree. Absent for a no-agent run (falls back
|
||||
// to the executor default).
|
||||
// Run the hook in the AGENT'S session workspace (the `session/new` cwd on the session
|
||||
// header), not the executor default (the ACP server's launch dir).
|
||||
const workdir = opts.agent?.session.header.cwd
|
||||
// CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to
|
||||
// the session workspace (the same dir the hook RUNS in). Claude Code always
|
||||
// exports this var, and common unmodified hooks reference `$CLAUDE_PROJECT_DIR`
|
||||
// (shell expansion at run time) for project-relative paths — leaving it empty
|
||||
// in the default ACP wiring (no `projectDir` configured) would break them even
|
||||
// though the bridge already knows the workspace. Absent only for a no-agent run
|
||||
// with no configured projectDir (nothing to point at).
|
||||
// CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to the session
|
||||
// workspace (the same dir the hook RUNS in).
|
||||
const projectDir = config.projectDir ?? workdir
|
||||
const hookEnv = projectDir !== undefined ? { CLAUDE_PROJECT_DIR: projectDir } : undefined
|
||||
for (const group of groups) {
|
||||
@@ -206,13 +180,7 @@ export function apply(ctx: Context, config: Config): void {
|
||||
return mergeHookOutputs(outputs)
|
||||
}
|
||||
|
||||
// TODO(hook-continue-false): the merge computes `merged.stop`/`stopReason` from
|
||||
// a hook's `continue:false`, but no seam below honors it — there is no
|
||||
// "hard-halt the whole agent" primitive on the interception seams yet (a
|
||||
// Decision can block/deny/steer a single point, not stop the run). Honoring it
|
||||
// needs that primitive; deferred with the loop-guard work. Until then a
|
||||
// `continue:false` hook still has its per-point effect (its decision/context),
|
||||
// and the halt request is recorded in the `hook/result` log but not acted on.
|
||||
// TODO(hook-continue-false): `merged.stop` is logged but needs a run-level halt seam.
|
||||
|
||||
/** Build a HookContext from accumulated additionalContext strings, or undefined when none. */
|
||||
function contextFrom(merged: MergedHookOutcome): HookContext | undefined {
|
||||
@@ -221,30 +189,14 @@ export function apply(ctx: Context, config: Config): void {
|
||||
return { content, source: PLUGIN_SOURCE }
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenate this bridge's {@link HookContext} (`ours`, always present at the
|
||||
* call sites) with a downstream listener's optional one, so folding our
|
||||
* additionalContext onto a delegated decision drops neither. The merged block
|
||||
* carries a single `source` — this bridge's — because a `HookContext` holds one
|
||||
* `MessageSource` and the seam cannot represent mixed provenance; the rendered
|
||||
* `context/message` only distinguishes by `source.kind` ('plugin'), so a
|
||||
* downstream plugin's text is still correctly framed as plugin context, not a
|
||||
* user prompt.
|
||||
*/
|
||||
/** Merge hook context while retaining this bridge's plugin-level source. */
|
||||
function concatContext(ours: HookContext, theirs: HookContext | undefined): HookContext {
|
||||
if (!theirs) return ours
|
||||
return { content: [...ours.content, ...theirs.content], source: ours.source }
|
||||
}
|
||||
|
||||
// --- SessionStart: emit (cannot block). Inject any additionalContext into the
|
||||
// agent. The matcher subject is the source.
|
||||
// TODO(session-start-gating): `agent/session-start` is a SYNCHRONOUS emit and
|
||||
// this hook runs on a detached `.then`, so the injected context is BEST-EFFORT
|
||||
// — it is not guaranteed to land before the first turn reaches the model. A
|
||||
// slow hook can miss the first request (the context then arrives as a later
|
||||
// injection turn). Gating startup on the hook is a loop-level change deferred
|
||||
// to the interception seams; today the contract is "injected as soon as the
|
||||
// hook resolves", not "before the first request". ---
|
||||
// SessionStart injects context when its detached hook resolves.
|
||||
// TODO(session-start-gating): add a startup gate before promising first-turn delivery.
|
||||
ctx.on('agent/session-start', (agent, source) => {
|
||||
detached.track(runPoint('SessionStart', source, sessionStartPayload(agent, source), { agent, signal: detached.signal })
|
||||
.then((merged) => {
|
||||
@@ -264,10 +216,7 @@ export function apply(ctx: Context, config: Config): void {
|
||||
if (merged.decision === 'deny') {
|
||||
return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' }
|
||||
}
|
||||
// Our hooks did not block. DELEGATE (attaching context alone is not a veto):
|
||||
// a later `agent/prompt-submit` listener must still get to block or rewrite.
|
||||
// Then fold our additionalContext onto its decision — a downstream block wins
|
||||
// (a dropped prompt makes the context moot; `block` carries no context field).
|
||||
// Our hooks did not block.
|
||||
const downstream = await next()
|
||||
const ours = contextFrom(merged)
|
||||
if (!ours || downstream.kind !== 'allow') return downstream
|
||||
@@ -309,34 +258,20 @@ export function apply(ctx: Context, config: Config): void {
|
||||
}
|
||||
})
|
||||
|
||||
// --- 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. ---
|
||||
// A blocking Stop hook forces continuation with its reason.
|
||||
// TODO(stop-loop-guard): cap consecutive forced continuations.
|
||||
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') {
|
||||
// A blocking Stop hook forces continuation. It carries its reason as
|
||||
// next-step steering; a blocking hook that emitted no reason (exit 2, empty
|
||||
// stderr) still forces the turn to continue — the block is what matters, so
|
||||
// fall back to a generic steering line rather than letting the turn stop.
|
||||
// A blocking Stop hook forces continuation.
|
||||
const text = merged.reason ?? 'continue: blocked by Stop hook'
|
||||
return { action: 'continue', reason: { content: [{ type: 'text', text }], 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. Both look the live child up
|
||||
// so the hook runs in the child's session workspace and the payload carries
|
||||
// the child's session_id/cwd (see subagentPayload). The matcher subject is the
|
||||
// CC-default `agent_type` (SUBAGENT_TYPE) — the harness seam carries no
|
||||
// per-kind label, so a config's default/`*`/empty agent_type matcher fires and
|
||||
// a specific-kind matcher does not (documented in the RFC). ---
|
||||
// --- SubagentStart / SubagentStop: observe-only emits (the subagent seam is observe-only
|
||||
// this cut).
|
||||
ctx.on('subagent/start', (info) => {
|
||||
const child = ctx.get('agents')?.get(info.id)
|
||||
detached.track(runPoint('SubagentStart', SUBAGENT_TYPE, subagentPayload('SubagentStart', info, child), { ...child ? { agent: child } : {}, signal: detached.signal })
|
||||
@@ -347,13 +282,9 @@ export function apply(ctx: Context, config: Config): void {
|
||||
.catch((error: unknown) => { ctx.logger.warn(`hooks-claude: SubagentStart hook failed: ${String(error)}`) }))
|
||||
})
|
||||
ctx.on('subagent/end', (info) => {
|
||||
// Look up the child (still recoverable: `subagent/end` fires from the
|
||||
// service's detached `.then` BEFORE the tool caller's `await run.result`
|
||||
// disposes it) so the hook runs in the child's cwd, not the server default.
|
||||
// No `.then`/inject follows (SubagentStop only observes), and no `turn` is
|
||||
// passed (so no `hook/*` log records), so runPoint has nothing that can
|
||||
// reject — no `.catch` is needed (the tracker's settlement bookkeeping
|
||||
// would absorb one anyway).
|
||||
// Look up the child (still recoverable: `subagent/end` fires from the service's detached
|
||||
// `.then` before the tool caller's `await run.result` disposes it) so the hook runs in the
|
||||
// child's cwd, not the server default.
|
||||
const child = ctx.get('agents')?.get(info.id)
|
||||
detached.track(runPoint('SubagentStop', SUBAGENT_TYPE, subagentPayload('SubagentStop', info, child), { ...child ? { agent: child } : {}, signal: detached.signal }))
|
||||
})
|
||||
|
||||
@@ -302,12 +302,8 @@ describe('hooks-claude bridge — SubagentStart / SubagentStop (observe)', () =>
|
||||
await waitFor(() => existsSync(startMarker) && existsSync(stopMarker))
|
||||
expect(existsSync(startMarker)).toBe(true)
|
||||
expect(existsSync(stopMarker)).toBe(true)
|
||||
// The markers prove the hook PROCESSES ran, not that the detached `.then`
|
||||
// continuations did (`touch` lands before the process exits). Dispose drains
|
||||
// them, so the no-context arm of the SubagentStart continuation — covered
|
||||
// only here — executes before this file's coverage snapshot instead of
|
||||
// racing it (the arm went uncovered on a loaded CI runner and failed the
|
||||
// per-file 100% branch gate).
|
||||
// The markers prove the hook PROCESSES ran, not that the detached `.then` continuations did
|
||||
// (`touch` lands before the process exits).
|
||||
await hooks.dispose()
|
||||
})
|
||||
|
||||
@@ -317,10 +313,8 @@ describe('hooks-claude bridge — SubagentStart / SubagentStop (observe)', () =>
|
||||
const pidFile = join(dir, 'pid')
|
||||
const marker = join(dir, 'started')
|
||||
const slowHook = join(dir, 'slow.sh')
|
||||
// Record the hook shell's PID and touch the marker FIRST so the test can
|
||||
// tell "the hook is genuinely mid-run", then sleep far past the suite
|
||||
// timeout. Dispose must KILL the process (the tracker's abort signal), not
|
||||
// await its exit or its 10-minute default hook timeout.
|
||||
// Record the hook shell's PID and touch the marker FIRST so the test can tell "the hook is
|
||||
// genuinely mid-run", then sleep far past the suite timeout.
|
||||
writeFileSync(slowHook, `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
|
||||
chmodSync(slowHook, 0o755)
|
||||
writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: {
|
||||
@@ -334,11 +328,9 @@ describe('hooks-claude bridge — SubagentStart / SubagentStop (observe)', () =>
|
||||
await waitFor(() => existsSync(marker))
|
||||
const pid = Number(readFileSync(pidFile, 'utf8').trim())
|
||||
await hooks.dispose()
|
||||
// Quiescence, not just promptness: the drain resolves only after the run
|
||||
// settled, and the run settles only after the killed process was reaped —
|
||||
// so by the time dispose returns, the PID must be GONE (kill(pid, 0)
|
||||
// throws ESRCH). An untracked fire-and-forget regression would leave the
|
||||
// process alive (or unreaped) and fail this deterministically.
|
||||
// Quiescence, not just promptness: the drain resolves only after the run settled, and the
|
||||
// run settles only after the killed process was reaped — so by the time dispose returns,
|
||||
// the PID must be GONE (kill(pid, 0) throws ESRCH).
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
// The aborted run resolves as a non-blocking error (runHook never rejects),
|
||||
// so the drained continuation must NOT have logged a failure.
|
||||
@@ -367,11 +359,8 @@ describe('hooks-claude bridge — load resilience', () => {
|
||||
})
|
||||
|
||||
it('disposing the bridge fiber removes its listeners (HMR safety)', async () => {
|
||||
// A BLOCKING UserPromptSubmit hook: if the listener leaked past dispose it
|
||||
// would veto the prompt (0 model requests) and log a hook/invoked. Build the
|
||||
// ctx WITHOUT the harness's own bridge mount so this is the ONLY mount, then
|
||||
// dispose it — a leaked listener fails the test (a no-op `true` hook would
|
||||
// pass even leaked, so it proved nothing).
|
||||
// A BLOCKING UserPromptSubmit hook: if the listener leaked past dispose it would veto the
|
||||
// prompt (0 model requests) and log a hook/invoked.
|
||||
const dir = writeConfig({ UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'exit 2' }] }] })
|
||||
const adapter = new MockAdapter([textResponse('ok')])
|
||||
const ctx = new Context()
|
||||
@@ -393,10 +382,7 @@ describe('hooks-claude bridge — load resilience', () => {
|
||||
})
|
||||
|
||||
it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/apply', () => {
|
||||
// Postmortem 0001 guard: this plugin HAS `inject = ['bash']`, so a stray
|
||||
// `export default apply` would collapse the module via `unwrapExports`
|
||||
// (`exports.default ?? exports`), DROP `inject`, and crash at load with
|
||||
// "cannot get property … without inject". Guard the shape directly.
|
||||
// Loader must retain this namespace's injection metadata.
|
||||
expect('default' in HooksClaude).toBe(false)
|
||||
expect(HooksClaude.name).toBe('hooks-claude')
|
||||
expect(HooksClaude.inject).toEqual(['bash'])
|
||||
|
||||
@@ -183,9 +183,9 @@ describe('hooks-claude coverage — Stop continuation + subagent inject/catch',
|
||||
})
|
||||
|
||||
it('a Stop hook that blocks with EMPTY stderr still forces continuation (no reason required)', async () => {
|
||||
// Regression: a blocking Stop hook (exit 2) with no stderr yields decision
|
||||
// 'deny' + reason undefined; the turn must STILL force-continue (the block is
|
||||
// what matters), not silently stop. Self-limit to one block so it can't loop.
|
||||
// Regression: a blocking Stop hook (exit 2) with no stderr yields decision 'deny' + reason
|
||||
// undefined; the turn must STILL force-continue (the block is what matters), not silently
|
||||
// stop.
|
||||
const d = dir()
|
||||
const marker = join(d, 'fired')
|
||||
const s = sh(d, 'stop.sh', `#!/usr/bin/env bash\nif [ -e "${marker}" ]; then exit 0; fi\ntouch "${marker}"\nexit 2\n`)
|
||||
@@ -382,10 +382,8 @@ describe('hooks-claude coverage — schema-bypass apply + unspawnable hook', ()
|
||||
|
||||
describe('hooks-claude coverage — continue:false, context arm, no-cwd', () => {
|
||||
it('a {"continue":false} hook is RECORDED as decision "stop" but does not halt the run (TODO(hook-continue-false))', async () => {
|
||||
// Honoring `continue:false` (hard-halt the whole run) is deferred — there is
|
||||
// no such primitive on the interception seams yet. So this asserts the LOG
|
||||
// faithfully records the halt request (decision "stop"), AND that the run is
|
||||
// NOT actually halted: the tool still runs and the turn completes normally.
|
||||
// Honoring `continue:false` (hard-halt the whole run) is deferred — there is no such
|
||||
// primitive on the interception seams yet.
|
||||
const d = dir()
|
||||
const s = sh(d, 'stop.sh', '#!/usr/bin/env bash\necho \'{"continue":false,"stopReason":"halt"}\'\n')
|
||||
const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
|
||||
@@ -457,9 +455,8 @@ describe('hooks-claude coverage — continue:false, context arm, no-cwd', () =>
|
||||
})
|
||||
|
||||
it('a context-only UserPromptSubmit hook DELEGATES so a later listener can still block', async () => {
|
||||
// A hook that only adds context must NOT short-circuit the waterfall: a
|
||||
// downstream agent/prompt-submit listener (a policy plugin) must still get to
|
||||
// block the prompt. The bridge delegates via next() and folds its context.
|
||||
// A hook that only adds context must not short-circuit the waterfall: a downstream
|
||||
// agent/prompt-submit listener (a policy plugin) must still get to block the prompt.
|
||||
const d = dir()
|
||||
const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"bridge ctx"}}\'\n')
|
||||
const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
|
||||
@@ -589,10 +586,8 @@ describe('hooks-claude coverage — detached-listener catch handlers', () => {
|
||||
|
||||
describe('hooks-claude coverage — hook runs in the session cwd, not the server cwd', () => {
|
||||
it('runs an agent-scoped hook in the session workspace even when the executor default differs', async () => {
|
||||
// The bug: the bridge passed no workdir, so hooks ran in the executor default
|
||||
// (the server launch dir), not session/new.cwd. Here the executor default and
|
||||
// the session cwd are DIFFERENT temp dirs; a PreToolUse hook writes `pwd` to a
|
||||
// marker and we assert it ran in the SESSION cwd.
|
||||
// The bug: the bridge passed no workdir, so hooks ran in the executor default (the server
|
||||
// launch dir), not session/new.cwd.
|
||||
const serverDir = dir()
|
||||
const sessionDir = dir()
|
||||
const marker = join(sessionDir, 'where')
|
||||
@@ -626,11 +621,8 @@ describe('hooks-claude coverage — hook runs in the session cwd, not the server
|
||||
})
|
||||
|
||||
it('runs a SubagentStop hook in the CHILD session workspace, not the server cwd', async () => {
|
||||
// SubagentStop looks the child up (recoverable at subagent/end) and runs the
|
||||
// hook in the CHILD's session cwd, not the executor default. Here the executor
|
||||
// default and the child session cwd are DIFFERENT dirs; a SubagentStop hook
|
||||
// writes `pwd` to a relative marker and we assert it landed in the CHILD dir —
|
||||
// which only holds if the listener threaded the child agent into runPoint.
|
||||
// SubagentStop looks the child up (recoverable at subagent/end) and runs the hook in the
|
||||
// CHILD's session cwd, not the executor default.
|
||||
const serverDir = dir()
|
||||
const childDir = dir()
|
||||
const marker = join(childDir, 'stopwhere')
|
||||
@@ -681,11 +673,8 @@ describe('hooks-claude coverage — systemMessage is warned, not surfaced', () =
|
||||
|
||||
describe('hooks-claude coverage — SessionStart timing is best-effort (no-wait)', () => {
|
||||
it('does NOT crash or block when the prompt is sent immediately (context is best-effort, may miss the first request)', async () => {
|
||||
// Regression for the documented downgrade: session-start injection is
|
||||
// detached, so a prompt sent immediately need not observe it. This asserts
|
||||
// the SAFE properties (no crash, the turn still runs) WITHOUT waiting for the
|
||||
// inject first — it documents the best-effort timing rather than masking it
|
||||
// by pre-waiting for context/message (which the guaranteed-timing tests do).
|
||||
// Regression for the documented downgrade: session-start injection is detached, so a prompt
|
||||
// sent immediately need not observe it.
|
||||
const d = dir()
|
||||
const s = sh(d, 'start.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"late ctx"}}\'\n')
|
||||
const path = hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: s }] }] })
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
/**
|
||||
* Parse a Codex `hooks.json` into the shared {@link MatcherGroup} shape. Codex's
|
||||
* config format is a SUBSET of Claude Code's: the same event-name → matcher-group
|
||||
* structure and the same `{ type: 'command', command, timeout?/timeoutSec? }`
|
||||
* hook shape, but only five events and NO command-string substitution (Codex sets
|
||||
* no hook env vars and does not expand `${…}`). Non-command hooks (and Codex's
|
||||
* `async: true` commands) are parsed-and-skipped with a warning.
|
||||
*
|
||||
* Parse a Codex `hooks.json` into the shared {@link MatcherGroup} shape.
|
||||
* @module @deepseek-ai/dsh-hooks-codex/config
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,17 +1,6 @@
|
||||
/**
|
||||
* `dsh-hooks-codex` — a bridge plugin that runs a user's existing Codex
|
||||
* `hooks.json` on the harness's canonical interception seams. The CODEX DIALECT
|
||||
* half of the hooks subsystem.
|
||||
*
|
||||
* Codex's hook protocol is a deliberate SUBSET of Claude Code's: five hook points
|
||||
* (`PreToolUse`, `PostToolUse`, `SessionStart`, `UserPromptSubmit`, `Stop` — no
|
||||
* subagent/notification/compaction), regex-only matchers, snake_case stdin
|
||||
* payloads with `turn_id`/`model` extras and NO trailing newline, no env vars and
|
||||
* no command substitution, and a block-only decision model (allow/ask are not
|
||||
* honored — a hook can only block, never pre-approve). The dialect-agnostic
|
||||
* primitives come from `@deepseek-ai/dsh-hook-protocol`; this bridge owns the
|
||||
* Codex-specific payloads + matcher mode + decision mapping.
|
||||
*
|
||||
* `dsh-hooks-codex` — a bridge plugin that runs a user's existing Codex `hooks.json` on the
|
||||
* harness's canonical interception seams. The CODEX DIALECT half of the hooks subsystem.
|
||||
* @module @deepseek-ai/dsh-hooks-codex
|
||||
*/
|
||||
|
||||
@@ -112,9 +101,9 @@ export function apply(ctx: Context, config: Config): void {
|
||||
): Promise<MergedHookOutcome> {
|
||||
const groups: MatcherGroup[] = parsed[point] ?? []
|
||||
const outputs: HookOutput[] = []
|
||||
// Run the hook in the agent's session workspace (the `session/new` cwd), not
|
||||
// the executor default (the server launch dir) — a hook reading a relative
|
||||
// file or `pwd` must see the user's project tree. Absent for a no-agent run.
|
||||
// Run the hook in the agent's session workspace (the `session/new` cwd), not the executor
|
||||
// default (the server launch dir) — a hook reading a relative file or `pwd` must see the
|
||||
// user's project tree.
|
||||
const workdir = opts.agent?.session.header.cwd
|
||||
for (const group of groups) {
|
||||
// Codex matches with PURE regex (no literal fast path).
|
||||
@@ -137,16 +126,8 @@ export function apply(ctx: Context, config: Config): void {
|
||||
// Discard a `hookSpecificOutput` block naming a different event.
|
||||
expectedEventName: point,
|
||||
}, () => performance.now())
|
||||
// Codex's SessionStart/UserPromptSubmit treat a CLEAN hook's PLAIN
|
||||
// (non-JSON) stdout as additionalContext. The codec keeps that raw text on
|
||||
// `output.stdout` but only sets `additionalContext` from a JSON
|
||||
// `hookSpecificOutput`, so fold plain stdout in here and let the shared
|
||||
// merge + contextFrom path carry it. Gated exactly like the codec's own
|
||||
// structured-stdout parse: only on a clean `exitCode === 0` (a non-zero
|
||||
// exit is an error, not context — an `echo x; exit 2` must not inject
|
||||
// `x`), only when stdout is non-JSON (`!startsWith('{')` — a structured
|
||||
// hook's raw JSON is never dumped as prose), and never clobbering an
|
||||
// explicit additionalContext from a JSON block.
|
||||
// Codex's SessionStart/UserPromptSubmit treat a CLEAN hook's PLAIN (non-JSON) stdout as
|
||||
// additionalContext.
|
||||
if (opts.plainStdoutAsContext === true && output.exitCode === 0
|
||||
&& output.additionalContext === undefined
|
||||
&& output.stdout.length > 0 && !output.stdout.startsWith('{')) {
|
||||
@@ -164,11 +145,7 @@ export function apply(ctx: Context, config: Config): void {
|
||||
return mergeHookOutputs(outputs)
|
||||
}
|
||||
|
||||
// TODO(hook-continue-false): the merge computes `merged.stop`/`stopReason` from
|
||||
// a hook's `continue:false`, but no seam below honors it — there is no
|
||||
// "hard-halt the whole agent" primitive on the interception seams yet. Deferred
|
||||
// with the loop-guard work; until then a `continue:false` hook keeps its
|
||||
// per-point effect and the halt request is recorded in `hook/result`, not acted on.
|
||||
// TODO(hook-continue-false): `merged.stop` is logged but needs a run-level halt seam.
|
||||
|
||||
function contextFrom(merged: MergedHookOutcome): HookContext | undefined {
|
||||
if (merged.additionalContext.length === 0) return undefined
|
||||
@@ -176,25 +153,14 @@ export function apply(ctx: Context, config: Config): void {
|
||||
return { content, source: PLUGIN_SOURCE }
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenate this bridge's {@link HookContext} (`ours`, always present at the
|
||||
* call sites) with a downstream listener's optional one, so folding our
|
||||
* additionalContext onto a delegated decision drops neither. The merged block
|
||||
* carries a single `source` — this bridge's — because a `HookContext` holds one
|
||||
* `MessageSource` and the seam cannot represent mixed provenance; the rendered
|
||||
* `context/message` only distinguishes by `source.kind` ('plugin'), so a
|
||||
* downstream plugin's text is still correctly framed as plugin context.
|
||||
*/
|
||||
/** Merge hook context while retaining this bridge's plugin-level source. */
|
||||
function concatContext(ours: HookContext, theirs: HookContext | undefined): HookContext {
|
||||
if (!theirs) return ours
|
||||
return { content: [...ours.content, ...theirs.content], source: ours.source }
|
||||
}
|
||||
|
||||
// SessionStart: emit. Codex passes a plain-stdout hook's output as additionalContext.
|
||||
// TODO(session-start-gating): a synchronous emit + detached `.then`, so the
|
||||
// injected context is BEST-EFFORT — not guaranteed before the first turn reaches
|
||||
// the model (a slow hook can miss the first request). Gating is a deferred
|
||||
// loop-level change; the contract is "injected as soon as the hook resolves".
|
||||
// SessionStart injects plain stdout when its detached hook resolves.
|
||||
// TODO(session-start-gating): add a startup gate before promising first-turn delivery.
|
||||
ctx.on('agent/session-start', (agent, source) => {
|
||||
detached.track(runPoint('SessionStart', source, { ...base(agent, 'SessionStart', model), source }, { agent, plainStdoutAsContext: true, signal: detached.signal })
|
||||
.then((merged) => {
|
||||
|
||||
@@ -143,10 +143,8 @@ describe('hooks-codex bridge', () => {
|
||||
|
||||
it('disposing the bridge fiber removes its listeners (HMR safety)', async () => {
|
||||
const dir = configDir()
|
||||
// A BLOCKING UserPromptSubmit hook: if the listener leaked past dispose, it
|
||||
// would veto the prompt (0 model requests) and log a hook/invoked. After a
|
||||
// clean dispose the turn must proceed untouched — this fails loudly on a leak
|
||||
// (a no-op `true` hook would pass even with a leaked listener).
|
||||
// A BLOCKING UserPromptSubmit hook: if the listener leaked past dispose, it would veto the
|
||||
// prompt (0 model requests) and log a hook/invoked.
|
||||
const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\nexit 2\n')
|
||||
writeHooks(dir, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: deny }] }] })
|
||||
const adapter = new MockAdapter([textResponse('ok')])
|
||||
@@ -172,10 +170,8 @@ describe('hooks-codex bridge', () => {
|
||||
const dir = configDir()
|
||||
const pidFile = join(dir, 'pid')
|
||||
const marker = join(dir, 'started')
|
||||
// Record the hook shell's PID and touch the marker FIRST so the test can
|
||||
// tell "the hook is genuinely mid-run", then sleep far past the suite
|
||||
// timeout. Dispose must KILL the process (the tracker's abort signal wired
|
||||
// through this bridge's runPoint), not await its exit.
|
||||
// Record the hook shell's PID and touch the marker FIRST so the test can tell "the hook is
|
||||
// genuinely mid-run", then sleep far past the suite timeout.
|
||||
const slow = script(dir, 'slow.sh', `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
|
||||
writeHooks(dir, { SessionStart: [{ hooks: [{ type: 'command', command: slow }] }] })
|
||||
const ctx = new Context()
|
||||
@@ -194,11 +190,9 @@ describe('hooks-codex bridge', () => {
|
||||
await waitFor(() => existsSync(marker))
|
||||
const pid = Number(readFileSync(pidFile, 'utf8').trim())
|
||||
await fiber.dispose()
|
||||
// Quiescence, not just promptness: the drain resolves only after the run
|
||||
// settled, and the run settles only after the killed process was reaped —
|
||||
// so by the time dispose returns, the PID must be GONE (kill(pid, 0)
|
||||
// throws ESRCH). An untracked fire-and-forget regression would leave the
|
||||
// process alive (or unreaped) and fail this deterministically.
|
||||
// Quiescence, not just promptness: the drain resolves only after the run settled, and the
|
||||
// run settles only after the killed process was reaped — so by the time dispose returns,
|
||||
// the PID must be GONE (kill(pid, 0) throws ESRCH).
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
// The aborted run resolves as a non-blocking error (runHook never rejects),
|
||||
// so the drained continuation must NOT have logged a failure.
|
||||
|
||||
@@ -70,9 +70,8 @@ describe('hooks-codex coverage — decision mapping paths', () => {
|
||||
})
|
||||
|
||||
it('a context-only UserPromptSubmit hook DELEGATES so a later listener can still block', async () => {
|
||||
// Context alone is not a veto: a downstream agent/prompt-submit listener (a
|
||||
// policy plugin registered after the bridge) must still get to block. The
|
||||
// bridge delegates via next() and folds its context onto the decision.
|
||||
// Context alone is not a veto: a downstream agent/prompt-submit listener (a policy plugin
|
||||
// registered after the bridge) must still get to block.
|
||||
const d = dir()
|
||||
hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'c.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"bridge ctx"}}\'\n') }] }] })
|
||||
const adapter = new MockAdapter([textResponse('should not run')])
|
||||
@@ -438,11 +437,8 @@ describe('hooks-codex coverage — decision mapping paths', () => {
|
||||
})
|
||||
|
||||
it('a NON-clean SessionStart hook (exit 2) does NOT inject its stdout as context', async () => {
|
||||
// The plain-stdout→context fold is gated on exitCode === 0, matching the
|
||||
// codec's structured-stdout rule. SessionStart is an EMIT (cannot block), so
|
||||
// an `echo stale; exit 2` here is the exact case the gate guards: without it,
|
||||
// the non-clean hook's stdout would wrongly inject "stale". A marker lets us
|
||||
// wait for the detached hook to finish before asserting absence.
|
||||
// The plain-stdout→context fold is gated on exitCode === 0, matching the codec's
|
||||
// structured-stdout rule.
|
||||
const d = dir()
|
||||
const marker = join(d, 'ran')
|
||||
hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: sh(d, 'b.sh', `#!/usr/bin/env bash\ntouch "${marker}"\necho "stale"\nexit 2\n`) }] }] })
|
||||
|
||||
Reference in New Issue
Block a user