index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  23. import {
  24. appendHookInvoked,
  25. appendHookResult,
  26. createDetachedRuns,
  27. DEFAULT_HOOK_TIMEOUT_MS,
  28. DEFAULT_STDERR_SUMMARY_MAX_CHARS,
  29. matchesMatcher,
  30. mergeHookOutputs,
  31. runHook,
  32. type HookOutput,
  33. type MatcherGroup,
  34. type MergedHookOutcome,
  35. } from '@deepseek-ai/dsh-hook-protocol'
  36. import { parseCodexConfig, type CodexHookConfig } from './config.ts'
  37. /* jscpd:ignore-end */
  38. export const name = 'hooks-codex'
  39. export const inject = ['shell', 'sessionProjections']
  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`.
  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 before config parsing so a bad value cannot be hidden by its early return.
  75. const stderrSummaryMaxChars = config.stderrSummaryMaxChars ?? DEFAULT_STDERR_SUMMARY_MAX_CHARS
  76. assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
  77. const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
  78. let parsed: CodexHookConfig = {}
  79. try {
  80. const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
  81. const result = parseCodexConfig(raw)
  82. parsed = result.config
  83. for (const s of result.skipped) {
  84. ctx.logger.warn(`hooks-codex: skipping ${s.reason} on ${s.event} (only sync command hooks run)`)
  85. }
  86. } catch (error: unknown) {
  87. ctx.logger.warn(`hooks-codex: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
  88. return
  89. }
  90. const model = config.model ?? ''
  91. // SessionStart is the one emit-shaped (detached) point Codex has: track its
  92. // run chains so disposal aborts a still-running hook process and drains the
  93. // continuation (docs/defensive-patterns.md: dispose must reach quiescence).
  94. const detached = createDetachedRuns()
  95. ctx.effect(() => () => detached.drain(), 'hooks-codex: drain detached hook runs')
  96. /**
  97. * Run and fold one configured Codex hook point.
  98. *
  99. * A supplied turn records the hook invocation/result pair inside that open turn.
  100. * Detached lifecycle points omit it.
  101. */
  102. async function runPoint(
  103. point: string,
  104. matchQuery: string,
  105. payload: unknown,
  106. opts: {
  107. agent?: Agent
  108. turn?: number
  109. readonly signal: AbortSignal
  110. plainStdoutAsContext?: boolean
  111. },
  112. ): Promise<MergedHookOutcome> {
  113. const groups: MatcherGroup[] = parsed[point] ?? []
  114. const outputs: HookOutput[] = []
  115. // Run hooks in the agent's session workspace so relative paths address the
  116. // user's project rather than the server launch directory.
  117. const workdir = opts.agent?.session.header.cwd
  118. for (const group of groups) {
  119. // Codex always interprets matchers as regexes; it has no literal fast path.
  120. if (!matchesMatcher(group.matcher, matchQuery, 'codex')) continue
  121. for (const hook of group.hooks) {
  122. const handlerId = nextHandlerId(point)
  123. const session = opts.agent?.session
  124. if (session && opts.turn !== undefined) {
  125. appendHookInvoked(session, {
  126. turn: opts.turn, point, dialect: 'codex', handlerId,
  127. ...group.matcher !== undefined ? { matcher: group.matcher } : {},
  128. })
  129. }
  130. const { output, durationMs } = await runHook(ctx.shell, hook, {
  131. payload,
  132. defaultTimeoutMs,
  133. ...workdir !== undefined ? { cwd: workdir } : {},
  134. signal: opts.signal,
  135. trailingNewline: false, // Codex writes stdin without a trailing newline.
  136. // Discard a `hookSpecificOutput` block naming a different event.
  137. expectedEventName: point,
  138. }, () => performance.now())
  139. // Clean plain stdout becomes context only when no structured context
  140. // exists; nonzero output and raw JSON never leak as prose.
  141. if (opts.plainStdoutAsContext === true && output.exitCode === 0
  142. && output.additionalContext === undefined
  143. && output.stdout.length > 0 && !output.stdout.startsWith('{')) {
  144. output.additionalContext = output.stdout
  145. }
  146. outputs.push(output)
  147. // Execution and decision mapping remain in each bridge so dialect
  148. // differences stay explicit at their owning extension point.
  149. /* jscpd:ignore-start */
  150. if (output.systemMessage !== undefined) {
  151. ctx.logger.warn(`hooks-codex: ${point} hook emitted a systemMessage, which is not yet surfaced (ignored)`)
  152. }
  153. if (session && opts.turn !== undefined) {
  154. appendHookResult(session, { turn: opts.turn, point, handlerId, output, stderrSummaryMaxChars, durationMs })
  155. }
  156. }
  157. }
  158. return mergeHookOutputs(outputs)
  159. }
  160. // TODO(hook-continue-false): `merged.stop` is logged but needs a run-level halt mechanism.
  161. function contextFrom(merged: MergedHookOutcome): UserMessage | undefined {
  162. if (merged.additionalContext.length === 0) return undefined
  163. const content: ContentBlock[] = merged.additionalContext.map(text => ({ type: 'text', text }))
  164. return createUserMessage({ content, source: PLUGIN_SOURCE })
  165. }
  166. /** Prepend one context without flattening source fields or other downstream metadata. */
  167. function prependContext(ours: UserMessage, theirs: UserMessage[] | undefined): UserMessage[] {
  168. return [ours, ...theirs ?? []]
  169. }
  170. // SessionStart injects plain stdout when its detached hook resolves; a slow
  171. // hook may miss the first request.
  172. // TODO(session-start-gating): add a startup gate before promising first-turn delivery.
  173. ctx.on('agent/session-start', ({ agent, source }) => {
  174. detached.track(runPoint('SessionStart', source, { ...base(agent, 'SessionStart', model), source }, { agent, plainStdoutAsContext: true, signal: detached.signal })
  175. .then((merged) => {
  176. const context = contextFrom(merged)
  177. if (context) agent.inject(context)
  178. })
  179. .catch((error: unknown) => { ctx.logger.warn(`hooks-codex: SessionStart hook failed: ${String(error)}`) }))
  180. /* jscpd:ignore-end */
  181. })
  182. // UserPromptSubmit → PreStepDecision. Codex supports reject, not rewrite or ask.
  183. ctx.on('agent/pre-step', async ({ agent, messages, turn, signal }, next): Promise<PreStepDecision> => {
  184. if (messages.length === 0) return next()
  185. const payload = {
  186. ...base(agent, 'UserPromptSubmit', model),
  187. turn_id: String(turn),
  188. prompt: blocksToText(messages.flatMap(message => message.content)),
  189. }
  190. const merged = await runPoint('UserPromptSubmit', '', payload, {
  191. agent, turn, plainStdoutAsContext: true, signal,
  192. })
  193. /* jscpd:ignore-start */
  194. if (merged.decision === 'deny') {
  195. return { kind: 'reject' }
  196. }
  197. // Context alone is not a veto: DELEGATE so a later pre-step listener can
  198. // still reject/rewrite, then fold our context onto its decision.
  199. const downstream = await next()
  200. const ours = contextFrom(merged)
  201. if (!ours || downstream.kind !== 'enter') return downstream
  202. return {
  203. ...downstream,
  204. messages: [...downstream.messages, ours],
  205. }
  206. })
  207. // PreToolUse → PreToolDecision. Codex blocks only (no allow/ask honored).
  208. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  209. const turn = lastTurn(ctx, exec.agent)
  210. const merged = await runPoint('PreToolUse', exec.name, preToolPayload(ctx, exec, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  211. /* jscpd:ignore-end */
  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(ctx, exec.agent)
  218. /* jscpd:ignore-start */
  219. const merged = await runPoint('PostToolUse', exec.name, postToolPayload(ctx, exec, result, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  220. const context = contextFrom(merged)
  221. if (merged.decision === 'deny') {
  222. return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContexts: [context] } : {} }
  223. }
  224. // Context alone is not a veto: DELEGATE, then fold our context onto the
  225. // downstream decision (a downstream block carries it too).
  226. const downstream = await next()
  227. if (!context) return downstream
  228. if (downstream.kind === 'block') {
  229. return { ...downstream, additionalContexts: prependContext(context, downstream.additionalContexts) }
  230. }
  231. return {
  232. ...downstream,
  233. additionalContexts: prependContext(context, downstream.additionalContexts),
  234. }
  235. })
  236. // A blocking Stop hook steers at the stopping boundary, which makes the
  237. // machine observe pending input and run another step.
  238. // TODO(stop-loop-guard): Codex supplies `stop_hook_active` so a Stop hook can
  239. // avoid continuing the same turn indefinitely. It is always false here, so an
  240. // unconditionally blocking hook force-continues every step until it self-limits.
  241. ctx.on('agent/turn-stopping', async ({ agent, turn, signal }): Promise<void> => {
  242. const merged = await runPoint('Stop', '', { ...turnBase(ctx, agent, 'Stop', model), stop_hook_active: false, last_assistant_message: null }, { agent, turn, signal })
  243. /* jscpd:ignore-end */
  244. if (merged.decision === 'deny') {
  245. // A blocking Stop hook forces continuation; a block with no reason (exit 2,
  246. // empty stderr) still forces it — fall back to a generic steering line
  247. // rather than letting the turn stop.
  248. const text = merged.reason ?? 'continue: blocked by Stop hook'
  249. agent.steer(createUserMessage({ content: [{ type: 'text', text }], source: PLUGIN_SOURCE }))
  250. }
  251. })
  252. }
  253. // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on
  254. // turn-scoped events. ---
  255. // These small payload helpers intentionally remain next to the dialect shape;
  256. // sharing them would pull bridge-only agent/LLM dependencies into hook-protocol.
  257. /* jscpd:ignore-start */
  258. function lastTurn(ctx: Context, agent: Agent | undefined): number {
  259. if (!agent) return 0
  260. /* v8 ignore next -- agent-present hook points run inside AgentLoop, which owns this projection. */
  261. return ctx.sessionProjections.stateOf(agent.session, 'turnBoundary')?.lastTurn ?? 0
  262. }
  263. function blocksToText(content: ContentBlock[]): string {
  264. return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
  265. }
  266. /* jscpd:ignore-end */
  267. /** Base fields on every Codex payload (no turn_id). */
  268. function base(agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  269. return {
  270. session_id: agent?.session.header.id ?? '',
  271. // The persistence seam exposes no artifact path; the field stays null
  272. // (a durable consumer gap recorded in this package's README).
  273. transcript_path: null,
  274. cwd: agent?.session.header.cwd ?? process.cwd(),
  275. hook_event_name: event,
  276. model,
  277. permission_mode: 'default',
  278. }
  279. }
  280. /** Base + turn_id, for the turn-scoped events (PreToolUse/PostToolUse/UserPromptSubmit/Stop). */
  281. function turnBase(ctx: Context, agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  282. return { ...base(agent, event, model), turn_id: String(lastTurn(ctx, agent)) }
  283. }
  284. /** Extract a `command` string from a tool call's parsed arguments, else ''. */
  285. function commandOf(args: unknown): string {
  286. if (typeof args === 'object' && args !== null && 'command' in args) {
  287. const command: unknown = args.command
  288. if (typeof command === 'string') return command
  289. }
  290. return ''
  291. }
  292. function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Record<string, unknown> {
  293. // `tool_name` is the REAL tool name (matching the `exec.name` matcher subject);
  294. // a hardcoded constant would disagree with what the matcher tests and make a
  295. // config's tool matcher never fire. `tool_input` keeps Codex's `{ command }`
  296. // shape (its shell payload), derived from the call's `command` arg when present.
  297. return { ...turnBase(ctx, exec.agent, 'PreToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId }
  298. }
  299. function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record<string, unknown> {
  300. 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) }
  301. }