index.ts 15 KB

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