@namzu/sdk 63.1.0 → 64.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +2 -1
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/agents/file-definitions.d.ts +10 -0
  6. package/dist/agents/file-definitions.d.ts.map +1 -1
  7. package/dist/agents/file-definitions.js +10 -2
  8. package/dist/agents/file-definitions.js.map +1 -1
  9. package/dist/compaction/hooks.d.ts +57 -0
  10. package/dist/compaction/hooks.d.ts.map +1 -0
  11. package/dist/compaction/hooks.js +44 -0
  12. package/dist/compaction/hooks.js.map +1 -0
  13. package/dist/compaction/manual.d.ts +9 -0
  14. package/dist/compaction/manual.d.ts.map +1 -1
  15. package/dist/compaction/manual.js +74 -5
  16. package/dist/compaction/manual.js.map +1 -1
  17. package/dist/compaction/model-summary.d.ts +6 -0
  18. package/dist/compaction/model-summary.d.ts.map +1 -1
  19. package/dist/compaction/model-summary.js +13 -3
  20. package/dist/compaction/model-summary.js.map +1 -1
  21. package/dist/compaction/verifier.d.ts +8 -2
  22. package/dist/compaction/verifier.d.ts.map +1 -1
  23. package/dist/compaction/verifier.js +23 -7
  24. package/dist/compaction/verifier.js.map +1 -1
  25. package/dist/plugin/file-change-hooks.d.ts +53 -0
  26. package/dist/plugin/file-change-hooks.d.ts.map +1 -0
  27. package/dist/plugin/file-change-hooks.js +111 -0
  28. package/dist/plugin/file-change-hooks.js.map +1 -0
  29. package/dist/plugin/file-change-watch.d.ts +111 -0
  30. package/dist/plugin/file-change-watch.d.ts.map +1 -0
  31. package/dist/plugin/file-change-watch.js +324 -0
  32. package/dist/plugin/file-change-watch.js.map +1 -0
  33. package/dist/plugin/hook-context.d.ts +16 -0
  34. package/dist/plugin/hook-context.d.ts.map +1 -1
  35. package/dist/plugin/hook-context.js +40 -0
  36. package/dist/plugin/hook-context.js.map +1 -1
  37. package/dist/plugin/index.d.ts +14 -4
  38. package/dist/plugin/index.d.ts.map +1 -1
  39. package/dist/plugin/index.js +10 -3
  40. package/dist/plugin/index.js.map +1 -1
  41. package/dist/plugin/lifecycle.d.ts +60 -1
  42. package/dist/plugin/lifecycle.d.ts.map +1 -1
  43. package/dist/plugin/lifecycle.js +118 -7
  44. package/dist/plugin/lifecycle.js.map +1 -1
  45. package/dist/plugin/loader.d.ts.map +1 -1
  46. package/dist/plugin/loader.js +24 -1
  47. package/dist/plugin/loader.js.map +1 -1
  48. package/dist/plugin/session-hook-env.d.ts +140 -0
  49. package/dist/plugin/session-hook-env.d.ts.map +1 -0
  50. package/dist/plugin/session-hook-env.js +458 -0
  51. package/dist/plugin/session-hook-env.js.map +1 -0
  52. package/dist/plugin/shell-hook-command.d.ts +25 -0
  53. package/dist/plugin/shell-hook-command.d.ts.map +1 -0
  54. package/dist/plugin/shell-hook-command.js +218 -0
  55. package/dist/plugin/shell-hook-command.js.map +1 -0
  56. package/dist/plugin/shell-hook-env.d.ts +107 -0
  57. package/dist/plugin/shell-hook-env.d.ts.map +1 -0
  58. package/dist/plugin/shell-hook-env.js +272 -0
  59. package/dist/plugin/shell-hook-env.js.map +1 -0
  60. package/dist/plugin/shell-hook-tool-names.d.ts +20 -0
  61. package/dist/plugin/shell-hook-tool-names.d.ts.map +1 -0
  62. package/dist/plugin/shell-hook-tool-names.js +43 -0
  63. package/dist/plugin/shell-hook-tool-names.js.map +1 -0
  64. package/dist/plugin/shell-hook.d.ts +167 -22
  65. package/dist/plugin/shell-hook.d.ts.map +1 -1
  66. package/dist/plugin/shell-hook.js +651 -106
  67. package/dist/plugin/shell-hook.js.map +1 -1
  68. package/dist/plugin/worktree-hook-answer.d.ts +26 -0
  69. package/dist/plugin/worktree-hook-answer.d.ts.map +1 -0
  70. package/dist/plugin/worktree-hook-answer.js +132 -0
  71. package/dist/plugin/worktree-hook-answer.js.map +1 -0
  72. package/dist/public-runtime.d.ts +5 -3
  73. package/dist/public-runtime.d.ts.map +1 -1
  74. package/dist/public-runtime.js +4 -3
  75. package/dist/public-runtime.js.map +1 -1
  76. package/dist/public-types.d.ts +9 -2
  77. package/dist/public-types.d.ts.map +1 -1
  78. package/dist/runtime/query/compact-session.d.ts +7 -1
  79. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  80. package/dist/runtime/query/compact-session.js +8 -3
  81. package/dist/runtime/query/compact-session.js.map +1 -1
  82. package/dist/runtime/query/executor/tool-call-admission.d.ts +1 -1
  83. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  84. package/dist/runtime/query/executor/tool-call-admission.js +4 -3
  85. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  86. package/dist/runtime/query/executor.d.ts +5 -0
  87. package/dist/runtime/query/executor.d.ts.map +1 -1
  88. package/dist/runtime/query/executor.js +8 -3
  89. package/dist/runtime/query/executor.js.map +1 -1
  90. package/dist/runtime/query/finalize-turn.d.ts.map +1 -1
  91. package/dist/runtime/query/finalize-turn.js +9 -2
  92. package/dist/runtime/query/finalize-turn.js.map +1 -1
  93. package/dist/runtime/query/index.d.ts +9 -0
  94. package/dist/runtime/query/index.d.ts.map +1 -1
  95. package/dist/runtime/query/index.js +3 -0
  96. package/dist/runtime/query/index.js.map +1 -1
  97. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  98. package/dist/runtime/query/iteration/index.js +2 -1
  99. package/dist/runtime/query/iteration/index.js.map +1 -1
  100. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  101. package/dist/runtime/query/iteration/phases/compaction.js +24 -12
  102. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  103. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  104. package/dist/runtime/query/iteration/phases/tool-review.js +2 -0
  105. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  106. package/dist/runtime/query/plugin-hooks.d.ts +13 -0
  107. package/dist/runtime/query/plugin-hooks.d.ts.map +1 -1
  108. package/dist/runtime/query/plugin-hooks.js +29 -2
  109. package/dist/runtime/query/plugin-hooks.js.map +1 -1
  110. package/dist/runtime/query/tooling.d.ts +5 -0
  111. package/dist/runtime/query/tooling.d.ts.map +1 -1
  112. package/dist/runtime/query/tooling.js +3 -0
  113. package/dist/runtime/query/tooling.js.map +1 -1
  114. package/dist/session/workspace/hooked-driver.d.ts +72 -0
  115. package/dist/session/workspace/hooked-driver.d.ts.map +1 -0
  116. package/dist/session/workspace/hooked-driver.js +204 -0
  117. package/dist/session/workspace/hooked-driver.js.map +1 -0
  118. package/dist/session/workspace/index.d.ts +2 -0
  119. package/dist/session/workspace/index.d.ts.map +1 -1
  120. package/dist/session/workspace/index.js +1 -0
  121. package/dist/session/workspace/index.js.map +1 -1
  122. package/dist/skills/index.d.ts +1 -1
  123. package/dist/skills/index.d.ts.map +1 -1
  124. package/dist/skills/index.js +1 -1
  125. package/dist/skills/index.js.map +1 -1
  126. package/dist/skills/loader.d.ts +22 -0
  127. package/dist/skills/loader.d.ts.map +1 -1
  128. package/dist/skills/loader.js +41 -0
  129. package/dist/skills/loader.js.map +1 -1
  130. package/dist/tools/builtins/bash-cwd.d.ts +6 -1
  131. package/dist/tools/builtins/bash-cwd.d.ts.map +1 -1
  132. package/dist/tools/builtins/bash-cwd.js +27 -2
  133. package/dist/tools/builtins/bash-cwd.js.map +1 -1
  134. package/dist/tools/builtins/bash.js +1 -1
  135. package/dist/tools/builtins/bash.js.map +1 -1
  136. package/dist/tools/builtins/skill.d.ts.map +1 -1
  137. package/dist/tools/builtins/skill.js +93 -16
  138. package/dist/tools/builtins/skill.js.map +1 -1
  139. package/dist/types/agent/query.d.ts +8 -0
  140. package/dist/types/agent/query.d.ts.map +1 -1
  141. package/dist/types/plugin/index.d.ts +130 -13
  142. package/dist/types/plugin/index.d.ts.map +1 -1
  143. package/dist/types/plugin/index.js +5 -0
  144. package/dist/types/plugin/index.js.map +1 -1
  145. package/dist/types/skills/index.d.ts +8 -0
  146. package/dist/types/skills/index.d.ts.map +1 -1
  147. package/dist/types/skills/index.js.map +1 -1
  148. package/dist/types/tool/index.d.ts +68 -0
  149. package/dist/types/tool/index.d.ts.map +1 -1
  150. package/dist/types/tool/index.js.map +1 -1
  151. package/dist/types/workspace/ref.d.ts +6 -0
  152. package/dist/types/workspace/ref.d.ts.map +1 -1
  153. package/dist/utils/frontmatter.d.ts +16 -0
  154. package/dist/utils/frontmatter.d.ts.map +1 -1
  155. package/dist/utils/frontmatter.js +31 -1
  156. package/dist/utils/frontmatter.js.map +1 -1
  157. package/package.json +1 -1
  158. package/src/agents/QueryAgent.ts +2 -1
  159. package/src/agents/file-definitions.ts +17 -2
  160. package/src/compaction/hooks.ts +104 -0
  161. package/src/compaction/manual.ts +117 -4
  162. package/src/compaction/model-summary.ts +19 -3
  163. package/src/compaction/verifier.ts +33 -3
  164. package/src/plugin/file-change-hooks.ts +131 -0
  165. package/src/plugin/file-change-watch.ts +367 -0
  166. package/src/plugin/hook-context.ts +46 -0
  167. package/src/plugin/index.ts +53 -1
  168. package/src/plugin/lifecycle.ts +162 -8
  169. package/src/plugin/loader.ts +22 -1
  170. package/src/plugin/session-hook-env.ts +475 -0
  171. package/src/plugin/shell-hook-command.ts +215 -0
  172. package/src/plugin/shell-hook-env.ts +335 -0
  173. package/src/plugin/shell-hook-tool-names.ts +46 -0
  174. package/src/plugin/shell-hook.ts +818 -100
  175. package/src/plugin/worktree-hook-answer.ts +142 -0
  176. package/src/public-runtime.ts +44 -0
  177. package/src/public-types.ts +22 -1
  178. package/src/runtime/query/compact-session.ts +16 -4
  179. package/src/runtime/query/executor/tool-call-admission.ts +10 -2
  180. package/src/runtime/query/executor.ts +13 -2
  181. package/src/runtime/query/finalize-turn.ts +9 -2
  182. package/src/runtime/query/index.ts +12 -0
  183. package/src/runtime/query/iteration/index.ts +2 -1
  184. package/src/runtime/query/iteration/phases/compaction.ts +31 -12
  185. package/src/runtime/query/iteration/phases/tool-review.ts +2 -0
  186. package/src/runtime/query/plugin-hooks.ts +32 -2
  187. package/src/runtime/query/tooling.ts +8 -0
  188. package/src/session/workspace/hooked-driver.ts +272 -0
  189. package/src/session/workspace/index.ts +7 -0
  190. package/src/skills/index.ts +3 -0
  191. package/src/skills/loader.ts +47 -0
  192. package/src/tools/builtins/bash-cwd.ts +25 -1
  193. package/src/tools/builtins/bash.ts +1 -1
  194. package/src/tools/builtins/skill.ts +115 -26
  195. package/src/types/agent/query.ts +9 -0
  196. package/src/types/plugin/index.ts +150 -23
  197. package/src/types/skills/index.ts +9 -0
  198. package/src/types/tool/index.ts +74 -0
  199. package/src/types/workspace/ref.ts +6 -0
  200. package/src/utils/frontmatter.ts +52 -1
@@ -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,
@@ -697,8 +700,13 @@ export {
697
700
 
698
701
  export {
699
702
  attachShellHooks,
703
+ boundCompactionSummary,
700
704
  boundHookContext,
701
705
  boundHookReplacement,
706
+ boundLastAssistantMessage,
707
+ compactionHookInstructions,
708
+ MAX_COMPACTION_SUMMARY_HOOK_CHARS,
709
+ MAX_LAST_MESSAGE_HOOK_CHARS,
702
710
  createShellHook,
703
711
  DEFAULT_SHELL_HOOK_TIMEOUT_MS,
704
712
  definePlugin,
@@ -712,14 +720,45 @@ export {
712
720
  loadPluginManifest,
713
721
  parsePluginManifestText,
714
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,
715
733
  PluginLifecycleManager,
716
734
  PluginResolver,
717
735
  runShellHook,
718
736
  SHELL_HOOK_EVENTS,
737
+ SHELL_HOOK_PASCAL_EVENT_NAMES,
738
+ SHELL_HOOK_WRITTEN_TOOL_NAMES,
719
739
  SHELL_HOOKS_PLUGIN_ID,
740
+ shellHookToolName,
720
741
  shellHookIfMatches,
742
+ shellHookIfProblem,
743
+ shellHookMatcherProblem,
721
744
  shellHookMatches,
722
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,
723
762
  } from './plugin/index.js'
724
763
  export type { DefinedPlugin, DefinePluginOptions } from './plugin/define.js'
725
764
 
@@ -1180,6 +1219,9 @@ export type { VaultInstrumentationOptions } from './vault/instrumentation.js'
1180
1219
 
1181
1220
  export {
1182
1221
  GitWorktreeDriver,
1222
+ HookedWorkspaceDriver,
1223
+ WorktreeHookError,
1224
+ worktreeHookHost,
1183
1225
  parseWorktreeList,
1184
1226
  SharedSessionWorkspace,
1185
1227
  WorkspaceBackendRegistry,
@@ -1343,6 +1385,7 @@ export { assertTaskStatus, isTerminalTaskStatus } from './types/task/index.js'
1343
1385
  // offer "compact this conversation", could not shrink an idle session
1344
1386
  // between turns, and could not collapse a span it had chosen.
1345
1387
  export { compactNow, compactRegion } from './compaction/manual.js'
1388
+ export { CompactionRefusedError } from './compaction/hooks.js'
1346
1389
  // A host persisting manual compaction has to recognise the system message on
1347
1390
  // resume. Export the identity predicate rather than making every host copy the
1348
1391
  // marker string and eventually disagree with the writer.
@@ -1380,6 +1423,7 @@ export { isWorkingMemoryMessage } from './runtime/query/iteration/phases/working
1380
1423
  // `any` — and the first host to try (`@namzu/cli`'s `/compact`) did exactly
1381
1424
  // that before this line existed.
1382
1425
  export type { CompactNowInput, CompactionResult } from './compaction/manual.js'
1426
+ export type { CompactionHookHost, ManualCompactionHooks } from './compaction/hooks.js'
1383
1427
  export type {
1384
1428
  CompactionSummaryRoute,
1385
1429
  CompactionSummaryRouter,
@@ -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,
@@ -242,12 +242,22 @@ export type {
242
242
  ShellHookHandler,
243
243
  ShellHookJudge,
244
244
  ShellHookOnFailure,
245
+ ShellHookCall,
245
246
  ShellHookInput,
246
247
  ShellHookOptions,
247
248
  ShellHookPathFilter,
248
249
  ShellHookOutcome,
249
250
  ShellHooksConfig,
250
251
  } from './plugin/shell-hook.js'
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'
251
261
 
252
262
  export type {
253
263
  PlanApprovalHandler,
@@ -341,6 +351,17 @@ export type { ProjectManagerDeps } from './manager/project/lifecycle.js'
341
351
  export type { TopicManagerDeps } from './manager/topic/lifecycle.js'
342
352
  export type { FileLockManagerConfig } from './bus/lock.js'
343
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'
344
365
  export type { CapacityDimension } from './session/handoff/capacity.js'
345
366
  export type { HandoffLockRejectedReason } from './session/handoff/version.js'
346
367
  export type { SessionSummaryMaterializerDeps } from './session/summary/materialize.js'
@@ -1,3 +1,4 @@
1
+ import type { ManualCompactionHooks } from '../../compaction/hooks.js'
1
2
  import {
2
3
  type CompactNowInput,
3
4
  type CompactionResult,
@@ -13,8 +14,14 @@ import { generateMessageId } from '../../utils/id.js'
13
14
  import { type SessionLocatorOptions, locateSessionLog, withSessionLease } from './abandon-turn.js'
14
15
 
15
16
  /** A compaction a host asks for between turns. */
16
- export interface CompactSessionParams extends Omit<CompactNowInput, 'messages' | 'onShed'> {
17
+ export interface CompactSessionParams
18
+ extends Omit<CompactNowInput, 'messages' | 'onShed' | 'hooks'> {
17
19
  readonly sessionId: SessionId
20
+ /**
21
+ * Fire `pre_compact` and `post_compact` around the pass. The session and
22
+ * the trigger are this call's own. See {@link CompactNowInput.hooks}.
23
+ */
24
+ readonly hooks?: Omit<ManualCompactionHooks, 'sessionId' | 'trigger'>
18
25
  /**
19
26
  * Who asked. `'manual'` (the default) is a person's request; `'idle'` is a
20
27
  * host compacting a conversation nobody is using before its prompt cache
@@ -37,7 +44,7 @@ export interface CompactSessionParams extends Omit<CompactNowInput, 'messages' |
37
44
  export async function compactSession(
38
45
  params: CompactSessionParams,
39
46
  ): Promise<CompactionResult | null> {
40
- const { sessionId, locator = {}, trigger = 'manual', ...input } = params
47
+ const { sessionId, locator = {}, trigger = 'manual', hooks, ...input } = params
41
48
  const log = await locateSessionLog(sessionId, locator)
42
49
  return withSessionLease(log, locator.lease, async (lease) => {
43
50
  const active = await log.activeTurn({ lease })
@@ -47,7 +54,11 @@ export async function compactSession(
47
54
  const history = await readFoldedHistory(log)
48
55
  const ids = new Map<Message, MessageId>()
49
56
  for (const entry of history) if (entry.messageId) ids.set(entry.message, entry.messageId)
50
- const result = await compactNow({ ...input, messages: history.map((entry) => entry.message) })
57
+ const result = await compactNow({
58
+ ...input,
59
+ messages: history.map((entry) => entry.message),
60
+ ...(hooks ? { hooks: { ...hooks, sessionId, trigger } } : {}),
61
+ })
51
62
  if (!result) return null
52
63
  const head = await log.head()
53
64
  if (!head) {
@@ -105,7 +116,7 @@ export interface CompactSessionRangeParams extends CompactSessionParams {
105
116
  export async function compactSessionRange(
106
117
  params: CompactSessionRangeParams,
107
118
  ): Promise<CompactionResult | null> {
108
- const { sessionId, locator = {}, from, until, ...input } = params
119
+ const { sessionId, locator = {}, from, until, hooks, ...input } = params
109
120
  const log = await locateSessionLog(sessionId, locator)
110
121
  return withSessionLease(log, locator.lease, async (lease) => {
111
122
  const active = await log.activeTurn({ lease })
@@ -134,6 +145,7 @@ export async function compactSessionRange(
134
145
  messages: history.map((entry) => entry.message),
135
146
  start,
136
147
  end,
148
+ ...(hooks ? { hooks: { ...hooks, sessionId, trigger: 'manual' as const } } : {}),
137
149
  })
138
150
  if (!result) return null
139
151
  const head = await log.head()
@@ -78,6 +78,7 @@ export async function runPreToolHook(
78
78
  toolName: string,
79
79
  input: unknown,
80
80
  signal: AbortSignal = host.config.abortSignal,
81
+ toolCallId?: string,
81
82
  ): Promise<PreToolHookOutcome> {
82
83
  signal.throwIfAborted()
83
84
  if (!host.config.pluginManager) return { kind: 'continue', input, modified: false }
@@ -88,6 +89,7 @@ export async function runPreToolHook(
88
89
  sessionId: host.config.sessionId,
89
90
  turnId: host.config.turnId,
90
91
  toolName,
92
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
91
93
  toolInput: input,
92
94
  signal,
93
95
  },
@@ -155,7 +157,7 @@ export async function prepareDirectCall(
155
157
  : {}),
156
158
  }
157
159
  }
158
- const preOutcome = await runPreToolHook(host, toolName, resolved.input)
160
+ const preOutcome = await runPreToolHook(host, toolName, resolved.input, undefined, toolCall.id)
159
161
  if (preOutcome.kind === 'skip' || preOutcome.kind === 'error') {
160
162
  return {
161
163
  kind: 'synthetic',
@@ -297,7 +299,13 @@ export async function prepareDirectCall(
297
299
  }
298
300
  }
299
301
 
300
- const preOutcome = await runPreToolHook(host, toolName, preparation.prepared.input)
302
+ const preOutcome = await runPreToolHook(
303
+ host,
304
+ toolName,
305
+ preparation.prepared.input,
306
+ undefined,
307
+ toolCall.id,
308
+ )
301
309
  if (preOutcome.kind === 'skip' || preOutcome.kind === 'error') {
302
310
  return {
303
311
  kind: 'synthetic',
@@ -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
  : {}),
@@ -2790,7 +2798,7 @@ export class ToolExecutor {
2790
2798
  // block had it discarded here — before the wire mapper that was
2791
2799
  // built to carry it ever saw it.
2792
2800
  let result: ToolResult = await this.runOnce(toolName, input, toolContext, prepared)
2793
- let post = await this.runPostToolHook(toolName, input, result)
2801
+ let post = await this.runPostToolHook(toolName, input, result, toolCall.id)
2794
2802
 
2795
2803
  // In-loop retry. A transient failure used to cost a full model round
2796
2804
  // trip: the error went back as a `tool_result`, the model read it and
@@ -2873,7 +2881,7 @@ export class ToolExecutor {
2873
2881
  break
2874
2882
  }
2875
2883
  result = await this.runOnce(toolName, input, toolContext, prepared)
2876
- post = await this.runPostToolHook(toolName, input, result)
2884
+ post = await this.runPostToolHook(toolName, input, result, toolCall.id)
2877
2885
  }
2878
2886
  const durationMs = Date.now() - startMs
2879
2887
 
@@ -3515,6 +3523,7 @@ export class ToolExecutor {
3515
3523
  toolName: string,
3516
3524
  input: unknown,
3517
3525
  toolResult: ToolResult,
3526
+ toolCallId?: string,
3518
3527
  ): Promise<{
3519
3528
  override: PostToolOverride | null
3520
3529
  retry: boolean
@@ -3529,6 +3538,7 @@ export class ToolExecutor {
3529
3538
  sessionId: this.config.sessionId,
3530
3539
  turnId: this.config.turnId,
3531
3540
  toolName,
3541
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
3532
3542
  toolInput: input,
3533
3543
  toolResult,
3534
3544
  signal: this.config.abortSignal,
@@ -3547,6 +3557,7 @@ export class ToolExecutor {
3547
3557
  sessionId: this.config.sessionId,
3548
3558
  turnId: this.config.turnId,
3549
3559
  toolName,
3560
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
3550
3561
  toolInput: input,
3551
3562
  toolResult,
3552
3563
  signal: this.config.abortSignal,
@@ -8,7 +8,7 @@ import type { TurnContext } from './context.js'
8
8
  import type { EventTranslator } from './events.js'
9
9
  import { runOutputGuardrails } from './guardrails.js'
10
10
  import type { QueryParams } from './index.js'
11
- import { applyLifecycleHookResults } from './plugin-hooks.js'
11
+ import { applyLifecycleHookResults, lastAssistantMessageField } from './plugin-hooks.js'
12
12
  import type { ResultAssembler } from './result.js'
13
13
 
14
14
  /**
@@ -86,7 +86,12 @@ export async function* finalizeTurn(
86
86
  if (params.pluginManager && finalization.turnEndHooksFired?.() !== true) {
87
87
  const hookResults = await params.pluginManager.executeHooks(
88
88
  'turn_end',
89
- { sessionId: ctx.sessionId, turnId: ctx.turnId, signal: ctx.abortController.signal },
89
+ {
90
+ sessionId: ctx.sessionId,
91
+ turnId: ctx.turnId,
92
+ ...lastAssistantMessageField(ctx.recorder.messages),
93
+ signal: ctx.abortController.signal,
94
+ },
90
95
  eventTranslator.emitEvent,
91
96
  )
92
97
  applyLifecycleHookResults('turn_end', hookResults)
@@ -100,8 +105,10 @@ export async function* finalizeTurn(
100
105
  {
101
106
  sessionId: ctx.sessionId,
102
107
  turnId: ctx.turnId,
108
+ ...lastAssistantMessageField(ctx.recorder.messages),
103
109
  parentSessionId: params.parentSessionId,
104
110
  ...(params.parentTurnId !== undefined ? { parentTurnId: params.parentTurnId } : {}),
111
+ agentType: params.agentType ?? params.agentName,
105
112
  signal: ctx.abortController.signal,
106
113
  },
107
114
  eventTranslator.emitEvent,
@@ -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.
@@ -70,7 +70,7 @@ import { SandboxAcquisitionStopped } from '../deferred-sandbox.js'
70
70
  import { deliverDurableInbound } from '../durable-inbound.js'
71
71
  import type { ToolCallOutcome } from '../executor.js'
72
72
  import { projectObservationContext } from '../observation-context.js'
73
- import { applyLifecycleHookResults } from '../plugin-hooks.js'
73
+ import { applyLifecycleHookResults, lastAssistantMessageField } from '../plugin-hooks.js'
74
74
  import {
75
75
  type RequestContextSnapshot,
76
76
  diffRequestContext,
@@ -419,6 +419,7 @@ export class IterationOrchestrator {
419
419
  sessionId: recorder.sessionId,
420
420
  turnId: recorder.turnId,
421
421
  ...extra,
422
+ ...lastAssistantMessageField(recorder.messages),
422
423
  ...(this.stopHookActive ? { stopHookActive: true } : {}),
423
424
  signal: this.ctx.abortController.signal,
424
425
  },
@@ -3,6 +3,7 @@ import {
3
3
  resolveTriggerThreshold,
4
4
  } from '../../../../compaction/context-window.js'
5
5
  import { findDanglingMessages } from '../../../../compaction/dangling.js'
6
+ import { askPreCompact, postCompactSummary } from '../../../../compaction/hooks.js'
6
7
  import {
7
8
  LOADED_SKILLS_ENTRY_KEY,
8
9
  type RenderedSkills,
@@ -781,6 +782,10 @@ async function recordShed(
781
782
  interface CompactionPass {
782
783
  attempted: boolean
783
784
  reason: 'threshold' | 'overflow'
785
+ /** What the `pre_compact` hooks said the summary should keep. */
786
+ hookInstructions?: string
787
+ /** The summary the pass installed, for `post_compact`. */
788
+ summary?: string
784
789
  tokensBefore: number
785
790
  contextWindowTokens: number
786
791
  }
@@ -807,9 +812,11 @@ export async function runCompactionCheck(
807
812
  iteration: ctx.recorder.currentIteration,
808
813
  compaction: {
809
814
  reason: pass.reason,
815
+ trigger: 'auto',
810
816
  tokensBefore: pass.tokensBefore,
811
817
  tokensAfter: estimateTokens(ctx),
812
818
  contextWindowTokens: pass.contextWindowTokens,
819
+ ...postCompactSummary(pass.summary),
813
820
  },
814
821
  signal: ctx.abortController.signal,
815
822
  },
@@ -903,24 +910,29 @@ async function runCompactionCheckInner(
903
910
  pass.tokensBefore = estimatedTokens
904
911
  pass.contextWindowTokens = budget
905
912
  if (ctx.pluginManager) {
906
- const results = await ctx.pluginManager.executeHooks(
907
- 'pre_compact',
913
+ const answer = await askPreCompact(
914
+ ctx.pluginManager,
908
915
  {
909
916
  sessionId: ctx.recorder.sessionId,
910
917
  turnId: ctx.recorder.turnId,
911
918
  iteration: ctx.recorder.currentIteration,
912
- compaction: {
913
- reason: pass.reason,
914
- tokensBefore: estimatedTokens,
915
- contextWindowTokens: budget,
916
- },
917
919
  signal: ctx.abortController.signal,
920
+ emitEvent: ctx.emitEvent,
921
+ },
922
+ {
923
+ reason: pass.reason,
924
+ trigger: 'auto',
925
+ instructions: null,
926
+ tokensBefore: estimatedTokens,
927
+ contextWindowTokens: budget,
918
928
  },
919
- ctx.emitEvent,
920
929
  )
921
- applyLifecycleHookResults('pre_compact', results)
922
- const refusal = results.find((result) => result.action === 'skip')
923
- if (refusal?.action === 'skip') {
930
+ // What the hooks said the summary should keep is heard even when a
931
+ // forced pass overrides a refusal. A reducer or the extracted state
932
+ // alone has no place for it (see `docs/sdk/hooks.md`).
933
+ if (answer.instructions !== undefined) pass.hookInstructions = answer.instructions
934
+ const refusal = answer.refusal !== undefined ? { reason: answer.refusal } : undefined
935
+ if (refusal) {
924
936
  // A threshold pass is the context's own housekeeping and a hook may
925
937
  // postpone it. A forced pass runs because the provider rejected the
926
938
  // prompt: a context it will reject is not something a hook may insist
@@ -1130,6 +1142,7 @@ async function runCompactionCheckInner(
1130
1142
  olderMessages,
1131
1143
  previousSummaries: replaceableSummaries(systemMessages),
1132
1144
  config,
1145
+ ...(pass.hookInstructions !== undefined ? { hookInstructions: pass.hookInstructions } : {}),
1133
1146
  resolveRoute: async (signal) => {
1134
1147
  const route = await ctx.compactionSummaryRoute?.(signal)
1135
1148
  if (route) {
@@ -1162,7 +1175,10 @@ async function runCompactionCheckInner(
1162
1175
 
1163
1176
  if (modelWritten !== undefined) {
1164
1177
  compactedContent = modelWritten
1165
- } else if (config.llmVerification && manager.slotCount() < config.richStateThreshold) {
1178
+ } else if (
1179
+ pass.hookInstructions !== undefined ||
1180
+ (config.llmVerification && manager.slotCount() < config.richStateThreshold)
1181
+ ) {
1166
1182
  // Named once and used twice on purpose. The model the summariser is
1167
1183
  // asked for is also the model its tokens are priced at, and computing
1168
1184
  // the two separately is how they drift — a router that sends compaction
@@ -1188,6 +1204,8 @@ async function runCompactionCheckInner(
1188
1204
  // was added, and nothing ever consulted it.
1189
1205
  compactionModel,
1190
1206
  ctx.abortController.signal,
1207
+ undefined,
1208
+ pass.hookInstructions,
1191
1209
  )
1192
1210
  } catch (error) {
1193
1211
  // The model step only ADDS to the extracted state, so a failed one (a
@@ -1308,6 +1326,7 @@ async function runCompactionCheckInner(
1308
1326
  await recordShed(ctx, [...live], newMessages, options?.force ? 'overflow' : 'threshold')
1309
1327
 
1310
1328
  installMessages(live, newMessages)
1329
+ pass.summary = compactedContent
1311
1330
 
1312
1331
  const newEstimate = estimateTokens(ctx)
1313
1332
 
@@ -318,6 +318,7 @@ export async function* runToolReview(
318
318
  sessionId: ctx.recorder.sessionId,
319
319
  turnId: ctx.recorder.turnId,
320
320
  toolName: summary.name,
321
+ toolCallId: summary.id,
321
322
  toolInput: summary.input,
322
323
  reason,
323
324
  signal: ctx.abortController.signal,
@@ -854,6 +855,7 @@ export async function* runToolReview(
854
855
  sessionId: ctx.recorder.sessionId,
855
856
  turnId: ctx.recorder.turnId,
856
857
  toolName: tc.name,
858
+ toolCallId: tc.id,
857
859
  toolInput: tc.input,
858
860
  signal: ctx.abortController.signal,
859
861
  },