index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 { 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. 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 the cap BEFORE the config-file parse: a bad value must fail the
  74. // load loudly, not be skipped by the parse-failure 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. async function runPoint(
  97. point: string,
  98. matchQuery: string,
  99. payload: unknown,
  100. opts: { agent?: Agent; turn?: number; signal?: AbortSignal; plainStdoutAsContext?: boolean },
  101. ): Promise<MergedHookOutcome> {
  102. const groups: MatcherGroup[] = parsed[point] ?? []
  103. const outputs: HookOutput[] = []
  104. // Run the hook in the agent's session workspace (the `session/new` cwd), not
  105. // the executor default (the server launch dir) — a hook reading a relative
  106. // file or `pwd` must see the user's project tree. Absent for a no-agent run.
  107. const workdir = opts.agent?.session.header.cwd
  108. for (const group of groups) {
  109. // Codex matches with PURE regex (no literal fast path).
  110. if (!matchesMatcher(group.matcher, matchQuery, 'codex')) continue
  111. for (const hook of group.hooks) {
  112. const handlerId = nextHandlerId(point)
  113. const session = opts.agent?.session
  114. if (session && opts.turn !== undefined) {
  115. appendHookInvoked(session, {
  116. turn: opts.turn, point, dialect: 'codex', handlerId,
  117. ...group.matcher !== undefined ? { matcher: group.matcher } : {},
  118. })
  119. }
  120. const { output, durationMs } = await runHook(ctx.bash, hook, {
  121. payload,
  122. defaultTimeoutMs,
  123. ...workdir !== undefined ? { cwd: workdir } : {},
  124. ...opts.signal ? { signal: opts.signal } : {},
  125. trailingNewline: false, // Codex writes stdin WITHOUT a trailing newline.
  126. // Discard a `hookSpecificOutput` block naming a different event.
  127. expectedEventName: point,
  128. }, () => performance.now())
  129. // Codex's SessionStart/UserPromptSubmit treat a CLEAN hook's PLAIN
  130. // (non-JSON) stdout as additionalContext. The codec keeps that raw text on
  131. // `output.stdout` but only sets `additionalContext` from a JSON
  132. // `hookSpecificOutput`, so fold plain stdout in here and let the shared
  133. // merge + contextFrom path carry it. Gated exactly like the codec's own
  134. // structured-stdout parse: only on a clean `exitCode === 0` (a non-zero
  135. // exit is an error, not context — an `echo x; exit 2` must not inject
  136. // `x`), only when stdout is non-JSON (`!startsWith('{')` — a structured
  137. // hook's raw JSON is never dumped as prose), and never clobbering an
  138. // explicit additionalContext from a JSON block.
  139. if (opts.plainStdoutAsContext === true && output.exitCode === 0
  140. && output.additionalContext === undefined
  141. && output.stdout.length > 0 && !output.stdout.startsWith('{')) {
  142. output.additionalContext = output.stdout
  143. }
  144. outputs.push(output)
  145. if (output.systemMessage !== undefined) {
  146. ctx.logger.warn(`hooks-codex: ${point} hook emitted a systemMessage, which is not yet surfaced (ignored)`)
  147. }
  148. if (session && opts.turn !== undefined) {
  149. appendHookResult(session, { turn: opts.turn, point, handlerId, output, stderrSummaryMaxChars, durationMs })
  150. }
  151. }
  152. }
  153. return mergeHookOutputs(outputs)
  154. }
  155. // TODO(hook-continue-false): the merge computes `merged.stop`/`stopReason` from
  156. // a hook's `continue:false`, but no seam below honors it — there is no
  157. // "hard-halt the whole agent" primitive on the interception seams yet. Deferred
  158. // with the loop-guard work; until then a `continue:false` hook keeps its
  159. // per-point effect and the halt request is recorded in `hook/result`, not acted on.
  160. function contextFrom(merged: MergedHookOutcome): HookContext | 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. /**
  166. * Concatenate this bridge's {@link HookContext} (`ours`, always present at the
  167. * call sites) with a downstream listener's optional one, so folding our
  168. * additionalContext onto a delegated decision drops neither. The merged block
  169. * carries a single `source` — this bridge's — because a `HookContext` holds one
  170. * `MessageSource` and the seam cannot represent mixed provenance; the rendered
  171. * `context/message` only distinguishes by `source.kind` ('plugin'), so a
  172. * downstream plugin's text is still correctly framed as plugin context.
  173. */
  174. function concatContext(ours: HookContext, theirs: HookContext | undefined): HookContext {
  175. if (!theirs) return ours
  176. return { content: [...ours.content, ...theirs.content], source: ours.source }
  177. }
  178. // SessionStart: emit. Codex passes a plain-stdout hook's output as additionalContext.
  179. // TODO(session-start-gating): a synchronous emit + detached `.then`, so the
  180. // injected context is BEST-EFFORT — not guaranteed before the first turn reaches
  181. // the model (a slow hook can miss the first request). Gating is a deferred
  182. // loop-level change; the contract is "injected as soon as the hook resolves".
  183. ctx.on('agent/session-start', (agent, source) => {
  184. detached.track(runPoint('SessionStart', source, { ...base(agent, 'SessionStart', model), source }, { agent, plainStdoutAsContext: true, signal: detached.signal })
  185. .then((merged) => {
  186. const context = contextFrom(merged)
  187. if (context) agent.inject(context.content, { source: context.source })
  188. })
  189. .catch((error: unknown) => { ctx.logger.warn(`hooks-codex: SessionStart hook failed: ${String(error)}`) }))
  190. })
  191. // UserPromptSubmit → PromptDecision. Codex can only BLOCK (no allow/ask).
  192. ctx.on('agent/prompt-submit', async (agent, content, _source, next): Promise<PromptDecision> => {
  193. const turn = lastTurn(agent)
  194. const merged = await runPoint('UserPromptSubmit', '', { ...turnBase(agent, 'UserPromptSubmit', model), prompt: blocksToText(content) }, { agent, turn, plainStdoutAsContext: true })
  195. if (merged.decision === 'deny') return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' }
  196. // Context alone is not a veto: DELEGATE so a later prompt-submit listener can
  197. // still block/rewrite, then fold our context onto its decision.
  198. const downstream = await next()
  199. const ours = contextFrom(merged)
  200. if (!ours || downstream.kind !== 'allow') return downstream
  201. return {
  202. kind: 'allow',
  203. ...downstream.content !== undefined ? { content: downstream.content } : {},
  204. additionalContext: concatContext(ours, downstream.additionalContext),
  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(exec.agent)
  210. const merged = await runPoint('PreToolUse', exec.name, preToolPayload(exec, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, ...exec.signal ? { signal: exec.signal } : {} })
  211. if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' }
  212. return next()
  213. })
  214. // PostToolUse → PostToolDecision (block with feedback, or attach context).
  215. ctx.on('tools/post-execute', async (exec, result, next): Promise<PostToolDecision> => {
  216. const turn = lastTurn(exec.agent)
  217. const merged = await runPoint('PostToolUse', exec.name, postToolPayload(exec, result, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, ...exec.signal ? { signal: exec.signal } : {} })
  218. const context = contextFrom(merged)
  219. if (merged.decision === 'deny') {
  220. return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContext: context } : {} }
  221. }
  222. // Context alone is not a veto: DELEGATE, then fold our context onto the
  223. // downstream decision (a downstream block carries it too).
  224. const downstream = await next()
  225. if (!context) return downstream
  226. if (downstream.kind === 'block') {
  227. return { ...downstream, additionalContext: concatContext(context, downstream.additionalContext) }
  228. }
  229. return {
  230. kind: 'accept',
  231. ...downstream.content !== undefined ? { content: downstream.content } : {},
  232. additionalContext: concatContext(context, downstream.additionalContext),
  233. }
  234. })
  235. // Stop → ContinuationDecision. A blocking Stop hook forces continuation.
  236. // TODO(stop-loop-guard): like CC, a Stop hook that unconditionally blocks would
  237. // force-continue every step (`stop_hook_active` is always false here); the
  238. // loop-guard (stop_hook_active + a max-consecutive cap) is deferred.
  239. ctx.on('agent/turn-continuation', async (agent, turn, _default, next): Promise<ContinuationDecision> => {
  240. const merged = await runPoint('Stop', '', { ...turnBase(agent, 'Stop', model), stop_hook_active: false, last_assistant_message: null }, { agent, turn })
  241. if (merged.decision === 'deny') {
  242. // A blocking Stop hook forces continuation; a block with no reason (exit 2,
  243. // empty stderr) still forces it — fall back to a generic steering line
  244. // rather than letting the turn stop.
  245. const text = merged.reason ?? 'continue: blocked by Stop hook'
  246. return { action: 'continue', reason: { content: [{ type: 'text', text }], source: PLUGIN_SOURCE } }
  247. }
  248. return next()
  249. })
  250. }
  251. // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on
  252. // turn-scoped events. ---
  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 -- the `: 0` arm is a defensive fallback: when an agent is
  257. present, lastTurn is only called from the mid-turn seams, which always run
  258. inside an open turn, so `last` is always a turn/start here. */
  259. return last?.type === 'turn/start' ? last.data.turn : 0
  260. }
  261. function blocksToText(content: ContentBlock[]): string {
  262. return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
  263. }
  264. /** Base fields on every Codex payload (no turn_id). */
  265. function base(agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  266. return {
  267. session_id: agent?.session.header.id ?? '',
  268. transcript_path: null,
  269. cwd: agent?.session.header.cwd ?? process.cwd(),
  270. hook_event_name: event,
  271. model,
  272. permission_mode: 'default',
  273. }
  274. }
  275. /** Base + turn_id, for the turn-scoped events (PreToolUse/PostToolUse/UserPromptSubmit/Stop). */
  276. function turnBase(agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  277. return { ...base(agent, event, model), turn_id: String(lastTurn(agent)) }
  278. }
  279. /** Extract a `command` string from a tool call's parsed arguments, else ''. */
  280. function commandOf(args: unknown): string {
  281. if (typeof args === 'object' && args !== null && 'command' in args) {
  282. const command: unknown = args.command
  283. if (typeof command === 'string') return command
  284. }
  285. return ''
  286. }
  287. function preToolPayload(exec: ToolExecution, model: string): Record<string, unknown> {
  288. // `tool_name` is the REAL tool name (matching the `exec.name` matcher subject);
  289. // a hardcoded constant would disagree with what the matcher tests and make a
  290. // config's tool matcher never fire. `tool_input` keeps Codex's `{ command }`
  291. // shape (its shell payload), derived from the call's `command` arg when present.
  292. return { ...turnBase(exec.agent, 'PreToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId }
  293. }
  294. function postToolPayload(exec: ToolExecution, result: ToolExecutionResult, model: string): Record<string, unknown> {
  295. return { ...turnBase(exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) }
  296. }