index.ts 17 KB

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