index.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**
  2. * Bridge for unmodified Claude Code command hooks on harness interception
  3. * seams. 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 seams; see the
  8. * [hook-bridges Agent Note](../../../../.agents/notes/implemented/feature/2026-06-30-hook-bridges.md).
  9. * @module @deepseek-ai/dsh-hooks-claude
  10. */
  11. import { readFileSync } from 'node:fs'
  12. import type { Context } from 'cordis'
  13. import z from 'schemastery'
  14. import type { Agent, PromptDecision } from '@deepseek-ai/dsh-agent'
  15. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  16. import type { UserMessageData } from '@deepseek-ai/dsh-session'
  17. import type {} from '@deepseek-ai/dsh-session-persistence'
  18. import type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  19. import {
  20. appendHookInvoked,
  21. appendHookResult,
  22. createDetachedRuns,
  23. DEFAULT_HOOK_TIMEOUT_MS,
  24. DEFAULT_STDERR_SUMMARY_MAX_CHARS,
  25. matchesMatcher,
  26. mergeHookOutputs,
  27. runHook,
  28. type HookOutput,
  29. type MatcherGroup,
  30. type MergedHookOutcome,
  31. } from '@deepseek-ai/dsh-hook-protocol'
  32. // Side-effect type import: pulls in the `subagent/start` + `subagent/end` event
  33. // declarations (declaration-merged into cordis `Events` by dsh-subagent) so the
  34. // SubagentStart/SubagentStop listeners below type-check.
  35. import type {} from '@deepseek-ai/dsh-subagent'
  36. import { parseClaudeConfig, type ClaudeHookConfig } from './config.ts'
  37. export const name = 'hooks-claude'
  38. // `bash` is required to run hooks; the rest are read opportunistically via
  39. // ctx.get so a deployment can load this bridge without every seam present.
  40. export const inject = ['bash']
  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` is not yet implemented.
  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:${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' }
  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: ${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: ClaudeHookConfig = {}
  95. try {
  96. const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
  97. const result = parseClaudeConfig(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: skipping unsupported "${s.type}" hook on ${s.event} (only command hooks run)`)
  104. }
  105. } catch (error: unknown) {
  106. ctx.logger.warn(`hooks-claude: 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. ctx.effect(() => () => detached.drain(), 'hooks-claude: drain detached hook runs')
  113. /**
  114. * Run every command hook configured for `point` whose matcher selects
  115. * `matchQuery`, with the per-event `payload` on stdin, and fold the results.
  116. * Writes a `hook/invoked`/`hook/result` pair per hook when `opts.turn` names
  117. * an open turn. Pre-turn `UserPromptSubmit` and detached lifecycle points
  118. * omit the pair. Returns the merged outcome (a neutral,
  119. * already-most-restrictive view) for the caller to map onto its seam
  120. * decision. `matchQuery` is the event's matcher subject (tool name, session
  121. * source, …); `''` for events that ignore matchers.
  122. */
  123. async function runPoint(
  124. point: string,
  125. matchQuery: string,
  126. payload: unknown,
  127. opts: { agent?: Agent; turn?: number; readonly signal: AbortSignal },
  128. ): Promise<MergedHookOutcome> {
  129. const groups: MatcherGroup[] = parsed[point] ?? []
  130. const outputs: HookOutput[] = []
  131. // Run the hook in the agent's session workspace (the `session/new` cwd on the session
  132. // header), not the executor default (the ACP server's launch dir).
  133. const workdir = opts.agent?.session.header.cwd
  134. // CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to the session
  135. // workspace (the same dir the hook runs in).
  136. const projectDir = config.projectDir ?? workdir
  137. const hookEnv = projectDir !== undefined ? { CLAUDE_PROJECT_DIR: projectDir } : undefined
  138. for (const group of groups) {
  139. if (!matchesMatcher(group.matcher, matchQuery, 'claude')) continue
  140. for (const hook of group.hooks) {
  141. const handlerId = nextHandlerId(point)
  142. const session = opts.agent?.session
  143. if (session && opts.turn !== undefined) {
  144. appendHookInvoked(session, {
  145. turn: opts.turn, point, dialect: 'claude', handlerId,
  146. ...group.matcher !== undefined ? { matcher: group.matcher } : {},
  147. })
  148. }
  149. const { output, durationMs } = await runHook(ctx.bash, hook, {
  150. payload,
  151. defaultTimeoutMs,
  152. ...hookEnv ? { env: hookEnv } : {},
  153. ...workdir !== undefined ? { cwd: workdir } : {},
  154. signal: opts.signal,
  155. trailingNewline: true,
  156. // Discard a `hookSpecificOutput` block whose `hookEventName` names a
  157. // different event than the one firing (the schemas key it by event).
  158. expectedEventName: point,
  159. }, () => performance.now())
  160. outputs.push(output)
  161. if (output.updatedInput !== undefined) {
  162. ctx.logger.warn(`hooks-claude: ${point} hook requested updatedInput, which is not yet honored (ignored)`)
  163. }
  164. if (output.systemMessage !== undefined) {
  165. ctx.logger.warn(`hooks-claude: ${point} hook emitted a systemMessage, which is not yet surfaced (ignored)`)
  166. }
  167. if (session && opts.turn !== undefined) {
  168. appendHookResult(session, { turn: opts.turn, point, handlerId, output, stderrSummaryMaxChars, durationMs })
  169. }
  170. }
  171. }
  172. return mergeHookOutputs(outputs)
  173. }
  174. // TODO(hook-continue-false): `merged.stop` is logged but needs a run-level halt seam.
  175. /** Build additional model context from hook output, or return undefined when empty. */
  176. function contextFrom(merged: MergedHookOutcome): UserMessageData | undefined {
  177. if (merged.additionalContext.length === 0) return undefined
  178. const content: ContentBlock[] = merged.additionalContext.map(text => ({ type: 'text', text }))
  179. return { content, source: PLUGIN_SOURCE }
  180. }
  181. /** Prepend one context without flattening downstream provenance or metadata. */
  182. function prependContext(ours: UserMessageData, theirs: UserMessageData[] | undefined): UserMessageData[] {
  183. return [ours, ...theirs ?? []]
  184. }
  185. // SessionStart injects context when its detached hook resolves; a slow hook
  186. // may miss the first request.
  187. // TODO(session-start-gating): add a startup gate before promising first-turn delivery.
  188. ctx.on('agent/session-start', (agent, source) => {
  189. detached.track(runPoint('SessionStart', source, sessionStartPayload(ctx, agent, source), { agent, signal: detached.signal })
  190. .then((merged) => {
  191. const context = contextFrom(merged)
  192. if (context) agent.inject({ content: context.content, source: context.source })
  193. })
  194. .catch((error: unknown) => {
  195. ctx.logger.warn(`hooks-claude: SessionStart hook failed: ${String(error)}`)
  196. }))
  197. })
  198. // --- UserPromptSubmit → PromptDecision. The prompt text is the payload; no
  199. // matcher subject (CC ignores matchers for this event). ---
  200. ctx.on('agent/prompt-submit', async (agent, content, _source, signal, next): Promise<PromptDecision> => {
  201. const merged = await runPoint('UserPromptSubmit', '', promptPayload(ctx, agent, content), { agent, signal })
  202. if (merged.decision === 'deny') {
  203. return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' }
  204. }
  205. // Delegate so later listeners may still rewrite or block, then prepend our
  206. // context only to a downstream allow decision.
  207. const downstream = await next()
  208. const ours = contextFrom(merged)
  209. if (!ours || downstream.kind !== 'allow') return downstream
  210. return {
  211. kind: 'allow',
  212. ...downstream.content !== undefined ? { content: downstream.content } : {},
  213. additionalContexts: prependContext(ours, downstream.additionalContexts),
  214. }
  215. })
  216. // --- PreToolUse → PreToolDecision. Matcher subject is the tool name. ---
  217. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  218. const turn = lastTurn(exec.agent)
  219. const merged = await runPoint('PreToolUse', exec.name, preToolPayload(ctx, exec), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  220. if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' }
  221. if (merged.decision === 'ask') return { kind: 'ask', ...merged.reason !== undefined ? { reason: merged.reason } : {} }
  222. return next()
  223. })
  224. // --- PostToolUse → PostToolDecision. Matcher subject is the tool name. ---
  225. ctx.on('tools/post-execute', async (exec, result, next): Promise<PostToolDecision> => {
  226. const turn = lastTurn(exec.agent)
  227. const merged = await runPoint('PostToolUse', exec.name, postToolPayload(ctx, exec, result), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal })
  228. const context = contextFrom(merged)
  229. if (merged.decision === 'deny') {
  230. return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContexts: [context] } : {} }
  231. }
  232. // Our hooks did not block. DELEGATE so a later listener can still block/replace,
  233. // then fold our context onto its decision (a downstream block carries it too).
  234. const downstream = await next()
  235. if (!context) return downstream
  236. if (downstream.kind === 'block') {
  237. return { ...downstream, additionalContexts: prependContext(context, downstream.additionalContexts) }
  238. }
  239. return {
  240. ...downstream,
  241. additionalContexts: prependContext(context, downstream.additionalContexts),
  242. }
  243. })
  244. // A blocking Stop hook steers at the stopping boundary, which makes the
  245. // machine observe pending input and run another step.
  246. // TODO(stop-loop-guard): cap consecutive forced continuations; hooks must self-limit meanwhile.
  247. ctx.on('agent/stopping', async (agent, turn, signal): Promise<void> => {
  248. const merged = await runPoint('Stop', '', stopPayload(ctx, agent), { agent, turn, signal })
  249. if (merged.decision === 'deny') {
  250. // A blocking Stop hook forces continuation.
  251. const text = merged.reason ?? 'continue: blocked by Stop hook'
  252. agent.steer({ content: [{ type: 'text', text }], source: PLUGIN_SOURCE })
  253. }
  254. })
  255. // SubagentStart may inject child context; SubagentStop only observes. Both
  256. // use the live child's workspace and the generic agent-type matcher subject.
  257. ctx.on('subagent/start', (info) => {
  258. const child = ctx.get('agents')?.get(info.id)
  259. detached.track(runPoint('SubagentStart', SUBAGENT_TYPE, subagentPayload(ctx, 'SubagentStart', info, child), { ...child ? { agent: child } : {}, signal: detached.signal })
  260. .then((merged) => {
  261. const context = contextFrom(merged)
  262. if (context && child) child.inject({ content: context.content, source: context.source })
  263. })
  264. .catch((error: unknown) => { ctx.logger.warn(`hooks-claude: SubagentStart hook failed: ${String(error)}`) }))
  265. })
  266. ctx.on('subagent/end', (info) => {
  267. // Look up the child (still recoverable: `subagent/end` fires from the service's detached
  268. // `.then` before the tool caller's `await run.result` disposes it) so the hook runs in the
  269. // child's cwd, not the server default.
  270. const child = ctx.get('agents')?.get(info.id)
  271. detached.track(runPoint('SubagentStop', SUBAGENT_TYPE, subagentPayload(ctx, 'SubagentStop', info, child), { ...child ? { agent: child } : {}, signal: detached.signal }))
  272. })
  273. }
  274. /**
  275. * The `agent_type` value the bridge reports for SubagentStart/Stop. The harness
  276. * subagent seam carries no per-kind label, so the bridge uses Claude Code's own
  277. * Task-tool default — a hooks.json with a default/`*`/empty `agent_type` matcher
  278. * fires; a config matching a specific kind (e.g. `code-reviewer`) does not.
  279. */
  280. const SUBAGENT_TYPE = 'general-purpose'
  281. // --- Per-event stdin payloads (the CC DIALECT shape). Field names match CC's
  282. // hook input schema; this is the part a bridge owns. ---
  283. /** The last open turn number in the agent's log, or 0 without an agent. */
  284. function lastTurn(agent: Agent | undefined): number {
  285. if (!agent) return 0
  286. const last = [...agent.session.events].findLast(e => e.type === 'turn/start')
  287. /* v8 ignore next -- agent-present callers are tool/stop seams inside an open turn. */
  288. return last?.type === 'turn/start' ? last.data.turn : 0
  289. }
  290. /** Flatten content blocks to the text a hook payload carries (the common case). */
  291. function blocksToText(content: ContentBlock[]): string {
  292. return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
  293. }
  294. function base(ctx: Context, agent: Agent | undefined, event: string): Record<string, unknown> {
  295. return {
  296. session_id: agent?.session.header.id ?? '',
  297. transcript_path: agent === undefined
  298. ? ''
  299. : ctx.get('sessionPersistence')?.locate(agent.session.header)?.path ?? '',
  300. cwd: agent?.session.header.cwd ?? process.cwd(),
  301. hook_event_name: event,
  302. }
  303. }
  304. function sessionStartPayload(ctx: Context, agent: Agent, source: string): Record<string, unknown> {
  305. return { ...base(ctx, agent, 'SessionStart'), source }
  306. }
  307. function promptPayload(ctx: Context, agent: Agent, content: ContentBlock[]): Record<string, unknown> {
  308. return { ...base(ctx, agent, 'UserPromptSubmit'), prompt: blocksToText(content) }
  309. }
  310. function preToolPayload(ctx: Context, exec: ToolExecution): Record<string, unknown> {
  311. return { ...base(ctx, exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId }
  312. }
  313. function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult): Record<string, unknown> {
  314. return { ...base(ctx, exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) }
  315. }
  316. function stopPayload(ctx: Context, agent: Agent): Record<string, unknown> {
  317. return { ...base(ctx, agent, 'Stop'), stop_hook_active: false }
  318. }
  319. /**
  320. * Build a SubagentStart/SubagentStop payload from the CC base (the child's
  321. * `session_id`/`cwd` when the child agent is available) plus the subagent-hook
  322. * fields. `agent_type` is the CC-default {@link SUBAGENT_TYPE}; `stop_hook_active`
  323. * is present on SubagentStop only (the loop-guard flag, always false this cut).
  324. */
  325. function subagentPayload(ctx: Context, event: 'SubagentStart' | 'SubagentStop', info: { id: string }, child: Agent | undefined): Record<string, unknown> {
  326. return {
  327. ...base(ctx, child, event),
  328. agent_id: info.id,
  329. agent_type: SUBAGENT_TYPE,
  330. ...event === 'SubagentStop' ? { stop_hook_active: false } : {},
  331. }
  332. }