@namzu/sdk 71.0.1 → 72.0.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 (268) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +1 -0
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/authorization/readonly-commands.d.ts +9 -1
  6. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  7. package/dist/authorization/readonly-commands.js +70 -4
  8. package/dist/authorization/readonly-commands.js.map +1 -1
  9. package/dist/authorization/shell-paths.d.ts.map +1 -1
  10. package/dist/authorization/shell-paths.js +68 -16
  11. package/dist/authorization/shell-paths.js.map +1 -1
  12. package/dist/compaction/index.d.ts +1 -1
  13. package/dist/compaction/index.d.ts.map +1 -1
  14. package/dist/compaction/index.js +1 -1
  15. package/dist/compaction/index.js.map +1 -1
  16. package/dist/compaction/manual.d.ts +8 -0
  17. package/dist/compaction/manual.d.ts.map +1 -1
  18. package/dist/compaction/manual.js +18 -14
  19. package/dist/compaction/manual.js.map +1 -1
  20. package/dist/compaction/model-summary.d.ts +24 -6
  21. package/dist/compaction/model-summary.d.ts.map +1 -1
  22. package/dist/compaction/model-summary.js +152 -28
  23. package/dist/compaction/model-summary.js.map +1 -1
  24. package/dist/compaction/restore.d.ts +23 -0
  25. package/dist/compaction/restore.d.ts.map +1 -1
  26. package/dist/compaction/restore.js +59 -1
  27. package/dist/compaction/restore.js.map +1 -1
  28. package/dist/compaction/summary.d.ts +37 -2
  29. package/dist/compaction/summary.d.ts.map +1 -1
  30. package/dist/compaction/summary.js +46 -6
  31. package/dist/compaction/summary.js.map +1 -1
  32. package/dist/config/registry.d.ts +2 -0
  33. package/dist/config/registry.d.ts.map +1 -1
  34. package/dist/config/registry.js +76 -5
  35. package/dist/config/registry.js.map +1 -1
  36. package/dist/config/runtime.js +3 -3
  37. package/dist/config/runtime.js.map +1 -1
  38. package/dist/connector/index.d.ts +2 -2
  39. package/dist/connector/index.d.ts.map +1 -1
  40. package/dist/connector/index.js +1 -1
  41. package/dist/connector/index.js.map +1 -1
  42. package/dist/connector/mcp/adapter.d.ts +8 -0
  43. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  44. package/dist/connector/mcp/adapter.js +131 -1
  45. package/dist/connector/mcp/adapter.js.map +1 -1
  46. package/dist/connector/mcp/client.d.ts +26 -6
  47. package/dist/connector/mcp/client.d.ts.map +1 -1
  48. package/dist/connector/mcp/client.js +49 -7
  49. package/dist/connector/mcp/client.js.map +1 -1
  50. package/dist/connector/mcp/index.d.ts +2 -0
  51. package/dist/connector/mcp/index.d.ts.map +1 -1
  52. package/dist/connector/mcp/index.js +1 -0
  53. package/dist/connector/mcp/index.js.map +1 -1
  54. package/dist/connector/mcp/sandbox-stdio.d.ts +67 -0
  55. package/dist/connector/mcp/sandbox-stdio.d.ts.map +1 -0
  56. package/dist/connector/mcp/sandbox-stdio.js +178 -0
  57. package/dist/connector/mcp/sandbox-stdio.js.map +1 -0
  58. package/dist/connector/mcp/stdio-program.d.ts +34 -0
  59. package/dist/connector/mcp/stdio-program.d.ts.map +1 -0
  60. package/dist/connector/mcp/stdio-program.js +47 -0
  61. package/dist/connector/mcp/stdio-program.js.map +1 -0
  62. package/dist/connector/mcp/stdio.d.ts +12 -0
  63. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  64. package/dist/connector/mcp/stdio.js +54 -7
  65. package/dist/connector/mcp/stdio.js.map +1 -1
  66. package/dist/connector/web/guarded-fetch.d.ts +51 -2
  67. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  68. package/dist/connector/web/guarded-fetch.js +140 -19
  69. package/dist/connector/web/guarded-fetch.js.map +1 -1
  70. package/dist/connector/web/index.d.ts +2 -2
  71. package/dist/connector/web/index.d.ts.map +1 -1
  72. package/dist/connector/web/index.js +1 -1
  73. package/dist/connector/web/index.js.map +1 -1
  74. package/dist/constants/mcp/index.d.ts +29 -0
  75. package/dist/constants/mcp/index.d.ts.map +1 -1
  76. package/dist/constants/mcp/index.js +29 -0
  77. package/dist/constants/mcp/index.js.map +1 -1
  78. package/dist/manager/agent/lifecycle.d.ts +18 -1
  79. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  80. package/dist/manager/agent/lifecycle.js +53 -8
  81. package/dist/manager/agent/lifecycle.js.map +1 -1
  82. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  83. package/dist/plugin/hook-module/capabilities.js +24 -13
  84. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  85. package/dist/plugin/hook-module/host.d.ts +31 -0
  86. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  87. package/dist/plugin/hook-module/host.js +56 -13
  88. package/dist/plugin/hook-module/host.js.map +1 -1
  89. package/dist/plugin/hook-module/index.d.ts +3 -2
  90. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  91. package/dist/plugin/hook-module/index.js +2 -1
  92. package/dist/plugin/hook-module/index.js.map +1 -1
  93. package/dist/plugin/index.d.ts +2 -1
  94. package/dist/plugin/index.d.ts.map +1 -1
  95. package/dist/plugin/index.js +1 -0
  96. package/dist/plugin/index.js.map +1 -1
  97. package/dist/plugin/shell-hook-execute.d.ts +55 -0
  98. package/dist/plugin/shell-hook-execute.d.ts.map +1 -0
  99. package/dist/plugin/shell-hook-execute.js +73 -0
  100. package/dist/plugin/shell-hook-execute.js.map +1 -0
  101. package/dist/plugin/shell-hook-restrict.d.ts +31 -0
  102. package/dist/plugin/shell-hook-restrict.d.ts.map +1 -0
  103. package/dist/plugin/shell-hook-restrict.js +69 -0
  104. package/dist/plugin/shell-hook-restrict.js.map +1 -0
  105. package/dist/plugin/shell-hook.d.ts +73 -4
  106. package/dist/plugin/shell-hook.d.ts.map +1 -1
  107. package/dist/plugin/shell-hook.js +118 -17
  108. package/dist/plugin/shell-hook.js.map +1 -1
  109. package/dist/public-runtime.d.ts +9 -7
  110. package/dist/public-runtime.d.ts.map +1 -1
  111. package/dist/public-runtime.js +6 -5
  112. package/dist/public-runtime.js.map +1 -1
  113. package/dist/public-types.d.ts +4 -2
  114. package/dist/public-types.d.ts.map +1 -1
  115. package/dist/runtime/jobs/websocket-source.d.ts +2 -22
  116. package/dist/runtime/jobs/websocket-source.d.ts.map +1 -1
  117. package/dist/runtime/jobs/websocket-source.js +2 -33
  118. package/dist/runtime/jobs/websocket-source.js.map +1 -1
  119. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  120. package/dist/runtime/query/compact-session.js +5 -0
  121. package/dist/runtime/query/compact-session.js.map +1 -1
  122. package/dist/runtime/query/events.d.ts +7 -0
  123. package/dist/runtime/query/events.d.ts.map +1 -1
  124. package/dist/runtime/query/events.js +29 -11
  125. package/dist/runtime/query/events.js.map +1 -1
  126. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  127. package/dist/runtime/query/executor/tool-call-admission.js +51 -10
  128. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  129. package/dist/runtime/query/index.d.ts +6 -0
  130. package/dist/runtime/query/index.d.ts.map +1 -1
  131. package/dist/runtime/query/index.js +3 -0
  132. package/dist/runtime/query/index.js.map +1 -1
  133. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  134. package/dist/runtime/query/iteration/phases/compaction.js +21 -3
  135. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  136. package/dist/runtime/query/iteration/phases/context.d.ts +4 -0
  137. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  138. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  139. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  140. package/dist/runtime/query/path-escalation.js +90 -17
  141. package/dist/runtime/query/path-escalation.js.map +1 -1
  142. package/dist/runtime/query/steering.d.ts +15 -0
  143. package/dist/runtime/query/steering.d.ts.map +1 -1
  144. package/dist/runtime/query/steering.js +27 -3
  145. package/dist/runtime/query/steering.js.map +1 -1
  146. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  147. package/dist/scheduler/completion-inbox.js +15 -0
  148. package/dist/scheduler/completion-inbox.js.map +1 -1
  149. package/dist/session/workspace/driver.d.ts +12 -0
  150. package/dist/session/workspace/driver.d.ts.map +1 -1
  151. package/dist/session/workspace/git-worktree.d.ts +16 -0
  152. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  153. package/dist/session/workspace/git-worktree.js +35 -0
  154. package/dist/session/workspace/git-worktree.js.map +1 -1
  155. package/dist/session/workspace/holds.d.ts +78 -0
  156. package/dist/session/workspace/holds.d.ts.map +1 -0
  157. package/dist/session/workspace/holds.js +150 -0
  158. package/dist/session/workspace/holds.js.map +1 -0
  159. package/dist/session/workspace/index.d.ts +3 -1
  160. package/dist/session/workspace/index.d.ts.map +1 -1
  161. package/dist/session/workspace/index.js +2 -1
  162. package/dist/session/workspace/index.js.map +1 -1
  163. package/dist/store/config/index.d.ts +3 -0
  164. package/dist/store/config/index.d.ts.map +1 -1
  165. package/dist/store/config/index.js +3 -0
  166. package/dist/store/config/index.js.map +1 -1
  167. package/dist/store/session-index/index.d.ts +13 -0
  168. package/dist/store/session-index/index.d.ts.map +1 -1
  169. package/dist/store/session-index/index.js +1 -0
  170. package/dist/store/session-index/index.js.map +1 -1
  171. package/dist/store/session-index/rebuild.d.ts +12 -0
  172. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  173. package/dist/store/session-index/rebuild.js +20 -4
  174. package/dist/store/session-index/rebuild.js.map +1 -1
  175. package/dist/store/session-index/sqlite.d.ts +20 -0
  176. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  177. package/dist/store/session-index/sqlite.js +50 -12
  178. package/dist/store/session-index/sqlite.js.map +1 -1
  179. package/dist/tools/admit-facts.d.ts.map +1 -1
  180. package/dist/tools/admit-facts.js +59 -0
  181. package/dist/tools/admit-facts.js.map +1 -1
  182. package/dist/tools/builtins/grep.d.ts.map +1 -1
  183. package/dist/tools/builtins/grep.js +57 -0
  184. package/dist/tools/builtins/grep.js.map +1 -1
  185. package/dist/tools/builtins/lsp.d.ts.map +1 -1
  186. package/dist/tools/builtins/lsp.js +41 -4
  187. package/dist/tools/builtins/lsp.js.map +1 -1
  188. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  189. package/dist/tools/coordinator/ask-user-question.js +67 -3
  190. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  191. package/dist/turn/memory-promoter.d.ts.map +1 -1
  192. package/dist/turn/memory-promoter.js +20 -4
  193. package/dist/turn/memory-promoter.js.map +1 -1
  194. package/dist/types/agent/base.d.ts +6 -0
  195. package/dist/types/agent/base.d.ts.map +1 -1
  196. package/dist/types/agent/task.d.ts +5 -0
  197. package/dist/types/agent/task.d.ts.map +1 -1
  198. package/dist/types/agent/task.js.map +1 -1
  199. package/dist/types/code-navigation/index.d.ts +34 -4
  200. package/dist/types/code-navigation/index.d.ts.map +1 -1
  201. package/dist/types/hitl/index.d.ts +8 -0
  202. package/dist/types/hitl/index.d.ts.map +1 -1
  203. package/dist/types/hitl/index.js.map +1 -1
  204. package/dist/types/message/index.d.ts +7 -0
  205. package/dist/types/message/index.d.ts.map +1 -1
  206. package/dist/types/message/index.js.map +1 -1
  207. package/dist/types/tool/presentation.d.ts +21 -0
  208. package/dist/types/tool/presentation.d.ts.map +1 -1
  209. package/package.json +6 -6
  210. package/src/agents/QueryAgent.ts +1 -0
  211. package/src/authorization/readonly-commands.ts +72 -4
  212. package/src/authorization/shell-paths.ts +75 -18
  213. package/src/compaction/index.ts +1 -0
  214. package/src/compaction/manual.ts +48 -12
  215. package/src/compaction/model-summary.ts +163 -28
  216. package/src/compaction/restore.ts +74 -1
  217. package/src/compaction/summary.ts +69 -3
  218. package/src/config/registry.ts +87 -5
  219. package/src/config/runtime.ts +3 -3
  220. package/src/connector/index.ts +3 -0
  221. package/src/connector/mcp/adapter.ts +137 -1
  222. package/src/connector/mcp/client.ts +49 -7
  223. package/src/connector/mcp/index.ts +5 -0
  224. package/src/connector/mcp/sandbox-stdio.ts +214 -0
  225. package/src/connector/mcp/stdio-program.ts +68 -0
  226. package/src/connector/mcp/stdio.ts +61 -7
  227. package/src/connector/web/guarded-fetch.ts +197 -30
  228. package/src/connector/web/index.ts +4 -1
  229. package/src/constants/mcp/index.ts +31 -0
  230. package/src/manager/agent/lifecycle.ts +58 -13
  231. package/src/plugin/hook-module/capabilities.ts +36 -14
  232. package/src/plugin/hook-module/host.ts +86 -13
  233. package/src/plugin/hook-module/index.ts +3 -0
  234. package/src/plugin/index.ts +4 -0
  235. package/src/plugin/shell-hook-execute.ts +126 -0
  236. package/src/plugin/shell-hook-restrict.ts +66 -0
  237. package/src/plugin/shell-hook.ts +209 -16
  238. package/src/public-runtime.ts +19 -0
  239. package/src/public-types.ts +20 -0
  240. package/src/runtime/jobs/websocket-source.ts +2 -46
  241. package/src/runtime/query/compact-session.ts +5 -0
  242. package/src/runtime/query/events.ts +29 -11
  243. package/src/runtime/query/executor/tool-call-admission.ts +62 -17
  244. package/src/runtime/query/index.ts +10 -0
  245. package/src/runtime/query/iteration/phases/compaction.ts +26 -2
  246. package/src/runtime/query/iteration/phases/context.ts +6 -0
  247. package/src/runtime/query/path-escalation.ts +102 -16
  248. package/src/runtime/query/steering.ts +38 -3
  249. package/src/scheduler/completion-inbox.ts +14 -0
  250. package/src/session/workspace/driver.ts +12 -0
  251. package/src/session/workspace/git-worktree.ts +49 -0
  252. package/src/session/workspace/holds.ts +201 -0
  253. package/src/session/workspace/index.ts +13 -1
  254. package/src/store/config/index.ts +6 -0
  255. package/src/store/session-index/index.ts +14 -0
  256. package/src/store/session-index/rebuild.ts +22 -4
  257. package/src/store/session-index/sqlite.ts +63 -14
  258. package/src/tools/admit-facts.ts +64 -0
  259. package/src/tools/builtins/grep.ts +52 -0
  260. package/src/tools/builtins/lsp.ts +47 -4
  261. package/src/tools/coordinator/ask-user-question.ts +88 -4
  262. package/src/turn/memory-promoter.ts +24 -3
  263. package/src/types/agent/base.ts +7 -0
  264. package/src/types/agent/task.ts +5 -0
  265. package/src/types/code-navigation/index.ts +48 -4
  266. package/src/types/hitl/index.ts +8 -0
  267. package/src/types/message/index.ts +7 -0
  268. package/src/types/tool/presentation.ts +22 -0
@@ -1,3 +1,4 @@
1
+ import { isDeepStrictEqual } from 'node:util'
1
2
  import { GENAI, NAMZU } from '../../../constants/telemetry/index.js'
2
3
  import { boundHookContext } from '../../../plugin/hook-context.js'
3
4
  import { callableToolNames, formatToolNames } from '../../../registry/tool/callable.js'
@@ -83,30 +84,74 @@ export async function runPreToolHook(
83
84
  signal.throwIfAborted()
84
85
  const manager = host.config.pluginManager
85
86
  if (!manager) return { kind: 'continue', input, modified: false }
86
- const results = await awaitWithAbort(
87
- manager.executeHooks(
88
- 'pre_tool_use',
89
- {
90
- sessionId: host.config.sessionId,
91
- turnId: host.config.turnId,
92
- toolName,
93
- ...(toolCallId !== undefined ? { toolCallId } : {}),
94
- toolInput: input,
95
- signal,
96
- },
97
- host.emitEvent,
98
- ),
99
- signal,
100
- )
101
- signal.throwIfAborted()
102
- const outcome = interpretPreToolResults(toolName, input, results, host.requestHalt)
87
+ const runHooks = async (toolInput: unknown): Promise<readonly PluginHookResult[]> => {
88
+ const results = await awaitWithAbort(
89
+ manager.executeHooks(
90
+ 'pre_tool_use',
91
+ {
92
+ sessionId: host.config.sessionId,
93
+ turnId: host.config.turnId,
94
+ toolName,
95
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
96
+ toolInput,
97
+ signal,
98
+ },
99
+ host.emitEvent,
100
+ ),
101
+ signal,
102
+ )
103
+ signal.throwIfAborted()
104
+ return results
105
+ }
106
+ let outcome = interpretPreToolResults(toolName, input, await runHooks(input), host.requestHalt)
103
107
  if (outcome.kind !== 'continue') return outcome
108
+ if (outcome.modified) {
109
+ // The hooks answered about the call the model made. The call that will
110
+ // run is the rewritten one, so every hook answers again about that one:
111
+ // a refusal or a question from any of them stands, and an `allow` counts
112
+ // only when it was given to the input that runs. A second rewrite is not
113
+ // followed (a hook that rewrites every input would never settle), but it
114
+ // is not taken as a yes either.
115
+ const rewritten = outcome.input
116
+ const first = outcome
117
+ const again = interpretPreToolResults(
118
+ toolName,
119
+ rewritten,
120
+ (await runHooks(rewritten)).map((result) => settleRewrite(result, rewritten)),
121
+ host.requestHalt,
122
+ )
123
+ if (again.kind !== 'continue') return again
124
+ const contexts = [
125
+ ...new Set([...(first.context?.split('\n') ?? []), ...(again.context?.split('\n') ?? [])]),
126
+ ]
127
+ outcome = {
128
+ kind: 'continue',
129
+ input: rewritten,
130
+ modified: true,
131
+ ...(again.permission ? { permission: again.permission } : {}),
132
+ ...(contexts.length > 0 ? { context: contexts.join('\n') } : {}),
133
+ }
134
+ }
104
135
  // A task being made or completed is announced once the call itself is allowed.
105
136
  const refusal = await runTaskHook(host, manager, toolName, outcome.input, signal)
106
137
  if (refusal === undefined) return outcome
107
138
  return { kind: 'skip', input: outcome.input, output: refusal }
108
139
  }
109
140
 
141
+ /**
142
+ * A hook's answer to the rewritten input: a `modify` to the same input is the
143
+ * hook agreeing, and a `modify` to anything else is dropped to a plain
144
+ * `continue` (its verdict was about an input that will not run).
145
+ */
146
+ function settleRewrite(result: PluginHookResult, rewritten: unknown): PluginHookResult {
147
+ if (result.action !== 'modify') return result
148
+ const { input: _input, permission, ...rest } = result
149
+ if (isDeepStrictEqual(result.input, rewritten)) {
150
+ return { ...rest, action: 'continue', ...(permission ? { permission } : {}) }
151
+ }
152
+ return { ...rest, action: 'continue' }
153
+ }
154
+
110
155
  /**
111
156
  * `task_created` before `task_create` runs and `task_completed` before a
112
157
  * `task_update` that completes a task. The text that refuses the call, or
@@ -29,6 +29,7 @@ import { withTokenBudget } from '../../provider/token-budget.js'
29
29
  import type { SessionPaths } from '../../session/paths.js'
30
30
  import type { SessionTokenBudget, SessionTokenBudgetStore } from '../../store/budget/index.js'
31
31
  import type { SessionCheckpointStore } from '../../store/checkpoint/index.js'
32
+ import { DiskSessionLog } from '../../store/session-log/index.js'
32
33
  import type { SessionLease, SessionLog } from '../../store/session-log/index.js'
33
34
  import {
34
35
  GENAI,
@@ -923,6 +924,13 @@ export interface QueryParams {
923
924
  */
924
925
  compactionSummaryRoute?: CompactionSummaryRouter
925
926
 
927
+ /**
928
+ * Close a compaction summary with the wording that lets the model ask when
929
+ * something is unclear, instead of telling it to continue directly. Absent
930
+ * or false, it continues directly.
931
+ */
932
+ compactionAskWhenUnclear?: boolean
933
+
926
934
  /**
927
935
  * Where this conversation's durable state lives.
928
936
  *
@@ -2104,12 +2112,14 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
2104
2112
  ...(params.projectInstructionContext
2105
2113
  ? { projectInstructionContext: params.projectInstructionContext }
2106
2114
  : {}),
2115
+ ...(ctx.storage.log instanceof DiskSessionLog ? { sessionFile: ctx.storage.log.file } : {}),
2107
2116
  ...(params.postCompactionContext
2108
2117
  ? { postCompactionContext: params.postCompactionContext }
2109
2118
  : {}),
2110
2119
  ...(params.compactionSummaryRoute
2111
2120
  ? { compactionSummaryRoute: params.compactionSummaryRoute }
2112
2121
  : {}),
2122
+ ...(params.compactionAskWhenUnclear ? { compactionAskWhenUnclear: true } : {}),
2113
2123
  ...(providerContextWindow !== undefined ? { providerContextWindow } : {}),
2114
2124
  ...(providerAutoCompactLimit !== undefined ? { providerAutoCompactLimit } : {}),
2115
2125
  resolveModelAutoCompactLimit: async (model) => {
@@ -26,7 +26,12 @@ import {
26
26
  } from '../../../../compaction/plan.js'
27
27
  import type { ContextReducer, ContextReduction } from '../../../../compaction/reducer.js'
28
28
  import { createSlidingWindowReducer } from '../../../../compaction/reducer.js'
29
- import { carriedWorkingCommands, renderRestoredContext } from '../../../../compaction/restore.js'
29
+ import {
30
+ carriedWorkingCommands,
31
+ collectToolsUsed,
32
+ keptInstructionFiles,
33
+ renderRestoredContext,
34
+ } from '../../../../compaction/restore.js'
30
35
  import { findRetainedIndices } from '../../../../compaction/retention.js'
31
36
  import { serializeState } from '../../../../compaction/serializer.js'
32
37
  import {
@@ -1302,18 +1307,30 @@ async function runCompactionCheckInner(
1302
1307
  // shown by an earlier pass, is not put back a second time.
1303
1308
  const wholeSkills = handledSkillNames([...preservedSystem, ...retainedOlder, ...recentMessages])
1304
1309
  const putBack: { rendered?: RenderedSkills } = {}
1310
+ const mounted = new Set(ctx.tools?.listNames?.() ?? [])
1305
1311
  const restored = renderRestoredContext(manager.getState(), {
1306
1312
  contextWindowTokens: budget,
1307
1313
  wholeSkills,
1308
1314
  onSkills: (rendered) => {
1309
1315
  putBack.rendered = rendered
1310
1316
  },
1317
+ // What the model was working with, named so it keeps using it: the tools it
1318
+ // called (this pass's span and what earlier summaries listed) and the
1319
+ // project instructions that stay whole after the summary.
1320
+ toolsUsed: collectToolsUsed(messages),
1321
+ instructionFiles: keptInstructionFiles([
1322
+ ...preservedSystem,
1323
+ ...retainedOlder,
1324
+ ...recentMessages,
1325
+ ]),
1326
+ // The roster of agents is in the description of the tool that hands work to
1327
+ // them, which every request carries; say so instead of copying it.
1328
+ ...(mounted.has('create_task') ? { agentsTool: 'create_task' } : {}),
1311
1329
  ...(hostNote ? { hostNote } : {}),
1312
1330
  })
1313
1331
  if (restored) compactedContent = `${compactedContent}\n\n${restored}`
1314
1332
 
1315
1333
  // The pointer is only worth a line when both tools it names are mounted.
1316
- const mounted = new Set(ctx.tools?.listNames?.() ?? [])
1317
1334
  const compactionMessage = buildCompactionMessage(
1318
1335
  compactedContent,
1319
1336
  mounted.has('search_conversation') && mounted.has('read_conversation')
@@ -1322,6 +1339,13 @@ async function runCompactionCheckInner(
1322
1339
  // The tools the model had loaded stay loaded: the messages that loaded
1323
1340
  // them are what this pass cuts.
1324
1341
  collectRevealedTools(messages),
1342
+ {
1343
+ // The summary was written without the messages kept after it.
1344
+ keptTail: retainedOlder.length + recentMessages.length > 0,
1345
+ toolsUsed: collectToolsUsed(messages),
1346
+ ...(ctx.sessionFile ? { sessionFile: ctx.sessionFile } : {}),
1347
+ ...(ctx.compactionAskWhenUnclear ? { askWhenUnclear: true } : {}),
1348
+ },
1325
1349
  )
1326
1350
 
1327
1351
  const newMessages = [...preservedSystem, compactionMessage, ...retainedOlder, ...recentMessages]
@@ -274,6 +274,12 @@ export interface IterationContext {
274
274
  /** Live project policy; separate from human inbound continuation. */
275
275
  readonly projectInstructionContext?: ProjectInstructionContext
276
276
 
277
+ /** The file the session's full record is stored in, named in a compaction summary so exact text can be found again. Absent for an in-memory session. */
278
+ readonly sessionFile?: string
279
+
280
+ /** Close a compaction summary with the wording that lets the model ask when something is unclear. */
281
+ readonly compactionAskWhenUnclear?: boolean
282
+
277
283
  /** Host text appended to the restored context after a compaction. */
278
284
  readonly postCompactionContext?: () => string | undefined | Promise<string | undefined>
279
285
 
@@ -22,6 +22,7 @@ import { homedir } from 'node:os'
22
22
  import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
23
23
 
24
24
  import { isProtectedPath } from '../../authorization/protected-paths.js'
25
+ import { isReadOnlyCommandLine } from '../../authorization/readonly-commands.js'
25
26
  import { dangerousRemoval } from '../../authorization/removal.js'
26
27
  import type { ShellDialect } from '../../authorization/shell-lexer.js'
27
28
  import { readShellLine, shellPathAccess } from '../../authorization/shell-paths.js'
@@ -178,29 +179,83 @@ export function expandBraces(value: string, limit = 16): string[] {
178
179
  return out
179
180
  }
180
181
 
181
- /** The path a use names with `~` and `$HOME` read as the home directory, or why it cannot be. */
182
+ /**
183
+ * `$PWD` or `${PWD}` inside a word. The lookahead keeps `$PWDfoo` a variable of
184
+ * its own, and the braced form carries its own braces, so `${PWD:-x}` — which
185
+ * decides its value at run time — matches neither.
186
+ */
187
+ const WORKING_DIRECTORY_VARIABLE = /\$(?:\{PWD\}|PWD(?![A-Za-z0-9_]))/
188
+
189
+ /** A directory whose every character an unquoted expansion leaves as it is: no space, glob character or backslash. */
190
+ const PLAIN_DIRECTORY = /^[A-Za-z0-9._/@%+,:=~-]*$/
191
+
192
+ /** Whether `$PWD` or `${PWD}` appears outside double and single quotes. */
193
+ function hasUnquotedWorkingDirectory(line: string): boolean {
194
+ let single = false
195
+ let double = false
196
+ for (let i = 0; i < line.length; i += 1) {
197
+ const c = line[i] as string
198
+ if (c === '\\' && !single) {
199
+ i += 1
200
+ continue
201
+ }
202
+ if (c === "'" && !double) single = !single
203
+ else if (c === '"' && !single) double = !double
204
+ else if (c === '$' && !single && !double) {
205
+ if (/^\$(?:\{PWD\}|PWD(?![A-Za-z0-9_]))/.test(line.slice(i))) return true
206
+ }
207
+ }
208
+ return false
209
+ }
210
+
211
+ /**
212
+ * The path a use names with `~` and the variables whose value is known before
213
+ * the line runs, or why it cannot be.
214
+ *
215
+ * `$NAMZU_SCRATCH` names the session's scratch folder; `$PWD` and `${PWD}` name
216
+ * the directory the line starts in. A word resolved from one of those carries
217
+ * `resolved`, so the caller does not treat it as decided at run time; anything
218
+ * else that expands has no path.
219
+ */
182
220
  function settle(
183
221
  value: string,
184
222
  home: string,
185
- scratch?: string,
223
+ scratch: string | undefined,
224
+ startDirectory: string | undefined,
186
225
  ):
187
226
  | { readonly path: string }
188
- | { readonly unresolved: true; readonly scratch?: never }
189
- | { readonly path: string; readonly scratch: true } {
227
+ | { readonly unresolved: true; readonly resolved?: never }
228
+ | { readonly path: string; readonly resolved: true } {
190
229
  if (scratch !== undefined) {
191
230
  const named = /^\$(?:\{NAMZU_SCRATCH\}|NAMZU_SCRATCH)(?=\/|$)/.exec(value)
192
231
  const rest = named === null ? undefined : value.slice(named[0].length)
193
232
  if (rest !== undefined && !/[$`~*?[{]/.test(rest)) {
194
- return { path: resolve(scratch, `.${rest}`), scratch: true }
233
+ return { path: resolve(scratch, `.${rest}`), resolved: true }
195
234
  }
196
235
  }
197
- if (value === '~') return { path: home }
198
- if (value.startsWith('~/')) return { path: resolve(home, value.slice(2)) }
199
- if (value.startsWith('~')) return { unresolved: true }
200
- const variable = /^\$(?:\{HOME\}|HOME)(?=\/|$)/.exec(value)
201
- if (variable !== null) return { path: resolve(home, `.${value.slice(variable[0].length)}`) }
202
- if (/[$`]/.test(value)) return { unresolved: true }
203
- return { path: value }
236
+ // `$PWD` and `${PWD}` name the directory the line starts in, which the shell
237
+ // fixes before the line runs, so a word carrying one reads as the same word
238
+ // with that directory spelled out. Every other expansion leaves a `$` behind
239
+ // and is therefore decided at run time.
240
+ const spelled =
241
+ startDirectory === undefined
242
+ ? value
243
+ : value.replace(new RegExp(WORKING_DIRECTORY_VARIABLE, 'g'), () => startDirectory)
244
+ const spelledOut = spelled !== value
245
+ if (spelledOut && /[$`]/.test(spelled)) return { unresolved: true }
246
+ if (spelled === '~') return spelledOut ? { path: home, resolved: true } : { path: home }
247
+ if (spelled.startsWith('~/')) {
248
+ const path = resolve(home, spelled.slice(2))
249
+ return spelledOut ? { path, resolved: true } : { path }
250
+ }
251
+ if (spelled.startsWith('~')) return { unresolved: true }
252
+ const variable = /^\$(?:\{HOME\}|HOME)(?=\/|$)/.exec(spelled)
253
+ if (variable !== null) {
254
+ const path = resolve(home, `.${spelled.slice(variable[0].length)}`)
255
+ return spelledOut ? { path, resolved: true } : { path }
256
+ }
257
+ if (/[$`]/.test(spelled)) return { unresolved: true }
258
+ return spelledOut ? { path: spelled, resolved: true } : { path: spelled }
204
259
  }
205
260
 
206
261
  /** The part of a glob path before the first segment that holds a glob character. */
@@ -242,6 +297,23 @@ export async function shellEscalations(
242
297
  const reads =
243
298
  line.split('$NAMZU_SCRATCH').length - 1 + (line.split('${NAMZU_SCRATCH}').length - 1)
244
299
  const scratch = mentions === reads ? context.scratchpadDirectory : undefined
300
+ // `$PWD` is read as the start directory only for a line the read-only
301
+ // recogniser accepts: every command on it is a known reader, it assigns
302
+ // nothing, and it never runs `cd`, `eval`, `source` or a function, so
303
+ // nothing before the use can have changed the variable. Any other line
304
+ // keeps `$PWD` as a word decided at run time, so a write through it is
305
+ // asked about. An unquoted use is resolved only when every character of
306
+ // the directory is one the shell leaves alone in an expanded word; any
307
+ // other (a space, a glob character, a backslash that a glob reads as an
308
+ // escape) would let splitting or globbing change which paths the word
309
+ // names, so the use stays unresolved and, on a read-only line, is asked
310
+ // about rather than left to run.
311
+ const readOnlyWithPwd =
312
+ cwd !== undefined &&
313
+ WORKING_DIRECTORY_VARIABLE.test(line) &&
314
+ isReadOnlyCommandLine(line, dialect)
315
+ const pwdHeld =
316
+ readOnlyWithPwd && (PLAIN_DIRECTORY.test(cwd) || !hasUnquotedWorkingDirectory(line))
245
317
  if (cwd !== undefined) {
246
318
  // A link made earlier in this very line leads somewhere that cannot be
247
319
  // read before the line runs: `ln -s /etc l && cd l && echo x > passwd`
@@ -255,9 +327,16 @@ export async function shellEscalations(
255
327
  .map((value) => resolve(cwd, value))
256
328
  for (const use of access.uses) {
257
329
  for (const spelled of expandBraces(use.path)) {
258
- const settled = settle(spelled, home, scratch)
330
+ // After a `cd` the shell holds another directory, so `$PWD` no longer
331
+ // names the one the line started in and is left to run time.
332
+ const settled = settle(
333
+ spelled,
334
+ home,
335
+ scratch,
336
+ use.directory === undefined && pwdHeld ? cwd : undefined,
337
+ )
259
338
  const unresolved =
260
- ('scratch' in settled ? false : use.unresolved) || 'unresolved' in settled
339
+ ('resolved' in settled ? false : use.unresolved) || 'unresolved' in settled
261
340
  const base = 'path' in settled ? settled.path : spelled
262
341
  // Where a relative path may start from. Usually the directory the
263
342
  // line began in; after a literal `cd <relative>` also the directory
@@ -291,8 +370,15 @@ export async function shellEscalations(
291
370
  if (!context.reviewOutside) continue
292
371
  if (unresolved) {
293
372
  // A write whose target is decided at runtime cannot be checked; a
294
- // read of one is left alone.
295
- if (use.access === 'write') outside.add(spelled)
373
+ // read of one is left alone. The exception is a read through
374
+ // `$PWD` on a line accepted as read-only only because `$PWD` was
375
+ // expected to name the start directory: left alone, it would run
376
+ // unasked wherever the shell's splitting or globbing took it.
377
+ if (
378
+ use.access === 'write' ||
379
+ (readOnlyWithPwd && WORKING_DIRECTORY_VARIABLE.test(spelled))
380
+ )
381
+ outside.add(spelled)
296
382
  continue
297
383
  }
298
384
  if (
@@ -120,6 +120,28 @@ export class SteeringBinding implements SteeringChannel {
120
120
  */
121
121
  export const JOB_NOTICE_INLINE_OUTPUT_MAX_BYTES = 2048
122
122
 
123
+ /**
124
+ * The most of a job's command line an exit notice quotes. The notice is
125
+ * carried into every later session that learns the job ended, so an unbounded
126
+ * command would be pasted into each of them; the whole line stays in the job's
127
+ * own record, which the job tool lists.
128
+ */
129
+ export const JOB_NOTICE_COMMAND_MAX_CHARS = 300
130
+
131
+ /**
132
+ * A job's command as its exit notice quotes it: the whole of it when it fits
133
+ * {@link JOB_NOTICE_COMMAND_MAX_CHARS}, otherwise its first and last stretch
134
+ * with the number of characters left out between them — the same head-and-tail
135
+ * summary a value is cut with elsewhere in the kernel. The full line is not
136
+ * lost, only the notice does not carry it.
137
+ */
138
+ export function boundJobNoticeCommand(
139
+ command: string,
140
+ max: number = JOB_NOTICE_COMMAND_MAX_CHARS,
141
+ ): string {
142
+ return cutMiddle(command, max, inlineCutMarker)
143
+ }
144
+
123
145
  /**
124
146
  * One job's exit as the text the model reads. The output is inlined only when
125
147
  * the whole of it fits {@link JOB_NOTICE_INLINE_OUTPUT_MAX_BYTES} and none was
@@ -145,7 +167,7 @@ export function formatJobExitNotice(
145
167
  ? ` after ${formatMonitorDuration(Math.max(0, job.exitedAt - job.startedAt))}`
146
168
  : ''
147
169
  const saved = job.outputFile === undefined ? '' : ` Its output is saved to ${job.outputFile}.`
148
- const head = `Background job ${job.id} (${job.command}) ${outcome}${endedAt}${ran}.${saved}`
170
+ const head = `Background job ${job.id} (${boundJobNoticeCommand(job.command)}) ${outcome}${endedAt}${ran}.${saved}`
149
171
  if (
150
172
  output === undefined ||
151
173
  output.chunk.length === 0 ||
@@ -334,9 +356,22 @@ export function capMonitorContent(
334
356
  return text.length <= max ? text : cutMiddle(text, max)
335
357
  }
336
358
 
337
- function cutMiddle(text: string, max: number): string {
359
+ /** The cut a multi-line block gets: the marker stands on a line of its own. */
360
+ function multilineCutMarker(omitted: number): string {
361
+ return `\n...[${omitted} characters omitted]...\n`
362
+ }
363
+
364
+ /** The cut a value inside a line gets: no newline, so the line stays one line. */
365
+ function inlineCutMarker(omitted: number): string {
366
+ return `…[${omitted} characters omitted]…`
367
+ }
368
+
369
+ function cutMiddle(
370
+ text: string,
371
+ max: number,
372
+ marker: (omitted: number) => string = multilineCutMarker,
373
+ ): string {
338
374
  if (text.length <= max) return text
339
- const marker = (omitted: number) => `\n...[${omitted} characters omitted]...\n`
340
375
  // Reserve room for the marker itself so the result never exceeds `max`.
341
376
  const room = Math.max(0, max - marker(text.length).length)
342
377
  const head = Math.ceil(room / 2)
@@ -1,3 +1,4 @@
1
+ import { existsSync } from 'node:fs'
1
2
  import { wrapUntrusted } from '../tools/untrusted-envelope.js'
2
3
  import type { TaskHandle, TaskScheduler } from '../types/agent/scheduler.js'
3
4
  import { isTerminalAgentTaskState } from '../types/agent/task.js'
@@ -722,6 +723,18 @@ function neutralizeNotificationDelimiter(content: string): string {
722
723
  return content.replace(NOTIFICATION_DELIMITER, 'task_notification')
723
724
  }
724
725
 
726
+ /**
727
+ * Where a worker that had a checkout of its own left its work. The checkout is kept when the
728
+ * worker changed or committed anything and removed when it did not, so the answer is read from
729
+ * the disk: a path that is gone is not offered as something to look at.
730
+ */
731
+ function workspaceLines(handle: TaskHandle): string[] {
732
+ const meta = handle.workspace?.meta
733
+ if (meta?.backend !== 'git-worktree') return []
734
+ if (!existsSync(meta.worktreePath)) return ['workspace: removed (the worker changed nothing)']
735
+ return [`workspace: ${meta.worktreePath}`, `branch: ${meta.branch}`]
736
+ }
737
+
725
738
  /**
726
739
  * The message a supervisor reads when a worker it stopped waiting for
727
740
  * finishes.
@@ -790,6 +803,7 @@ export function formatCompletionNotification(handles: readonly TaskHandle[]): st
790
803
  ...(handle.result?.stopReason ? [`stop_reason: ${handle.result.stopReason}`] : []),
791
804
  ...(durationMs !== undefined ? [`duration_ms: ${durationMs}`] : []),
792
805
  ...(handle.completedAt ? [`finished_at: ${new Date(handle.completedAt).toISOString()}`] : []),
806
+ ...workspaceLines(handle),
793
807
  '',
794
808
  body,
795
809
  // Outside the envelope, deliberately: this sentence is an
@@ -69,6 +69,18 @@ export interface WorkspaceBackendDriver {
69
69
  branch(source: WorkspaceRef, params: BranchWorkspaceParams): Promise<WorkspaceRef>
70
70
  dispose(ref: WorkspaceRef): Promise<void>
71
71
  inspect(ref: WorkspaceRef): Promise<WorkspaceInspection>
72
+ /**
73
+ * The child that worked in `ref` has ended: let go of whatever claim this
74
+ * driver still makes on that checkout, whether or not the checkout is kept.
75
+ *
76
+ * A checkout provisioned with `retain`, or with `retain-changed` when the
77
+ * child left something behind, is never passed to {@link dispose}, so without
78
+ * this the backend would go on reporting a checkout as in use by a session
79
+ * that has already finished. A driver that claims nothing can leave it out.
80
+ *
81
+ * Called on every terminal path of a child, before the retention decision.
82
+ */
83
+ release?(ref: WorkspaceRef): Promise<void>
72
84
  }
73
85
 
74
86
  export type { WorkspaceBackendKind } from '../../types/workspace/ref.js'
@@ -31,6 +31,12 @@ import type {
31
31
  WorkspaceBackendDriver,
32
32
  WorkspaceInspection,
33
33
  } from './driver.js'
34
+ import {
35
+ DiskWorkspaceHoldStore,
36
+ type WorkspaceHold,
37
+ type WorkspaceHoldStore,
38
+ WorkspaceInUseError,
39
+ } from './holds.js'
34
40
 
35
41
  const execFileAsync = promisify(execFile)
36
42
 
@@ -75,6 +81,12 @@ export interface GitWorktreeDriverConfig {
75
81
  branchPrefix?: string
76
82
  /** Test-seam: inject a stub `execFile` implementation. */
77
83
  execFile?: ExecFile
84
+ /**
85
+ * Who is working in a checkout right now. `dispose` asks it before removing
86
+ * anything and refuses a path a live session or subagent still has. Absent,
87
+ * the machine's own hold directory is read.
88
+ */
89
+ holds?: WorkspaceHoldStore
78
90
  }
79
91
 
80
92
  const DEFAULT_BRANCH_PREFIX = 'namzu'
@@ -97,12 +109,14 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
97
109
  private readonly log: Logger
98
110
  private readonly exec: ExecFile
99
111
  private readonly branchPrefix: string
112
+ private readonly holds: WorkspaceHoldStore
100
113
 
101
114
  constructor(config: GitWorktreeDriverConfig) {
102
115
  this.repoRoot = resolve(config.repoRoot)
103
116
  this.worktreesDir = resolve(config.worktreesDir ?? defaultWorktreesDir(config.repoRoot))
104
117
  this.log = config.logger.child({ [SCOPE_ATTRIBUTE]: 'session/workspace/git-worktree' })
105
118
  this.exec = config.execFile ?? defaultExecFile
119
+ this.holds = config.holds ?? new DiskWorkspaceHoldStore()
106
120
  const prefix = config.branchPrefix ?? DEFAULT_BRANCH_PREFIX
107
121
  if (!isBranchPrefix(prefix)) {
108
122
  throw new Error(
@@ -221,6 +235,20 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
221
235
  return
222
236
  }
223
237
 
238
+ // A checkout another live process has open is not this call's to remove:
239
+ // `worktree remove --force` would take that process's uncommitted files
240
+ // with it. The refusal names the folder asked for and every folder its
241
+ // holders work in, so a person can see which session to close.
242
+ const holders = await this.liveHolders(owned.worktreePath)
243
+ if (holders.length > 0) {
244
+ this.log.info('git-worktree kept; another session has it', {
245
+ [NAMZU.SESSION_ID]: ref.id,
246
+ 'namzu.session.path': owned.worktreePath,
247
+ 'namzu.session.holder_count': holders.length,
248
+ })
249
+ throw new WorkspaceInUseError(owned.worktreePath, holders)
250
+ }
251
+
224
252
  // Tolerate missing directories per roadmap Risk #3 mitigation: the
225
253
  // broadcast-rollback compensating step calls dispose on partially
226
254
  // provisioned refs and must not propagate "already gone" errors. The
@@ -276,6 +304,27 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
276
304
  }
277
305
  }
278
306
 
307
+ /**
308
+ * Who is working in `worktreePath` right now.
309
+ *
310
+ * A hold store that cannot be read is not a "nobody": answering that on a
311
+ * guess is how an in-use checkout gets deleted, so it refuses the removal
312
+ * and says what it could not read.
313
+ */
314
+ private async liveHolders(worktreePath: string): Promise<readonly WorkspaceHold[]> {
315
+ try {
316
+ return await this.holds.holders(worktreePath)
317
+ } catch (cause) {
318
+ throw new WorkspaceBackendError({
319
+ op: 'dispose:holders',
320
+ kind: this.kind,
321
+ cause: new Error(
322
+ `The worktree ${worktreePath} was not removed: Namzu could not read who is working in it (${cause instanceof Error ? cause.message : String(cause)}).`,
323
+ ),
324
+ })
325
+ }
326
+ }
327
+
279
328
  /**
280
329
  * Did the worktree arrive despite the command reporting failure?
281
330
  *