index.ts 15 KB

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