index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /**
  2. * Bridge for unmodified Claude Code command hooks on harness interception
  3. * extension points. It supports SessionStart, prompt/tool pre/post, Stop, and subagent
  4. * start/stop. It owns Claude payloads, environment, substitution, and decision
  5. * mapping; shared execution and parsing live in `dsh-hook-protocol`.
  6. * `updatedInput` is logged and warned but not honored. Bespoke behavior should
  7. * use typed native plugins on the same extension points; see the
  8. * [hook-bridges Agent Note](../../../../.agents/notes/implemented/feature/2026-06-30-hook-bridges.md).
  9. * @module @deepseek-ai/dsh-hooks-claude-code
  10. */
  11. import { readFileSync } from 'node:fs'
  12. import type { Context } from '@deepseek-ai/cordis'
  13. import z from '@deepseek-ai/schemastery'
  14. import type { Agent, PreStepDecision, TurnBoundaryProjection } from '@deepseek-ai/dsh-agent'
  15. import type {} from '@deepseek-ai/dsh-session-projection'
  16. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  17. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  18. import type { UserMessage } from '@deepseek-ai/dsh-session'
  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. // Pulls in the declaration-merged subagent events and the identity pairing their
  35. // start/end edges.
  36. import type { SubagentRunId } from '@deepseek-ai/dsh-subagent'
  37. import { parseClaudeCodeConfig, type ClaudeCodeHookConfig } from './config.ts'
  38. export const name = 'hooks-claude-code'
  39. // `shell` runs hooks and `sessionProjections` supplies turn numbers; the rest
  40. // are read opportunistically via ctx.get so a deployment can omit them.
  41. export const inject = ['shell', 'sessionProjections']
  42. /** Plugin config: where the CC hook config lives + substitution roots. */
  43. export interface Config {
  44. /**
  45. * Path to a `hooks.json` or a settings file whose `hooks` key holds the config.
  46. * Process-level: read once at load, a relative path resolves against the process
  47. * launch cwd, so one config applies to the whole process.
  48. * TODO(per-session-hook-config): per-session discovery of a project-local
  49. * `hooks.json` from each `session/new.cwd`.
  50. */
  51. configPath: string
  52. /**
  53. * Replaces `${CLAUDE_PLUGIN_ROOT}` in command strings (the plugin's root dir).
  54. */
  55. pluginRoot?: string
  56. /**
  57. * Replaces `${CLAUDE_PROJECT_DIR}` in command strings AND is exported as the
  58. * `CLAUDE_PROJECT_DIR` env var for hook processes. When omitted, the env var
  59. * defaults per-run to the agent's session workspace (`session.header.cwd`, the
  60. * same dir the hook runs in) — Claude Code always exports this var, and common
  61. * unmodified hooks reference `$CLAUDE_PROJECT_DIR` for project-relative paths.
  62. */
  63. projectDir?: string
  64. /** Default per-hook timeout in ms when a hook sets none (CC default: 600000). */
  65. defaultTimeoutMs?: number
  66. /** Character cap for the `hook/result` event's persisted stderr summary. */
  67. stderrSummaryMaxChars?: number
  68. }
  69. export const Config: z<Config> = z.object({
  70. configPath: z.string().required(),
  71. pluginRoot: z.string(),
  72. projectDir: z.string(),
  73. defaultTimeoutMs: z.number().default(DEFAULT_HOOK_TIMEOUT_MS),
  74. stderrSummaryMaxChars: z.number().default(DEFAULT_STDERR_SUMMARY_MAX_CHARS),
  75. })
  76. /** A stable per-handler id so an invoked/result pair correlates in the log. */
  77. let handlerCounter = 0
  78. function nextHandlerId(point: string): string {
  79. return `claude-code:${point}:${++handlerCounter}`
  80. }
  81. /** The `{kind:'plugin'}` source stamped on every context this bridge injects. */
  82. const PLUGIN_SOURCE: MessageSource = { kind: 'plugin', plugin: 'hooks-claude-code' }
  83. /** The summary cap bounds a persisted event field — a positive integer or the slice misbehaves silently. */
  84. function assertPositiveInteger(name: string, value: number): void {
  85. if (!Number.isInteger(value) || value < 1) {
  86. throw new Error(`hooks-claude-code: ${name} must be a positive integer`)
  87. }
  88. }
  89. export function apply(ctx: Context, config: Config): void {
  90. // Validate before config parsing so a bad value cannot be hidden by its early return.
  91. const stderrSummaryMaxChars = config.stderrSummaryMaxChars ?? DEFAULT_STDERR_SUMMARY_MAX_CHARS
  92. assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
  93. const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
  94. // Parse once at load. A read or parse failure logs and registers nothing.
  95. let parsed: ClaudeCodeHookConfig = {}
  96. try {
  97. const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
  98. const result = parseClaudeCodeConfig(raw, {
  99. ...config.pluginRoot !== undefined ? { pluginRoot: config.pluginRoot } : {},
  100. ...config.projectDir !== undefined ? { projectDir: config.projectDir } : {},
  101. })
  102. parsed = result.config
  103. for (const s of result.skipped) {
  104. ctx.logger.warn(`hooks-claude-code: skipping unsupported "${s.type}" hook on ${s.event} (only command hooks run)`)
  105. }
  106. } catch (error: unknown) {
  107. ctx.logger.warn(`hooks-claude-code: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
  108. return
  109. }
  110. // Emit-shaped points run detached, so track their chains; disposal aborts
  111. // active hooks and drains continuations before resolving.
  112. const detached = createDetachedRuns()
  113. // Only the start edge guarantees registry access. Retain each local child
  114. // through its paired end so stop hooks keep the session workspace after the
  115. // handle unregisters the agent. Every retained entry relies on that paired
  116. // end; a producer that can omit it must provide another release edge.
  117. const subagentChildren = new Map<SubagentRunId, Agent>()
  118. ctx.effect(() => () => detached.drain(), 'hooks-claude-code: drain detached hook runs')
  119. /**
  120. * Run every command hook configured for `point` whose matcher selects
  121. * `matchQuery`, with the per-event `payload` on stdin, and fold the results.
  122. * Writes a `hook/invoked`/`hook/result` pair per hook when `opts.turn` names
  123. * an open turn. Detached lifecycle points omit the pair. Returns the merged outcome (a neutral,
  124. * already-most-restrictive view) for the caller to map onto its extension point
  125. * decision. `matchQuery` is the event's matcher subject (tool name, session
  126. * source, …); `''` for events that ignore matchers.
  127. */
  128. async function runPoint(
  129. point: string,
  130. matchQuery: string,
  131. payload: unknown,
  132. opts: { agent?: Agent; turn?: number; readonly signal: AbortSignal },
  133. ): Promise<MergedHookOutcome> {
  134. const groups: MatcherGroup[] = parsed[point] ?? []
  135. const outputs: HookOutput[] = []
  136. // Run the hook in the agent's session workspace (the `session/new` cwd on the session
  137. // header), not the executor or entry-point process's launch dir.
  138. const workdir = opts.agent?.session.header.cwd
  139. // CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to the session
  140. // workspace (the same dir the hook runs in).
  141. const projectDir = config.projectDir ?? workdir
  142. const hookEnv = projectDir !== undefined ? { CLAUDE_PROJECT_DIR: projectDir } : undefined
  143. for (const group of groups) {
  144. if (!matchesMatcher(group.matcher, matchQuery, 'claude-code')) continue
  145. for (const hook of group.hooks) {
  146. const handlerId = nextHandlerId(point)
  147. const session = opts.agent?.session
  148. if (session && opts.turn !== undefined) {
  149. appendHookInvoked(session, {
  150. turn: opts.turn, point, dialect: 'claude-code', handlerId,
  151. ...group.matcher !== undefined ? { matcher: group.matcher } : {},
  152. })
  153. }
  154. const { output, durationMs } = await runHook(ctx.shell, hook, {
  155. payload,
  156. defaultTimeoutMs,
  157. ...hookEnv ? { env: hookEnv } : {},
  158. ...workdir !== undefined ? { cwd: workdir } : {},
  159. signal: opts.signal,
  160. trailingNewline: true,
  161. // Discard a `hookSpecificOutput` block whose `hookEventName` names a
  162. // different event than the one firing (the schemas key it by event).
  163. expectedEventName: point,
  164. }, () => performance.now())
  165. outputs.push(output)
  166. if (output.updatedInput !== undefined) {
  167. ctx.logger.warn(`hooks-claude-code: ${point} hook requested updatedInput, which is not yet honored (ignored)`)
  168. }
  169. if (output.systemMessage !== undefined) {
  170. ctx.logger.warn(`hooks-claude-code: ${point} hook emitted a systemMessage, which is not yet surfaced (ignored)`)
  171. }
  172. if (session && opts.turn !== undefined) {
  173. appendHookResult(session, { turn: opts.turn, point, handlerId, output, stderrSummaryMaxChars, durationMs })
  174. }
  175. }
  176. }
  177. return mergeHookOutputs(outputs)
  178. }
  179. // TODO(hook-continue-false): `merged.stop` is logged but needs a run-level halt mechanism.
  180. /** Build additional model context from hook output, or return undefined when empty. */
  181. function contextFrom(merged: MergedHookOutcome): UserMessage | undefined {
  182. if (merged.additionalContext.length === 0) return undefined
  183. const content: ContentBlock[] = merged.additionalContext.map(text => ({ type: 'text', text }))
  184. return createUserMessage({ content, source: PLUGIN_SOURCE })
  185. }
  186. /** Prepend one context without flattening source fields or other downstream metadata. */
  187. function prependContext(ours: UserMessage, theirs: UserMessage[] | undefined): UserMessage[] {
  188. return [ours, ...theirs ?? []]
  189. }
  190. // SessionStart injects context when its detached hook resolves; a slow hook
  191. // may miss the first request.
  192. // TODO(session-start-gating): add a startup gate before promising first-turn delivery.
  193. ctx.on('agent/session-start', ({ agent, source }) => {
  194. detached.track(runPoint('SessionStart', source, sessionStartPayload(ctx, agent, source), { agent, signal: detached.signal })
  195. .then((merged) => {
  196. const context = contextFrom(merged)
  197. if (context) agent.inject(context)
  198. })
  199. .catch((error: unknown) => {
  200. ctx.logger.warn(`hooks-claude-code: SessionStart hook failed: ${String(error)}`)
  201. }))
  202. })
  203. // --- UserPromptSubmit → PreStepDecision. The prompt text is the payload; no
  204. // matcher subject (CC ignores matchers for this event). ---
  205. ctx.on('agent/pre-step', async ({ agent, messages, turn, signal }, next): Promise<PreStepDecision> => {
  206. if (messages.length === 0) return next()
  207. const content = messages.flatMap(message => message.content)
  208. const merged = await runPoint('UserPromptSubmit', '', promptPayload(ctx, agent, content), { agent, turn, signal })
  209. if (merged.decision === 'deny') {
  210. return { kind: 'reject' }
  211. }
  212. // Delegate so later listeners may still rewrite or reject, then prepend our
  213. // context only to a downstream enter decision.
  214. const downstream = await next()
  215. const ours = contextFrom(merged)
  216. if (!ours || downstream.kind !== 'enter') return downstream
  217. return {
  218. ...downstream,
  219. messages: [...downstream.messages, ours],
  220. }
  221. })
  222. // --- PreToolUse → PreToolDecision. Matcher subject is the tool name. ---
  223. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  224. const turn = lastTurn(ctx, exec.agent)
  225. const merged = await runPoint('PreToolUse', exec.name, preToolPayload(ctx, exec), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  226. if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' }
  227. if (merged.decision === 'ask') return { kind: 'ask', ...merged.reason !== undefined ? { reason: merged.reason } : {} }
  228. return next()
  229. })
  230. // --- PostToolUse → PostToolDecision. Matcher subject is the tool name. ---
  231. ctx.on('tools/post-execute', async (exec, result, next): Promise<PostToolDecision> => {
  232. const turn = lastTurn(ctx, exec.agent)
  233. const merged = await runPoint('PostToolUse', exec.name, postToolPayload(ctx, exec, result), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  234. const context = contextFrom(merged)
  235. if (merged.decision === 'deny') {
  236. return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContexts: [context] } : {} }
  237. }
  238. // Our hooks did not block. DELEGATE so a later listener can still block/replace,
  239. // then fold our context onto its decision (a downstream block carries it too).
  240. const downstream = await next()
  241. if (!context) return downstream
  242. if (downstream.kind === 'block') {
  243. return { ...downstream, additionalContexts: prependContext(context, downstream.additionalContexts) }
  244. }
  245. return {
  246. ...downstream,
  247. additionalContexts: prependContext(context, downstream.additionalContexts),
  248. }
  249. })
  250. // A blocking Stop hook steers at the stopping boundary, which makes the
  251. // machine observe pending input and run another step.
  252. // TODO(stop-loop-guard): cap consecutive forced continuations; hooks must self-limit meanwhile.
  253. ctx.on('agent/turn-stopping', async ({ agent, turn, signal }): Promise<void> => {
  254. const merged = await runPoint('Stop', '', stopPayload(ctx, agent), { agent, turn, signal })
  255. if (merged.decision === 'deny') {
  256. // A blocking Stop hook forces continuation.
  257. const text = merged.reason ?? 'continue: blocked by Stop hook'
  258. agent.steer(createUserMessage({ content: [{ type: 'text', text }], source: PLUGIN_SOURCE }))
  259. }
  260. })
  261. // SubagentStart may inject child context; SubagentStop only observes. Both
  262. // use the live child's workspace and the generic agent-type matcher subject.
  263. ctx.on('subagent/start', (info) => {
  264. const child = ctx.get('agents')?.get(info.id)
  265. if (child !== undefined) subagentChildren.set(info.runId, child)
  266. detached.track(runPoint('SubagentStart', SUBAGENT_TYPE, subagentPayload(ctx, 'SubagentStart', info, child), { ...child ? { agent: child } : {}, signal: detached.signal })
  267. .then((merged) => {
  268. const context = contextFrom(merged)
  269. if (context && child) child.inject(context)
  270. })
  271. .catch((error: unknown) => { ctx.logger.warn(`hooks-claude-code: SubagentStart hook failed: ${String(error)}`) }))
  272. })
  273. ctx.on('subagent/end', (info) => {
  274. const child = subagentChildren.get(info.runId) ?? ctx.get('agents')?.get(info.id)
  275. subagentChildren.delete(info.runId)
  276. detached.track(runPoint('SubagentStop', SUBAGENT_TYPE, subagentPayload(ctx, 'SubagentStop', info, child), { ...child ? { agent: child } : {}, signal: detached.signal }))
  277. })
  278. }
  279. /**
  280. * The `agent_type` value the bridge reports for SubagentStart/Stop. The harness
  281. * subagent seam carries no per-kind label, so the bridge uses Claude Code's own
  282. * Task-tool default — a hooks.json with a default/`*`/empty `agent_type` matcher
  283. * fires; a config matching a specific kind (e.g. `code-reviewer`) does not.
  284. */
  285. const SUBAGENT_TYPE = 'general-purpose'
  286. // --- Per-event stdin payloads (the CC DIALECT shape). Field names match CC's
  287. // hook input schema; this is the part a bridge owns. ---
  288. /** The last open turn number in the agent's log, or 0 without an agent. */
  289. function lastTurn(ctx: Context, agent: Agent | undefined): number {
  290. if (!agent) return 0
  291. const boundary = ctx.sessionProjections.stateOf(agent.session, 'turnBoundary') as TurnBoundaryProjection
  292. return boundary.lastTurn
  293. }
  294. /** Flatten content blocks to the text a hook payload carries (the common case). */
  295. function blocksToText(content: ContentBlock[]): string {
  296. return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
  297. }
  298. function base(ctx: Context, agent: Agent | undefined, event: string): Record<string, unknown> {
  299. return {
  300. session_id: agent?.session.header.id ?? '',
  301. transcript_path: agent === undefined
  302. ? ''
  303. : ctx.get('sessionPersistence')?.locate(agent.session.header)?.path ?? '',
  304. cwd: agent?.session.header.cwd ?? process.cwd(),
  305. hook_event_name: event,
  306. }
  307. }
  308. function sessionStartPayload(ctx: Context, agent: Agent, source: string): Record<string, unknown> {
  309. return { ...base(ctx, agent, 'SessionStart'), source }
  310. }
  311. function promptPayload(ctx: Context, agent: Agent, content: ContentBlock[]): Record<string, unknown> {
  312. return { ...base(ctx, agent, 'UserPromptSubmit'), prompt: blocksToText(content) }
  313. }
  314. function preToolPayload(ctx: Context, exec: ToolExecution): Record<string, unknown> {
  315. return { ...base(ctx, exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId }
  316. }
  317. function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult): Record<string, unknown> {
  318. return { ...base(ctx, exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) }
  319. }
  320. function stopPayload(ctx: Context, agent: Agent): Record<string, unknown> {
  321. return { ...base(ctx, agent, 'Stop'), stop_hook_active: false }
  322. }
  323. /**
  324. * Build a SubagentStart/SubagentStop payload from the CC base (the child's
  325. * `session_id`/`cwd` when the child agent is available) plus the subagent-hook
  326. * fields. `agent_type` is the CC-default {@link SUBAGENT_TYPE}; `stop_hook_active`
  327. * is present on SubagentStop only (the loop-guard flag, always false).
  328. */
  329. function subagentPayload(ctx: Context, event: 'SubagentStart' | 'SubagentStop', info: { id: string }, child: Agent | undefined): Record<string, unknown> {
  330. return {
  331. ...base(ctx, child, event),
  332. agent_id: info.id,
  333. agent_type: SUBAGENT_TYPE,
  334. ...event === 'SubagentStop' ? { stop_hook_active: false } : {},
  335. }
  336. }