@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
@@ -1,5 +1,31 @@
1
+ import { boundLastAssistantMessage } from '../../plugin/hook-context.js'
1
2
  import { NamzuError } from '../../types/errors/index.js'
3
+ import type { Message } from '../../types/message/index.js'
2
4
  import type { PluginHookEvent, PluginHookResult } from '../../types/plugin/index.js'
5
+ import { isOperatorUserMessage } from './steering.js'
6
+
7
+ /**
8
+ * The model's last message of the turn, as a `turn_end` or `subagent_stop`
9
+ * hook receives it: the text of the last assistant message after the
10
+ * operator's latest prompt, bounded. A message that carries only tool calls,
11
+ * a turn that stopped before the model wrote anything, and a turn with no
12
+ * assistant message yet all give `undefined`: the field is then absent, and a
13
+ * hook never gets an earlier turn's words or an earlier step's narration in
14
+ * its place.
15
+ */
16
+ export function lastAssistantMessageField(messages: readonly Message[]): {
17
+ lastAssistantMessage?: string
18
+ } {
19
+ for (let index = messages.length - 1; index >= 0; index--) {
20
+ const message = messages[index]
21
+ if (!message) continue
22
+ if (isOperatorUserMessage(message)) return {}
23
+ if (message.role !== 'assistant') continue
24
+ const text = boundLastAssistantMessage(message.content)
25
+ return text === undefined ? {} : { lastAssistantMessage: text }
26
+ }
27
+ return {}
28
+ }
3
29
 
4
30
  /**
5
31
  * Interpret hook results from non-tool lifecycle events (run_start, run_end,
@@ -19,9 +45,13 @@ export function applyLifecycleHookResults(
19
45
  case 'continue':
20
46
  continue
21
47
  case 'annotate':
22
- if (event !== 'user_prompt_submit' && event !== 'subagent_start') {
48
+ if (
49
+ event !== 'user_prompt_submit' &&
50
+ event !== 'subagent_start' &&
51
+ event !== 'pre_compact'
52
+ ) {
23
53
  throw new Error(
24
- `Plugin hook ${event} returned 'annotate', which only user_prompt_submit and subagent_start accept`,
54
+ `Plugin hook ${event} returned 'annotate', which only user_prompt_submit, subagent_start and pre_compact accept`,
25
55
  )
26
56
  }
27
57
  if (result.text.trim().length > 0) annotations.push(result.text.trim())
@@ -53,6 +53,11 @@ export interface ToolingBootstrapConfig {
53
53
  onJobCollected?: (id: string) => void
54
54
  /** See `ToolExecutorConfig.monitorTimeoutCapMs`. */
55
55
  monitorTimeoutCapMs?: number
56
+ /** See `QueryParams.onWorkingDirectoryChange`. */
57
+ onWorkingDirectoryChange?: (change: {
58
+ readonly from: string
59
+ readonly to: string
60
+ }) => Promise<void> | void
56
61
  /** See `ToolExecutorConfig.onMonitorStarted`. */
57
62
  onMonitorStarted?: (id: string) => void
58
63
  /** Where the `skill` tool reads from. */
@@ -121,6 +126,9 @@ export class ToolingBootstrap {
121
126
  ...(config.monitorTimeoutCapMs !== undefined
122
127
  ? { monitorTimeoutCapMs: config.monitorTimeoutCapMs }
123
128
  : {}),
129
+ ...(config.onWorkingDirectoryChange
130
+ ? { onWorkingDirectoryChange: config.onWorkingDirectoryChange }
131
+ : {}),
124
132
  ...(config.onMonitorStarted ? { onMonitorStarted: config.onMonitorStarted } : {}),
125
133
  ...(config.skills ? { skills: config.skills } : {}),
126
134
  ...(config.web ? { web: config.web } : {}),
@@ -0,0 +1,272 @@
1
+ /**
2
+ * HookedWorkspaceDriver: lets `worktree_create` and `worktree_remove` hooks
3
+ * take over a workspace driver.
4
+ *
5
+ * The kernel makes worktrees with its own Git logic. A person whose checkout
6
+ * needs something else (another version-control tool, a prepared checkout, a
7
+ * plain copy) puts a hook on `worktree_create`; the hook makes the folder and
8
+ * answers with its path, and the kernel uses it. A hook on `worktree_remove`
9
+ * does the removing. With no hook on an event, the wrapped driver does what it
10
+ * always did.
11
+ *
12
+ * Hooks decide, so a failure never falls back behind the person's back:
13
+ * - hooks on `worktree_create` that fail, or none of which gives a path, fail
14
+ * the creation with the hook's own words;
15
+ * - hooks on `worktree_remove` that fail fail the removal, unless nothing is
16
+ * left at the path;
17
+ * - a folder a create hook made carries `meta.hookOwned`: the kernel never runs
18
+ * its Git removal on it. With no remove hook it is left, and the person is
19
+ * told where.
20
+ */
21
+
22
+ import { createHash } from 'node:crypto'
23
+ import { lstat, readdir, stat } from 'node:fs/promises'
24
+ import { isAbsolute, join, resolve } from 'node:path'
25
+ import type { SessionId } from '../../types/ids/index.js'
26
+ import type { PluginHookResult } from '../../types/plugin/index.js'
27
+ import type { WorkspaceRef } from '../../types/workspace/ref.js'
28
+ import { generateWorkspaceId } from '../../utils/id.js'
29
+ import type {
30
+ BranchWorkspaceParams,
31
+ CreateWorkspaceParams,
32
+ WorkspaceBackendDriver,
33
+ WorkspaceInspection,
34
+ } from './driver.js'
35
+
36
+ /** What a worktree event carries. */
37
+ export interface WorktreeHookContext {
38
+ readonly worktreeName?: string
39
+ readonly worktreeRoot?: string
40
+ readonly worktreeBaseRef?: string
41
+ readonly worktreePath?: string
42
+ }
43
+
44
+ /** Runs the hooks of one event and returns their answers (none when no hook is attached). */
45
+ export interface WorktreeHookHost {
46
+ execute(
47
+ event: 'worktree_create' | 'worktree_remove',
48
+ context: WorktreeHookContext,
49
+ ): Promise<readonly PluginHookResult[]>
50
+ }
51
+
52
+ /** Binds a lifecycle manager (or anything with its `executeHooks`) to a session. */
53
+ export function worktreeHookHost(
54
+ manager: {
55
+ executeHooks(
56
+ event: 'worktree_create' | 'worktree_remove',
57
+ context: WorktreeHookContext & { sessionId: SessionId },
58
+ ): Promise<PluginHookResult[]>
59
+ },
60
+ sessionId: () => string,
61
+ ): WorktreeHookHost {
62
+ return {
63
+ execute: (event, context) =>
64
+ manager.executeHooks(event, { ...context, sessionId: sessionId() as SessionId }),
65
+ }
66
+ }
67
+
68
+ /** A failure whose message is the sentence the person should read. */
69
+ export class WorktreeHookError extends Error {
70
+ constructor(message: string) {
71
+ super(message)
72
+ this.name = 'WorktreeHookError'
73
+ }
74
+ }
75
+
76
+ export interface HookedWorkspaceDriverOptions {
77
+ readonly inner: WorkspaceBackendDriver
78
+ /** The hooks, or a function that finds them when a worktree is made (a host initializes plugins late). */
79
+ readonly hooks: WorktreeHookHost | (() => WorktreeHookHost | undefined)
80
+ /** The folder the kernel would have placed the worktree under; a relative answer is placed there. */
81
+ readonly root: () => string | Promise<string>
82
+ /** The repository recorded on a ref a hook made. Defaults to `root`. */
83
+ readonly repoRoot?: () => string | Promise<string>
84
+ /** A line for the person (a folder left in place, a second answer ignored). */
85
+ readonly onNotice?: (line: string) => void
86
+ }
87
+
88
+ async function isDirectory(path: string): Promise<boolean> {
89
+ try {
90
+ return (await stat(path)).isDirectory()
91
+ } catch {
92
+ return false
93
+ }
94
+ }
95
+
96
+ async function isGone(path: string): Promise<boolean> {
97
+ try {
98
+ await stat(path)
99
+ return false
100
+ } catch (cause) {
101
+ return (cause as NodeJS.ErrnoException).code === 'ENOENT'
102
+ }
103
+ }
104
+
105
+ /** The most entries looked at to tell whether a hook's folder changed; more reads as "changed". */
106
+ export const MAX_FINGERPRINT_ENTRIES = 20_000
107
+
108
+ /**
109
+ * A digest of the names, sizes and times of everything under a folder, or
110
+ * `undefined` when it cannot be taken (too many entries, unreadable). A change
111
+ * of any file, however small, changes it.
112
+ */
113
+ async function fingerprint(root: string): Promise<string | undefined> {
114
+ const lines: string[] = []
115
+ const walk = async (dir: string, prefix: string): Promise<boolean> => {
116
+ const entries = await readdir(dir, { withFileTypes: true })
117
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
118
+ for (const entry of entries) {
119
+ if (lines.length >= MAX_FINGERPRINT_ENTRIES) return false
120
+ const path = join(dir, entry.name)
121
+ const info = await lstat(path)
122
+ lines.push(`${prefix}${entry.name}:${info.isDirectory() ? 'd' : info.size}:${info.mtimeMs}`)
123
+ if (info.isDirectory() && !(await walk(path, `${prefix}${entry.name}/`))) return false
124
+ }
125
+ return true
126
+ }
127
+ try {
128
+ if (!(await walk(root, ''))) return undefined
129
+ } catch {
130
+ return undefined
131
+ }
132
+ return createHash('sha1').update(lines.join('\n')).digest('hex')
133
+ }
134
+
135
+ export class HookedWorkspaceDriver implements WorkspaceBackendDriver {
136
+ readonly kind: WorkspaceBackendDriver['kind']
137
+ /** What each hook-made folder looked like when its hook finished, by workspace id. */
138
+ private readonly started = new Map<string, string | undefined>()
139
+
140
+ constructor(private readonly options: HookedWorkspaceDriverOptions) {
141
+ this.kind = options.inner.kind
142
+ }
143
+
144
+ private host(): WorktreeHookHost | undefined {
145
+ const { hooks } = this.options
146
+ return typeof hooks === 'function' ? hooks() : hooks
147
+ }
148
+
149
+ async create(params: CreateWorkspaceParams): Promise<WorkspaceRef> {
150
+ return this.make(params, () => this.options.inner.create(params))
151
+ }
152
+
153
+ async branch(source: WorkspaceRef, params: BranchWorkspaceParams): Promise<WorkspaceRef> {
154
+ const request: CreateWorkspaceParams = {
155
+ ...(params.label !== undefined ? { label: params.label } : {}),
156
+ baseRef: source.meta.branch,
157
+ }
158
+ return this.make(request, async () => {
159
+ if (source.meta.hookOwned === true) {
160
+ throw new WorktreeHookError(
161
+ `The worktree at ${source.meta.worktreePath} was made by a worktree_create hook, and no worktree_create hook is attached now, so a branch of it cannot be made.`,
162
+ )
163
+ }
164
+ return this.options.inner.branch(source, params)
165
+ })
166
+ }
167
+
168
+ private async make(
169
+ params: CreateWorkspaceParams,
170
+ kernel: () => Promise<WorkspaceRef>,
171
+ ): Promise<WorkspaceRef> {
172
+ const host = this.host()
173
+ if (host === undefined) return kernel()
174
+ const root = await this.options.root()
175
+ const name = params.label ?? `worktree-${generateWorkspaceId()}`
176
+ const results = await host.execute('worktree_create', {
177
+ worktreeName: name,
178
+ worktreeRoot: root,
179
+ ...(params.baseRef !== undefined ? { worktreeBaseRef: params.baseRef } : {}),
180
+ })
181
+ // No hook is attached to the event: the kernel makes it, as it always did.
182
+ if (results.length === 0) return kernel()
183
+
184
+ const failures = results.flatMap((result) =>
185
+ result.action === 'error' ? [result.message] : [],
186
+ )
187
+ if (failures.length > 0) throw new WorktreeHookError(failures.join(' '))
188
+ const answers = results.flatMap((result) =>
189
+ 'worktreePath' in result && result.worktreePath !== undefined ? [result.worktreePath] : [],
190
+ )
191
+ const given = answers[0]
192
+ if (given === undefined) {
193
+ throw new WorktreeHookError(
194
+ 'The hooks on worktree_create gave no worktree path, so none was created. A hook prints the folder it made as its last line, or answers JSON with hookSpecificOutput.worktreePath.',
195
+ )
196
+ }
197
+ if (answers.length > 1) {
198
+ this.options.onNotice?.(
199
+ `More than one worktree_create hook gave a path; the first, ${given}, is used.`,
200
+ )
201
+ }
202
+ const path = isAbsolute(given) ? resolve(given) : resolve(root, given)
203
+ if (!(await isDirectory(path))) {
204
+ throw new WorktreeHookError(
205
+ `A worktree_create hook gave ${given}${path === given ? '' : ` (${path})`}, which is not a folder that exists, so no worktree was created.`,
206
+ )
207
+ }
208
+ const id = generateWorkspaceId()
209
+ this.started.set(id, await fingerprint(path))
210
+ return {
211
+ id,
212
+ meta: {
213
+ backend: 'git-worktree',
214
+ repoRoot: resolve(await (this.options.repoRoot ?? this.options.root)()),
215
+ branch: name,
216
+ worktreePath: path,
217
+ hookOwned: true,
218
+ },
219
+ createdAt: new Date(),
220
+ }
221
+ }
222
+
223
+ async dispose(ref: WorkspaceRef): Promise<void> {
224
+ const host = this.host()
225
+ this.started.delete(ref.id)
226
+ const results =
227
+ host === undefined
228
+ ? []
229
+ : await host.execute('worktree_remove', { worktreePath: ref.meta.worktreePath })
230
+ if (results.length === 0) {
231
+ if (ref.meta.hookOwned === true) {
232
+ // Made by a hook: the kernel has no removal of its own for it.
233
+ this.options.onNotice?.(
234
+ `The worktree at ${ref.meta.worktreePath} was made by a worktree_create hook and is left in place: no worktree_remove hook is set. Remove it yourself when you are done with it.`,
235
+ )
236
+ return
237
+ }
238
+ return this.options.inner.dispose(ref)
239
+ }
240
+ const failures = results.flatMap((result) =>
241
+ result.action === 'error' ? [result.message] : [],
242
+ )
243
+ if (failures.length === 0) return
244
+ // A hook that failed after finishing its job leaves nothing to remove.
245
+ if (await isGone(ref.meta.worktreePath)) return
246
+ throw new WorktreeHookError(failures.join(' '))
247
+ }
248
+
249
+ async inspect(ref: WorkspaceRef): Promise<WorkspaceInspection> {
250
+ if (ref.meta.hookOwned !== true) return this.options.inner.inspect(ref)
251
+ const exists = await isDirectory(ref.meta.worktreePath)
252
+ if (!exists) return { exists, currentRef: ref.meta.branch, isDirty: false }
253
+ // Git cannot say whether a hook's folder changed. What can is the folder
254
+ // itself: it is unchanged only when it looks exactly as it did when the
255
+ // hook finished. Anything else, or no record of that moment (another
256
+ // process made it, or it was too large to take), reads as changed, so a
257
+ // caller deciding whether to keep it keeps it.
258
+ const before = this.started.get(ref.id)
259
+ const unchanged = before !== undefined && before === (await fingerprint(ref.meta.worktreePath))
260
+ if (!unchanged) {
261
+ this.options.onNotice?.(
262
+ `The worktree at ${ref.meta.worktreePath} was made by a worktree_create hook and has changes (or could not be compared), so it is kept.`,
263
+ )
264
+ }
265
+ return {
266
+ exists,
267
+ currentRef: ref.meta.branch,
268
+ isDirty: !unchanged,
269
+ hasNewCommits: !unchanged,
270
+ }
271
+ }
272
+ }
@@ -27,3 +27,10 @@ export type {
27
27
  RegisterSharedSessionPlanInput,
28
28
  SharedSessionWorkspaceConfig,
29
29
  } from './shared-session.js'
30
+
31
+ export { HookedWorkspaceDriver, WorktreeHookError, worktreeHookHost } from './hooked-driver.js'
32
+ export type {
33
+ HookedWorkspaceDriverOptions,
34
+ WorktreeHookContext,
35
+ WorktreeHookHost,
36
+ } from './hooked-driver.js'
@@ -1,6 +1,9 @@
1
1
  export {
2
2
  SKILL_FRONTMATTER_KEYS,
3
+ SKILL_FRONTMATTER_RAW_KEYS,
3
4
  SKILL_FRONTMATTER_TOLERATED_KEYS,
5
+ SKILL_FRONTMATTER_HOOK_EVENT_KEYS,
6
+ skillHooksSource,
4
7
  loadSkill,
5
8
  parseSkillMarkdown,
6
9
  discoverSkills,
@@ -1,5 +1,6 @@
1
1
  import { readFile, readdir, stat } from 'node:fs/promises'
2
2
  import { basename, join } from 'node:path'
3
+ import { SHELL_HOOK_EVENTS, SHELL_HOOK_PASCAL_EVENT_NAMES } from '../plugin/shell-hook.js'
3
4
  import type { ReasoningEffort } from '../types/provider/chat.js'
4
5
  import type {
5
6
  Skill,
@@ -38,6 +39,7 @@ export const SKILL_FRONTMATTER_KEYS: readonly string[] = Object.freeze([
38
39
  'model',
39
40
  'effort',
40
41
  'background',
42
+ 'hooks',
41
43
  ])
42
44
 
43
45
  /**
@@ -54,6 +56,42 @@ export const SKILL_FRONTMATTER_TOLERATED_KEYS: readonly string[] = [
54
56
  'background',
55
57
  ]
56
58
 
59
+ /**
60
+ * A hook event named at the top level of the front matter (`PreToolUse:` with
61
+ * its list, written beside `name:` instead of under `hooks:`) is read as if it
62
+ * had been written under `hooks:`. A guard its author wrote in the wrong place
63
+ * is attached, not skipped as an unknown key and left to run unguarded.
64
+ */
65
+ export const SKILL_FRONTMATTER_HOOK_EVENT_KEYS: readonly string[] = [
66
+ ...new Set([
67
+ ...(Object.values(SHELL_HOOK_PASCAL_EVENT_NAMES) as string[]),
68
+ ...SHELL_HOOK_EVENTS.filter((event) => event.includes('_')),
69
+ ]),
70
+ ]
71
+
72
+ /** Keys handed back as the text the file wrote, for the host to read. */
73
+ export const SKILL_FRONTMATTER_RAW_KEYS: readonly string[] = ['hooks']
74
+
75
+ /**
76
+ * The hooks text of a skill: the `hooks` key's block, with every hook event
77
+ * written at the top level of the front matter moved under it. Absent when the
78
+ * file carries none. `rawBlocks` is {@link ParsedFrontmatter.rawBlocks} read
79
+ * with {@link SKILL_FRONTMATTER_RAW_KEYS} and {@link SKILL_FRONTMATTER_HOOK_EVENT_KEYS}.
80
+ */
81
+ export function skillHooksSource(rawBlocks: Readonly<Record<string, string>>): string | undefined {
82
+ const own = Object.hasOwn(rawBlocks, 'hooks') ? (rawBlocks.hooks ?? '') : ''
83
+ const moved = SKILL_FRONTMATTER_HOOK_EVENT_KEYS.filter(
84
+ (key) => Object.hasOwn(rawBlocks, key) && (rawBlocks[key] ?? '').trim() !== '',
85
+ ).map((key) =>
86
+ (rawBlocks[key] ?? '')
87
+ .split('\n')
88
+ .map((line) => (line.trim() === '' ? line : ` ${line}`))
89
+ .join('\n'),
90
+ )
91
+ if (moved.length === 0) return own.trim() === '' ? undefined : own
92
+ return `${own.trim() === '' ? 'hooks:' : own}\n${moved.join('\n')}`
93
+ }
94
+
57
95
  const READS_SKILL_KEY = (key: string): boolean => SKILL_FRONTMATTER_KEYS.includes(key)
58
96
 
59
97
  /**
@@ -66,6 +104,12 @@ export const SKILL_FRONTMATTER_OPTIONS = {
66
104
  lists: ['allowed-tools'],
67
105
  readsKey: READS_SKILL_KEY,
68
106
  tolerates: (key: string): boolean => SKILL_FRONTMATTER_TOLERATED_KEYS.includes(key),
107
+ /**
108
+ * `hooks` is a list of mappings in a mapping, which this reader cannot
109
+ * hold: the host reads its text with a YAML reader (see
110
+ * `SkillMetadata.hooksSource`).
111
+ */
112
+ raw: [...SKILL_FRONTMATTER_RAW_KEYS, ...SKILL_FRONTMATTER_HOOK_EVENT_KEYS],
69
113
  } as const
70
114
 
71
115
  /**
@@ -204,6 +248,9 @@ function toSkillMetadata(parsed: ParsedFrontmatter, dirPath: string): SkillMetad
204
248
  skillMetadata.background = background === 'true'
205
249
  }
206
250
 
251
+ const hooksSource = skillHooksSource(parsed.rawBlocks)
252
+ if (hooksSource !== undefined) skillMetadata.hooksSource = hooksSource
253
+
207
254
  const extra = mappingAt(values, 'metadata')
208
255
  if (extra && Object.keys(extra).length > 0) {
209
256
  skillMetadata.metadata = { ...extra }
@@ -16,7 +16,7 @@
16
16
  */
17
17
 
18
18
  import { randomUUID } from 'node:crypto'
19
- import { statSync } from 'node:fs'
19
+ import { realpathSync, statSync } from 'node:fs'
20
20
  import { rm } from 'node:fs/promises'
21
21
 
22
22
  import { tempFilePath } from '../../utils/temp.js'
@@ -101,7 +101,14 @@ export async function recordDirectory(
101
101
  sessionId: string,
102
102
  file: string,
103
103
  context: Parameters<typeof toolRoots>[0],
104
+ /** Told once when the directory the next call starts in is a different folder from this call's. */
105
+ onChange?: (change: { readonly from: string; readonly to: string }) => Promise<void> | void,
104
106
  ): Promise<string | undefined> {
107
+ const previous = carried.get(sessionId)
108
+ const from =
109
+ previous !== undefined && previous.base === context.workingDirectory
110
+ ? previous.cwd
111
+ : context.workingDirectory
105
112
  let reported: string
106
113
  try {
107
114
  reported = (await readBoundedFile(file, 64 * 1024)).toString('utf8').trim()
@@ -122,9 +129,26 @@ export async function recordDirectory(
122
129
  if (oldest !== undefined) carried.delete(oldest)
123
130
  }
124
131
  }
132
+ if (onChange !== undefined && !sameFolder(from, next)) {
133
+ try {
134
+ await onChange({ from, to: next })
135
+ } catch {
136
+ // A host's observer must not fail the command that already ran.
137
+ }
138
+ }
125
139
  return outside === undefined ? undefined : cwdResetNotice(base)
126
140
  }
127
141
 
142
+ /** Whether two paths are one folder: the shell reports its physical path, a session may hold a link. */
143
+ function sameFolder(a: string, b: string): boolean {
144
+ if (a === b) return true
145
+ try {
146
+ return realpathSync(a) === realpathSync(b)
147
+ } catch {
148
+ return false
149
+ }
150
+ }
151
+
128
152
  /** For tests: forget every session. */
129
153
  export function forgetCarriedDirectories(): void {
130
154
  carried.clear()
@@ -863,7 +863,7 @@ const BashToolBase = defineTool({
863
863
  const settle = async (): Promise<string | undefined> => {
864
864
  if (cwdFile === undefined) return undefined
865
865
  settled = true
866
- return recordDirectory(context.sessionId, cwdFile, context)
866
+ return recordDirectory(context.sessionId, cwdFile, context, context.workingDirectoryChanged)
867
867
  }
868
868
 
869
869
  try {