@namzu/sdk 71.0.0 → 71.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 (115) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/dist/authorization/readonly-commands.d.ts +9 -1
  3. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  4. package/dist/authorization/readonly-commands.js +70 -4
  5. package/dist/authorization/readonly-commands.js.map +1 -1
  6. package/dist/authorization/shell-paths.d.ts.map +1 -1
  7. package/dist/authorization/shell-paths.js +68 -16
  8. package/dist/authorization/shell-paths.js.map +1 -1
  9. package/dist/compaction/model-summary.d.ts.map +1 -1
  10. package/dist/compaction/model-summary.js +44 -5
  11. package/dist/compaction/model-summary.js.map +1 -1
  12. package/dist/config/registry.d.ts +2 -0
  13. package/dist/config/registry.d.ts.map +1 -1
  14. package/dist/config/registry.js +76 -5
  15. package/dist/config/registry.js.map +1 -1
  16. package/dist/connector/mcp/adapter.d.ts +8 -0
  17. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  18. package/dist/connector/mcp/adapter.js +131 -1
  19. package/dist/connector/mcp/adapter.js.map +1 -1
  20. package/dist/connector/mcp/stdio.d.ts +12 -0
  21. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  22. package/dist/connector/mcp/stdio.js +49 -5
  23. package/dist/connector/mcp/stdio.js.map +1 -1
  24. package/dist/constants/mcp/index.d.ts +29 -0
  25. package/dist/constants/mcp/index.d.ts.map +1 -1
  26. package/dist/constants/mcp/index.js +29 -0
  27. package/dist/constants/mcp/index.js.map +1 -1
  28. package/dist/manager/agent/lifecycle.d.ts +18 -1
  29. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  30. package/dist/manager/agent/lifecycle.js +52 -7
  31. package/dist/manager/agent/lifecycle.js.map +1 -1
  32. package/dist/plugin/index.d.ts +1 -1
  33. package/dist/plugin/index.d.ts.map +1 -1
  34. package/dist/plugin/index.js.map +1 -1
  35. package/dist/plugin/shell-hook.d.ts +44 -2
  36. package/dist/plugin/shell-hook.d.ts.map +1 -1
  37. package/dist/plugin/shell-hook.js +74 -5
  38. package/dist/plugin/shell-hook.js.map +1 -1
  39. package/dist/public-runtime.d.ts +2 -2
  40. package/dist/public-runtime.d.ts.map +1 -1
  41. package/dist/public-runtime.js +1 -1
  42. package/dist/public-runtime.js.map +1 -1
  43. package/dist/public-types.d.ts +2 -2
  44. package/dist/public-types.d.ts.map +1 -1
  45. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  46. package/dist/runtime/query/path-escalation.js +90 -17
  47. package/dist/runtime/query/path-escalation.js.map +1 -1
  48. package/dist/runtime/query/steering.d.ts +15 -0
  49. package/dist/runtime/query/steering.d.ts.map +1 -1
  50. package/dist/runtime/query/steering.js +27 -3
  51. package/dist/runtime/query/steering.js.map +1 -1
  52. package/dist/session/workspace/driver.d.ts +12 -0
  53. package/dist/session/workspace/driver.d.ts.map +1 -1
  54. package/dist/session/workspace/git-worktree.d.ts +16 -0
  55. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  56. package/dist/session/workspace/git-worktree.js +35 -0
  57. package/dist/session/workspace/git-worktree.js.map +1 -1
  58. package/dist/session/workspace/holds.d.ts +78 -0
  59. package/dist/session/workspace/holds.d.ts.map +1 -0
  60. package/dist/session/workspace/holds.js +150 -0
  61. package/dist/session/workspace/holds.js.map +1 -0
  62. package/dist/session/workspace/index.d.ts +3 -1
  63. package/dist/session/workspace/index.d.ts.map +1 -1
  64. package/dist/session/workspace/index.js +2 -1
  65. package/dist/session/workspace/index.js.map +1 -1
  66. package/dist/store/config/index.d.ts +3 -0
  67. package/dist/store/config/index.d.ts.map +1 -1
  68. package/dist/store/config/index.js +3 -0
  69. package/dist/store/config/index.js.map +1 -1
  70. package/dist/store/session-index/index.d.ts +5 -0
  71. package/dist/store/session-index/index.d.ts.map +1 -1
  72. package/dist/store/session-index/index.js +5 -1
  73. package/dist/store/session-index/index.js.map +1 -1
  74. package/dist/store/session-index/rebuild.d.ts +18 -0
  75. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  76. package/dist/store/session-index/rebuild.js +79 -5
  77. package/dist/store/session-index/rebuild.js.map +1 -1
  78. package/dist/store/session-index/sqlite.d.ts +8 -0
  79. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  80. package/dist/store/session-index/sqlite.js +23 -1
  81. package/dist/store/session-index/sqlite.js.map +1 -1
  82. package/dist/tools/builtins/grep.d.ts.map +1 -1
  83. package/dist/tools/builtins/grep.js +57 -0
  84. package/dist/tools/builtins/grep.js.map +1 -1
  85. package/dist/tools/builtins/lsp.d.ts.map +1 -1
  86. package/dist/tools/builtins/lsp.js +41 -4
  87. package/dist/tools/builtins/lsp.js.map +1 -1
  88. package/dist/types/code-navigation/index.d.ts +34 -4
  89. package/dist/types/code-navigation/index.d.ts.map +1 -1
  90. package/package.json +1 -1
  91. package/src/authorization/readonly-commands.ts +72 -4
  92. package/src/authorization/shell-paths.ts +75 -18
  93. package/src/compaction/model-summary.ts +45 -5
  94. package/src/config/registry.ts +87 -5
  95. package/src/connector/mcp/adapter.ts +137 -1
  96. package/src/connector/mcp/stdio.ts +56 -5
  97. package/src/constants/mcp/index.ts +31 -0
  98. package/src/manager/agent/lifecycle.ts +57 -12
  99. package/src/plugin/index.ts +3 -0
  100. package/src/plugin/shell-hook.ts +131 -6
  101. package/src/public-runtime.ts +5 -0
  102. package/src/public-types.ts +7 -0
  103. package/src/runtime/query/path-escalation.ts +102 -16
  104. package/src/runtime/query/steering.ts +38 -3
  105. package/src/session/workspace/driver.ts +12 -0
  106. package/src/session/workspace/git-worktree.ts +49 -0
  107. package/src/session/workspace/holds.ts +201 -0
  108. package/src/session/workspace/index.ts +13 -1
  109. package/src/store/config/index.ts +6 -0
  110. package/src/store/session-index/index.ts +10 -1
  111. package/src/store/session-index/rebuild.ts +81 -5
  112. package/src/store/session-index/sqlite.ts +30 -1
  113. package/src/tools/builtins/grep.ts +52 -0
  114. package/src/tools/builtins/lsp.ts +47 -4
  115. package/src/types/code-navigation/index.ts +48 -4
@@ -1,4 +1,8 @@
1
1
  import { type ChildProcess, spawn } from 'node:child_process'
2
+ import {
3
+ MCP_STDIO_MAX_PENDING_LINE_CHARS,
4
+ MCP_STDIO_STDERR_LOG_CHARS,
5
+ } from '../../constants/mcp/index.js'
2
6
  import { SESSION_CHILD_ENV } from '../../process/session-child.js'
3
7
  import type {
4
8
  MCPJsonRpcMessage,
@@ -105,6 +109,12 @@ export class StdioTransport implements MCPTransport {
105
109
  /** True between kill and the process's own `close` event. */
106
110
  private exitPending = false
107
111
  private buffer = ''
112
+ /**
113
+ * True once the pending line has been refused for length. Everything up
114
+ * to the next newline is then dropped, so one over-long line costs one
115
+ * report and no memory rather than one report per read.
116
+ */
117
+ private discardingOverlongLine = false
108
118
  private log: Logger
109
119
 
110
120
  constructor(
@@ -122,7 +132,7 @@ export class StdioTransport implements MCPTransport {
122
132
  if (this.process) await this.close()
123
133
  const generation = ++this.generation
124
134
  this.retired = false
125
- this.buffer = ''
135
+ this.resetLineBuffer()
126
136
 
127
137
  const child = spawn(this.config.command, this.config.args ?? [], {
128
138
  env: buildChildEnv(this.config),
@@ -141,8 +151,14 @@ export class StdioTransport implements MCPTransport {
141
151
  child.stdout?.once('error', (err) => this.retire(generation, 'error', err))
142
152
 
143
153
  child.stderr?.on('data', (chunk: Buffer) => {
154
+ // One record per read, so the read's text is bounded here: a server
155
+ // that floods its error stream otherwise puts the whole of it on
156
+ // the terminal, a read at a time. The length travels beside the
157
+ // head so the record says how much it is not showing.
158
+ const text = chunk.toString('utf-8').trim()
144
159
  this.log.warn('MCP server stderr', {
145
- 'namzu.mcp.stderr': chunk.toString('utf-8').trim(),
160
+ 'namzu.mcp.stderr': text.slice(0, MCP_STDIO_STDERR_LOG_CHARS),
161
+ 'namzu.mcp.stderr_chars': text.length,
146
162
  })
147
163
  })
148
164
 
@@ -178,7 +194,7 @@ export class StdioTransport implements MCPTransport {
178
194
  this.exitPending = true
179
195
  const child = this.process
180
196
  this.process = null
181
- this.buffer = ''
197
+ this.resetLineBuffer()
182
198
 
183
199
  // Resolve when the child is actually gone, not when the signal was
184
200
  // sent. `kill()` returns as soon as the signal is delivered, so an
@@ -235,6 +251,16 @@ export class StdioTransport implements MCPTransport {
235
251
  this.errorHandlers = []
236
252
  }
237
253
 
254
+ /**
255
+ * Drop the framing state of a protocol session that ended or is being
256
+ * replaced. Keeping either half across generations would let a refused
257
+ * line swallow the first bytes of the next one.
258
+ */
259
+ private resetLineBuffer(): void {
260
+ this.buffer = ''
261
+ this.discardingOverlongLine = false
262
+ }
263
+
238
264
  /**
239
265
  * Publish one terminal result for the current response channel.
240
266
  *
@@ -247,7 +273,7 @@ export class StdioTransport implements MCPTransport {
247
273
  if (generation !== this.generation || this.retired) return
248
274
  this.retired = true
249
275
  this.connected = false
250
- this.buffer = ''
276
+ this.resetLineBuffer()
251
277
  const closeHandlers = this.closeHandlers
252
278
  const errorHandlers = this.errorHandlers
253
279
  this.clearHandlers()
@@ -289,8 +315,22 @@ export class StdioTransport implements MCPTransport {
289
315
  }
290
316
 
291
317
  private processBuffer(): void {
318
+ // An already-refused line is skipped to its terminator before anything
319
+ // else is read from the buffer. Without this the rest of that line
320
+ // would be re-buffered, re-measured and re-reported once per read,
321
+ // turning one bad line into an output flood of the transport's own.
322
+ if (this.discardingOverlongLine) {
323
+ const terminator = this.buffer.indexOf('\n')
324
+ if (terminator === -1) {
325
+ this.buffer = ''
326
+ return
327
+ }
328
+ this.buffer = this.buffer.slice(terminator + 1)
329
+ this.discardingOverlongLine = false
330
+ }
331
+
292
332
  const lines = this.buffer.split('\n')
293
- this.buffer = lines.pop() ?? ''
333
+ let pending = lines.pop() ?? ''
294
334
 
295
335
  for (const line of lines) {
296
336
  const trimmed = line.trim()
@@ -304,5 +344,16 @@ export class StdioTransport implements MCPTransport {
304
344
  })
305
345
  }
306
346
  }
347
+
348
+ if (pending.length > MCP_STDIO_MAX_PENDING_LINE_CHARS) {
349
+ this.discardingOverlongLine = true
350
+ this.log.warn('StdioTransport: dropping MCP server output past the pending-line ceiling', {
351
+ 'namzu.mcp.line_chars': pending.length,
352
+ 'namzu.mcp.line_ceiling': MCP_STDIO_MAX_PENDING_LINE_CHARS,
353
+ })
354
+ pending = ''
355
+ }
356
+
357
+ this.buffer = pending
307
358
  }
308
359
  }
@@ -87,6 +87,37 @@ export const DEFAULT_MCP_TOTAL_TIMEOUT_FACTOR = 10
87
87
  */
88
88
  export const MCP_TOOL_DEADLINE_SLACK_MS = 5_000
89
89
 
90
+ /**
91
+ * The most characters of a not-yet-terminated line the stdio transport holds
92
+ * for a server.
93
+ *
94
+ * stdout is framed by newlines, so the tail after the last one is the one
95
+ * part of the channel that is not dropped as it arrives: a server that
96
+ * writes one very long line, or simply never stops writing, grows that tail
97
+ * for as long as it keeps going, in the session's own memory, with nothing
98
+ * to stop it short of killing the child. The ceiling is what bounds it.
99
+ *
100
+ * Generous rather than tight, because a legitimate frame can be large — a
101
+ * tool result carrying an inline image arrives base64-encoded in a single
102
+ * JSON line — and a line over the ceiling is refused, never truncated. What
103
+ * the ceiling buys is that the refusal is bounded: the bytes past it are
104
+ * dropped and reported instead of accumulated.
105
+ */
106
+ export const MCP_STDIO_MAX_PENDING_LINE_CHARS = 8 * 1024 * 1024
107
+
108
+ /**
109
+ * How many characters of one stderr read the stdio transport puts in the
110
+ * record it reports it with.
111
+ *
112
+ * stderr is logged a read at a time, so a server that floods its error
113
+ * stream writes one record per read and the operator's terminal is where
114
+ * that lands. Reading the whole chunk can put tens of kilobytes of a
115
+ * server's text into a single record; the head says what arrived, and the
116
+ * full length travels beside it so nothing is claimed to be complete when it
117
+ * is not.
118
+ */
119
+ export const MCP_STDIO_STDERR_LOG_CHARS = 500
120
+
90
121
  /** JSON-RPC 2.0 reserved code for parameters the receiver cannot accept. */
91
122
  export const JSON_RPC_INVALID_PARAMS = -32602
92
123
 
@@ -1085,6 +1085,13 @@ export class AgentManager {
1085
1085
  } catch (writeError) {
1086
1086
  failure = writeError
1087
1087
  }
1088
+ // The child has stopped working in its checkout, whatever keeps that
1089
+ // checkout next. Released BEFORE the parent hears the child idle: a
1090
+ // listener that removes the kept checkout must not be refused by a
1091
+ // holder that has already ended, which is what a cancelled child
1092
+ // used to leave behind — the cancellation marked the task terminal,
1093
+ // and the cleanup below it ran only after the idle event.
1094
+ await this.releaseChildWorkspace(spawnRecord)
1088
1095
  // The child's turn is over either way; its parent hears so first.
1089
1096
  await this.settleChildSession(
1090
1097
  runningTask,
@@ -2397,10 +2404,44 @@ export class AgentManager {
2397
2404
  await this.disposeChildWorkspace(spawnRecord)
2398
2405
  }
2399
2406
 
2407
+ /**
2408
+ * Tell the driver the child stopped working in its checkout.
2409
+ *
2410
+ * Every path a child ends by has to reach this before anything decides what
2411
+ * happens to that checkout: success and failure through
2412
+ * `disposeChildWorkspace`, and a cancelled child from the run's rejection,
2413
+ * before its parent hears the child idle. A driver that publishes who is
2414
+ * working in a checkout then stops naming a session that has ended, even
2415
+ * when the checkout itself is kept.
2416
+ *
2417
+ * Never throws. A release that fails is logged: the child's work is already
2418
+ * done, and a stale holding is an operator's problem, not the child's result.
2419
+ */
2420
+ private async releaseChildWorkspace(
2421
+ spawnRecord: Pick<ChildSpawnRecord, 'workspaceRef' | 'subSessionId'>,
2422
+ ): Promise<void> {
2423
+ if (!spawnRecord.workspaceRef) return
2424
+ const backend = spawnRecord.workspaceRef.meta.backend
2425
+ if (!this.deps.workspaceRegistry.has(backend)) return
2426
+ const driver = this.deps.workspaceRegistry.get(backend)
2427
+ if (!driver.release) return
2428
+ await driver.release(spawnRecord.workspaceRef).catch((releaseErr) => {
2429
+ this.log.warn('Workspace release failed', {
2430
+ 'namzu.manager.backend': backend,
2431
+ 'namzu.manager.workspace_id': spawnRecord.workspaceRef?.id,
2432
+ 'namzu.sub_session.id': spawnRecord.subSessionId,
2433
+ 'exception.message': toErrorMessage(releaseErr),
2434
+ })
2435
+ })
2436
+ }
2437
+
2400
2438
  /**
2401
2439
  * Release the workspace this manager provisioned for a child.
2402
2440
  *
2403
- * Called on every terminal path, success included. `has(backend)` before
2441
+ * Called on every terminal path, success included, and it tells the driver
2442
+ * the child stopped working in its checkout before deciding whether to keep
2443
+ * it: a checkout that is kept must not go on claiming a live holder.
2444
+ * `has(backend)` before
2404
2445
  * `get(backend)` because the registry is deny-by-default and throws on an
2405
2446
  * unknown kind — a driver deregistered mid-turn must not turn cleanup into
2406
2447
  * an exception on a child that already finished.
@@ -2414,10 +2455,17 @@ export class AgentManager {
2414
2455
  private async disposeChildWorkspace(
2415
2456
  spawnRecord: Pick<ChildSpawnRecord, 'workspaceRef' | 'workspaceRetention' | 'subSessionId'>,
2416
2457
  ): Promise<void> {
2417
- if (spawnRecord.workspaceRetention === 'retain') return
2418
2458
  if (!spawnRecord.workspaceRef) return
2419
2459
  const backend = spawnRecord.workspaceRef.meta.backend
2420
2460
  if (!this.deps.workspaceRegistry.has(backend)) return
2461
+ const driver = this.deps.workspaceRegistry.get(backend)
2462
+ // The child has ended, so it stops working in its checkout whatever this
2463
+ // does with that checkout next. Told here, BEFORE the retention returns
2464
+ // below: both of those keep the checkout, and a kept checkout must not go
2465
+ // on claiming a holder that finished — that is a removal refused later for
2466
+ // a session that is gone.
2467
+ await this.releaseChildWorkspace(spawnRecord)
2468
+ if (spawnRecord.workspaceRetention === 'retain') return
2421
2469
  if (spawnRecord.workspaceRetention === 'retain-changed') {
2422
2470
  // Keep the checkout unless it provably holds nothing. A look that fails,
2423
2471
  // or a backend that cannot say whether it moved, keeps it too.
@@ -2435,17 +2483,14 @@ export class AgentManager {
2435
2483
  if (!seen) return
2436
2484
  if (seen.exists && (seen.isDirty || seen.hasNewCommits !== false)) return
2437
2485
  }
2438
- await this.deps.workspaceRegistry
2439
- .get(backend)
2440
- .dispose(spawnRecord.workspaceRef)
2441
- .catch((disposeErr) => {
2442
- this.log.warn('Workspace dispose failed', {
2443
- 'namzu.manager.backend': backend,
2444
- 'namzu.manager.workspace_id': spawnRecord.workspaceRef?.id,
2445
- 'namzu.sub_session.id': spawnRecord.subSessionId,
2446
- 'exception.message': toErrorMessage(disposeErr),
2447
- })
2486
+ await driver.dispose(spawnRecord.workspaceRef).catch((disposeErr) => {
2487
+ this.log.warn('Workspace dispose failed', {
2488
+ 'namzu.manager.backend': backend,
2489
+ 'namzu.manager.workspace_id': spawnRecord.workspaceRef?.id,
2490
+ 'namzu.sub_session.id': spawnRecord.subSessionId,
2491
+ 'exception.message': toErrorMessage(disposeErr),
2448
2492
  })
2493
+ })
2449
2494
  }
2450
2495
 
2451
2496
  private markCanceled(taskId: TaskId, cause?: CancelCause): void {
@@ -68,11 +68,14 @@ export {
68
68
  } from './shell-hook-tool-names.js'
69
69
  export type {
70
70
  HttpHookEntry,
71
+ McpToolHookEntry,
71
72
  PromptHookEntry,
72
73
  ShellHookEntry,
73
74
  ShellHookEvent,
74
75
  ShellHookHandler,
75
76
  ShellHookJudge,
77
+ ShellHookMcpToolAnswer,
78
+ ShellHookMcpToolCaller,
76
79
  ShellHookOnFailure,
77
80
  ShellHookCall,
78
81
  ShellHookInput,
@@ -351,8 +351,22 @@ export interface PromptHookEntry extends ShellHookEntryBase {
351
351
  readonly prompt: string
352
352
  }
353
353
 
354
+ /** One call to a tool on a connected tool server, at one event. */
355
+ export interface McpToolHookEntry extends ShellHookEntryBase {
356
+ readonly type: 'mcp_tool'
357
+ /** The server to call, by its name in the tool-server config. */
358
+ readonly server: string
359
+ /** The tool to call, by the name the server itself reports (no `mcp__` prefix). */
360
+ readonly tool: string
361
+ /**
362
+ * The arguments the tool is called with, as one JSON object. Absent, the
363
+ * tool is called with none.
364
+ */
365
+ readonly arguments?: Readonly<Record<string, unknown>>
366
+ }
367
+
354
368
  /** Any hook entry a config may carry. */
355
- export type ShellHookHandler = ShellHookEntry | HttpHookEntry | PromptHookEntry
369
+ export type ShellHookHandler = ShellHookEntry | HttpHookEntry | PromptHookEntry | McpToolHookEntry
356
370
 
357
371
  /** Event → entries, the shape a host's config file carries. */
358
372
  export type ShellHooksConfig = {
@@ -2027,10 +2041,11 @@ export function shellHookVerdict(
2027
2041
  }
2028
2042
  }
2029
2043
 
2030
- /** A short name for a hook in logs: its command, its url, or the start of its prompt. */
2044
+ /** A short name for a hook in logs: its command, its url, the tool it calls, or the start of its prompt. */
2031
2045
  export function describeShellHook(entry: ShellHookHandler): string {
2032
2046
  if (entry.type === 'http') return entry.url
2033
2047
  if (entry.type === 'prompt') return `prompt: ${entry.prompt.slice(0, 80)}`
2048
+ if (entry.type === 'mcp_tool') return `mcp: ${entry.server}/${entry.tool}`
2034
2049
  return entry.command
2035
2050
  }
2036
2051
 
@@ -2052,9 +2067,40 @@ export type ShellHookJudge = (request: {
2052
2067
  readonly signal: AbortSignal
2053
2068
  }) => Promise<string | undefined>
2054
2069
 
2070
+ /**
2071
+ * What one `mcp_tool` call came back with. `ok` false is a call the server
2072
+ * refused or that failed; `output` is the text of a successful one, read
2073
+ * exactly as a command hook's stdout is (its JSON answer included).
2074
+ */
2075
+ export interface ShellHookMcpToolAnswer {
2076
+ readonly ok: boolean
2077
+ readonly output: string
2078
+ readonly error?: string
2079
+ }
2080
+
2081
+ /**
2082
+ * Calls one tool on one connected tool server and returns its answer, or
2083
+ * `undefined` when no connected server has that tool. The host supplies it:
2084
+ * the kernel does not own the servers a session is connected to. It should
2085
+ * honour `signal`.
2086
+ */
2087
+ export type ShellHookMcpToolCaller = (request: {
2088
+ readonly server: string
2089
+ readonly tool: string
2090
+ readonly arguments: Readonly<Record<string, unknown>>
2091
+ readonly sessionId: string
2092
+ readonly turnId?: string
2093
+ readonly signal: AbortSignal
2094
+ }) => Promise<ShellHookMcpToolAnswer | undefined>
2095
+
2055
2096
  export interface ShellHookOptions {
2056
2097
  /** Answers `prompt` hooks. Without it a `prompt` hook is logged and lets the action go ahead. */
2057
2098
  readonly judge?: ShellHookJudge
2099
+ /**
2100
+ * Calls the tool an `mcp_tool` hook names. Without it such a hook is
2101
+ * reported as a failure, which `onFailure: block` counts as a refusal.
2102
+ */
2103
+ readonly mcpToolCall?: ShellHookMcpToolCaller
2058
2104
  /** Where the command runs and what `cwd` says on stdin. */
2059
2105
  readonly cwd: string
2060
2106
  readonly log?: Logger
@@ -2220,11 +2266,79 @@ function readJudgement(reply: string): { ok: boolean; reason: string } | undefin
2220
2266
  }
2221
2267
  }
2222
2268
 
2269
+ /**
2270
+ * An `mcp_tool` hook: the host calls the named tool on the named server, and
2271
+ * its answer is read exactly as a command hook's stdout is. A call that
2272
+ * cannot be made — no caller, no such server or tool, a refused or failed
2273
+ * call, the deadline — is the hook's own failure, which `onFailure: block`
2274
+ * counts as a refusal.
2275
+ */
2276
+ async function runMcpToolHook(
2277
+ entry: McpToolHookEntry,
2278
+ input: ShellHookInput,
2279
+ call: ShellHookMcpToolCaller | undefined,
2280
+ signal: AbortSignal | undefined,
2281
+ log: Logger,
2282
+ ): Promise<ShellHookOutcome> {
2283
+ const where = describeShellHook(entry)
2284
+ if (call === undefined) {
2285
+ return {
2286
+ exitCode: null,
2287
+ timedOut: false,
2288
+ stdout: '',
2289
+ stderr: '',
2290
+ spawnError: `no connected tool server is reachable, so ${where} was not called`,
2291
+ }
2292
+ }
2293
+ const deadline = AbortSignal.timeout(hookTimeout(entry))
2294
+ const combined = signal ? AbortSignal.any([signal, deadline]) : deadline
2295
+ let answer: ShellHookMcpToolAnswer | undefined
2296
+ try {
2297
+ answer = await call({
2298
+ server: entry.server,
2299
+ tool: entry.tool,
2300
+ arguments: entry.arguments ?? {},
2301
+ sessionId: input.sessionId,
2302
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
2303
+ signal: combined,
2304
+ })
2305
+ } catch (error) {
2306
+ log.warn('mcp tool hook failed', {
2307
+ 'namzu.hook.event': input.event,
2308
+ 'namzu.hook.command': where,
2309
+ 'namzu.hook.error': error instanceof Error ? error.message : String(error),
2310
+ })
2311
+ return {
2312
+ exitCode: 1,
2313
+ timedOut: deadline.aborted,
2314
+ stdout: '',
2315
+ stderr: error instanceof Error ? error.message : String(error),
2316
+ }
2317
+ }
2318
+ if (answer === undefined) {
2319
+ return {
2320
+ exitCode: 1,
2321
+ timedOut: deadline.aborted,
2322
+ stdout: '',
2323
+ stderr: `no connected server named ${entry.server} offers a tool named ${entry.tool}`,
2324
+ }
2325
+ }
2326
+ if (!answer.ok) {
2327
+ return {
2328
+ exitCode: 1,
2329
+ timedOut: deadline.aborted,
2330
+ stdout: '',
2331
+ stderr: answer.error ?? 'the tool call failed',
2332
+ }
2333
+ }
2334
+ return { exitCode: 0, timedOut: false, stdout: answer.output, stderr: '' }
2335
+ }
2336
+
2223
2337
  /**
2224
2338
  * One run of a `worktree_create` or `worktree_remove` hook, to its answer. It
2225
2339
  * is always awaited (an `async` flag cannot make a hook that does the work run
2226
- * out of sight), and a `prompt` hook cannot do it at all, which is said as a
2227
- * failure rather than skipped.
2340
+ * out of sight), and a `prompt` or `mcp_tool` hook cannot do it at all, which
2341
+ * is said as a failure rather than skipped.
2228
2342
  */
2229
2343
  async function runWorktreeHook(
2230
2344
  event: 'worktree_create' | 'worktree_remove',
@@ -2234,10 +2348,10 @@ async function runWorktreeHook(
2234
2348
  reportTimeout: (timedOut: boolean) => void,
2235
2349
  ): Promise<PluginHookResult> {
2236
2350
  const label = describeShellHook(entry)
2237
- if (entry.type === 'prompt') {
2351
+ if (entry.type === 'prompt' || entry.type === 'mcp_tool') {
2238
2352
  return {
2239
2353
  action: 'error',
2240
- message: `The ${event} hook \`${label}\` is a prompt, and a prompt cannot make or remove a worktree. Use a command or an http hook.`,
2354
+ message: `The ${event} hook \`${label}\` is a ${entry.type} hook, and it cannot make or remove a worktree. Use a command or an http hook.`,
2241
2355
  }
2242
2356
  }
2243
2357
  if (entry.type === 'http') {
@@ -2499,6 +2613,17 @@ export function createShellHook(
2499
2613
  if (entry.type === 'prompt') {
2500
2614
  return judgePromptHook(event, entry, hookInput, options.judge, context.signal, log)
2501
2615
  }
2616
+ if (entry.type === 'mcp_tool') {
2617
+ const outcome = await runMcpToolHook(
2618
+ entry,
2619
+ hookInput,
2620
+ options.mcpToolCall,
2621
+ context.signal,
2622
+ log,
2623
+ )
2624
+ reportTimeout(outcome.timedOut)
2625
+ return shellHookVerdict(event, entry, outcome, log, verdictCall)
2626
+ }
2502
2627
  if (entry.async === true) {
2503
2628
  // Started and left running: it decides nothing, so nothing waits
2504
2629
  // for it and its own failure is only written down.
@@ -96,6 +96,7 @@ export type {
96
96
 
97
97
  export type {
98
98
  CodeNavigationProvider,
99
+ CodeNavigationRequestOptions,
99
100
  CodeNavigationResult,
100
101
  HoverResult,
101
102
  SourceLocation,
@@ -1398,6 +1399,10 @@ export type { VaultInstrumentationOptions } from './vault/instrumentation.js'
1398
1399
 
1399
1400
  export {
1400
1401
  GitWorktreeDriver,
1402
+ DiskWorkspaceHoldStore,
1403
+ WorkspaceInUseError,
1404
+ defaultWorkspaceHoldsDir,
1405
+ defaultWorktreesDir,
1401
1406
  HookedWorkspaceDriver,
1402
1407
  WorktreeHookError,
1403
1408
  worktreeHookHost,
@@ -243,11 +243,14 @@ export type {
243
243
  } from './agents/file-definitions.js'
244
244
  export type {
245
245
  HttpHookEntry,
246
+ McpToolHookEntry,
246
247
  PromptHookEntry,
247
248
  ShellHookEntry,
248
249
  ShellHookEvent,
249
250
  ShellHookHandler,
250
251
  ShellHookJudge,
252
+ ShellHookMcpToolAnswer,
253
+ ShellHookMcpToolCaller,
251
254
  ShellHookOnFailure,
252
255
  ShellHookCall,
253
256
  ShellHookInput,
@@ -284,6 +287,10 @@ export type {
284
287
  export type {
285
288
  RegisterSharedSessionPlanInput,
286
289
  SharedSessionWorkspaceConfig,
290
+ DiskWorkspaceHoldStoreOptions,
291
+ WorkspaceHold,
292
+ WorkspaceHoldRequest,
293
+ WorkspaceHoldStore,
287
294
  } from './session/workspace/index.js'
288
295
 
289
296
  export type {
@@ -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 (