@namzu/sdk 64.0.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 (127) hide show
  1. package/CHANGELOG.md +43 -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 +3 -3
  42. package/dist/public-runtime.d.ts.map +1 -1
  43. package/dist/public-runtime.js +3 -3
  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 +5 -0
  48. package/dist/runtime/query/executor.d.ts.map +1 -1
  49. package/dist/runtime/query/executor.js +3 -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 +3 -0
  54. package/dist/runtime/query/index.js.map +1 -1
  55. package/dist/runtime/query/tooling.d.ts +5 -0
  56. package/dist/runtime/query/tooling.d.ts.map +1 -1
  57. package/dist/runtime/query/tooling.js +3 -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 +93 -16
  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/skills/index.d.ts +8 -0
  89. package/dist/types/skills/index.d.ts.map +1 -1
  90. package/dist/types/skills/index.js.map +1 -1
  91. package/dist/types/tool/index.d.ts +68 -0
  92. package/dist/types/tool/index.d.ts.map +1 -1
  93. package/dist/types/tool/index.js.map +1 -1
  94. package/dist/types/workspace/ref.d.ts +6 -0
  95. package/dist/types/workspace/ref.d.ts.map +1 -1
  96. package/dist/utils/frontmatter.d.ts +16 -0
  97. package/dist/utils/frontmatter.d.ts.map +1 -1
  98. package/dist/utils/frontmatter.js +31 -1
  99. package/dist/utils/frontmatter.js.map +1 -1
  100. package/package.json +1 -1
  101. package/src/agents/file-definitions.ts +17 -2
  102. package/src/plugin/file-change-hooks.ts +131 -0
  103. package/src/plugin/file-change-watch.ts +367 -0
  104. package/src/plugin/index.ts +39 -1
  105. package/src/plugin/lifecycle.ts +162 -8
  106. package/src/plugin/loader.ts +22 -1
  107. package/src/plugin/session-hook-env.ts +475 -0
  108. package/src/plugin/shell-hook-env.ts +335 -0
  109. package/src/plugin/shell-hook.ts +416 -24
  110. package/src/plugin/worktree-hook-answer.ts +142 -0
  111. package/src/public-runtime.ts +32 -0
  112. package/src/public-types.ts +20 -1
  113. package/src/runtime/query/executor.ts +8 -0
  114. package/src/runtime/query/index.ts +12 -0
  115. package/src/runtime/query/tooling.ts +8 -0
  116. package/src/session/workspace/hooked-driver.ts +272 -0
  117. package/src/session/workspace/index.ts +7 -0
  118. package/src/skills/index.ts +3 -0
  119. package/src/skills/loader.ts +47 -0
  120. package/src/tools/builtins/bash-cwd.ts +25 -1
  121. package/src/tools/builtins/bash.ts +1 -1
  122. package/src/tools/builtins/skill.ts +115 -26
  123. package/src/types/plugin/index.ts +84 -1
  124. package/src/types/skills/index.ts +9 -0
  125. package/src/types/tool/index.ts +74 -0
  126. package/src/types/workspace/ref.ts +6 -0
  127. package/src/utils/frontmatter.ts +52 -1
@@ -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 {
@@ -5,7 +5,7 @@ import { parseAllowedTools } from '../../authorization/skill-grant.js'
5
5
  import { forkedSkillReportNote } from '../../compaction/loaded-skills.js'
6
6
  import type { Sandbox } from '../../types/sandbox/index.js'
7
7
  import { isInvocableBy, skillInvocation } from '../../types/skills/index.js'
8
- import type { ToolContext } from '../../types/tool/index.js'
8
+ import type { SkillHooksPlan, ToolContext } from '../../types/tool/index.js'
9
9
  import { defineTool } from '../defineTool.js'
10
10
 
11
11
  export { parseAllowedTools }
@@ -337,6 +337,11 @@ export function createSkillTool(options: SkillToolOptions = {}) {
337
337
  readOnly: true,
338
338
  destructive: false,
339
339
  concurrencySafe: true,
340
+ // A skill that carries hooks attaches them when it is used. A call the
341
+ // model wrote after it in the same message must run under them, so the
342
+ // calls before settle first and the calls after wait: message order is
343
+ // the order they run in.
344
+ executionBarrier: true,
340
345
 
341
346
  // The body is instructions for the model, often a hundred lines; the
342
347
  // person needs the row that says which skill was read, not the text.
@@ -496,28 +501,43 @@ export function createSkillTool(options: SkillToolOptions = {}) {
496
501
  let forkUnavailable = ''
497
502
  if (skill.metadata.context === 'fork' && input.cursor === undefined) {
498
503
  if (context.dispatchTool && context.toolRegistry?.has(DELEGATION_TOOL_NAME)) {
499
- return runForkedSkill({
504
+ const forkHeader = resolveModelDirectory
505
+ ? directoryHeader(
506
+ nonEmpty(
507
+ await resolveModelDirectory(
508
+ { name: input.name, directory: skill.dirPath },
509
+ directoryContextOf(context.sandbox),
510
+ ),
511
+ ),
512
+ )
513
+ : ''
514
+ // The delegated prompt is known before the agent starts: the host
515
+ // recognises the agent that receives it, among any others that
516
+ // start at the same time, and binds the skill's hooks to that one.
517
+ const forkPrompt = forkedPrompt(forkHeader, argsLine, skill.body)
518
+ const forkHooks = hooksPlanFor(skill, context, true, forkPrompt)
519
+ const forkResult = await runForkedSkill({
500
520
  name: input.name,
501
521
  skill,
502
- argsLine,
522
+ prompt: forkPrompt,
503
523
  dispatch: context.dispatchTool,
504
- header: resolveModelDirectory
505
- ? directoryHeader(
506
- nonEmpty(
507
- await resolveModelDirectory(
508
- { name: input.name, directory: skill.dirPath },
509
- directoryContextOf(context.sandbox),
510
- ),
511
- ),
512
- )
513
- : '',
524
+ hooks: forkHooks,
514
525
  })
526
+ return forkHooks?.notice
527
+ ? { ...forkResult, output: `[${forkHooks.notice}]\n\n${forkResult.output}` }
528
+ : forkResult
515
529
  }
516
530
  forkUnavailable =
517
531
  '[This skill is written to run as a delegated agent, but this turn cannot delegate. Follow its instructions yourself.]\n\n'
518
532
  }
519
533
 
520
- const allowed = parseAllowedTools(skill.metadata.allowedTools)
534
+ // A skill that carries hooks is read by the host first. When a hook
535
+ // that guards its work cannot be loaded, the skill's pre-approval is
536
+ // withheld, whatever else it says.
537
+ const hooksPlan = hooksPlanFor(skill, context, false)
538
+ const allowed = hooksPlan?.withholdGrants
539
+ ? undefined
540
+ : parseAllowedTools(skill.metadata.allowedTools)
521
541
  // Asked on every call, first page or continuation: the digest binds
522
542
  // the answer, so a mount that changed between pages is a stale cursor
523
543
  // rather than a second half written for a different directory.
@@ -572,7 +592,9 @@ export function createSkillTool(options: SkillToolOptions = {}) {
572
592
  ...(snapshot.skillDirectory ? { skillDirectory: snapshot.skillDirectory } : {}),
573
593
  })
574
594
  }
575
- const notice = grantNotice(allowed, grant, context.grantSkillTools !== undefined)
595
+ const notice =
596
+ (hooksPlan?.notice ? `\n\n[${hooksPlan.notice}]` : '') +
597
+ grantNotice(allowed, grant, context.grantSkillTools !== undefined)
576
598
  const page = pageSkillBody({
577
599
  snapshot:
578
600
  start === 0 && argsLine ? { ...snapshot, header: argsLine + snapshot.header } : snapshot,
@@ -589,6 +611,8 @@ export function createSkillTool(options: SkillToolOptions = {}) {
589
611
  }
590
612
  }
591
613
  grant?.commit()
614
+ // Live only now that the instructions were delivered, like the grant.
615
+ hooksPlan?.attach()
592
616
 
593
617
  return {
594
618
  success: true,
@@ -605,6 +629,48 @@ export function createSkillTool(options: SkillToolOptions = {}) {
605
629
  })
606
630
  }
607
631
 
632
+ /**
633
+ * What the host says of the hooks a skill carries, or `undefined` for a skill
634
+ * that carries none. A registry that cannot read hooks answers with a plan
635
+ * that attaches nothing and withholds the pre-approval: the skill still
636
+ * loads, and the model is told in one line why its commands are not
637
+ * pre-approved.
638
+ */
639
+ function hooksPlanFor(
640
+ skill: {
641
+ readonly metadata: { readonly name: string; readonly hooksSource?: string }
642
+ readonly dirPath?: string
643
+ },
644
+ context: ToolContext,
645
+ forked: boolean,
646
+ /** For a forked skill: the prompt the delegated agent is given. */
647
+ prompt?: string,
648
+ ): SkillHooksPlan | undefined {
649
+ const hooksSource = skill.metadata.hooksSource
650
+ if (hooksSource === undefined) return undefined
651
+ const prepare = context.skills?.prepareHooks
652
+ if (!prepare || !context.skills) {
653
+ return {
654
+ notice: `Skill ${skill.metadata.name} carries hooks, but this session cannot run a skill's hooks. They are not attached and its allowed-tools are not pre-approved.`,
655
+ withholdGrants: true,
656
+ attach: () => ({ remove: () => undefined }),
657
+ }
658
+ }
659
+ return prepare.call(
660
+ context.skills,
661
+ {
662
+ name: skill.metadata.name,
663
+ ...(skill.dirPath !== undefined ? { dirPath: skill.dirPath } : {}),
664
+ hooksSource,
665
+ },
666
+ {
667
+ forked,
668
+ ...(forked && prompt !== undefined ? { prompt } : {}),
669
+ ...(context.sessionId !== undefined ? { sessionId: String(context.sessionId) } : {}),
670
+ },
671
+ )
672
+ }
673
+
608
674
  /** The `skill` tool with no host options: the listing carries the registry's `location`. */
609
675
  export const SkillTool = createSkillTool()
610
676
 
@@ -667,6 +733,11 @@ function grantNotice(
667
733
  return `\n\n[${lines.join(' ')}]`
668
734
  }
669
735
 
736
+ /** The prompt a forked skill's delegated agent is given. */
737
+ function forkedPrompt(header: string, argsLine: string, body: string | undefined): string {
738
+ return `${header}${argsLine}${body ?? '(this skill has no body)'}`
739
+ }
740
+
670
741
  /**
671
742
  * Run a `context: fork` skill through the turn's delegation tool.
672
743
  *
@@ -687,19 +758,37 @@ async function runForkedSkill(input: {
687
758
  }
688
759
  readonly body?: string
689
760
  }
690
- readonly argsLine: string
691
- readonly header: string
761
+ /** The prompt the delegated agent is given; see {@link forkedPrompt}. */
762
+ readonly prompt: string
692
763
  readonly dispatch: NonNullable<ToolContext['dispatchTool']>
764
+ /** The skill's hooks, made live for the delegated agent's run only. */
765
+ readonly hooks?: SkillHooksPlan
693
766
  }) {
694
- const { metadata, body } = input.skill
695
- const result = await input.dispatch(DELEGATION_TOOL_NAME, {
696
- description: `Skill ${input.name}`,
697
- prompt: `${input.header}${input.argsLine}${body ?? '(this skill has no body)'}`,
698
- ...(metadata.agent === undefined ? {} : { subagent_type: metadata.agent }),
699
- ...(metadata.model === undefined ? {} : { model: metadata.model }),
700
- ...(metadata.effort === undefined ? {} : { effort: metadata.effort }),
701
- ...(metadata.background === undefined ? {} : { run_in_background: metadata.background }),
702
- })
767
+ const { metadata } = input.skill
768
+ const attached = input.hooks?.attach()
769
+ let ended = false
770
+ const end = (): void => {
771
+ if (ended) return
772
+ ended = true
773
+ attached?.remove()
774
+ }
775
+ let result: Awaited<ReturnType<typeof input.dispatch>>
776
+ try {
777
+ result = await input.dispatch(DELEGATION_TOOL_NAME, {
778
+ description: `Skill ${input.name}`,
779
+ prompt: input.prompt,
780
+ ...(metadata.agent === undefined ? {} : { subagent_type: metadata.agent }),
781
+ ...(metadata.model === undefined ? {} : { model: metadata.model }),
782
+ ...(metadata.effort === undefined ? {} : { effort: metadata.effort }),
783
+ ...(metadata.background === undefined ? {} : { run_in_background: metadata.background }),
784
+ })
785
+ } catch (error) {
786
+ end()
787
+ throw error
788
+ }
789
+ // A foreground agent is over when the dispatch returns. A background one is
790
+ // not: the host that bound the hooks to it ends them when it ends.
791
+ if (metadata.background !== true || !result.success) end()
703
792
  return {
704
793
  ...result,
705
794
  // Says what the text is, so a later pass never carries a report as the skill's steps.
@@ -158,6 +158,30 @@ export type PluginHookEvent =
158
158
  * settled. Carries `notification` (`type` and `message`). Observational.
159
159
  */
160
160
  | 'notification'
161
+ /**
162
+ * A file a hook asked to watch changed on disk. Carries `filePath` and
163
+ * `change`. Fired by the host once the file has been still for a moment, so a
164
+ * burst of writes is one event. A hook cannot refuse anything here; it may
165
+ * hand back a new list of paths to watch (`watchPaths`).
166
+ */
167
+ | 'file_changed'
168
+ /**
169
+ * The folder the session's shell commands run in changed. Carries `oldCwd`
170
+ * and `newCwd`. Fired by the host, never when the two are the same folder.
171
+ */
172
+ | 'cwd_changed'
173
+ /**
174
+ * A worktree is about to be created. Carries `worktreeName` (the suggested
175
+ * name) and `worktreeRoot` (where a relative answer is placed). A hook that
176
+ * answers with a path (`worktreePath`) makes the worktree itself; the host
177
+ * then creates none.
178
+ */
179
+ | 'worktree_create'
180
+ /**
181
+ * A worktree is about to be removed. Carries `worktreePath`. A hook on it
182
+ * does the removing; the host then removes nothing.
183
+ */
184
+ | 'worktree_remove'
161
185
  | 'pre_llm_call'
162
186
  | 'post_llm_call'
163
187
  | 'iteration_start'
@@ -197,6 +221,10 @@ export function assertPluginHookEvent(event: PluginHookEvent): void {
197
221
  case 'permission_denied':
198
222
  case 'permission_request':
199
223
  case 'notification':
224
+ case 'file_changed':
225
+ case 'cwd_changed':
226
+ case 'worktree_create':
227
+ case 'worktree_remove':
200
228
  case 'pre_llm_call':
201
229
  case 'post_llm_call':
202
230
  case 'iteration_start':
@@ -288,6 +316,9 @@ export interface PluginToolBatchCall {
288
316
  readonly isError: boolean
289
317
  }
290
318
 
319
+ /** What happened to a watched file, on `file_changed`. */
320
+ export type PluginFileChange = 'change' | 'add' | 'unlink'
321
+
291
322
  /** What a `notification` hook is shown. */
292
323
  export interface PluginNotificationInfo {
293
324
  /**
@@ -335,6 +366,22 @@ export interface PluginHookContext {
335
366
  readonly endReason?: PluginSessionEndReason
336
367
  /** The operator's prompt, on `user_prompt_submit`. */
337
368
  readonly prompt?: string
369
+ /** The file that changed, absolute, on `file_changed`. */
370
+ readonly filePath?: string
371
+ /** What happened to `filePath`, on `file_changed`. */
372
+ readonly change?: PluginFileChange
373
+ /** The folder commands ran in before, on `cwd_changed`. */
374
+ readonly oldCwd?: string
375
+ /** The folder commands run in now, on `cwd_changed`. */
376
+ readonly newCwd?: string
377
+ /** The suggested name of the worktree, on `worktree_create`. */
378
+ readonly worktreeName?: string
379
+ /** The folder a relative worktree path is placed under, on `worktree_create`. */
380
+ readonly worktreeRoot?: string
381
+ /** The commit or branch the worktree should start from, on `worktree_create`, when one was asked for. */
382
+ readonly worktreeBaseRef?: string
383
+ /** The worktree to remove, on `worktree_remove`. */
384
+ readonly worktreePath?: string
338
385
  /** The pass, on `pre_compact` and `post_compact`. */
339
386
  readonly compaction?: PluginCompactionInfo
340
387
  readonly toolName?: string
@@ -451,6 +498,17 @@ export interface PluginHookNotes {
451
498
  readonly halt?: { readonly reason: string }
452
499
  /** A warning for the operator, reported through the logger. */
453
500
  readonly notice?: string
501
+ /**
502
+ * On `file_changed`, `cwd_changed` and `session_start`: the files the host
503
+ * should watch from now on, replacing the list hooks gave before. Other
504
+ * events ignore it.
505
+ */
506
+ readonly watchPaths?: readonly string[]
507
+ /**
508
+ * On `worktree_create`: the folder the hook made. The host uses it as the
509
+ * worktree and creates none. Other events ignore it.
510
+ */
511
+ readonly worktreePath?: string
454
512
  }
455
513
 
456
514
  export type PluginHookResult =
@@ -466,7 +524,12 @@ export type PluginHookResult =
466
524
  * on the prompt. Accepted on that event only: a tool hook that returns
467
525
  * it is rejected, because a tool result is not a place for context.
468
526
  */
469
- | { action: 'annotate'; text: string }
527
+ | {
528
+ action: 'annotate'
529
+ text: string
530
+ watchPaths?: readonly string[]
531
+ notice?: string
532
+ }
470
533
  | ({ action: 'skip'; reason: string } & PluginHookNotes)
471
534
  | ({
472
535
  action: 'modify'
@@ -555,6 +618,8 @@ export type PluginHookResultFor<E extends PluginHookEvent> = E extends 'user_pro
555
618
  | 'notification'
556
619
  | 'turn_failure'
557
620
  | 'permission_denied'
621
+ | 'file_changed'
622
+ | 'cwd_changed'
558
623
  ? Extract<PluginHookResult, { action: 'continue' }>
559
624
  : Extract<PluginHookResult, { action: 'continue' | 'error' }>
560
625
 
@@ -580,6 +645,12 @@ export type PluginHookDefinition<E extends PluginHookEvent = PluginHookEvent> =
580
645
  * ignores it.
581
646
  */
582
647
  readonly statusMessage?: string
648
+ /**
649
+ * On a `file_changed` hook: the paths its matcher names, which the host
650
+ * watches for as long as the hook is attached. Listed by
651
+ * `PluginLifecycleManager.listHooks`.
652
+ */
653
+ readonly watches?: readonly string[]
583
654
  }
584
655
  : never
585
656
 
@@ -609,7 +680,18 @@ export interface PluginManifest {
609
680
  readonly instructions?: string
610
681
  readonly tools?: readonly string[]
611
682
  readonly skills?: readonly string[]
683
+ /**
684
+ * Paths inside the plugin folder. A path that ends in `.json` names a file of
685
+ * shell, http or prompt hook entries (read by the host, see `hookEntries`);
686
+ * any other path is a JavaScript module exporting a `hooks` array.
687
+ */
612
688
  readonly hooks?: readonly string[]
689
+ /**
690
+ * Shell, http or prompt hook entries written inline: the same events object a
691
+ * hooks file holds (event name to a list of entries or groups). The runtime
692
+ * keeps it as written; the host that owns shell hooks reads it.
693
+ */
694
+ readonly hookEntries?: Readonly<Record<string, unknown>>
613
695
  readonly mcpServers?: readonly PluginMCPServerConfig[]
614
696
  readonly connectors?: readonly string[]
615
697
  readonly personas?: readonly string[]
@@ -664,6 +746,7 @@ export const PluginManifestSchema = z.object({
664
746
  tools: z.array(z.string()).max(MAX_TOOLS_PER_PLUGIN).optional(),
665
747
  skills: z.array(z.string()).max(MAX_SKILLS_PER_PLUGIN).optional(),
666
748
  hooks: z.array(z.string()).max(MAX_HOOKS_PER_PLUGIN).optional(),
749
+ hookEntries: z.record(z.string(), z.unknown()).optional(),
667
750
  mcpServers: z.array(PluginMCPServerConfigSchema).max(MAX_MCP_SERVERS_PER_PLUGIN).optional(),
668
751
  connectors: z.array(z.string()).max(MAX_CONNECTORS_PER_PLUGIN).optional(),
669
752
  personas: z.array(z.string()).max(MAX_PERSONAS_PER_PLUGIN).optional(),
@@ -72,6 +72,15 @@ export interface SkillMetadata {
72
72
 
73
73
  /** Whether a `fork` skill's agent runs in the background (`background`). */
74
74
  background?: boolean
75
+
76
+ /**
77
+ * The `hooks` block of the front matter, as the file wrote it (the key's
78
+ * line and the lines under it). The kernel does not read it: a host that
79
+ * runs hooks parses it with its own YAML reader, because the block is a
80
+ * list of mappings in a mapping, which the front matter reader holds only
81
+ * as text. Absent when the file has no `hooks` key or it is empty.
82
+ */
83
+ hooksSource?: string
75
84
  }
76
85
 
77
86
  /**
@@ -99,6 +99,8 @@ export interface SkillRegistryRef {
99
99
  model?: string
100
100
  effort?: import('../provider/chat.js').ReasoningEffort
101
101
  background?: boolean
102
+ /** The `hooks` block as the file wrote it; see `SkillMetadata.hooksSource`. */
103
+ hooksSource?: string
102
104
  }
103
105
  body?: string
104
106
  /** The skill's directory, which `${CLAUDE_SKILL_DIR}` in `allowed-tools` names. */
@@ -109,6 +111,65 @@ export interface SkillRegistryRef {
109
111
  >
110
112
  /** Every registered name, for a "did you mean" that names real options. */
111
113
  names(): readonly string[]
114
+ /**
115
+ * Read the hooks a skill carries, without attaching anything.
116
+ *
117
+ * Called by the `skill` tool for a skill whose front matter has a `hooks`
118
+ * block. Hooks are not a thing the kernel reads: the host that runs them
119
+ * answers. The answer says what to tell the model, whether the skill's
120
+ * `allowed-tools` may still be pre-approved, and, as `attach`, the one
121
+ * call that makes the hooks live. `attach` is called only once the skill's
122
+ * instructions have been delivered, like the tool grant's `commit`, and
123
+ * returns a handle that removes exactly what it attached.
124
+ *
125
+ * Absent, a skill that carries hooks loads without them, and without its
126
+ * `allowed-tools` pre-approval: a skill written to run its commands under
127
+ * its own guard must not run them unguarded and pre-approved.
128
+ */
129
+ prepareHooks?(
130
+ skill: {
131
+ readonly name: string
132
+ readonly dirPath?: string
133
+ readonly hooksSource: string
134
+ },
135
+ options: SkillHooksOptions,
136
+ ): SkillHooksPlan
137
+ }
138
+
139
+ /** What the `skill` tool tells a host's hook reader about the use it is making of a skill. */
140
+ export interface SkillHooksOptions {
141
+ /** The skill runs in a delegated agent: its hooks belong to that agent's run only. */
142
+ readonly forked: boolean
143
+ /**
144
+ * For a forked skill: the prompt the delegated agent is given, so the host
145
+ * can tell that agent from any other that starts at the same time.
146
+ */
147
+ readonly prompt?: string
148
+ /** The session the `skill` tool was called in. */
149
+ readonly sessionId?: string
150
+ }
151
+
152
+ /** What a host decided about the hooks a skill carries; see {@link SkillRegistryRef.prepareHooks}. */
153
+ export interface SkillHooksPlan {
154
+ /** One line for the model, and for the person, about the hooks. Empty when there is nothing to say. */
155
+ readonly notice?: string
156
+ /**
157
+ * The skill's `allowed-tools` must not be pre-approved: some hook that
158
+ * guards its work could not be loaded, or hooks cannot be attached here.
159
+ */
160
+ readonly withholdGrants: boolean
161
+ /** Make the hooks live. Idempotent for a skill already attached to the conversation. */
162
+ attach(): SkillHooksHandle
163
+ }
164
+
165
+ /** What {@link SkillHooksPlan.attach} gives back. */
166
+ export interface SkillHooksHandle {
167
+ /**
168
+ * For a forked skill: bind the hooks to the delegated agent that is about
169
+ * to start, and end them when it ends. Absent for an inline skill, whose
170
+ * hooks last as long as the conversation.
171
+ */
172
+ readonly remove: () => void
112
173
  }
113
174
 
114
175
  /**
@@ -547,6 +608,19 @@ export interface ToolContext {
547
608
  /** The turn this call belongs to. */
548
609
  turnId: TurnId
549
610
  workingDirectory: string
611
+ /**
612
+ * Called by the shell tool, after a command has finished, when the folder the
613
+ * session's next shell command starts in is a different folder from the one
614
+ * this command started in (it ran `cd`, or was put back at the working
615
+ * directory for leaving the allowed folders). Awaited before the result is
616
+ * returned, so what a host does here is done before the next command. Never
617
+ * called with the same folder twice in a row, and not at all for a command
618
+ * that did not move.
619
+ */
620
+ workingDirectoryChanged?: (change: {
621
+ readonly from: string
622
+ readonly to: string
623
+ }) => Promise<void> | void
550
624
  /**
551
625
  * Directories besides the working directory the file tools may reach,
552
626
  * absolute. A host adds one for a session (`/add-dir`); a sandboxed turn
@@ -31,6 +31,12 @@ export interface GitWorktreeBackendMeta {
31
31
  worktreePath: string
32
32
  /** The commit the checkout started on; absent on refs made before it was recorded. */
33
33
  baseCommit?: string
34
+ /**
35
+ * Set when a `worktree_create` hook made the folder. It is the hook's: the
36
+ * kernel never runs its own Git removal on it, it asks the `worktree_remove`
37
+ * hooks and, with none, leaves the folder where it is.
38
+ */
39
+ hookOwned?: true
34
40
  }
35
41
 
36
42
  /**
@@ -157,6 +157,16 @@ export interface FrontmatterOptions {
157
157
  * which is what it meant to everything before it was read.
158
158
  */
159
159
  readonly tolerates?: (key: string) => boolean
160
+ /**
161
+ * Keys whose value is handed back as the text the file wrote, not parsed
162
+ * here: the key's own line and every line under it, up to the next
163
+ * top-level key, in {@link ParsedFrontmatter.rawBlocks}. For a key whose
164
+ * structure this flat reader cannot hold (a `hooks` block is a list of
165
+ * mappings, a list in it) and whose reader is the caller's, which has a
166
+ * real YAML parser. The key is never refused for its shape and never
167
+ * appears in `values`; every other key is read exactly as before.
168
+ */
169
+ readonly raw?: readonly string[]
160
170
  }
161
171
 
162
172
  export interface ParsedFrontmatter {
@@ -174,6 +184,13 @@ export interface ParsedFrontmatter {
174
184
  */
175
185
  readonly values: Readonly<Record<string, FrontmatterValue>>
176
186
 
187
+ /**
188
+ * The text of each key named in {@link FrontmatterOptions.raw} that the
189
+ * file declared, from its key line to the line before the next top-level
190
+ * key. Absent keys are absent.
191
+ */
192
+ readonly rawBlocks: Readonly<Record<string, string>>
193
+
177
194
  /** Everything after the closing fence, trimmed. */
178
195
  readonly body: string
179
196
  }
@@ -230,10 +247,38 @@ export function parseFrontmatter(
230
247
  // The current top-level key is one the caller does not read: its value
231
248
  // and its indented lines are skipped rather than parsed or refused.
232
249
  let skipping = false
250
+ // The caller reads these keys itself: their lines are collected as written.
251
+ const rawKeys = new Set(options.raw ?? [])
252
+ const rawBlocks = new Map<string, string[]>()
253
+ let rawCurrent: string[] | undefined
233
254
 
234
255
  for (const line of frontmatterRaw.split(LINE_SPLIT)) {
256
+ // Blank lines and comments inside a raw block belong to it (a block
257
+ // scalar's blank line is part of its text); they end nothing.
258
+ if (rawCurrent && (!line.trim() || line.trimStart().startsWith('#'))) {
259
+ rawCurrent.push(line)
260
+ continue
261
+ }
235
262
  if (!line.trim() || line.trimStart().startsWith('#')) continue
236
263
 
264
+ if (rawCurrent && (/^\s/.test(line) || /^-(\s|$)/.test(line))) {
265
+ rawCurrent.push(line)
266
+ continue
267
+ }
268
+
269
+ if (!/^\s/.test(line)) {
270
+ rawCurrent = undefined
271
+ const rawColon = line.indexOf(':')
272
+ const rawKey = rawColon === -1 ? '' : line.slice(0, rawColon).trim()
273
+ if (rawKey && rawKeys.has(rawKey)) {
274
+ rawCurrent = [line]
275
+ rawBlocks.set(rawKey, rawCurrent)
276
+ currentKey = rawKey
277
+ skipping = true
278
+ continue
279
+ }
280
+ }
281
+
237
282
  if (/^\s/.test(line)) {
238
283
  if (!currentKey || skipping) continue
239
284
 
@@ -342,7 +387,13 @@ export function parseFrontmatter(
342
387
  values.set(key, { kind: 'mapping', entries: Object.fromEntries(entries) })
343
388
  }
344
389
 
345
- return { values: Object.fromEntries(values), body }
390
+ return {
391
+ values: Object.fromEntries(values),
392
+ rawBlocks: Object.fromEntries(
393
+ [...rawBlocks].map(([key, lines]) => [key, lines.join('\n').replace(/\s+$/, '')]),
394
+ ),
395
+ body,
396
+ }
346
397
  }
347
398
 
348
399
  function normalizeScalar(value: string): string {