@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
@@ -0,0 +1,142 @@
1
+ /**
2
+ * What a hook on `worktree_create` or `worktree_remove` answered.
3
+ *
4
+ * These two events are not like the others: a hook does not advise the kernel,
5
+ * it does the work. So the answer is read strictly and never falls back to the
6
+ * outcome the person was trying to replace:
7
+ *
8
+ * - `worktree_create` needs a path. It is `hookSpecificOutput.worktreePath` of
9
+ * a JSON answer, or else the last non-empty line the hook printed. Anything
10
+ * else (no path, a failed hook, a refusal, output cut short) is an `error`
11
+ * answer carrying a sentence that names the hook and what it printed.
12
+ * - `worktree_remove` needs the hook to finish cleanly. A failure is an `error`
13
+ * answer carrying the start and the end of what it printed.
14
+ *
15
+ * The host reads `error` as "do not create / do not remove behind the person's
16
+ * back"; see `HookedWorkspaceDriver`.
17
+ */
18
+
19
+ import type { PluginHookResult } from '../types/plugin/index.js'
20
+ import type { ShellHookOutcome } from './shell-hook.js'
21
+
22
+ /** The most characters of a hook's output shown at each end. */
23
+ export const WORKTREE_HOOK_SHOWN_CHARS = 300
24
+
25
+ /** The start and the end of what a hook printed, with the middle elided when it is long. */
26
+ export function worktreeHookPrinted(outcome: Pick<ShellHookOutcome, 'stdout' | 'stderr'>): string {
27
+ const parts: string[] = []
28
+ for (const [label, raw] of [
29
+ ['stdout', outcome.stdout],
30
+ ['stderr', outcome.stderr],
31
+ ] as const) {
32
+ const text = raw.trim()
33
+ if (text === '') continue
34
+ const shown =
35
+ text.length <= WORKTREE_HOOK_SHOWN_CHARS * 2
36
+ ? text
37
+ : `${text.slice(0, WORKTREE_HOOK_SHOWN_CHARS)} … ${text.slice(-WORKTREE_HOOK_SHOWN_CHARS)}`
38
+ parts.push(`${label}: ${shown}`)
39
+ }
40
+ return parts.length === 0 ? 'it printed nothing' : `it printed ${parts.join('; ')}`
41
+ }
42
+
43
+ function isRecord(value: unknown): value is Record<string, unknown> {
44
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
45
+ }
46
+
47
+ /** The JSON object a hook printed, when its whole output is one. */
48
+ function jsonOf(stdout: string): Record<string, unknown> | undefined {
49
+ const text = stdout.trim()
50
+ if (!text.startsWith('{')) return undefined
51
+ try {
52
+ const parsed: unknown = JSON.parse(text)
53
+ return isRecord(parsed) ? parsed : undefined
54
+ } catch {
55
+ return undefined
56
+ }
57
+ }
58
+
59
+ /** A refusal written in JSON, as the other events read it: `continue: false` or `decision: "block"`. */
60
+ function refusalIn(json: Record<string, unknown>): string | undefined {
61
+ const reason = (value: unknown, fallback: string): string =>
62
+ typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
63
+ if (json.continue === false) return reason(json.stopReason, 'it answered continue: false')
64
+ if (json.decision === 'block') return reason(json.reason, 'it answered decision: block')
65
+ return undefined
66
+ }
67
+
68
+ function failureOf(
69
+ event: 'worktree_create' | 'worktree_remove',
70
+ label: string,
71
+ outcome: ShellHookOutcome,
72
+ ): string | undefined {
73
+ const what = event === 'worktree_create' ? 'create' : 'remove'
74
+ if (outcome.spawnError !== undefined) {
75
+ return `The ${event} hook \`${label}\` could not start (${outcome.spawnError}), so the worktree was not ${what === 'create' ? 'created' : 'removed'}.`
76
+ }
77
+ if (outcome.timedOut) {
78
+ return `The ${event} hook \`${label}\` timed out, so the worktree was not ${what === 'create' ? 'created' : 'removed'}; ${worktreeHookPrinted(outcome)}.`
79
+ }
80
+ if (outcome.exitCode !== 0) {
81
+ return `The ${event} hook \`${label}\` failed (exit ${outcome.exitCode ?? 'by signal'}), so the worktree was not ${what === 'create' ? 'created' : 'removed'}; ${worktreeHookPrinted(outcome)}.`
82
+ }
83
+ return undefined
84
+ }
85
+
86
+ /** The answer of one hook run on `worktree_create` or `worktree_remove`. */
87
+ export function worktreeHookVerdict(
88
+ event: 'worktree_create' | 'worktree_remove',
89
+ label: string,
90
+ outcome: ShellHookOutcome,
91
+ ): PluginHookResult {
92
+ const failed = failureOf(event, label, outcome)
93
+ if (failed !== undefined) return { action: 'error', message: failed }
94
+
95
+ const json = jsonOf(outcome.stdout)
96
+ if (json !== undefined) {
97
+ const refused = refusalIn(json)
98
+ if (refused !== undefined) {
99
+ return {
100
+ action: 'error',
101
+ message: `The ${event} hook \`${label}\` refused: ${refused}.`,
102
+ }
103
+ }
104
+ }
105
+ if (event === 'worktree_remove') return { action: 'continue' }
106
+
107
+ // worktree_create: a path is the answer.
108
+ if (outcome.stdoutTruncated === true) {
109
+ return {
110
+ action: 'error',
111
+ message: `The ${event} hook \`${label}\` printed more than is kept, so its last line cannot be trusted as the path; ${worktreeHookPrinted(outcome)}. Send progress to stderr and print only the path, or answer JSON with hookSpecificOutput.worktreePath.`,
112
+ }
113
+ }
114
+ let path: string | undefined
115
+ if (json !== undefined) {
116
+ const specific = json.hookSpecificOutput
117
+ const given = isRecord(specific) ? specific.worktreePath : undefined
118
+ if (typeof given === 'string' && given.trim() !== '') path = given.trim()
119
+ else if (given !== undefined) {
120
+ return {
121
+ action: 'error',
122
+ message: `The ${event} hook \`${label}\` answered hookSpecificOutput.worktreePath that is not a path (a string); ${worktreeHookPrinted(outcome)}.`,
123
+ }
124
+ } else if (json.worktreePath !== undefined) {
125
+ return {
126
+ action: 'error',
127
+ message: `The ${event} hook \`${label}\` wrote worktreePath at the top level of its answer; it is read under hookSpecificOutput. ${worktreeHookPrinted(outcome)}.`,
128
+ }
129
+ }
130
+ } else {
131
+ const lines = outcome.stdout.split(/\r?\n/).filter((line) => line.trim() !== '')
132
+ const last = lines[lines.length - 1]
133
+ if (last !== undefined) path = last.trim()
134
+ }
135
+ if (path === undefined) {
136
+ return {
137
+ action: 'error',
138
+ message: `The ${event} hook \`${label}\` gave no worktree path, so none was created; ${worktreeHookPrinted(outcome)}. Print the folder it made as its last line, or answer JSON with hookSpecificOutput.worktreePath.`,
139
+ }
140
+ }
141
+ return { action: 'continue', worktreePath: path }
142
+ }
@@ -519,6 +519,9 @@ export {
519
519
  parseSkillMarkdown,
520
520
  resolveSkillChain,
521
521
  SKILL_FRONTMATTER_KEYS,
522
+ SKILL_FRONTMATTER_RAW_KEYS,
523
+ SKILL_FRONTMATTER_HOOK_EVENT_KEYS,
524
+ skillHooksSource,
522
525
  SKILL_FRONTMATTER_TOLERATED_KEYS,
523
526
  SkillCollisionError,
524
527
  SkillRegistry,
@@ -717,6 +720,16 @@ export {
717
720
  loadPluginManifest,
718
721
  parsePluginManifestText,
719
722
  MAX_SHELL_HOOK_TIMEOUT_MS,
723
+ isHookEntriesPath,
724
+ assignedWithin,
725
+ isPluginFolderVariable,
726
+ isShellOwnVariable,
727
+ MOVED_FOLDER_ENDINGS,
728
+ referencedVariables,
729
+ SHELL_HOOK_RESERVED_ENV,
730
+ shellHookEnvNameProblem,
731
+ shellHookEnvProblems,
732
+ substitutePluginFolders,
720
733
  PluginLifecycleManager,
721
734
  PluginResolver,
722
735
  runShellHook,
@@ -730,6 +743,22 @@ export {
730
743
  shellHookMatcherProblem,
731
744
  shellHookMatches,
732
745
  shellHookVerdict,
746
+ fileChangedMatcherNote,
747
+ fileChangedMatcherPaths,
748
+ fileChangedMatches,
749
+ HOOK_ENV_EVENTS,
750
+ MAX_HOOK_ENV_FILE_BYTES,
751
+ MAX_HOOK_ENV_VALUE_CHARS,
752
+ MAX_HOOK_ENV_VARIABLES,
753
+ refusedHookEnvName,
754
+ SessionHookEnv,
755
+ FILE_SETTLE_MS,
756
+ FileChangeWatcher,
757
+ MAX_WATCHED_PATHS,
758
+ FileChangeHooks,
759
+ worktreeHookVerdict,
760
+ worktreeHookPrinted,
761
+ WORKTREE_HOOK_SHOWN_CHARS,
733
762
  } from './plugin/index.js'
734
763
  export type { DefinedPlugin, DefinePluginOptions } from './plugin/define.js'
735
764
 
@@ -1190,6 +1219,9 @@ export type { VaultInstrumentationOptions } from './vault/instrumentation.js'
1190
1219
 
1191
1220
  export {
1192
1221
  GitWorktreeDriver,
1222
+ HookedWorkspaceDriver,
1223
+ WorktreeHookError,
1224
+ worktreeHookHost,
1193
1225
  parseWorktreeList,
1194
1226
  SharedSessionWorkspace,
1195
1227
  WorkspaceBackendRegistry,
@@ -226,7 +226,7 @@ export type {
226
226
 
227
227
  export type { ManagedRegistryConfig } from './registry/index.js'
228
228
 
229
- export type { PluginLifecycleManagerConfig } from './plugin/lifecycle.js'
229
+ export type { HookAttachment, PluginLifecycleManagerConfig } from './plugin/lifecycle.js'
230
230
  export type {
231
231
  AgentDefinitionRoot,
232
232
  AgentFileDefinition,
@@ -250,6 +250,14 @@ export type {
250
250
  ShellHooksConfig,
251
251
  } from './plugin/shell-hook.js'
252
252
  export type { ShellHookToolNames } from './plugin/shell-hook-tool-names.js'
253
+ export type { HookEnvEvent, SessionHookEnvOptions } from './plugin/session-hook-env.js'
254
+ export type {
255
+ FileChange,
256
+ FileChangeWatcherOptions,
257
+ WatchDirectory,
258
+ } from './plugin/file-change-watch.js'
259
+ export type { FileChangeHooksOptions } from './plugin/file-change-hooks.js'
260
+ export type { PluginFolders } from './plugin/shell-hook-env.js'
253
261
 
254
262
  export type {
255
263
  PlanApprovalHandler,
@@ -343,6 +351,17 @@ export type { ProjectManagerDeps } from './manager/project/lifecycle.js'
343
351
  export type { TopicManagerDeps } from './manager/topic/lifecycle.js'
344
352
  export type { FileLockManagerConfig } from './bus/lock.js'
345
353
  export type { GitWorktreeDriverConfig } from './session/workspace/git-worktree.js'
354
+ export type {
355
+ BranchWorkspaceParams,
356
+ CreateWorkspaceParams,
357
+ WorkspaceBackendDriver,
358
+ WorkspaceInspection,
359
+ } from './session/workspace/driver.js'
360
+ export type {
361
+ HookedWorkspaceDriverOptions,
362
+ WorktreeHookContext,
363
+ WorktreeHookHost,
364
+ } from './session/workspace/hooked-driver.js'
346
365
  export type { CapacityDimension } from './session/handoff/capacity.js'
347
366
  export type { HandoffLockRejectedReason } from './session/handoff/version.js'
348
367
  export type { SessionSummaryMaterializerDeps } from './session/summary/materialize.js'
@@ -447,6 +447,11 @@ export interface ToolExecutorConfig {
447
447
  onJobCollected?: (id: string) => void
448
448
  /** The longest a monitor may live in this turn; see `QueryParams.monitorTimeoutCapMs`. */
449
449
  monitorTimeoutCapMs?: number
450
+ /** See `QueryParams.onWorkingDirectoryChange`. */
451
+ onWorkingDirectoryChange?: (change: {
452
+ readonly from: string
453
+ readonly to: string
454
+ }) => Promise<void> | void
450
455
  /**
451
456
  * Where a monitor the turn owns itself is recorded, so the turn stays open
452
457
  * for it. Passed only when the monitor's owner is the turn: a session-owned
@@ -2530,6 +2535,9 @@ export class ToolExecutor {
2530
2535
  sessionId: this.config.sessionId,
2531
2536
  turnId: this.config.turnId,
2532
2537
  workingDirectory: this.config.workingDirectory,
2538
+ ...(this.config.onWorkingDirectoryChange
2539
+ ? { workingDirectoryChanged: this.config.onWorkingDirectoryChange }
2540
+ : {}),
2533
2541
  ...(this.additionalDirectoriesNow()?.length
2534
2542
  ? { additionalDirectories: this.additionalDirectoriesNow() }
2535
2543
  : {}),
@@ -314,6 +314,15 @@ export interface QueryParams {
314
314
  * clamped to it without an error.
315
315
  */
316
316
  monitorTimeoutCapMs?: number
317
+ /**
318
+ * Told, once and awaited, when a shell command of this turn leaves the
319
+ * session's next shell command in a different folder (see
320
+ * `ToolContext.workingDirectoryChanged`). A host fires `cwd_changed` here.
321
+ */
322
+ onWorkingDirectoryChange?: (change: {
323
+ readonly from: string
324
+ readonly to: string
325
+ }) => Promise<void> | void
317
326
 
318
327
  /**
319
328
  * What else goes in this turn's prompt.
@@ -1634,6 +1643,9 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
1634
1643
  ...(params.monitorTimeoutCapMs !== undefined
1635
1644
  ? { monitorTimeoutCapMs: params.monitorTimeoutCapMs }
1636
1645
  : {}),
1646
+ ...(params.onWorkingDirectoryChange
1647
+ ? { onWorkingDirectoryChange: params.onWorkingDirectoryChange }
1648
+ : {}),
1637
1649
  // The `skill` tool's registry. Threaded from the turn rather than
1638
1650
  // held by the tool, because a tool that reached for a module-level
1639
1651
  // registry would answer about whatever the last turn configured.
@@ -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 }