@zvada/agent-server 0.3.22 → 0.3.24

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 (558) hide show
  1. package/CHANGELOG.md +295 -0
  2. package/README.md +14 -5
  3. package/dist/accounts/chatgpt.js +144 -0
  4. package/dist/accounts/check.js +71 -0
  5. package/dist/accounts/claude.js +80 -0
  6. package/dist/accounts/endpoint.js +104 -0
  7. package/dist/accounts/http.js +58 -0
  8. package/dist/accounts/index.js +9 -0
  9. package/dist/client/client.js +686 -0
  10. package/dist/client/connection.js +338 -0
  11. package/dist/client/history.js +49 -0
  12. package/dist/client/index.js +6 -0
  13. package/dist/client/listeners.js +19 -0
  14. package/dist/client/logins.js +92 -0
  15. package/dist/client/rpc.js +105 -0
  16. package/dist/client/streams.js +432 -0
  17. package/dist/client/transports.js +118 -0
  18. package/dist/client/turns.js +122 -0
  19. package/dist/core/agents/acp/acp-agent.js +425 -0
  20. package/dist/core/agents/acp/adapter.js +231 -0
  21. package/dist/core/agents/acp/client.js +222 -0
  22. package/dist/core/agents/acp/known-agents.js +57 -0
  23. package/dist/core/agents/acp/mappings.js +164 -0
  24. package/dist/core/agents/acp/requests.js +79 -0
  25. package/dist/core/agents/attachments.js +14 -0
  26. package/dist/core/agents/base.js +64 -0
  27. package/dist/core/agents/claude-code/adapter.js +474 -0
  28. package/dist/core/agents/claude-code/approvals.js +245 -0
  29. package/dist/core/agents/claude-code/claude-agent.js +319 -0
  30. package/dist/core/agents/claude-code/credentials.js +142 -0
  31. package/dist/core/agents/claude-code/events.js +11 -0
  32. package/dist/core/agents/claude-code/login.js +217 -0
  33. package/dist/core/agents/claude-code/mcp.js +181 -0
  34. package/dist/core/agents/claude-code/models.js +74 -0
  35. package/dist/core/agents/claude-code/options.js +240 -0
  36. package/dist/core/agents/claude-code/outcome.js +204 -0
  37. package/dist/core/agents/claude-code/results.js +58 -0
  38. package/dist/core/agents/claude-code/sdk-pair.js +59 -0
  39. package/dist/core/agents/claude-code/session.js +593 -0
  40. package/dist/core/agents/claude-code/spawn.js +125 -0
  41. package/dist/core/agents/claude-code/spend.js +118 -0
  42. package/dist/core/agents/claude-code/tools.js +131 -0
  43. package/dist/core/agents/claude-code/turn-usage.js +121 -0
  44. package/dist/core/agents/claude-code/turn.js +199 -0
  45. package/dist/core/agents/codex-app-server/adapter.js +463 -0
  46. package/dist/core/agents/codex-app-server/client.js +338 -0
  47. package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
  48. package/dist/core/agents/codex-app-server/commands.js +184 -0
  49. package/dist/core/agents/codex-app-server/credentials.js +92 -0
  50. package/dist/core/agents/codex-app-server/effort.js +13 -0
  51. package/dist/core/agents/codex-app-server/events.js +18 -0
  52. package/dist/core/agents/codex-app-server/homes.js +118 -0
  53. package/dist/core/agents/codex-app-server/input.js +52 -0
  54. package/dist/core/agents/codex-app-server/items.js +307 -0
  55. package/dist/core/agents/codex-app-server/login.js +183 -0
  56. package/dist/core/agents/codex-app-server/mcp.js +323 -0
  57. package/dist/core/agents/codex-app-server/models.js +160 -0
  58. package/dist/core/agents/codex-app-server/options.js +155 -0
  59. package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
  60. package/dist/core/agents/codex-app-server/protocol.js +38 -0
  61. package/dist/core/agents/codex-app-server/requests.js +250 -0
  62. package/dist/core/agents/codex-app-server/session.js +278 -0
  63. package/dist/core/agents/codex-app-server/subagents.js +260 -0
  64. package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
  65. package/dist/core/agents/codex-app-server/turn-items.js +69 -0
  66. package/dist/core/agents/codex-app-server/turn.js +448 -0
  67. package/dist/core/agents/codex-app-server/user-login.js +78 -0
  68. package/dist/core/agents/config-fingerprint.js +10 -0
  69. package/dist/core/agents/credentials.js +71 -0
  70. package/dist/core/agents/diffs.js +27 -0
  71. package/dist/core/agents/elicitation.js +42 -0
  72. package/dist/core/agents/inherit-config.js +5 -0
  73. package/dist/core/agents/login.js +56 -0
  74. package/dist/core/agents/mcp-config.js +109 -0
  75. package/dist/core/agents/plan.js +6 -0
  76. package/dist/core/agents/process-pool.js +307 -0
  77. package/dist/core/agents/registry.js +49 -0
  78. package/dist/core/agents/scripted/adapter.js +86 -0
  79. package/dist/core/agents/scripted/mcp-call.js +74 -0
  80. package/dist/core/agents/scripted/scripted-agent.js +330 -0
  81. package/dist/core/agents/scripted/scripts.js +154 -0
  82. package/dist/core/agents/scripted/steps.js +87 -0
  83. package/dist/core/agents/session-agent.js +209 -0
  84. package/dist/core/agents/stderr-tail.js +71 -0
  85. package/dist/core/agents/thinking-levels.js +9 -0
  86. package/dist/core/agents/types.js +1 -0
  87. package/dist/core/diagnostics.js +23 -0
  88. package/dist/core/index.js +31 -0
  89. package/dist/core/presets.js +114 -0
  90. package/dist/core/processes/identity.js +91 -0
  91. package/dist/core/processes/lifeline.js +210 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +163 -0
  94. package/dist/core/provision/cache-trust.js +121 -0
  95. package/dist/core/provision/cache-usage.js +61 -0
  96. package/dist/core/provision/checksums.js +22 -0
  97. package/dist/core/provision/extract.js +28 -0
  98. package/dist/core/provision/index.js +4 -0
  99. package/dist/core/provision/install-build.js +99 -0
  100. package/dist/core/provision/npm.js +316 -0
  101. package/dist/core/provision/pins.js +35 -0
  102. package/dist/core/provision/platform.js +65 -0
  103. package/dist/core/provision/provisioner.js +372 -0
  104. package/dist/core/provision/releases.js +68 -0
  105. package/dist/core/provision/tools.js +279 -0
  106. package/dist/core/proxy/anthropic-proxy.js +163 -0
  107. package/dist/core/proxy/api-key-store.js +30 -0
  108. package/dist/core/proxy/index.js +3 -0
  109. package/dist/core/proxy/loopback.js +86 -0
  110. package/dist/core/runtime/agent-runtime.js +434 -0
  111. package/dist/core/runtime/event-processor.js +379 -0
  112. package/dist/core/runtime/event-sink.js +65 -0
  113. package/dist/core/runtime/harness-clis.js +83 -0
  114. package/dist/core/runtime/harness-logins.js +313 -0
  115. package/dist/core/runtime/login-reads.js +71 -0
  116. package/dist/core/runtime/model-lists.js +160 -0
  117. package/dist/core/runtime/permission-policy.js +84 -0
  118. package/dist/core/runtime/request-broker.js +139 -0
  119. package/dist/core/runtime/steering.js +79 -0
  120. package/dist/core/runtime/turn-outcome.js +16 -0
  121. package/dist/core/runtime/turn.js +329 -0
  122. package/dist/core/utils/bounded.js +13 -0
  123. package/dist/core/utils/deadline.js +57 -0
  124. package/dist/core/utils/errors.js +176 -0
  125. package/dist/core/utils/is-record.js +4 -0
  126. package/dist/core/utils/loopback.js +11 -0
  127. package/dist/index.js +4 -0
  128. package/dist/operator/index.js +10 -0
  129. package/dist/operator/mcp.js +139 -0
  130. package/dist/operator/operator.js +499 -0
  131. package/dist/operator/render.js +408 -0
  132. package/dist/operator/view.js +35 -0
  133. package/dist/protocol/account.js +96 -0
  134. package/dist/protocol/async-queue.js +65 -0
  135. package/dist/protocol/auth.js +169 -0
  136. package/dist/protocol/canonical.js +18 -0
  137. package/dist/protocol/clis.js +63 -0
  138. package/dist/protocol/config.js +137 -0
  139. package/dist/protocol/conversation.js +231 -0
  140. package/dist/protocol/credentials.js +141 -0
  141. package/dist/protocol/errors.js +181 -0
  142. package/dist/protocol/execution.js +28 -0
  143. package/dist/protocol/factories.js +231 -0
  144. package/dist/protocol/guards.js +71 -0
  145. package/dist/protocol/harness.js +93 -0
  146. package/dist/protocol/history.js +201 -0
  147. package/dist/protocol/ids.js +37 -0
  148. package/dist/protocol/index.js +36 -0
  149. package/dist/protocol/lifecycle.js +562 -0
  150. package/dist/protocol/meta-keys.js +17 -0
  151. package/dist/protocol/meta.js +13 -0
  152. package/dist/protocol/model-catalog.js +223 -0
  153. package/dist/protocol/models.js +84 -0
  154. package/dist/protocol/part-input.js +94 -0
  155. package/dist/protocol/parts.js +166 -0
  156. package/dist/protocol/plan.js +31 -0
  157. package/dist/protocol/reduce.js +484 -0
  158. package/dist/protocol/selectors.js +136 -0
  159. package/dist/protocol/seq-cursor.js +37 -0
  160. package/dist/protocol/stop-reasons.js +41 -0
  161. package/dist/protocol/thinking.js +31 -0
  162. package/dist/protocol/time.js +21 -0
  163. package/dist/protocol/tokens.js +57 -0
  164. package/dist/protocol/tool-closure.js +70 -0
  165. package/dist/protocol/tool-state.js +153 -0
  166. package/dist/protocol/verify.js +467 -0
  167. package/dist/protocol/vocabulary.js +27 -0
  168. package/dist/protocol/wire-api.js +94 -0
  169. package/dist/protocol/wire.js +669 -0
  170. package/dist/server/acp/binding.js +251 -0
  171. package/dist/server/acp/session-records.js +53 -0
  172. package/dist/server/acp/translate.js +401 -0
  173. package/dist/server/agent-server.js +338 -0
  174. package/dist/server/bin.js +492 -0
  175. package/dist/server/feedback.js +216 -0
  176. package/dist/server/history.js +123 -0
  177. package/dist/server/index.js +8 -0
  178. package/dist/server/install.js +171 -0
  179. package/dist/server/open-parts.js +87 -0
  180. package/dist/server/routes.js +291 -0
  181. package/dist/server/secrets.js +19 -0
  182. package/dist/server/session-gate.js +54 -0
  183. package/dist/server/session-log.js +66 -0
  184. package/dist/server/session-store.js +243 -0
  185. package/dist/server/subscriptions.js +189 -0
  186. package/dist/server/transports.js +214 -0
  187. package/dist/server/wire-error.js +26 -0
  188. package/dist/sync/event-log.js +89 -0
  189. package/dist/sync/fit.js +202 -0
  190. package/dist/sync/history-reader.js +33 -0
  191. package/dist/sync/history-sqlite.js +281 -0
  192. package/dist/sync/history.js +163 -0
  193. package/dist/sync/index.js +5 -0
  194. package/dist/sync/journal-sqlite.js +316 -0
  195. package/dist/sync/journal.js +10 -0
  196. package/dist/sync/live-tails.js +85 -0
  197. package/dist/sync/node-sqlite.js +27 -0
  198. package/dist/sync/projection.js +32 -0
  199. package/dist/sync/recovery.js +117 -0
  200. package/dist/sync/retry.js +45 -0
  201. package/dist/sync/schema.js +73 -0
  202. package/dist/sync/sql.js +94 -0
  203. package/dist/sync/sqlite-file.js +31 -0
  204. package/dist/sync/sqlite.js +18 -0
  205. package/dist/sync/worker.js +212 -0
  206. package/dist/types/accounts/chatgpt.d.ts +1 -1
  207. package/dist/types/accounts/chatgpt.d.ts.map +1 -1
  208. package/dist/types/accounts/http.d.ts +2 -4
  209. package/dist/types/accounts/http.d.ts.map +1 -1
  210. package/dist/types/client/client.d.ts +37 -11
  211. package/dist/types/client/client.d.ts.map +1 -1
  212. package/dist/types/client/connection.d.ts +64 -13
  213. package/dist/types/client/connection.d.ts.map +1 -1
  214. package/dist/types/client/index.d.ts +1 -1
  215. package/dist/types/client/index.d.ts.map +1 -1
  216. package/dist/types/client/logins.d.ts +2 -1
  217. package/dist/types/client/logins.d.ts.map +1 -1
  218. package/dist/types/client/streams.d.ts +9 -3
  219. package/dist/types/client/streams.d.ts.map +1 -1
  220. package/dist/types/client/turns.d.ts +1 -1
  221. package/dist/types/client/turns.d.ts.map +1 -1
  222. package/dist/types/core/agents/acp/acp-agent.d.ts +34 -1
  223. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  224. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  225. package/dist/types/core/agents/acp/client.d.ts +12 -3
  226. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  227. package/dist/types/core/agents/acp/mappings.d.ts +8 -2
  228. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  229. package/dist/types/core/agents/base.d.ts +22 -8
  230. package/dist/types/core/agents/base.d.ts.map +1 -1
  231. package/dist/types/core/agents/claude-code/adapter.d.ts +7 -0
  232. package/dist/types/core/agents/claude-code/adapter.d.ts.map +1 -1
  233. package/dist/types/core/agents/claude-code/approvals.d.ts +4 -1
  234. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  235. package/dist/types/core/agents/claude-code/claude-agent.d.ts +19 -5
  236. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  237. package/dist/types/core/agents/claude-code/events.d.ts +9 -1
  238. package/dist/types/core/agents/claude-code/events.d.ts.map +1 -1
  239. package/dist/types/core/agents/claude-code/login.d.ts +4 -1
  240. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  241. package/dist/types/core/agents/claude-code/mcp.d.ts +21 -7
  242. package/dist/types/core/agents/claude-code/mcp.d.ts.map +1 -1
  243. package/dist/types/core/agents/claude-code/models.d.ts +5 -1
  244. package/dist/types/core/agents/claude-code/models.d.ts.map +1 -1
  245. package/dist/types/core/agents/claude-code/options.d.ts +29 -10
  246. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  247. package/dist/types/core/agents/claude-code/outcome.d.ts +3 -5
  248. package/dist/types/core/agents/claude-code/outcome.d.ts.map +1 -1
  249. package/dist/types/core/agents/claude-code/results.d.ts +16 -0
  250. package/dist/types/core/agents/claude-code/results.d.ts.map +1 -0
  251. package/dist/types/core/agents/claude-code/sdk-pair.d.ts +13 -0
  252. package/dist/types/core/agents/claude-code/sdk-pair.d.ts.map +1 -0
  253. package/dist/types/core/agents/claude-code/session.d.ts +58 -12
  254. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  255. package/dist/types/core/agents/claude-code/spend.d.ts +2 -1
  256. package/dist/types/core/agents/claude-code/spend.d.ts.map +1 -1
  257. package/dist/types/core/agents/claude-code/tools.d.ts +26 -3
  258. package/dist/types/core/agents/claude-code/tools.d.ts.map +1 -1
  259. package/dist/types/core/agents/codex-app-server/adapter.d.ts +2 -2
  260. package/dist/types/core/agents/codex-app-server/adapter.d.ts.map +1 -1
  261. package/dist/types/core/agents/codex-app-server/client.d.ts +12 -2
  262. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  263. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +58 -13
  264. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  265. package/dist/types/core/agents/codex-app-server/commands.d.ts +2 -2
  266. package/dist/types/core/agents/codex-app-server/commands.d.ts.map +1 -1
  267. package/dist/types/core/agents/codex-app-server/credentials.d.ts +5 -1
  268. package/dist/types/core/agents/codex-app-server/credentials.d.ts.map +1 -1
  269. package/dist/types/core/agents/codex-app-server/effort.d.ts +2 -1
  270. package/dist/types/core/agents/codex-app-server/effort.d.ts.map +1 -1
  271. package/dist/types/core/agents/codex-app-server/homes.d.ts +25 -0
  272. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  273. package/dist/types/core/agents/codex-app-server/items.d.ts +27 -2
  274. package/dist/types/core/agents/codex-app-server/items.d.ts.map +1 -1
  275. package/dist/types/core/agents/codex-app-server/login.d.ts +16 -1
  276. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  277. package/dist/types/core/agents/codex-app-server/mcp.d.ts +15 -30
  278. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  279. package/dist/types/core/agents/codex-app-server/models.d.ts +3 -10
  280. package/dist/types/core/agents/codex-app-server/models.d.ts.map +1 -1
  281. package/dist/types/core/agents/codex-app-server/options.d.ts +27 -4
  282. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  283. package/dist/types/core/agents/codex-app-server/plan-approval.d.ts +2 -1
  284. package/dist/types/core/agents/codex-app-server/plan-approval.d.ts.map +1 -1
  285. package/dist/types/core/agents/codex-app-server/protocol.d.ts +16 -3
  286. package/dist/types/core/agents/codex-app-server/protocol.d.ts.map +1 -1
  287. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  288. package/dist/types/core/agents/codex-app-server/session.d.ts +71 -40
  289. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  290. package/dist/types/core/agents/codex-app-server/subagents.d.ts +9 -4
  291. package/dist/types/core/agents/codex-app-server/subagents.d.ts.map +1 -1
  292. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts +3 -2
  293. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts.map +1 -1
  294. package/dist/types/core/agents/codex-app-server/turn-items.d.ts +2 -1
  295. package/dist/types/core/agents/codex-app-server/turn-items.d.ts.map +1 -1
  296. package/dist/types/core/agents/codex-app-server/turn.d.ts +31 -8
  297. package/dist/types/core/agents/codex-app-server/turn.d.ts.map +1 -1
  298. package/dist/types/core/agents/codex-app-server/user-login.d.ts +28 -0
  299. package/dist/types/core/agents/codex-app-server/user-login.d.ts.map +1 -0
  300. package/dist/types/core/agents/credentials.d.ts +3 -1
  301. package/dist/types/core/agents/credentials.d.ts.map +1 -1
  302. package/dist/types/core/agents/diffs.d.ts +9 -0
  303. package/dist/types/core/agents/diffs.d.ts.map +1 -0
  304. package/dist/types/core/agents/elicitation.d.ts +3 -2
  305. package/dist/types/core/agents/elicitation.d.ts.map +1 -1
  306. package/dist/types/core/agents/login.d.ts +6 -0
  307. package/dist/types/core/agents/login.d.ts.map +1 -1
  308. package/dist/types/core/agents/mcp-config.d.ts +0 -4
  309. package/dist/types/core/agents/mcp-config.d.ts.map +1 -1
  310. package/dist/types/core/agents/process-pool.d.ts +201 -0
  311. package/dist/types/core/agents/process-pool.d.ts.map +1 -0
  312. package/dist/types/core/agents/scripted/adapter.d.ts +68 -0
  313. package/dist/types/core/agents/scripted/adapter.d.ts.map +1 -0
  314. package/dist/types/core/agents/scripted/mcp-call.d.ts +56 -0
  315. package/dist/types/core/agents/scripted/mcp-call.d.ts.map +1 -0
  316. package/dist/types/core/agents/scripted/scripted-agent.d.ts +73 -0
  317. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -0
  318. package/dist/types/core/agents/scripted/scripts.d.ts +29 -0
  319. package/dist/types/core/agents/scripted/scripts.d.ts.map +1 -0
  320. package/dist/types/core/agents/scripted/steps.d.ts +132 -0
  321. package/dist/types/core/agents/scripted/steps.d.ts.map +1 -0
  322. package/dist/types/core/agents/session-agent.d.ts +49 -6
  323. package/dist/types/core/agents/session-agent.d.ts.map +1 -1
  324. package/dist/types/core/diagnostics.d.ts +4 -1
  325. package/dist/types/core/diagnostics.d.ts.map +1 -1
  326. package/dist/types/core/index.d.ts +5 -0
  327. package/dist/types/core/index.d.ts.map +1 -1
  328. package/dist/types/core/presets.d.ts +32 -6
  329. package/dist/types/core/presets.d.ts.map +1 -1
  330. package/dist/types/core/processes/lifeline.d.ts +0 -20
  331. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  332. package/dist/types/core/provision/index.d.ts +2 -2
  333. package/dist/types/core/provision/index.d.ts.map +1 -1
  334. package/dist/types/core/provision/install-build.d.ts +2 -1
  335. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  336. package/dist/types/core/provision/npm.d.ts +20 -8
  337. package/dist/types/core/provision/npm.d.ts.map +1 -1
  338. package/dist/types/core/provision/provisioner.d.ts +4 -1
  339. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  340. package/dist/types/core/provision/tools.d.ts +2 -1
  341. package/dist/types/core/provision/tools.d.ts.map +1 -1
  342. package/dist/types/core/runtime/agent-runtime.d.ts +16 -8
  343. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  344. package/dist/types/core/runtime/event-processor.d.ts +5 -1
  345. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  346. package/dist/types/core/runtime/harness-clis.d.ts +9 -0
  347. package/dist/types/core/runtime/harness-clis.d.ts.map +1 -1
  348. package/dist/types/core/runtime/harness-logins.d.ts +33 -5
  349. package/dist/types/core/runtime/harness-logins.d.ts.map +1 -1
  350. package/dist/types/core/runtime/model-lists.d.ts +2 -0
  351. package/dist/types/core/runtime/model-lists.d.ts.map +1 -1
  352. package/dist/types/core/runtime/permission-policy.d.ts +5 -3
  353. package/dist/types/core/runtime/permission-policy.d.ts.map +1 -1
  354. package/dist/types/core/runtime/request-broker.d.ts +2 -1
  355. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  356. package/dist/types/core/runtime/turn.d.ts +12 -1
  357. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  358. package/dist/types/core/utils/deadline.d.ts +6 -0
  359. package/dist/types/core/utils/deadline.d.ts.map +1 -1
  360. package/dist/types/core/utils/errors.d.ts +7 -1
  361. package/dist/types/core/utils/errors.d.ts.map +1 -1
  362. package/dist/types/operator/operator.d.ts.map +1 -1
  363. package/dist/types/operator/render.d.ts +6 -4
  364. package/dist/types/operator/render.d.ts.map +1 -1
  365. package/dist/types/protocol/auth.d.ts +54 -24
  366. package/dist/types/protocol/auth.d.ts.map +1 -1
  367. package/dist/types/protocol/clis.d.ts +14 -7
  368. package/dist/types/protocol/clis.d.ts.map +1 -1
  369. package/dist/types/protocol/config.d.ts +2 -0
  370. package/dist/types/protocol/config.d.ts.map +1 -1
  371. package/dist/types/protocol/conversation.d.ts +40 -3
  372. package/dist/types/protocol/conversation.d.ts.map +1 -1
  373. package/dist/types/protocol/credentials.d.ts +7 -0
  374. package/dist/types/protocol/credentials.d.ts.map +1 -1
  375. package/dist/types/protocol/execution.d.ts +2 -1
  376. package/dist/types/protocol/execution.d.ts.map +1 -1
  377. package/dist/types/protocol/factories.d.ts +12 -2
  378. package/dist/types/protocol/factories.d.ts.map +1 -1
  379. package/dist/types/protocol/harness.d.ts +6 -2
  380. package/dist/types/protocol/harness.d.ts.map +1 -1
  381. package/dist/types/protocol/history.d.ts +19 -0
  382. package/dist/types/protocol/history.d.ts.map +1 -1
  383. package/dist/types/protocol/lifecycle.d.ts +47 -8
  384. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  385. package/dist/types/protocol/model-catalog.d.ts.map +1 -1
  386. package/dist/types/protocol/models.d.ts +3 -0
  387. package/dist/types/protocol/models.d.ts.map +1 -1
  388. package/dist/types/protocol/parts.d.ts +14 -0
  389. package/dist/types/protocol/parts.d.ts.map +1 -1
  390. package/dist/types/protocol/tool-state.d.ts +12 -0
  391. package/dist/types/protocol/tool-state.d.ts.map +1 -1
  392. package/dist/types/protocol/wire-api.d.ts +129 -23
  393. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  394. package/dist/types/protocol/wire.d.ts +70 -10
  395. package/dist/types/protocol/wire.d.ts.map +1 -1
  396. package/dist/types/server/acp/binding.d.ts +6 -1
  397. package/dist/types/server/acp/binding.d.ts.map +1 -1
  398. package/dist/types/server/acp/translate.d.ts +33 -7
  399. package/dist/types/server/acp/translate.d.ts.map +1 -1
  400. package/dist/types/server/agent-server.d.ts +6 -0
  401. package/dist/types/server/agent-server.d.ts.map +1 -1
  402. package/dist/types/server/bin.d.ts +3 -0
  403. package/dist/types/server/bin.d.ts.map +1 -0
  404. package/dist/types/server/feedback.d.ts +2 -1
  405. package/dist/types/server/feedback.d.ts.map +1 -1
  406. package/dist/types/server/install.d.ts +11 -0
  407. package/dist/types/server/install.d.ts.map +1 -1
  408. package/dist/types/server/session-gate.d.ts +2 -1
  409. package/dist/types/server/session-gate.d.ts.map +1 -1
  410. package/dist/types/server/session-store.d.ts +1 -0
  411. package/dist/types/server/session-store.d.ts.map +1 -1
  412. package/dist/types/server/subscriptions.d.ts +2 -1
  413. package/dist/types/server/subscriptions.d.ts.map +1 -1
  414. package/dist/types/server/transports.d.ts +2 -1
  415. package/dist/types/server/transports.d.ts.map +1 -1
  416. package/dist/types/sync/fit.d.ts +8 -7
  417. package/dist/types/sync/fit.d.ts.map +1 -1
  418. package/dist/types/sync/history-sqlite.d.ts.map +1 -1
  419. package/dist/types/sync/index.d.ts +1 -0
  420. package/dist/types/sync/index.d.ts.map +1 -1
  421. package/dist/types/sync/journal-sqlite.d.ts +2 -1
  422. package/dist/types/sync/journal-sqlite.d.ts.map +1 -1
  423. package/dist/types/sync/journal.d.ts +11 -3
  424. package/dist/types/sync/journal.d.ts.map +1 -1
  425. package/dist/types/sync/node-sqlite.d.ts +4 -1
  426. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  427. package/dist/types/sync/projection.d.ts +6 -0
  428. package/dist/types/sync/projection.d.ts.map +1 -1
  429. package/dist/types/sync/recovery.d.ts +2 -1
  430. package/dist/types/sync/recovery.d.ts.map +1 -1
  431. package/dist/types/sync/schema.d.ts +10 -0
  432. package/dist/types/sync/schema.d.ts.map +1 -1
  433. package/dist/types/sync/sql.d.ts +2 -1
  434. package/dist/types/sync/sql.d.ts.map +1 -1
  435. package/docs/consuming.md +304 -28
  436. package/docs/deploy.md +64 -8
  437. package/docs/durable-sessions.md +35 -5
  438. package/docs/harnesses.md +398 -25
  439. package/package.json +48 -18
  440. package/src/accounts/chatgpt.ts +2 -2
  441. package/src/accounts/http.ts +2 -16
  442. package/src/client/client.ts +92 -31
  443. package/src/client/connection.ts +103 -22
  444. package/src/client/index.ts +1 -0
  445. package/src/client/logins.ts +1 -1
  446. package/src/client/streams.ts +12 -4
  447. package/src/client/turns.ts +1 -1
  448. package/src/core/agents/acp/acp-agent.ts +181 -52
  449. package/src/core/agents/acp/adapter.ts +9 -1
  450. package/src/core/agents/acp/client.ts +16 -4
  451. package/src/core/agents/acp/mappings.ts +27 -0
  452. package/src/core/agents/base.ts +25 -10
  453. package/src/core/agents/claude-code/adapter.ts +47 -17
  454. package/src/core/agents/claude-code/approvals.ts +11 -6
  455. package/src/core/agents/claude-code/claude-agent.ts +89 -32
  456. package/src/core/agents/claude-code/events.ts +11 -1
  457. package/src/core/agents/claude-code/login.ts +14 -2
  458. package/src/core/agents/claude-code/mcp.ts +31 -15
  459. package/src/core/agents/claude-code/models.ts +7 -2
  460. package/src/core/agents/claude-code/options.ts +30 -9
  461. package/src/core/agents/claude-code/outcome.ts +10 -2
  462. package/src/core/agents/claude-code/results.ts +73 -0
  463. package/src/core/agents/claude-code/sdk-pair.ts +66 -0
  464. package/src/core/agents/claude-code/session.ts +179 -37
  465. package/src/core/agents/claude-code/spend.ts +1 -1
  466. package/src/core/agents/claude-code/tools.ts +108 -12
  467. package/src/core/agents/codex-app-server/adapter.ts +37 -12
  468. package/src/core/agents/codex-app-server/client.ts +37 -8
  469. package/src/core/agents/codex-app-server/codex-agent.ts +115 -50
  470. package/src/core/agents/codex-app-server/commands.ts +2 -2
  471. package/src/core/agents/codex-app-server/credentials.ts +10 -5
  472. package/src/core/agents/codex-app-server/effort.ts +1 -1
  473. package/src/core/agents/codex-app-server/homes.ts +54 -3
  474. package/src/core/agents/codex-app-server/items.ts +219 -31
  475. package/src/core/agents/codex-app-server/login.ts +44 -2
  476. package/src/core/agents/codex-app-server/mcp.ts +47 -32
  477. package/src/core/agents/codex-app-server/models.ts +9 -8
  478. package/src/core/agents/codex-app-server/options.ts +69 -10
  479. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  480. package/src/core/agents/codex-app-server/protocol.ts +14 -4
  481. package/src/core/agents/codex-app-server/requests.ts +17 -8
  482. package/src/core/agents/codex-app-server/session.ts +160 -113
  483. package/src/core/agents/codex-app-server/subagents.ts +21 -14
  484. package/src/core/agents/codex-app-server/thread-settings.ts +18 -8
  485. package/src/core/agents/codex-app-server/turn-items.ts +1 -1
  486. package/src/core/agents/codex-app-server/turn.ts +79 -32
  487. package/src/core/agents/codex-app-server/user-login.ts +107 -0
  488. package/src/core/agents/credentials.ts +5 -2
  489. package/src/core/agents/diffs.ts +25 -0
  490. package/src/core/agents/elicitation.ts +2 -2
  491. package/src/core/agents/login.ts +6 -0
  492. package/src/core/agents/mcp-config.ts +2 -2
  493. package/src/core/agents/process-pool.ts +458 -0
  494. package/src/core/agents/scripted/adapter.ts +142 -0
  495. package/src/core/agents/scripted/mcp-call.ts +134 -0
  496. package/src/core/agents/scripted/scripted-agent.ts +418 -0
  497. package/src/core/agents/scripted/scripts.ts +171 -0
  498. package/src/core/agents/scripted/steps.ts +127 -0
  499. package/src/core/agents/session-agent.ts +105 -8
  500. package/src/core/diagnostics.ts +9 -1
  501. package/src/core/index.ts +11 -0
  502. package/src/core/presets.ts +100 -14
  503. package/src/core/processes/lifeline.ts +99 -25
  504. package/src/core/provision/index.ts +1 -2
  505. package/src/core/provision/install-build.ts +4 -1
  506. package/src/core/provision/npm.ts +309 -97
  507. package/src/core/provision/provisioner.ts +22 -8
  508. package/src/core/provision/tools.ts +44 -19
  509. package/src/core/runtime/agent-runtime.ts +48 -18
  510. package/src/core/runtime/event-processor.ts +18 -2
  511. package/src/core/runtime/harness-clis.ts +36 -1
  512. package/src/core/runtime/harness-logins.ts +82 -31
  513. package/src/core/runtime/model-lists.ts +1 -1
  514. package/src/core/runtime/permission-policy.ts +4 -3
  515. package/src/core/runtime/request-broker.ts +1 -1
  516. package/src/core/runtime/turn.ts +51 -3
  517. package/src/core/utils/deadline.ts +23 -0
  518. package/src/core/utils/errors.ts +11 -4
  519. package/src/operator/operator.ts +8 -4
  520. package/src/operator/render.ts +46 -8
  521. package/src/protocol/auth.ts +30 -23
  522. package/src/protocol/clis.ts +12 -4
  523. package/src/protocol/credentials.ts +19 -0
  524. package/src/protocol/execution.ts +5 -0
  525. package/src/protocol/factories.ts +25 -3
  526. package/src/protocol/harness.ts +11 -1
  527. package/src/protocol/history.ts +20 -0
  528. package/src/protocol/lifecycle.ts +10 -1
  529. package/src/protocol/model-catalog.ts +19 -8
  530. package/src/protocol/parts.ts +12 -1
  531. package/src/protocol/tool-state.ts +14 -1
  532. package/src/protocol/wire.ts +14 -0
  533. package/src/server/acp/binding.ts +113 -23
  534. package/src/server/acp/translate.ts +161 -8
  535. package/src/server/agent-server.ts +10 -1
  536. package/src/server/bin.ts +108 -19
  537. package/src/server/feedback.ts +1 -1
  538. package/src/server/install.ts +82 -4
  539. package/src/server/session-gate.ts +1 -1
  540. package/src/server/session-store.ts +5 -1
  541. package/src/server/subscriptions.ts +1 -1
  542. package/src/server/transports.ts +20 -1
  543. package/src/sync/fit.ts +115 -28
  544. package/src/sync/history-sqlite.ts +6 -2
  545. package/src/sync/index.ts +1 -0
  546. package/src/sync/journal-sqlite.ts +20 -2
  547. package/src/sync/journal.ts +10 -2
  548. package/src/sync/node-sqlite.ts +19 -3
  549. package/src/sync/projection.ts +10 -0
  550. package/src/sync/recovery.ts +11 -4
  551. package/src/sync/schema.ts +7 -5
  552. package/src/sync/sql.ts +1 -1
  553. package/dist/types/core/agents/claude-code/session-pool.d.ts +0 -36
  554. package/dist/types/core/agents/claude-code/session-pool.d.ts.map +0 -1
  555. package/dist/types/core/agents/session-pool.d.ts +0 -41
  556. package/dist/types/core/agents/session-pool.d.ts.map +0 -1
  557. package/src/core/agents/claude-code/session-pool.ts +0 -136
  558. package/src/core/agents/session-pool.ts +0 -111
@@ -1,13 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
- import { once } from "node:events";
3
- import { createWriteStream } from "node:fs";
2
+ import { createReadStream } from "node:fs";
3
+ import { open, stat, writeFile } from "node:fs/promises";
4
+ import type { ErrorCategory } from "../../protocol/index.ts";
4
5
  import { withTimeout } from "../utils/deadline.ts";
5
6
  import { CliProvisionError } from "../utils/errors.ts";
6
7
 
7
8
  export const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
8
9
 
9
10
  /** The subset of npm packument `dist` we need to fetch a package verifiably. */
10
- export interface NpmDist {
11
+ interface NpmDist {
11
12
  tarball: string;
12
13
  /** Subresource integrity, e.g. `sha512-<base64>`. */
13
14
  integrity: string;
@@ -33,13 +34,66 @@ export function withoutSecrets(text: string): string {
33
34
  });
34
35
  }
35
36
 
36
- /** How long a request may wait for its response, and a download for its next bytes. */
37
+ /**
38
+ * How long a request may wait for its response, a download for its next
39
+ * bytes, and an install before asking again (doubled each time it asks again).
40
+ */
37
41
  export interface DownloadTimeouts {
38
42
  responseMs: number;
39
43
  stallMs: number;
44
+ retryDelayMs?: number;
45
+ }
46
+
47
+ export const DEFAULT_DOWNLOAD_TIMEOUTS: DownloadTimeouts = {
48
+ responseMs: 30_000,
49
+ stallMs: 30_000,
50
+ retryDelayMs: 1_000,
51
+ };
52
+
53
+ /**
54
+ * The metadata request is asked this many times, each waiting one deadline
55
+ * longer than the last (30 s, 60 s, 90 s): a slow registry answers on a later
56
+ * attempt instead of failing at the first deadline.
57
+ */
58
+ const METADATA_ATTEMPTS = 3;
59
+ /**
60
+ * A download is asked again after a cut, from the bytes it has, until this
61
+ * many attempts in a row bring nothing new; an attempt that gets further
62
+ * into the file than any before it starts the count again. However much each brings, it gives up after
63
+ * `DOWNLOAD_ATTEMPTS_IN_ALL`.
64
+ */
65
+ const DOWNLOAD_ATTEMPTS_IN_A_ROW = 5;
66
+ const DOWNLOAD_ATTEMPTS_IN_ALL = 25;
67
+ /** The longest wait between two attempts. */
68
+ const MAX_RETRY_DELAY_MS = 10_000;
69
+
70
+ /** A failure the next attempt may not have: no answer, a cut or a stall. Always `network`. */
71
+ class TransientFailure extends CliProvisionError {
72
+ constructor(message: string, options?: { cause?: unknown }) {
73
+ super(message, { ...options, category: "network" });
74
+ }
40
75
  }
41
76
 
42
- export const DEFAULT_DOWNLOAD_TIMEOUTS: DownloadTimeouts = { responseMs: 30_000, stallMs: 30_000 };
77
+ /** What a registry's answer with this status says failed. */
78
+ function statusCategory(status: number): ErrorCategory {
79
+ if (status === 401 || status === 403) return "auth";
80
+ if (status === 429) return "rate_limit";
81
+ return status >= 500 ? "network" : "internal";
82
+ }
83
+
84
+ function messageOf(error: unknown): string {
85
+ return error instanceof Error ? error.message : String(error);
86
+ }
87
+
88
+ function pause(ms: number): Promise<void> {
89
+ return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
90
+ }
91
+
92
+ /** The wait before attempt `again` + 1, after `again` attempts in a row failed. */
93
+ function retryDelay(timeouts: DownloadTimeouts, again: number): number {
94
+ const base = timeouts.retryDelayMs ?? DEFAULT_DOWNLOAD_TIMEOUTS.retryDelayMs ?? 0;
95
+ return Math.min(MAX_RETRY_DELAY_MS, base * 2 ** Math.max(0, again - 1));
96
+ }
43
97
 
44
98
  /** A response, and the abort that ends its body (a stalled download's). */
45
99
  interface OpenResponse {
@@ -47,44 +101,62 @@ interface OpenResponse {
47
101
  abort: AbortController;
48
102
  }
49
103
 
50
- /** One retry on network-level failures and a response that never came; 4xx/5xx are not retried. */
51
- async function fetchOk(
104
+ /**
105
+ * One request: its response within `deadlineMs`, or a `TransientFailure`
106
+ * (no answer, a connection that failed). An answer that is not 2xx is a
107
+ * failure of its status's category, never asked again: a 5xx is `network`.
108
+ */
109
+ async function request(
52
110
  fetchImpl: FetchLike,
53
111
  url: string,
54
- timeouts: DownloadTimeouts,
112
+ deadlineMs: number,
113
+ headers?: Record<string, string>,
55
114
  ): Promise<OpenResponse> {
56
- let lastError: unknown;
57
- for (let attempt = 0; attempt < 2; attempt++) {
58
- const abort = new AbortController();
59
- const timer = setTimeout(() => abort.abort(), timeouts.responseMs);
60
- try {
61
- const res = await fetchImpl(url, { signal: abort.signal });
62
- if (!res.ok) {
63
- await res.body?.cancel().catch(() => {});
64
- throw new CliProvisionError(
65
- `GET ${withoutSecrets(url)} failed: ${res.status} ${res.statusText}`,
66
- );
67
- }
68
- return { res, abort };
69
- } catch (error) {
70
- if (error instanceof CliProvisionError) throw error;
71
- lastError = abort.signal.aborted
72
- ? new Error(`no response within ${timeouts.responseMs / 1000} s`)
73
- : error;
74
- } finally {
75
- clearTimeout(timer);
115
+ const abort = new AbortController();
116
+ const timer = setTimeout(() => abort.abort(), deadlineMs);
117
+ try {
118
+ const res = await fetchImpl(url, {
119
+ signal: abort.signal,
120
+ // A fresh connection each time: Bun's fetch (1.3) sends a request again by itself
121
+ // when a reused connection is cut mid-body, and splices the second body onto the first.
122
+ keepalive: false,
123
+ ...(headers && { headers }),
124
+ });
125
+ if (!res.ok) {
126
+ await res.body?.cancel().catch(() => {});
127
+ throw new CliProvisionError(
128
+ `GET ${withoutSecrets(url)} failed: ${res.status} ${res.statusText}`,
129
+ { category: statusCategory(res.status) },
130
+ );
76
131
  }
132
+ return { res, abort };
133
+ } catch (error) {
134
+ if (error instanceof CliProvisionError) throw error;
135
+ throw new TransientFailure(
136
+ abort.signal.aborted
137
+ ? `no response within ${deadlineMs / 1000} s`
138
+ : withoutSecrets(messageOf(error)),
139
+ { cause: error },
140
+ );
141
+ } finally {
142
+ clearTimeout(timer);
77
143
  }
78
- throw new CliProvisionError(
79
- `GET ${withoutSecrets(url)} failed: ${withoutSecrets(lastError instanceof Error ? lastError.message : String(lastError))}`,
80
- { cause: lastError },
144
+ }
145
+
146
+ /** The failure an install reports after `attempts` attempts, the last of which failed with `last`. */
147
+ function gaveUp(url: string, attempts: number, last: TransientFailure): CliProvisionError {
148
+ return new CliProvisionError(
149
+ `GET ${withoutSecrets(url)} failed${attempts > 1 ? ` after ${attempts} attempts` : ""}: ${last.message}`,
150
+ { cause: last.cause ?? last, category: "network" },
81
151
  );
82
152
  }
83
153
 
84
154
  /**
85
155
  * Fetch the registry metadata for one exact package version and return its
86
156
  * tarball location + integrity. The returned tarball URL is the registry's own
87
- * (works with mirrors/private registries that rewrite hosts).
157
+ * (works with mirrors/private registries that rewrite hosts). A request
158
+ * without an answer (its body included: a proxy can send the headers and
159
+ * stall) is asked again, each time waiting longer.
88
160
  */
89
161
  export async function fetchDist(
90
162
  registry: string,
@@ -96,53 +168,113 @@ export async function fetchDist(
96
168
  // Scoped names keep the literal `@` but escape the inner slash.
97
169
  const base = registry.replace(/\/+$/, "");
98
170
  const url = `${base}/${packageName.replace("/", "%2F")}/${version}`;
99
- const { res, abort } = await fetchOk(fetchImpl, url, timeouts);
100
- // The body has the same deadline as the headers: a proxy can send those and stall.
101
- const read = await withTimeout(res.json(), timeouts.responseMs);
102
- if (!read) {
103
- abort.abort();
104
- throw new CliProvisionError(
105
- `GET ${withoutSecrets(url)} failed: no response within ${timeouts.responseMs / 1000} s`,
106
- );
171
+ let body: unknown;
172
+ // The first answer ends the loop, whatever it holds: only no answer is asked again.
173
+ for (let attempt = 1; ; attempt++) {
174
+ const deadlineMs = timeouts.responseMs * attempt;
175
+ try {
176
+ const { res, abort } = await request(fetchImpl, url, deadlineMs);
177
+ const read = await withTimeout(res.json(), deadlineMs);
178
+ if (!read) {
179
+ abort.abort();
180
+ throw new TransientFailure(`no response within ${deadlineMs / 1000} s`);
181
+ }
182
+ body = read.value;
183
+ break;
184
+ } catch (error) {
185
+ // A page that is not JSON (a captive portal's, a proxy's) is a wrong answer.
186
+ if (error instanceof SyntaxError)
187
+ throw new CliProvisionError(
188
+ `GET ${withoutSecrets(url)} did not answer with JSON: is something in front of the registry?`,
189
+ { cause: error, category: "internal" },
190
+ );
191
+ // An answer of the wrong status is final; a body that broke off (a cut, a reset) is not.
192
+ if (error instanceof CliProvisionError && !(error instanceof TransientFailure)) throw error;
193
+ const failure =
194
+ error instanceof TransientFailure
195
+ ? error
196
+ : new TransientFailure(withoutSecrets(messageOf(error)), { cause: error });
197
+ if (attempt >= METADATA_ATTEMPTS) throw gaveUp(url, attempt, failure);
198
+ await pause(retryDelay(timeouts, attempt));
199
+ }
107
200
  }
108
- const body = read.value as { dist?: { tarball?: string; integrity?: string } };
109
- const { tarball, integrity } = body.dist ?? {};
201
+ // A body that is not an object (`null`, `false`, a string) is not metadata either.
202
+ const dist =
203
+ typeof body === "object" && body !== null
204
+ ? (body as { dist?: { tarball?: string; integrity?: string } }).dist
205
+ : undefined;
206
+ const { tarball, integrity } = dist ?? {};
110
207
  if (!tarball || !integrity) {
111
208
  throw new CliProvisionError(
112
209
  `Registry metadata for ${packageName}@${version} has no dist.tarball/integrity — is this version published for your platform?`,
210
+ { category: "internal" },
113
211
  );
114
212
  }
115
213
  return { tarball, integrity };
116
214
  }
117
215
 
118
- export interface DownloadOptions {
216
+ interface DownloadOptions {
119
217
  timeouts?: DownloadTimeouts;
120
218
  /** The bytes received so far, and the total when the response states it. */
121
219
  onBytes?: (received: number, total: number | undefined) => void;
122
220
  }
123
221
 
222
+ /** What one attempt left: the file's size, and the whole download's when a response stated it. */
223
+ interface Received {
224
+ size: number;
225
+ total: number | undefined;
226
+ }
227
+
228
+ async function sizeOf(path: string): Promise<number> {
229
+ return (await stat(path)).size;
230
+ }
231
+
232
+ /** `bytes <start>-<end>/<total>` of a 206, its total `undefined` when `*`. */
233
+ function contentRange(header: string | null): { start: number; total?: number } | undefined {
234
+ const match = /^bytes (\d+)-\d+\/(\d+|\*)$/.exec(header?.trim() ?? "");
235
+ if (!match) return undefined;
236
+ return { start: Number(match[1]), ...(match[2] !== "*" && { total: Number(match[2]) }) };
237
+ }
238
+
124
239
  /**
125
- * Stream a tarball to disk, hashing as it lands, and reject on integrity
126
- * mismatch. Only sha512 (what the npm registry publishes) is supported.
127
- * A download that receives nothing for `stallMs` fails. Returns the byte
128
- * count for progress logs.
240
+ * One attempt at the rest of a download: from the file's `have` bytes with a
241
+ * `Range` request when it has some, starting over when the server answers
242
+ * with the whole file instead. Appends what arrives, and fails transiently on
243
+ * a cut, a stall, or an end short of the stated size.
129
244
  */
130
- export async function downloadWithIntegrity(
245
+ async function receive(
246
+ fetchImpl: FetchLike,
131
247
  url: string,
132
248
  destFile: string,
133
- integrity: string,
134
- fetchImpl: FetchLike = fetch,
135
- options: DownloadOptions = {},
136
- ): Promise<number> {
137
- const expected = /^sha512-([A-Za-z0-9+/=]+)$/.exec(integrity)?.[1];
138
- if (!expected) {
139
- throw new CliProvisionError(`Unsupported integrity format (want sha512-…): ${integrity}`);
140
- }
141
- const timeouts = options.timeouts ?? DEFAULT_DOWNLOAD_TIMEOUTS;
142
- const { res, abort } = await fetchOk(fetchImpl, url, timeouts);
143
- if (!res.body) throw new CliProvisionError(`GET ${withoutSecrets(url)} returned no body`);
249
+ have: number,
250
+ deadlineMs: number,
251
+ timeouts: DownloadTimeouts,
252
+ onBytes: DownloadOptions["onBytes"],
253
+ ): Promise<Received> {
254
+ // No `If-Range`: a published npm version never changes, and the whole file's hash decides.
255
+ const { res, abort } = await request(
256
+ fetchImpl,
257
+ url,
258
+ deadlineMs,
259
+ have > 0 ? { range: `bytes=${have}-` } : undefined,
260
+ );
144
261
  const length = Number(res.headers.get("content-length"));
145
- const stated = Number.isSafeInteger(length) && length > 0 ? length : undefined;
262
+ const stated = Number.isSafeInteger(length) && length >= 0 ? length : undefined;
263
+ let offset = 0;
264
+ let total: number | undefined;
265
+ const range = res.status === 206 ? contentRange(res.headers.get("content-range")) : undefined;
266
+ if (res.status === 206 && range?.start === have) {
267
+ offset = have;
268
+ total = range.total ?? (stated !== undefined ? have + stated : undefined);
269
+ } else if (res.status === 206) {
270
+ // A part of something else: nothing here can be kept.
271
+ await res.body?.cancel().catch(() => {});
272
+ await writeFile(destFile, "");
273
+ throw new TransientFailure(
274
+ `asked for the bytes from ${have}, the server answered ${res.headers.get("content-range") ?? "a part it did not name"}`,
275
+ );
276
+ } else total = stated && stated > 0 ? stated : undefined;
277
+ if (!res.body) throw new CliProvisionError(`GET ${withoutSecrets(url)} returned no body`);
146
278
  // Read by hand, so a stall ends the read even where the fetch ignores its signal.
147
279
  const reader = res.body.getReader();
148
280
  let stalled = false;
@@ -155,55 +287,135 @@ export async function downloadWithIntegrity(
155
287
  void reader.cancel().catch(() => {});
156
288
  }, timeouts.stallMs);
157
289
  };
158
-
159
- const hash = createHash("sha512");
160
- const out = createWriteStream(destFile);
161
- // One persistent listener: an unobserved WriteStream 'error' would crash the
162
- // process, and per-chunk `once("error")` listeners would accumulate instead.
163
- let streamError: unknown;
164
- out.on("error", (error) => {
165
- streamError = error;
166
- });
167
- let bytes = 0;
290
+ // The whole file again (the server did not honour the range): it starts over.
291
+ const file = await open(destFile, offset ? "a" : "w");
292
+ let size = offset;
293
+ const of = () => (total !== undefined ? `${size} of ${total}` : `${size}`);
168
294
  try {
169
295
  while (true) {
170
296
  // Only the wait for the network counts as a stall, not for the disk.
171
297
  armStall();
172
- const { done, value } = await reader.read();
173
- clearTimeout(stall);
174
- if (stalled) throw new Error("stalled");
175
- if (done) break;
176
- if (streamError) throw streamError;
177
- hash.update(value);
178
- bytes += value.byteLength;
298
+ let chunk: Awaited<ReturnType<typeof reader.read>>;
299
+ try {
300
+ chunk = await reader.read();
301
+ } catch (error) {
302
+ if (stalled) break;
303
+ throw new TransientFailure(
304
+ `the transfer was cut after ${of()} bytes (${withoutSecrets(messageOf(error))})`,
305
+ {
306
+ cause: error,
307
+ },
308
+ );
309
+ } finally {
310
+ clearTimeout(stall);
311
+ }
312
+ if (stalled || chunk.done) break;
313
+ await file.write(chunk.value);
314
+ size += chunk.value.byteLength;
179
315
  // A size the response got wrong is no size.
180
- options.onBytes?.(bytes, stated !== undefined && bytes <= stated ? stated : undefined);
181
- // events.once rejects on 'error' and removes its listeners either way.
182
- if (!out.write(value)) await once(out, "drain");
316
+ onBytes?.(size, total !== undefined && size <= total ? total : undefined);
183
317
  }
184
- if (streamError) throw streamError;
185
- // Reject on 'error' too: a failure during the terminal flush (e.g.
186
- // ENOSPC on the last buffered chunk) never fires the end callback, and
187
- // without this listener the await would hang instead of surfacing it.
188
- await new Promise<void>((resolve, reject) => {
189
- out.once("error", reject);
190
- out.end(() => (streamError ? reject(streamError as Error) : resolve()));
191
- });
192
318
  } catch (error) {
193
- clearTimeout(stall);
194
319
  void reader.cancel().catch(() => {});
195
- out.destroy();
196
- if (stalled)
197
- throw new CliProvisionError(
198
- `GET ${withoutSecrets(url)} stalled: nothing received for ${timeouts.stallMs / 1000} s after ${bytes} bytes`,
199
- );
200
320
  throw error;
321
+ } finally {
322
+ clearTimeout(stall);
323
+ await file.close();
324
+ }
325
+ if (stalled)
326
+ throw new TransientFailure(
327
+ `stalled: nothing received for ${timeouts.stallMs / 1000} s after ${of()} bytes`,
328
+ );
329
+ if (total !== undefined && size < total)
330
+ throw new TransientFailure(`the transfer ended after ${of()} bytes`);
331
+ return { size, total };
332
+ }
333
+
334
+ /**
335
+ * The whole file into `destFile`, asked again after each transient failure
336
+ * from the bytes it has, and how many responses it took (`pieces`).
337
+ */
338
+ async function fetchWhole(
339
+ url: string,
340
+ destFile: string,
341
+ fetchImpl: FetchLike,
342
+ timeouts: DownloadTimeouts,
343
+ onBytes: DownloadOptions["onBytes"],
344
+ ): Promise<Received & { pieces: number }> {
345
+ await writeFile(destFile, "");
346
+ let inARow = 0;
347
+ // The most of the file it has had: a start over that gets as far again brings nothing new.
348
+ let furthest = 0;
349
+ for (let attempt = 1; ; attempt++) {
350
+ const have = await sizeOf(destFile);
351
+ try {
352
+ const got = await receive(
353
+ fetchImpl,
354
+ url,
355
+ destFile,
356
+ have,
357
+ // A slow answer gets longer each time it fails to come.
358
+ timeouts.responseMs * Math.min(inARow + 1, METADATA_ATTEMPTS),
359
+ timeouts,
360
+ onBytes,
361
+ );
362
+ return { size: got.size, total: got.total, pieces: attempt };
363
+ } catch (error) {
364
+ if (!(error instanceof TransientFailure)) throw error;
365
+ const now = await sizeOf(destFile);
366
+ inARow = now > furthest ? 1 : inARow + 1;
367
+ furthest = Math.max(furthest, now);
368
+ if (inARow >= DOWNLOAD_ATTEMPTS_IN_A_ROW || attempt >= DOWNLOAD_ATTEMPTS_IN_ALL)
369
+ throw gaveUp(url, attempt, error);
370
+ await pause(retryDelay(timeouts, inARow));
371
+ }
372
+ }
373
+ }
374
+
375
+ async function sha512Of(path: string): Promise<string> {
376
+ const hash = createHash("sha512");
377
+ for await (const chunk of createReadStream(path)) hash.update(chunk as Buffer);
378
+ return hash.digest("base64");
379
+ }
380
+
381
+ /**
382
+ * Download a tarball to `destFile`, and reject unless its sha512 matches
383
+ * (only sha512, what the npm registry publishes, is supported). A transfer
384
+ * that is cut, stalls (nothing for `stallMs`) or ends short of its stated size
385
+ * is asked again from the bytes it has (an HTTP `Range` request; from the
386
+ * start where the server does not honour one), a bounded number of times,
387
+ * and failing that is a `network` failure that says how far it got. The
388
+ * hash is checked once, over the whole file as it is on disk, so "integrity
389
+ * mismatch" is said only of a file that arrived whole; a file put together
390
+ * from more than one response whose hash is wrong is downloaded once more
391
+ * first, since a resumed part may not be the file's. Returns the byte count.
392
+ */
393
+ export async function downloadWithIntegrity(
394
+ url: string,
395
+ destFile: string,
396
+ integrity: string,
397
+ fetchImpl: FetchLike = fetch,
398
+ options: DownloadOptions = {},
399
+ ): Promise<number> {
400
+ const expected = /^sha512-([A-Za-z0-9+/=]+)$/.exec(integrity)?.[1];
401
+ if (!expected) {
402
+ throw new CliProvisionError(`Unsupported integrity format (want sha512-…): ${integrity}`);
403
+ }
404
+ const timeouts = options.timeouts ?? DEFAULT_DOWNLOAD_TIMEOUTS;
405
+ let got = await fetchWhole(url, destFile, fetchImpl, timeouts, options.onBytes);
406
+ let actual = await sha512Of(destFile);
407
+ const again = actual !== expected && got.pieces > 1;
408
+ if (again) {
409
+ got = await fetchWhole(url, destFile, fetchImpl, timeouts, options.onBytes);
410
+ actual = await sha512Of(destFile);
201
411
  }
202
- const actual = hash.digest("base64");
203
412
  if (actual !== expected) {
204
413
  throw new CliProvisionError(
205
- `Integrity mismatch for ${withoutSecrets(url)}: expected sha512-${expected}, got sha512-${actual}`,
414
+ `Integrity mismatch for ${withoutSecrets(url)} (all ${got.size} bytes${
415
+ got.total === undefined ? ", of a size the server did not state" : ""
416
+ }${again ? ", downloaded twice" : ""}): expected sha512-${expected}, got sha512-${actual}`,
417
+ { category: "internal" },
206
418
  );
207
419
  }
208
- return bytes;
420
+ return got.size;
209
421
  }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { delimiter, dirname, join, resolve } from "node:path";
4
+ import { type ErrorCategory, classifyError } from "../../protocol/index.ts";
4
5
  import { CliProvisionError } from "../utils/errors.ts";
5
6
  import {
6
7
  managedDirectory,
@@ -89,8 +90,9 @@ export interface CliProgress {
89
90
  receivedBytes: number;
90
91
  /** The download's size, when the registry states it. */
91
92
  totalBytes?: number;
92
- /** Why it failed. */
93
+ /** Why it failed, and what failed (`network`: ask again later). */
93
94
  error?: string;
95
+ category?: ErrorCategory;
94
96
  }
95
97
 
96
98
  /** Where a CLI is, found without installing anything. */
@@ -99,7 +101,17 @@ export type CliStatus =
99
101
  /** `version` is what an install would fetch; absent where nothing installs (`system`). */
100
102
  | { state: "missing"; version?: string }
101
103
  | { state: "installing"; version: string; receivedBytes: number; totalBytes?: number }
102
- | { state: "failed"; version?: string; error: string };
104
+ | { state: "failed"; version?: string; error: string; category: ErrorCategory };
105
+
106
+ /** Why an install failed, and what failed. */
107
+ interface Failure {
108
+ error: string;
109
+ category: ErrorCategory;
110
+ }
111
+
112
+ function failureOf(error: unknown): Failure {
113
+ return { error: messageOf(error), category: classifyError(error) };
114
+ }
103
115
 
104
116
  /** Process/machine seams, injectable so the policy is testable offline. */
105
117
  export interface ProvisionerDeps {
@@ -166,7 +178,7 @@ export class CliProvisioner {
166
178
  /** Each tool's download while it runs. */
167
179
  private readonly downloads = new Map<CliTool, CliProgress>();
168
180
  /** Each tool's last failure to resolve, until one succeeds. */
169
- private readonly failures = new Map<CliTool, string>();
181
+ private readonly failures = new Map<CliTool, Failure>();
170
182
  /** The cache entries this process runs (`<tool>/<entry>`), and when each use was last recorded. */
171
183
  private readonly inUse = new Map<string, number>();
172
184
  /** Lines said once per process, however often a status asks. */
@@ -239,7 +251,7 @@ export class CliProvisioner {
239
251
  const found = this.locate(tool);
240
252
  if (found) return { state: "ready", ...found };
241
253
  } catch (error) {
242
- return { state: "failed", error: messageOf(error) };
254
+ return { state: "failed", ...failureOf(error) };
243
255
  }
244
256
  const { version } = this.build(tool);
245
257
  const download = this.downloads.get(tool);
@@ -254,8 +266,8 @@ export class CliProvisioner {
254
266
  const failure = this.failures.get(tool);
255
267
  // Where nothing installs (`system`), there is no version to name.
256
268
  if (this.mode === "system")
257
- return failure ? { state: "failed", error: failure } : { state: "missing" };
258
- return failure ? { state: "failed", version, error: failure } : { state: "missing", version };
269
+ return failure ? { state: "failed", ...failure } : { state: "missing" };
270
+ return failure ? { state: "failed", version, ...failure } : { state: "missing", version };
259
271
  }
260
272
 
261
273
  /**
@@ -313,7 +325,7 @@ export class CliProvisioner {
313
325
  this.failures.delete(tool);
314
326
  return result;
315
327
  } catch (error) {
316
- this.failures.set(tool, messageOf(error));
328
+ this.failures.set(tool, failureOf(error));
317
329
  throw error;
318
330
  } finally {
319
331
  const left = (this.resolving.get(tool) ?? 1) - 1;
@@ -343,6 +355,7 @@ export class CliProvisioner {
343
355
  throw new CliProvisionError(
344
356
  `${tool} CLI override points to a missing file: ${override} ` +
345
357
  `(from ${this.overrides[tool] ? "options.overrides" : `$${spec.overrideEnv}`})`,
358
+ { category: "invalid_request" },
346
359
  );
347
360
  }
348
361
  return { path: override, source: "override" };
@@ -453,7 +466,7 @@ export class CliProvisioner {
453
466
  );
454
467
  report({ phase: "ready" });
455
468
  } catch (error) {
456
- report({ phase: "failed", error: messageOf(error) });
469
+ report({ phase: "failed", ...failureOf(error) });
457
470
  throw error;
458
471
  } finally {
459
472
  this.downloads.delete(tool);
@@ -486,6 +499,7 @@ export class CliProvisioner {
486
499
  if ((MODES as readonly string[]).includes(raw)) return raw as ProvisionMode;
487
500
  throw new CliProvisionError(
488
501
  `Invalid $AGENT_SERVER_PROVISION: ${raw} (expected ${MODES.join(" | ")})`,
502
+ { category: "invalid_request" },
489
503
  );
490
504
  }
491
505
  }