@namzu/sdk 71.1.0 → 73.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 (380) hide show
  1. package/CHANGELOG.md +55 -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/agents/examples/SupervisorAgent.d.ts.map +1 -1
  6. package/dist/agents/examples/SupervisorAgent.js +5 -0
  7. package/dist/agents/examples/SupervisorAgent.js.map +1 -1
  8. package/dist/authorization/protected-paths.d.ts.map +1 -1
  9. package/dist/authorization/protected-paths.js +4 -0
  10. package/dist/authorization/protected-paths.js.map +1 -1
  11. package/dist/compaction/index.d.ts +1 -1
  12. package/dist/compaction/index.d.ts.map +1 -1
  13. package/dist/compaction/index.js +1 -1
  14. package/dist/compaction/index.js.map +1 -1
  15. package/dist/compaction/manual.d.ts +24 -1
  16. package/dist/compaction/manual.d.ts.map +1 -1
  17. package/dist/compaction/manual.js +80 -21
  18. package/dist/compaction/manual.js.map +1 -1
  19. package/dist/compaction/model-summary.d.ts +24 -6
  20. package/dist/compaction/model-summary.d.ts.map +1 -1
  21. package/dist/compaction/model-summary.js +108 -23
  22. package/dist/compaction/model-summary.js.map +1 -1
  23. package/dist/compaction/precompute.d.ts +179 -0
  24. package/dist/compaction/precompute.d.ts.map +1 -0
  25. package/dist/compaction/precompute.js +274 -0
  26. package/dist/compaction/precompute.js.map +1 -0
  27. package/dist/compaction/restore.d.ts +23 -0
  28. package/dist/compaction/restore.d.ts.map +1 -1
  29. package/dist/compaction/restore.js +59 -1
  30. package/dist/compaction/restore.js.map +1 -1
  31. package/dist/compaction/summary.d.ts +37 -2
  32. package/dist/compaction/summary.d.ts.map +1 -1
  33. package/dist/compaction/summary.js +46 -6
  34. package/dist/compaction/summary.js.map +1 -1
  35. package/dist/config/runtime.d.ts +4 -0
  36. package/dist/config/runtime.d.ts.map +1 -1
  37. package/dist/config/runtime.js +20 -3
  38. package/dist/config/runtime.js.map +1 -1
  39. package/dist/connector/index.d.ts +2 -2
  40. package/dist/connector/index.d.ts.map +1 -1
  41. package/dist/connector/index.js +1 -1
  42. package/dist/connector/index.js.map +1 -1
  43. package/dist/connector/mcp/client.d.ts +26 -6
  44. package/dist/connector/mcp/client.d.ts.map +1 -1
  45. package/dist/connector/mcp/client.js +49 -7
  46. package/dist/connector/mcp/client.js.map +1 -1
  47. package/dist/connector/mcp/index.d.ts +2 -0
  48. package/dist/connector/mcp/index.d.ts.map +1 -1
  49. package/dist/connector/mcp/index.js +1 -0
  50. package/dist/connector/mcp/index.js.map +1 -1
  51. package/dist/connector/mcp/sandbox-stdio.d.ts +67 -0
  52. package/dist/connector/mcp/sandbox-stdio.d.ts.map +1 -0
  53. package/dist/connector/mcp/sandbox-stdio.js +178 -0
  54. package/dist/connector/mcp/sandbox-stdio.js.map +1 -0
  55. package/dist/connector/mcp/stdio-program.d.ts +34 -0
  56. package/dist/connector/mcp/stdio-program.d.ts.map +1 -0
  57. package/dist/connector/mcp/stdio-program.js +47 -0
  58. package/dist/connector/mcp/stdio-program.js.map +1 -0
  59. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  60. package/dist/connector/mcp/stdio.js +5 -2
  61. package/dist/connector/mcp/stdio.js.map +1 -1
  62. package/dist/connector/web/guarded-fetch.d.ts +51 -2
  63. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  64. package/dist/connector/web/guarded-fetch.js +140 -19
  65. package/dist/connector/web/guarded-fetch.js.map +1 -1
  66. package/dist/connector/web/index.d.ts +2 -2
  67. package/dist/connector/web/index.d.ts.map +1 -1
  68. package/dist/connector/web/index.js +1 -1
  69. package/dist/connector/web/index.js.map +1 -1
  70. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  71. package/dist/manager/agent/lifecycle.js +9 -1
  72. package/dist/manager/agent/lifecycle.js.map +1 -1
  73. package/dist/manager/session/turn-recorder.d.ts +26 -0
  74. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  75. package/dist/manager/session/turn-recorder.js +72 -5
  76. package/dist/manager/session/turn-recorder.js.map +1 -1
  77. package/dist/peers/protocol.d.ts +9 -0
  78. package/dist/peers/protocol.d.ts.map +1 -1
  79. package/dist/peers/protocol.js +4 -0
  80. package/dist/peers/protocol.js.map +1 -1
  81. package/dist/peers/record.d.ts +6 -0
  82. package/dist/peers/record.d.ts.map +1 -1
  83. package/dist/peers/record.js +4 -0
  84. package/dist/peers/record.js.map +1 -1
  85. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  86. package/dist/plugin/hook-module/capabilities.js +24 -13
  87. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  88. package/dist/plugin/hook-module/host.d.ts +31 -0
  89. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  90. package/dist/plugin/hook-module/host.js +56 -13
  91. package/dist/plugin/hook-module/host.js.map +1 -1
  92. package/dist/plugin/hook-module/index.d.ts +3 -2
  93. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  94. package/dist/plugin/hook-module/index.js +2 -1
  95. package/dist/plugin/hook-module/index.js.map +1 -1
  96. package/dist/plugin/index.d.ts +3 -2
  97. package/dist/plugin/index.d.ts.map +1 -1
  98. package/dist/plugin/index.js +2 -1
  99. package/dist/plugin/index.js.map +1 -1
  100. package/dist/plugin/shell-hook-execute.d.ts +55 -0
  101. package/dist/plugin/shell-hook-execute.d.ts.map +1 -0
  102. package/dist/plugin/shell-hook-execute.js +73 -0
  103. package/dist/plugin/shell-hook-execute.js.map +1 -0
  104. package/dist/plugin/shell-hook-restrict.d.ts +31 -0
  105. package/dist/plugin/shell-hook-restrict.d.ts.map +1 -0
  106. package/dist/plugin/shell-hook-restrict.js +69 -0
  107. package/dist/plugin/shell-hook-restrict.js.map +1 -0
  108. package/dist/plugin/shell-hook.d.ts +59 -2
  109. package/dist/plugin/shell-hook.d.ts.map +1 -1
  110. package/dist/plugin/shell-hook.js +79 -12
  111. package/dist/plugin/shell-hook.js.map +1 -1
  112. package/dist/public-runtime.d.ts +11 -7
  113. package/dist/public-runtime.d.ts.map +1 -1
  114. package/dist/public-runtime.js +9 -6
  115. package/dist/public-runtime.js.map +1 -1
  116. package/dist/public-tools.d.ts +1 -1
  117. package/dist/public-tools.d.ts.map +1 -1
  118. package/dist/public-tools.js +1 -1
  119. package/dist/public-tools.js.map +1 -1
  120. package/dist/public-types.d.ts +5 -2
  121. package/dist/public-types.d.ts.map +1 -1
  122. package/dist/registry/command/kernel-commands.d.ts +7 -1
  123. package/dist/registry/command/kernel-commands.d.ts.map +1 -1
  124. package/dist/registry/command/kernel-commands.js +40 -2
  125. package/dist/registry/command/kernel-commands.js.map +1 -1
  126. package/dist/registry/tool/execute.d.ts +8 -0
  127. package/dist/registry/tool/execute.d.ts.map +1 -1
  128. package/dist/registry/tool/execute.js +12 -0
  129. package/dist/registry/tool/execute.js.map +1 -1
  130. package/dist/runtime/jobs/websocket-source.d.ts +2 -22
  131. package/dist/runtime/jobs/websocket-source.d.ts.map +1 -1
  132. package/dist/runtime/jobs/websocket-source.js +2 -33
  133. package/dist/runtime/jobs/websocket-source.js.map +1 -1
  134. package/dist/runtime/query/budget-nudge.d.ts +27 -0
  135. package/dist/runtime/query/budget-nudge.d.ts.map +1 -0
  136. package/dist/runtime/query/budget-nudge.js +66 -0
  137. package/dist/runtime/query/budget-nudge.js.map +1 -0
  138. package/dist/runtime/query/compact-session.d.ts +9 -0
  139. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  140. package/dist/runtime/query/compact-session.js +158 -76
  141. package/dist/runtime/query/compact-session.js.map +1 -1
  142. package/dist/runtime/query/events.d.ts +7 -0
  143. package/dist/runtime/query/events.d.ts.map +1 -1
  144. package/dist/runtime/query/events.js +29 -11
  145. package/dist/runtime/query/events.js.map +1 -1
  146. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  147. package/dist/runtime/query/executor/tool-call-admission.js +51 -10
  148. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  149. package/dist/runtime/query/guard.d.ts +8 -0
  150. package/dist/runtime/query/guard.d.ts.map +1 -1
  151. package/dist/runtime/query/guard.js +20 -0
  152. package/dist/runtime/query/guard.js.map +1 -1
  153. package/dist/runtime/query/index.d.ts +6 -0
  154. package/dist/runtime/query/index.d.ts.map +1 -1
  155. package/dist/runtime/query/index.js +3 -0
  156. package/dist/runtime/query/index.js.map +1 -1
  157. package/dist/runtime/query/iteration/index.d.ts +2 -0
  158. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  159. package/dist/runtime/query/iteration/index.js +27 -1
  160. package/dist/runtime/query/iteration/index.js.map +1 -1
  161. package/dist/runtime/query/iteration/phases/compaction.d.ts +1 -0
  162. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  163. package/dist/runtime/query/iteration/phases/compaction.js +164 -43
  164. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  165. package/dist/runtime/query/iteration/phases/context.d.ts +4 -0
  166. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  167. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  168. package/dist/runtime/query/iteration/phases/precompute.d.ts +60 -0
  169. package/dist/runtime/query/iteration/phases/precompute.d.ts.map +1 -0
  170. package/dist/runtime/query/iteration/phases/precompute.js +240 -0
  171. package/dist/runtime/query/iteration/phases/precompute.js.map +1 -0
  172. package/dist/runtime/query/turn/outcome-ledger.d.ts +14 -0
  173. package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -1
  174. package/dist/runtime/query/turn/outcome-ledger.js +28 -0
  175. package/dist/runtime/query/turn/outcome-ledger.js.map +1 -1
  176. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  177. package/dist/scheduler/completion-inbox.js +15 -0
  178. package/dist/scheduler/completion-inbox.js.map +1 -1
  179. package/dist/store/goal/gates.d.ts +53 -0
  180. package/dist/store/goal/gates.d.ts.map +1 -0
  181. package/dist/store/goal/gates.js +664 -0
  182. package/dist/store/goal/gates.js.map +1 -0
  183. package/dist/store/goal/index.d.ts +16 -1
  184. package/dist/store/goal/index.d.ts.map +1 -1
  185. package/dist/store/goal/index.js +74 -0
  186. package/dist/store/goal/index.js.map +1 -1
  187. package/dist/store/session-index/index.d.ts +13 -0
  188. package/dist/store/session-index/index.d.ts.map +1 -1
  189. package/dist/store/session-index/index.js +1 -0
  190. package/dist/store/session-index/index.js.map +1 -1
  191. package/dist/store/session-index/rebuild.d.ts +12 -0
  192. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  193. package/dist/store/session-index/rebuild.js +20 -4
  194. package/dist/store/session-index/rebuild.js.map +1 -1
  195. package/dist/store/session-index/sqlite.d.ts +20 -0
  196. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  197. package/dist/store/session-index/sqlite.js +50 -12
  198. package/dist/store/session-index/sqlite.js.map +1 -1
  199. package/dist/tools/admit-facts.d.ts.map +1 -1
  200. package/dist/tools/admit-facts.js +59 -0
  201. package/dist/tools/admit-facts.js.map +1 -1
  202. package/dist/tools/builtins/bash.js +1 -1
  203. package/dist/tools/builtins/bash.js.map +1 -1
  204. package/dist/tools/builtins/browser.d.ts.map +1 -1
  205. package/dist/tools/builtins/browser.js +2 -0
  206. package/dist/tools/builtins/browser.js.map +1 -1
  207. package/dist/tools/builtins/monitor.d.ts.map +1 -1
  208. package/dist/tools/builtins/monitor.js +1 -0
  209. package/dist/tools/builtins/monitor.js.map +1 -1
  210. package/dist/tools/builtins/search-tools.js +2 -2
  211. package/dist/tools/builtins/search-tools.js.map +1 -1
  212. package/dist/tools/builtins/sleep-guard.js +1 -1
  213. package/dist/tools/builtins/sleep-guard.js.map +1 -1
  214. package/dist/tools/builtins/wait-for-job.js +1 -1
  215. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  216. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  217. package/dist/tools/coordinator/ask-user-question.js +92 -3
  218. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  219. package/dist/tools/coordinator/index.d.ts.map +1 -1
  220. package/dist/tools/coordinator/index.js +3 -0
  221. package/dist/tools/coordinator/index.js.map +1 -1
  222. package/dist/tools/defineTool.d.ts +2 -0
  223. package/dist/tools/defineTool.d.ts.map +1 -1
  224. package/dist/tools/defineTool.js +3 -0
  225. package/dist/tools/defineTool.js.map +1 -1
  226. package/dist/tools/goal/confirmation.d.ts +40 -2
  227. package/dist/tools/goal/confirmation.d.ts.map +1 -1
  228. package/dist/tools/goal/confirmation.js +117 -0
  229. package/dist/tools/goal/confirmation.js.map +1 -1
  230. package/dist/tools/goal/index.d.ts.map +1 -1
  231. package/dist/tools/goal/index.js +14 -2
  232. package/dist/tools/goal/index.js.map +1 -1
  233. package/dist/tools/memory/save.d.ts.map +1 -1
  234. package/dist/tools/memory/save.js +1 -0
  235. package/dist/tools/memory/save.js.map +1 -1
  236. package/dist/tools/schedules/index.d.ts +1 -0
  237. package/dist/tools/schedules/index.d.ts.map +1 -1
  238. package/dist/tools/schedules/index.js +1 -0
  239. package/dist/tools/schedules/index.js.map +1 -1
  240. package/dist/tools/schedules/loop-tool.d.ts.map +1 -1
  241. package/dist/tools/schedules/loop-tool.js +1 -0
  242. package/dist/tools/schedules/loop-tool.js.map +1 -1
  243. package/dist/tools/schedules/present.d.ts.map +1 -1
  244. package/dist/tools/schedules/present.js +2 -0
  245. package/dist/tools/schedules/present.js.map +1 -1
  246. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  247. package/dist/tools/schedules/schedule-tool.js +79 -9
  248. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  249. package/dist/tools/schedules/self-tool.d.ts +16 -0
  250. package/dist/tools/schedules/self-tool.d.ts.map +1 -0
  251. package/dist/tools/schedules/self-tool.js +140 -0
  252. package/dist/tools/schedules/self-tool.js.map +1 -0
  253. package/dist/tools/schedules/timer-tools.d.ts.map +1 -1
  254. package/dist/tools/schedules/timer-tools.js +1 -0
  255. package/dist/tools/schedules/timer-tools.js.map +1 -1
  256. package/dist/tools/schedules/types.d.ts +63 -0
  257. package/dist/tools/schedules/types.d.ts.map +1 -1
  258. package/dist/toolsets/manager.d.ts +10 -0
  259. package/dist/toolsets/manager.d.ts.map +1 -1
  260. package/dist/toolsets/manager.js +56 -7
  261. package/dist/toolsets/manager.js.map +1 -1
  262. package/dist/turn/memory-promoter.d.ts.map +1 -1
  263. package/dist/turn/memory-promoter.js +20 -4
  264. package/dist/turn/memory-promoter.js.map +1 -1
  265. package/dist/types/agent/base.d.ts +6 -0
  266. package/dist/types/agent/base.d.ts.map +1 -1
  267. package/dist/types/agent/supervisor.d.ts +10 -0
  268. package/dist/types/agent/supervisor.d.ts.map +1 -1
  269. package/dist/types/agent/task.d.ts +11 -0
  270. package/dist/types/agent/task.d.ts.map +1 -1
  271. package/dist/types/agent/task.js.map +1 -1
  272. package/dist/types/goal/index.d.ts +66 -0
  273. package/dist/types/goal/index.d.ts.map +1 -1
  274. package/dist/types/hitl/index.d.ts +8 -0
  275. package/dist/types/hitl/index.d.ts.map +1 -1
  276. package/dist/types/hitl/index.js.map +1 -1
  277. package/dist/types/message/index.d.ts +7 -0
  278. package/dist/types/message/index.d.ts.map +1 -1
  279. package/dist/types/message/index.js.map +1 -1
  280. package/dist/types/session/events.d.ts +7 -0
  281. package/dist/types/session/events.d.ts.map +1 -1
  282. package/dist/types/session/events.js.map +1 -1
  283. package/dist/types/session/outcome.d.ts +12 -0
  284. package/dist/types/session/outcome.d.ts.map +1 -1
  285. package/dist/types/session/outcome.js.map +1 -1
  286. package/dist/types/session/records.d.ts +79 -1
  287. package/dist/types/session/records.d.ts.map +1 -1
  288. package/dist/types/session/records.js +24 -0
  289. package/dist/types/session/records.js.map +1 -1
  290. package/dist/types/tool/index.d.ts +7 -0
  291. package/dist/types/tool/index.d.ts.map +1 -1
  292. package/dist/types/tool/index.js.map +1 -1
  293. package/dist/types/tool/presentation.d.ts +21 -0
  294. package/dist/types/tool/presentation.d.ts.map +1 -1
  295. package/package.json +6 -6
  296. package/src/agents/QueryAgent.ts +1 -0
  297. package/src/agents/examples/SupervisorAgent.ts +5 -0
  298. package/src/authorization/protected-paths.ts +4 -0
  299. package/src/compaction/index.ts +1 -0
  300. package/src/compaction/manual.ts +130 -23
  301. package/src/compaction/model-summary.ts +118 -23
  302. package/src/compaction/precompute.ts +390 -0
  303. package/src/compaction/restore.ts +74 -1
  304. package/src/compaction/summary.ts +69 -3
  305. package/src/config/runtime.ts +20 -3
  306. package/src/connector/index.ts +3 -0
  307. package/src/connector/mcp/client.ts +49 -7
  308. package/src/connector/mcp/index.ts +5 -0
  309. package/src/connector/mcp/sandbox-stdio.ts +214 -0
  310. package/src/connector/mcp/stdio-program.ts +68 -0
  311. package/src/connector/mcp/stdio.ts +5 -2
  312. package/src/connector/web/guarded-fetch.ts +197 -30
  313. package/src/connector/web/index.ts +4 -1
  314. package/src/manager/agent/lifecycle.ts +10 -1
  315. package/src/manager/session/turn-recorder.ts +92 -5
  316. package/src/peers/protocol.ts +4 -0
  317. package/src/peers/record.ts +4 -0
  318. package/src/plugin/hook-module/capabilities.ts +36 -14
  319. package/src/plugin/hook-module/host.ts +86 -13
  320. package/src/plugin/hook-module/index.ts +3 -0
  321. package/src/plugin/index.ts +3 -0
  322. package/src/plugin/shell-hook-execute.ts +126 -0
  323. package/src/plugin/shell-hook-restrict.ts +66 -0
  324. package/src/plugin/shell-hook.ts +138 -10
  325. package/src/public-runtime.ts +41 -0
  326. package/src/public-tools.ts +2 -0
  327. package/src/public-types.ts +21 -0
  328. package/src/registry/command/kernel-commands.ts +62 -3
  329. package/src/registry/tool/execute.ts +14 -0
  330. package/src/runtime/jobs/websocket-source.ts +2 -46
  331. package/src/runtime/query/budget-nudge.ts +92 -0
  332. package/src/runtime/query/compact-session.ts +195 -70
  333. package/src/runtime/query/events.ts +29 -11
  334. package/src/runtime/query/executor/tool-call-admission.ts +62 -17
  335. package/src/runtime/query/guard.ts +22 -0
  336. package/src/runtime/query/index.ts +10 -0
  337. package/src/runtime/query/iteration/index.ts +26 -1
  338. package/src/runtime/query/iteration/phases/compaction.ts +173 -43
  339. package/src/runtime/query/iteration/phases/context.ts +6 -0
  340. package/src/runtime/query/iteration/phases/precompute.ts +277 -0
  341. package/src/runtime/query/turn/outcome-ledger.ts +34 -0
  342. package/src/scheduler/completion-inbox.ts +14 -0
  343. package/src/store/goal/gates.ts +738 -0
  344. package/src/store/goal/index.ts +109 -0
  345. package/src/store/session-index/index.ts +14 -0
  346. package/src/store/session-index/rebuild.ts +22 -4
  347. package/src/store/session-index/sqlite.ts +63 -14
  348. package/src/tools/admit-facts.ts +64 -0
  349. package/src/tools/builtins/bash.ts +1 -1
  350. package/src/tools/builtins/browser.ts +4 -0
  351. package/src/tools/builtins/monitor.ts +2 -0
  352. package/src/tools/builtins/search-tools.ts +2 -2
  353. package/src/tools/builtins/sleep-guard.ts +1 -1
  354. package/src/tools/builtins/wait-for-job.ts +1 -1
  355. package/src/tools/coordinator/ask-user-question.ts +124 -13
  356. package/src/tools/coordinator/index.ts +3 -0
  357. package/src/tools/defineTool.ts +5 -0
  358. package/src/tools/goal/confirmation.ts +171 -3
  359. package/src/tools/goal/index.ts +15 -3
  360. package/src/tools/memory/save.ts +2 -0
  361. package/src/tools/schedules/index.ts +1 -0
  362. package/src/tools/schedules/loop-tool.ts +2 -0
  363. package/src/tools/schedules/present.ts +2 -0
  364. package/src/tools/schedules/schedule-tool.ts +84 -9
  365. package/src/tools/schedules/self-tool.ts +152 -0
  366. package/src/tools/schedules/timer-tools.ts +2 -0
  367. package/src/tools/schedules/types.ts +62 -0
  368. package/src/toolsets/manager.ts +55 -8
  369. package/src/turn/memory-promoter.ts +24 -3
  370. package/src/types/agent/base.ts +7 -0
  371. package/src/types/agent/supervisor.ts +11 -0
  372. package/src/types/agent/task.ts +12 -0
  373. package/src/types/goal/index.ts +72 -0
  374. package/src/types/hitl/index.ts +8 -0
  375. package/src/types/message/index.ts +7 -0
  376. package/src/types/session/events.ts +7 -0
  377. package/src/types/session/outcome.ts +16 -1
  378. package/src/types/session/records.ts +27 -0
  379. package/src/types/tool/index.ts +7 -0
  380. package/src/types/tool/presentation.ts +22 -0
@@ -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,
@@ -946,6 +946,15 @@ export class AgentManager {
946
946
  childConfig.toolResultGuardrails = inheritedScreens
947
947
  }
948
948
 
949
+ // The parent's hook manager, for the same reason as the screens: a
950
+ // child's `configBuilder` cannot forward what it was never told about.
951
+ const inheritedPlugins =
952
+ (options.configOverrides as { pluginManager?: unknown } | undefined)?.pluginManager ??
953
+ context.pluginManager
954
+ if (inheritedPlugins !== undefined) {
955
+ ;(childConfig as { pluginManager?: unknown }).pluginManager = inheritedPlugins
956
+ }
957
+
949
958
  // A child of its own reader record over the family's authored ledger, so
950
959
  // what the parent wrote is still "this session's" to a child that runs
951
960
  // it, while what the child has read stays its own and a write by a
@@ -1740,7 +1749,7 @@ export class AgentManager {
1740
1749
  const driver = this.deps.workspaceRegistry.get(backend)
1741
1750
  workspaceDriver = driver
1742
1751
  workspaceRef = await driver.create({
1743
- label: subSession.id,
1752
+ label: (request?.mode === 'isolated' ? request.label : undefined) ?? subSession.id,
1744
1753
  ...(request?.mode === 'isolated' && request.baseRef ? { baseRef: request.baseRef } : {}),
1745
1754
  })
1746
1755
  if (request?.mode === 'isolated')
@@ -266,6 +266,10 @@ export class TurnRecorder {
266
266
  #turnSystemPrompt: string | undefined
267
267
  /** Set by {@link resume}: the next reconciliation re-bases the fold on the restored context. */
268
268
  #rebasePending = false
269
+ /** What the pass that is about to be re-based on measured; see {@link noteCompaction}. */
270
+ #pendingCompaction: CompactionFacts | undefined
271
+ /** Tokens all earlier compactions of this session dropped; read from the log when the first compaction of this recorder is written. */
272
+ #cumulativeDropped: number | undefined
269
273
  /** The summary the log already folds to, read when the recorder opened. */
270
274
  #foldSummary: readonly Message[] = []
271
275
  /**
@@ -371,6 +375,11 @@ export class TurnRecorder {
371
375
  return this.#phase === 'active'
372
376
  }
373
377
 
378
+ /** Whether usage accumulated now still reaches the turn's record: the turn is active and its closing record is not queued. */
379
+ get acceptsUsage(): boolean {
380
+ return this.#turnOpen()
381
+ }
382
+
374
383
  /** Whether the turn's last segment record is `turn_paused`. */
375
384
  get isPaused(): boolean {
376
385
  return this.#phase === 'paused'
@@ -578,6 +587,17 @@ export class TurnRecorder {
578
587
  this.#lastPromptMessageCount = this.#turn.messages.length
579
588
  }
580
589
 
590
+ /**
591
+ * Say what the compaction pass that just replaced the context measured. The
592
+ * `compaction` record the next reconciliation writes carries it (its
593
+ * trigger, real token counts, duration and the running total of tokens
594
+ * dropped). Without it the record still names the messages kept, with the
595
+ * counts left at zero.
596
+ */
597
+ noteCompaction(facts: CompactionFacts): void {
598
+ this.#pendingCompaction = facts
599
+ }
600
+
581
601
  /** Forget the last prompt measurement (after compaction replaced the context it described). */
582
602
  clearLastPromptTokens(): void {
583
603
  this.#lastPromptTokens = undefined
@@ -1479,20 +1499,40 @@ export class TurnRecorder {
1479
1499
  const keptMessageIds = keptEntries.map((entry) => entry.id as MessageId)
1480
1500
  this.#view = next
1481
1501
  const turnId = this.turnId
1502
+ const facts = this.#pendingCompaction
1503
+ this.#pendingCompaction = undefined
1504
+ const dropped = facts ? Math.max(0, facts.tokensBefore - facts.tokensAfter) : 0
1482
1505
  void this.#enqueue(async () => {
1506
+ // Read once, from the records already in the log, when the first
1507
+ // compaction of this recorder is written: a session that never compacts
1508
+ // never reads it.
1509
+ this.#cumulativeDropped ??= await readCumulativeDropped(this.log)
1510
+ this.#cumulativeDropped += dropped
1511
+ const cumulativeDropped = this.#cumulativeDropped
1483
1512
  const toSeq = this.#lastEntry?.record.seq ?? (await this.log.head())?.pointer.seq ?? 1
1484
- return this.#append({
1513
+ const compactionId = generateMessageId()
1514
+ const entry = await this.#append({
1485
1515
  type: 'compaction',
1486
1516
  turnId,
1487
- compactionId: generateMessageId(),
1517
+ compactionId,
1488
1518
  strategy: 'context-rewrite',
1489
- trigger: 'auto',
1519
+ // What an earlier release reads: `prepared` is told by the record below.
1520
+ trigger:
1521
+ facts?.trigger === 'prepared' || facts?.trigger === undefined ? 'auto' : facts.trigger,
1490
1522
  replacesSeqRange: [1, toSeq],
1491
1523
  summary,
1492
1524
  keptMessageIds,
1493
- tokensBefore: 0,
1494
- tokensAfter: 0,
1525
+ tokensBefore: facts?.tokensBefore ?? 0,
1526
+ tokensAfter: facts?.tokensAfter ?? 0,
1495
1527
  })
1528
+ if (facts) {
1529
+ // A record of its own, never a field of the one above: see
1530
+ // `CompactionMeasuredRecordSchema`. A refused write loses only the measures.
1531
+ await this.#append(measuredDraft(compactionId, facts, cumulativeDropped, turnId)).catch(
1532
+ () => undefined,
1533
+ )
1534
+ }
1535
+ return entry
1496
1536
  }).catch(() => undefined)
1497
1537
  for (const entry of tailEntries) {
1498
1538
  const message = entry.message
@@ -1673,6 +1713,53 @@ export async function recordedTurnStart(
1673
1713
  return undefined
1674
1714
  }
1675
1715
 
1716
+ /** What a compaction pass measured, handed to the recorder so its record is not left at zero. */
1717
+ export interface CompactionFacts {
1718
+ readonly trigger?: 'auto' | 'manual' | 'idle' | 'prepared'
1719
+ readonly tokensBefore: number
1720
+ readonly tokensAfter: number
1721
+ readonly durationMs?: number
1722
+ readonly precomputed?: boolean
1723
+ }
1724
+
1725
+ /** The `compaction_measured` record that follows the `compaction` record `compactionId`. */
1726
+ export function measuredDraft(
1727
+ compactionId: string,
1728
+ facts: CompactionFacts,
1729
+ cumulativeDroppedTokens: number,
1730
+ turnId?: TurnId,
1731
+ ): Parameters<SessionLog['append']>[1] {
1732
+ return {
1733
+ type: 'compaction_measured',
1734
+ ...(turnId ? { turnId } : {}),
1735
+ ignorable: true,
1736
+ compactionId,
1737
+ trigger: facts.trigger ?? 'auto',
1738
+ ...(facts.durationMs !== undefined ? { durationMs: facts.durationMs } : {}),
1739
+ cumulativeDroppedTokens,
1740
+ ...(facts.precomputed ? { precomputed: true } : {}),
1741
+ }
1742
+ }
1743
+
1744
+ /**
1745
+ * The running total of tokens the session's compactions have dropped: what
1746
+ * each `compaction` record's sizes say, summed. Read from the sizes, which an
1747
+ * earlier release also writes and reads, never from a stored total.
1748
+ */
1749
+ export async function readCumulativeDropped(log: SessionLog): Promise<number> {
1750
+ return foldSessionLog(log, {
1751
+ name: 'compaction-dropped',
1752
+ mode: 'strict',
1753
+ create: () => ({ total: 0 }),
1754
+ apply: (state, entry) => {
1755
+ const record = entry.record as SessionRecord
1756
+ if (record.type !== 'compaction') return
1757
+ state.total += Math.max(0, record.tokensBefore - record.tokensAfter)
1758
+ },
1759
+ result: (state) => state.total,
1760
+ })
1761
+ }
1762
+
1676
1763
  /**
1677
1764
  * The session's folded context with the id each message's record gave it,
1678
1765
  * spilled bodies read back.
@@ -43,6 +43,9 @@ export const MAX_PEER_CONNECTIONS = 16
43
43
  // only long enough to be verified, never accepts messages, and is not a terminal.
44
44
  // 'person' is `namzu send` or the watcher's message key: the operator's own words from another terminal. It
45
45
  // listens only long enough to be verified, never accepts messages, and is not a terminal either.
46
+ // 'run' is one scheduled run of a job: it opens a restricted endpoint for the life of the run, takes
47
+ // only plain messages (never an approval or an interrupt), and is not a terminal. An older reader skips
48
+ // a record of this kind, so it simply does not see the run.
46
49
  export const PeerSessionKindSchema = z.enum([
47
50
  'tui',
48
51
  'exec',
@@ -51,6 +54,7 @@ export const PeerSessionKindSchema = z.enum([
51
54
  'cli',
52
55
  'person',
53
56
  'net',
57
+ 'run',
54
58
  ])
55
59
  export type PeerSessionKind = z.infer<typeof PeerSessionKindSchema>
56
60
 
@@ -107,6 +107,10 @@ export const PeerRecordSchema = z
107
107
  /** The name of the machine that set the role. */
108
108
  roleBy: z.string().min(1).max(80).optional(),
109
109
  roleAt: z.number().int().nonnegative().optional(),
110
+ /** `kind: 'run'` only: the name of the scheduled job this run belongs to. */
111
+ jobName: z.string().min(1).max(64).optional(),
112
+ /** `kind: 'run'` only: the id of this run. */
113
+ runId: z.string().min(1).max(128).optional(),
110
114
  })
111
115
  .strict()
112
116
 
@@ -14,7 +14,12 @@ import {
14
14
  } from 'node:fs'
15
15
  import { isAbsolute, join, relative, resolve } from 'node:path'
16
16
 
17
- import { privateAddressProblem, proxyConfigured } from '../../connector/web/guarded-fetch.js'
17
+ import {
18
+ checkedAddresses,
19
+ pinnedFetch,
20
+ proxyConfigured,
21
+ } from '../../connector/web/guarded-fetch.js'
22
+ import { temporaryPathFor } from '../../utils/atomic-write.js'
18
23
  import type { Logger } from '../../utils/logger.js'
19
24
 
20
25
  /** The most one read, one output stream or one answer body may hold. */
@@ -278,7 +283,7 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
278
283
  }
279
284
  const path = storePath()
280
285
  mkdirSync(options.dataDir as string, { recursive: true, mode: 0o700 })
281
- const temporary = `${path}.${process.pid}.tmp`
286
+ const temporary = temporaryPathFor(path)
282
287
  writeFileSync(temporary, text, { mode: 0o600 })
283
288
  renameSync(temporary, path)
284
289
  }
@@ -457,14 +462,25 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
457
462
  // not be followed there.
458
463
  let response: Response
459
464
  for (let hop = 0; ; hop++) {
460
- await assertReachable(parsed, deadline)
461
- response = await fetchImpl(parsed, {
462
- method,
463
- headers,
464
- ...(body !== undefined ? { body } : {}),
465
- redirect: 'manual',
466
- signal: deadline,
467
- })
465
+ const pinned = await assertReachable(parsed, deadline)
466
+ // The connection goes to the addresses that were checked, with the name kept for
467
+ // `Host` and TLS, so a name that answers differently the second time has no second
468
+ // answer to give. A host that supplies its own `fetch` is handed them as `pinnedAddresses`.
469
+ response =
470
+ pinned !== undefined && options.fetch === undefined
471
+ ? await pinnedFetch(
472
+ parsed,
473
+ { method, headers, ...(body !== undefined ? { body } : {}), signal: deadline },
474
+ pinned,
475
+ )
476
+ : await fetchImpl(parsed, {
477
+ method,
478
+ headers,
479
+ ...(body !== undefined ? { body } : {}),
480
+ redirect: 'manual',
481
+ signal: deadline,
482
+ ...(pinned !== undefined ? { pinnedAddresses: pinned } : {}),
483
+ } as RequestInit)
468
484
  const location = response.headers.get('location')
469
485
  if (response.status < 300 || response.status >= 400 || location === null) break
470
486
  await response.body?.cancel().catch(() => undefined)
@@ -504,7 +520,10 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
504
520
  }
505
521
 
506
522
  /** Refuse an address a module may not reach: not https, or inside this machine's own network. */
507
- const assertReachable = async (target: URL, signal: AbortSignal): Promise<void> => {
523
+ const assertReachable = async (
524
+ target: URL,
525
+ signal: AbortSignal,
526
+ ): Promise<readonly string[] | undefined> => {
508
527
  if (target.protocol !== 'https:' && target.protocol !== 'http:') {
509
528
  throw new Error(`${target.protocol} is not http or https`)
510
529
  }
@@ -512,13 +531,16 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
512
531
  if (target.protocol === 'http:' && !(options.allowLoopbackHttp === true && loopback)) {
513
532
  throw new Error(`${target.hostname}: only https addresses are fetched`)
514
533
  }
515
- if (options.allowLoopbackHttp === true && loopback) return
516
- const problem = await privateAddressProblem(target.hostname, {
534
+ if (options.allowLoopbackHttp === true && loopback) return undefined
535
+ const proxied = options.proxied ?? proxyConfigured(process.env, target.hostname)
536
+ const { problem, addresses } = await checkedAddresses(target.hostname, {
517
537
  ...(options.resolve !== undefined ? { resolve: options.resolve } : {}),
518
- proxied: options.proxied ?? proxyConfigured(process.env, target.hostname),
538
+ proxied,
519
539
  signal,
520
540
  })
521
541
  if (problem !== undefined) throw new Error(`${target.hostname} was not fetched: ${problem}`)
542
+ // Behind a proxy the proxy resolves the name and there is nothing to pin.
543
+ return proxied || addresses.length === 0 ? undefined : addresses
522
544
  }
523
545
  const allowedCalls =
524
546
  options.allowedCalls === undefined ? undefined : new Set(options.allowedCalls)