@namzu/sdk 63.1.0 → 64.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +2 -1
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/agents/file-definitions.d.ts +10 -0
  6. package/dist/agents/file-definitions.d.ts.map +1 -1
  7. package/dist/agents/file-definitions.js +10 -2
  8. package/dist/agents/file-definitions.js.map +1 -1
  9. package/dist/compaction/hooks.d.ts +57 -0
  10. package/dist/compaction/hooks.d.ts.map +1 -0
  11. package/dist/compaction/hooks.js +44 -0
  12. package/dist/compaction/hooks.js.map +1 -0
  13. package/dist/compaction/manual.d.ts +9 -0
  14. package/dist/compaction/manual.d.ts.map +1 -1
  15. package/dist/compaction/manual.js +74 -5
  16. package/dist/compaction/manual.js.map +1 -1
  17. package/dist/compaction/model-summary.d.ts +6 -0
  18. package/dist/compaction/model-summary.d.ts.map +1 -1
  19. package/dist/compaction/model-summary.js +13 -3
  20. package/dist/compaction/model-summary.js.map +1 -1
  21. package/dist/compaction/verifier.d.ts +8 -2
  22. package/dist/compaction/verifier.d.ts.map +1 -1
  23. package/dist/compaction/verifier.js +23 -7
  24. package/dist/compaction/verifier.js.map +1 -1
  25. package/dist/plugin/file-change-hooks.d.ts +53 -0
  26. package/dist/plugin/file-change-hooks.d.ts.map +1 -0
  27. package/dist/plugin/file-change-hooks.js +111 -0
  28. package/dist/plugin/file-change-hooks.js.map +1 -0
  29. package/dist/plugin/file-change-watch.d.ts +111 -0
  30. package/dist/plugin/file-change-watch.d.ts.map +1 -0
  31. package/dist/plugin/file-change-watch.js +324 -0
  32. package/dist/plugin/file-change-watch.js.map +1 -0
  33. package/dist/plugin/hook-context.d.ts +16 -0
  34. package/dist/plugin/hook-context.d.ts.map +1 -1
  35. package/dist/plugin/hook-context.js +40 -0
  36. package/dist/plugin/hook-context.js.map +1 -1
  37. package/dist/plugin/index.d.ts +14 -4
  38. package/dist/plugin/index.d.ts.map +1 -1
  39. package/dist/plugin/index.js +10 -3
  40. package/dist/plugin/index.js.map +1 -1
  41. package/dist/plugin/lifecycle.d.ts +60 -1
  42. package/dist/plugin/lifecycle.d.ts.map +1 -1
  43. package/dist/plugin/lifecycle.js +118 -7
  44. package/dist/plugin/lifecycle.js.map +1 -1
  45. package/dist/plugin/loader.d.ts.map +1 -1
  46. package/dist/plugin/loader.js +24 -1
  47. package/dist/plugin/loader.js.map +1 -1
  48. package/dist/plugin/session-hook-env.d.ts +140 -0
  49. package/dist/plugin/session-hook-env.d.ts.map +1 -0
  50. package/dist/plugin/session-hook-env.js +458 -0
  51. package/dist/plugin/session-hook-env.js.map +1 -0
  52. package/dist/plugin/shell-hook-command.d.ts +25 -0
  53. package/dist/plugin/shell-hook-command.d.ts.map +1 -0
  54. package/dist/plugin/shell-hook-command.js +218 -0
  55. package/dist/plugin/shell-hook-command.js.map +1 -0
  56. package/dist/plugin/shell-hook-env.d.ts +107 -0
  57. package/dist/plugin/shell-hook-env.d.ts.map +1 -0
  58. package/dist/plugin/shell-hook-env.js +272 -0
  59. package/dist/plugin/shell-hook-env.js.map +1 -0
  60. package/dist/plugin/shell-hook-tool-names.d.ts +20 -0
  61. package/dist/plugin/shell-hook-tool-names.d.ts.map +1 -0
  62. package/dist/plugin/shell-hook-tool-names.js +43 -0
  63. package/dist/plugin/shell-hook-tool-names.js.map +1 -0
  64. package/dist/plugin/shell-hook.d.ts +167 -22
  65. package/dist/plugin/shell-hook.d.ts.map +1 -1
  66. package/dist/plugin/shell-hook.js +651 -106
  67. package/dist/plugin/shell-hook.js.map +1 -1
  68. package/dist/plugin/worktree-hook-answer.d.ts +26 -0
  69. package/dist/plugin/worktree-hook-answer.d.ts.map +1 -0
  70. package/dist/plugin/worktree-hook-answer.js +132 -0
  71. package/dist/plugin/worktree-hook-answer.js.map +1 -0
  72. package/dist/public-runtime.d.ts +5 -3
  73. package/dist/public-runtime.d.ts.map +1 -1
  74. package/dist/public-runtime.js +4 -3
  75. package/dist/public-runtime.js.map +1 -1
  76. package/dist/public-types.d.ts +9 -2
  77. package/dist/public-types.d.ts.map +1 -1
  78. package/dist/runtime/query/compact-session.d.ts +7 -1
  79. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  80. package/dist/runtime/query/compact-session.js +8 -3
  81. package/dist/runtime/query/compact-session.js.map +1 -1
  82. package/dist/runtime/query/executor/tool-call-admission.d.ts +1 -1
  83. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  84. package/dist/runtime/query/executor/tool-call-admission.js +4 -3
  85. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  86. package/dist/runtime/query/executor.d.ts +5 -0
  87. package/dist/runtime/query/executor.d.ts.map +1 -1
  88. package/dist/runtime/query/executor.js +8 -3
  89. package/dist/runtime/query/executor.js.map +1 -1
  90. package/dist/runtime/query/finalize-turn.d.ts.map +1 -1
  91. package/dist/runtime/query/finalize-turn.js +9 -2
  92. package/dist/runtime/query/finalize-turn.js.map +1 -1
  93. package/dist/runtime/query/index.d.ts +9 -0
  94. package/dist/runtime/query/index.d.ts.map +1 -1
  95. package/dist/runtime/query/index.js +3 -0
  96. package/dist/runtime/query/index.js.map +1 -1
  97. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  98. package/dist/runtime/query/iteration/index.js +2 -1
  99. package/dist/runtime/query/iteration/index.js.map +1 -1
  100. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  101. package/dist/runtime/query/iteration/phases/compaction.js +24 -12
  102. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  103. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  104. package/dist/runtime/query/iteration/phases/tool-review.js +2 -0
  105. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  106. package/dist/runtime/query/plugin-hooks.d.ts +13 -0
  107. package/dist/runtime/query/plugin-hooks.d.ts.map +1 -1
  108. package/dist/runtime/query/plugin-hooks.js +29 -2
  109. package/dist/runtime/query/plugin-hooks.js.map +1 -1
  110. package/dist/runtime/query/tooling.d.ts +5 -0
  111. package/dist/runtime/query/tooling.d.ts.map +1 -1
  112. package/dist/runtime/query/tooling.js +3 -0
  113. package/dist/runtime/query/tooling.js.map +1 -1
  114. package/dist/session/workspace/hooked-driver.d.ts +72 -0
  115. package/dist/session/workspace/hooked-driver.d.ts.map +1 -0
  116. package/dist/session/workspace/hooked-driver.js +204 -0
  117. package/dist/session/workspace/hooked-driver.js.map +1 -0
  118. package/dist/session/workspace/index.d.ts +2 -0
  119. package/dist/session/workspace/index.d.ts.map +1 -1
  120. package/dist/session/workspace/index.js +1 -0
  121. package/dist/session/workspace/index.js.map +1 -1
  122. package/dist/skills/index.d.ts +1 -1
  123. package/dist/skills/index.d.ts.map +1 -1
  124. package/dist/skills/index.js +1 -1
  125. package/dist/skills/index.js.map +1 -1
  126. package/dist/skills/loader.d.ts +22 -0
  127. package/dist/skills/loader.d.ts.map +1 -1
  128. package/dist/skills/loader.js +41 -0
  129. package/dist/skills/loader.js.map +1 -1
  130. package/dist/tools/builtins/bash-cwd.d.ts +6 -1
  131. package/dist/tools/builtins/bash-cwd.d.ts.map +1 -1
  132. package/dist/tools/builtins/bash-cwd.js +27 -2
  133. package/dist/tools/builtins/bash-cwd.js.map +1 -1
  134. package/dist/tools/builtins/bash.js +1 -1
  135. package/dist/tools/builtins/bash.js.map +1 -1
  136. package/dist/tools/builtins/skill.d.ts.map +1 -1
  137. package/dist/tools/builtins/skill.js +93 -16
  138. package/dist/tools/builtins/skill.js.map +1 -1
  139. package/dist/types/agent/query.d.ts +8 -0
  140. package/dist/types/agent/query.d.ts.map +1 -1
  141. package/dist/types/plugin/index.d.ts +130 -13
  142. package/dist/types/plugin/index.d.ts.map +1 -1
  143. package/dist/types/plugin/index.js +5 -0
  144. package/dist/types/plugin/index.js.map +1 -1
  145. package/dist/types/skills/index.d.ts +8 -0
  146. package/dist/types/skills/index.d.ts.map +1 -1
  147. package/dist/types/skills/index.js.map +1 -1
  148. package/dist/types/tool/index.d.ts +68 -0
  149. package/dist/types/tool/index.d.ts.map +1 -1
  150. package/dist/types/tool/index.js.map +1 -1
  151. package/dist/types/workspace/ref.d.ts +6 -0
  152. package/dist/types/workspace/ref.d.ts.map +1 -1
  153. package/dist/utils/frontmatter.d.ts +16 -0
  154. package/dist/utils/frontmatter.d.ts.map +1 -1
  155. package/dist/utils/frontmatter.js +31 -1
  156. package/dist/utils/frontmatter.js.map +1 -1
  157. package/package.json +1 -1
  158. package/src/agents/QueryAgent.ts +2 -1
  159. package/src/agents/file-definitions.ts +17 -2
  160. package/src/compaction/hooks.ts +104 -0
  161. package/src/compaction/manual.ts +117 -4
  162. package/src/compaction/model-summary.ts +19 -3
  163. package/src/compaction/verifier.ts +33 -3
  164. package/src/plugin/file-change-hooks.ts +131 -0
  165. package/src/plugin/file-change-watch.ts +367 -0
  166. package/src/plugin/hook-context.ts +46 -0
  167. package/src/plugin/index.ts +53 -1
  168. package/src/plugin/lifecycle.ts +162 -8
  169. package/src/plugin/loader.ts +22 -1
  170. package/src/plugin/session-hook-env.ts +475 -0
  171. package/src/plugin/shell-hook-command.ts +215 -0
  172. package/src/plugin/shell-hook-env.ts +335 -0
  173. package/src/plugin/shell-hook-tool-names.ts +46 -0
  174. package/src/plugin/shell-hook.ts +818 -100
  175. package/src/plugin/worktree-hook-answer.ts +142 -0
  176. package/src/public-runtime.ts +44 -0
  177. package/src/public-types.ts +22 -1
  178. package/src/runtime/query/compact-session.ts +16 -4
  179. package/src/runtime/query/executor/tool-call-admission.ts +10 -2
  180. package/src/runtime/query/executor.ts +13 -2
  181. package/src/runtime/query/finalize-turn.ts +9 -2
  182. package/src/runtime/query/index.ts +12 -0
  183. package/src/runtime/query/iteration/index.ts +2 -1
  184. package/src/runtime/query/iteration/phases/compaction.ts +31 -12
  185. package/src/runtime/query/iteration/phases/tool-review.ts +2 -0
  186. package/src/runtime/query/plugin-hooks.ts +32 -2
  187. package/src/runtime/query/tooling.ts +8 -0
  188. package/src/session/workspace/hooked-driver.ts +272 -0
  189. package/src/session/workspace/index.ts +7 -0
  190. package/src/skills/index.ts +3 -0
  191. package/src/skills/loader.ts +47 -0
  192. package/src/tools/builtins/bash-cwd.ts +25 -1
  193. package/src/tools/builtins/bash.ts +1 -1
  194. package/src/tools/builtins/skill.ts +115 -26
  195. package/src/types/agent/query.ts +9 -0
  196. package/src/types/plugin/index.ts +150 -23
  197. package/src/types/skills/index.ts +9 -0
  198. package/src/types/tool/index.ts +74 -0
  199. package/src/types/workspace/ref.ts +6 -0
  200. package/src/utils/frontmatter.ts +52 -1
@@ -24,8 +24,8 @@
24
24
  * same facts as `NAMZU_HOOK_EVENT`, `NAMZU_SESSION_ID`, `NAMZU_TURN_ID`,
25
25
  * `NAMZU_TOOL_NAME` and, when the input names a file, `NAMZU_TOOL_PATH`;
26
26
  * `NAMZU_PROJECT_DIR` is the folder the session was started for.
27
- * `session_start` also sends `source` (`startup` or `resume`) and `session_end`
28
- * `reason` (`exit` or `replaced`).
27
+ * `session_start` also sends `source` (`startup`, `resume` or `clear`) and
28
+ * `session_end` `reason` (`exit`, `replaced` or `clear`).
29
29
  *
30
30
  * `session_start` and `session_end` run outside any turn, so they carry no
31
31
  * `turn_id` on stdin and no `NAMZU_TURN_ID` in the environment — not even
@@ -36,7 +36,8 @@
36
36
  * stdout. The exit codes:
37
37
  *
38
38
  * - `0` — carry on. On `user_prompt_submit`, `subagent_start` and
39
- * `session_start`, plain (non-JSON) stdout becomes context for the model.
39
+ * `session_start`, plain (non-JSON) stdout becomes context for the model;
40
+ * on `pre_compact` it is instructions for the summariser.
40
41
  * - `2` — **block**, read per event: before a tool (`pre_tool_use`) the call is
41
42
  * skipped and the model is told why, with the hook's stderr as the reason;
42
43
  * on `user_prompt_submit` the turn ends; on `turn_end` and `subagent_stop`
@@ -105,6 +106,8 @@
105
106
  */
106
107
 
107
108
  import { spawn } from 'node:child_process'
109
+ import { constants, accessSync, mkdirSync, statSync } from 'node:fs'
110
+ import { basename, delimiter } from 'node:path'
108
111
 
109
112
  import { decodedCommands, decomposeCommandLine } from '../authorization/command-line.js'
110
113
  import {
@@ -116,6 +119,7 @@ import { spawnHostShell } from '../tools/command-shell.js'
116
119
  import type { PluginId } from '../types/ids/index.js'
117
120
  import type {
118
121
  PluginCompactionInfo,
122
+ PluginFileChange,
119
123
  PluginHookContext,
120
124
  PluginHookDefinition,
121
125
  PluginHookEvent,
@@ -130,7 +134,18 @@ import { NOOP_LOGGER } from '../utils/log/create-logger.js'
130
134
  import type { Logger } from '../utils/logger.js'
131
135
  import { boundHookReplacement } from './hook-context.js'
132
136
  import type { PluginLifecycleManager } from './lifecycle.js'
137
+ import type { SessionHookEnv } from './session-hook-env.js'
138
+ import { readHookCommand } from './shell-hook-command.js'
139
+ import {
140
+ type PluginFolders,
141
+ hookUnsetVariableHint,
142
+ movedEnvironment,
143
+ shellPathOutsideEnv,
144
+ substituteMovedFolders,
145
+ } from './shell-hook-env.js'
133
146
  import { postHookJson } from './shell-hook-http.js'
147
+ import { type ShellHookToolNames, shellHookToolName } from './shell-hook-tool-names.js'
148
+ import { worktreeHookVerdict } from './worktree-hook-answer.js'
134
149
 
135
150
  /**
136
151
  * The events a shell hook may attach to: the ones an operator can act on
@@ -156,6 +171,10 @@ export type ShellHookEvent = Extract<
156
171
  | 'turn_failure'
157
172
  | 'turn_start'
158
173
  | 'turn_end'
174
+ | 'file_changed'
175
+ | 'cwd_changed'
176
+ | 'worktree_create'
177
+ | 'worktree_remove'
159
178
  >
160
179
 
161
180
  export const SHELL_HOOK_EVENTS: readonly ShellHookEvent[] = [
@@ -176,6 +195,10 @@ export const SHELL_HOOK_EVENTS: readonly ShellHookEvent[] = [
176
195
  'turn_failure',
177
196
  'turn_start',
178
197
  'turn_end',
198
+ 'file_changed',
199
+ 'cwd_changed',
200
+ 'worktree_create',
201
+ 'worktree_remove',
179
202
  ]
180
203
 
181
204
  /** What a failed hook does to the action it guards. */
@@ -223,6 +246,15 @@ interface ShellHookEntryBase {
223
246
  * here are the same entry.
224
247
  */
225
248
  readonly source?: string
249
+ /**
250
+ * Which spelling of a tool's name the hook is sent as `tool_name` (and
251
+ * `NAMZU_TOOL_NAME`): `namzu`, the name the tool is registered under
252
+ * (`bash`; the default), or `written`, the capitalised name a person writes
253
+ * in a matcher (`Bash`). A tool with no written name, and every tool-server
254
+ * tool, keeps its own. `matcher` and `if` read either spelling whatever this
255
+ * says. An entry read from the common hook contract is `written`.
256
+ */
257
+ readonly toolNames?: ShellHookToolNames
226
258
  }
227
259
 
228
260
  /** One shell command at one event. */
@@ -239,6 +271,15 @@ export interface ShellHookEntry extends ShellHookEntryBase {
239
271
  * parser. An empty list runs `command` with no arguments.
240
272
  */
241
273
  readonly args?: readonly string[]
274
+ /**
275
+ * Variables the command is started with, in addition to the ones Namzu sets
276
+ * for every hook. A value may use `$NAME` or `${NAME}` of a variable the
277
+ * hook already has (`${NAMZU_PROJECT_DIR}`); text it cannot fill stays as
278
+ * written. A name Namzu sets itself (`NAMZU_HOOK_EVENT` and the rest) cannot
279
+ * be replaced. For a script that reads a variable inside its own file, which
280
+ * no rule reading the command text can see.
281
+ */
282
+ readonly env?: Readonly<Record<string, string>>
242
283
  /**
243
284
  * Start the command and carry on without waiting. Its exit code and output
244
285
  * decide nothing (a failure is logged), and `onFailure` is not read.
@@ -318,12 +359,29 @@ const WRITTEN_TOOL_NAMES: Readonly<Record<string, string>> = Object.freeze({
318
359
  tasklist: 'TaskList',
319
360
  })
320
361
 
362
+ /**
363
+ * The tools a written name stands for. The skill alias table sends `Task` and
364
+ * `Agent` to `create_task`, but the command line's sub-agent tool is named
365
+ * `Agent`, and a hook written for either spelling means it: both name it.
366
+ */
367
+ function toolsNamedBy(written: string): string[] {
368
+ const alias = SKILL_TOOL_NAME_ALIASES[written]
369
+ const names = alias !== undefined ? [alias] : []
370
+ if (written === 'task' || written === 'agent') names.push('agent')
371
+ return names
372
+ }
373
+
374
+ /** A name with the separators dropped: `ViewImage` and `view_image` are one tool. */
375
+ function squashed(name: string): string {
376
+ return name.toLowerCase().replace(/[_-]/g, '')
377
+ }
378
+
321
379
  /** The names a skill writes for the tool called `toolName` here. */
322
380
  function writtenNamesFor(toolName: string): string[] {
323
381
  const lower = toolName.toLowerCase()
324
382
  const names: string[] = []
325
- for (const [written, tool] of Object.entries(SKILL_TOOL_NAME_ALIASES)) {
326
- if (tool !== lower) continue
383
+ for (const written of new Set([...Object.keys(SKILL_TOOL_NAME_ALIASES), 'agent', 'task'])) {
384
+ if (!toolsNamedBy(written).includes(lower)) continue
327
385
  names.push(written)
328
386
  const spelled = WRITTEN_TOOL_NAMES[written]
329
387
  if (spelled !== undefined) names.push(spelled)
@@ -331,27 +389,73 @@ function writtenNamesFor(toolName: string): string[] {
331
389
  return names
332
390
  }
333
391
 
392
+ /** A glob over names: `*` matches any run of characters, the rest is literal. */
393
+ function globMatches(pattern: string, subject: string): boolean {
394
+ const source = pattern
395
+ .split('*')
396
+ .map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
397
+ .join('.*')
398
+ return new RegExp(`^${source}$`, 'i').test(subject)
399
+ }
400
+
401
+ /**
402
+ * Whether a list part (`Edit`, `Web*`, `mcp__*__search`) names `subject`, as a
403
+ * tool name or not. A `*` at the end is a prefix; a `*` anywhere else is a
404
+ * glob. For a tool, a bare tool-server name (`mcp__github`) names every tool
405
+ * of that server.
406
+ */
407
+ function listPartNames(part: string, subject: string, tool: boolean): boolean {
408
+ const prefix = part.endsWith('*')
409
+ const core = prefix ? part.slice(0, -1) : part
410
+ const written = core.toLowerCase()
411
+ const lower = subject.toLowerCase()
412
+ if (core.includes('*')) {
413
+ if (globMatches(part, subject)) return true
414
+ return tool && writtenNamesFor(subject).some((name) => globMatches(part, name))
415
+ }
416
+ const spellings = [written]
417
+ if (tool) spellings.push(...toolsNamedBy(written))
418
+ return spellings.some((name) => {
419
+ if (prefix ? lower.startsWith(name) : lower === name) return true
420
+ if (!tool) return false
421
+ // A tool's name also compares without its `_` and `-`.
422
+ if (prefix ? squashed(lower).startsWith(squashed(name)) : squashed(lower) === squashed(name)) {
423
+ return true
424
+ }
425
+ return !prefix && name.startsWith('mcp__') && !name.slice(5).includes('__')
426
+ ? lower.startsWith(`${name}__`)
427
+ : false
428
+ })
429
+ }
430
+
431
+ const MATCHER_LIST_PART = /^[A-Za-z0-9_.:*-]+$/
432
+
334
433
  /**
335
434
  * `matcher` against a name (a tool's, or a notification's type).
336
435
  *
337
436
  * Empty or `*` matches everything. A list of names separated by `|` or `,`
338
437
  * matches exactly, each part optionally ending in `*` as a prefix (the
339
438
  * spelling this adapter has always taken). Anything else is a regular
340
- * expression, tested unanchored against the name; one that does not compile
341
- * matches nothing. A matcher on an event that has no name (`turn_start`)
342
- * matches nothing unless it is `*`.
439
+ * expression, tested unanchored against the name. This function called with no
440
+ * name matches only `*`; a hook on an event that has no name (`turn_end`)
441
+ * ignores its matcher and fires (see `createShellHook`).
442
+ *
443
+ * A text that reads both ways (it is a list, and it holds a `.*`
444
+ * that a regular expression reads differently: `Bash.*`,
445
+ * `mcp__.*__search`) fires when either reading matches. A pattern that does
446
+ * not compile cannot be read, and a guard that silently matches nothing is
447
+ * the failure to avoid, so it matches every name; `/hooks` and
448
+ * `namzu doctor` say that it cannot be read (`shellHookMatcherProblem`).
343
449
  *
344
450
  * Names in a list compare without regard to case. With `tool: true` (the
345
451
  * event's name is a tool: the tool events and `permission_request`) they also
346
- * take the names skills write, the way an entry's `if` does: `Bash` matches
347
- * the tool `bash`, `MultiEdit` matches `edit`, and a prefix such as `Web*`
348
- * matches `web_fetch` by its written name too. Where the name is not a tool
349
- * (a notification's type, an agent's name, a session's `source` or `reason`)
350
- * no tool alias applies, since those words are not tool names; case is still
351
- * ignored there, because a guard that silently never runs over a capital
352
- * letter is worse than one that also runs for a name differing only in case.
353
- *
354
- * A list part ending in `.*` is also tried as a regular expression.
452
+ * take the names skills write, the way an entry's `if` does, and a tool name
453
+ * compares without its `_` and `-`: `Bash` matches the tool `bash`,
454
+ * `MultiEdit` matches `edit`, `ViewImage` matches `view_image`, `Task` and
455
+ * `Agent` match the sub-agent tool `Agent`, and a prefix such as `Web*`
456
+ * matches `web_fetch`. Where the name is not a tool (a notification's type,
457
+ * an agent's name, a session's `source` or `reason`) no tool alias applies,
458
+ * since those words are not tool names; case is still ignored there.
355
459
  *
356
460
  * A regular expression is tested, case-sensitively as written, against the
357
461
  * real name and, with `tool: true`, against each name skills write for that
@@ -367,37 +471,115 @@ export function shellHookMatches(
367
471
  if (toolName === undefined) return false
368
472
  const tool = options.tool === true
369
473
  const parts = matcher.split(/[|,]/).map((part) => part.trim())
370
- if (parts.every((part) => /^[A-Za-z0-9_.:-]+\*?$/.test(part))) {
371
- const subject = toolName.toLowerCase()
372
- const listed = parts.some((candidate) => {
373
- const prefix = candidate.endsWith('*')
374
- const written = (prefix ? candidate.slice(0, -1) : candidate).toLowerCase()
375
- const spellings = [written]
376
- if (tool) {
377
- const alias = SKILL_TOOL_NAME_ALIASES[written]
378
- if (alias !== undefined) spellings.push(alias)
379
- }
380
- return spellings.some((name) => (prefix ? subject.startsWith(name) : subject === name))
381
- })
382
- // `Bash.*` reads as the prefix `bash.` above, which no tool has. A part
383
- // ending in `.*` is also a regular expression, so it is tried as one.
384
- if (listed || !matcher.includes('.*')) return listed
474
+ if (parts.every((part) => MATCHER_LIST_PART.test(part))) {
475
+ if (parts.some((part) => listPartNames(part, toolName, tool))) return true
476
+ // A list of names is exact (a `*` in it is a prefix or a glob). Only `.*` reads differently
477
+ // as a regular expression, so only then is the second reading tried.
478
+ if (!matcher.includes('.*')) return false
385
479
  }
386
480
  try {
387
481
  const expression = new RegExp(matcher)
388
482
  if (expression.test(toolName)) return true
389
483
  return tool && writtenNamesFor(toolName).some((name) => expression.test(name))
390
484
  } catch {
391
- return false
485
+ return true
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Why a `matcher` cannot be read, or `undefined` when it can. A matcher that
491
+ * is not a list of names and does not compile as a regular expression fires
492
+ * for every name (see {@link shellHookMatches}).
493
+ */
494
+ export function shellHookMatcherProblem(matcher: string | undefined): string | undefined {
495
+ if (matcher === undefined || matcher.trim() === '' || matcher.trim() === '*') return undefined
496
+ const parts = matcher.split(/[|,]/).map((part) => part.trim())
497
+ if (parts.every((part) => MATCHER_LIST_PART.test(part))) return undefined
498
+ // `Bash(git push *)` is a tool and a pattern, which is what an `if` reads. As a
499
+ // matcher it is a regular expression that no tool name satisfies, so the hook
500
+ // would never fire; say so, and name the `if`.
501
+ if (/^[A-Za-z0-9_.:*-]+\([\s\S]*\)$/.test(matcher.trim())) {
502
+ return `the matcher "${matcher}" is written as Tool(pattern), which is an if, not a matcher: as a matcher it matches no tool name and the hook never fires; put the tool in matcher and the pattern in if`
392
503
  }
504
+ try {
505
+ new RegExp(matcher)
506
+ return undefined
507
+ } catch (error) {
508
+ return `the matcher "${matcher}" is not a list of names and is not a regular expression (${(error as Error).message}), so it cannot be read and the hook fires for every call`
509
+ }
510
+ }
511
+
512
+ const IF_SHAPE = /^([A-Za-z0-9_.:*|, -]+)(?:\(([\s\S]*)\))?$/
513
+
514
+ /** A part of a `file_changed` matcher that names a path: letters, digits and the characters of a path. */
515
+ const FILE_LIST_PART = /^[A-Za-z0-9_.:*\\/-]+$/
516
+
517
+ /** The parts of a `file_changed` matcher when every part is written as a path, else `undefined`. */
518
+ function fileMatcherParts(matcher: string | undefined): string[] | undefined {
519
+ if (matcher === undefined || matcher.trim() === '' || matcher.trim() === '*') return undefined
520
+ const parts = matcher.split(/[|,]/).map((part) => part.trim())
521
+ return parts.every((part) => FILE_LIST_PART.test(part)) ? parts : undefined
522
+ }
523
+
524
+ /**
525
+ * The files a `file_changed` matcher names: each part of a `|` list that is a
526
+ * path with no `*` in it (`.envrc`, `config/app.json`, `/etc/hosts`). A part
527
+ * with a `*`, a pattern, or no matcher names no file; the hook then runs only
528
+ * for the files hooks hand back with `watchPaths`. A relative path is under
529
+ * the working folder, which the host knows.
530
+ */
531
+ export function fileChangedMatcherPaths(matcher: string | undefined): string[] {
532
+ return (fileMatcherParts(matcher) ?? []).filter((part) => !part.includes('*'))
533
+ }
534
+
535
+ /**
536
+ * Whether a `file_changed` hook with this matcher runs for `filePath`. The
537
+ * matcher is read as every matcher is, but against the file's base name: a
538
+ * part written as a path (`config/app.json`) stands for its base name
539
+ * (`app.json`). An unreadable pattern runs the hook.
540
+ */
541
+ export function fileChangedMatches(
542
+ matcher: string | undefined,
543
+ filePath: string | undefined,
544
+ ): boolean {
545
+ if (filePath === undefined) return true
546
+ const name = basename(filePath.replace(/[\\/]+$/, ''))
547
+ const parts = fileMatcherParts(matcher)
548
+ if (parts === undefined) return shellHookMatches(matcher, name)
549
+ return shellHookMatches(
550
+ parts.map((part) => basename(part.replace(/[\\/]+$/, '')) || part).join('|'),
551
+ name,
552
+ )
553
+ }
554
+
555
+ /**
556
+ * What a `file_changed` entry's matcher does not do, or `undefined`: a matcher
557
+ * that names no file watches nothing by itself.
558
+ */
559
+ export function fileChangedMatcherNote(matcher: string | undefined): string | undefined {
560
+ if (fileChangedMatcherPaths(matcher).length > 0) return undefined
561
+ return 'its matcher names no file, so it watches nothing itself and runs only for files other hooks hand back with watchPaths'
562
+ }
563
+
564
+ /**
565
+ * Why an `if` cannot be read, or `undefined` when it can. A filter that
566
+ * cannot be read runs the hook.
567
+ */
568
+ export function shellHookIfProblem(filter: string | undefined): string | undefined {
569
+ if (filter === undefined || filter.trim() === '') return undefined
570
+ return IF_SHAPE.test(filter.trim())
571
+ ? undefined
572
+ : `the if "${filter}" is not Tool or Tool(pattern), so it cannot be read and the hook runs for every call`
393
573
  }
394
574
 
395
575
  /**
396
576
  * A hook's `if` against one tool call: `Tool` or `Tool(pattern)`. The tool
397
- * part is case-insensitive and takes the names skills write (`Bash`,
398
- * `Read`). A pattern is matched against a shell tool's command line and only
399
- * there; for a tool with no command line the filter cannot be read, which
400
- * runs the hook.
577
+ * part takes every spelling a `matcher` takes as a list: names skills write
578
+ * (`Bash`, `Read`, `Agent`), separated by `|` or `,`, a prefix ending in `*`,
579
+ * case ignored; a regular expression is not read here (use `matcher`). A
580
+ * pattern is matched against a shell tool's command line (one command at a
581
+ * time) or, for a file tool, a path the host reads; for a tool with neither
582
+ * the filter cannot be read, which runs the hook.
401
583
  */
402
584
  export function shellHookIfMatches(
403
585
  filter: string | undefined,
@@ -407,22 +589,36 @@ export function shellHookIfMatches(
407
589
  ): boolean {
408
590
  if (filter === undefined || filter.trim() === '') return true
409
591
  if (toolName === undefined) return true
410
- const shape = /^([A-Za-z0-9_.-]+)(?:\(([\s\S]*)\))?$/.exec(filter.trim())
592
+ const shape = IF_SHAPE.exec(filter.trim())
411
593
  if (!shape) return true
412
- const written = (shape[1] ?? '').toLowerCase()
413
- const tool = SKILL_TOOL_NAME_ALIASES[written] ?? written
414
594
  const specifier = shape[2]?.trim()
415
595
  const hasPattern =
416
596
  specifier !== undefined && specifier !== '' && specifier.replaceAll('*', '') !== ''
417
- // A path pattern is the permission rules' own: the host that has them says
418
- // whether this call's path is named. It decides for the tools it knows.
419
- if (hasPattern && pathFilter !== undefined) {
420
- const answer = pathFilter(tool, specifier, toolName, toolInput)
421
- if (answer !== undefined) return answer
422
- }
423
- if (tool !== toolName.toLowerCase()) return false
424
- if (!hasPattern) return true
425
- if (tool !== 'bash') return true
597
+ const parts = (shape[1] ?? '')
598
+ .split(/[|,]/)
599
+ .map((part) => part.trim())
600
+ .filter((part) => part !== '')
601
+ if (parts.length === 0) return true
602
+ if (parts.some((part) => part === '*')) return true
603
+ const callTool = toolName.toLowerCase()
604
+ return parts.some((part) => {
605
+ const written = part.replace(/\*$/, '').toLowerCase()
606
+ const tool = SKILL_TOOL_NAME_ALIASES[written] ?? written
607
+ // A path pattern is the permission rules' own: the host that has them says
608
+ // whether this call's path is named. It decides for the tools it knows.
609
+ if (hasPattern && pathFilter !== undefined && !part.endsWith('*')) {
610
+ const answer = pathFilter(tool, specifier, toolName, toolInput)
611
+ if (answer !== undefined) return answer
612
+ }
613
+ if (!listPartNames(part, toolName, true)) return false
614
+ if (!hasPattern) return true
615
+ if (callTool !== 'bash') return true
616
+ return commandMatches(specifier, toolInput)
617
+ })
618
+ }
619
+
620
+ /** A shell tool's command line against a permission-rule pattern, per command. */
621
+ function commandMatches(specifier: string, toolInput: unknown): boolean {
426
622
  const line =
427
623
  toolInput !== null && typeof toolInput === 'object'
428
624
  ? (toolInput as Record<string, unknown>).command
@@ -436,9 +632,16 @@ export function shellHookIfMatches(
436
632
  // filter names, so the hook runs. A filter only ever narrows when the
437
633
  // whole line is visible and none of its commands matches.
438
634
  if (decomposed.opaque) return true
439
- const candidates = [...decomposed.segments, ...decodedCommands(line, 'sh')].map((each) =>
440
- each.trim(),
441
- )
635
+ // Wrappers, a program's full path and git's global options do not change
636
+ // which command runs; a command whose name is only known at run time
637
+ // cannot be compared, so the hook runs.
638
+ const reading = readHookCommand(line)
639
+ if (reading.unknowable) return true
640
+ const candidates = [
641
+ ...decomposed.segments,
642
+ ...decodedCommands(line, 'sh'),
643
+ ...reading.candidates,
644
+ ].map((each) => each.trim())
442
645
  return candidates.some((each) => matcher.test(each))
443
646
  } catch {
444
647
  return true
@@ -469,6 +672,8 @@ export interface ShellHookOutcome {
469
672
  readonly stdoutTruncated?: boolean
470
673
  /** Set when the process could not be started at all. */
471
674
  readonly spawnError?: string
675
+ /** The variables the command refers to that were set nowhere; read when the command was not found. */
676
+ readonly unsetVariables?: readonly string[]
472
677
  }
473
678
 
474
679
  export interface ShellHookInput {
@@ -484,6 +689,12 @@ export interface ShellHookInput {
484
689
  readonly endReason?: string
485
690
  /** The folder the session was started for. Sent as `NAMZU_PROJECT_DIR`; absent, `cwd`. */
486
691
  readonly projectDir?: string
692
+ /**
693
+ * Set for a hook entry a plugin ships: the plugin's own folder and the folder
694
+ * kept for its data. Sent as `NAMZU_PLUGIN_ROOT` and `NAMZU_PLUGIN_DATA`, and
695
+ * put in the command and arguments where they name them.
696
+ */
697
+ readonly plugin?: PluginFolders
487
698
  /** The delegating session, on `subagent_start` and `subagent_stop`. */
488
699
  readonly parentSessionId?: string
489
700
  /** The parent turn whose tool call spawned the child, on `subagent_start` and `subagent_stop`. */
@@ -491,8 +702,32 @@ export interface ShellHookInput {
491
702
  /** The agent the child runs, on `subagent_start` and `subagent_stop`. */
492
703
  readonly agentType?: string
493
704
  readonly prompt?: string
705
+ /** On `file_changed`: the file, absolute. Sent as `file_path`. */
706
+ readonly filePath?: string
707
+ /** On `file_changed`: what happened to it. Sent as `change`. */
708
+ readonly change?: PluginFileChange
709
+ /** On `cwd_changed`: the folder left and the folder entered. Sent as `old_cwd` and `new_cwd`. */
710
+ readonly oldCwd?: string
711
+ readonly newCwd?: string
712
+ /** On `worktree_create`: the suggested name. Sent as `name`. */
713
+ readonly worktreeName?: string
714
+ /** On `worktree_create`: where a relative path is placed. Sent as `worktree_root`. */
715
+ readonly worktreeRoot?: string
716
+ /** On `worktree_create`: the commit or branch asked for, when one was. Sent as `base_ref`. */
717
+ readonly worktreeBaseRef?: string
718
+ /** On `worktree_remove`: the worktree. Sent as `worktree_path`. */
719
+ readonly worktreePath?: string
720
+ /**
721
+ * The file this hook may append `export NAME=value` lines to. Sent as
722
+ * `NAMZU_ENV_FILE`; on every other event the variable is not set at all.
723
+ */
724
+ readonly envFile?: string
494
725
  readonly compaction?: PluginCompactionInfo
495
726
  readonly toolName?: string
727
+ /** The spelling `toolName` (and each `toolCalls` name) is sent in; absent is `namzu`. */
728
+ readonly toolNames?: ShellHookToolNames
729
+ /** The call's id, on the single-call tool events. Sent as `tool_use_id`. */
730
+ readonly toolCallId?: string
496
731
  readonly toolInput?: unknown
497
732
  readonly toolResult?: {
498
733
  readonly success: boolean
@@ -509,17 +744,27 @@ export interface ShellHookInput {
509
744
  readonly notification?: PluginNotificationInfo
510
745
  /** On `turn_end` and `subagent_stop`: an earlier answer already kept this turn going. */
511
746
  readonly stopHookActive?: boolean
747
+ /** On `turn_end` and `subagent_stop`: the model's last message of the turn. Sent as `last_assistant_message`. */
748
+ readonly lastAssistantMessage?: string
512
749
  /** The session's transcript file, when the host has one. Sent as `transcript_path`. */
513
750
  readonly transcriptPath?: string
514
751
  /** How tool calls are being decided right now. Sent as `permission_mode`. */
515
752
  readonly permissionMode?: string
753
+ /**
754
+ * Variables added to a command's environment, under the ones the kernel sets
755
+ * for every hook (`NAMZU_HOOK_EVENT` and the rest, which these never
756
+ * replace). Not part of the JSON the hook reads.
757
+ */
758
+ readonly extraEnv?: Readonly<Record<string, string>>
759
+ /** The skill's folder, when the hook came from a skill; see {@link ShellHookOptions.skillRoot}. */
760
+ readonly skillRoot?: string
516
761
  }
517
762
 
518
763
  /** The JSON a hook receives on stdin (or as an HTTP body). */
519
764
  export function shellHookPayload(input: ShellHookInput): string {
520
765
  return JSON.stringify({
521
766
  event: input.event,
522
- hook_event_name: PASCAL_EVENT_NAMES[input.event] ?? input.event,
767
+ hook_event_name: SHELL_HOOK_PASCAL_EVENT_NAMES[input.event] ?? input.event,
523
768
  cwd: input.cwd,
524
769
  session_id: input.sessionId,
525
770
  ...(input.transcriptPath !== undefined ? { transcript_path: input.transcriptPath } : {}),
@@ -532,9 +777,22 @@ export function shellHookPayload(input: ShellHookInput): string {
532
777
  ? { agent_id: input.sessionId, agent_type: input.agentType }
533
778
  : {}),
534
779
  ...(input.prompt !== undefined ? { prompt: input.prompt } : {}),
535
- ...(input.compaction !== undefined ? { compaction: input.compaction } : {}),
536
- ...(input.toolName !== undefined ? { tool_name: input.toolName } : {}),
537
- ...(input.toolInput !== undefined ? { tool_input: input.toolInput } : {}),
780
+ ...(input.filePath !== undefined ? { file_path: input.filePath } : {}),
781
+ ...(input.change !== undefined ? { change: input.change } : {}),
782
+ ...(input.oldCwd !== undefined ? { old_cwd: input.oldCwd } : {}),
783
+ ...(input.newCwd !== undefined ? { new_cwd: input.newCwd } : {}),
784
+ ...(input.worktreeName !== undefined ? { name: input.worktreeName } : {}),
785
+ ...(input.worktreeRoot !== undefined ? { worktree_root: input.worktreeRoot } : {}),
786
+ ...(input.worktreeBaseRef !== undefined ? { base_ref: input.worktreeBaseRef } : {}),
787
+ ...(input.worktreePath !== undefined ? { worktree_path: input.worktreePath } : {}),
788
+ ...(input.compaction !== undefined ? compactionFields(input.event, input.compaction) : {}),
789
+ ...(input.toolName !== undefined
790
+ ? { tool_name: shellHookToolName(input.toolName, input.toolNames) }
791
+ : {}),
792
+ ...(input.toolCallId !== undefined ? { tool_use_id: input.toolCallId } : {}),
793
+ ...(input.toolInput !== undefined
794
+ ? { tool_input: withFilePathKey(input.toolName, input.toolInput) }
795
+ : {}),
538
796
  ...(input.toolResult !== undefined
539
797
  ? { tool_result: input.toolResult, tool_response: input.toolResult }
540
798
  : {}),
@@ -544,8 +802,8 @@ export function shellHookPayload(input: ShellHookInput): string {
544
802
  ...(input.toolCalls !== undefined
545
803
  ? {
546
804
  tool_calls: input.toolCalls.map((call) => ({
547
- tool_name: call.toolName,
548
- tool_input: call.toolInput,
805
+ tool_name: shellHookToolName(call.toolName, input.toolNames),
806
+ tool_input: withFilePathKey(call.toolName, call.toolInput),
549
807
  tool_use_id: call.toolCallId,
550
808
  tool_response: call.output,
551
809
  is_error: call.isError,
@@ -565,9 +823,41 @@ export function shellHookPayload(input: ShellHookInput): string {
565
823
  }
566
824
  : {}),
567
825
  ...(input.stopHookActive === true ? { stop_hook_active: true } : {}),
826
+ ...(input.lastAssistantMessage !== undefined
827
+ ? { last_assistant_message: input.lastAssistantMessage }
828
+ : {}),
568
829
  })
569
830
  }
570
831
 
832
+ /**
833
+ * A compaction hook's fields. `compaction` keeps what it always had and gains
834
+ * `trigger`; the person's instructions and the summary are top-level
835
+ * (`custom_instructions`, null when there are none, and `compact_summary`),
836
+ * where a script reads them without opening the object.
837
+ */
838
+ function compactionFields(
839
+ event: ShellHookEvent,
840
+ compaction: PluginCompactionInfo,
841
+ ): Record<string, unknown> {
842
+ const { instructions, summary, ...rest } = compaction
843
+ return {
844
+ compaction: rest,
845
+ ...(compaction.trigger !== undefined ? { trigger: compaction.trigger } : {}),
846
+ ...(event === 'pre_compact' ? { custom_instructions: instructions ?? null } : {}),
847
+ ...(event === 'post_compact' && summary !== undefined ? { compact_summary: summary } : {}),
848
+ }
849
+ }
850
+
851
+ function isExecutableFile(path: string): boolean {
852
+ try {
853
+ if (!statSync(path).isFile()) return false
854
+ accessSync(path, constants.X_OK)
855
+ return true
856
+ } catch {
857
+ return false
858
+ }
859
+ }
860
+
571
861
  /** Run one hook command to completion, bounded by its deadline and capture. */
572
862
  export function runShellHook(
573
863
  entry: ShellHookEntry,
@@ -582,19 +872,72 @@ export function runShellHook(
582
872
  const toolPath = pathOf(input.toolInput)
583
873
  // A hook outside a turn must not see a turn id, including one the host
584
874
  // inherited from an enclosing hook's environment.
585
- const { NAMZU_TURN_ID: _inheritedTurnId, ...inherited } = process.env
875
+ // Nor the variables file of an enclosing hook: only the three events that own one get it.
876
+ const {
877
+ NAMZU_TURN_ID: _inheritedTurnId,
878
+ NAMZU_ENV_FILE: _inheritedEnvFile,
879
+ ...inherited
880
+ } = process.env
881
+ const projectDir = input.projectDir ?? input.cwd
882
+ const kernel = {
883
+ NAMZU_HOOK_EVENT: input.event,
884
+ NAMZU_SESSION_ID: input.sessionId,
885
+ NAMZU_PROJECT_DIR: projectDir,
886
+ ...(input.plugin !== undefined
887
+ ? { NAMZU_PLUGIN_ROOT: input.plugin.root, NAMZU_PLUGIN_DATA: input.plugin.dataDir }
888
+ : {}),
889
+ ...(input.turnId !== undefined ? { NAMZU_TURN_ID: input.turnId } : {}),
890
+ ...(input.envFile !== undefined ? { NAMZU_ENV_FILE: input.envFile } : {}),
891
+ ...(input.toolName !== undefined
892
+ ? { NAMZU_TOOL_NAME: shellHookToolName(input.toolName, input.toolNames) }
893
+ : {}),
894
+ ...(toolPath !== undefined ? { NAMZU_TOOL_PATH: toolPath } : {}),
895
+ }
896
+ // The entry's `env`, and any `..._PROJECT_DIR`, `..._PLUGIN_ROOT` or
897
+ // `..._PLUGIN_DATA` its command refers to without it being set, over the
898
+ // inherited environment; the kernel's own names last. A shell expands the
899
+ // variables itself, so a folder name is never read as shell text.
900
+ const pluginFolders = input.plugin
901
+ const { env, unset } = movedEnvironment(
902
+ entry,
903
+ { ...inherited, ...input.extraEnv, ...kernel },
904
+ kernel,
905
+ {
906
+ project: projectDir,
907
+ ...(input.skillRoot !== undefined ? { skill: input.skillRoot } : {}),
908
+ ...(input.envFile !== undefined ? { envFile: input.envFile } : {}),
909
+ ...(pluginFolders !== undefined
910
+ ? { plugin: pluginFolders.root, pluginData: pluginFolders.dataDir }
911
+ : {}),
912
+ },
913
+ )
914
+ // The exec form has no shell to expand them, so the values are put in.
915
+ const placed: ShellHookEntry =
916
+ entry.args === undefined
917
+ ? entry
918
+ : {
919
+ ...entry,
920
+ command: substituteMovedFolders(entry.command, env),
921
+ args: entry.args.map((arg) => substituteMovedFolders(arg, env)),
922
+ }
923
+ const unsetVariables = unset.length > 0 ? { unsetVariables: unset } : {}
924
+ if (pluginFolders !== undefined) {
925
+ try {
926
+ // Created when first needed; never inside the plugin's own folder.
927
+ mkdirSync(pluginFolders.dataDir, { recursive: true, mode: 0o700 })
928
+ } catch (error) {
929
+ return Promise.resolve({
930
+ exitCode: null,
931
+ timedOut: false,
932
+ stdout: '',
933
+ stderr: '',
934
+ spawnError: `the plugin's data folder could not be created (${error instanceof Error ? error.message : String(error)})`,
935
+ })
936
+ }
937
+ }
586
938
  return new Promise((resolve) => {
587
939
  let child: ReturnType<typeof spawn>
588
940
  try {
589
- const env = {
590
- ...inherited,
591
- NAMZU_HOOK_EVENT: input.event,
592
- NAMZU_SESSION_ID: input.sessionId,
593
- NAMZU_PROJECT_DIR: input.projectDir ?? input.cwd,
594
- ...(input.turnId !== undefined ? { NAMZU_TURN_ID: input.turnId } : {}),
595
- ...(input.toolName !== undefined ? { NAMZU_TOOL_NAME: input.toolName } : {}),
596
- ...(toolPath !== undefined ? { NAMZU_TOOL_PATH: toolPath } : {}),
597
- }
598
941
  // Its own process group, so the deadline can kill everything the
599
942
  // command started. `sh -c 'sleep 5'` is one process under a shell
600
943
  // that execs its last command and two under one that forks it;
@@ -603,15 +946,15 @@ export function runShellHook(
603
946
  // its own — the hook's deadline becomes the grandchild's.
604
947
  const detached = process.platform !== 'win32'
605
948
  child =
606
- entry.args !== undefined
949
+ placed.args !== undefined
607
950
  ? // The exec form: no shell reads `command` or any argument.
608
- spawn(entry.command, [...entry.args], {
951
+ spawn(placed.command, [...placed.args], {
609
952
  cwd: input.cwd,
610
953
  env: withSessionChildMarker(env),
611
954
  stdio: ['pipe', 'pipe', 'pipe'],
612
955
  detached,
613
956
  })
614
- : spawnHostShell(entry.command, {
957
+ : spawnHostShell(placed.command, {
615
958
  cwd: input.cwd,
616
959
  env,
617
960
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -621,7 +964,20 @@ export function runShellHook(
621
964
  // when installed, cmd.exe when not.
622
965
  ...(process.platform === 'win32'
623
966
  ? {}
624
- : { shell: { path: 'sh', dialect: 'sh', source: 'sh' } as const }),
967
+ : {
968
+ shell: {
969
+ path:
970
+ shellPathOutsideEnv(
971
+ 'sh',
972
+ inherited.PATH,
973
+ env.PATH,
974
+ isExecutableFile,
975
+ delimiter,
976
+ ) ?? 'sh',
977
+ dialect: 'sh',
978
+ source: 'sh',
979
+ } as const,
980
+ }),
625
981
  })
626
982
  } catch (error) {
627
983
  resolve({
@@ -630,6 +986,7 @@ export function runShellHook(
630
986
  stdout: '',
631
987
  stderr: '',
632
988
  spawnError: error instanceof Error ? error.message : String(error),
989
+ ...unsetVariables,
633
990
  })
634
991
  return
635
992
  }
@@ -687,6 +1044,7 @@ export function runShellHook(
687
1044
  stderr,
688
1045
  ...(stdoutTruncated ? { stdoutTruncated } : {}),
689
1046
  spawnError: error.message,
1047
+ ...unsetVariables,
690
1048
  })
691
1049
  })
692
1050
  child.on('close', (code) => {
@@ -696,6 +1054,7 @@ export function runShellHook(
696
1054
  stdout,
697
1055
  stderr,
698
1056
  ...(stdoutTruncated ? { stdoutTruncated } : {}),
1057
+ ...unsetVariables,
699
1058
  })
700
1059
  })
701
1060
  child.on('exit', () => {
@@ -713,6 +1072,56 @@ export function runShellHook(
713
1072
  })
714
1073
  }
715
1074
 
1075
+ /**
1076
+ * The tools whose input names a file or folder `path`. A moved script reads
1077
+ * that file under the key `file_path`, so the input a hook receives carries
1078
+ * both, with the same value.
1079
+ */
1080
+ const FILE_PATH_TOOLS: ReadonlySet<string> = new Set([
1081
+ 'read',
1082
+ 'write',
1083
+ 'edit',
1084
+ 'grep',
1085
+ 'glob',
1086
+ 'ls',
1087
+ 'view_image',
1088
+ 'lsp',
1089
+ ])
1090
+
1091
+ /** `toolInput` as a hook receives it: a file tool's `path` is also `file_path`. */
1092
+ function withFilePathKey(toolName: string | undefined, toolInput: unknown): unknown {
1093
+ if (toolName === undefined || !FILE_PATH_TOOLS.has(toolName.toLowerCase())) return toolInput
1094
+ if (!isRecord(toolInput)) return toolInput
1095
+ const path = toolInput.path
1096
+ if (typeof path !== 'string' || 'file_path' in toolInput) return toolInput
1097
+ return { ...toolInput, file_path: path }
1098
+ }
1099
+
1100
+ /**
1101
+ * A rewritten input read back. An echoed `file_path` is never a reason to
1102
+ * refuse the rewrite: when only one of the two keys was changed that change is
1103
+ * the new path; when both were changed to different values the answer cannot be
1104
+ * read (`undefined`). The tool never sees `file_path`.
1105
+ */
1106
+ function readRewrittenInput(
1107
+ toolName: string | undefined,
1108
+ original: unknown,
1109
+ rewritten: Record<string, unknown>,
1110
+ ): Record<string, unknown> | undefined {
1111
+ if (toolName === undefined || !FILE_PATH_TOOLS.has(toolName.toLowerCase())) return rewritten
1112
+ if (!('file_path' in rewritten)) return rewritten
1113
+ const { file_path: echoed, ...rest } = rewritten
1114
+ const before = isRecord(original) ? original.path : undefined
1115
+ const pathChanged = 'path' in rest && rest.path !== before
1116
+ const echoChanged = echoed !== before
1117
+ if (pathChanged && echoChanged && echoed !== rest.path) return undefined
1118
+ if (!pathChanged && echoChanged) {
1119
+ if (typeof echoed !== 'string') return undefined
1120
+ return { ...rest, path: echoed }
1121
+ }
1122
+ return rest
1123
+ }
1124
+
716
1125
  function pathOf(toolInput: unknown): string | undefined {
717
1126
  if (toolInput === null || typeof toolInput !== 'object') return undefined
718
1127
  const record = toolInput as Record<string, unknown>
@@ -724,7 +1133,7 @@ function pathOf(toolInput: unknown): string | undefined {
724
1133
  }
725
1134
 
726
1135
  /** The PascalCase spelling of each event name, which a hook's JSON may use. */
727
- const PASCAL_EVENT_NAMES: Readonly<Partial<Record<ShellHookEvent, string>>> = {
1136
+ export const SHELL_HOOK_PASCAL_EVENT_NAMES: Readonly<Partial<Record<ShellHookEvent, string>>> = {
728
1137
  user_prompt_submit: 'UserPromptSubmit',
729
1138
  session_start: 'SessionStart',
730
1139
  session_end: 'SessionEnd',
@@ -741,6 +1150,10 @@ const PASCAL_EVENT_NAMES: Readonly<Partial<Record<ShellHookEvent, string>>> = {
741
1150
  permission_denied: 'PermissionDenied',
742
1151
  turn_failure: 'StopFailure',
743
1152
  turn_end: 'Stop',
1153
+ file_changed: 'FileChanged',
1154
+ cwd_changed: 'CwdChanged',
1155
+ worktree_create: 'WorktreeCreate',
1156
+ worktree_remove: 'WorktreeRemove',
744
1157
  }
745
1158
 
746
1159
  /** What a hook's stdout JSON said, before it is mapped to a verdict for an event. */
@@ -756,10 +1169,46 @@ interface ShellHookReading {
756
1169
  replacement?: string
757
1170
  /** The hook asked for its stdout to stay out of the debug log. */
758
1171
  suppressOutput?: boolean
1172
+ /** On `session_start`, `file_changed` and `cwd_changed`: the files to watch from now on. */
1173
+ watchPaths?: readonly string[]
759
1174
  /** Why the JSON was set aside, when it was. */
760
1175
  invalid?: string
761
1176
  }
762
1177
 
1178
+ /** The keys that carry a replacement for a tool's result. */
1179
+ const REPLACEMENT_KEYS = ['updatedToolOutput', 'updatedMCPToolOutput'] as const
1180
+
1181
+ /** The tool tied to an answer: what a rewrite or a replacement is read against. */
1182
+ export interface ShellHookCall {
1183
+ readonly toolName?: string
1184
+ readonly toolInput?: unknown
1185
+ }
1186
+
1187
+ /**
1188
+ * A replacement for a tool's result, whatever its JSON type. A string is the
1189
+ * text; an object that has the shape of the result object a hook is sent
1190
+ * (`output` a string, `success` a boolean and `error` a string when present)
1191
+ * is read as that; anything else (another object, an array, a number, a
1192
+ * boolean) is shown as its JSON text. The call's own success is not changed.
1193
+ */
1194
+ function replacementText(value: unknown): string {
1195
+ if (typeof value === 'string') return value
1196
+ if (
1197
+ isRecord(value) &&
1198
+ typeof value.output === 'string' &&
1199
+ (value.success === undefined || typeof value.success === 'boolean') &&
1200
+ (value.error === undefined || typeof value.error === 'string')
1201
+ ) {
1202
+ if (value.success === false && typeof value.error === 'string' && value.error !== '') {
1203
+ return value.output === ''
1204
+ ? `Error: ${value.error}`
1205
+ : `${value.output}\n\nError: ${value.error}`
1206
+ }
1207
+ return value.output
1208
+ }
1209
+ return JSON.stringify(value)
1210
+ }
1211
+
763
1212
  function isRecord(value: unknown): value is Record<string, unknown> {
764
1213
  return value !== null && typeof value === 'object' && !Array.isArray(value)
765
1214
  }
@@ -770,7 +1219,11 @@ function isRecord(value: unknown): value is Record<string, unknown> {
770
1219
  * sets the whole object aside rather than half-obeying it, so a typo in a
771
1220
  * guard's `decision` is reported instead of silently becoming "continue".
772
1221
  */
773
- function readShellHookJson(event: ShellHookEvent, stdout: string): ShellHookReading | undefined {
1222
+ function readShellHookJson(
1223
+ event: ShellHookEvent,
1224
+ stdout: string,
1225
+ call: ShellHookCall = {},
1226
+ ): ShellHookReading | undefined {
774
1227
  const text = stdout.trim()
775
1228
  if (!text.startsWith('{')) return undefined
776
1229
  let parsed: unknown
@@ -815,6 +1268,36 @@ function readShellHookJson(event: ShellHookEvent, stdout: string): ShellHookRead
815
1268
  return { invalid: '`decision` must be "approve" or "block"' }
816
1269
  }
817
1270
 
1271
+ // A replacement written where it is not read (at the top level of the answer
1272
+ // instead of under `hookSpecificOutput`) is a hook that clearly tried to say
1273
+ // something we cannot read: set the answer aside as unreadable, so
1274
+ // `onFailure: block` withholds the result rather than showing the original.
1275
+ if (event === 'post_tool_use' || event === 'post_tool_use_failure') {
1276
+ const misplaced = REPLACEMENT_KEYS.find((key) => parsed[key] !== undefined)
1277
+ const inSpecific =
1278
+ isRecord(parsed.hookSpecificOutput) &&
1279
+ REPLACEMENT_KEYS.some(
1280
+ (key) => (parsed.hookSpecificOutput as Record<string, unknown>)[key] !== undefined,
1281
+ )
1282
+ if (misplaced !== undefined && !inSpecific) {
1283
+ return {
1284
+ invalid: `\`${misplaced}\` is read under \`hookSpecificOutput\`, not at the top level of the answer`,
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ // The same for a list of files to watch written at the top level.
1290
+ if (
1291
+ (event === 'session_start' || event === 'file_changed' || event === 'cwd_changed') &&
1292
+ parsed.watchPaths !== undefined &&
1293
+ !(isRecord(parsed.hookSpecificOutput) && parsed.hookSpecificOutput.watchPaths !== undefined)
1294
+ ) {
1295
+ return {
1296
+ invalid:
1297
+ '`watchPaths` is read under `hookSpecificOutput`, not at the top level of the answer',
1298
+ }
1299
+ }
1300
+
818
1301
  const reading: ShellHookReading = {}
819
1302
  if (parsed.suppressOutput === true) reading.suppressOutput = true
820
1303
  const systemMessage = optionalString('systemMessage')
@@ -836,7 +1319,7 @@ function readShellHookJson(event: ShellHookEvent, stdout: string): ShellHookRead
836
1319
  if (typeof named !== 'string') {
837
1320
  return { invalid: '`hookSpecificOutput` is missing its `hookEventName`' }
838
1321
  }
839
- if (named !== event && named !== PASCAL_EVENT_NAMES[event]) {
1322
+ if (named !== event && named !== SHELL_HOOK_PASCAL_EVENT_NAMES[event]) {
840
1323
  return {
841
1324
  invalid: `\`hookSpecificOutput.hookEventName\` is "${named}" but this hook ran for ${event}`,
842
1325
  }
@@ -848,6 +1331,16 @@ function readShellHookJson(event: ShellHookEvent, stdout: string): ShellHookRead
848
1331
  const problem = wrongType(key, type, specific)
849
1332
  if (problem) return { invalid: `hookSpecificOutput: ${problem}` }
850
1333
  }
1334
+ if (
1335
+ (event === 'session_start' || event === 'file_changed' || event === 'cwd_changed') &&
1336
+ specific.watchPaths !== undefined
1337
+ ) {
1338
+ const list = specific.watchPaths
1339
+ if (!Array.isArray(list) || list.some((item) => typeof item !== 'string')) {
1340
+ return { invalid: 'hookSpecificOutput: `watchPaths` must be a list of paths (strings)' }
1341
+ }
1342
+ reading.watchPaths = (list as string[]).filter((item) => item.trim() !== '')
1343
+ }
851
1344
  const additional = optionalString('additionalContext', specific)
852
1345
  if (additional && additional.trim().length > 0) reading.context = additional.trim()
853
1346
 
@@ -869,14 +1362,27 @@ function readShellHookJson(event: ShellHookEvent, stdout: string): ShellHookRead
869
1362
  }
870
1363
  if (specific.updatedInput !== undefined) {
871
1364
  if (!isRecord(specific.updatedInput)) return { invalid: '`updatedInput` must be an object' }
872
- reading.updatedInput = specific.updatedInput
1365
+ const rewritten = readRewrittenInput(call.toolName, call.toolInput, specific.updatedInput)
1366
+ if (rewritten === undefined) {
1367
+ return {
1368
+ invalid:
1369
+ '`updatedInput` changes both `path` and `file_path`, to different values: say which file is meant',
1370
+ }
1371
+ }
1372
+ reading.updatedInput = rewritten
873
1373
  }
874
1374
  }
875
- if (event === 'post_tool_use' && specific.updatedToolOutput !== undefined) {
876
- if (typeof specific.updatedToolOutput !== 'string') {
877
- return { invalid: 'hookSpecificOutput: `updatedToolOutput` must be a string' }
1375
+ if (event === 'post_tool_use' || event === 'post_tool_use_failure') {
1376
+ // For a tool-server tool the common contract has a second field, read
1377
+ // when `updatedToolOutput` is absent or null. `updatedToolOutput` wins when
1378
+ // both carry a value: it is the field for every tool, so a script that
1379
+ // sets both has said the general thing last.
1380
+ const toolServer = call.toolName?.startsWith('mcp__') === true
1381
+ const chosen =
1382
+ specific.updatedToolOutput ?? (toolServer ? specific.updatedMCPToolOutput : undefined)
1383
+ if (chosen !== undefined && chosen !== null) {
1384
+ reading.replacement = boundHookReplacement(replacementText(chosen))
878
1385
  }
879
- reading.replacement = boundHookReplacement(specific.updatedToolOutput)
880
1386
  }
881
1387
  if (event === 'permission_request') {
882
1388
  const decision = specific.decision
@@ -907,17 +1413,23 @@ export function shellHookVerdict(
907
1413
  entry: ShellHookHandler,
908
1414
  outcome: ShellHookOutcome,
909
1415
  log: Logger = NOOP_LOGGER,
1416
+ call: ShellHookCall = {},
910
1417
  ): PluginHookResult {
911
1418
  const label = describeShellHook(entry)
912
1419
  const attrs = {
913
1420
  'namzu.hook.event': event,
914
1421
  'namzu.hook.command': label,
915
1422
  }
1423
+ // A program or file that was not found, with a variable in the command that
1424
+ // is set nowhere: the line says which, and what to do about it.
1425
+ const hint = hookUnsetVariableHint(outcome)
916
1426
  // A failure of the hook itself is "carry on" unless the entry asked for
917
1427
  // it to count as a refusal, which is exit 2 with the failure as the reason.
918
1428
  const failed = (reason: string, shown: string = reason): PluginHookResult => {
919
1429
  if (entry.onFailure !== 'block' || entry.type === 'prompt' || isAsyncShellHook(entry)) {
920
- return { action: 'continue' }
1430
+ return hint !== undefined
1431
+ ? { action: 'continue', notice: `${label}: ${hint}` }
1432
+ : { action: 'continue' }
921
1433
  }
922
1434
  // The call has run and a refusal cannot undo it, but the hook may have
923
1435
  // been the one thing keeping something out of the result (a redaction),
@@ -937,14 +1449,16 @@ export function shellHookVerdict(
937
1449
  { ...entry, onFailure: 'continue' },
938
1450
  { exitCode: 2, timedOut: false, stdout: '', stderr: `hook failed: ${reason}` },
939
1451
  log,
1452
+ call,
940
1453
  )
941
1454
  }
942
1455
  if (outcome.spawnError !== undefined) {
943
1456
  log.warn('hook could not start', {
944
1457
  ...attrs,
945
1458
  'namzu.hook.error': outcome.spawnError,
1459
+ ...(hint !== undefined ? { 'namzu.hook.hint': hint } : {}),
946
1460
  })
947
- return failed(`could not start (${outcome.spawnError})`)
1461
+ return failed(`could not start (${outcome.spawnError})${hint !== undefined ? `; ${hint}` : ''}`)
948
1462
  }
949
1463
  if (outcome.timedOut) {
950
1464
  log.warn('hook timed out', attrs)
@@ -981,8 +1495,11 @@ export function shellHookVerdict(
981
1495
  ...attrs,
982
1496
  'namzu.hook.exit': outcome.exitCode ?? -1,
983
1497
  'namzu.hook.stderr': outcome.stderr.trim().slice(0, 500),
1498
+ ...(hint !== undefined ? { 'namzu.hook.hint': hint } : {}),
984
1499
  })
985
- return failed(`exited with ${outcome.exitCode ?? 'no code'}`)
1500
+ return failed(
1501
+ `exited with ${outcome.exitCode ?? 'no code'}${hint !== undefined ? `; ${hint}` : ''}`,
1502
+ )
986
1503
  }
987
1504
 
988
1505
  // Exit 0.
@@ -992,13 +1509,31 @@ export function shellHookVerdict(
992
1509
  ? {
993
1510
  invalid: `answer is too large: the hook printed more than the ${MAX_CAPTURE_BYTES} characters of stdout that are read`,
994
1511
  }
995
- : readShellHookJson(event, outcome.stdout)
1512
+ : readShellHookJson(event, outcome.stdout, call)
996
1513
  if (reading === undefined) {
1514
+ // A post-tool hook whose plain output (or whose stderr) names a replacement
1515
+ // key tried to replace the result and put the answer where it is not read
1516
+ // (a log line before the JSON, the JSON on stderr). That is an answer that
1517
+ // does not read, so it follows `onFailure` like one.
1518
+ if (
1519
+ (event === 'post_tool_use' || event === 'post_tool_use_failure') &&
1520
+ REPLACEMENT_KEYS.some((key) => outcome.stdout.includes(key) || outcome.stderr.includes(key))
1521
+ ) {
1522
+ log.warn('hook output ignored', {
1523
+ ...attrs,
1524
+ 'namzu.hook.problem':
1525
+ 'a replacement is named but the answer is not a JSON object on stdout',
1526
+ })
1527
+ return failed('its answer names a replacement but is not a JSON object that starts stdout')
1528
+ }
997
1529
  // On the prompt event, what the hook printed is context for the
998
1530
  // model — the branch, the time, a ticket. Everywhere else stdout is
999
1531
  // the operator's to read and the model's business not at all.
1000
1532
  if (
1001
- (event === 'user_prompt_submit' || event === 'subagent_start' || event === 'session_start') &&
1533
+ (event === 'user_prompt_submit' ||
1534
+ event === 'subagent_start' ||
1535
+ event === 'session_start' ||
1536
+ event === 'pre_compact') &&
1002
1537
  text.length > 0
1003
1538
  )
1004
1539
  return { action: 'annotate', text }
@@ -1064,13 +1599,33 @@ export function shellHookVerdict(
1064
1599
  // Nothing here can be refused. What the hook said for the model becomes
1065
1600
  // the session's context; a stop request and a warning still count.
1066
1601
  return reading.context !== undefined
1067
- ? { action: 'annotate', text: reading.context }
1602
+ ? {
1603
+ action: 'annotate',
1604
+ text: reading.context,
1605
+ ...(reading.watchPaths !== undefined ? { watchPaths: reading.watchPaths } : {}),
1606
+ ...(reading.notice ? { notice: reading.notice } : {}),
1607
+ }
1068
1608
  : {
1069
1609
  action: 'continue',
1070
1610
  ...(reading.halt ? { halt: reading.halt } : {}),
1071
1611
  ...(reading.notice ? { notice: reading.notice } : {}),
1612
+ ...(reading.watchPaths !== undefined ? { watchPaths: reading.watchPaths } : {}),
1072
1613
  }
1073
1614
  }
1615
+ case 'worktree_create':
1616
+ case 'worktree_remove':
1617
+ // Read by `worktreeHookVerdict`, which the handler calls for these two
1618
+ // events; a caller that gets here has no run to read.
1619
+ return { action: 'continue' }
1620
+ case 'file_changed':
1621
+ case 'cwd_changed':
1622
+ // Nothing here can be refused and nothing reaches the model: what the hook
1623
+ // can say is a line for the person and the files to watch from now on.
1624
+ return {
1625
+ action: 'continue',
1626
+ ...(reading.notice ? { notice: reading.notice } : {}),
1627
+ ...(reading.watchPaths !== undefined ? { watchPaths: reading.watchPaths } : {}),
1628
+ }
1074
1629
  case 'post_tool_use':
1075
1630
  case 'post_tool_use_failure': {
1076
1631
  // The call has run, so a "block" cannot undo it: its reason is what the
@@ -1118,6 +1673,8 @@ export function shellHookVerdict(
1118
1673
  }
1119
1674
  }
1120
1675
  case 'pre_compact':
1676
+ // What the hook said is for the summariser: it rides as `context` on
1677
+ // either answer (a refusal a forced pass overrides is still heard).
1121
1678
  return reading.block !== undefined
1122
1679
  ? { action: 'skip', reason: reading.block, ...notes }
1123
1680
  : { action: 'continue', ...notes }
@@ -1189,6 +1746,33 @@ export interface ShellHookOptions {
1189
1746
  * `NAMZU_PROJECT_DIR`. Absent, `cwd`.
1190
1747
  */
1191
1748
  readonly projectDir?: string
1749
+ /**
1750
+ * Variables added to the environment of every command this adapter runs,
1751
+ * beside the ones the kernel sets for each hook, which they never replace.
1752
+ * For a host that attaches a group of hooks with something in common (a
1753
+ * skill's folder).
1754
+ */
1755
+ readonly extraEnv?: Readonly<Record<string, string>>
1756
+ /**
1757
+ * Called when a hook of this adapter was selected to run (its matcher and
1758
+ * `if` allowed it), before it runs. For a host that decides what happens to
1759
+ * a hook once it has run (removing it after a first successful run).
1760
+ */
1761
+ readonly onRun?: (info: { readonly event: ShellHookEvent }) => void
1762
+ /**
1763
+ * Set when the entries belong to a plugin: its own folder and the folder kept
1764
+ * for its data, given to every command as `NAMZU_PLUGIN_ROOT` and
1765
+ * `NAMZU_PLUGIN_DATA` and put in the command and arguments where they name
1766
+ * them. The data folder is created when a command first runs.
1767
+ */
1768
+ readonly plugin?: PluginFolders
1769
+ /**
1770
+ * Set when the entries belong to a skill: the skill's own folder. A variable
1771
+ * the command refers to without it being set, whose name ends in
1772
+ * `_PLUGIN_ROOT` or `_SKILL_ROOT`, is given this folder under the name the
1773
+ * command used (a skill moved as written names its folder that way).
1774
+ */
1775
+ readonly skillRoot?: string
1192
1776
  /** How a path pattern in an entry's `if` is read. Absent, such a filter runs the hook. */
1193
1777
  readonly pathFilter?: ShellHookPathFilter
1194
1778
  /**
@@ -1197,6 +1781,13 @@ export interface ShellHookOptions {
1197
1781
  * the cap). Absent, or an event not listed, the ordinary default applies.
1198
1782
  */
1199
1783
  readonly defaultTimeoutMs?: { readonly [event in ShellHookEvent]?: number }
1784
+ /**
1785
+ * Where the variables a hook sets for later commands are kept. With it, a
1786
+ * command hook on `session_start`, `cwd_changed` or `file_changed` is
1787
+ * started with `NAMZU_ENV_FILE`, and the file is read when the hook ends.
1788
+ * Without it no hook gets the variable and nothing is carried.
1789
+ */
1790
+ readonly hookEnv?: SessionHookEnv
1200
1791
  /**
1201
1792
  * Called when a hook of this adapter ran out its deadline and was ended.
1202
1793
  * `hook` is the command, URL or prompt text the entry names.
@@ -1304,6 +1895,56 @@ function readJudgement(reply: string): { ok: boolean; reason: string } | undefin
1304
1895
  }
1305
1896
  }
1306
1897
 
1898
+ /**
1899
+ * One run of a `worktree_create` or `worktree_remove` hook, to its answer. It
1900
+ * is always awaited (an `async` flag cannot make a hook that does the work run
1901
+ * out of sight), and a `prompt` hook cannot do it at all, which is said as a
1902
+ * failure rather than skipped.
1903
+ */
1904
+ async function runWorktreeHook(
1905
+ event: 'worktree_create' | 'worktree_remove',
1906
+ entry: ShellHookHandler,
1907
+ input: ShellHookInput,
1908
+ signal: AbortSignal | undefined,
1909
+ reportTimeout: (timedOut: boolean) => void,
1910
+ ): Promise<PluginHookResult> {
1911
+ const label = describeShellHook(entry)
1912
+ if (entry.type === 'prompt') {
1913
+ return {
1914
+ action: 'error',
1915
+ message: `The ${event} hook \`${label}\` is a prompt, and a prompt cannot make or remove a worktree. Use a command or an http hook.`,
1916
+ }
1917
+ }
1918
+ if (entry.type === 'http') {
1919
+ const response = await postHookJson({
1920
+ url: entry.url,
1921
+ body: shellHookPayload(input),
1922
+ ...(entry.headers !== undefined ? { headers: entry.headers } : {}),
1923
+ ...(entry.allowedEnvVars !== undefined ? { allowedEnvVars: entry.allowedEnvVars } : {}),
1924
+ timeoutMs: hookTimeout(entry),
1925
+ ...(signal !== undefined ? { signal } : {}),
1926
+ })
1927
+ reportTimeout(response.timedOut)
1928
+ const ok = response.status !== null && response.status >= 200 && response.status < 300
1929
+ return worktreeHookVerdict(event, label, {
1930
+ exitCode: ok ? 0 : (response.status ?? null),
1931
+ timedOut: response.timedOut,
1932
+ stdout: ok ? response.body : '',
1933
+ stderr: ok ? '' : response.body.slice(0, 500),
1934
+ ...(response.error !== undefined ? { spawnError: response.error } : {}),
1935
+ })
1936
+ }
1937
+ const outcome = await runShellHook(entry, input, signal)
1938
+ reportTimeout(outcome.timedOut)
1939
+ return worktreeHookVerdict(event, label, outcome)
1940
+ }
1941
+
1942
+ /**
1943
+ * The place a hook has among the ones that set variables: entries are made in
1944
+ * configuration order, so a later number is a later line in the file.
1945
+ */
1946
+ let nextHookEnvSlot = 0
1947
+
1307
1948
  /** One entry as a hook definition the lifecycle manager accepts. */
1308
1949
  export function createShellHook(
1309
1950
  event: ShellHookEvent,
@@ -1311,6 +1952,7 @@ export function createShellHook(
1311
1952
  options: ShellHookOptions,
1312
1953
  ): PluginHookDefinition {
1313
1954
  const log = options.log ?? NOOP_LOGGER
1955
+ const envSlot = nextHookEnvSlot++
1314
1956
  const eventDefault = options.defaultTimeoutMs?.[event]
1315
1957
  const entry: ShellHookHandler =
1316
1958
  configured.timeoutMs === undefined && eventDefault !== undefined
@@ -1328,10 +1970,18 @@ export function createShellHook(
1328
1970
  return {
1329
1971
  event,
1330
1972
  ...(entry.statusMessage !== undefined ? { statusMessage: entry.statusMessage } : {}),
1973
+ // A file named by the matcher is watched for as long as the hook is attached.
1974
+ ...(event === 'file_changed' && fileChangedMatcherPaths(entry.matcher).length > 0
1975
+ ? { watches: fileChangedMatcherPaths(entry.matcher) }
1976
+ : {}),
1331
1977
  handler: async (context: PluginHookContext) => {
1332
- if (spent) return { action: 'continue' }
1978
+ if (spent && event !== 'worktree_create' && event !== 'worktree_remove') {
1979
+ return { action: 'continue' }
1980
+ }
1333
1981
  // A notification is matched on its type; every other event on the tool.
1334
1982
  const namesATool = !(
1983
+ event === 'pre_compact' ||
1984
+ event === 'post_compact' ||
1335
1985
  event === 'notification' ||
1336
1986
  event === 'subagent_start' ||
1337
1987
  event === 'subagent_stop' ||
@@ -1341,25 +1991,67 @@ export function createShellHook(
1341
1991
  const subject =
1342
1992
  event === 'notification'
1343
1993
  ? context.notification?.type
1344
- : event === 'subagent_start' || event === 'subagent_stop'
1345
- ? context.agentType
1346
- : event === 'session_start'
1347
- ? context.source
1348
- : event === 'session_end'
1349
- ? context.endReason
1350
- : context.toolName
1351
- if (!shellHookMatches(entry.matcher, subject, { tool: namesATool }))
1994
+ : event === 'pre_compact' || event === 'post_compact'
1995
+ ? context.compaction?.trigger
1996
+ : event === 'subagent_start' || event === 'subagent_stop'
1997
+ ? context.agentType
1998
+ : event === 'session_start'
1999
+ ? context.source
2000
+ : event === 'session_end'
2001
+ ? context.endReason
2002
+ : context.toolName
2003
+ // An event that has no name to match (`turn_end`, `user_prompt_submit`,
2004
+ // `turn_start`, `post_tool_batch`) ignores the matcher and the hook
2005
+ // fires: a matcher cannot be read against a name that is not there, and
2006
+ // a guard that never fires is the failure to avoid. The compaction
2007
+ // events are matched on `trigger`.
2008
+ if (subject !== undefined && !shellHookMatches(entry.matcher, subject, { tool: namesATool }))
1352
2009
  return { action: 'continue' }
1353
- if (!shellHookIfMatches(entry.if, context.toolName, context.toolInput, options.pathFilter)) {
2010
+ // A changed file is matched on its base name, and a matcher written as a
2011
+ // path stands for the file's name: `config/app.json` is `app.json`.
2012
+ if (event === 'file_changed' && !fileChangedMatches(entry.matcher, context.filePath)) {
1354
2013
  return { action: 'continue' }
1355
2014
  }
1356
- if (entry.once === true) spent = true
2015
+ // A worktree hook does the work itself, so a filter or a one-shot flag on
2016
+ // it could only make the kernel act where the person wanted the hook to:
2017
+ // both are ignored there, and the hook always runs.
2018
+ const doesTheWork = event === 'worktree_create' || event === 'worktree_remove'
2019
+ if (
2020
+ !doesTheWork &&
2021
+ !shellHookIfMatches(entry.if, context.toolName, context.toolInput, options.pathFilter)
2022
+ ) {
2023
+ return { action: 'continue' }
2024
+ }
2025
+ if (entry.once === true && !doesTheWork) spent = true
2026
+ options.onRun?.({ event })
1357
2027
  const transcriptPath = options.transcriptPath?.(String(context.sessionId))
1358
2028
  const permissionMode = options.permissionMode?.()
2029
+ const envEvent =
2030
+ event === 'session_start' || event === 'cwd_changed' || event === 'file_changed'
2031
+ ? event
2032
+ : undefined
2033
+ const runsACommand = entry.type === undefined || entry.type === 'command'
2034
+ const envFile =
2035
+ envEvent !== undefined && runsACommand
2036
+ ? options.hookEnv?.fileFor(envEvent, envSlot)
2037
+ : undefined
1359
2038
  const hookInput: ShellHookInput = {
1360
2039
  event,
1361
- cwd: options.cwd,
2040
+ // A hook told the folder changed runs in the folder entered.
2041
+ cwd: event === 'cwd_changed' && context.newCwd !== undefined ? context.newCwd : options.cwd,
2042
+ ...(envFile !== undefined ? { envFile } : {}),
2043
+ ...(context.filePath !== undefined ? { filePath: context.filePath } : {}),
2044
+ ...(context.change !== undefined ? { change: context.change } : {}),
2045
+ ...(context.oldCwd !== undefined ? { oldCwd: context.oldCwd } : {}),
2046
+ ...(context.newCwd !== undefined ? { newCwd: context.newCwd } : {}),
2047
+ ...(context.worktreeName !== undefined ? { worktreeName: context.worktreeName } : {}),
2048
+ ...(context.worktreeRoot !== undefined ? { worktreeRoot: context.worktreeRoot } : {}),
2049
+ ...(context.worktreeBaseRef !== undefined
2050
+ ? { worktreeBaseRef: context.worktreeBaseRef }
2051
+ : {}),
2052
+ ...(context.worktreePath !== undefined ? { worktreePath: context.worktreePath } : {}),
1362
2053
  ...(options.projectDir !== undefined ? { projectDir: options.projectDir } : {}),
2054
+ ...(options.plugin !== undefined ? { plugin: options.plugin } : {}),
1363
2055
  sessionId: String(context.sessionId),
1364
2056
  ...(context.source !== undefined ? { sessionSource: context.source } : {}),
1365
2057
  ...(context.endReason !== undefined ? { endReason: context.endReason } : {}),
@@ -1374,6 +2066,8 @@ export function createShellHook(
1374
2066
  ...(context.prompt !== undefined ? { prompt: context.prompt } : {}),
1375
2067
  ...(context.compaction !== undefined ? { compaction: context.compaction } : {}),
1376
2068
  ...(context.toolName !== undefined ? { toolName: context.toolName } : {}),
2069
+ ...(entry.toolNames !== undefined ? { toolNames: entry.toolNames } : {}),
2070
+ ...(context.toolCallId !== undefined ? { toolCallId: context.toolCallId } : {}),
1377
2071
  ...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
1378
2072
  ...(context.toolResult !== undefined
1379
2073
  ? {
@@ -1391,8 +2085,20 @@ export function createShellHook(
1391
2085
  ...(context.error !== undefined ? { error: context.error } : {}),
1392
2086
  ...(context.notification !== undefined ? { notification: context.notification } : {}),
1393
2087
  ...(context.stopHookActive === true ? { stopHookActive: true } : {}),
2088
+ ...(context.lastAssistantMessage !== undefined
2089
+ ? { lastAssistantMessage: context.lastAssistantMessage }
2090
+ : {}),
1394
2091
  ...(transcriptPath !== undefined ? { transcriptPath } : {}),
1395
2092
  ...(permissionMode !== undefined ? { permissionMode } : {}),
2093
+ ...(options.extraEnv !== undefined ? { extraEnv: options.extraEnv } : {}),
2094
+ ...(options.skillRoot !== undefined ? { skillRoot: options.skillRoot } : {}),
2095
+ }
2096
+ const verdictCall: ShellHookCall = {
2097
+ ...(context.toolName !== undefined ? { toolName: context.toolName } : {}),
2098
+ ...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
2099
+ }
2100
+ if (event === 'worktree_create' || event === 'worktree_remove') {
2101
+ return runWorktreeHook(event, entry, hookInput, context.signal, reportTimeout)
1396
2102
  }
1397
2103
  if (entry.type === 'http') {
1398
2104
  const response = await postHookJson({
@@ -1416,6 +2122,7 @@ export function createShellHook(
1416
2122
  ...(response.error !== undefined ? { spawnError: response.error } : {}),
1417
2123
  },
1418
2124
  log,
2125
+ verdictCall,
1419
2126
  )
1420
2127
  }
1421
2128
  if (entry.type === 'prompt') {
@@ -1426,14 +2133,25 @@ export function createShellHook(
1426
2133
  // for it and its own failure is only written down.
1427
2134
  void runShellHook(entry, hookInput)
1428
2135
  .then((outcome) => {
1429
- shellHookVerdict(event, entry, outcome, log)
2136
+ if (envEvent !== undefined) options.hookEnv?.absorb(envEvent, envSlot)
2137
+ const verdict = shellHookVerdict(event, entry, outcome, log, verdictCall)
2138
+ if (verdict.action !== 'continue') {
2139
+ log.warn('an async hook answered, and its answer is not applied', {
2140
+ 'namzu.hook.event': event,
2141
+ 'namzu.hook.command': describeShellHook(entry),
2142
+ 'namzu.hook.action': verdict.action,
2143
+ })
2144
+ }
1430
2145
  })
1431
2146
  .catch(() => undefined)
1432
2147
  return { action: 'continue' }
1433
2148
  }
1434
2149
  const outcome = await runShellHook(entry, hookInput, context.signal)
2150
+ // What the hook appended counts even when it was ended or failed after
2151
+ // writing it: the lines are data it already gave.
2152
+ if (envEvent !== undefined) options.hookEnv?.absorb(envEvent, envSlot)
1435
2153
  reportTimeout(outcome.timedOut)
1436
- return shellHookVerdict(event, entry, outcome, log)
2154
+ return shellHookVerdict(event, entry, outcome, log, verdictCall)
1437
2155
  },
1438
2156
  } as PluginHookDefinition
1439
2157
  }