index.ts 16 KB

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