index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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`.
  8. * @module @deepseek-ai/dsh-hooks-codex
  9. */
  10. // Each dialect bridge keeps its complete dependency list visible at the entry
  11. // point; a cross-package facade for imports alone would add indirection.
  12. /* jscpd:ignore-start */
  13. import { readFileSync } from 'node:fs'
  14. import type { Context } from '@deepseek-ai/cordis'
  15. import z from '@deepseek-ai/schemastery'
  16. import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
  17. import type {} from '@deepseek-ai/dsh-session-projection'
  18. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  19. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  20. import type { UserMessage } from '@deepseek-ai/dsh-session'
  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 = ['shell', 'sessionProjections']
  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`.
  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 invocation/result pair inside that open turn.
  99. * 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.shell, 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 extension point.
  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 mechanism.
  160. function contextFrom(merged: MergedHookOutcome): UserMessage | undefined {
  161. if (merged.additionalContext.length === 0) return undefined
  162. const content: ContentBlock[] = merged.additionalContext.map(text => ({ type: 'text', text }))
  163. return createUserMessage({ content, source: PLUGIN_SOURCE })
  164. }
  165. /** Prepend one context without flattening source fields or other downstream metadata. */
  166. function prependContext(ours: UserMessage, theirs: UserMessage[] | undefined): UserMessage[] {
  167. return [ours, ...theirs ?? []]
  168. }
  169. ctx.on('agent/created', async ({ agent, source, signal }) => {
  170. const ownerSignal = signal === undefined ? detached.signal : AbortSignal.any([signal, detached.signal])
  171. const run = runPoint('SessionStart', source, { ...base(agent, 'SessionStart', model), source }, { agent, plainStdoutAsContext: true, signal: ownerSignal })
  172. .then((merged) => {
  173. const context = contextFrom(merged)
  174. if (context) agent.inject(context)
  175. })
  176. .catch((error: unknown) => { ctx.logger.warn(`hooks-codex: SessionStart hook failed: ${String(error)}`) })
  177. detached.track(run)
  178. await run
  179. /* jscpd:ignore-end */
  180. })
  181. // UserPromptSubmit → PreStepDecision. Codex supports reject, not rewrite or ask.
  182. ctx.on('agent/pre-step', async ({ agent, messages, turn, signal }, next): Promise<PreStepDecision> => {
  183. if (messages.length === 0) return next()
  184. const payload = {
  185. ...base(agent, 'UserPromptSubmit', model),
  186. turn_id: String(turn),
  187. prompt: blocksToText(messages.flatMap(message => message.content)),
  188. }
  189. const merged = await runPoint('UserPromptSubmit', '', payload, {
  190. agent, turn, plainStdoutAsContext: true, signal,
  191. })
  192. /* jscpd:ignore-start */
  193. if (merged.decision === 'deny') {
  194. return { kind: 'reject' }
  195. }
  196. // Context alone is not a veto: DELEGATE so a later pre-step listener can
  197. // still reject/rewrite, then fold our context onto its decision.
  198. const downstream = await next()
  199. const ours = contextFrom(merged)
  200. if (!ours || downstream.kind !== 'enter') return downstream
  201. return {
  202. ...downstream,
  203. messages: [...downstream.messages, ours],
  204. }
  205. })
  206. // PreToolUse → PreToolDecision. Codex blocks only (no allow/ask honored).
  207. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  208. const turn = lastTurn(ctx, exec.agent)
  209. const merged = await runPoint('PreToolUse', exec.name, preToolPayload(ctx, exec, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  210. /* jscpd:ignore-end */
  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(ctx, exec.agent)
  217. /* jscpd:ignore-start */
  218. const merged = await runPoint('PostToolUse', exec.name, postToolPayload(ctx, exec, result, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  219. const context = contextFrom(merged)
  220. if (merged.decision === 'deny') {
  221. return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContexts: [context] } : {} }
  222. }
  223. // Context alone is not a veto: DELEGATE, then fold our context onto the
  224. // downstream decision (a downstream block carries it too).
  225. const downstream = await next()
  226. if (!context) return downstream
  227. if (downstream.kind === 'block') {
  228. return { ...downstream, additionalContexts: prependContext(context, downstream.additionalContexts) }
  229. }
  230. return {
  231. ...downstream,
  232. additionalContexts: prependContext(context, downstream.additionalContexts),
  233. }
  234. })
  235. // A blocking Stop hook steers at the stopping boundary, which makes the
  236. // machine observe pending input and run another step.
  237. // TODO(stop-loop-guard): Codex supplies `stop_hook_active` so a Stop hook can
  238. // avoid continuing the same turn indefinitely. It is always false here, so an
  239. // unconditionally blocking hook force-continues every step until it self-limits.
  240. ctx.on('agent/turn-stopping', async ({ agent, turn, signal }): Promise<void> => {
  241. const merged = await runPoint('Stop', '', { ...turnBase(ctx, agent, 'Stop', model), stop_hook_active: false, last_assistant_message: null }, { agent, turn, signal })
  242. /* jscpd:ignore-end */
  243. if (merged.decision === 'deny') {
  244. // A blocking Stop hook forces continuation; a block with no reason (exit 2,
  245. // empty stderr) still forces it — fall back to a generic steering line
  246. // rather than letting the turn stop.
  247. const text = merged.reason ?? 'continue: blocked by Stop hook'
  248. agent.steer(createUserMessage({ content: [{ type: 'text', text }], source: PLUGIN_SOURCE }))
  249. }
  250. })
  251. }
  252. // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on
  253. // turn-scoped events. ---
  254. // These small payload helpers intentionally remain next to the dialect shape;
  255. // sharing them would pull bridge-only agent/LLM dependencies into hook-protocol.
  256. /* jscpd:ignore-start */
  257. function lastTurn(ctx: Context, agent: Agent | undefined): number {
  258. if (!agent) return 0
  259. /* v8 ignore next -- agent-present hook points run inside AgentLoop, which owns this projection. */
  260. return ctx.sessionProjections.stateOf(agent.session, 'turnBoundary')?.lastTurn ?? 0
  261. }
  262. function blocksToText(content: ContentBlock[]): string {
  263. return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
  264. }
  265. /* jscpd:ignore-end */
  266. /** Base fields on every Codex payload (no turn_id). */
  267. function base(agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  268. return {
  269. session_id: agent?.session.header.id ?? '',
  270. // The persistence seam exposes no artifact path; the field stays null
  271. // (a durable consumer gap recorded in this package's README).
  272. transcript_path: null,
  273. cwd: agent?.session.header.cwd ?? process.cwd(),
  274. hook_event_name: event,
  275. model,
  276. permission_mode: 'default',
  277. }
  278. }
  279. /** Base + turn_id, for the turn-scoped events (PreToolUse/PostToolUse/UserPromptSubmit/Stop). */
  280. function turnBase(ctx: Context, agent: Agent | undefined, event: string, model: string): Record<string, unknown> {
  281. return { ...base(agent, event, model), turn_id: String(lastTurn(ctx, agent)) }
  282. }
  283. /** Extract a `command` string from a tool call's parsed arguments, else ''. */
  284. function commandOf(args: unknown): string {
  285. if (typeof args === 'object' && args !== null && 'command' in args) {
  286. const command: unknown = args.command
  287. if (typeof command === 'string') return command
  288. }
  289. return ''
  290. }
  291. function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Record<string, unknown> {
  292. // `tool_name` is the REAL tool name (matching the `exec.name` matcher subject);
  293. // a hardcoded constant would disagree with what the matcher tests and make a
  294. // config's tool matcher never fire. `tool_input` keeps Codex's `{ command }`
  295. // shape (its shell payload), derived from the call's `command` arg when present.
  296. return { ...turnBase(ctx, exec.agent, 'PreToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId }
  297. }
  298. function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record<string, unknown> {
  299. 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) }
  300. }