index.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /**
  2. * `dsh-hooks-codex` — a bridge plugin that runs a user's existing Codex
  3. * `hooks.json` on the harness's canonical interception seams. The CODEX DIALECT
  4. * half of the hooks subsystem.
  5. *
  6. * Codex's hook protocol is a deliberate SUBSET of Claude Code's: five hook points
  7. * (`PreToolUse`, `PostToolUse`, `SessionStart`, `UserPromptSubmit`, `Stop` — no
  8. * subagent/notification/compaction), regex-only matchers, snake_case stdin
  9. * payloads with `turn_id`/`model` extras and NO trailing newline, no env vars and
  10. * no command substitution, and a block-only decision model (allow/ask are not
  11. * honored — a hook can only block, never pre-approve). The dialect-agnostic
  12. * primitives come from `@deepseek-ai/dsh-hook-protocol`; this bridge owns the
  13. * Codex-specific payloads + matcher mode + decision mapping.
  14. *
  15. * @module @deepseek-ai/dsh-hooks-codex
  16. */
  17. // Each dialect bridge keeps its complete dependency list visible at the entry
  18. // point; a cross-package facade for imports alone would add indirection.
  19. /* jscpd:ignore-start */
  20. import { readFileSync } from 'node:fs'
  21. import type { Context } from 'cordis'
  22. import z from 'schemastery'
  23. import type { Agent, ContinuationDecision, HookContext, PromptDecision } from '@deepseek-ai/dsh-agent'
  24. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  25. import type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  26. import {
  27. appendHookInvoked,
  28. appendHookResult,
  29. createDetachedRuns,
  30. DEFAULT_HOOK_TIMEOUT_MS,
  31. DEFAULT_STDERR_SUMMARY_MAX_CHARS,
  32. matchesMatcher,
  33. mergeHookOutputs,
  34. runHook,
  35. type HookOutput,
  36. type MatcherGroup,
  37. type MergedHookOutcome,
  38. } from '@deepseek-ai/dsh-hook-protocol'
  39. import { parseCodexConfig, type CodexHookConfig } from './config.ts'
  40. /* jscpd:ignore-end */
  41. export const name = 'hooks-codex'
  42. export const inject = ['bash']
  43. /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */
  44. export interface Config {
  45. /**
  46. * Path to a Codex `hooks.json`. PROCESS-LEVEL: read once at load, a relative
  47. * path resolves against the process launch cwd.
  48. * TODO(per-session-hook-config): per-session project-local discovery from each
  49. * `session/new.cwd` is not yet implemented.
  50. */
  51. configPath: string
  52. /** The model name stamped on every payload (Codex includes `model` on each event). */
  53. model?: string
  54. /** Default per-hook timeout in ms when a hook sets none (Codex default: 600000). */
  55. defaultTimeoutMs?: number
  56. /** Character cap for the `hook/result` event's persisted stderr summary. */
  57. stderrSummaryMaxChars?: number
  58. }
  59. export const Config: z<Config> = z.object({
  60. configPath: z.string().required(),
  61. model: z.string().default(''),
  62. defaultTimeoutMs: z.number().default(DEFAULT_HOOK_TIMEOUT_MS),
  63. stderrSummaryMaxChars: z.number().default(DEFAULT_STDERR_SUMMARY_MAX_CHARS),
  64. })
  65. let handlerCounter = 0
  66. function nextHandlerId(point: string): string {
  67. return `codex:${point}:${++handlerCounter}`
  68. }
  69. const PLUGIN_SOURCE: MessageSource = { kind: 'plugin', plugin: 'hooks-codex' }
  70. /** The summary cap bounds a persisted event field — a positive integer or the slice misbehaves silently. */
  71. function assertPositiveInteger(name: string, value: number): void {
  72. if (!Number.isInteger(value) || value < 1) {
  73. throw new Error(`hooks-codex: ${name} must be a positive integer`)
  74. }
  75. }
  76. export function apply(ctx: Context, config: Config): void {
  77. // Validate the cap BEFORE the config-file parse: a bad value must fail the
  78. // load loudly, not be skipped by the parse-failure early return.
  79. const stderrSummaryMaxChars = config.stderrSummaryMaxChars ?? DEFAULT_STDERR_SUMMARY_MAX_CHARS
  80. assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
  81. const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
  82. let parsed: CodexHookConfig = {}
  83. try {
  84. const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
  85. const result = parseCodexConfig(raw)
  86. parsed = result.config
  87. for (const s of result.skipped) {
  88. ctx.logger.warn(`hooks-codex: skipping ${s.reason} on ${s.event} (only sync command hooks run)`)
  89. }
  90. } catch (error: unknown) {
  91. ctx.logger.warn(`hooks-codex: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
  92. return
  93. }
  94. const model = config.model ?? ''
  95. // SessionStart is the one emit-shaped (detached) point Codex has: track its
  96. // run chains so disposal aborts a still-running hook process and drains the
  97. // continuation (docs/defensive-patterns.md: dispose must reach quiescence).
  98. const detached = createDetachedRuns()
  99. ctx.effect(() => () => detached.drain(), 'hooks-codex: drain detached hook runs')
  100. async function runPoint(
  101. point: string,
  102. matchQuery: string,
  103. payload: unknown,
  104. opts: { agent?: Agent; turn?: number; signal?: AbortSignal; plainStdoutAsContext?: boolean },
  105. ): Promise<MergedHookOutcome> {
  106. const groups: MatcherGroup[] = parsed[point] ?? []
  107. const outputs: HookOutput[] = []
  108. // Run the hook in the agent's session workspace (the `session/new` cwd), not
  109. // the executor default (the server launch dir) — a hook reading a relative
  110. // file or `pwd` must see the user's project tree. Absent for a no-agent run.
  111. const workdir = opts.agent?.session.header.cwd
  112. for (const group of groups) {
  113. // Codex matches with PURE regex (no literal fast path).
  114. if (!matchesMatcher(group.matcher, matchQuery, 'codex')) continue
  115. for (const hook of group.hooks) {
  116. const handlerId = nextHandlerId(point)
  117. const session = opts.agent?.session
  118. if (session && opts.turn !== undefined) {
  119. appendHookInvoked(session, {
  120. turn: opts.turn, point, dialect: 'codex', handlerId,
  121. ...group.matcher !== undefined ? { matcher: group.matcher } : {},
  122. })
  123. }
  124. const { output, durationMs } = await runHook(ctx.bash, hook, {
  125. payload,
  126. defaultTimeoutMs,
  127. ...workdir !== undefined ? { cwd: workdir } : {},
  128. ...opts.signal ? { signal: opts.signal } : {},
  129. trailingNewline: false, // Codex writes stdin WITHOUT a trailing newline.
  130. // Discard a `hookSpecificOutput` block naming a different event.
  131. expectedEventName: point,
  132. }, () => performance.now())
  133. // Codex's SessionStart/UserPromptSubmit treat a CLEAN hook's PLAIN
  134. // (non-JSON) stdout as additionalContext. The codec keeps that raw text on
  135. // `output.stdout` but only sets `additionalContext` from a JSON
  136. // `hookSpecificOutput`, so fold plain stdout in here and let the shared
  137. // merge + contextFrom path carry it. Gated exactly like the codec's own
  138. // structured-stdout parse: only on a clean `exitCode === 0` (a non-zero
  139. // exit is an error, not context — an `echo x; exit 2` must not inject
  140. // `x`), only when stdout is non-JSON (`!startsWith('{')` — a structured
  141. // hook's raw JSON is never dumped as prose), and never clobbering an
  142. // explicit additionalContext from a JSON block.
  143. if (opts.plainStdoutAsContext === true && output.exitCode === 0
  144. && output.additionalContext === undefined
  145. && output.stdout.length > 0 && !output.stdout.startsWith('{')) {
  146. output.additionalContext = output.stdout
  147. }
  148. outputs.push(output)
  149. // Execution and decision mapping remain in each bridge so dialect
  150. // differences stay explicit at their owning seam.
  151. /* jscpd:ignore-start */
  152. if (output.systemMessage !== undefined) {
  153. ctx.logger.warn(`hooks-codex: ${point} hook emitted a systemMessage, which is not yet surfaced (ignored)`)
  154. }
  155. if (session && opts.turn !== undefined) {
  156. appendHookResult(session, { turn: opts.turn, point, handlerId, output, stderrSummaryMaxChars, durationMs })
  157. }
  158. }
  159. }
  160. return mergeHookOutputs(outputs)
  161. }
  162. // TODO(hook-continue-false): the merge computes `merged.stop`/`stopReason` from
  163. // a hook's `continue:false`, but no seam below honors it — there is no
  164. // "hard-halt the whole agent" primitive on the interception seams yet. Deferred
  165. // with the loop-guard work; until then a `continue:false` hook keeps its
  166. // per-point effect and the halt request is recorded in `hook/result`, not acted on.
  167. function contextFrom(merged: MergedHookOutcome): HookContext | undefined {
  168. if (merged.additionalContext.length === 0) return undefined
  169. const content: ContentBlock[] = merged.additionalContext.map(text => ({ type: 'text', text }))
  170. return { content, source: PLUGIN_SOURCE }
  171. }
  172. /**
  173. * Concatenate this bridge's {@link HookContext} (`ours`, always present at the
  174. * call sites) with a downstream listener's optional one, so folding our
  175. * additionalContext onto a delegated decision drops neither. The merged block
  176. * carries a single `source` — this bridge's — because a `HookContext` holds one
  177. * `MessageSource` and the seam cannot represent mixed provenance; the rendered
  178. * `context/message` only distinguishes by `source.kind` ('plugin'), so a
  179. * downstream plugin's text is still correctly framed as plugin context.
  180. */
  181. function concatContext(ours: HookContext, theirs: HookContext | undefined): HookContext {
  182. if (!theirs) return ours
  183. return { content: [...ours.content, ...theirs.content], source: ours.source }
  184. }
  185. // SessionStart: emit. Codex passes a plain-stdout hook's output as additionalContext.
  186. // TODO(session-start-gating): a synchronous emit + detached `.then`, so the
  187. // injected context is BEST-EFFORT — not guaranteed before the first turn reaches
  188. // the model (a slow hook can miss the first request). Gating is a deferred
  189. // loop-level change; the contract is "injected as soon as the hook resolves".
  190. ctx.on('agent/session-start', (agent, source) => {
  191. detached.track(runPoint('SessionStart', source, { ...base(agent, 'SessionStart', model), source }, { agent, plainStdoutAsContext: true, signal: detached.signal })
  192. .then((merged) => {
  193. const context = contextFrom(merged)
  194. if (context) agent.inject(context.content, { source: context.source })
  195. })
  196. .catch((error: unknown) => { ctx.logger.warn(`hooks-codex: SessionStart hook failed: ${String(error)}`) }))
  197. /* jscpd:ignore-end */
  198. })
  199. // UserPromptSubmit → PromptDecision. Codex can only BLOCK (no allow/ask).
  200. ctx.on('agent/prompt-submit', async (agent, content, _source, next): Promise<PromptDecision> => {
  201. const turn = lastTurn(agent)
  202. const merged = await runPoint('UserPromptSubmit', '', { ...turnBase(agent, 'UserPromptSubmit', model), prompt: blocksToText(content) }, { agent, turn, plainStdoutAsContext: true })
  203. /* jscpd:ignore-start */
  204. if (merged.decision === 'deny') return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' }
  205. // Context alone is not a veto: DELEGATE so a later prompt-submit listener can
  206. // still block/rewrite, then fold our context onto its decision.
  207. const downstream = await next()
  208. const ours = contextFrom(merged)
  209. if (!ours || downstream.kind !== 'allow') return downstream
  210. return {
  211. kind: 'allow',
  212. ...downstream.content !== undefined ? { content: downstream.content } : {},
  213. additionalContext: concatContext(ours, downstream.additionalContext),
  214. }
  215. })
  216. // PreToolUse → PreToolDecision. Codex blocks only (no allow/ask honored).
  217. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  218. const turn = lastTurn(exec.agent)
  219. const merged = await runPoint('PreToolUse', exec.name, preToolPayload(exec, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, ...exec.signal ? { signal: exec.signal } : {} })
  220. /* jscpd:ignore-end */
  221. if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' }
  222. return next()
  223. })
  224. // PostToolUse → PostToolDecision (block with feedback, or attach context).
  225. ctx.on('tools/post-execute', async (exec, result, next): Promise<PostToolDecision> => {
  226. const turn = lastTurn(exec.agent)
  227. /* jscpd:ignore-start */
  228. const merged = await runPoint('PostToolUse', exec.name, postToolPayload(exec, result, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, ...exec.signal ? { signal: exec.signal } : {} })
  229. const context = contextFrom(merged)
  230. if (merged.decision === 'deny') {
  231. return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContext: context } : {} }
  232. }
  233. // Context alone is not a veto: DELEGATE, then fold our context onto the
  234. // downstream decision (a downstream block carries it too).
  235. const downstream = await next()
  236. if (!context) return downstream
  237. if (downstream.kind === 'block') {
  238. return { ...downstream, additionalContext: concatContext(context, downstream.additionalContext) }
  239. }
  240. return {
  241. kind: 'accept',
  242. ...downstream.content !== undefined ? { content: downstream.content } : {},
  243. additionalContext: concatContext(context, downstream.additionalContext),
  244. }
  245. })
  246. // Stop → ContinuationDecision. A blocking Stop hook forces continuation.
  247. // TODO(stop-loop-guard): like CC, a Stop hook that unconditionally blocks would
  248. // force-continue every step (`stop_hook_active` is always false here); the
  249. // loop-guard (stop_hook_active + a max-consecutive cap) is deferred.
  250. ctx.on('agent/turn-continuation', async (agent, turn, _default, next): Promise<ContinuationDecision> => {
  251. const merged = await runPoint('Stop', '', { ...turnBase(agent, 'Stop', model), stop_hook_active: false, last_assistant_message: null }, { agent, turn })
  252. /* jscpd:ignore-end */
  253. if (merged.decision === 'deny') {
  254. // A blocking Stop hook forces continuation; a block with no reason (exit 2,
  255. // empty stderr) still forces it — fall back to a generic steering line
  256. // rather than letting the turn stop.
  257. const text = merged.reason ?? 'continue: blocked by Stop hook'
  258. return { action: 'continue', reason: { content: [{ type: 'text', text }], source: PLUGIN_SOURCE } }
  259. }
  260. return next()
  261. })
  262. }
  263. // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on
  264. // turn-scoped events. ---
  265. // These small payload helpers intentionally remain next to the dialect shape;
  266. // sharing them would pull bridge-only agent/LLM dependencies into hook-protocol.
  267. /* jscpd:ignore-start */
  268. function lastTurn(agent: Agent | undefined): number {
  269. if (!agent) return 0
  270. const last = [...agent.session.events].findLast(e => e.type === 'turn/start')
  271. /* v8 ignore next -- the `: 0` arm is a defensive fallback: when an agent is
  272. present, lastTurn is only called from the mid-turn seams, which always run
  273. inside an open turn, so `last` is always a turn/start here. */
  274. return last?.type === 'turn/start' ? last.data.turn : 0
  275. }
  276. function blocksToText(content: ContentBlock[]): string {
  277. return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
  278. }
  279. /* jscpd:ignore-end */
  280. /** Base fields on every Codex payload (no turn_id). */
  281. function base(agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  282. return {
  283. session_id: agent?.session.header.id ?? '',
  284. transcript_path: null,
  285. cwd: agent?.session.header.cwd ?? process.cwd(),
  286. hook_event_name: event,
  287. model,
  288. permission_mode: 'default',
  289. }
  290. }
  291. /** Base + turn_id, for the turn-scoped events (PreToolUse/PostToolUse/UserPromptSubmit/Stop). */
  292. function turnBase(agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  293. return { ...base(agent, event, model), turn_id: String(lastTurn(agent)) }
  294. }
  295. /** Extract a `command` string from a tool call's parsed arguments, else ''. */
  296. function commandOf(args: unknown): string {
  297. if (typeof args === 'object' && args !== null && 'command' in args) {
  298. const command: unknown = args.command
  299. if (typeof command === 'string') return command
  300. }
  301. return ''
  302. }
  303. function preToolPayload(exec: ToolExecution, model: string): Record<string, unknown> {
  304. // `tool_name` is the REAL tool name (matching the `exec.name` matcher subject);
  305. // a hardcoded constant would disagree with what the matcher tests and make a
  306. // config's tool matcher never fire. `tool_input` keeps Codex's `{ command }`
  307. // shape (its shell payload), derived from the call's `command` arg when present.
  308. return { ...turnBase(exec.agent, 'PreToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId }
  309. }
  310. function postToolPayload(exec: ToolExecution, result: ToolExecutionResult, model: string): Record<string, unknown> {
  311. return { ...turnBase(exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) }
  312. }