@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
@@ -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,
@@ -1891,6 +1923,7 @@ export {
1891
1923
  SessionLeaseDocumentSchema,
1892
1924
  SessionRecordSchema,
1893
1925
  SessionStartedRecordSchema,
1926
+ SkillHooksAttachedRecordSchema,
1894
1927
  TurnCompletedRecordSchema,
1895
1928
  TurnFailedRecordSchema,
1896
1929
  TurnOutcomeRecordedRecordSchema,
@@ -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'
@@ -56,6 +56,7 @@ import type {
56
56
  PreparedToolExecution,
57
57
  RequestToolPause,
58
58
  ShellDialect,
59
+ SkillHooksRecordFact,
59
60
  SkillRegistryRef,
60
61
  ToolCallView,
61
62
  ToolContext,
@@ -447,6 +448,11 @@ export interface ToolExecutorConfig {
447
448
  onJobCollected?: (id: string) => void
448
449
  /** The longest a monitor may live in this turn; see `QueryParams.monitorTimeoutCapMs`. */
449
450
  monitorTimeoutCapMs?: number
451
+ /** See `QueryParams.onWorkingDirectoryChange`. */
452
+ onWorkingDirectoryChange?: (change: {
453
+ readonly from: string
454
+ readonly to: string
455
+ }) => Promise<void> | void
450
456
  /**
451
457
  * Where a monitor the turn owns itself is recorded, so the turn stays open
452
458
  * for it. Passed only when the monitor's owner is the turn: a session-owned
@@ -551,6 +557,8 @@ export interface ToolExecutorConfig {
551
557
  authorizationGate?: AuthorizationGate
552
558
  /** Durable refusal sink paired with {@link authorizationGate}. */
553
559
  recordAudit?: (input: AuditEventInput) => Promise<unknown>
560
+ /** Where a skill's hooks are kept in the conversation's record; see `ToolContext.recordSkillHooks`. */
561
+ recordSkillHooks?: (fact: SkillHooksRecordFact) => Promise<boolean>
554
562
  /**
555
563
  * Where the `skill` tool's `allowed-tools` pre-approvals are recorded for
556
564
  * this turn. The review phase reads the same set. Absent: a loaded skill
@@ -2530,6 +2538,9 @@ export class ToolExecutor {
2530
2538
  sessionId: this.config.sessionId,
2531
2539
  turnId: this.config.turnId,
2532
2540
  workingDirectory: this.config.workingDirectory,
2541
+ ...(this.config.onWorkingDirectoryChange
2542
+ ? { workingDirectoryChanged: this.config.onWorkingDirectoryChange }
2543
+ : {}),
2533
2544
  ...(this.additionalDirectoriesNow()?.length
2534
2545
  ? { additionalDirectories: this.additionalDirectoriesNow() }
2535
2546
  : {}),
@@ -2564,6 +2575,7 @@ export class ToolExecutor {
2564
2575
  ...(this.config.skillGrants
2565
2576
  ? { grantSkillTools: (grant) => this.grantSkillTools(grant) }
2566
2577
  : {}),
2578
+ ...(this.config.recordSkillHooks ? { recordSkillHooks: this.config.recordSkillHooks } : {}),
2567
2579
  maxToolOutputChars: this.config.maxToolOutputChars ?? DEFAULT_MAX_TOOL_OUTPUT_CHARS,
2568
2580
  // The turn's screens, defaulted HERE rather than on the registry: a
2569
2581
  // host builds the registry and hands it over, so a registry-side
@@ -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.
@@ -1679,6 +1691,22 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
1679
1691
  ...(params.repairToolCall ? { repairToolCall: params.repairToolCall } : {}),
1680
1692
  ...(verificationGate ? { authorizationGate: verificationGate } : {}),
1681
1693
  recordAudit: (input) => ctx.recorder.recordAudit(input),
1694
+ recordSkillHooks: async (fact) => {
1695
+ try {
1696
+ await ctx.recorder.appendRecord({
1697
+ type: 'skill_hooks_attached',
1698
+ turnId: ctx.turnId,
1699
+ ignorable: true,
1700
+ skill: fact.skill,
1701
+ directory: fact.directory,
1702
+ grantsWithheld: fact.grantsWithheld,
1703
+ ...(fact.toolCallId !== undefined ? { toolCallId: fact.toolCallId } : {}),
1704
+ })
1705
+ return true
1706
+ } catch {
1707
+ return false
1708
+ }
1709
+ },
1682
1710
  // The durable pause, reachable from any tool rather than from the
1683
1711
  // four kernel-owned points that used to own it. Built here from
1684
1712
  // the machinery the turn already holds; the recorder binds a few
@@ -8,7 +8,12 @@ import type { InvocationState } from '../../types/invocation/index.js'
8
8
  import type { PermissionMode } from '../../types/permission/index.js'
9
9
  import type { AuditEventInput } from '../../types/session/audit.js'
10
10
  import type { SessionRecord } from '../../types/session/records.js'
11
- import type { RequestToolPause, SkillRegistryRef, ToolDefinition } from '../../types/tool/index.js'
11
+ import type {
12
+ RequestToolPause,
13
+ SkillHooksRecordFact,
14
+ SkillRegistryRef,
15
+ ToolDefinition,
16
+ } from '../../types/tool/index.js'
12
17
  import type { RepairToolCall } from '../../types/tool/repair.js'
13
18
  import type { BackoffPolicy } from '../../utils/backoff.js'
14
19
  import type { Logger } from '../../utils/logger.js'
@@ -53,6 +58,11 @@ export interface ToolingBootstrapConfig {
53
58
  onJobCollected?: (id: string) => void
54
59
  /** See `ToolExecutorConfig.monitorTimeoutCapMs`. */
55
60
  monitorTimeoutCapMs?: number
61
+ /** See `QueryParams.onWorkingDirectoryChange`. */
62
+ onWorkingDirectoryChange?: (change: {
63
+ readonly from: string
64
+ readonly to: string
65
+ }) => Promise<void> | void
56
66
  /** See `ToolExecutorConfig.onMonitorStarted`. */
57
67
  onMonitorStarted?: (id: string) => void
58
68
  /** Where the `skill` tool reads from. */
@@ -76,6 +86,8 @@ export interface ToolingBootstrapConfig {
76
86
  authorizationGate?: AuthorizationGate
77
87
  /** Durable refusal recorder for nested authorization decisions. */
78
88
  recordAudit?: (input: AuditEventInput) => Promise<unknown>
89
+ /** Where a skill's hooks are kept in the conversation's record. */
90
+ recordSkillHooks?: (fact: SkillHooksRecordFact) => Promise<boolean>
79
91
  /** Builds the durable-pause seam for one tool call; see ToolContext.requestPause. */
80
92
  toolPause?: (toolUseId: string) => RequestToolPause
81
93
  /** The turn's skill pre-approvals; see the executor's own field. */
@@ -121,6 +133,9 @@ export class ToolingBootstrap {
121
133
  ...(config.monitorTimeoutCapMs !== undefined
122
134
  ? { monitorTimeoutCapMs: config.monitorTimeoutCapMs }
123
135
  : {}),
136
+ ...(config.onWorkingDirectoryChange
137
+ ? { onWorkingDirectoryChange: config.onWorkingDirectoryChange }
138
+ : {}),
124
139
  ...(config.onMonitorStarted ? { onMonitorStarted: config.onMonitorStarted } : {}),
125
140
  ...(config.skills ? { skills: config.skills } : {}),
126
141
  ...(config.web ? { web: config.web } : {}),
@@ -158,6 +173,9 @@ export class ToolingBootstrap {
158
173
  ? { authorizationGate: config.authorizationGate }
159
174
  : {}),
160
175
  ...(config.recordAudit !== undefined ? { recordAudit: config.recordAudit } : {}),
176
+ ...(config.recordSkillHooks !== undefined
177
+ ? { recordSkillHooks: config.recordSkillHooks }
178
+ : {}),
161
179
  ...(config.toolPause !== undefined ? { toolPause: config.toolPause } : {}),
162
180
  ...(config.skillGrants !== undefined ? { skillGrants: config.skillGrants } : {}),
163
181
  },
@@ -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'