@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
@@ -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 {
@@ -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,10 +611,30 @@ 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()
616
+ // Kept with the conversation, so a host that continues it later can
617
+ // attach the same hooks again. Once, on the first page of a load.
618
+ let output = page.output
619
+ if (hooksPlan?.resumable === true && start === 0 && skill.dirPath !== undefined) {
620
+ const kept = context.recordSkillHooks
621
+ ? await context
622
+ .recordSkillHooks({
623
+ skill: skill.metadata.name,
624
+ directory: skill.dirPath,
625
+ grantsWithheld: hooksPlan.withholdGrants,
626
+ ...(context.toolUseId !== undefined ? { toolCallId: context.toolUseId } : {}),
627
+ })
628
+ .catch(() => false)
629
+ : false
630
+ if (!kept) {
631
+ output += `\n\n[${SKILL_HOOKS_NOT_KEPT}]`
632
+ }
633
+ }
592
634
 
593
635
  return {
594
636
  success: true,
595
- output: page.output,
637
+ output,
596
638
  data: {
597
639
  skill: skill.metadata.name,
598
640
  ...(modelDirectory === undefined ? {} : { directory: modelDirectory }),
@@ -605,6 +647,52 @@ export function createSkillTool(options: SkillToolOptions = {}) {
605
647
  })
606
648
  }
607
649
 
650
+ /** Said to the model when a skill's hooks could not be written into the conversation's record. */
651
+ const SKILL_HOOKS_NOT_KEPT =
652
+ "This conversation could not keep a record of this skill's hooks, so if it is continued later they will not be attached again: load the skill again then."
653
+
654
+ /**
655
+ * What the host says of the hooks a skill carries, or `undefined` for a skill
656
+ * that carries none. A registry that cannot read hooks answers with a plan
657
+ * that attaches nothing and withholds the pre-approval: the skill still
658
+ * loads, and the model is told in one line why its commands are not
659
+ * pre-approved.
660
+ */
661
+ function hooksPlanFor(
662
+ skill: {
663
+ readonly metadata: { readonly name: string; readonly hooksSource?: string }
664
+ readonly dirPath?: string
665
+ },
666
+ context: ToolContext,
667
+ forked: boolean,
668
+ /** For a forked skill: the prompt the delegated agent is given. */
669
+ prompt?: string,
670
+ ): SkillHooksPlan | undefined {
671
+ const hooksSource = skill.metadata.hooksSource
672
+ if (hooksSource === undefined) return undefined
673
+ const prepare = context.skills?.prepareHooks
674
+ if (!prepare || !context.skills) {
675
+ return {
676
+ 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.`,
677
+ withholdGrants: true,
678
+ attach: () => ({ remove: () => undefined }),
679
+ }
680
+ }
681
+ return prepare.call(
682
+ context.skills,
683
+ {
684
+ name: skill.metadata.name,
685
+ ...(skill.dirPath !== undefined ? { dirPath: skill.dirPath } : {}),
686
+ hooksSource,
687
+ },
688
+ {
689
+ forked,
690
+ ...(forked && prompt !== undefined ? { prompt } : {}),
691
+ ...(context.sessionId !== undefined ? { sessionId: String(context.sessionId) } : {}),
692
+ },
693
+ )
694
+ }
695
+
608
696
  /** The `skill` tool with no host options: the listing carries the registry's `location`. */
609
697
  export const SkillTool = createSkillTool()
610
698
 
@@ -667,6 +755,11 @@ function grantNotice(
667
755
  return `\n\n[${lines.join(' ')}]`
668
756
  }
669
757
 
758
+ /** The prompt a forked skill's delegated agent is given. */
759
+ function forkedPrompt(header: string, argsLine: string, body: string | undefined): string {
760
+ return `${header}${argsLine}${body ?? '(this skill has no body)'}`
761
+ }
762
+
670
763
  /**
671
764
  * Run a `context: fork` skill through the turn's delegation tool.
672
765
  *
@@ -687,19 +780,37 @@ async function runForkedSkill(input: {
687
780
  }
688
781
  readonly body?: string
689
782
  }
690
- readonly argsLine: string
691
- readonly header: string
783
+ /** The prompt the delegated agent is given; see {@link forkedPrompt}. */
784
+ readonly prompt: string
692
785
  readonly dispatch: NonNullable<ToolContext['dispatchTool']>
786
+ /** The skill's hooks, made live for the delegated agent's run only. */
787
+ readonly hooks?: SkillHooksPlan
693
788
  }) {
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
- })
789
+ const { metadata } = input.skill
790
+ const attached = input.hooks?.attach()
791
+ let ended = false
792
+ const end = (): void => {
793
+ if (ended) return
794
+ ended = true
795
+ attached?.remove()
796
+ }
797
+ let result: Awaited<ReturnType<typeof input.dispatch>>
798
+ try {
799
+ result = await input.dispatch(DELEGATION_TOOL_NAME, {
800
+ description: `Skill ${input.name}`,
801
+ prompt: input.prompt,
802
+ ...(metadata.agent === undefined ? {} : { subagent_type: metadata.agent }),
803
+ ...(metadata.model === undefined ? {} : { model: metadata.model }),
804
+ ...(metadata.effort === undefined ? {} : { effort: metadata.effort }),
805
+ ...(metadata.background === undefined ? {} : { run_in_background: metadata.background }),
806
+ })
807
+ } catch (error) {
808
+ end()
809
+ throw error
810
+ }
811
+ // A foreground agent is over when the dispatch returns. A background one is
812
+ // not: the host that bound the hooks to it ends them when it ends.
813
+ if (metadata.background !== true || !result.success) end()
703
814
  return {
704
815
  ...result,
705
816
  // 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(),
@@ -660,6 +660,31 @@ export const OutcomeProgressWrittenRecordSchema = inTurn('outcome_progress_writt
660
660
  progress: outcomeBody,
661
661
  })
662
662
 
663
+ /**
664
+ * A skill's hooks were attached to the conversation (or refused) when the model
665
+ * loaded it. Written by the `skill` tool's host in the turn that loaded it,
666
+ * flagged `ignorable`: a release that does not know the type skips it, keeps it
667
+ * in the hash chain and folds the conversation as before, and a host that does
668
+ * know it attaches the skill's hooks again when the conversation is continued
669
+ * (`docs/sdk/hooks.md`, "Hooks in a skill"). Never a field of a record that
670
+ * existed before it, for the reason the outcome records give above.
671
+ *
672
+ * Carries the turn's id when the skill was loaded in a turn, and none when a
673
+ * copy of a conversation (a fork) carries the record over.
674
+ *
675
+ * `directory` is the skill's own folder, `grantsWithheld` whether its
676
+ * `allowed-tools` were left unapproved, and `toolCallId` the `skill` call that
677
+ * loaded it, so a copy of a conversation that stops before that call can leave
678
+ * the record behind.
679
+ */
680
+ export const SkillHooksAttachedRecordSchema = recordSchema('skill_hooks_attached', {
681
+ ignorable: z.literal(true),
682
+ skill: text.min(1),
683
+ directory: text.min(1),
684
+ grantsWithheld: z.boolean(),
685
+ toolCallId: text.min(1).optional(),
686
+ })
687
+
663
688
  export const LogRepairedRecordSchema = recordSchema('log_repaired', {
664
689
  truncatedBytes: positive,
665
690
  lastGoodSeq: positive,
@@ -702,6 +727,7 @@ const RECORD_ONLY_SCHEMAS = {
702
727
  turn_outcome_recorded: TurnOutcomeRecordedRecordSchema,
703
728
  child_outcome_recorded: ChildOutcomeRecordedRecordSchema,
704
729
  outcome_progress_written: OutcomeProgressWrittenRecordSchema,
730
+ skill_hooks_attached: SkillHooksAttachedRecordSchema,
705
731
  } as const
706
732
 
707
733
  export type SessionRecordOnlyType = keyof typeof RECORD_ONLY_SCHEMAS
@@ -1124,6 +1150,7 @@ export type LogRepairedRecord = z.infer<typeof LogRepairedRecordSchema>
1124
1150
  export type TurnOutcomeRecordedRecord = z.infer<typeof TurnOutcomeRecordedRecordSchema>
1125
1151
  export type ChildOutcomeRecordedRecord = z.infer<typeof ChildOutcomeRecordedRecordSchema>
1126
1152
  export type OutcomeProgressWrittenRecord = z.infer<typeof OutcomeProgressWrittenRecordSchema>
1153
+ export type SkillHooksAttachedRecord = z.infer<typeof SkillHooksAttachedRecordSchema>
1127
1154
 
1128
1155
  export type SessionRecordOnly =
1129
1156
  | SessionStartedRecord
@@ -1145,6 +1172,7 @@ export type SessionRecordOnly =
1145
1172
  | TurnOutcomeRecordedRecord
1146
1173
  | ChildOutcomeRecordedRecord
1147
1174
  | OutcomeProgressWrittenRecord
1175
+ | SkillHooksAttachedRecord
1148
1176
 
1149
1177
  /** One line of a session log. */
1150
1178
  export type SessionRecord = SessionEventRecord | SessionRecordOnly
@@ -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
  /**