@namzu/sdk 71.1.0 → 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 (198) hide show
  1. package/CHANGELOG.md +32 -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/compaction/index.d.ts +1 -1
  6. package/dist/compaction/index.d.ts.map +1 -1
  7. package/dist/compaction/index.js +1 -1
  8. package/dist/compaction/index.js.map +1 -1
  9. package/dist/compaction/manual.d.ts +8 -0
  10. package/dist/compaction/manual.d.ts.map +1 -1
  11. package/dist/compaction/manual.js +18 -14
  12. package/dist/compaction/manual.js.map +1 -1
  13. package/dist/compaction/model-summary.d.ts +24 -6
  14. package/dist/compaction/model-summary.d.ts.map +1 -1
  15. package/dist/compaction/model-summary.js +108 -23
  16. package/dist/compaction/model-summary.js.map +1 -1
  17. package/dist/compaction/restore.d.ts +23 -0
  18. package/dist/compaction/restore.d.ts.map +1 -1
  19. package/dist/compaction/restore.js +59 -1
  20. package/dist/compaction/restore.js.map +1 -1
  21. package/dist/compaction/summary.d.ts +37 -2
  22. package/dist/compaction/summary.d.ts.map +1 -1
  23. package/dist/compaction/summary.js +46 -6
  24. package/dist/compaction/summary.js.map +1 -1
  25. package/dist/config/runtime.js +3 -3
  26. package/dist/config/runtime.js.map +1 -1
  27. package/dist/connector/index.d.ts +2 -2
  28. package/dist/connector/index.d.ts.map +1 -1
  29. package/dist/connector/index.js +1 -1
  30. package/dist/connector/index.js.map +1 -1
  31. package/dist/connector/mcp/client.d.ts +26 -6
  32. package/dist/connector/mcp/client.d.ts.map +1 -1
  33. package/dist/connector/mcp/client.js +49 -7
  34. package/dist/connector/mcp/client.js.map +1 -1
  35. package/dist/connector/mcp/index.d.ts +2 -0
  36. package/dist/connector/mcp/index.d.ts.map +1 -1
  37. package/dist/connector/mcp/index.js +1 -0
  38. package/dist/connector/mcp/index.js.map +1 -1
  39. package/dist/connector/mcp/sandbox-stdio.d.ts +67 -0
  40. package/dist/connector/mcp/sandbox-stdio.d.ts.map +1 -0
  41. package/dist/connector/mcp/sandbox-stdio.js +178 -0
  42. package/dist/connector/mcp/sandbox-stdio.js.map +1 -0
  43. package/dist/connector/mcp/stdio-program.d.ts +34 -0
  44. package/dist/connector/mcp/stdio-program.d.ts.map +1 -0
  45. package/dist/connector/mcp/stdio-program.js +47 -0
  46. package/dist/connector/mcp/stdio-program.js.map +1 -0
  47. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  48. package/dist/connector/mcp/stdio.js +5 -2
  49. package/dist/connector/mcp/stdio.js.map +1 -1
  50. package/dist/connector/web/guarded-fetch.d.ts +51 -2
  51. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  52. package/dist/connector/web/guarded-fetch.js +140 -19
  53. package/dist/connector/web/guarded-fetch.js.map +1 -1
  54. package/dist/connector/web/index.d.ts +2 -2
  55. package/dist/connector/web/index.d.ts.map +1 -1
  56. package/dist/connector/web/index.js +1 -1
  57. package/dist/connector/web/index.js.map +1 -1
  58. package/dist/manager/agent/lifecycle.js +1 -1
  59. package/dist/manager/agent/lifecycle.js.map +1 -1
  60. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  61. package/dist/plugin/hook-module/capabilities.js +24 -13
  62. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  63. package/dist/plugin/hook-module/host.d.ts +31 -0
  64. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  65. package/dist/plugin/hook-module/host.js +56 -13
  66. package/dist/plugin/hook-module/host.js.map +1 -1
  67. package/dist/plugin/hook-module/index.d.ts +3 -2
  68. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  69. package/dist/plugin/hook-module/index.js +2 -1
  70. package/dist/plugin/hook-module/index.js.map +1 -1
  71. package/dist/plugin/index.d.ts +1 -0
  72. package/dist/plugin/index.d.ts.map +1 -1
  73. package/dist/plugin/index.js +1 -0
  74. package/dist/plugin/index.js.map +1 -1
  75. package/dist/plugin/shell-hook-execute.d.ts +55 -0
  76. package/dist/plugin/shell-hook-execute.d.ts.map +1 -0
  77. package/dist/plugin/shell-hook-execute.js +73 -0
  78. package/dist/plugin/shell-hook-execute.js.map +1 -0
  79. package/dist/plugin/shell-hook-restrict.d.ts +31 -0
  80. package/dist/plugin/shell-hook-restrict.d.ts.map +1 -0
  81. package/dist/plugin/shell-hook-restrict.js +69 -0
  82. package/dist/plugin/shell-hook-restrict.js.map +1 -0
  83. package/dist/plugin/shell-hook.d.ts +29 -2
  84. package/dist/plugin/shell-hook.d.ts.map +1 -1
  85. package/dist/plugin/shell-hook.js +44 -12
  86. package/dist/plugin/shell-hook.js.map +1 -1
  87. package/dist/public-runtime.d.ts +7 -5
  88. package/dist/public-runtime.d.ts.map +1 -1
  89. package/dist/public-runtime.js +5 -4
  90. package/dist/public-runtime.js.map +1 -1
  91. package/dist/public-types.d.ts +2 -0
  92. package/dist/public-types.d.ts.map +1 -1
  93. package/dist/runtime/jobs/websocket-source.d.ts +2 -22
  94. package/dist/runtime/jobs/websocket-source.d.ts.map +1 -1
  95. package/dist/runtime/jobs/websocket-source.js +2 -33
  96. package/dist/runtime/jobs/websocket-source.js.map +1 -1
  97. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  98. package/dist/runtime/query/compact-session.js +5 -0
  99. package/dist/runtime/query/compact-session.js.map +1 -1
  100. package/dist/runtime/query/events.d.ts +7 -0
  101. package/dist/runtime/query/events.d.ts.map +1 -1
  102. package/dist/runtime/query/events.js +29 -11
  103. package/dist/runtime/query/events.js.map +1 -1
  104. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  105. package/dist/runtime/query/executor/tool-call-admission.js +51 -10
  106. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  107. package/dist/runtime/query/index.d.ts +6 -0
  108. package/dist/runtime/query/index.d.ts.map +1 -1
  109. package/dist/runtime/query/index.js +3 -0
  110. package/dist/runtime/query/index.js.map +1 -1
  111. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  112. package/dist/runtime/query/iteration/phases/compaction.js +21 -3
  113. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  114. package/dist/runtime/query/iteration/phases/context.d.ts +4 -0
  115. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  116. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  117. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  118. package/dist/scheduler/completion-inbox.js +15 -0
  119. package/dist/scheduler/completion-inbox.js.map +1 -1
  120. package/dist/store/session-index/index.d.ts +13 -0
  121. package/dist/store/session-index/index.d.ts.map +1 -1
  122. package/dist/store/session-index/index.js +1 -0
  123. package/dist/store/session-index/index.js.map +1 -1
  124. package/dist/store/session-index/rebuild.d.ts +12 -0
  125. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  126. package/dist/store/session-index/rebuild.js +20 -4
  127. package/dist/store/session-index/rebuild.js.map +1 -1
  128. package/dist/store/session-index/sqlite.d.ts +20 -0
  129. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  130. package/dist/store/session-index/sqlite.js +50 -12
  131. package/dist/store/session-index/sqlite.js.map +1 -1
  132. package/dist/tools/admit-facts.d.ts.map +1 -1
  133. package/dist/tools/admit-facts.js +59 -0
  134. package/dist/tools/admit-facts.js.map +1 -1
  135. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  136. package/dist/tools/coordinator/ask-user-question.js +67 -3
  137. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  138. package/dist/turn/memory-promoter.d.ts.map +1 -1
  139. package/dist/turn/memory-promoter.js +20 -4
  140. package/dist/turn/memory-promoter.js.map +1 -1
  141. package/dist/types/agent/base.d.ts +6 -0
  142. package/dist/types/agent/base.d.ts.map +1 -1
  143. package/dist/types/agent/task.d.ts +5 -0
  144. package/dist/types/agent/task.d.ts.map +1 -1
  145. package/dist/types/agent/task.js.map +1 -1
  146. package/dist/types/hitl/index.d.ts +8 -0
  147. package/dist/types/hitl/index.d.ts.map +1 -1
  148. package/dist/types/hitl/index.js.map +1 -1
  149. package/dist/types/message/index.d.ts +7 -0
  150. package/dist/types/message/index.d.ts.map +1 -1
  151. package/dist/types/message/index.js.map +1 -1
  152. package/dist/types/tool/presentation.d.ts +21 -0
  153. package/dist/types/tool/presentation.d.ts.map +1 -1
  154. package/package.json +6 -6
  155. package/src/agents/QueryAgent.ts +1 -0
  156. package/src/compaction/index.ts +1 -0
  157. package/src/compaction/manual.ts +48 -12
  158. package/src/compaction/model-summary.ts +118 -23
  159. package/src/compaction/restore.ts +74 -1
  160. package/src/compaction/summary.ts +69 -3
  161. package/src/config/runtime.ts +3 -3
  162. package/src/connector/index.ts +3 -0
  163. package/src/connector/mcp/client.ts +49 -7
  164. package/src/connector/mcp/index.ts +5 -0
  165. package/src/connector/mcp/sandbox-stdio.ts +214 -0
  166. package/src/connector/mcp/stdio-program.ts +68 -0
  167. package/src/connector/mcp/stdio.ts +5 -2
  168. package/src/connector/web/guarded-fetch.ts +197 -30
  169. package/src/connector/web/index.ts +4 -1
  170. package/src/manager/agent/lifecycle.ts +1 -1
  171. package/src/plugin/hook-module/capabilities.ts +36 -14
  172. package/src/plugin/hook-module/host.ts +86 -13
  173. package/src/plugin/hook-module/index.ts +3 -0
  174. package/src/plugin/index.ts +1 -0
  175. package/src/plugin/shell-hook-execute.ts +126 -0
  176. package/src/plugin/shell-hook-restrict.ts +66 -0
  177. package/src/plugin/shell-hook.ts +78 -10
  178. package/src/public-runtime.ts +14 -0
  179. package/src/public-types.ts +13 -0
  180. package/src/runtime/jobs/websocket-source.ts +2 -46
  181. package/src/runtime/query/compact-session.ts +5 -0
  182. package/src/runtime/query/events.ts +29 -11
  183. package/src/runtime/query/executor/tool-call-admission.ts +62 -17
  184. package/src/runtime/query/index.ts +10 -0
  185. package/src/runtime/query/iteration/phases/compaction.ts +26 -2
  186. package/src/runtime/query/iteration/phases/context.ts +6 -0
  187. package/src/scheduler/completion-inbox.ts +14 -0
  188. package/src/store/session-index/index.ts +14 -0
  189. package/src/store/session-index/rebuild.ts +22 -4
  190. package/src/store/session-index/sqlite.ts +63 -14
  191. package/src/tools/admit-facts.ts +64 -0
  192. package/src/tools/coordinator/ask-user-question.ts +88 -4
  193. package/src/turn/memory-promoter.ts +24 -3
  194. package/src/types/agent/base.ts +7 -0
  195. package/src/types/agent/task.ts +5 -0
  196. package/src/types/hitl/index.ts +8 -0
  197. package/src/types/message/index.ts +7 -0
  198. package/src/types/tool/presentation.ts +22 -0
@@ -0,0 +1,214 @@
1
+ import { StringDecoder } from 'node:string_decoder'
2
+ import type {
3
+ MCPJsonRpcMessage,
4
+ MCPTransport,
5
+ MCPTransportSendOptions,
6
+ } from '../../types/connector/index.js'
7
+ import type { SandboxStdioChannel, SandboxStdioOperation } from '../../types/sandbox/index.js'
8
+
9
+ type Channel = SandboxStdioChannel
10
+ type Operation = SandboxStdioOperation
11
+ const MAX_MESSAGE_BYTES = 16 * 1024 * 1024
12
+ // The allocation-owned channel admits each stdin write up to 1 MiB. Refuse a
13
+ // larger serialized request before reserving an effect barrier or delivering bytes.
14
+ const MAX_WRITE_BYTES = 1024 * 1024
15
+
16
+ /** What a host decided about one reply to an issued request. */
17
+ export interface SandboxStdioReplyVerdict {
18
+ /**
19
+ * True when the reply proves the request finished, so its effect barrier
20
+ * is released. False leaves the sandbox fenced: the outcome is unknown and
21
+ * the request must never be replayed.
22
+ */
23
+ readonly confirmed: boolean
24
+ /** Deliver this in place of the reply, e.g. to mark an unconfirmed outcome. */
25
+ readonly reply?: MCPJsonRpcMessage
26
+ }
27
+
28
+ export interface SandboxStdioTransportOptions {
29
+ /** Opens the guest process: typically `() => sandbox.openStdio(command, args, options)`. */
30
+ readonly open: () => Promise<SandboxStdioChannel>
31
+ /**
32
+ * Judge a reply that answers an issued request (`request` is undefined for
33
+ * an id this transport did not issue). The default treats every well-formed
34
+ * reply as exact, which is right for a server that reports no effects the
35
+ * channel cannot see.
36
+ */
37
+ readonly settleReply?: (
38
+ reply: MCPJsonRpcMessage,
39
+ request: { readonly method: string } | undefined,
40
+ ) => SandboxStdioReplyVerdict
41
+ /** Largest accepted JSON-RPC line from the server, in bytes. Defaults to 16 MiB. */
42
+ readonly maxMessageBytes?: number
43
+ }
44
+
45
+ /**
46
+ * MCP over a guest process's stdin and stdout, for a sandbox that implements
47
+ * `openStdio`. The server runs in the sandbox and never on the host: pass it
48
+ * to an `MCPClient` as `transportFactory: () => new SandboxStdioTransport({
49
+ * open })`. Closing the transport, or destroying the sandbox, stops the
50
+ * server.
51
+ *
52
+ * An idle server owns no sandbox input; each issued request holds the
53
+ * channel's effect barrier until its reply is seen, and a request whose
54
+ * outcome cannot be known (a failed write, a lost stream, a reply the
55
+ * `settleReply` hook refuses to confirm) is reported unknown and fences the
56
+ * sandbox rather than being replayed.
57
+ */
58
+ export class SandboxStdioTransport implements MCPTransport {
59
+ private channel?: Channel
60
+ private closing?: Promise<void>
61
+ private ended = false
62
+ private messageHandler?: (message: MCPJsonRpcMessage) => void
63
+ private closeHandler?: () => void
64
+ private errorHandler?: (error: Error) => void
65
+ private readonly pending = new Map<
66
+ string | number,
67
+ { operation: Operation; removeAbort(): void; method: string }
68
+ >()
69
+
70
+ private readonly open: () => Promise<Channel>
71
+ private readonly settleReply: NonNullable<SandboxStdioTransportOptions['settleReply']>
72
+ private readonly maxMessageBytes: number
73
+
74
+ constructor(options: SandboxStdioTransportOptions | (() => Promise<SandboxStdioChannel>)) {
75
+ const resolved = typeof options === 'function' ? { open: options } : options
76
+ this.open = resolved.open
77
+ this.settleReply = resolved.settleReply ?? (() => ({ confirmed: true }))
78
+ this.maxMessageBytes = resolved.maxMessageBytes ?? MAX_MESSAGE_BYTES
79
+ }
80
+
81
+ async connect(): Promise<void> {
82
+ if (this.channel || this.ended) throw new Error('This sandbox MCP transport cannot reconnect.')
83
+ this.channel = await this.open()
84
+ void this.read(this.channel).catch((error: unknown) => {
85
+ this.fail(error instanceof Error ? error : new Error(String(error)))
86
+ })
87
+ // EOF follows buffered stdout. Group exit can be observed before the reader
88
+ // drains its last positive reply, so only a failed close skips that drain.
89
+ void this.channel.closed.catch((error: unknown) =>
90
+ this.fail(error instanceof Error ? error : new Error(String(error))),
91
+ )
92
+ }
93
+
94
+ isConnected(): boolean {
95
+ return this.channel !== undefined && !this.ended && !this.closing
96
+ }
97
+ onMessage(handler: (message: MCPJsonRpcMessage) => void): void {
98
+ this.messageHandler = handler
99
+ }
100
+ onClose(handler: () => void): void {
101
+ this.closeHandler = handler
102
+ }
103
+ onError(handler: (error: Error) => void): void {
104
+ this.errorHandler = handler
105
+ }
106
+
107
+ async send(message: MCPJsonRpcMessage, options?: MCPTransportSendOptions): Promise<void> {
108
+ options?.signal?.throwIfAborted()
109
+ const channel = this.channel
110
+ if (!channel || !this.isConnected()) throw new Error('This sandbox MCP channel is closed.')
111
+ const data = `${JSON.stringify(message)}\n`
112
+ if (Buffer.byteLength(data) > MAX_WRITE_BYTES)
113
+ throw new Error('This sandbox MCP request exceeds the 1 MiB write limit; nothing was sent.')
114
+ const request = message.method !== undefined && message.id !== undefined
115
+ if (!request) {
116
+ await channel.write(data, options?.signal)
117
+ return
118
+ }
119
+ const id = message.id as string | number
120
+ if (this.pending.has(id)) throw new Error('This sandbox MCP request ID is already active.')
121
+ const operation = await channel.beginOperation(options?.signal)
122
+ // No bytes were handed to the channel on either of these paths.
123
+ if (options?.signal?.aborted || !this.isConnected()) {
124
+ operation.complete()
125
+ options?.signal?.throwIfAborted()
126
+ throw new Error('This sandbox MCP channel closed before dispatch.')
127
+ }
128
+ const onAbort = () => this.settle(id, false)
129
+ const entry = {
130
+ operation,
131
+ method: message.method as string,
132
+ removeAbort: () => options?.signal?.removeEventListener('abort', onAbort),
133
+ }
134
+ this.pending.set(id, entry)
135
+ options?.signal?.addEventListener('abort', onAbort, { once: true })
136
+ try {
137
+ await channel.write(data, options?.signal)
138
+ } catch (error) {
139
+ // A failed stdin acknowledgement cannot prove the editor did not receive it.
140
+ this.settle(id, false)
141
+ throw error
142
+ }
143
+ }
144
+
145
+ private settle(id: string | number, confirmed: boolean): void {
146
+ const entry = this.pending.get(id)
147
+ if (!entry) return
148
+ this.pending.delete(id)
149
+ entry.removeAbort()
150
+ if (confirmed) entry.operation.complete()
151
+ else entry.operation.outcomeUnknown()
152
+ }
153
+
154
+ private accept(line: string): void {
155
+ if (Buffer.byteLength(line) > this.maxMessageBytes)
156
+ throw new Error('This sandbox MCP reply exceeds the message limit.')
157
+ const message: unknown = JSON.parse(line)
158
+ if (!message || typeof message !== 'object' || Array.isArray(message))
159
+ throw new Error('This sandbox MCP server returned an invalid JSON-RPC message.')
160
+ let rpc = message as MCPJsonRpcMessage
161
+ if (rpc.jsonrpc !== '2.0') throw new Error('This sandbox MCP server returned invalid JSON-RPC.')
162
+ if (rpc.method === undefined && rpc.id !== undefined) {
163
+ if (Object.hasOwn(rpc, 'result') === Object.hasOwn(rpc, 'error'))
164
+ throw new Error('This sandbox MCP server returned an invalid reply.')
165
+ const entry = this.pending.get(rpc.id)
166
+ const verdict = this.settleReply(rpc, entry ? { method: entry.method } : undefined)
167
+ this.settle(rpc.id, verdict.confirmed)
168
+ if (verdict.reply) rpc = verdict.reply
169
+ }
170
+ this.messageHandler?.(rpc)
171
+ }
172
+
173
+ private async read(channel: Channel): Promise<void> {
174
+ const decoder = new StringDecoder('utf8')
175
+ let buffered = ''
176
+ for await (const event of channel.events) {
177
+ if (event.stream !== 'stdout') continue
178
+ buffered += decoder.write(Buffer.from(event.data))
179
+ for (;;) {
180
+ const end = buffered.indexOf('\n')
181
+ if (end < 0) break
182
+ const line = buffered.slice(0, end).replace(/\r$/, '')
183
+ buffered = buffered.slice(end + 1)
184
+ if (line.trim()) this.accept(line)
185
+ }
186
+ if (Buffer.byteLength(buffered) > this.maxMessageBytes)
187
+ throw new Error('This sandbox MCP reply exceeds the message limit.')
188
+ }
189
+ if (!this.closing) {
190
+ if (buffered.length || decoder.end())
191
+ throw new Error('This sandbox MCP server closed with an incomplete reply.')
192
+ this.end()
193
+ }
194
+ }
195
+
196
+ private end(): void {
197
+ if (this.ended) return
198
+ this.ended = true
199
+ for (const id of this.pending.keys()) this.settle(id, false)
200
+ this.closeHandler?.()
201
+ }
202
+ private fail(error: Error): void {
203
+ if (this.ended) return
204
+ this.errorHandler?.(error)
205
+ this.end()
206
+ void this.close().catch(() => undefined)
207
+ }
208
+ close(): Promise<void> {
209
+ if (this.closing) return this.closing
210
+ this.end()
211
+ this.closing = this.channel?.close() ?? Promise.resolve()
212
+ return this.closing
213
+ }
214
+ }
@@ -0,0 +1,68 @@
1
+ import { join } from 'node:path'
2
+
3
+ /**
4
+ * The folder of an installed Desktop's own tools (`<resources>/toolchain`), named by the app when it
5
+ * starts the engine. Absent means the engine runs on whatever the machine has.
6
+ */
7
+ export const TOOLCHAIN_DIR_ENV = 'NAMZU_TOOLCHAIN_DIR'
8
+ /** `bundled` when tool servers must run on the app's own Node, `system` when the machine's Node is used. */
9
+ export const TOOLCHAIN_NODE_ENV = 'NAMZU_TOOLCHAIN_NODE'
10
+
11
+ export interface StdioProgram {
12
+ command: string
13
+ args: string[]
14
+ /** Variables the program needs beyond the server's own environment. */
15
+ env: Record<string, string>
16
+ }
17
+
18
+ export interface StdioProgramContext {
19
+ platform?: NodeJS.Platform
20
+ /** Where the toolchain variables are read from; the engine's own environment by default. */
21
+ source?: NodeJS.ProcessEnv
22
+ /** The program running the engine, which is the app's own executable under Desktop. */
23
+ execPath?: string
24
+ /** True when `execPath` is an Electron executable that needs ELECTRON_RUN_AS_NODE to behave as Node. */
25
+ electron?: boolean
26
+ }
27
+
28
+ const WINDOWS_SPELLING = /\.(exe|cmd|bat)$/i
29
+
30
+ /** `node`, `npx` or `npm` out of a command as written (`npx`, `NPX.CMD`), or undefined for any other program. */
31
+ function toolName(command: string): 'node' | 'npx' | 'npm' | undefined {
32
+ if (/[\\/]/.test(command)) return undefined
33
+ const name = command.replace(WINDOWS_SPELLING, '').toLowerCase()
34
+ return name === 'node' || name === 'npx' || name === 'npm' ? name : undefined
35
+ }
36
+
37
+ /**
38
+ * What to start for a tool server's command.
39
+ *
40
+ * A server is usually written as `npx -y some-server` or `node server.js`. On a machine with no Node
41
+ * that fails to start, and on Windows `npx` and `npm` are `.cmd` files that `spawn` cannot start
42
+ * without a shell even when Node is installed. When the app declares a toolchain, those three names
43
+ * are started as the app's own Node running its pinned npm; every other command is returned as given.
44
+ * The machine's own Node is kept for `node` when the app says it chose it, and on Windows `npx` and
45
+ * `npm` still run the pinned npm, on that Node.
46
+ */
47
+ export function resolveStdioProgram(
48
+ command: string,
49
+ args: readonly string[],
50
+ context: StdioProgramContext = {},
51
+ ): StdioProgram {
52
+ const source = context.source ?? process.env
53
+ const platform = context.platform ?? process.platform
54
+ const dir = source[TOOLCHAIN_DIR_ENV]
55
+ const unchanged: StdioProgram = { command, args: [...args], env: {} }
56
+ const name = toolName(command)
57
+ if (!dir || !name) return unchanged
58
+ const bundled = source[TOOLCHAIN_NODE_ENV] === 'bundled'
59
+ const cli = (file: string) => join(dir, 'npm', 'bin', file)
60
+ if (!bundled && !(platform === 'win32' && name !== 'node')) return unchanged
61
+ const node = bundled ? (context.execPath ?? process.execPath) : 'node'
62
+ const env: Record<string, string> =
63
+ bundled && (context.electron ?? Boolean(process.versions.electron))
64
+ ? { ELECTRON_RUN_AS_NODE: '1' }
65
+ : {}
66
+ if (name === 'node') return { command: node, args: [...args], env }
67
+ return { command: node, args: [cli(name === 'npx' ? 'npx-cli.js' : 'npm-cli.js'), ...args], env }
68
+ }
@@ -19,6 +19,7 @@ import {
19
19
  readEnvironmentEntry,
20
20
  setEnvironmentEntry,
21
21
  } from '../../utils/process-environment.js'
22
+ import { resolveStdioProgram } from './stdio-program.js'
22
23
 
23
24
  /**
24
25
  * How long a child gets to honour SIGTERM before SIGKILL. Two seconds is
@@ -134,8 +135,10 @@ export class StdioTransport implements MCPTransport {
134
135
  this.retired = false
135
136
  this.resetLineBuffer()
136
137
 
137
- const child = spawn(this.config.command, this.config.args ?? [], {
138
- 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 },
139
142
  cwd: this.config.cwd,
140
143
  stdio: ['pipe', 'pipe', 'pipe'],
141
144
  })
@@ -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,
@@ -1740,7 +1740,7 @@ export class AgentManager {
1740
1740
  const driver = this.deps.workspaceRegistry.get(backend)
1741
1741
  workspaceDriver = driver
1742
1742
  workspaceRef = await driver.create({
1743
- label: subSession.id,
1743
+ label: (request?.mode === 'isolated' ? request.label : undefined) ?? subSession.id,
1744
1744
  ...(request?.mode === 'isolated' && request.baseRef ? { baseRef: request.baseRef } : {}),
1745
1745
  })
1746
1746
  if (request?.mode === 'isolated')