@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,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,
@@ -15,6 +19,7 @@ import {
15
19
  readEnvironmentEntry,
16
20
  setEnvironmentEntry,
17
21
  } from '../../utils/process-environment.js'
22
+ import { resolveStdioProgram } from './stdio-program.js'
18
23
 
19
24
  /**
20
25
  * How long a child gets to honour SIGTERM before SIGKILL. Two seconds is
@@ -105,6 +110,12 @@ export class StdioTransport implements MCPTransport {
105
110
  /** True between kill and the process's own `close` event. */
106
111
  private exitPending = false
107
112
  private buffer = ''
113
+ /**
114
+ * True once the pending line has been refused for length. Everything up
115
+ * to the next newline is then dropped, so one over-long line costs one
116
+ * report and no memory rather than one report per read.
117
+ */
118
+ private discardingOverlongLine = false
108
119
  private log: Logger
109
120
 
110
121
  constructor(
@@ -122,10 +133,12 @@ export class StdioTransport implements MCPTransport {
122
133
  if (this.process) await this.close()
123
134
  const generation = ++this.generation
124
135
  this.retired = false
125
- this.buffer = ''
136
+ this.resetLineBuffer()
126
137
 
127
- const child = spawn(this.config.command, this.config.args ?? [], {
128
- env: buildChildEnv(this.config),
138
+ // `npx` and `node` run on the app's own tools when the app declares them (stdio-program.ts).
139
+ const program = resolveStdioProgram(this.config.command, this.config.args ?? [])
140
+ const child = spawn(program.command, program.args, {
141
+ env: { ...buildChildEnv(this.config), ...program.env },
129
142
  cwd: this.config.cwd,
130
143
  stdio: ['pipe', 'pipe', 'pipe'],
131
144
  })
@@ -141,8 +154,14 @@ export class StdioTransport implements MCPTransport {
141
154
  child.stdout?.once('error', (err) => this.retire(generation, 'error', err))
142
155
 
143
156
  child.stderr?.on('data', (chunk: Buffer) => {
157
+ // One record per read, so the read's text is bounded here: a server
158
+ // that floods its error stream otherwise puts the whole of it on
159
+ // the terminal, a read at a time. The length travels beside the
160
+ // head so the record says how much it is not showing.
161
+ const text = chunk.toString('utf-8').trim()
144
162
  this.log.warn('MCP server stderr', {
145
- 'namzu.mcp.stderr': chunk.toString('utf-8').trim(),
163
+ 'namzu.mcp.stderr': text.slice(0, MCP_STDIO_STDERR_LOG_CHARS),
164
+ 'namzu.mcp.stderr_chars': text.length,
146
165
  })
147
166
  })
148
167
 
@@ -178,7 +197,7 @@ export class StdioTransport implements MCPTransport {
178
197
  this.exitPending = true
179
198
  const child = this.process
180
199
  this.process = null
181
- this.buffer = ''
200
+ this.resetLineBuffer()
182
201
 
183
202
  // Resolve when the child is actually gone, not when the signal was
184
203
  // sent. `kill()` returns as soon as the signal is delivered, so an
@@ -235,6 +254,16 @@ export class StdioTransport implements MCPTransport {
235
254
  this.errorHandlers = []
236
255
  }
237
256
 
257
+ /**
258
+ * Drop the framing state of a protocol session that ended or is being
259
+ * replaced. Keeping either half across generations would let a refused
260
+ * line swallow the first bytes of the next one.
261
+ */
262
+ private resetLineBuffer(): void {
263
+ this.buffer = ''
264
+ this.discardingOverlongLine = false
265
+ }
266
+
238
267
  /**
239
268
  * Publish one terminal result for the current response channel.
240
269
  *
@@ -247,7 +276,7 @@ export class StdioTransport implements MCPTransport {
247
276
  if (generation !== this.generation || this.retired) return
248
277
  this.retired = true
249
278
  this.connected = false
250
- this.buffer = ''
279
+ this.resetLineBuffer()
251
280
  const closeHandlers = this.closeHandlers
252
281
  const errorHandlers = this.errorHandlers
253
282
  this.clearHandlers()
@@ -289,8 +318,22 @@ export class StdioTransport implements MCPTransport {
289
318
  }
290
319
 
291
320
  private processBuffer(): void {
321
+ // An already-refused line is skipped to its terminator before anything
322
+ // else is read from the buffer. Without this the rest of that line
323
+ // would be re-buffered, re-measured and re-reported once per read,
324
+ // turning one bad line into an output flood of the transport's own.
325
+ if (this.discardingOverlongLine) {
326
+ const terminator = this.buffer.indexOf('\n')
327
+ if (terminator === -1) {
328
+ this.buffer = ''
329
+ return
330
+ }
331
+ this.buffer = this.buffer.slice(terminator + 1)
332
+ this.discardingOverlongLine = false
333
+ }
334
+
292
335
  const lines = this.buffer.split('\n')
293
- this.buffer = lines.pop() ?? ''
336
+ let pending = lines.pop() ?? ''
294
337
 
295
338
  for (const line of lines) {
296
339
  const trimmed = line.trim()
@@ -304,5 +347,16 @@ export class StdioTransport implements MCPTransport {
304
347
  })
305
348
  }
306
349
  }
350
+
351
+ if (pending.length > MCP_STDIO_MAX_PENDING_LINE_CHARS) {
352
+ this.discardingOverlongLine = true
353
+ this.log.warn('StdioTransport: dropping MCP server output past the pending-line ceiling', {
354
+ 'namzu.mcp.line_chars': pending.length,
355
+ 'namzu.mcp.line_ceiling': MCP_STDIO_MAX_PENDING_LINE_CHARS,
356
+ })
357
+ pending = ''
358
+ }
359
+
360
+ this.buffer = pending
307
361
  }
308
362
  }
@@ -1,5 +1,9 @@
1
1
  import { lookup } from 'node:dns/promises'
2
+ import { request as httpRequest } from 'node:http'
3
+ import { request as httpsRequest } from 'node:https'
2
4
  import { isIP } from 'node:net'
5
+ import { Readable } from 'node:stream'
6
+ import { createBrotliDecompress, createGunzip, createInflate } from 'node:zlib'
3
7
 
4
8
  import {
5
9
  ConnectorHttpOperation,
@@ -174,17 +178,37 @@ export function isPrivateAddress(address: string): boolean {
174
178
  */
175
179
  export async function privateAddressProblem(
176
180
  hostname: string,
177
- options: {
178
- readonly resolve?: (hostname: string, signal?: AbortSignal) => Promise<readonly string[]>
179
- readonly signal?: AbortSignal
180
- /**
181
- * The request goes out through a proxy, which resolves the name itself: this machine failing
182
- * to resolve it says nothing about where it points, so that failure is not a refusal. A name
183
- * that does resolve here is still checked, and a literal address always is.
184
- */
185
- readonly proxied?: boolean
186
- } = {},
181
+ options: AddressCheckOptions = {},
187
182
  ): Promise<string | undefined> {
183
+ return (await checkedAddresses(hostname, options)).problem
184
+ }
185
+
186
+ export interface AddressCheckOptions {
187
+ readonly resolve?: (hostname: string, signal?: AbortSignal) => Promise<readonly string[]>
188
+ readonly signal?: AbortSignal
189
+ /**
190
+ * The request goes out through a proxy, which resolves the name itself: this machine failing
191
+ * to resolve it says nothing about where it points, so that failure is not a refusal. A name
192
+ * that does resolve here is still checked, and a literal address always is.
193
+ */
194
+ readonly proxied?: boolean
195
+ }
196
+
197
+ /**
198
+ * The same check as {@link privateAddressProblem}, with the addresses it looked at.
199
+ *
200
+ * A caller that connects itself passes `addresses` to {@link pinnedFetch} (or
201
+ * {@link pinnedLookup}), so the connection goes to what was checked and the
202
+ * name is not resolved a second time: a name that answers publicly to the
203
+ * check and privately to the connection (DNS rebinding) then has no second
204
+ * answer to differ. `addresses` is empty when there is a `problem`, and when
205
+ * the request goes through a proxy and this machine could not resolve the
206
+ * name (the proxy resolves it, and there is nothing to pin).
207
+ */
208
+ export async function checkedAddresses(
209
+ hostname: string,
210
+ options: AddressCheckOptions = {},
211
+ ): Promise<{ readonly problem?: string; readonly addresses: readonly string[] }> {
188
212
  const name = hostname.toLowerCase().replace(/^\[|\]$/g, '')
189
213
  let addresses: readonly string[]
190
214
  if (isIP(name) !== 0) {
@@ -196,16 +220,142 @@ export async function privateAddressProblem(
196
220
  try {
197
221
  addresses = await resolve(name, options.signal)
198
222
  } catch (error) {
199
- if (options.proxied === true && !options.signal?.aborted) return undefined
200
- return `${name} could not be resolved (${error instanceof Error ? error.message : String(error)}), so nothing here can say where it points`
223
+ if (options.proxied === true && !options.signal?.aborted) return { addresses: [] }
224
+ return {
225
+ problem: `${name} could not be resolved (${error instanceof Error ? error.message : String(error)}), so nothing here can say where it points`,
226
+ addresses: [],
227
+ }
201
228
  }
202
- if (addresses.length === 0) return `${name} resolves to no addresses`
229
+ if (addresses.length === 0)
230
+ return { problem: `${name} resolves to no addresses`, addresses: [] }
203
231
  }
204
232
  for (const address of addresses) {
205
233
  if (isPrivateAddress(address))
206
- return `${name} resolves to ${address}, inside this host's own network`
234
+ return {
235
+ problem: `${name} resolves to ${address}, inside this host's own network`,
236
+ addresses: [],
237
+ }
238
+ }
239
+ return { addresses }
240
+ }
241
+
242
+ /**
243
+ * A `lookup` for a socket that answers with the addresses that were checked
244
+ * and nothing else. The URL still names the host, so TLS keeps its SNI and
245
+ * its certificate check on the hostname and not on an address, and the
246
+ * `Host` header is the name the caller wrote.
247
+ */
248
+ export function pinnedLookup(
249
+ addresses: readonly { readonly address: string; readonly family: 4 | 6 }[],
250
+ ) {
251
+ return (
252
+ _hostname: string,
253
+ options: { all?: boolean; family?: number | string } | undefined,
254
+ callback: (
255
+ error: NodeJS.ErrnoException | null,
256
+ address: string | { address: string; family: number }[],
257
+ family?: number,
258
+ ) => void,
259
+ ): void => {
260
+ // A caller that wants one family gets that family's addresses; asking for
261
+ // one we hold none of is an error rather than a fall back to DNS.
262
+ const wanted = options?.family === 4 || options?.family === 6 ? options.family : undefined
263
+ const usable = wanted === undefined ? addresses : addresses.filter((a) => a.family === wanted)
264
+ const first = usable[0]
265
+ if (first === undefined) {
266
+ const error: NodeJS.ErrnoException = new Error('no vetted address of that family')
267
+ error.code = 'ENOTFOUND'
268
+ callback(error, '', 0)
269
+ return
270
+ }
271
+ if (options?.all === true) {
272
+ callback(
273
+ null,
274
+ usable.map((a) => ({ address: a.address, family: a.family })),
275
+ )
276
+ return
277
+ }
278
+ callback(null, first.address, first.family)
207
279
  }
208
- return undefined
280
+ }
281
+
282
+ export interface PinnedRequest {
283
+ readonly method?: string
284
+ readonly headers?: Readonly<Record<string, string>>
285
+ readonly body?: string
286
+ readonly signal?: AbortSignal
287
+ }
288
+
289
+ /**
290
+ * One request that connects to `addresses` (the ones a check looked at) and
291
+ * never asks DNS. Redirects are not followed: each hop is a new call with its
292
+ * own check. The body is decoded the way `fetch` decodes it (gzip, deflate,
293
+ * brotli), so the `Response` reads the same.
294
+ *
295
+ * It does not go through the process-wide proxy and client-certificate setup
296
+ * that the platform `fetch` uses, so a caller behind a proxy keeps using
297
+ * `fetch` (the proxy resolves the name, and there is no address to pin).
298
+ */
299
+ export function pinnedFetch(
300
+ url: URL,
301
+ init: PinnedRequest,
302
+ addresses: readonly string[],
303
+ ): Promise<Response> {
304
+ return new Promise<Response>((resolve, reject) => {
305
+ const send = url.protocol === 'https:' ? httpsRequest : httpRequest
306
+ const lookupFor = pinnedLookup(
307
+ addresses.map((address) => ({ address, family: isIP(address) === 6 ? 6 : 4 })),
308
+ )
309
+ const headers: Record<string, string> = { 'accept-encoding': 'gzip, deflate, br' }
310
+ for (const [key, value] of Object.entries(init.headers ?? {}))
311
+ headers[key.toLowerCase()] = value
312
+ const req = send(
313
+ url,
314
+ {
315
+ method: init.method ?? 'GET',
316
+ headers,
317
+ lookup: lookupFor as never,
318
+ ...(init.signal ? { signal: init.signal } : {}),
319
+ },
320
+ (res) => {
321
+ const answered = new Headers()
322
+ for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
323
+ answered.append(res.rawHeaders[i] as string, res.rawHeaders[i + 1] as string)
324
+ }
325
+ const status = res.statusCode ?? 502
326
+ if (status < 200 || status === 204 || status === 205 || status === 304) {
327
+ res.resume()
328
+ resolve(new Response(null, { status, headers: answered }))
329
+ return
330
+ }
331
+ const encoding = (res.headers['content-encoding'] ?? '').toLowerCase().trim()
332
+ const decoder =
333
+ encoding === 'gzip' || encoding === 'x-gzip'
334
+ ? createGunzip()
335
+ : encoding === 'deflate'
336
+ ? createInflate()
337
+ : encoding === 'br'
338
+ ? createBrotliDecompress()
339
+ : undefined
340
+ let source: Readable = res
341
+ if (decoder) {
342
+ answered.delete('content-encoding')
343
+ answered.delete('content-length')
344
+ res.on('error', (error) => decoder.destroy(error))
345
+ source = res.pipe(decoder)
346
+ }
347
+ resolve(
348
+ new Response(Readable.toWeb(source) as unknown as ReadableStream<Uint8Array>, {
349
+ status,
350
+ headers: answered,
351
+ }),
352
+ )
353
+ },
354
+ )
355
+ req.on('error', reject)
356
+ if (init.body !== undefined) req.write(init.body)
357
+ req.end()
358
+ })
209
359
  }
210
360
 
211
361
  /** Whether a proxy variable holds an http or https proxy address (what the client library uses). */
@@ -297,7 +447,10 @@ export class GuardedFetchProvider implements WebFetchProvider {
297
447
  * `302 -> http://169.254.169.254/`, and a fetch that validated only what
298
448
  * the caller typed follows it happily.
299
449
  */
300
- private async assertAllowed(rawUrl: string, operation: ConnectorHttpOperation): Promise<URL> {
450
+ private async assertAllowed(
451
+ rawUrl: string,
452
+ operation: ConnectorHttpOperation,
453
+ ): Promise<{ readonly url: URL; readonly addresses?: readonly string[] }> {
301
454
  operation.throwIfStopped()
302
455
  let url: URL
303
456
  try {
@@ -329,18 +482,17 @@ export class GuardedFetchProvider implements WebFetchProvider {
329
482
 
330
483
  if (this.config.allowPrivateAddresses === true) {
331
484
  operation.throwIfStopped()
332
- return url
485
+ return { url }
333
486
  }
334
487
 
335
488
  // RESOLVED, not just parsed. A hostname check alone is bypassed by any
336
489
  // name whose A record points inside — which is a thing anyone can set
337
490
  // up on a domain they own, and costs nothing to try.
338
491
  //
339
- // The residual gap is stated rather than hidden: between this lookup
340
- // and the connection, the name can be re-resolved to something else
341
- // (DNS rebinding). Closing that needs the fetch to pin the address it
342
- // checked, which the platform `fetch` gives no way to do. A host that
343
- // needs that guarantee supplies its own `fetch` that does.
492
+ // The addresses checked here are the ones the connection is pinned to
493
+ // (see `fetch`): the name is resolved once per hop, so a name that
494
+ // answers publicly now and privately on the connection's own lookup
495
+ // (DNS rebinding) has no second answer to differ.
344
496
  const resolve =
345
497
  this.config.resolve ??
346
498
  (async (name: string) => (await lookup(name, { all: true })).map((r) => r.address))
@@ -382,7 +534,7 @@ export class GuardedFetchProvider implements WebFetchProvider {
382
534
  }
383
535
  }
384
536
  operation.throwIfStopped()
385
- return url
537
+ return { url, addresses }
386
538
  }
387
539
 
388
540
  async fetch(request: WebFetchRequest): Promise<WebFetchResult> {
@@ -401,7 +553,7 @@ export class GuardedFetchProvider implements WebFetchProvider {
401
553
 
402
554
  const redirects: string[] = []
403
555
  let redirectsFollowed = 0
404
- let current = await this.assertAllowed(request.url, operation)
556
+ let { url: current, addresses: pinned } = await this.assertAllowed(request.url, operation)
405
557
 
406
558
  for (;;) {
407
559
  operation.throwIfStopped()
@@ -411,12 +563,24 @@ export class GuardedFetchProvider implements WebFetchProvider {
411
563
  // the platform follow redirects is exactly the hole this class
412
564
  // exists to close: it would land on the final URL having never
413
565
  // asked whether that URL was allowed.
566
+ //
567
+ // The connection goes to the addresses that were checked. The default
568
+ // transport connects to them by address and keeps the name for the
569
+ // `Host` header and TLS; an injected `fetch` is handed them as
570
+ // `pinnedAddresses`, so a host that brings its own client can pin too.
571
+ const target = current
572
+ const addresses = pinned
414
573
  const response = await operation.run(() =>
415
- doFetch(current, {
416
- headers,
417
- redirect: 'manual',
418
- signal: operation.signal,
419
- }),
574
+ this.config.fetch === undefined &&
575
+ addresses !== undefined &&
576
+ !proxyConfigured(process.env, target.hostname)
577
+ ? pinnedFetch(target, { headers, signal: operation.signal }, addresses)
578
+ : doFetch(target, {
579
+ headers,
580
+ redirect: 'manual',
581
+ signal: operation.signal,
582
+ ...(addresses !== undefined ? { pinnedAddresses: addresses } : {}),
583
+ } as RequestInit),
420
584
  )
421
585
 
422
586
  const location = response.headers.get('location')
@@ -464,7 +628,10 @@ export class GuardedFetchProvider implements WebFetchProvider {
464
628
  }
465
629
  }
466
630
  try {
467
- current = await this.assertAllowed(next.toString(), operation)
631
+ ;({ url: current, addresses: pinned } = await this.assertAllowed(
632
+ next.toString(),
633
+ operation,
634
+ ))
468
635
  } catch (err) {
469
636
  operation.throwIfStopped()
470
637
  if (err instanceof WebFetchRefusedError) {
@@ -4,11 +4,14 @@
4
4
  // design rather than an omission.
5
5
  export {
6
6
  GuardedFetchProvider,
7
+ checkedAddresses,
7
8
  isPrivateAddress,
9
+ pinnedFetch,
10
+ pinnedLookup,
8
11
  privateAddressProblem,
9
12
  proxyConfigured,
10
13
  } from './guarded-fetch.js'
11
- export type { GuardedFetchConfig } from './guarded-fetch.js'
14
+ export type { AddressCheckOptions, GuardedFetchConfig, PinnedRequest } from './guarded-fetch.js'
12
15
  export { WebFetchRefusedError } from './types.js'
13
16
  export type {
14
17
  WebContentExtractor,
@@ -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,
@@ -1733,7 +1740,7 @@ export class AgentManager {
1733
1740
  const driver = this.deps.workspaceRegistry.get(backend)
1734
1741
  workspaceDriver = driver
1735
1742
  workspaceRef = await driver.create({
1736
- label: subSession.id,
1743
+ label: (request?.mode === 'isolated' ? request.label : undefined) ?? subSession.id,
1737
1744
  ...(request?.mode === 'isolated' && request.baseRef ? { baseRef: request.baseRef } : {}),
1738
1745
  })
1739
1746
  if (request?.mode === 'isolated')
@@ -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 {