@zvada/agent-server 0.3.18 → 0.3.19

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 (572) hide show
  1. package/AGENTS.md +11 -26
  2. package/CHANGELOG.md +1005 -1
  3. package/README.md +35 -39
  4. package/dist/types/accounts/chatgpt.d.ts +34 -0
  5. package/dist/types/accounts/chatgpt.d.ts.map +1 -0
  6. package/dist/types/accounts/check.d.ts +24 -0
  7. package/dist/types/accounts/check.d.ts.map +1 -0
  8. package/dist/types/accounts/claude.d.ts +21 -0
  9. package/dist/types/accounts/claude.d.ts.map +1 -0
  10. package/dist/types/accounts/endpoint.d.ts +50 -0
  11. package/dist/types/accounts/endpoint.d.ts.map +1 -0
  12. package/dist/types/accounts/http.d.ts +38 -0
  13. package/dist/types/accounts/http.d.ts.map +1 -0
  14. package/dist/types/accounts/index.d.ts +6 -0
  15. package/dist/types/accounts/index.d.ts.map +1 -0
  16. package/dist/types/client/client.d.ts +272 -0
  17. package/dist/types/client/client.d.ts.map +1 -0
  18. package/dist/types/client/connection.d.ts +160 -0
  19. package/dist/types/client/connection.d.ts.map +1 -0
  20. package/dist/types/client/history.d.ts +8 -0
  21. package/dist/types/client/history.d.ts.map +1 -0
  22. package/dist/types/client/index.d.ts +5 -0
  23. package/dist/types/client/index.d.ts.map +1 -0
  24. package/dist/types/client/listeners.d.ts +8 -0
  25. package/dist/types/client/listeners.d.ts.map +1 -0
  26. package/dist/types/client/logins.d.ts +35 -0
  27. package/dist/types/client/logins.d.ts.map +1 -0
  28. package/dist/types/client/rpc.d.ts +46 -0
  29. package/dist/types/client/rpc.d.ts.map +1 -0
  30. package/dist/types/client/streams.d.ts +150 -0
  31. package/dist/types/client/streams.d.ts.map +1 -0
  32. package/dist/types/client/transports.d.ts +35 -0
  33. package/dist/types/client/transports.d.ts.map +1 -0
  34. package/dist/types/client/turns.d.ts +81 -0
  35. package/dist/types/client/turns.d.ts.map +1 -0
  36. package/dist/types/core/agents/acp/acp-agent.d.ts +68 -0
  37. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -0
  38. package/dist/types/core/agents/acp/adapter.d.ts +39 -0
  39. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -0
  40. package/dist/types/core/agents/acp/client.d.ts +90 -0
  41. package/dist/types/core/agents/acp/client.d.ts.map +1 -0
  42. package/dist/types/core/agents/acp/known-agents.d.ts +35 -0
  43. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -0
  44. package/dist/types/core/agents/acp/mappings.d.ts +46 -0
  45. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -0
  46. package/dist/types/core/agents/acp/requests.d.ts +26 -0
  47. package/dist/types/core/agents/acp/requests.d.ts.map +1 -0
  48. package/dist/types/core/agents/attachments.d.ts +11 -0
  49. package/dist/types/core/agents/attachments.d.ts.map +1 -0
  50. package/dist/types/core/agents/base.d.ts +227 -0
  51. package/dist/types/core/agents/base.d.ts.map +1 -0
  52. package/dist/types/core/agents/claude-code/adapter.d.ts +58 -0
  53. package/dist/types/core/agents/claude-code/adapter.d.ts.map +1 -0
  54. package/dist/types/core/agents/claude-code/approvals.d.ts +26 -0
  55. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -0
  56. package/dist/types/core/agents/claude-code/claude-agent.d.ts +70 -0
  57. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -0
  58. package/dist/types/core/agents/claude-code/credentials.d.ts +54 -0
  59. package/dist/types/core/agents/claude-code/credentials.d.ts.map +1 -0
  60. package/dist/types/core/agents/claude-code/events.d.ts +42 -0
  61. package/dist/types/core/agents/claude-code/events.d.ts.map +1 -0
  62. package/dist/types/core/agents/claude-code/login.d.ts +61 -0
  63. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -0
  64. package/dist/types/core/agents/claude-code/mcp.d.ts +52 -0
  65. package/dist/types/core/agents/claude-code/mcp.d.ts.map +1 -0
  66. package/dist/types/core/agents/claude-code/models.d.ts +30 -0
  67. package/dist/types/core/agents/claude-code/models.d.ts.map +1 -0
  68. package/dist/types/core/agents/claude-code/options.d.ts +183 -0
  69. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -0
  70. package/dist/types/core/agents/claude-code/outcome.d.ts +50 -0
  71. package/dist/types/core/agents/claude-code/outcome.d.ts.map +1 -0
  72. package/dist/types/core/agents/claude-code/session-pool.d.ts +36 -0
  73. package/dist/types/core/agents/claude-code/session-pool.d.ts.map +1 -0
  74. package/dist/types/core/agents/claude-code/session.d.ts +148 -0
  75. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -0
  76. package/dist/types/core/agents/claude-code/spawn.d.ts +29 -0
  77. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -0
  78. package/dist/types/core/agents/claude-code/spend.d.ts +58 -0
  79. package/dist/types/core/agents/claude-code/spend.d.ts.map +1 -0
  80. package/dist/types/core/agents/claude-code/tools.d.ts +4 -0
  81. package/dist/types/core/agents/claude-code/tools.d.ts.map +1 -0
  82. package/dist/types/core/agents/claude-code/turn-usage.d.ts +52 -0
  83. package/dist/types/core/agents/claude-code/turn-usage.d.ts.map +1 -0
  84. package/dist/types/core/agents/claude-code/turn.d.ts +121 -0
  85. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -0
  86. package/dist/types/core/agents/codex-app-server/adapter.d.ts +59 -0
  87. package/dist/types/core/agents/codex-app-server/adapter.d.ts.map +1 -0
  88. package/dist/types/core/agents/codex-app-server/client.d.ts +116 -0
  89. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -0
  90. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +113 -0
  91. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -0
  92. package/dist/types/core/agents/codex-app-server/commands.d.ts +66 -0
  93. package/dist/types/core/agents/codex-app-server/commands.d.ts.map +1 -0
  94. package/dist/types/core/agents/codex-app-server/credentials.d.ts +49 -0
  95. package/dist/types/core/agents/codex-app-server/credentials.d.ts.map +1 -0
  96. package/dist/types/core/agents/codex-app-server/effort.d.ts +12 -0
  97. package/dist/types/core/agents/codex-app-server/effort.d.ts.map +1 -0
  98. package/dist/types/core/agents/codex-app-server/events.d.ts +45 -0
  99. package/dist/types/core/agents/codex-app-server/events.d.ts.map +1 -0
  100. package/dist/types/core/agents/codex-app-server/homes.d.ts +20 -0
  101. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -0
  102. package/dist/types/core/agents/codex-app-server/input.d.ts +26 -0
  103. package/dist/types/core/agents/codex-app-server/input.d.ts.map +1 -0
  104. package/dist/types/core/agents/codex-app-server/items.d.ts +31 -0
  105. package/dist/types/core/agents/codex-app-server/items.d.ts.map +1 -0
  106. package/dist/types/core/agents/codex-app-server/login.d.ts +38 -0
  107. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -0
  108. package/dist/types/core/agents/codex-app-server/mcp.d.ts +62 -0
  109. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -0
  110. package/dist/types/core/agents/codex-app-server/models.d.ts +67 -0
  111. package/dist/types/core/agents/codex-app-server/models.d.ts.map +1 -0
  112. package/dist/types/core/agents/codex-app-server/options.d.ts +40 -0
  113. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -0
  114. package/dist/types/core/agents/codex-app-server/plan-approval.d.ts +19 -0
  115. package/dist/types/core/agents/codex-app-server/plan-approval.d.ts.map +1 -0
  116. package/dist/types/core/agents/codex-app-server/protocol.d.ts +99 -0
  117. package/dist/types/core/agents/codex-app-server/protocol.d.ts.map +1 -0
  118. package/dist/types/core/agents/codex-app-server/requests.d.ts +42 -0
  119. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -0
  120. package/dist/types/core/agents/codex-app-server/session.d.ts +96 -0
  121. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -0
  122. package/dist/types/core/agents/codex-app-server/subagents.d.ts +53 -0
  123. package/dist/types/core/agents/codex-app-server/subagents.d.ts.map +1 -0
  124. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts +87 -0
  125. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts.map +1 -0
  126. package/dist/types/core/agents/codex-app-server/turn-items.d.ts +33 -0
  127. package/dist/types/core/agents/codex-app-server/turn-items.d.ts.map +1 -0
  128. package/dist/types/core/agents/codex-app-server/turn.d.ts +163 -0
  129. package/dist/types/core/agents/codex-app-server/turn.d.ts.map +1 -0
  130. package/dist/types/core/agents/config-fingerprint.d.ts +5 -0
  131. package/dist/types/core/agents/config-fingerprint.d.ts.map +1 -0
  132. package/dist/types/core/agents/credentials.d.ts +28 -0
  133. package/dist/types/core/agents/credentials.d.ts.map +1 -0
  134. package/dist/types/core/agents/elicitation.d.ts +37 -0
  135. package/dist/types/core/agents/elicitation.d.ts.map +1 -0
  136. package/dist/types/core/agents/inherit-config.d.ts +18 -0
  137. package/dist/types/core/agents/inherit-config.d.ts.map +1 -0
  138. package/dist/types/core/agents/login.d.ts +67 -0
  139. package/dist/types/core/agents/login.d.ts.map +1 -0
  140. package/dist/types/core/agents/mcp-config.d.ts +57 -0
  141. package/dist/types/core/agents/mcp-config.d.ts.map +1 -0
  142. package/dist/types/core/agents/plan.d.ts +16 -0
  143. package/dist/types/core/agents/plan.d.ts.map +1 -0
  144. package/dist/types/core/agents/registry.d.ts +30 -0
  145. package/dist/types/core/agents/registry.d.ts.map +1 -0
  146. package/dist/types/core/agents/session-agent.d.ts +48 -0
  147. package/dist/types/core/agents/session-agent.d.ts.map +1 -0
  148. package/dist/types/core/agents/session-pool.d.ts +41 -0
  149. package/dist/types/core/agents/session-pool.d.ts.map +1 -0
  150. package/dist/types/core/agents/stderr-tail.d.ts +28 -0
  151. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -0
  152. package/dist/types/core/agents/thinking-levels.d.ts +4 -0
  153. package/dist/types/core/agents/thinking-levels.d.ts.map +1 -0
  154. package/dist/types/core/agents/types.d.ts +124 -0
  155. package/dist/types/core/agents/types.d.ts.map +1 -0
  156. package/dist/types/core/diagnostics.d.ts +36 -0
  157. package/dist/types/core/diagnostics.d.ts.map +1 -0
  158. package/dist/types/core/index.d.ts +29 -0
  159. package/dist/types/core/index.d.ts.map +1 -0
  160. package/dist/types/core/presets.d.ts +80 -0
  161. package/dist/types/core/presets.d.ts.map +1 -0
  162. package/dist/types/core/processes/identity.d.ts +31 -0
  163. package/dist/types/core/processes/identity.d.ts.map +1 -0
  164. package/dist/types/core/processes/lifeline.d.ts +47 -0
  165. package/dist/types/core/processes/lifeline.d.ts.map +1 -0
  166. package/dist/types/core/processes/native-processes.d.ts +130 -0
  167. package/dist/types/core/processes/native-processes.d.ts.map +1 -0
  168. package/dist/types/core/processes/process-table.d.ts +43 -0
  169. package/dist/types/core/processes/process-table.d.ts.map +1 -0
  170. package/dist/types/core/provision/cache-trust.d.ts +13 -0
  171. package/dist/types/core/provision/cache-trust.d.ts.map +1 -0
  172. package/dist/types/core/provision/cache-usage.d.ts +14 -0
  173. package/dist/types/core/provision/cache-usage.d.ts.map +1 -0
  174. package/dist/types/core/provision/checksums.d.ts +46 -0
  175. package/dist/types/core/provision/checksums.d.ts.map +1 -0
  176. package/dist/types/core/provision/extract.d.ts +7 -0
  177. package/dist/types/core/provision/extract.d.ts.map +1 -0
  178. package/dist/types/core/provision/index.d.ts +5 -0
  179. package/dist/types/core/provision/index.d.ts.map +1 -0
  180. package/dist/types/core/provision/install-build.d.ts +36 -0
  181. package/dist/types/core/provision/install-build.d.ts.map +1 -0
  182. package/dist/types/core/provision/npm.d.ts +40 -0
  183. package/dist/types/core/provision/npm.d.ts.map +1 -0
  184. package/dist/types/core/provision/pins.d.ts +24 -0
  185. package/dist/types/core/provision/pins.d.ts.map +1 -0
  186. package/dist/types/core/provision/platform.d.ts +28 -0
  187. package/dist/types/core/provision/platform.d.ts.map +1 -0
  188. package/dist/types/core/provision/provisioner.d.ts +189 -0
  189. package/dist/types/core/provision/provisioner.d.ts.map +1 -0
  190. package/dist/types/core/provision/releases.d.ts +8 -0
  191. package/dist/types/core/provision/releases.d.ts.map +1 -0
  192. package/dist/types/core/provision/tools.d.ts +81 -0
  193. package/dist/types/core/provision/tools.d.ts.map +1 -0
  194. package/dist/types/core/proxy/anthropic-proxy.d.ts +52 -0
  195. package/dist/types/core/proxy/anthropic-proxy.d.ts.map +1 -0
  196. package/dist/types/core/proxy/api-key-store.d.ts +37 -0
  197. package/dist/types/core/proxy/api-key-store.d.ts.map +1 -0
  198. package/dist/types/core/proxy/index.d.ts +3 -0
  199. package/dist/types/core/proxy/index.d.ts.map +1 -0
  200. package/dist/types/core/proxy/loopback.d.ts +14 -0
  201. package/dist/types/core/proxy/loopback.d.ts.map +1 -0
  202. package/dist/types/core/runtime/agent-runtime.d.ts +181 -0
  203. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -0
  204. package/dist/types/core/runtime/event-processor.d.ts +87 -0
  205. package/dist/types/core/runtime/event-processor.d.ts.map +1 -0
  206. package/dist/types/core/runtime/event-sink.d.ts +44 -0
  207. package/dist/types/core/runtime/event-sink.d.ts.map +1 -0
  208. package/dist/types/core/runtime/harness-clis.d.ts +10 -0
  209. package/dist/types/core/runtime/harness-clis.d.ts.map +1 -0
  210. package/dist/types/core/runtime/harness-logins.d.ts +68 -0
  211. package/dist/types/core/runtime/harness-logins.d.ts.map +1 -0
  212. package/dist/types/core/runtime/login-reads.d.ts +28 -0
  213. package/dist/types/core/runtime/login-reads.d.ts.map +1 -0
  214. package/dist/types/core/runtime/model-lists.d.ts +37 -0
  215. package/dist/types/core/runtime/model-lists.d.ts.map +1 -0
  216. package/dist/types/core/runtime/permission-policy.d.ts +61 -0
  217. package/dist/types/core/runtime/permission-policy.d.ts.map +1 -0
  218. package/dist/types/core/runtime/request-broker.d.ts +49 -0
  219. package/dist/types/core/runtime/request-broker.d.ts.map +1 -0
  220. package/dist/types/core/runtime/steering.d.ts +38 -0
  221. package/dist/types/core/runtime/steering.d.ts.map +1 -0
  222. package/dist/types/core/runtime/turn-outcome.d.ts +21 -0
  223. package/dist/types/core/runtime/turn-outcome.d.ts.map +1 -0
  224. package/dist/types/core/runtime/turn.d.ts +121 -0
  225. package/dist/types/core/runtime/turn.d.ts.map +1 -0
  226. package/dist/types/core/utils/bounded.d.ts +6 -0
  227. package/dist/types/core/utils/bounded.d.ts.map +1 -0
  228. package/dist/types/core/utils/deadline.d.ts +14 -0
  229. package/dist/types/core/utils/deadline.d.ts.map +1 -0
  230. package/dist/types/core/utils/errors.d.ts +104 -0
  231. package/dist/types/core/utils/errors.d.ts.map +1 -0
  232. package/dist/types/core/utils/is-record.d.ts +3 -0
  233. package/dist/types/core/utils/is-record.d.ts.map +1 -0
  234. package/dist/types/core/utils/loopback.d.ts +6 -0
  235. package/dist/types/core/utils/loopback.d.ts.map +1 -0
  236. package/dist/types/index.d.ts +2 -0
  237. package/dist/types/index.d.ts.map +1 -0
  238. package/dist/types/protocol/account.d.ts +26 -0
  239. package/dist/types/protocol/account.d.ts.map +1 -0
  240. package/dist/types/protocol/async-queue.d.ts +21 -0
  241. package/dist/types/protocol/async-queue.d.ts.map +1 -0
  242. package/dist/types/protocol/auth.d.ts +228 -0
  243. package/dist/types/protocol/auth.d.ts.map +1 -0
  244. package/dist/types/protocol/canonical.d.ts +9 -0
  245. package/dist/types/protocol/canonical.d.ts.map +1 -0
  246. package/dist/types/protocol/clis.d.ts +74 -0
  247. package/dist/types/protocol/clis.d.ts.map +1 -0
  248. package/dist/types/protocol/config.d.ts +200 -0
  249. package/dist/types/protocol/config.d.ts.map +1 -0
  250. package/dist/types/protocol/conversation.d.ts +942 -0
  251. package/dist/types/protocol/conversation.d.ts.map +1 -0
  252. package/dist/types/protocol/credentials.d.ts +145 -0
  253. package/dist/types/protocol/credentials.d.ts.map +1 -0
  254. package/dist/types/protocol/errors.d.ts +36 -0
  255. package/dist/types/protocol/errors.d.ts.map +1 -0
  256. package/dist/types/protocol/execution.d.ts +28 -0
  257. package/dist/types/protocol/execution.d.ts.map +1 -0
  258. package/dist/types/protocol/factories.d.ts +94 -0
  259. package/dist/types/protocol/factories.d.ts.map +1 -0
  260. package/dist/types/protocol/guards.d.ts +55 -0
  261. package/dist/types/protocol/guards.d.ts.map +1 -0
  262. package/dist/types/protocol/harness.d.ts +70 -0
  263. package/dist/types/protocol/harness.d.ts.map +1 -0
  264. package/dist/types/protocol/history.d.ts +318 -0
  265. package/dist/types/protocol/history.d.ts.map +1 -0
  266. package/dist/types/protocol/ids.d.ts +9 -0
  267. package/dist/types/protocol/ids.d.ts.map +1 -0
  268. package/dist/types/protocol/index.d.ts +35 -0
  269. package/dist/types/protocol/index.d.ts.map +1 -0
  270. package/dist/types/protocol/lifecycle.d.ts +1190 -0
  271. package/dist/types/protocol/lifecycle.d.ts.map +1 -0
  272. package/dist/types/protocol/meta-keys.d.ts +17 -0
  273. package/dist/types/protocol/meta-keys.d.ts.map +1 -0
  274. package/dist/types/protocol/meta.d.ts +13 -0
  275. package/dist/types/protocol/meta.d.ts.map +1 -0
  276. package/dist/types/protocol/model-catalog.d.ts +11 -0
  277. package/dist/types/protocol/model-catalog.d.ts.map +1 -0
  278. package/dist/types/protocol/models.d.ts +107 -0
  279. package/dist/types/protocol/models.d.ts.map +1 -0
  280. package/dist/types/protocol/part-input.d.ts +101 -0
  281. package/dist/types/protocol/part-input.d.ts.map +1 -0
  282. package/dist/types/protocol/parts.d.ts +357 -0
  283. package/dist/types/protocol/parts.d.ts.map +1 -0
  284. package/dist/types/protocol/reduce.d.ts +26 -0
  285. package/dist/types/protocol/reduce.d.ts.map +1 -0
  286. package/dist/types/protocol/selectors.d.ts +64 -0
  287. package/dist/types/protocol/selectors.d.ts.map +1 -0
  288. package/dist/types/protocol/seq-cursor.d.ts +66 -0
  289. package/dist/types/protocol/seq-cursor.d.ts.map +1 -0
  290. package/dist/types/protocol/stop-reasons.d.ts +33 -0
  291. package/dist/types/protocol/stop-reasons.d.ts.map +1 -0
  292. package/dist/types/protocol/thinking.d.ts +28 -0
  293. package/dist/types/protocol/thinking.d.ts.map +1 -0
  294. package/dist/types/protocol/time.d.ts +21 -0
  295. package/dist/types/protocol/time.d.ts.map +1 -0
  296. package/dist/types/protocol/tokens.d.ts +29 -0
  297. package/dist/types/protocol/tokens.d.ts.map +1 -0
  298. package/dist/types/protocol/tool-closure.d.ts +25 -0
  299. package/dist/types/protocol/tool-closure.d.ts.map +1 -0
  300. package/dist/types/protocol/tool-state.d.ts +209 -0
  301. package/dist/types/protocol/tool-state.d.ts.map +1 -0
  302. package/dist/types/protocol/verify.d.ts +52 -0
  303. package/dist/types/protocol/verify.d.ts.map +1 -0
  304. package/dist/types/protocol/vocabulary.d.ts +19 -0
  305. package/dist/types/protocol/vocabulary.d.ts.map +1 -0
  306. package/dist/types/protocol/wire-api.d.ts +1983 -0
  307. package/dist/types/protocol/wire-api.d.ts.map +1 -0
  308. package/dist/types/protocol/wire.d.ts +1758 -0
  309. package/dist/types/protocol/wire.d.ts.map +1 -0
  310. package/dist/types/server/acp/binding.d.ts +33 -0
  311. package/dist/types/server/acp/binding.d.ts.map +1 -0
  312. package/dist/types/server/acp/session-records.d.ts +17 -0
  313. package/dist/types/server/acp/session-records.d.ts.map +1 -0
  314. package/dist/types/server/acp/translate.d.ts +48 -0
  315. package/dist/types/server/acp/translate.d.ts.map +1 -0
  316. package/dist/types/server/agent-server.d.ts +121 -0
  317. package/dist/types/server/agent-server.d.ts.map +1 -0
  318. package/dist/types/server/feedback.d.ts +37 -0
  319. package/dist/types/server/feedback.d.ts.map +1 -0
  320. package/dist/types/server/history.d.ts +15 -0
  321. package/dist/types/server/history.d.ts.map +1 -0
  322. package/dist/types/server/index.d.ts +7 -0
  323. package/dist/types/server/index.d.ts.map +1 -0
  324. package/dist/types/server/install.d.ts +42 -0
  325. package/dist/types/server/install.d.ts.map +1 -0
  326. package/dist/types/server/open-parts.d.ts +27 -0
  327. package/dist/types/server/open-parts.d.ts.map +1 -0
  328. package/dist/types/server/routes.d.ts +61 -0
  329. package/dist/types/server/routes.d.ts.map +1 -0
  330. package/dist/types/server/secrets.d.ts +11 -0
  331. package/dist/types/server/secrets.d.ts.map +1 -0
  332. package/dist/types/server/session-gate.d.ts +32 -0
  333. package/dist/types/server/session-gate.d.ts.map +1 -0
  334. package/dist/types/server/session-log.d.ts +39 -0
  335. package/dist/types/server/session-log.d.ts.map +1 -0
  336. package/dist/types/server/session-store.d.ts +119 -0
  337. package/dist/types/server/session-store.d.ts.map +1 -0
  338. package/dist/types/server/subscriptions.d.ts +74 -0
  339. package/dist/types/server/subscriptions.d.ts.map +1 -0
  340. package/dist/types/server/transports.d.ts +74 -0
  341. package/dist/types/server/transports.d.ts.map +1 -0
  342. package/dist/types/server/wire-error.d.ts +9 -0
  343. package/dist/types/server/wire-error.d.ts.map +1 -0
  344. package/dist/types/sync/event-log.d.ts +45 -0
  345. package/dist/types/sync/event-log.d.ts.map +1 -0
  346. package/dist/types/sync/fit.d.ts +40 -0
  347. package/dist/types/sync/fit.d.ts.map +1 -0
  348. package/dist/types/sync/history-reader.d.ts +8 -0
  349. package/dist/types/sync/history-reader.d.ts.map +1 -0
  350. package/dist/types/sync/history-sqlite.d.ts +37 -0
  351. package/dist/types/sync/history-sqlite.d.ts.map +1 -0
  352. package/dist/types/sync/history.d.ts +70 -0
  353. package/dist/types/sync/history.d.ts.map +1 -0
  354. package/dist/types/sync/index.d.ts +4 -0
  355. package/dist/types/sync/index.d.ts.map +1 -0
  356. package/dist/types/sync/journal-sqlite.d.ts +51 -0
  357. package/dist/types/sync/journal-sqlite.d.ts.map +1 -0
  358. package/dist/types/sync/journal.d.ts +107 -0
  359. package/dist/types/sync/journal.d.ts.map +1 -0
  360. package/dist/types/sync/live-tails.d.ts +30 -0
  361. package/dist/types/sync/live-tails.d.ts.map +1 -0
  362. package/dist/types/sync/node-sqlite.d.ts +7 -0
  363. package/dist/types/sync/node-sqlite.d.ts.map +1 -0
  364. package/dist/types/sync/projection.d.ts +10 -0
  365. package/dist/types/sync/projection.d.ts.map +1 -0
  366. package/dist/types/sync/recovery.d.ts +25 -0
  367. package/dist/types/sync/recovery.d.ts.map +1 -0
  368. package/dist/types/sync/retry.d.ts +25 -0
  369. package/dist/types/sync/retry.d.ts.map +1 -0
  370. package/dist/types/sync/schema.d.ts +4 -0
  371. package/dist/types/sync/schema.d.ts.map +1 -0
  372. package/dist/types/sync/sql.d.ts +38 -0
  373. package/dist/types/sync/sql.d.ts.map +1 -0
  374. package/dist/types/sync/sqlite-file.d.ts +9 -0
  375. package/dist/types/sync/sqlite-file.d.ts.map +1 -0
  376. package/dist/types/sync/sqlite.d.ts +6 -0
  377. package/dist/types/sync/sqlite.d.ts.map +1 -0
  378. package/dist/types/sync/worker.d.ts +63 -0
  379. package/dist/types/sync/worker.d.ts.map +1 -0
  380. package/docs/consuming.md +452 -53
  381. package/docs/deploy.md +218 -47
  382. package/docs/{sync-experiment.md → durable-sessions.md} +77 -72
  383. package/docs/feedback.md +116 -0
  384. package/docs/harnesses.md +212 -88
  385. package/docs/sync-history.md +29 -13
  386. package/docs/sync-integration.md +52 -66
  387. package/package.json +43 -25
  388. package/src/accounts/chatgpt.ts +194 -0
  389. package/src/accounts/check.ts +112 -0
  390. package/src/accounts/claude.ts +111 -0
  391. package/src/accounts/endpoint.ts +151 -0
  392. package/src/accounts/http.ts +97 -0
  393. package/src/accounts/index.ts +19 -0
  394. package/src/client/client.ts +604 -670
  395. package/src/client/connection.ts +371 -0
  396. package/src/client/history.ts +29 -52
  397. package/src/client/index.ts +11 -2
  398. package/src/client/listeners.ts +20 -0
  399. package/src/client/logins.ts +105 -0
  400. package/src/client/rpc.ts +144 -0
  401. package/src/client/streams.ts +488 -0
  402. package/src/client/transports.ts +62 -8
  403. package/src/client/turns.ts +171 -0
  404. package/src/core/agents/acp/acp-agent.ts +94 -118
  405. package/src/core/agents/acp/adapter.ts +20 -9
  406. package/src/core/agents/acp/client.ts +125 -47
  407. package/src/core/agents/acp/known-agents.ts +36 -4
  408. package/src/core/agents/acp/mappings.ts +64 -18
  409. package/src/core/agents/acp/requests.ts +125 -0
  410. package/src/core/agents/attachments.ts +18 -0
  411. package/src/core/agents/base.ts +120 -42
  412. package/src/core/agents/claude-code/adapter.ts +177 -238
  413. package/src/core/agents/claude-code/approvals.ts +270 -0
  414. package/src/core/agents/claude-code/claude-agent.ts +175 -158
  415. package/src/core/agents/claude-code/credentials.ts +171 -0
  416. package/src/core/agents/claude-code/events.ts +55 -0
  417. package/src/core/agents/claude-code/login.ts +269 -0
  418. package/src/core/agents/claude-code/mcp.ts +206 -0
  419. package/src/core/agents/claude-code/models.ts +15 -9
  420. package/src/core/agents/claude-code/options.ts +326 -39
  421. package/src/core/agents/claude-code/outcome.ts +209 -0
  422. package/src/core/agents/claude-code/session-pool.ts +136 -0
  423. package/src/core/agents/claude-code/session.ts +513 -0
  424. package/src/core/agents/claude-code/spawn.ts +144 -0
  425. package/src/core/agents/claude-code/spend.ts +160 -0
  426. package/src/core/agents/claude-code/tools.ts +47 -0
  427. package/src/core/agents/claude-code/turn-usage.ts +135 -0
  428. package/src/core/agents/claude-code/turn.ts +232 -0
  429. package/src/core/agents/codex-app-server/adapter.ts +314 -117
  430. package/src/core/agents/codex-app-server/client.ts +186 -84
  431. package/src/core/agents/codex-app-server/codex-agent.ts +343 -0
  432. package/src/core/agents/codex-app-server/commands.ts +228 -0
  433. package/src/core/agents/codex-app-server/credentials.ts +126 -0
  434. package/src/core/agents/codex-app-server/effort.ts +29 -0
  435. package/src/core/agents/codex-app-server/events.ts +47 -0
  436. package/src/core/agents/codex-app-server/homes.ts +64 -0
  437. package/src/core/agents/codex-app-server/input.ts +60 -0
  438. package/src/core/agents/codex-app-server/items.ts +149 -0
  439. package/src/core/agents/codex-app-server/login.ts +180 -0
  440. package/src/core/agents/codex-app-server/mcp.ts +182 -37
  441. package/src/core/agents/codex-app-server/models.ts +99 -46
  442. package/src/core/agents/codex-app-server/options.ts +146 -0
  443. package/src/core/agents/codex-app-server/plan-approval.ts +135 -0
  444. package/src/core/agents/codex-app-server/protocol.ts +117 -0
  445. package/src/core/agents/codex-app-server/requests.ts +332 -0
  446. package/src/core/agents/codex-app-server/session.ts +285 -0
  447. package/src/core/agents/codex-app-server/subagents.ts +108 -42
  448. package/src/core/agents/codex-app-server/thread-settings.ts +279 -0
  449. package/src/core/agents/codex-app-server/turn-items.ts +88 -0
  450. package/src/core/agents/codex-app-server/turn.ts +463 -0
  451. package/src/core/agents/config-fingerprint.ts +7 -14
  452. package/src/core/agents/credentials.ts +98 -0
  453. package/src/core/agents/elicitation.ts +75 -0
  454. package/src/core/agents/inherit-config.ts +21 -0
  455. package/src/core/agents/login.ts +116 -0
  456. package/src/core/agents/mcp-config.ts +112 -8
  457. package/src/core/agents/plan.ts +25 -0
  458. package/src/core/agents/registry.ts +21 -4
  459. package/src/core/agents/session-agent.ts +96 -4
  460. package/src/core/agents/{session-store.ts → session-pool.ts} +11 -5
  461. package/src/core/agents/stderr-tail.ts +75 -0
  462. package/src/core/agents/types.ts +40 -5
  463. package/src/core/index.ts +58 -48
  464. package/src/core/presets.ts +100 -39
  465. package/src/core/processes/identity.ts +113 -0
  466. package/src/core/processes/lifeline.ts +170 -0
  467. package/src/core/processes/native-processes.ts +379 -0
  468. package/src/core/processes/process-table.ts +174 -0
  469. package/src/core/provision/cache-trust.ts +121 -0
  470. package/src/core/provision/cache-usage.ts +69 -0
  471. package/src/core/provision/checksums.ts +64 -0
  472. package/src/core/provision/extract.ts +11 -2
  473. package/src/core/provision/index.ts +4 -1
  474. package/src/core/provision/install-build.ts +136 -0
  475. package/src/core/provision/npm.ts +112 -17
  476. package/src/core/provision/pins.ts +9 -33
  477. package/src/core/provision/platform.ts +12 -1
  478. package/src/core/provision/provisioner.ts +329 -397
  479. package/src/core/provision/releases.ts +86 -0
  480. package/src/core/provision/tools.ts +329 -0
  481. package/src/core/proxy/anthropic-proxy.ts +55 -25
  482. package/src/core/proxy/api-key-store.ts +2 -12
  483. package/src/core/proxy/loopback.ts +106 -0
  484. package/src/core/runtime/agent-runtime.ts +327 -498
  485. package/src/core/runtime/event-processor.ts +197 -70
  486. package/src/core/runtime/harness-clis.ts +61 -0
  487. package/src/core/runtime/harness-logins.ts +328 -0
  488. package/src/core/runtime/login-reads.ts +78 -0
  489. package/src/core/runtime/model-lists.ts +33 -48
  490. package/src/core/runtime/permission-policy.ts +113 -0
  491. package/src/core/runtime/request-broker.ts +204 -0
  492. package/src/core/runtime/steering.ts +112 -0
  493. package/src/core/runtime/turn-outcome.ts +30 -0
  494. package/src/core/runtime/turn.ts +360 -0
  495. package/src/core/utils/bounded.ts +12 -0
  496. package/src/core/utils/deadline.ts +38 -0
  497. package/src/core/utils/errors.ts +113 -21
  498. package/src/core/utils/is-record.ts +4 -0
  499. package/src/core/utils/loopback.ts +10 -0
  500. package/src/protocol/account.ts +104 -0
  501. package/src/protocol/auth.ts +199 -0
  502. package/src/protocol/canonical.ts +16 -0
  503. package/src/protocol/clis.ts +69 -0
  504. package/src/protocol/config.ts +60 -6
  505. package/src/protocol/conversation.ts +272 -0
  506. package/src/protocol/credentials.ts +145 -0
  507. package/src/protocol/errors.ts +78 -20
  508. package/src/protocol/execution.ts +5 -2
  509. package/src/protocol/factories.ts +55 -7
  510. package/src/protocol/guards.ts +55 -2
  511. package/src/protocol/harness.ts +56 -6
  512. package/src/protocol/history.ts +72 -64
  513. package/src/protocol/ids.ts +0 -12
  514. package/src/protocol/index.ts +9 -0
  515. package/src/protocol/lifecycle.ts +250 -79
  516. package/src/protocol/meta-keys.ts +17 -0
  517. package/src/protocol/meta.ts +3 -3
  518. package/src/protocol/models.ts +2 -43
  519. package/src/protocol/part-input.ts +2 -1
  520. package/src/protocol/parts.ts +12 -3
  521. package/src/protocol/reduce.ts +302 -413
  522. package/src/protocol/selectors.ts +1 -20
  523. package/src/protocol/seq-cursor.ts +14 -0
  524. package/src/protocol/stop-reasons.ts +1 -1
  525. package/src/protocol/thinking.ts +1 -30
  526. package/src/protocol/time.ts +2 -2
  527. package/src/protocol/tool-closure.ts +93 -0
  528. package/src/protocol/tool-state.ts +19 -4
  529. package/src/protocol/verify.ts +222 -92
  530. package/src/protocol/vocabulary.ts +21 -5
  531. package/src/protocol/wire-api.ts +232 -0
  532. package/src/protocol/wire.ts +351 -64
  533. package/src/server/acp/binding.ts +63 -103
  534. package/src/server/acp/session-records.ts +53 -0
  535. package/src/server/acp/translate.ts +129 -20
  536. package/src/server/agent-server.ts +223 -387
  537. package/src/server/bin.ts +280 -78
  538. package/src/server/feedback.ts +204 -14
  539. package/src/server/history.ts +116 -122
  540. package/src/server/index.ts +3 -8
  541. package/src/server/install.ts +107 -8
  542. package/src/server/open-parts.ts +95 -0
  543. package/src/server/routes.ts +391 -0
  544. package/src/server/secrets.ts +24 -0
  545. package/src/server/session-gate.ts +69 -0
  546. package/src/server/session-log.ts +14 -2
  547. package/src/server/session-store.ts +136 -72
  548. package/src/server/subscriptions.ts +232 -0
  549. package/src/server/transports.ts +125 -25
  550. package/src/server/wire-error.ts +31 -45
  551. package/src/sync/event-log.ts +31 -3
  552. package/src/sync/fit.ts +27 -11
  553. package/src/sync/history-reader.ts +10 -5
  554. package/src/sync/history-sqlite.ts +37 -42
  555. package/src/sync/history.ts +9 -15
  556. package/src/sync/index.ts +17 -5
  557. package/src/sync/journal-sqlite.ts +162 -76
  558. package/src/sync/journal.ts +91 -32
  559. package/src/sync/live-tails.ts +107 -0
  560. package/src/sync/projection.ts +35 -0
  561. package/src/sync/recovery.ts +80 -51
  562. package/src/sync/schema.ts +27 -6
  563. package/docs/rfds/0001-deterministic-echo-ids.md +0 -44
  564. package/docs/rfds/0002-native-subagents.md +0 -197
  565. package/src/client/request.ts +0 -19
  566. package/src/core/agents/claude-code/generator-session.ts +0 -572
  567. package/src/core/agents/claude-code/session-manager.ts +0 -166
  568. package/src/core/agents/codex-app-server/codex-app-server-agent.ts +0 -962
  569. package/src/core/agents/codex-items.ts +0 -149
  570. package/src/core/agents/codex-sdk/adapter.ts +0 -237
  571. package/src/core/agents/codex-sdk/codex-sdk-agent.ts +0 -330
  572. package/src/core/agents/tool-meta.ts +0 -68
@@ -1,47 +1,52 @@
1
1
  import {
2
+ type AgentHarness,
3
+ type AgentInput,
2
4
  type AsyncHistoryApi,
3
- AsyncQueue,
5
+ type AuthUpdated,
6
+ AuthUpdatedSchema,
4
7
  type DecodedEventsReplayResult,
5
- type DecodedLifecycleEvent,
6
8
  type DecodedWireEventEnvelope,
7
9
  type DurableSession,
8
- DurableSessionSchema,
10
+ type ElicitationOutcome,
11
+ type HarnessAuth,
12
+ type HarnessCli,
13
+ type HarnessCliProgress,
14
+ HarnessCliProgressSchema,
9
15
  type InitializeResult,
10
- InitializeResultSchema,
11
- type JsonRpcId,
12
16
  type ModelList,
13
17
  type ModelsListParams,
14
18
  type PermissionOutcome,
15
- PermissionRespondResultSchema,
16
- SessionCloseResultSchema,
19
+ type RunningTurn,
17
20
  type SessionConfirmStoppedParams,
18
- SessionConfirmStoppedResultSchema,
19
- ShutdownResultSchema,
21
+ SessionOverflowParamsSchema,
22
+ type SessionSubscribeResult,
20
23
  type TurnCancelResult,
21
- TurnCancelResultSchema,
22
- type TurnEndedEvent,
23
24
  type TurnReceipt,
24
- TurnReceiptSchema,
25
25
  type TurnStartParams,
26
26
  type TurnStartResult,
27
- TurnStartResultSchema,
28
- type UnknownEvent,
27
+ type TurnSteerParams,
28
+ type TurnSteerResult,
29
29
  WIRE_ERROR_CODES,
30
30
  WIRE_METHODS,
31
- WIRE_PROTOCOL_VERSION,
32
- type WireImplementationInfo,
33
31
  type WireTransport,
34
- createSeqCursor,
35
- decodeEventsReplayResult,
36
- decodeModelList,
37
32
  decodeWireEventEnvelope,
38
33
  decodeWireMessage,
39
- encodeRequest,
40
34
  generateUUIDv7,
41
- isUnknownEvent,
42
35
  } from "../protocol/index.ts";
36
+ import {
37
+ type AgentServerClientOptions,
38
+ Connection,
39
+ ConnectionClosedError,
40
+ type ConnectionEvent,
41
+ type ConnectionRefusal,
42
+ ConnectionRefusedError,
43
+ type TransportFactory,
44
+ } from "./connection.ts";
43
45
  import { createHistoryClient } from "./history.ts";
44
- import { DEFAULT_REQUEST_TIMEOUT_MS, type ResultSchema, WireRequestError } from "./request.ts";
46
+ import { Listeners } from "./listeners.ts";
47
+ import { type LoginHandle, startLogin } from "./logins.ts";
48
+ import { WireRequestError } from "./rpc.ts";
49
+ import { EventGapError, type Follow, type SessionEventGap, Streams } from "./streams.ts";
45
50
  import {
46
51
  type SpawnServerOptions,
47
52
  type WebSocketLike,
@@ -49,149 +54,121 @@ import {
49
54
  socketTransport,
50
55
  spawnTransport,
51
56
  } from "./transports.ts";
57
+ import { type Handle, type TurnHandle, Turns } from "./turns.ts";
58
+
59
+ export {
60
+ type AgentServerClientOptions,
61
+ ConnectionClosedError,
62
+ type ConnectionEvent,
63
+ type ConnectionRefusal,
64
+ ConnectionRefusedError,
65
+ EventGapError,
66
+ type SessionEventGap,
67
+ type TurnHandle,
68
+ };
52
69
 
53
- /** The transport dropped (and reconnection, if enabled, gave up). */
54
- export class ConnectionClosedError extends Error {
55
- override readonly name = "ConnectionClosedError";
56
- }
57
-
58
- /**
59
- * Events were lost irrecoverably: the replay window was evicted or the server
60
- * restarted. The consumer's local view of the session is stale.
61
- */
62
- export class EventGapError extends Error {
63
- override readonly name = "EventGapError";
70
+ export interface SubscribeOptions {
71
+ /**
72
+ * Catch up after this seq: the session's kept events after it reach
73
+ * `onEvent` first. Default: none, the head (live only). A session this
74
+ * client follows already keeps its place.
75
+ */
76
+ afterSeq?: number;
64
77
  }
65
78
 
66
- /** A delivery failure, reported before surviving events. Execution may continue. */
67
- export interface SessionEventGap {
68
- sessionId: string;
69
- reason: "evicted" | "replay_failed" | "session_missing" | "server_restarted" | "log_reset";
70
- error: EventGapError;
79
+ /** How `connect` dials. */
80
+ export interface ConnectOptions extends AgentServerClientOptions {
81
+ /**
82
+ * Sent as `Authorization: Bearer <token>` with every dial, redials
83
+ * included: what a listener with a token requires. Bun and Node only; a
84
+ * browser's WebSocket sends no headers.
85
+ */
86
+ token?: string;
71
87
  }
72
88
 
73
- /**
74
- * A running turn: consume `events` (ends after `turn.ended`) or await `result`.
75
- *
76
- * `events` yields `UnknownEvent`s too (Law 6): a newer server's event type is
77
- * delivered in order rather than dropped, so consumers persist and forward it.
78
- * Narrow with `isUnknownEvent` before switching on a known `type`;
79
- * `reduceConversation` already accepts the union as-is.
80
- */
81
- export interface TurnHandle {
89
+ /** Where a subscription started. */
90
+ export interface SessionSubscription {
82
91
  sessionId: string;
83
- turnId: string;
84
- events: AsyncIterableIterator<DecodedLifecycleEvent | UnknownEvent>;
85
- result: Promise<TurnEndedEvent>;
92
+ /** The session's last kept seq at the subscription point. */
93
+ headSeq: number;
94
+ /** The turn running at the point. */
95
+ activeTurn?: RunningTurn;
86
96
  }
87
97
 
88
- export interface AgentServerClientOptions {
89
- /**
90
- * Redial and replay missed events on transport drop. Defaults to true for
91
- * `connect`, false for `spawn`/`attach` (a respawned server is a new
92
- * process with empty session state).
93
- */
94
- reconnect?: boolean;
95
- maxReconnectAttempts?: number;
96
- /** Base reconnect delay; grows exponentially, capped at 10s. */
97
- reconnectDelayMs?: number;
98
- /** A request unanswered this long fails. With reconnection (connect mode)
99
- * the connection is presumed half-open and redialed, and the request fails
100
- * with ConnectionClosedError. Default 30s. */
101
- requestTimeoutMs?: number;
102
- /** Attempts to heal one sequence gap before failing its turn. Default 3. */
103
- maxReplayAttempts?: number;
104
- /** Delay between failed replay requests. Defaults to reconnectDelayMs. */
105
- replayRetryDelayMs?: number;
106
- /** Sent in `initialize`. */
107
- clientInfo?: WireImplementationInfo;
98
+ /** How a turn handle follows its turn (`runTurn`, `joinTurn`). */
99
+ export interface FollowOptions {
100
+ /** Stop following: `events` and `result` fail with the signal's reason, an `AbortError`. */
101
+ signal?: AbortSignal;
108
102
  }
109
103
 
110
- interface PendingRequest {
111
- resolve: (raw: unknown) => void;
112
- reject: (error: unknown) => void;
113
- timer: ReturnType<typeof setTimeout>;
104
+ export interface JoinTurnOptions extends FollowOptions {
105
+ /** The first kept event to yield. Default: the running turn's `turn.started`. */
106
+ fromSeq?: number;
114
107
  }
115
108
 
116
- interface InternalTurn {
117
- turnId: string;
118
- queue: AsyncQueue<DecodedLifecycleEvent | UnknownEvent>;
119
- resolveResult: (event: TurnEndedEvent) => void;
120
- rejectResult: (error: unknown) => void;
109
+ /** `signal` stops the handle following its turn. */
110
+ function stopOn(handle: Handle, signal: AbortSignal | undefined): void {
111
+ if (!signal) return;
112
+ const stop = () => handle.fail(signal.reason ?? new Error("stopped following the turn"));
113
+ if (signal.aborted) {
114
+ stop();
115
+ return;
116
+ }
117
+ signal.addEventListener("abort", stop, { once: true });
118
+ const off = () => signal.removeEventListener("abort", stop);
119
+ void handle.result.then(off, off);
121
120
  }
122
121
 
123
- /**
124
- * `events/replay` decoded the Law-6 way. Using `EventsReplayResultSchema`
125
- * here would embed the closed event union in the very path that heals a gap,
126
- * so a single unknown event type in the buffer would fail the replay, retry,
127
- * and take the turn handle down with an `EventGapError`.
128
- */
129
- const REPLAY_RESULT: ResultSchema<DecodedEventsReplayResult> = {
130
- safeParse(raw) {
131
- try {
132
- return { success: true, data: decodeEventsReplayResult(raw) };
133
- } catch {
134
- return { success: false };
135
- }
136
- },
137
- };
138
-
139
- /** A model list from a server that may know thinking levels this build does not. */
140
- const MODEL_LIST: ResultSchema<ModelList> = {
141
- safeParse(raw) {
142
- try {
143
- return { success: true, data: decodeModelList(raw) };
144
- } catch {
145
- return { success: false };
146
- }
147
- },
148
- };
149
-
150
- type TransportFactory = () => Promise<WireTransport> | WireTransport;
151
-
152
- /** Re-sends of a `turn/start` whose connection dropped before its ack. */
153
- const MAX_TURN_START_RESENDS = 3;
122
+ /** How often `prepareClis` asks again while an install runs, besides when one ends. */
123
+ const PREPARE_POLL_MS = 2_000;
154
124
 
155
125
  /**
156
126
  * Typed client for the agent-server wire. Turns are quick-ack: `runTurn`
157
127
  * resolves once the server accepts the turn and hands back an async iterable
158
- * that yields every lifecycle event for the session, ending with `turn.ended`.
159
- * Per-session `seq` is tracked so duplicates are dropped, in-stream gaps are
160
- * healed via `events/replay`, and — in `connect` mode — a dropped socket is
161
- * redialed and resynced transparently.
128
+ * of its events, from its `turn.started` to its `turn.ended`. The client
129
+ * follows the sessions it subscribed to (and its turns subscribe): each
130
+ * session's `seq` is tracked so duplicates are dropped and gaps healed via
131
+ * `events/replay`, and — in `connect` mode — a dropped socket is redialed and
132
+ * its sessions subscribed again.
162
133
  */
163
134
  export class AgentServerClient {
164
- private transport: WireTransport | null = null;
165
- private nextId = 1;
166
- private readonly pending = new Map<JsonRpcId, PendingRequest>();
167
- /** Per-session seq discipline — the shared `/protocol` implementation. */
168
- private readonly cursor = createSeqCursor();
169
- private readonly heldBack = new Map<
170
- string,
171
- Array<{ envelope: DecodedWireEventEnvelope; transport: WireTransport | null }>
172
- >();
173
- /** The server process behind the transport, learned at `initialize`. */
174
- private serverInstanceId: string | undefined;
175
- private readonly syncing = new Map<string, WireTransport>();
176
- private readonly eventHandlers = new Set<(envelope: DecodedWireEventEnvelope) => void>();
177
- private readonly gapHandlers = new Set<(gap: SessionEventGap) => void>();
178
- private awaitingHandshake = false;
179
- private readonly turnBySession = new Map<string, InternalTurn>();
180
- private initializePromise: Promise<InitializeResult> | null = null;
181
- private closed = false;
182
- private reconnecting = false;
183
- /** The running reconnect loop, for a request that waits to be re-sent. */
184
- private reconnection: Promise<void> | null = null;
135
+ private readonly connection: Connection;
136
+ private readonly turns = new Turns();
137
+ private readonly progress = new Listeners<HarnessCliProgress>();
138
+ private readonly authUpdates = new Listeners<AuthUpdated>();
139
+ private readonly streams: Streams;
185
140
  /** Portable history operations (`history/*`), independent of execution subscriptions. */
186
141
  readonly history: AsyncHistoryApi;
187
142
 
188
143
  private constructor(
189
- private readonly factory: TransportFactory,
144
+ factory: TransportFactory,
190
145
  private readonly options: AgentServerClientOptions,
191
- private readonly reconnectEnabled: boolean,
146
+ redials: boolean,
192
147
  ) {
148
+ this.connection = new Connection(factory, options, redials, {
149
+ line: (line, transport) => this.handleLine(line, transport),
150
+ opened: (redialed) => this.streams.reconnected(redialed),
151
+ serverChanged: () => this.streams.adoptFreshLogs(),
152
+ reconnected: () => {
153
+ this.streams.resume();
154
+ this.subscribeAgain();
155
+ },
156
+ closed: (error) => this.turns.failAll(error),
157
+ });
158
+ this.streams = new Streams(
159
+ {
160
+ transport: () => this.connection.transport,
161
+ open: () => !this.connection.closed,
162
+ replay: (sessionId, fromSeq) => this.replay(sessionId, fromSeq),
163
+ resubscribe: (sessionId, turnId) => void this.resubscribe(sessionId, turnId),
164
+ resubscribeAll: () => void this.resubscribeAll(),
165
+ maxReplayAttempts: options.maxReplayAttempts ?? 3,
166
+ replayRetryDelayMs: options.replayRetryDelayMs ?? options.reconnectDelayMs ?? 250,
167
+ },
168
+ this.turns,
169
+ );
193
170
  this.history = createHistoryClient(
194
- (method, params, schema) => this.request(method, params, schema),
171
+ (method, params) => this.connection.request(method, params),
195
172
  () => this.initialize(),
196
173
  options,
197
174
  );
@@ -206,7 +183,7 @@ export class AgentServerClient {
206
183
  options: AgentServerClientOptions = {},
207
184
  ): Promise<AgentServerClient> {
208
185
  const client = new AgentServerClient(factory, options, options.reconnect ?? true);
209
- await client.openTransport();
186
+ await client.connection.open();
210
187
  return client;
211
188
  }
212
189
 
@@ -220,21 +197,24 @@ export class AgentServerClient {
220
197
  options,
221
198
  options.reconnect ?? false,
222
199
  );
223
- await client.openTransport();
200
+ await client.connection.open();
224
201
  return client;
225
202
  }
226
203
 
227
- /** Dial a listening agent-server (reconnects by default). */
228
- static async connect(
229
- url: string,
230
- options: AgentServerClientOptions = {},
231
- ): Promise<AgentServerClient> {
204
+ /**
205
+ * Dial a listening agent-server (reconnects by default). One that refuses
206
+ * the client (401: the token it sent, or that it sent none) fails it with
207
+ * `ConnectionRefusedError`, and is not redialed.
208
+ */
209
+ static async connect(url: string, options: ConnectOptions = {}): Promise<AgentServerClient> {
210
+ const headers =
211
+ options.token === undefined ? undefined : { authorization: `Bearer ${options.token}` };
232
212
  const client = new AgentServerClient(
233
- () => connectTransport(url),
213
+ () => connectTransport(url, headers),
234
214
  options,
235
215
  options.reconnect ?? true,
236
216
  );
237
- await client.openTransport();
217
+ await client.connection.open();
238
218
  return client;
239
219
  }
240
220
 
@@ -254,178 +234,137 @@ export class AgentServerClient {
254
234
  options,
255
235
  false,
256
236
  );
257
- await client.openTransport();
237
+ await client.connection.open();
258
238
  return client;
259
239
  }
260
240
 
261
- // ---- public API --------------------------------------------------------
241
+ // ---- turns ---------------------------------------------------------------
262
242
 
263
243
  /** Handshake (memoized). Called lazily by `runTurn`/`startTurn`. */
264
244
  initialize(): Promise<InitializeResult> {
265
- this.initializePromise ??= this.request(
266
- WIRE_METHODS.initialize,
267
- { protocolVersion: WIRE_PROTOCOL_VERSION, client: this.options.clientInfo },
268
- InitializeResultSchema,
269
- )
270
- .then((result) => {
271
- if (result.protocolVersion !== WIRE_PROTOCOL_VERSION) {
272
- throw new WireRequestError(
273
- WIRE_ERROR_CODES.protocolVersionMismatch,
274
- `server selected unsupported protocol version: ${result.protocolVersion}`,
275
- { supported: [WIRE_PROTOCOL_VERSION] },
276
- );
277
- }
278
- // The restart question, answered by the handshake instead of
279
- // inferred from seq patterns: a changed identity means every session
280
- // log we were tracking died with the old process. Durable logs
281
- // (`historyId`) outlive it, and so do our cursors.
282
- const logIdentity = result.historyId ?? result.instanceId;
283
- if (this.serverInstanceId !== undefined && this.serverInstanceId !== logIdentity) {
284
- this.adoptFreshLogs();
285
- }
286
- this.serverInstanceId = logIdentity;
287
- return result;
288
- })
289
- .catch((err) => {
290
- this.initializePromise = null;
291
- throw err;
292
- });
293
- return this.initializePromise;
245
+ return this.connection.initialize();
294
246
  }
295
247
 
296
248
  /**
297
- * The server process we were talking to is gone; its logs died with it.
298
- * Drop every per-session cursor and queue so the reconnect resync replays
299
- * each fresh log from seq 1. Local views may be stale relative to the fresh
300
- * logs; consumers with durable state resnapshot on their side.
249
+ * Start a turn and stream it, from its `turn.started` to its `turn.ended`.
250
+ * Ids are minted client-side when omitted. The start subscribes this client
251
+ * to the session from its head until the turn ends, so it downloads none
252
+ * of its history; a start re-sent after a redial converges on the turn the
253
+ * server admitted and catches up on it from its `turn.started`. `signal`
254
+ * stops the handle, as on `joinTurn`: the turn runs on (`cancelTurn` stops
255
+ * it), and `onEvent` hears it to its end.
301
256
  */
302
- private adoptFreshLogs(): void {
303
- // Active turns first: their logs died with the old process, and no fresh
304
- // log will ever emit THEIR turn.ended — an un-failed handle hangs forever
305
- // (a session id the fresh process happens to reuse would even feed it
306
- // someone else's events).
307
- const sessionIds = new Set([...this.cursor.sessions(), ...this.turnBySession.keys()]);
308
- for (const sessionId of sessionIds) {
309
- this.reportEventGap(
310
- sessionId,
311
- "server_restarted",
312
- new EventGapError(
313
- `server instance changed; the turn's session log died with the old process`,
314
- ),
315
- );
316
- }
317
- for (const sessionId of this.cursor.sessions()) this.cursor.reset(sessionId);
318
- // Keep frames actually received from the fresh process: they may already
319
- // have left its bounded replay window. Only old transport entries die.
320
- for (const [sessionId, held] of this.heldBack) {
321
- const fresh = held.filter((entry) => entry.transport === this.transport);
322
- if (fresh.length) {
323
- this.heldBack.set(sessionId, fresh);
324
- this.cursor.seek(sessionId, 0);
325
- } else this.heldBack.delete(sessionId);
326
- }
327
- }
328
-
329
- /**
330
- * Start a turn and stream it. Ids are minted client-side when omitted so
331
- * events arriving around the ack are never dropped.
332
- */
333
- async runTurn(params: TurnStartParams): Promise<TurnHandle> {
257
+ async runTurn(params: TurnStartParams, options: FollowOptions = {}): Promise<TurnHandle> {
334
258
  await this.initialize();
335
259
  const sessionId = params.sessionId ?? generateUUIDv7();
336
260
  const turnId = params.turnId ?? generateUUIDv7();
337
- if (this.turnBySession.has(sessionId)) {
261
+ if (this.turns.running(sessionId))
338
262
  throw new Error(`session ${sessionId} already has an active turn`);
339
- }
340
- const queue = new AsyncQueue<DecodedLifecycleEvent | UnknownEvent>();
341
- let resolveResult!: (event: TurnEndedEvent) => void;
342
- let rejectResult!: (error: unknown) => void;
343
- const result = new Promise<TurnEndedEvent>((resolve, reject) => {
344
- resolveResult = resolve;
345
- rejectResult = reject;
346
- });
347
- // Consumers may only iterate `events`; don't surface an unhandled rejection.
348
- result.catch(() => undefined);
349
- this.turnBySession.set(sessionId, { turnId, queue, resolveResult, rejectResult });
263
+ const handle = this.turns.open(sessionId, turnId, true);
264
+ stopOn(handle, options.signal);
350
265
  try {
351
- const accepted = await this.admitTurn({ ...params, sessionId, turnId });
352
- // A duplicate durable turn may have finished before this handle existed.
353
- // Its completion is returned without duplicating the global event stream;
354
- // `replay` or `history` serve its full transcript.
355
- if (
356
- accepted.terminal &&
357
- (accepted.terminal.sessionId !== sessionId || accepted.terminal.turnId !== turnId)
358
- )
266
+ const accepted = await this.connection.resend(
267
+ WIRE_METHODS.turnStart,
268
+ { ...params, sessionId, turnId, subscribe: true },
269
+ // A turn that already ended streams nothing: its end is in the ack.
270
+ (ack) => {
271
+ if (!ack.terminal) this.joinAt(handle, ack.headSeq, { turnId });
272
+ },
273
+ );
274
+ const { terminal } = accepted;
275
+ if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
359
276
  throw new Error("Turn receipt belongs to a different request");
360
- if (accepted.terminal && this.turnBySession.get(sessionId)?.turnId === turnId) {
361
- this.turnBySession.delete(sessionId);
362
- queue.push(accepted.terminal);
363
- resolveResult(accepted.terminal);
364
- queue.end();
365
- }
366
- } catch (err) {
367
- this.turnBySession.delete(sessionId);
368
- queue.fail(err);
369
- rejectResult(err);
370
- throw err;
277
+ // A retried start of a turn that already ended: its end, without its events
278
+ // (`replay` or `history` serve its transcript).
279
+ if (terminal) handle.push(terminal);
280
+ else
281
+ await this.catchUp(
282
+ handle,
283
+ accepted.deduplicated
284
+ ? (accepted.startedSeq ?? accepted.headSeq + 1)
285
+ : accepted.headSeq + 1,
286
+ accepted.headSeq,
287
+ );
288
+ } catch (error) {
289
+ handle.fail(error);
290
+ throw error;
371
291
  }
372
- return { sessionId, turnId, events: queue, result };
292
+ return this.handleOf(handle);
373
293
  }
374
294
 
375
295
  /**
376
- * `turn/start`, re-sent over a redialed connection: the server converges a
377
- * repeated `{sessionId, turnId}` onto the turn it admitted, so a start whose
378
- * ack was lost continues instead of failing while the turn runs unseen. Not
379
- * to a server with fresh logs (a volatile restart): the turn died with the
380
- * old process, or never reached it, and a re-send could run it again. A few
381
- * re-sends at most: a server that accepts connections but never answers the
382
- * start would otherwise be retried forever.
296
+ * Quick-ack only: the turn's events reach `onEvent` through its
297
+ * `turn.ended` (unless `subscribe: false`), and `replay` serves what came
298
+ * before.
383
299
  */
384
- private async admitTurn(
385
- params: TurnStartParams & { sessionId: string; turnId: string },
386
- ): Promise<TurnStartResult> {
387
- for (let resends = 0; ; resends++) {
388
- const identity = this.serverInstanceId;
389
- try {
390
- return await this.request(WIRE_METHODS.turnStart, params, TurnStartResultSchema);
391
- } catch (error) {
392
- if (
393
- !(error instanceof ConnectionClosedError) ||
394
- !this.reconnectEnabled ||
395
- resends >= MAX_TURN_START_RESENDS
396
- )
397
- throw error;
398
- await this.reconnection;
399
- if (this.closed || !this.transport || this.serverInstanceId !== identity) throw error;
400
- }
401
- }
402
- }
403
-
404
- /** Quick-ack only — observe the turn via `onEvent` / `replay`. */
405
300
  async startTurn(params: TurnStartParams): Promise<TurnStartResult> {
406
301
  await this.initialize();
407
302
  const sessionId = params.sessionId ?? generateUUIDv7();
408
303
  const turnId = params.turnId ?? generateUUIDv7();
409
- this.cursor.seek(sessionId, this.cursor.last(sessionId));
410
- return this.request(
304
+ return this.connection.request(
411
305
  WIRE_METHODS.turnStart,
412
306
  { ...params, sessionId, turnId },
413
- TurnStartResultSchema,
307
+ (ack) => {
308
+ if (params.subscribe !== false && !ack.terminal)
309
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
310
+ },
414
311
  );
415
312
  }
416
313
 
417
- /** Answer a `permission.requested` event. */
418
- async respondPermission(
314
+ /**
315
+ * Join the turn running in `sessionId`. Yields, each once and in seq
316
+ * order: the session's kept events from `fromSeq` (default: the turn's
317
+ * `turn.started`), the turn's open parts as of the join, then live frames
318
+ * through the turn's `turn.ended` — so even when this client already
319
+ * follows the session or another handle joined earlier. Resolves once the
320
+ * catch-up is replayed (`catchUp` counts it); `undefined` when no turn is
321
+ * running. `steer` and `result` work as on `runTurn`'s handle. Joining
322
+ * watches the session (`subscribe`).
323
+ */
324
+ async joinTurn(
419
325
  sessionId: string,
420
- requestId: string,
421
- outcome: PermissionOutcome,
422
- ): Promise<boolean> {
423
- const { accepted } = await this.request(
424
- WIRE_METHODS.permissionRespond,
425
- { sessionId, requestId, outcome },
426
- PermissionRespondResultSchema,
427
- );
428
- return accepted;
326
+ options: JoinTurnOptions = {},
327
+ ): Promise<TurnHandle | undefined> {
328
+ await this.initialize();
329
+ let handle: Handle | undefined;
330
+ const answer = await this.subscribeTo({ sessionId }, (ack) => {
331
+ if (!ack.activeTurn) return this.streams.joined(sessionId, ack.headSeq, "watch");
332
+ handle = this.turns.open(sessionId, ack.activeTurn.turnId, false);
333
+ this.joinAt(handle, ack.headSeq, "watch");
334
+ });
335
+ if (!handle) return undefined;
336
+ stopOn(handle, options.signal);
337
+ const fromSeq = options.fromSeq ?? answer.activeTurn?.startedSeq ?? answer.headSeq + 1;
338
+ await this.catchUp(handle, fromSeq, answer.headSeq);
339
+ return this.handleOf(handle);
340
+ }
341
+
342
+ // @ref LLP 0001#d13--input-while-a-turn-runs-steers-it — the client half
343
+ /**
344
+ * Add input to a running turn. The agent reads it at its next step, where
345
+ * the turn's stream shows it as a user message (`steerMessageId(steerId)`);
346
+ * a turn that ends first lists it in `turn.ended.undeliveredSteers`.
347
+ * `no_active_turn` means the turn takes no more input — send it as a new
348
+ * turn; `unsupported` means the harness cannot steer. `steerId` is minted
349
+ * when omitted; a re-send with the same one converges, so a steer whose
350
+ * answer was lost to a reconnect is re-sent, never doubled. A session this
351
+ * client does not follow is followed first, until the turn ends, so the
352
+ * steer's user message, its receipt, reaches it.
353
+ */
354
+ async steerTurn(params: TurnSteerParams): Promise<TurnSteerResult> {
355
+ await this.initialize();
356
+ const { sessionId, turnId } = params;
357
+ // One it cannot subscribe to still takes the steer; only its receipt is lost.
358
+ if (!this.streams.follows(sessionId))
359
+ await this.subscribeTo({ sessionId, turnId }, (ack) => {
360
+ // A turn that is not running subscribes nothing, and is not followed.
361
+ if (ack.activeTurn?.turnId === turnId)
362
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
363
+ }).catch(() => undefined);
364
+ return this.connection.resend(WIRE_METHODS.turnSteer, {
365
+ ...params,
366
+ steerId: params.steerId ?? generateUUIDv7(),
367
+ });
429
368
  }
430
369
 
431
370
  /**
@@ -437,57 +376,241 @@ export class AgentServerClient {
437
376
  * be running; `turn.ended` remains the source of truth.
438
377
  */
439
378
  cancelTurn(sessionId: string, turnId?: string): Promise<TurnCancelResult> {
440
- return this.request(
441
- WIRE_METHODS.turnCancel,
442
- { sessionId, ...(turnId !== undefined ? { turnId } : {}) },
443
- TurnCancelResultSchema,
379
+ return this.connection.request(WIRE_METHODS.turnCancel, {
380
+ sessionId,
381
+ ...(turnId !== undefined ? { turnId } : {}),
382
+ });
383
+ }
384
+
385
+ /** Answer a `permission.requested` event. */
386
+ async respondPermission(
387
+ sessionId: string,
388
+ requestId: string,
389
+ outcome: PermissionOutcome,
390
+ ): Promise<boolean> {
391
+ const { accepted } = await this.connection.request(WIRE_METHODS.permissionRespond, {
392
+ sessionId,
393
+ requestId,
394
+ outcome,
395
+ });
396
+ return accepted;
397
+ }
398
+
399
+ /** Answer an `elicitation.requested` event. */
400
+ async respondElicitation(
401
+ sessionId: string,
402
+ requestId: string,
403
+ outcome: ElicitationOutcome,
404
+ ): Promise<boolean> {
405
+ const { accepted } = await this.connection.request(WIRE_METHODS.elicitationRespond, {
406
+ sessionId,
407
+ requestId,
408
+ outcome,
409
+ });
410
+ return accepted;
411
+ }
412
+
413
+ // ---- sessions ------------------------------------------------------------
414
+
415
+ /**
416
+ * Watch a session until `unsubscribe` (or its end): its kept events after
417
+ * `afterSeq` reach `onEvent` (and the session's handles), each once and in
418
+ * order, then its open parts, then its frames live; after a redial, what a
419
+ * dropped connection missed. Refused `unknownSession` when the server has
420
+ * no log for it, and `subscriptionLimit` past the sessions a connection may
421
+ * watch.
422
+ */
423
+ async subscribe(sessionId: string, options: SubscribeOptions = {}): Promise<SessionSubscription> {
424
+ await this.initialize();
425
+ // What it holds, or `afterSeq`, it catches up from with `events/replay`.
426
+ const answer = await this.subscribeTo({ sessionId }, (ack) =>
427
+ this.streams.joined(sessionId, ack.headSeq, "watch", options.afterSeq),
444
428
  );
429
+ return {
430
+ sessionId,
431
+ headSeq: answer.headSeq,
432
+ ...(answer.activeTurn && { activeTurn: answer.activeTurn }),
433
+ };
434
+ }
435
+
436
+ /**
437
+ * Stop watching a session; `false` when this client did not. A turn of
438
+ * this client's that runs there is still followed to its end.
439
+ */
440
+ async unsubscribe(sessionId: string): Promise<boolean> {
441
+ const watched = this.streams.watches(sessionId);
442
+ this.streams.unwatch(sessionId);
443
+ const { unsubscribed } = await this.connection.request(WIRE_METHODS.sessionUnsubscribe, {
444
+ sessionId,
445
+ });
446
+ return unsubscribed || watched;
447
+ }
448
+
449
+ /**
450
+ * Every session's frames, live from now, to `onEvent` (observers): no
451
+ * history, the open parts of running turns, and after a redial, the gaps a
452
+ * dropped connection left healed.
453
+ */
454
+ async subscribeAll(): Promise<void> {
455
+ await this.initialize();
456
+ await this.requestAll();
457
+ }
458
+
459
+ /** Stop following every session (`subscribeAll`); those subscribed by name stay. */
460
+ async unsubscribeAll(): Promise<boolean> {
461
+ this.streams.unfollowAll();
462
+ const { unsubscribed } = await this.connection.request(WIRE_METHODS.sessionUnsubscribeAll, {});
463
+ return unsubscribed;
445
464
  }
446
465
 
447
466
  /** Release an idle session's replay history and harness-native resources. */
448
467
  async closeSession(sessionId: string): Promise<boolean> {
449
- if (this.turnBySession.has(sessionId)) {
468
+ if (this.turns.running(sessionId))
450
469
  throw new Error(`cannot close session ${sessionId} while its turn is active`);
451
- }
452
- const { closed } = await this.request(
453
- WIRE_METHODS.sessionClose,
454
- { sessionId },
455
- SessionCloseResultSchema,
456
- );
457
- // Keep the seq watermark: the server continues a reused id's seq where the
458
- // closed incarnation stopped, so post-reuse events stay contiguous for this
459
- // client too. A genuine server restart surfaces as a transport drop, and the
460
- // resync's unknownSession path resets the watermark then.
461
- this.heldBack.delete(sessionId);
462
- this.syncing.delete(sessionId);
470
+ const { closed } = await this.connection.request(WIRE_METHODS.sessionClose, { sessionId });
471
+ this.streams.forget(sessionId);
463
472
  return closed;
464
473
  }
465
474
 
475
+ /**
476
+ * Durable servers: let an idle session's agent go (its process, a Codex
477
+ * home it holds) while the session stays open, as after a restart. Its
478
+ * next turn names its native conversation (`config.resumeSessionId`; a turn
479
+ * that does not is refused `resumeRequired`, whose data names it), also a
480
+ * turn another client of the session sends: nothing tells it of the
481
+ * release. `false` when the server holds no open session by that id.
482
+ */
483
+ async releaseSession(sessionId: string): Promise<boolean> {
484
+ await this.initialize();
485
+ const { released } = await this.connection.request(WIRE_METHODS.sessionRelease, {
486
+ sessionId,
487
+ });
488
+ return released;
489
+ }
490
+
466
491
  /**
467
492
  * The models a harness offers for the login and folder a turn with the same
468
493
  * `cwd`, `env` and `apiKey` would use. `source: "catalog"` (with `error`)
469
494
  * means the CLI did not answer and the list is agent-server's built-in one.
470
495
  */
471
496
  listModels(params: ModelsListParams): Promise<ModelList> {
472
- return this.request(WIRE_METHODS.modelsList, params, MODEL_LIST);
497
+ return this.connection.request(WIRE_METHODS.modelsList, params);
473
498
  }
474
499
 
475
- /** Fetch buffered events (`seq >= fromSeq`) without touching seq tracking.
500
+ /**
501
+ * Where each harness's CLI is on the server (every harness when absent):
502
+ * `ready`, `missing` (what its first turn installs), `installing`,
503
+ * `failed` (with `error`) or `unmanaged`. Installs nothing.
504
+ */
505
+ async listClis(harnesses?: AgentHarness[]): Promise<HarnessCli[]> {
506
+ await this.initialize();
507
+ const { clis } = await this.connection.request(WIRE_METHODS.clisList, {
508
+ ...(harnesses && { harnesses }),
509
+ });
510
+ return clis;
511
+ }
512
+
513
+ /**
514
+ * Install each harness's CLI on the server now, so a first turn does not
515
+ * wait for it, and answer once each is ready or failed. The server answers
516
+ * `clis/prepare` at once, since an install outlasts a request's timeout;
517
+ * this waits for `clis/progress` to say an install ended, asking
518
+ * `clis/list` then and every few seconds, across a redial to the same
519
+ * server. Safe to call again: a running install is joined. `signal` stops
520
+ * the waiting, not the install.
521
+ */
522
+ async prepareClis(
523
+ harnesses?: AgentHarness[],
524
+ options: { signal?: AbortSignal } = {},
525
+ ): Promise<HarnessCli[]> {
526
+ const { signal } = options;
527
+ signal?.throwIfAborted();
528
+ // Before the first request: a redial asks again only of the server it knows.
529
+ await this.initialize();
530
+ const which = { ...(harnesses && { harnesses }) };
531
+ let wake = () => {};
532
+ const off = this.progress.add(({ phase }) => {
533
+ if (phase === "ready" || phase === "failed") wake();
534
+ });
535
+ /** `work`, or the signal's reason once it aborts. */
536
+ const unlessAborted = <T>(work: (aborted: Promise<never>) => Promise<T>): Promise<T> => {
537
+ if (!signal) return work(new Promise<never>(() => {}));
538
+ let stop = () => {};
539
+ const aborted = new Promise<never>((_, reject) => {
540
+ stop = () => reject(signal.reason);
541
+ signal.addEventListener("abort", stop, { once: true });
542
+ });
543
+ return work(aborted).finally(() => signal.removeEventListener("abort", stop));
544
+ };
545
+ try {
546
+ let { clis } = await unlessAborted((aborted) =>
547
+ Promise.race([this.connection.resend(WIRE_METHODS.clisPrepare, which), aborted]),
548
+ );
549
+ while (clis.some((cli) => cli.state === "installing")) {
550
+ ({ clis } = await unlessAborted(async (aborted) => {
551
+ let timer: ReturnType<typeof setTimeout> | undefined;
552
+ try {
553
+ await Promise.race([
554
+ new Promise<void>((resolve) => {
555
+ timer = setTimeout(resolve, PREPARE_POLL_MS);
556
+ wake = resolve;
557
+ }),
558
+ aborted,
559
+ ]);
560
+ } finally {
561
+ clearTimeout(timer);
562
+ }
563
+ return Promise.race([this.connection.resend(WIRE_METHODS.clisList, which), aborted]);
564
+ }));
565
+ }
566
+ return clis;
567
+ } finally {
568
+ off();
569
+ }
570
+ }
571
+
572
+ /** Fetch kept events (`seq >= fromSeq`) without touching what the client follows.
476
573
  * A durable server answers a page at a time: `hasMore` asks for the next. */
477
574
  replay(sessionId: string, fromSeq: number): Promise<DecodedEventsReplayResult> {
478
- return this.request(WIRE_METHODS.eventsReplay, { sessionId, fromSeq }, REPLAY_RESULT);
575
+ return this.connection.request(WIRE_METHODS.eventsReplay, { sessionId, fromSeq });
576
+ }
577
+
578
+ /**
579
+ * The session's kept events from `fromSeq` through `throughSeq` (default:
580
+ * the last), oldest first: every page `replay` answers. Fails
581
+ * `EventGapError` when some of them were evicted.
582
+ */
583
+ async replayAll(
584
+ sessionId: string,
585
+ fromSeq: number,
586
+ throughSeq = Number.POSITIVE_INFINITY,
587
+ ): Promise<DecodedWireEventEnvelope[]> {
588
+ const kept: DecodedWireEventEnvelope[] = [];
589
+ for (let from = fromSeq; from <= throughSeq; ) {
590
+ const page = await this.replay(sessionId, from);
591
+ if (page.firstAvailableSeq !== null && page.firstAvailableSeq > from)
592
+ throw new EventGapError(
593
+ `events ${from}..${page.firstAvailableSeq - 1} for session ${sessionId} were evicted`,
594
+ );
595
+ for (const envelope of page.events)
596
+ if (envelope.seq >= from && envelope.seq <= throughSeq) kept.push(envelope);
597
+ const last = page.events.at(-1)?.seq;
598
+ if (!page.hasMore || last === undefined || last >= throughSeq) break;
599
+ from = last + 1;
600
+ }
601
+ return kept;
479
602
  }
480
603
 
481
604
  /** Durable servers: a turn's receipt, even for a turn a restart cut off. */
482
605
  async getTurn(sessionId: string, turnId: string): Promise<TurnReceipt> {
483
606
  await this.initialize();
484
- return this.request(WIRE_METHODS.turnGet, { sessionId, turnId }, TurnReceiptSchema);
607
+ return this.connection.request(WIRE_METHODS.turnGet, { sessionId, turnId });
485
608
  }
486
609
 
487
610
  /** Durable servers: the session's head, native id, and whether a restart cut off its last turn. */
488
611
  async getSession(sessionId: string): Promise<DurableSession> {
489
612
  await this.initialize();
490
- return this.request(WIRE_METHODS.sessionGet, { sessionId }, DurableSessionSchema);
613
+ return this.connection.request(WIRE_METHODS.sessionGet, { sessionId });
491
614
  }
492
615
 
493
616
  /** Durable servers: lift the fence a restart put on a session. Check first
@@ -495,414 +618,225 @@ export class AgentServerClient {
495
618
  * detached agent or tool process is dead. */
496
619
  async confirmSessionStopped(params: SessionConfirmStoppedParams): Promise<boolean> {
497
620
  await this.initialize();
498
- return (
499
- await this.request(
500
- WIRE_METHODS.sessionConfirmStopped,
501
- params,
502
- SessionConfirmStoppedResultSchema,
503
- )
504
- ).recovered;
621
+ const { recovered } = await this.connection.request(WIRE_METHODS.sessionConfirmStopped, params);
622
+ return recovered;
505
623
  }
506
624
 
507
- /** Firehose of sequenced events across all sessions (post-dedupe, in order). */
508
- onEvent(handler: (envelope: DecodedWireEventEnvelope) => void): () => void {
509
- this.eventHandlers.add(handler);
510
- return () => this.eventHandlers.delete(handler);
625
+ // ---- logins ----------------------------------------------------------------
626
+
627
+ /**
628
+ * Each harness's login on the server (every harness when `harnesses` is
629
+ * absent), for the store and environment a turn with `env` would use:
630
+ * signed in, with what and as whom, signed out, or unknown and why; and
631
+ * the logins it offers.
632
+ */
633
+ async authStatus(
634
+ options: { harnesses?: AgentHarness[]; env?: Record<string, string> } = {},
635
+ ): Promise<HarnessAuth[]> {
636
+ await this.initialize();
637
+ const { auth } = await this.connection.request(WIRE_METHODS.authStatus, options);
638
+ return auth;
511
639
  }
512
640
 
513
641
  /**
514
- * Follow a session this client did not start, such as a turn another client
515
- * left running: its events after `afterSeq` reach `onEvent`, those already
516
- * logged now and later ones live, and after a redial the ones a dropped
517
- * connection missed. A session already tracked keeps its position. Gaps that
518
- * cannot be filled reach `onEventGap`.
642
+ * Start one of a harness's logins through its CLI's own flow: answered
643
+ * once the CLI says where the user signs in (`url`, `userCode`, or from
644
+ * another device `codeUrl`, then `complete` with the code it shows).
645
+ * `done` resolves with the harness's login once it succeeded.
519
646
  */
520
- watch(sessionId: string, afterSeq = 0): void {
521
- if (!this.cursor.sessions().includes(sessionId)) this.cursor.seek(sessionId, afterSeq);
522
- void this.syncSession(sessionId);
647
+ async login(
648
+ harness: AgentHarness,
649
+ method: string,
650
+ options: { apiKey?: string; env?: Record<string, string> } = {},
651
+ ): Promise<LoginHandle> {
652
+ await this.initialize();
653
+ return startLogin(
654
+ {
655
+ updates: this.authUpdates,
656
+ connection: this.connection.events,
657
+ complete: (loginId, code) =>
658
+ this.connection.request(WIRE_METHODS.authComplete, { loginId, code }),
659
+ cancel: (loginId) => this.connection.request(WIRE_METHODS.authCancel, { loginId }),
660
+ },
661
+ () => this.connection.request(WIRE_METHODS.authLogin, { harness, method, ...options }),
662
+ );
663
+ }
664
+
665
+ /** Remove a harness's CLI login on the server; answers its login after. */
666
+ async logout(
667
+ harness: AgentHarness,
668
+ options: { env?: Record<string, string> } = {},
669
+ ): Promise<HarnessAuth> {
670
+ await this.initialize();
671
+ return this.connection.request(WIRE_METHODS.authLogout, { harness, ...options });
672
+ }
673
+
674
+ // ---- observing -----------------------------------------------------------
675
+
676
+ /** The frames of the sessions this client follows, each once and in order (post-dedupe). */
677
+ onEvent(handler: (envelope: DecodedWireEventEnvelope) => void): () => void {
678
+ return this.streams.events.add(handler);
679
+ }
680
+
681
+ /** A harness's CLI being installed on the server, whatever caused it (`clis/progress`). */
682
+ onCliProgress(handler: (progress: HarnessCliProgress) => void): () => void {
683
+ return this.progress.add(handler);
684
+ }
685
+
686
+ /** A harness's login changed on the server, or a login ended, whoever caused it (`auth/updated`). */
687
+ onAuthUpdated(handler: (update: AuthUpdated) => void): () => void {
688
+ return this.authUpdates.add(handler);
523
689
  }
524
690
 
525
691
  /** Observe unrecoverable delivery gaps even when using startTurn without a handle. */
526
692
  onEventGap(handler: (gap: SessionEventGap) => void): () => void {
527
- this.gapHandlers.add(handler);
528
- return () => this.gapHandlers.delete(handler);
693
+ return this.streams.gaps.add(handler);
694
+ }
695
+
696
+ /**
697
+ * Observe the connection: a drop, each redial attempt, the reconnect (and
698
+ * whether the server is still the one whose logs this client followed),
699
+ * and the end. Handlers run synchronously, before requests waiting on the
700
+ * redial are sent again; one that throws is ignored.
701
+ */
702
+ onConnection(handler: (event: ConnectionEvent) => void): () => void {
703
+ return this.connection.events.add(handler);
529
704
  }
530
705
 
531
706
  /** Ask the server to shut down, then close this client. */
532
707
  async shutdownServer(): Promise<void> {
533
- await this.request(WIRE_METHODS.shutdown, {}, ShutdownResultSchema).catch(() => undefined);
708
+ await this.connection.request(WIRE_METHODS.shutdown, {}).catch(() => undefined);
534
709
  await this.close();
535
710
  }
536
711
 
537
712
  async close(): Promise<void> {
538
- if (this.closed) return;
539
- this.closed = true;
540
- const reason = new ConnectionClosedError("client closed");
541
- this.failPending(reason);
542
- this.failAllTurns(reason);
543
- this.transport?.close();
544
- this.transport = null;
545
- }
546
-
547
- // ---- transport lifecycle -----------------------------------------------
548
-
549
- private async openTransport(): Promise<void> {
550
- const transport = await this.factory();
551
- if (this.closed) {
552
- transport.close();
553
- throw new ConnectionClosedError("client closed while connecting");
554
- }
555
- if (transport.closed) throw new ConnectionClosedError("transport opened already closed");
556
- this.transport = transport;
557
- this.awaitingHandshake = this.reconnecting;
558
- transport.onLine((line) => {
559
- if (this.transport === transport) this.handleLine(line);
560
- });
561
- transport.onClose((reason) => this.handleTransportClose(transport, reason));
562
- }
563
-
564
- private handleTransportClose(transport: WireTransport, reason?: string): void {
565
- // A late close from a superseded transport must not tear down the current one.
566
- if (this.transport !== transport) return;
567
- this.transport = null;
568
- this.failPending(new ConnectionClosedError(reason ?? "connection closed"));
569
- if (this.closed) return;
570
- if (!this.reconnectEnabled) {
571
- this.closed = true;
572
- this.failAllTurns(new ConnectionClosedError(reason ?? "connection closed"));
573
- return;
574
- }
575
- this.reconnection ??= this.reconnectLoop().finally(() => {
576
- this.reconnection = null;
577
- });
578
- }
579
-
580
- private async reconnectLoop(): Promise<void> {
581
- if (this.reconnecting) return;
582
- this.reconnecting = true;
583
- const maxAttempts = this.options.maxReconnectAttempts ?? 8;
584
- const base = this.options.reconnectDelayMs ?? 250;
585
- try {
586
- for (let attempt = 0; attempt < maxAttempts && !this.closed; attempt++) {
587
- await sleep(Math.min(10_000, base * 2 ** Math.min(attempt, 5)));
588
- if (this.closed) break;
589
- try {
590
- await this.openTransport();
591
- if (this.closed || !this.transport) continue;
592
- // Re-handshake: the transport may have reconnected to a DIFFERENT
593
- // process (or a different build). A version mismatch fails loudly
594
- // here instead of silently mixing dialects, and a changed
595
- // instanceId adopts the fresh logs before any resync runs.
596
- this.initializePromise = null;
597
- await this.initialize();
598
- if (this.closed || !this.transport) continue;
599
- this.awaitingHandshake = false;
600
- // Heal every tracked session — including turns that saw no event
601
- // before the drop (or none after it): without a resync they would
602
- // never receive their turn.ended and would hang forever.
603
- const sessionIds = new Set([
604
- ...this.cursor.sessions(),
605
- ...this.turnBySession.keys(),
606
- ...this.heldBack.keys(),
607
- ]);
608
- for (const sessionId of sessionIds) void this.syncSession(sessionId);
609
- if (!this.transport) continue;
610
- return;
611
- } catch {
612
- // next attempt
613
- }
614
- }
615
- if (!this.closed) {
616
- this.closed = true;
617
- this.failAllTurns(new ConnectionClosedError("reconnect failed"));
618
- }
619
- } finally {
620
- this.reconnecting = false;
621
- }
713
+ this.connection.close();
622
714
  }
623
715
 
624
- // ---- inbound dispatch ----------------------------------------------------
716
+ // ---- internals -------------------------------------------------------------
625
717
 
626
- private handleLine(line: string): void {
627
- const msg = decodeWireMessage(line);
628
- if (msg.kind === "response") {
629
- if (msg.id === null) return; // protocol-level error for an unparseable line
630
- const pending = this.pending.get(msg.id);
631
- if (!pending) return;
632
- this.pending.delete(msg.id);
633
- clearTimeout(pending.timer);
634
- if (msg.error)
635
- pending.reject(new WireRequestError(msg.error.code, msg.error.message, msg.error.data));
636
- else pending.resolve(msg.result);
718
+ private handleLine(line: string, transport: WireTransport): void {
719
+ const message = decodeWireMessage(line);
720
+ if (message.kind === "response") {
721
+ this.connection.rpc.settle(message);
637
722
  return;
638
723
  }
639
- if (msg.kind === "notification" && msg.method === WIRE_METHODS.event) {
724
+ if (message.kind !== "notification") return;
725
+ if (message.method === WIRE_METHODS.event) {
640
726
  try {
641
- // Law 6: an unknown event TYPE is preserved and still advances seq.
642
- // Only a malformed envelope or a malformed KNOWN event lands here —
727
+ // An unknown event TYPE is preserved and still advances seq. Only a
728
+ // malformed envelope or a malformed KNOWN event lands in the catch —
643
729
  // a server bug, which must not be papered over by advancing past it.
644
- this.handleEnvelope(decodeWireEventEnvelope(msg.params));
730
+ this.streams.accept(decodeWireEventEnvelope(message.params), transport);
645
731
  } catch {
646
732
  // undeliverable; the next event's seq gap raises it honestly
647
733
  }
734
+ } else if (message.method === WIRE_METHODS.sessionOverflow) {
735
+ const notice = SessionOverflowParamsSchema.safeParse(message.params);
736
+ if (notice.success) this.streams.overflowed(notice.data);
737
+ } else if (message.method === WIRE_METHODS.clisProgress) {
738
+ const progress = HarnessCliProgressSchema.safeParse(message.params);
739
+ if (progress.success) this.progress.emit(progress.data);
740
+ } else if (message.method === WIRE_METHODS.authUpdated) {
741
+ const update = AuthUpdatedSchema.safeParse(message.params);
742
+ if (update.success) this.authUpdates.emit(update.data);
648
743
  }
649
744
  }
650
745
 
651
746
  /**
652
- * Seq discipline: drop duplicates, deliver contiguous, hold back and heal
653
- * gaps via replay. Events are always delivered in seq order per session.
654
- * The verdicts come from the shared `SeqCursor`; this method owns only what
655
- * a client does about them (queue, replay, deliver).
747
+ * A start or join's answer, the moment it arrives: the handle's point
748
+ * among the frames. What follows the point waits for the catch-up before it.
656
749
  */
657
- private handleEnvelope(envelope: DecodedWireEventEnvelope): void {
658
- const sessionId = envelope.sessionId;
659
- // While a replay is in flight, every envelope queues: the drain re-runs
660
- // the cursor over the merged (replayed + live) backlog in seq order.
661
- if (this.awaitingHandshake || this.syncing.get(sessionId) === this.transport) {
662
- this.holdBack(sessionId, envelope);
663
- return;
664
- }
665
- switch (this.cursor.advance(sessionId, envelope.seq)) {
666
- case "duplicate":
667
- return; // e.g. a replay overlap
668
- case "reset":
669
- // Defense-in-depth. Real restarts are detected by the handshake
670
- // (`instanceId` at re-initialize) before any envelope flows — this
671
- // arm fires only if a fresh log appears with NO transport drop,
672
- // which no current topology produces. If it does: the queue is
673
- // dead-log state, the fresh frame is authoritative.
674
- this.reportEventGap(
675
- sessionId,
676
- "log_reset",
677
- new EventGapError(`session ${sessionId} log reset`),
678
- );
679
- this.heldBack.delete(sessionId);
680
- this.deliver(envelope);
681
- return;
682
- case "deliver":
683
- this.deliver(envelope);
684
- this.drainHeld(sessionId);
685
- return;
686
- case "gap":
687
- this.holdBack(sessionId, envelope);
688
- void this.syncSession(sessionId);
689
- return;
690
- }
750
+ private joinAt(handle: Handle, headSeq: number, follow: Follow): void {
751
+ this.streams.joined(handle.sessionId, headSeq, follow);
752
+ handle.point = { headSeq, position: this.streams.position };
753
+ handle.catchingUp();
691
754
  }
692
755
 
693
- private holdBack(sessionId: string, envelope: DecodedWireEventEnvelope): void {
694
- const held = this.heldBack.get(sessionId) ?? [];
695
- held.push({ envelope, transport: this.transport });
696
- this.heldBack.set(sessionId, held);
697
- }
698
-
699
- private drainHeld(sessionId: string): void {
700
- if (this.awaitingHandshake) return;
701
- const held = this.heldBack.get(sessionId);
702
- if (!held?.length) return;
703
- held.sort((a, b) => a.envelope.seq - b.envelope.seq);
704
- while (held.length) {
705
- const next = held[0]!.envelope;
706
- // `gap` leaves the cursor untouched, so breaking here is safe: the
707
- // envelope stays queued for the replay that fills the hole.
708
- const verdict = this.cursor.advance(sessionId, next.seq);
709
- if (verdict === "gap") break;
710
- held.shift();
711
- if (verdict === "reset") {
712
- // Defense-in-depth only (see the reset arm in handleEnvelope):
713
- // drop the queue, deliver the fresh frame, resync for its tail.
714
- this.reportEventGap(
715
- sessionId,
716
- "log_reset",
717
- new EventGapError(`session ${sessionId} log reset`),
718
- );
719
- held.length = 0;
720
- this.deliver(next);
721
- // Let any replay owning this drain release its transport first.
722
- queueMicrotask(() => void this.syncSession(sessionId));
723
- break;
724
- }
725
- if (verdict !== "duplicate") this.deliver(next);
726
- }
727
- if (!held.length) this.heldBack.delete(sessionId);
728
- }
729
-
730
- private async syncSession(sessionId: string): Promise<void> {
731
- const transport = this.transport;
732
- if (
733
- !transport ||
734
- this.awaitingHandshake ||
735
- this.closed ||
736
- this.syncing.get(sessionId) === transport
737
- )
738
- return;
739
- this.syncing.set(sessionId, transport);
740
- const isCurrent = () => !this.closed && !this.awaitingHandshake && this.transport === transport;
756
+ /** The kept events from `fromSeq` through `headSeq`, replayed into the handle before what followed its point. */
757
+ private async catchUp(handle: Handle, fromSeq: number, headSeq: number): Promise<void> {
758
+ let replayed: DecodedWireEventEnvelope[];
741
759
  try {
742
- const maxAttempts = Math.max(1, this.options.maxReplayAttempts ?? 3);
743
- const retryDelay = this.options.replayRetryDelayMs ?? this.options.reconnectDelayMs ?? 250;
744
- for (let attempt = 1; attempt <= maxAttempts && isCurrent(); attempt++) {
745
- this.drainHeld(sessionId);
746
- if (!isCurrent()) return;
747
- const fromSeq = this.cursor.last(sessionId) + 1;
748
- try {
749
- const replayed = await this.replay(sessionId, fromSeq);
750
- if (!isCurrent()) return;
751
- for (const envelope of replayed.events) this.holdBack(sessionId, envelope);
752
- this.drainHeld(sessionId);
753
- const missingFrom = this.cursor.last(sessionId) + 1;
754
- if (replayed.firstAvailableSeq !== null && replayed.firstAvailableSeq > missingFrom) {
755
- // The prefix was evicted — the gap is unfillable. Fail the turn
756
- // handle (its part reconstruction is broken) and jump forward.
757
- this.reportEventGap(
758
- sessionId,
759
- "evicted",
760
- new EventGapError(
761
- `events ${missingFrom}..${replayed.firstAvailableSeq - 1} for session ${sessionId} were evicted`,
762
- ),
763
- );
764
- this.cursor.seek(sessionId, replayed.firstAvailableSeq - 1);
765
- }
766
- if (replayed.hasMore) {
767
- if (this.cursor.last(sessionId) < fromSeq) throw new Error("Replay made no progress");
768
- attempt = 0; // successful pages do not consume the transport retry budget
769
- continue;
770
- }
771
- break;
772
- } catch (err) {
773
- if (!isCurrent()) return;
774
- if (err instanceof WireRequestError && err.code === WIRE_ERROR_CODES.unknownSession) {
775
- this.reportEventGap(
776
- sessionId,
777
- "session_missing",
778
- new EventGapError(`session ${sessionId} is unknown to the server (restarted?)`),
779
- );
780
- this.cursor.reset(sessionId);
781
- this.heldBack.delete(sessionId);
782
- break;
783
- }
784
- if (!this.transport || this.closed) break; // reconnect performs a fresh resync
785
- if (attempt === maxAttempts) {
786
- this.reportEventGap(
787
- sessionId,
788
- "replay_failed",
789
- new EventGapError(
790
- `failed to replay events from ${fromSeq} for session ${sessionId} after ${maxAttempts} attempts`,
791
- ),
792
- );
793
- this.heldBack.delete(sessionId);
794
- break;
795
- }
796
- await sleep(retryDelay);
797
- }
798
- }
799
- } finally {
800
- if (this.syncing.get(sessionId) === transport) this.syncing.delete(sessionId);
760
+ replayed = await this.replayAll(handle.sessionId, fromSeq, headSeq);
761
+ } catch (error) {
762
+ handle.fail(
763
+ error instanceof WireRequestError && error.code === WIRE_ERROR_CODES.unknownSession
764
+ ? new EventGapError(`session ${handle.sessionId} is unknown to the server (restarted?)`)
765
+ : error,
766
+ );
767
+ throw error;
801
768
  }
802
- if (isCurrent()) this.drainHeld(sessionId);
769
+ handle.caughtUp(replayed.map((envelope) => envelope.event));
770
+ }
771
+
772
+ private handleOf(handle: Handle): TurnHandle {
773
+ const { sessionId, turnId } = handle;
774
+ return {
775
+ sessionId,
776
+ turnId,
777
+ events: handle.queue,
778
+ result: handle.result,
779
+ get catchUp() {
780
+ return handle.catchUp;
781
+ },
782
+ steer: (input: AgentInput, steerId?: string) =>
783
+ this.steerTurn({ sessionId, turnId, input, ...(steerId !== undefined && { steerId }) }),
784
+ };
803
785
  }
804
786
 
805
- /** Dispatch an envelope the cursor already accepted (it owns the watermark). */
806
- private deliver(envelope: DecodedWireEventEnvelope): void {
807
- for (const handler of [...this.eventHandlers]) {
808
- try {
809
- handler(envelope);
810
- } catch {
811
- // consumer handler errors must not break dispatch
812
- }
813
- }
814
- const turn = this.turnBySession.get(envelope.sessionId);
815
- if (!turn) return;
816
- const event = envelope.event;
817
- turn.queue.push(event);
818
- if (!isUnknownEvent(event) && event.type === "turn.ended" && event.turnId === turn.turnId) {
819
- this.turnBySession.delete(envelope.sessionId);
820
- turn.resolveResult(event);
821
- turn.queue.end();
787
+ /**
788
+ * Subscribe to the session again (a redial, an overflow), for the turn of
789
+ * this client's it runs or, without one, watching it; what it missed heals
790
+ * by replay. A turn the answer says runs no more ended by its `headSeq`:
791
+ * the session is followed through there, then let go. A refusal is the
792
+ * server's answer: the session is followed no more.
793
+ */
794
+ private async resubscribe(sessionId: string, turnId?: string): Promise<void> {
795
+ try {
796
+ await this.subscribeTo({ sessionId, ...(turnId !== undefined && { turnId }) }, (ack) => {
797
+ if (turnId === undefined) this.streams.joined(sessionId, ack.headSeq, "watch");
798
+ else if (ack.activeTurn?.turnId === turnId)
799
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
800
+ // @ref LLP 0008#client-api — followed through the head, then let go
801
+ else this.streams.turnEnded(sessionId, turnId, ack.headSeq);
802
+ });
803
+ } catch (error) {
804
+ // Any other failure: a dropped connection subscribes again once redialed.
805
+ if (!(error instanceof WireRequestError)) return;
806
+ if (error.code === WIRE_ERROR_CODES.unknownSession) this.streams.missing(sessionId);
807
+ else this.streams.refused(sessionId, error.message);
822
808
  }
823
809
  }
824
810
 
825
- private reportEventGap(
826
- sessionId: string,
827
- reason: SessionEventGap["reason"],
828
- error: EventGapError,
829
- ): void {
830
- this.failTurn(sessionId, error);
831
- for (const handler of [...this.gapHandlers]) {
832
- try {
833
- handler({ sessionId, reason, error });
834
- } catch {
835
- // A consumer callback cannot interrupt replay or other subscribers.
836
- }
811
+ /** Every session again; refused, the client follows every session no more. */
812
+ private async resubscribeAll(): Promise<void> {
813
+ try {
814
+ await this.requestAll();
815
+ } catch (error) {
816
+ if (error instanceof WireRequestError) this.streams.refusedAll(error.message);
837
817
  }
838
818
  }
839
819
 
840
- private failTurn(sessionId: string, error: Error): void {
841
- const turn = this.turnBySession.get(sessionId);
842
- if (!turn) return;
843
- this.turnBySession.delete(sessionId);
844
- turn.rejectResult(error);
845
- turn.queue.fail(error);
820
+ // @ref LLP 0008#what-requests-do-to-subscriptions — a redial subscribes the running turns first
821
+ /** After a redial: every session followed, from what the client holds, pipelined. */
822
+ private subscribeAgain(): void {
823
+ for (const { sessionId, turnId } of this.streams.resubscriptions())
824
+ void this.resubscribe(sessionId, turnId);
825
+ if (this.streams.followsAll) void this.resubscribeAll();
846
826
  }
847
827
 
848
- private failAllTurns(error: Error): void {
849
- for (const sessionId of [...this.turnBySession.keys()]) this.failTurn(sessionId, error);
828
+ /** `session/subscribeAll`, sent now. */
829
+ private requestAll(): Promise<unknown> {
830
+ return this.connection.request(WIRE_METHODS.sessionSubscribeAll, {}, ({ sessions }) =>
831
+ this.streams.joinedAll(sessions),
832
+ );
850
833
  }
851
834
 
852
- private failPending(error: Error): void {
853
- for (const [, pending] of this.pending) {
854
- clearTimeout(pending.timer);
855
- pending.reject(error);
856
- }
857
- this.pending.clear();
858
- }
859
-
860
- // ---- outbound ------------------------------------------------------------
861
-
862
- private request<T>(method: string, params: unknown, schema: ResultSchema<T>): Promise<T> {
863
- if (this.closed) return Promise.reject(new ConnectionClosedError("client closed"));
864
- const transport = this.transport;
865
- if (!transport) return Promise.reject(new ConnectionClosedError("not connected"));
866
- const id = this.nextId++;
867
- const timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
868
- return new Promise<T>((resolve, reject) => {
869
- const timer = setTimeout(() => {
870
- this.pending.delete(id);
871
- // A healthy server answers every request in time (`history/wait` is
872
- // bounded below this): a client that can redial replaces the
873
- // half-open connection. One that cannot (attach, and spawn, whose
874
- // transport is the server process) fails only this request.
875
- if (this.reconnectEnabled && this.transport === transport) {
876
- reject(new ConnectionClosedError(`request timed out: ${method}`));
877
- transport.close();
878
- } else
879
- reject(
880
- new WireRequestError(WIRE_ERROR_CODES.internalError, `request timed out: ${method}`),
881
- );
882
- }, timeoutMs);
883
- this.pending.set(id, {
884
- resolve: (raw) => {
885
- const parsed = schema.safeParse(raw);
886
- if (parsed.success) resolve(parsed.data);
887
- else
888
- reject(
889
- new WireRequestError(WIRE_ERROR_CODES.internalError, `malformed ${method} result`),
890
- );
891
- },
892
- reject,
893
- timer,
894
- });
895
- try {
896
- transport.send(encodeRequest(id, method, params));
897
- } catch (error) {
898
- clearTimeout(timer);
899
- this.pending.delete(id);
900
- reject(error);
901
- }
902
- });
835
+ /** `session/subscribe` for one session, `onAnswer` given its point the moment it arrives. */
836
+ private subscribeTo(
837
+ params: { sessionId: string; turnId?: string },
838
+ onAnswer: (point: SessionSubscribeResult) => void,
839
+ ): Promise<SessionSubscribeResult> {
840
+ return this.connection.request(WIRE_METHODS.sessionSubscribe, params, onAnswer);
903
841
  }
904
842
  }
905
-
906
- function sleep(ms: number): Promise<void> {
907
- return new Promise((resolve) => setTimeout(resolve, ms));
908
- }