index.ts 17 KB

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