index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /**
  2. * Bridge for unmodified Codex command hooks on harness interception seams. It
  3. * supports five points (SessionStart, prompt/tool pre/post, Stop), regex-only
  4. * matchers, snake_case payloads without a trailing newline, no hook environment
  5. * or command substitution, and no pre-tool approval or rewrite path; only
  6. * blocking decisions are honored. Shared execution and parsing live in
  7. * `dsh-hook-protocol`; see the
  8. * [hook-bridges Agent Note](../../../../.agents/notes/implemented/feature/2026-06-30-hook-bridges.md).
  9. * @module @deepseek-ai/dsh-hooks-codex
  10. */
  11. // Each dialect bridge keeps its complete dependency list visible at the entry
  12. // point; a cross-package facade for imports alone would add indirection.
  13. /* jscpd:ignore-start */
  14. import { readFileSync } from 'node:fs'
  15. import type { Context } from 'cordis'
  16. import z from 'schemastery'
  17. import type { Agent, PromptDecision } from '@deepseek-ai/dsh-agent'
  18. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  19. import type { UserMessageData } from '@deepseek-ai/dsh-session'
  20. import type {} from '@deepseek-ai/dsh-session-persistence'
  21. import type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  22. import {
  23. appendHookInvoked,
  24. appendHookResult,
  25. createDetachedRuns,
  26. DEFAULT_HOOK_TIMEOUT_MS,
  27. DEFAULT_STDERR_SUMMARY_MAX_CHARS,
  28. matchesMatcher,
  29. mergeHookOutputs,
  30. runHook,
  31. type HookOutput,
  32. type MatcherGroup,
  33. type MergedHookOutcome,
  34. } from '@deepseek-ai/dsh-hook-protocol'
  35. import { parseCodexConfig, type CodexHookConfig } from './config.ts'
  36. /* jscpd:ignore-end */
  37. export const name = 'hooks-codex'
  38. export const inject = ['bash']
  39. /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */
  40. export interface Config {
  41. /**
  42. * Path to a Codex `hooks.json`. Process-level: read once at load, a relative
  43. * path resolves against the process launch cwd.
  44. * TODO(per-session-hook-config): per-session project-local discovery from each
  45. * `session/new.cwd` is not yet implemented.
  46. */
  47. configPath: string
  48. /** The model name stamped on every payload (Codex includes `model` on each event). */
  49. model?: string
  50. /** Default per-hook timeout in ms when a hook sets none (Codex default: 600000). */
  51. defaultTimeoutMs?: number
  52. /** Character cap for the `hook/result` event's persisted stderr summary. */
  53. stderrSummaryMaxChars?: number
  54. }
  55. export const Config: z<Config> = z.object({
  56. configPath: z.string().required(),
  57. model: z.string().default(''),
  58. defaultTimeoutMs: z.number().default(DEFAULT_HOOK_TIMEOUT_MS),
  59. stderrSummaryMaxChars: z.number().default(DEFAULT_STDERR_SUMMARY_MAX_CHARS),
  60. })
  61. let handlerCounter = 0
  62. function nextHandlerId(point: string): string {
  63. return `codex:${point}:${++handlerCounter}`
  64. }
  65. const PLUGIN_SOURCE: MessageSource = { kind: 'plugin', plugin: 'hooks-codex' }
  66. /** The summary cap bounds a persisted event field — a positive integer or the slice misbehaves silently. */
  67. function assertPositiveInteger(name: string, value: number): void {
  68. if (!Number.isInteger(value) || value < 1) {
  69. throw new Error(`hooks-codex: ${name} must be a positive integer`)
  70. }
  71. }
  72. export function apply(ctx: Context, config: Config): void {
  73. // Validate before config parsing so a bad value cannot be hidden by its early return.
  74. const stderrSummaryMaxChars = config.stderrSummaryMaxChars ?? DEFAULT_STDERR_SUMMARY_MAX_CHARS
  75. assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
  76. const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
  77. let parsed: CodexHookConfig = {}
  78. try {
  79. const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
  80. const result = parseCodexConfig(raw)
  81. parsed = result.config
  82. for (const s of result.skipped) {
  83. ctx.logger.warn(`hooks-codex: skipping ${s.reason} on ${s.event} (only sync command hooks run)`)
  84. }
  85. } catch (error: unknown) {
  86. ctx.logger.warn(`hooks-codex: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
  87. return
  88. }
  89. const model = config.model ?? ''
  90. // SessionStart is the one emit-shaped (detached) point Codex has: track its
  91. // run chains so disposal aborts a still-running hook process and drains the
  92. // continuation (docs/defensive-patterns.md: dispose must reach quiescence).
  93. const detached = createDetachedRuns()
  94. ctx.effect(() => () => detached.drain(), 'hooks-codex: drain detached hook runs')
  95. /**
  96. * Run and fold one configured Codex hook point.
  97. *
  98. * A supplied turn records the hook provenance pair inside that open turn.
  99. * Pre-turn `UserPromptSubmit` and detached lifecycle points omit it.
  100. */
  101. async function runPoint(
  102. point: string,
  103. matchQuery: string,
  104. payload: unknown,
  105. opts: {
  106. agent?: Agent
  107. turn?: number
  108. readonly signal: AbortSignal
  109. plainStdoutAsContext?: boolean
  110. },
  111. ): Promise<MergedHookOutcome> {
  112. const groups: MatcherGroup[] = parsed[point] ?? []
  113. const outputs: HookOutput[] = []
  114. // Run hooks in the agent's session workspace so relative paths address the
  115. // user's project rather than the server launch directory.
  116. const workdir = opts.agent?.session.header.cwd
  117. for (const group of groups) {
  118. // Codex always interprets matchers as regexes; it has no literal fast path.
  119. if (!matchesMatcher(group.matcher, matchQuery, 'codex')) continue
  120. for (const hook of group.hooks) {
  121. const handlerId = nextHandlerId(point)
  122. const session = opts.agent?.session
  123. if (session && opts.turn !== undefined) {
  124. appendHookInvoked(session, {
  125. turn: opts.turn, point, dialect: 'codex', handlerId,
  126. ...group.matcher !== undefined ? { matcher: group.matcher } : {},
  127. })
  128. }
  129. const { output, durationMs } = await runHook(ctx.bash, hook, {
  130. payload,
  131. defaultTimeoutMs,
  132. ...workdir !== undefined ? { cwd: workdir } : {},
  133. signal: opts.signal,
  134. trailingNewline: false, // Codex writes stdin without a trailing newline.
  135. // Discard a `hookSpecificOutput` block naming a different event.
  136. expectedEventName: point,
  137. }, () => performance.now())
  138. // Clean plain stdout becomes context only when no structured context
  139. // exists; nonzero output and raw JSON never leak as prose.
  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. // Execution and decision mapping remain in each bridge so dialect
  147. // differences stay explicit at their owning seam.
  148. /* jscpd:ignore-start */
  149. if (output.systemMessage !== undefined) {
  150. ctx.logger.warn(`hooks-codex: ${point} hook emitted a systemMessage, which is not yet surfaced (ignored)`)
  151. }
  152. if (session && opts.turn !== undefined) {
  153. appendHookResult(session, { turn: opts.turn, point, handlerId, output, stderrSummaryMaxChars, durationMs })
  154. }
  155. }
  156. }
  157. return mergeHookOutputs(outputs)
  158. }
  159. // TODO(hook-continue-false): `merged.stop` is logged but needs a run-level halt seam.
  160. function contextFrom(merged: MergedHookOutcome): UserMessageData | undefined {
  161. if (merged.additionalContext.length === 0) return undefined
  162. const content: ContentBlock[] = merged.additionalContext.map(text => ({ type: 'text', text }))
  163. return { content, source: PLUGIN_SOURCE }
  164. }
  165. /** Prepend one context without flattening downstream provenance or metadata. */
  166. function prependContext(ours: UserMessageData, theirs: UserMessageData[] | undefined): UserMessageData[] {
  167. return [ours, ...theirs ?? []]
  168. }
  169. // SessionStart injects plain stdout when its detached hook resolves; a slow
  170. // hook may miss the first request.
  171. // TODO(session-start-gating): add a startup gate before promising first-turn delivery.
  172. ctx.on('agent/session-start', (agent, source) => {
  173. detached.track(runPoint('SessionStart', source, { ...base(ctx, agent, 'SessionStart', model), source }, { agent, plainStdoutAsContext: true, signal: detached.signal })
  174. .then((merged) => {
  175. const context = contextFrom(merged)
  176. if (context) agent.inject({ content: context.content, source: context.source })
  177. })
  178. .catch((error: unknown) => { ctx.logger.warn(`hooks-codex: SessionStart hook failed: ${String(error)}`) }))
  179. /* jscpd:ignore-end */
  180. })
  181. // UserPromptSubmit → PromptDecision. Codex supports block, not allow or ask.
  182. ctx.on('agent/prompt-submit', async (agent, content, _source, signal, next): Promise<PromptDecision> => {
  183. const payload = {
  184. ...base(ctx, agent, 'UserPromptSubmit', model),
  185. turn_id: String(lastTurn(agent) + 1),
  186. prompt: blocksToText(content),
  187. }
  188. const merged = await runPoint('UserPromptSubmit', '', payload, { agent, plainStdoutAsContext: true, signal })
  189. /* jscpd:ignore-start */
  190. if (merged.decision === 'deny') return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' }
  191. // Context alone is not a veto: DELEGATE so a later prompt-submit listener can
  192. // still block/rewrite, then fold our context onto its decision.
  193. const downstream = await next()
  194. const ours = contextFrom(merged)
  195. if (!ours || downstream.kind !== 'allow') return downstream
  196. return {
  197. kind: 'allow',
  198. ...downstream.content !== undefined ? { content: downstream.content } : {},
  199. additionalContexts: prependContext(ours, downstream.additionalContexts),
  200. }
  201. })
  202. // PreToolUse → PreToolDecision. Codex blocks only (no allow/ask honored).
  203. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  204. const turn = lastTurn(exec.agent)
  205. const merged = await runPoint('PreToolUse', exec.name, preToolPayload(ctx, exec, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  206. /* jscpd:ignore-end */
  207. if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' }
  208. return next()
  209. })
  210. // PostToolUse → PostToolDecision (block with feedback, or attach context).
  211. ctx.on('tools/post-execute', async (exec, result, next): Promise<PostToolDecision> => {
  212. const turn = lastTurn(exec.agent)
  213. /* jscpd:ignore-start */
  214. const merged = await runPoint('PostToolUse', exec.name, postToolPayload(ctx, exec, result, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  215. const context = contextFrom(merged)
  216. if (merged.decision === 'deny') {
  217. return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContexts: [context] } : {} }
  218. }
  219. // Context alone is not a veto: DELEGATE, then fold our context onto the
  220. // downstream decision (a downstream block carries it too).
  221. const downstream = await next()
  222. if (!context) return downstream
  223. if (downstream.kind === 'block') {
  224. return { ...downstream, additionalContexts: prependContext(context, downstream.additionalContexts) }
  225. }
  226. return {
  227. ...downstream,
  228. additionalContexts: prependContext(context, downstream.additionalContexts),
  229. }
  230. })
  231. // A blocking Stop hook steers at the stopping boundary, which makes the
  232. // machine observe pending input and run another step.
  233. // TODO(stop-loop-guard): Codex supplies `stop_hook_active` so a Stop hook can
  234. // avoid continuing the same turn indefinitely. It is always false here, so an
  235. // unconditionally blocking hook force-continues every step until it self-limits.
  236. ctx.on('agent/turn-stopping', async (agent, turn, signal): Promise<void> => {
  237. const merged = await runPoint('Stop', '', { ...turnBase(ctx, agent, 'Stop', model), stop_hook_active: false, last_assistant_message: null }, { agent, turn, signal })
  238. /* jscpd:ignore-end */
  239. if (merged.decision === 'deny') {
  240. // A blocking Stop hook forces continuation; a block with no reason (exit 2,
  241. // empty stderr) still forces it — fall back to a generic steering line
  242. // rather than letting the turn stop.
  243. const text = merged.reason ?? 'continue: blocked by Stop hook'
  244. agent.steer({ content: [{ type: 'text', text }], source: PLUGIN_SOURCE })
  245. }
  246. })
  247. }
  248. // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on
  249. // turn-scoped events. ---
  250. // These small payload helpers intentionally remain next to the dialect shape;
  251. // sharing them would pull bridge-only agent/LLM dependencies into hook-protocol.
  252. /* jscpd:ignore-start */
  253. function lastTurn(agent: Agent | undefined): number {
  254. if (!agent) return 0
  255. const last = [...agent.session.events].findLast(e => e.type === 'turn/start')
  256. /* v8 ignore next -- agent-present turnBase callers are tool/stop seams inside an open turn. */
  257. return last?.type === 'turn/start' ? last.data.turn : 0
  258. }
  259. function blocksToText(content: ContentBlock[]): string {
  260. return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
  261. }
  262. /* jscpd:ignore-end */
  263. /** Base fields on every Codex payload (no turn_id). */
  264. function base(ctx: Context, agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  265. return {
  266. session_id: agent?.session.header.id ?? '',
  267. transcript_path: agent === undefined
  268. ? null
  269. : ctx.get('sessionPersistence')?.locate(agent.session.header)?.path ?? null,
  270. cwd: agent?.session.header.cwd ?? process.cwd(),
  271. hook_event_name: event,
  272. model,
  273. permission_mode: 'default',
  274. }
  275. }
  276. /** Base + turn_id, for the turn-scoped events (PreToolUse/PostToolUse/UserPromptSubmit/Stop). */
  277. function turnBase(ctx: Context, agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  278. return { ...base(ctx, agent, event, model), turn_id: String(lastTurn(agent)) }
  279. }
  280. /** Extract a `command` string from a tool call's parsed arguments, else ''. */
  281. function commandOf(args: unknown): string {
  282. if (typeof args === 'object' && args !== null && 'command' in args) {
  283. const command: unknown = args.command
  284. if (typeof command === 'string') return command
  285. }
  286. return ''
  287. }
  288. function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Record<string, unknown> {
  289. // `tool_name` is the REAL tool name (matching the `exec.name` matcher subject);
  290. // a hardcoded constant would disagree with what the matcher tests and make a
  291. // config's tool matcher never fire. `tool_input` keeps Codex's `{ command }`
  292. // shape (its shell payload), derived from the call's `command` arg when present.
  293. return { ...turnBase(ctx, exec.agent, 'PreToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId }
  294. }
  295. function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record<string, unknown> {
  296. 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) }
  297. }