index.ts 17 KB

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