@namzu/sdk 64.0.0 → 64.2.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 (132) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/agents/file-definitions.d.ts +10 -0
  3. package/dist/agents/file-definitions.d.ts.map +1 -1
  4. package/dist/agents/file-definitions.js +10 -2
  5. package/dist/agents/file-definitions.js.map +1 -1
  6. package/dist/plugin/file-change-hooks.d.ts +53 -0
  7. package/dist/plugin/file-change-hooks.d.ts.map +1 -0
  8. package/dist/plugin/file-change-hooks.js +111 -0
  9. package/dist/plugin/file-change-hooks.js.map +1 -0
  10. package/dist/plugin/file-change-watch.d.ts +111 -0
  11. package/dist/plugin/file-change-watch.d.ts.map +1 -0
  12. package/dist/plugin/file-change-watch.js +324 -0
  13. package/dist/plugin/file-change-watch.js.map +1 -0
  14. package/dist/plugin/index.d.ts +10 -1
  15. package/dist/plugin/index.d.ts.map +1 -1
  16. package/dist/plugin/index.js +7 -1
  17. package/dist/plugin/index.js.map +1 -1
  18. package/dist/plugin/lifecycle.d.ts +60 -1
  19. package/dist/plugin/lifecycle.d.ts.map +1 -1
  20. package/dist/plugin/lifecycle.js +118 -7
  21. package/dist/plugin/lifecycle.js.map +1 -1
  22. package/dist/plugin/loader.d.ts.map +1 -1
  23. package/dist/plugin/loader.js +24 -1
  24. package/dist/plugin/loader.js.map +1 -1
  25. package/dist/plugin/session-hook-env.d.ts +140 -0
  26. package/dist/plugin/session-hook-env.d.ts.map +1 -0
  27. package/dist/plugin/session-hook-env.js +458 -0
  28. package/dist/plugin/session-hook-env.js.map +1 -0
  29. package/dist/plugin/shell-hook-env.d.ts +107 -0
  30. package/dist/plugin/shell-hook-env.d.ts.map +1 -0
  31. package/dist/plugin/shell-hook-env.js +272 -0
  32. package/dist/plugin/shell-hook-env.js.map +1 -0
  33. package/dist/plugin/shell-hook.d.ts +105 -2
  34. package/dist/plugin/shell-hook.d.ts.map +1 -1
  35. package/dist/plugin/shell-hook.js +282 -24
  36. package/dist/plugin/shell-hook.js.map +1 -1
  37. package/dist/plugin/worktree-hook-answer.d.ts +26 -0
  38. package/dist/plugin/worktree-hook-answer.d.ts.map +1 -0
  39. package/dist/plugin/worktree-hook-answer.js +132 -0
  40. package/dist/plugin/worktree-hook-answer.js.map +1 -0
  41. package/dist/public-runtime.d.ts +4 -4
  42. package/dist/public-runtime.d.ts.map +1 -1
  43. package/dist/public-runtime.js +4 -4
  44. package/dist/public-runtime.js.map +1 -1
  45. package/dist/public-types.d.ts +7 -1
  46. package/dist/public-types.d.ts.map +1 -1
  47. package/dist/runtime/query/executor.d.ts +8 -1
  48. package/dist/runtime/query/executor.d.ts.map +1 -1
  49. package/dist/runtime/query/executor.js +4 -0
  50. package/dist/runtime/query/executor.js.map +1 -1
  51. package/dist/runtime/query/index.d.ts +9 -0
  52. package/dist/runtime/query/index.d.ts.map +1 -1
  53. package/dist/runtime/query/index.js +20 -0
  54. package/dist/runtime/query/index.js.map +1 -1
  55. package/dist/runtime/query/tooling.d.ts +8 -1
  56. package/dist/runtime/query/tooling.d.ts.map +1 -1
  57. package/dist/runtime/query/tooling.js +6 -0
  58. package/dist/runtime/query/tooling.js.map +1 -1
  59. package/dist/session/workspace/hooked-driver.d.ts +72 -0
  60. package/dist/session/workspace/hooked-driver.d.ts.map +1 -0
  61. package/dist/session/workspace/hooked-driver.js +204 -0
  62. package/dist/session/workspace/hooked-driver.js.map +1 -0
  63. package/dist/session/workspace/index.d.ts +2 -0
  64. package/dist/session/workspace/index.d.ts.map +1 -1
  65. package/dist/session/workspace/index.js +1 -0
  66. package/dist/session/workspace/index.js.map +1 -1
  67. package/dist/skills/index.d.ts +1 -1
  68. package/dist/skills/index.d.ts.map +1 -1
  69. package/dist/skills/index.js +1 -1
  70. package/dist/skills/index.js.map +1 -1
  71. package/dist/skills/loader.d.ts +22 -0
  72. package/dist/skills/loader.d.ts.map +1 -1
  73. package/dist/skills/loader.js +41 -0
  74. package/dist/skills/loader.js.map +1 -1
  75. package/dist/tools/builtins/bash-cwd.d.ts +6 -1
  76. package/dist/tools/builtins/bash-cwd.d.ts.map +1 -1
  77. package/dist/tools/builtins/bash-cwd.js +27 -2
  78. package/dist/tools/builtins/bash-cwd.js.map +1 -1
  79. package/dist/tools/builtins/bash.js +1 -1
  80. package/dist/tools/builtins/bash.js.map +1 -1
  81. package/dist/tools/builtins/skill.d.ts.map +1 -1
  82. package/dist/tools/builtins/skill.js +114 -17
  83. package/dist/tools/builtins/skill.js.map +1 -1
  84. package/dist/types/plugin/index.d.ts +75 -2
  85. package/dist/types/plugin/index.d.ts.map +1 -1
  86. package/dist/types/plugin/index.js +5 -0
  87. package/dist/types/plugin/index.js.map +1 -1
  88. package/dist/types/session/records.d.ts +73 -1
  89. package/dist/types/session/records.d.ts.map +1 -1
  90. package/dist/types/session/records.js +25 -0
  91. package/dist/types/session/records.js.map +1 -1
  92. package/dist/types/skills/index.d.ts +8 -0
  93. package/dist/types/skills/index.d.ts.map +1 -1
  94. package/dist/types/skills/index.js.map +1 -1
  95. package/dist/types/tool/index.d.ts +97 -0
  96. package/dist/types/tool/index.d.ts.map +1 -1
  97. package/dist/types/tool/index.js.map +1 -1
  98. package/dist/types/workspace/ref.d.ts +6 -0
  99. package/dist/types/workspace/ref.d.ts.map +1 -1
  100. package/dist/utils/frontmatter.d.ts +16 -0
  101. package/dist/utils/frontmatter.d.ts.map +1 -1
  102. package/dist/utils/frontmatter.js +31 -1
  103. package/dist/utils/frontmatter.js.map +1 -1
  104. package/package.json +1 -1
  105. package/src/agents/file-definitions.ts +17 -2
  106. package/src/plugin/file-change-hooks.ts +131 -0
  107. package/src/plugin/file-change-watch.ts +367 -0
  108. package/src/plugin/index.ts +39 -1
  109. package/src/plugin/lifecycle.ts +162 -8
  110. package/src/plugin/loader.ts +22 -1
  111. package/src/plugin/session-hook-env.ts +475 -0
  112. package/src/plugin/shell-hook-env.ts +335 -0
  113. package/src/plugin/shell-hook.ts +416 -24
  114. package/src/plugin/worktree-hook-answer.ts +142 -0
  115. package/src/public-runtime.ts +33 -0
  116. package/src/public-types.ts +20 -1
  117. package/src/runtime/query/executor.ts +12 -0
  118. package/src/runtime/query/index.ts +28 -0
  119. package/src/runtime/query/tooling.ts +19 -1
  120. package/src/session/workspace/hooked-driver.ts +272 -0
  121. package/src/session/workspace/index.ts +7 -0
  122. package/src/skills/index.ts +3 -0
  123. package/src/skills/loader.ts +47 -0
  124. package/src/tools/builtins/bash-cwd.ts +25 -1
  125. package/src/tools/builtins/bash.ts +1 -1
  126. package/src/tools/builtins/skill.ts +138 -27
  127. package/src/types/plugin/index.ts +84 -1
  128. package/src/types/session/records.ts +28 -0
  129. package/src/types/skills/index.ts +9 -0
  130. package/src/types/tool/index.ts +105 -0
  131. package/src/types/workspace/ref.ts +6 -0
  132. package/src/utils/frontmatter.ts +52 -1
@@ -106,6 +106,8 @@
106
106
  */
107
107
 
108
108
  import { spawn } from 'node:child_process'
109
+ import { constants, accessSync, mkdirSync, statSync } from 'node:fs'
110
+ import { basename, delimiter } from 'node:path'
109
111
 
110
112
  import { decodedCommands, decomposeCommandLine } from '../authorization/command-line.js'
111
113
  import {
@@ -117,6 +119,7 @@ import { spawnHostShell } from '../tools/command-shell.js'
117
119
  import type { PluginId } from '../types/ids/index.js'
118
120
  import type {
119
121
  PluginCompactionInfo,
122
+ PluginFileChange,
120
123
  PluginHookContext,
121
124
  PluginHookDefinition,
122
125
  PluginHookEvent,
@@ -131,9 +134,18 @@ import { NOOP_LOGGER } from '../utils/log/create-logger.js'
131
134
  import type { Logger } from '../utils/logger.js'
132
135
  import { boundHookReplacement } from './hook-context.js'
133
136
  import type { PluginLifecycleManager } from './lifecycle.js'
137
+ import type { SessionHookEnv } from './session-hook-env.js'
134
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'
135
146
  import { postHookJson } from './shell-hook-http.js'
136
147
  import { type ShellHookToolNames, shellHookToolName } from './shell-hook-tool-names.js'
148
+ import { worktreeHookVerdict } from './worktree-hook-answer.js'
137
149
 
138
150
  /**
139
151
  * The events a shell hook may attach to: the ones an operator can act on
@@ -159,6 +171,10 @@ export type ShellHookEvent = Extract<
159
171
  | 'turn_failure'
160
172
  | 'turn_start'
161
173
  | 'turn_end'
174
+ | 'file_changed'
175
+ | 'cwd_changed'
176
+ | 'worktree_create'
177
+ | 'worktree_remove'
162
178
  >
163
179
 
164
180
  export const SHELL_HOOK_EVENTS: readonly ShellHookEvent[] = [
@@ -179,6 +195,10 @@ export const SHELL_HOOK_EVENTS: readonly ShellHookEvent[] = [
179
195
  'turn_failure',
180
196
  'turn_start',
181
197
  'turn_end',
198
+ 'file_changed',
199
+ 'cwd_changed',
200
+ 'worktree_create',
201
+ 'worktree_remove',
182
202
  ]
183
203
 
184
204
  /** What a failed hook does to the action it guards. */
@@ -251,6 +271,15 @@ export interface ShellHookEntry extends ShellHookEntryBase {
251
271
  * parser. An empty list runs `command` with no arguments.
252
272
  */
253
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>>
254
283
  /**
255
284
  * Start the command and carry on without waiting. Its exit code and output
256
285
  * decide nothing (a failure is logged), and `onFailure` is not read.
@@ -482,6 +511,56 @@ export function shellHookMatcherProblem(matcher: string | undefined): string | u
482
511
 
483
512
  const IF_SHAPE = /^([A-Za-z0-9_.:*|, -]+)(?:\(([\s\S]*)\))?$/
484
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
+
485
564
  /**
486
565
  * Why an `if` cannot be read, or `undefined` when it can. A filter that
487
566
  * cannot be read runs the hook.
@@ -593,6 +672,8 @@ export interface ShellHookOutcome {
593
672
  readonly stdoutTruncated?: boolean
594
673
  /** Set when the process could not be started at all. */
595
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[]
596
677
  }
597
678
 
598
679
  export interface ShellHookInput {
@@ -608,6 +689,12 @@ export interface ShellHookInput {
608
689
  readonly endReason?: string
609
690
  /** The folder the session was started for. Sent as `NAMZU_PROJECT_DIR`; absent, `cwd`. */
610
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
611
698
  /** The delegating session, on `subagent_start` and `subagent_stop`. */
612
699
  readonly parentSessionId?: string
613
700
  /** The parent turn whose tool call spawned the child, on `subagent_start` and `subagent_stop`. */
@@ -615,6 +702,26 @@ export interface ShellHookInput {
615
702
  /** The agent the child runs, on `subagent_start` and `subagent_stop`. */
616
703
  readonly agentType?: string
617
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
618
725
  readonly compaction?: PluginCompactionInfo
619
726
  readonly toolName?: string
620
727
  /** The spelling `toolName` (and each `toolCalls` name) is sent in; absent is `namzu`. */
@@ -643,6 +750,14 @@ export interface ShellHookInput {
643
750
  readonly transcriptPath?: string
644
751
  /** How tool calls are being decided right now. Sent as `permission_mode`. */
645
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
646
761
  }
647
762
 
648
763
  /** The JSON a hook receives on stdin (or as an HTTP body). */
@@ -662,6 +777,14 @@ export function shellHookPayload(input: ShellHookInput): string {
662
777
  ? { agent_id: input.sessionId, agent_type: input.agentType }
663
778
  : {}),
664
779
  ...(input.prompt !== undefined ? { prompt: input.prompt } : {}),
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 } : {}),
665
788
  ...(input.compaction !== undefined ? compactionFields(input.event, input.compaction) : {}),
666
789
  ...(input.toolName !== undefined
667
790
  ? { tool_name: shellHookToolName(input.toolName, input.toolNames) }
@@ -725,6 +848,16 @@ function compactionFields(
725
848
  }
726
849
  }
727
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
+
728
861
  /** Run one hook command to completion, bounded by its deadline and capture. */
729
862
  export function runShellHook(
730
863
  entry: ShellHookEntry,
@@ -739,21 +872,72 @@ export function runShellHook(
739
872
  const toolPath = pathOf(input.toolInput)
740
873
  // A hook outside a turn must not see a turn id, including one the host
741
874
  // inherited from an enclosing hook's environment.
742
- 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
+ }
743
938
  return new Promise((resolve) => {
744
939
  let child: ReturnType<typeof spawn>
745
940
  try {
746
- const env = {
747
- ...inherited,
748
- NAMZU_HOOK_EVENT: input.event,
749
- NAMZU_SESSION_ID: input.sessionId,
750
- NAMZU_PROJECT_DIR: input.projectDir ?? input.cwd,
751
- ...(input.turnId !== undefined ? { NAMZU_TURN_ID: input.turnId } : {}),
752
- ...(input.toolName !== undefined
753
- ? { NAMZU_TOOL_NAME: shellHookToolName(input.toolName, input.toolNames) }
754
- : {}),
755
- ...(toolPath !== undefined ? { NAMZU_TOOL_PATH: toolPath } : {}),
756
- }
757
941
  // Its own process group, so the deadline can kill everything the
758
942
  // command started. `sh -c 'sleep 5'` is one process under a shell
759
943
  // that execs its last command and two under one that forks it;
@@ -762,15 +946,15 @@ export function runShellHook(
762
946
  // its own — the hook's deadline becomes the grandchild's.
763
947
  const detached = process.platform !== 'win32'
764
948
  child =
765
- entry.args !== undefined
949
+ placed.args !== undefined
766
950
  ? // The exec form: no shell reads `command` or any argument.
767
- spawn(entry.command, [...entry.args], {
951
+ spawn(placed.command, [...placed.args], {
768
952
  cwd: input.cwd,
769
953
  env: withSessionChildMarker(env),
770
954
  stdio: ['pipe', 'pipe', 'pipe'],
771
955
  detached,
772
956
  })
773
- : spawnHostShell(entry.command, {
957
+ : spawnHostShell(placed.command, {
774
958
  cwd: input.cwd,
775
959
  env,
776
960
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -780,7 +964,20 @@ export function runShellHook(
780
964
  // when installed, cmd.exe when not.
781
965
  ...(process.platform === 'win32'
782
966
  ? {}
783
- : { 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
+ }),
784
981
  })
785
982
  } catch (error) {
786
983
  resolve({
@@ -789,6 +986,7 @@ export function runShellHook(
789
986
  stdout: '',
790
987
  stderr: '',
791
988
  spawnError: error instanceof Error ? error.message : String(error),
989
+ ...unsetVariables,
792
990
  })
793
991
  return
794
992
  }
@@ -846,6 +1044,7 @@ export function runShellHook(
846
1044
  stderr,
847
1045
  ...(stdoutTruncated ? { stdoutTruncated } : {}),
848
1046
  spawnError: error.message,
1047
+ ...unsetVariables,
849
1048
  })
850
1049
  })
851
1050
  child.on('close', (code) => {
@@ -855,6 +1054,7 @@ export function runShellHook(
855
1054
  stdout,
856
1055
  stderr,
857
1056
  ...(stdoutTruncated ? { stdoutTruncated } : {}),
1057
+ ...unsetVariables,
858
1058
  })
859
1059
  })
860
1060
  child.on('exit', () => {
@@ -950,6 +1150,10 @@ export const SHELL_HOOK_PASCAL_EVENT_NAMES: Readonly<Partial<Record<ShellHookEve
950
1150
  permission_denied: 'PermissionDenied',
951
1151
  turn_failure: 'StopFailure',
952
1152
  turn_end: 'Stop',
1153
+ file_changed: 'FileChanged',
1154
+ cwd_changed: 'CwdChanged',
1155
+ worktree_create: 'WorktreeCreate',
1156
+ worktree_remove: 'WorktreeRemove',
953
1157
  }
954
1158
 
955
1159
  /** What a hook's stdout JSON said, before it is mapped to a verdict for an event. */
@@ -965,6 +1169,8 @@ interface ShellHookReading {
965
1169
  replacement?: string
966
1170
  /** The hook asked for its stdout to stay out of the debug log. */
967
1171
  suppressOutput?: boolean
1172
+ /** On `session_start`, `file_changed` and `cwd_changed`: the files to watch from now on. */
1173
+ watchPaths?: readonly string[]
968
1174
  /** Why the JSON was set aside, when it was. */
969
1175
  invalid?: string
970
1176
  }
@@ -1080,6 +1286,18 @@ function readShellHookJson(
1080
1286
  }
1081
1287
  }
1082
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
+
1083
1301
  const reading: ShellHookReading = {}
1084
1302
  if (parsed.suppressOutput === true) reading.suppressOutput = true
1085
1303
  const systemMessage = optionalString('systemMessage')
@@ -1113,6 +1331,16 @@ function readShellHookJson(
1113
1331
  const problem = wrongType(key, type, specific)
1114
1332
  if (problem) return { invalid: `hookSpecificOutput: ${problem}` }
1115
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
+ }
1116
1344
  const additional = optionalString('additionalContext', specific)
1117
1345
  if (additional && additional.trim().length > 0) reading.context = additional.trim()
1118
1346
 
@@ -1192,11 +1420,16 @@ export function shellHookVerdict(
1192
1420
  'namzu.hook.event': event,
1193
1421
  'namzu.hook.command': label,
1194
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)
1195
1426
  // A failure of the hook itself is "carry on" unless the entry asked for
1196
1427
  // it to count as a refusal, which is exit 2 with the failure as the reason.
1197
1428
  const failed = (reason: string, shown: string = reason): PluginHookResult => {
1198
1429
  if (entry.onFailure !== 'block' || entry.type === 'prompt' || isAsyncShellHook(entry)) {
1199
- return { action: 'continue' }
1430
+ return hint !== undefined
1431
+ ? { action: 'continue', notice: `${label}: ${hint}` }
1432
+ : { action: 'continue' }
1200
1433
  }
1201
1434
  // The call has run and a refusal cannot undo it, but the hook may have
1202
1435
  // been the one thing keeping something out of the result (a redaction),
@@ -1223,8 +1456,9 @@ export function shellHookVerdict(
1223
1456
  log.warn('hook could not start', {
1224
1457
  ...attrs,
1225
1458
  'namzu.hook.error': outcome.spawnError,
1459
+ ...(hint !== undefined ? { 'namzu.hook.hint': hint } : {}),
1226
1460
  })
1227
- return failed(`could not start (${outcome.spawnError})`)
1461
+ return failed(`could not start (${outcome.spawnError})${hint !== undefined ? `; ${hint}` : ''}`)
1228
1462
  }
1229
1463
  if (outcome.timedOut) {
1230
1464
  log.warn('hook timed out', attrs)
@@ -1261,8 +1495,11 @@ export function shellHookVerdict(
1261
1495
  ...attrs,
1262
1496
  'namzu.hook.exit': outcome.exitCode ?? -1,
1263
1497
  'namzu.hook.stderr': outcome.stderr.trim().slice(0, 500),
1498
+ ...(hint !== undefined ? { 'namzu.hook.hint': hint } : {}),
1264
1499
  })
1265
- return failed(`exited with ${outcome.exitCode ?? 'no code'}`)
1500
+ return failed(
1501
+ `exited with ${outcome.exitCode ?? 'no code'}${hint !== undefined ? `; ${hint}` : ''}`,
1502
+ )
1266
1503
  }
1267
1504
 
1268
1505
  // Exit 0.
@@ -1362,13 +1599,33 @@ export function shellHookVerdict(
1362
1599
  // Nothing here can be refused. What the hook said for the model becomes
1363
1600
  // the session's context; a stop request and a warning still count.
1364
1601
  return reading.context !== undefined
1365
- ? { 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
+ }
1366
1608
  : {
1367
1609
  action: 'continue',
1368
1610
  ...(reading.halt ? { halt: reading.halt } : {}),
1369
1611
  ...(reading.notice ? { notice: reading.notice } : {}),
1612
+ ...(reading.watchPaths !== undefined ? { watchPaths: reading.watchPaths } : {}),
1370
1613
  }
1371
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
+ }
1372
1629
  case 'post_tool_use':
1373
1630
  case 'post_tool_use_failure': {
1374
1631
  // The call has run, so a "block" cannot undo it: its reason is what the
@@ -1489,6 +1746,33 @@ export interface ShellHookOptions {
1489
1746
  * `NAMZU_PROJECT_DIR`. Absent, `cwd`.
1490
1747
  */
1491
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
1492
1776
  /** How a path pattern in an entry's `if` is read. Absent, such a filter runs the hook. */
1493
1777
  readonly pathFilter?: ShellHookPathFilter
1494
1778
  /**
@@ -1497,6 +1781,13 @@ export interface ShellHookOptions {
1497
1781
  * the cap). Absent, or an event not listed, the ordinary default applies.
1498
1782
  */
1499
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
1500
1791
  /**
1501
1792
  * Called when a hook of this adapter ran out its deadline and was ended.
1502
1793
  * `hook` is the command, URL or prompt text the entry names.
@@ -1604,6 +1895,56 @@ function readJudgement(reply: string): { ok: boolean; reason: string } | undefin
1604
1895
  }
1605
1896
  }
1606
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
+
1607
1948
  /** One entry as a hook definition the lifecycle manager accepts. */
1608
1949
  export function createShellHook(
1609
1950
  event: ShellHookEvent,
@@ -1611,6 +1952,7 @@ export function createShellHook(
1611
1952
  options: ShellHookOptions,
1612
1953
  ): PluginHookDefinition {
1613
1954
  const log = options.log ?? NOOP_LOGGER
1955
+ const envSlot = nextHookEnvSlot++
1614
1956
  const eventDefault = options.defaultTimeoutMs?.[event]
1615
1957
  const entry: ShellHookHandler =
1616
1958
  configured.timeoutMs === undefined && eventDefault !== undefined
@@ -1628,8 +1970,14 @@ export function createShellHook(
1628
1970
  return {
1629
1971
  event,
1630
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
+ : {}),
1631
1977
  handler: async (context: PluginHookContext) => {
1632
- if (spent) return { action: 'continue' }
1978
+ if (spent && event !== 'worktree_create' && event !== 'worktree_remove') {
1979
+ return { action: 'continue' }
1980
+ }
1633
1981
  // A notification is matched on its type; every other event on the tool.
1634
1982
  const namesATool = !(
1635
1983
  event === 'pre_compact' ||
@@ -1659,16 +2007,51 @@ export function createShellHook(
1659
2007
  // events are matched on `trigger`.
1660
2008
  if (subject !== undefined && !shellHookMatches(entry.matcher, subject, { tool: namesATool }))
1661
2009
  return { action: 'continue' }
1662
- 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)) {
1663
2013
  return { action: 'continue' }
1664
2014
  }
1665
- 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 })
1666
2027
  const transcriptPath = options.transcriptPath?.(String(context.sessionId))
1667
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
1668
2038
  const hookInput: ShellHookInput = {
1669
2039
  event,
1670
- 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 } : {}),
1671
2053
  ...(options.projectDir !== undefined ? { projectDir: options.projectDir } : {}),
2054
+ ...(options.plugin !== undefined ? { plugin: options.plugin } : {}),
1672
2055
  sessionId: String(context.sessionId),
1673
2056
  ...(context.source !== undefined ? { sessionSource: context.source } : {}),
1674
2057
  ...(context.endReason !== undefined ? { endReason: context.endReason } : {}),
@@ -1707,11 +2090,16 @@ export function createShellHook(
1707
2090
  : {}),
1708
2091
  ...(transcriptPath !== undefined ? { transcriptPath } : {}),
1709
2092
  ...(permissionMode !== undefined ? { permissionMode } : {}),
2093
+ ...(options.extraEnv !== undefined ? { extraEnv: options.extraEnv } : {}),
2094
+ ...(options.skillRoot !== undefined ? { skillRoot: options.skillRoot } : {}),
1710
2095
  }
1711
2096
  const verdictCall: ShellHookCall = {
1712
2097
  ...(context.toolName !== undefined ? { toolName: context.toolName } : {}),
1713
2098
  ...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
1714
2099
  }
2100
+ if (event === 'worktree_create' || event === 'worktree_remove') {
2101
+ return runWorktreeHook(event, entry, hookInput, context.signal, reportTimeout)
2102
+ }
1715
2103
  if (entry.type === 'http') {
1716
2104
  const response = await postHookJson({
1717
2105
  url: entry.url,
@@ -1745,6 +2133,7 @@ export function createShellHook(
1745
2133
  // for it and its own failure is only written down.
1746
2134
  void runShellHook(entry, hookInput)
1747
2135
  .then((outcome) => {
2136
+ if (envEvent !== undefined) options.hookEnv?.absorb(envEvent, envSlot)
1748
2137
  const verdict = shellHookVerdict(event, entry, outcome, log, verdictCall)
1749
2138
  if (verdict.action !== 'continue') {
1750
2139
  log.warn('an async hook answered, and its answer is not applied', {
@@ -1758,6 +2147,9 @@ export function createShellHook(
1758
2147
  return { action: 'continue' }
1759
2148
  }
1760
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)
1761
2153
  reportTimeout(outcome.timedOut)
1762
2154
  return shellHookVerdict(event, entry, outcome, log, verdictCall)
1763
2155
  },