@zvada/agent-server 0.3.23 → 0.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +14 -5
  3. package/dist/accounts/chatgpt.js +144 -0
  4. package/dist/accounts/check.js +71 -0
  5. package/dist/accounts/claude.js +80 -0
  6. package/dist/accounts/endpoint.js +104 -0
  7. package/dist/accounts/http.js +58 -0
  8. package/dist/accounts/index.js +9 -0
  9. package/dist/client/client.js +686 -0
  10. package/dist/client/connection.js +338 -0
  11. package/dist/client/history.js +49 -0
  12. package/dist/client/index.js +6 -0
  13. package/dist/client/listeners.js +19 -0
  14. package/dist/client/logins.js +92 -0
  15. package/dist/client/rpc.js +105 -0
  16. package/dist/client/streams.js +432 -0
  17. package/dist/client/transports.js +118 -0
  18. package/dist/client/turns.js +122 -0
  19. package/dist/core/agents/acp/acp-agent.js +425 -0
  20. package/dist/core/agents/acp/adapter.js +231 -0
  21. package/dist/core/agents/acp/client.js +222 -0
  22. package/dist/core/agents/acp/known-agents.js +57 -0
  23. package/dist/core/agents/acp/mappings.js +164 -0
  24. package/dist/core/agents/acp/requests.js +79 -0
  25. package/dist/core/agents/attachments.js +14 -0
  26. package/dist/core/agents/base.js +64 -0
  27. package/dist/core/agents/claude-code/adapter.js +474 -0
  28. package/dist/core/agents/claude-code/approvals.js +245 -0
  29. package/dist/core/agents/claude-code/claude-agent.js +319 -0
  30. package/dist/core/agents/claude-code/credentials.js +142 -0
  31. package/dist/core/agents/claude-code/events.js +11 -0
  32. package/dist/core/agents/claude-code/login.js +217 -0
  33. package/dist/core/agents/claude-code/mcp.js +181 -0
  34. package/dist/core/agents/claude-code/models.js +74 -0
  35. package/dist/core/agents/claude-code/options.js +240 -0
  36. package/dist/core/agents/claude-code/outcome.js +204 -0
  37. package/dist/core/agents/claude-code/results.js +58 -0
  38. package/dist/core/agents/claude-code/sdk-pair.js +59 -0
  39. package/dist/core/agents/claude-code/session.js +593 -0
  40. package/dist/core/agents/claude-code/spawn.js +125 -0
  41. package/dist/core/agents/claude-code/spend.js +118 -0
  42. package/dist/core/agents/claude-code/tools.js +131 -0
  43. package/dist/core/agents/claude-code/turn-usage.js +121 -0
  44. package/dist/core/agents/claude-code/turn.js +199 -0
  45. package/dist/core/agents/codex-app-server/adapter.js +463 -0
  46. package/dist/core/agents/codex-app-server/client.js +338 -0
  47. package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
  48. package/dist/core/agents/codex-app-server/commands.js +184 -0
  49. package/dist/core/agents/codex-app-server/credentials.js +92 -0
  50. package/dist/core/agents/codex-app-server/effort.js +13 -0
  51. package/dist/core/agents/codex-app-server/events.js +18 -0
  52. package/dist/core/agents/codex-app-server/homes.js +118 -0
  53. package/dist/core/agents/codex-app-server/input.js +52 -0
  54. package/dist/core/agents/codex-app-server/items.js +307 -0
  55. package/dist/core/agents/codex-app-server/login.js +183 -0
  56. package/dist/core/agents/codex-app-server/mcp.js +323 -0
  57. package/dist/core/agents/codex-app-server/models.js +160 -0
  58. package/dist/core/agents/codex-app-server/options.js +155 -0
  59. package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
  60. package/dist/core/agents/codex-app-server/protocol.js +38 -0
  61. package/dist/core/agents/codex-app-server/requests.js +250 -0
  62. package/dist/core/agents/codex-app-server/session.js +278 -0
  63. package/dist/core/agents/codex-app-server/subagents.js +260 -0
  64. package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
  65. package/dist/core/agents/codex-app-server/turn-items.js +69 -0
  66. package/dist/core/agents/codex-app-server/turn.js +448 -0
  67. package/dist/core/agents/codex-app-server/user-login.js +78 -0
  68. package/dist/core/agents/config-fingerprint.js +10 -0
  69. package/dist/core/agents/credentials.js +71 -0
  70. package/dist/core/agents/diffs.js +27 -0
  71. package/dist/core/agents/elicitation.js +42 -0
  72. package/dist/core/agents/inherit-config.js +5 -0
  73. package/dist/core/agents/login.js +56 -0
  74. package/dist/core/agents/mcp-config.js +109 -0
  75. package/dist/core/agents/plan.js +6 -0
  76. package/dist/core/agents/process-pool.js +307 -0
  77. package/dist/core/agents/registry.js +49 -0
  78. package/dist/core/agents/scripted/adapter.js +86 -0
  79. package/dist/core/agents/scripted/mcp-call.js +74 -0
  80. package/dist/core/agents/scripted/scripted-agent.js +330 -0
  81. package/dist/core/agents/scripted/scripts.js +154 -0
  82. package/dist/core/agents/scripted/steps.js +87 -0
  83. package/dist/core/agents/session-agent.js +209 -0
  84. package/dist/core/agents/stderr-tail.js +71 -0
  85. package/dist/core/agents/thinking-levels.js +9 -0
  86. package/dist/core/agents/types.js +1 -0
  87. package/dist/core/diagnostics.js +23 -0
  88. package/dist/core/index.js +31 -0
  89. package/dist/core/presets.js +114 -0
  90. package/dist/core/processes/identity.js +91 -0
  91. package/dist/core/processes/lifeline.js +210 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +163 -0
  94. package/dist/core/provision/cache-trust.js +121 -0
  95. package/dist/core/provision/cache-usage.js +61 -0
  96. package/dist/core/provision/checksums.js +22 -0
  97. package/dist/core/provision/extract.js +28 -0
  98. package/dist/core/provision/index.js +4 -0
  99. package/dist/core/provision/install-build.js +99 -0
  100. package/dist/core/provision/npm.js +316 -0
  101. package/dist/core/provision/pins.js +35 -0
  102. package/dist/core/provision/platform.js +65 -0
  103. package/dist/core/provision/provisioner.js +372 -0
  104. package/dist/core/provision/releases.js +68 -0
  105. package/dist/core/provision/tools.js +279 -0
  106. package/dist/core/proxy/anthropic-proxy.js +163 -0
  107. package/dist/core/proxy/api-key-store.js +30 -0
  108. package/dist/core/proxy/index.js +3 -0
  109. package/dist/core/proxy/loopback.js +86 -0
  110. package/dist/core/runtime/agent-runtime.js +434 -0
  111. package/dist/core/runtime/event-processor.js +379 -0
  112. package/dist/core/runtime/event-sink.js +65 -0
  113. package/dist/core/runtime/harness-clis.js +83 -0
  114. package/dist/core/runtime/harness-logins.js +313 -0
  115. package/dist/core/runtime/login-reads.js +71 -0
  116. package/dist/core/runtime/model-lists.js +160 -0
  117. package/dist/core/runtime/permission-policy.js +84 -0
  118. package/dist/core/runtime/request-broker.js +139 -0
  119. package/dist/core/runtime/steering.js +79 -0
  120. package/dist/core/runtime/turn-outcome.js +16 -0
  121. package/dist/core/runtime/turn.js +329 -0
  122. package/dist/core/utils/bounded.js +13 -0
  123. package/dist/core/utils/deadline.js +57 -0
  124. package/dist/core/utils/errors.js +176 -0
  125. package/dist/core/utils/is-record.js +4 -0
  126. package/dist/core/utils/loopback.js +11 -0
  127. package/dist/index.js +4 -0
  128. package/dist/operator/index.js +10 -0
  129. package/dist/operator/mcp.js +139 -0
  130. package/dist/operator/operator.js +499 -0
  131. package/dist/operator/render.js +408 -0
  132. package/dist/operator/view.js +35 -0
  133. package/dist/protocol/account.js +96 -0
  134. package/dist/protocol/async-queue.js +65 -0
  135. package/dist/protocol/auth.js +169 -0
  136. package/dist/protocol/canonical.js +18 -0
  137. package/dist/protocol/clis.js +63 -0
  138. package/dist/protocol/config.js +137 -0
  139. package/dist/protocol/conversation.js +231 -0
  140. package/dist/protocol/credentials.js +141 -0
  141. package/dist/protocol/errors.js +181 -0
  142. package/dist/protocol/execution.js +28 -0
  143. package/dist/protocol/factories.js +231 -0
  144. package/dist/protocol/guards.js +71 -0
  145. package/dist/protocol/harness.js +93 -0
  146. package/dist/protocol/history.js +201 -0
  147. package/dist/protocol/ids.js +37 -0
  148. package/dist/protocol/index.js +36 -0
  149. package/dist/protocol/lifecycle.js +562 -0
  150. package/dist/protocol/meta-keys.js +17 -0
  151. package/dist/protocol/meta.js +13 -0
  152. package/dist/protocol/model-catalog.js +223 -0
  153. package/dist/protocol/models.js +84 -0
  154. package/dist/protocol/part-input.js +94 -0
  155. package/dist/protocol/parts.js +166 -0
  156. package/dist/protocol/plan.js +31 -0
  157. package/dist/protocol/reduce.js +484 -0
  158. package/dist/protocol/selectors.js +136 -0
  159. package/dist/protocol/seq-cursor.js +37 -0
  160. package/dist/protocol/stop-reasons.js +41 -0
  161. package/dist/protocol/thinking.js +31 -0
  162. package/dist/protocol/time.js +21 -0
  163. package/dist/protocol/tokens.js +57 -0
  164. package/dist/protocol/tool-closure.js +70 -0
  165. package/dist/protocol/tool-state.js +153 -0
  166. package/dist/protocol/verify.js +467 -0
  167. package/dist/protocol/vocabulary.js +27 -0
  168. package/dist/protocol/wire-api.js +94 -0
  169. package/dist/protocol/wire.js +669 -0
  170. package/dist/server/acp/binding.js +251 -0
  171. package/dist/server/acp/session-records.js +53 -0
  172. package/dist/server/acp/translate.js +401 -0
  173. package/dist/server/agent-server.js +338 -0
  174. package/dist/server/bin.js +492 -0
  175. package/dist/server/feedback.js +216 -0
  176. package/dist/server/history.js +123 -0
  177. package/dist/server/index.js +8 -0
  178. package/dist/server/install.js +171 -0
  179. package/dist/server/open-parts.js +87 -0
  180. package/dist/server/routes.js +291 -0
  181. package/dist/server/secrets.js +19 -0
  182. package/dist/server/session-gate.js +54 -0
  183. package/dist/server/session-log.js +66 -0
  184. package/dist/server/session-store.js +243 -0
  185. package/dist/server/subscriptions.js +189 -0
  186. package/dist/server/transports.js +214 -0
  187. package/dist/server/wire-error.js +26 -0
  188. package/dist/sync/event-log.js +89 -0
  189. package/dist/sync/fit.js +202 -0
  190. package/dist/sync/history-reader.js +33 -0
  191. package/dist/sync/history-sqlite.js +281 -0
  192. package/dist/sync/history.js +163 -0
  193. package/dist/sync/index.js +5 -0
  194. package/dist/sync/journal-sqlite.js +316 -0
  195. package/dist/sync/journal.js +10 -0
  196. package/dist/sync/live-tails.js +85 -0
  197. package/dist/sync/node-sqlite.js +27 -0
  198. package/dist/sync/projection.js +32 -0
  199. package/dist/sync/recovery.js +117 -0
  200. package/dist/sync/retry.js +45 -0
  201. package/dist/sync/schema.js +73 -0
  202. package/dist/sync/sql.js +94 -0
  203. package/dist/sync/sqlite-file.js +31 -0
  204. package/dist/sync/sqlite.js +18 -0
  205. package/dist/sync/worker.js +212 -0
  206. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  207. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  208. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/options.d.ts +24 -11
  210. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  212. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  213. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  214. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  216. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  218. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  219. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  220. package/dist/types/core/agents/process-pool.d.ts +8 -0
  221. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  222. package/dist/types/core/presets.d.ts +2 -2
  223. package/dist/types/core/presets.d.ts.map +1 -1
  224. package/dist/types/server/bin.d.ts +3 -0
  225. package/dist/types/server/bin.d.ts.map +1 -0
  226. package/dist/types/server/transports.d.ts +2 -1
  227. package/dist/types/server/transports.d.ts.map +1 -1
  228. package/dist/types/sync/node-sqlite.d.ts +4 -1
  229. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  230. package/docs/consuming.md +30 -4
  231. package/docs/deploy.md +28 -0
  232. package/docs/harnesses.md +13 -1
  233. package/package.json +43 -18
  234. package/src/core/agents/claude-code/approvals.ts +5 -1
  235. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  236. package/src/core/agents/claude-code/options.ts +24 -11
  237. package/src/core/agents/claude-code/session.ts +13 -0
  238. package/src/core/agents/codex-app-server/homes.ts +11 -2
  239. package/src/core/agents/codex-app-server/login.ts +30 -0
  240. package/src/core/agents/codex-app-server/requests.ts +7 -6
  241. package/src/core/agents/codex-app-server/session.ts +11 -2
  242. package/src/core/agents/process-pool.ts +30 -4
  243. package/src/core/presets.ts +3 -2
  244. package/src/server/bin.ts +25 -10
  245. package/src/server/transports.ts +6 -1
  246. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,338 @@
1
+ import { WIRE_API, WIRE_ERROR_CODES, WIRE_METHODS, WIRE_PROTOCOL_VERSION, readRefusalData, } from "../protocol/index.js";
2
+ import { Listeners } from "./listeners.js";
3
+ import { Rpc, WireRequestError } from "./rpc.js";
4
+ /** The transport dropped (and reconnection, if enabled, gave up). */
5
+ export class ConnectionClosedError extends Error {
6
+ name = "ConnectionClosedError";
7
+ }
8
+ /**
9
+ * The server answered, and refused this client (`reason`). Asked again it
10
+ * answers the same, so a client that redials stops: the connection is closed
11
+ * for good, and what waits on it fails with this.
12
+ */
13
+ export class ConnectionRefusedError extends ConnectionClosedError {
14
+ reason;
15
+ url;
16
+ name = "ConnectionRefusedError";
17
+ constructor(reason,
18
+ /** The server that refused it; empty for a client that dialed no URL (`spawn`, `attach`, a factory). */
19
+ url, message = `agent-server at ${url} ${reason === "token_refused" ? "refused the token" : "needs a token"} (401)`) {
20
+ super(message);
21
+ this.reason = reason;
22
+ this.url = url;
23
+ }
24
+ }
25
+ /**
26
+ * The server speaks another wire protocol version than this client: it
27
+ * answered `initialize` with `protocolVersionMismatch`, or selected a version
28
+ * this build does not speak. No redial can change that (only another build of
29
+ * the client or of the server), so it is a refusal: the client stops and what
30
+ * waits on it fails with this. `code` and `data` are the wire error's, as a
31
+ * `WireRequestError` would carry them.
32
+ */
33
+ export class ProtocolVersionMismatchError extends ConnectionRefusedError {
34
+ protocolVersion;
35
+ supported;
36
+ name = "ProtocolVersionMismatchError";
37
+ reason = "protocol_mismatch";
38
+ code = WIRE_ERROR_CODES.protocolVersionMismatch;
39
+ constructor(
40
+ /** The version this client speaks (`WIRE_PROTOCOL_VERSION`). */
41
+ protocolVersion,
42
+ /** The versions the server speaks, as it said; empty when it did not say. */
43
+ supported, url,
44
+ /** What the server said, when it refused the version itself. */
45
+ detail) {
46
+ super("protocol_mismatch", url, `agent-server${url ? ` at ${url}` : ""} speaks wire protocol ${supported.length ? supported.join(", ") : "another version"}, this client ${protocolVersion}${detail ? ` (${detail})` : ""}: upgrade the one that is older`);
47
+ this.protocolVersion = protocolVersion;
48
+ this.supported = supported;
49
+ }
50
+ get data() {
51
+ return { supported: this.supported };
52
+ }
53
+ }
54
+ /** Re-sends of a request the server converges on, whose connection dropped before its answer. */
55
+ const MAX_RESENDS = 3;
56
+ /**
57
+ * The client's connection to its server: the transport, its handshake and
58
+ * the identity of the server behind it, redialing with backoff, the requests
59
+ * in flight, and re-sending those the server converges on.
60
+ */
61
+ export class Connection {
62
+ factory;
63
+ options;
64
+ redials;
65
+ host;
66
+ url;
67
+ transport = null;
68
+ rpc;
69
+ events = new Listeners();
70
+ closed = false;
71
+ /** The server refused a redial: what every request since fails with. */
72
+ refusal = null;
73
+ /** The server process (or, durable, the journal) whose logs the client follows. */
74
+ serverIdentity;
75
+ initializing = null;
76
+ reconnecting = false;
77
+ /** Ends the redial backoff early: `close()` must not wait it out. */
78
+ stopBackoff = null;
79
+ /** The running reconnect loop, for a request that waits to be re-sent. */
80
+ reconnection = null;
81
+ constructor(factory, options, redials, host,
82
+ /** The URL it dials, for what a refusal says; empty when it dials none. */
83
+ url = "") {
84
+ this.factory = factory;
85
+ this.options = options;
86
+ this.redials = redials;
87
+ this.host = host;
88
+ this.url = url;
89
+ this.rpc = new Rpc({
90
+ requestTimeoutMs: options.requestTimeoutMs,
91
+ // A healthy server answers every request in time (`history/wait` is
92
+ // bounded below this): a client that can redial replaces the
93
+ // half-open connection. One that cannot (attach, and spawn, whose
94
+ // transport is the server process) fails only this request.
95
+ timedOut: (transport, method) => {
96
+ if (this.redials && this.transport === transport) {
97
+ transport.close();
98
+ return new ConnectionClosedError(`request timed out: ${method}`);
99
+ }
100
+ return new WireRequestError(WIRE_ERROR_CODES.internalError, `request timed out: ${method}`);
101
+ },
102
+ });
103
+ }
104
+ async open() {
105
+ const transport = await this.factory();
106
+ if (this.closed) {
107
+ transport.close();
108
+ throw new ConnectionClosedError("client closed while connecting");
109
+ }
110
+ if (transport.closed)
111
+ throw new ConnectionClosedError("transport opened already closed");
112
+ this.transport = transport;
113
+ this.host.opened(this.reconnecting);
114
+ transport.onLine((line) => {
115
+ if (this.transport === transport)
116
+ this.host.line(line, transport);
117
+ });
118
+ transport.onClose((reason) => this.dropped(transport, reason));
119
+ }
120
+ /**
121
+ * Handshake (memoized). A server of another protocol version closes the
122
+ * client for good: it rejects with `ProtocolVersionMismatchError`.
123
+ */
124
+ initialize() {
125
+ this.initializing ??= this.request(WIRE_METHODS.initialize, {
126
+ protocolVersion: WIRE_PROTOCOL_VERSION,
127
+ client: this.options.clientInfo,
128
+ })
129
+ .then((result) => {
130
+ if (result.protocolVersion !== WIRE_PROTOCOL_VERSION)
131
+ throw this.mismatched([result.protocolVersion], "it selected another");
132
+ // The restart question, answered by the handshake instead of
133
+ // inferred from seq patterns: a changed identity means every session
134
+ // log the client followed died with the old process. Durable logs
135
+ // (`historyId`) outlive it, and so do its cursors.
136
+ const identity = result.historyId ?? result.instanceId;
137
+ if (this.serverIdentity !== undefined && this.serverIdentity !== identity)
138
+ this.host.serverChanged();
139
+ this.serverIdentity = identity;
140
+ return result;
141
+ })
142
+ .catch((error) => {
143
+ this.initializing = null;
144
+ if (error instanceof WireRequestError &&
145
+ error.code === WIRE_ERROR_CODES.protocolVersionMismatch)
146
+ throw this.mismatched(readRefusalData(error, "protocolVersionMismatch")?.supported ?? [], error.message);
147
+ throw error;
148
+ });
149
+ return this.initializing;
150
+ }
151
+ // @ref LLP 0001#d16--a-listener-answers-native-clients-only-and-needs-a-token-beyond-loopback — refused like a token: no redial changes it
152
+ /** The server speaks another protocol version: the client is closed by its refusal, which this returns. */
153
+ mismatched(supported, detail) {
154
+ const refusal = new ProtocolVersionMismatchError(WIRE_PROTOCOL_VERSION, supported, this.url, detail);
155
+ this.refused(refusal);
156
+ return this.refusal ?? refusal;
157
+ }
158
+ /** A request, its answer read as `WIRE_API` reads the method's. */
159
+ request(method, params, onAnswer) {
160
+ if (this.closed)
161
+ return Promise.reject(this.refusal ?? new ConnectionClosedError("client closed"));
162
+ const transport = this.transport;
163
+ if (!transport)
164
+ return Promise.reject(new ConnectionClosedError("not connected"));
165
+ return this.rpc.request(transport, method, params, WIRE_API[method].decode, onAnswer);
166
+ }
167
+ /**
168
+ * A request the server converges on when repeated (`turn/start`,
169
+ * `turn/steer`), re-sent over a redialed connection: a start whose ack was
170
+ * lost continues instead of failing while the turn runs unseen. Not to a
171
+ * server with fresh logs (a volatile restart): the turn died with the old
172
+ * process, or never reached it, and a re-send could run it again. A few
173
+ * re-sends at most: a server that accepts connections but never answers
174
+ * would otherwise be retried forever.
175
+ */
176
+ async resend(method, params, onAnswer) {
177
+ for (let resends = 0;; resends++) {
178
+ const identity = this.serverIdentity;
179
+ try {
180
+ return await this.request(method, params, onAnswer);
181
+ }
182
+ catch (error) {
183
+ if (!(error instanceof ConnectionClosedError) || !this.redials || resends >= MAX_RESENDS)
184
+ throw error;
185
+ await this.reconnection;
186
+ if (this.closed || !this.transport || this.serverIdentity !== identity)
187
+ throw this.refusal ?? error;
188
+ }
189
+ }
190
+ }
191
+ close() {
192
+ if (this.closed)
193
+ return;
194
+ this.closed = true;
195
+ const reason = new ConnectionClosedError("client closed");
196
+ this.rpc.failAll(reason);
197
+ this.host.closed(reason);
198
+ this.transport?.close();
199
+ this.transport = null;
200
+ this.stopBackoff?.();
201
+ this.events.emit({ state: "closed", reason: reason.message });
202
+ }
203
+ dropped(transport, reason) {
204
+ // A late close from a superseded transport must not tear down the current one.
205
+ if (this.transport !== transport)
206
+ return;
207
+ this.transport = null;
208
+ const why = reason ?? "connection closed";
209
+ this.rpc.failAll(new ConnectionClosedError(why));
210
+ if (this.closed)
211
+ return;
212
+ this.events.emit({ state: "disconnected", reason: why });
213
+ if (!this.redials) {
214
+ this.closed = true;
215
+ this.host.closed(new ConnectionClosedError(why));
216
+ this.events.emit({ state: "closed", reason: why });
217
+ return;
218
+ }
219
+ this.reconnection ??= this.redial().finally(() => {
220
+ this.reconnection = null;
221
+ });
222
+ }
223
+ async redial() {
224
+ if (this.reconnecting)
225
+ return;
226
+ this.reconnecting = true;
227
+ const maxAttempts = this.options.maxReconnectAttempts ?? 8;
228
+ const base = this.options.reconnectDelayMs ?? 250;
229
+ const droppedAt = Date.now();
230
+ // The server whose logs this client followed, once: an attempt whose
231
+ // connection drops after its handshake has already adopted the new one.
232
+ const followed = this.serverIdentity;
233
+ let error;
234
+ try {
235
+ for (let attempt = 0; attempt < maxAttempts && !this.closed; attempt++) {
236
+ const delayMs = Math.min(10_000, base * 2 ** Math.min(attempt, 5));
237
+ this.events.emit({
238
+ state: "reconnecting",
239
+ attempt: attempt + 1,
240
+ delayMs,
241
+ ...(error !== undefined && { error }),
242
+ });
243
+ await new Promise((resolve) => {
244
+ const timer = setTimeout(resolve, delayMs);
245
+ this.stopBackoff = () => {
246
+ clearTimeout(timer);
247
+ resolve();
248
+ };
249
+ });
250
+ this.stopBackoff = null;
251
+ if (this.closed)
252
+ break;
253
+ try {
254
+ await this.open();
255
+ if (this.closed || !this.transport) {
256
+ error = "the connection closed as it opened";
257
+ continue;
258
+ }
259
+ // Re-handshake: the transport may have reconnected to a DIFFERENT
260
+ // process (or a different build). A version mismatch is a refusal
261
+ // (it closes the client) instead of silently mixing dialects, and a changed identity
262
+ // adopts the fresh logs before anything is subscribed again.
263
+ this.initializing = null;
264
+ const initialize = await this.initialize();
265
+ if (this.closed || !this.transport) {
266
+ error = "the connection closed during the handshake";
267
+ continue;
268
+ }
269
+ // Before subscribing again, and before requests waiting on this
270
+ // redial are sent again: a consumer may change what they carry.
271
+ this.events.emit({
272
+ state: "reconnected",
273
+ attempts: attempt + 1,
274
+ downMs: Date.now() - droppedAt,
275
+ serverChanged: followed !== undefined && followed !== this.serverIdentity,
276
+ initialize,
277
+ });
278
+ // Subscriptions die with the connection: subscribe to every session
279
+ // followed again (pipelined), each from what the client holds.
280
+ this.host.reconnected();
281
+ if (!this.transport)
282
+ continue;
283
+ return;
284
+ }
285
+ catch (failure) {
286
+ // @ref LLP 0001#d16--a-listener-answers-native-clients-only-and-needs-a-token-beyond-loopback
287
+ // A refusal is the server's answer, not an outage: every redial would get it.
288
+ if (failure instanceof ConnectionRefusedError)
289
+ return this.refused(failure);
290
+ error = failure instanceof Error ? failure.message : String(failure);
291
+ // The attempt's own transport, when its handshake failed: the next
292
+ // attempt opens another, and nothing else would close this one.
293
+ this.discard();
294
+ }
295
+ }
296
+ if (!this.closed) {
297
+ this.closed = true;
298
+ const reason = `reconnect failed${error === undefined ? "" : `: ${error}`}`;
299
+ this.host.closed(new ConnectionClosedError(reason));
300
+ this.events.emit({ state: "closed", reason });
301
+ }
302
+ }
303
+ finally {
304
+ this.reconnecting = false;
305
+ }
306
+ }
307
+ /** Let the current transport go without reporting it as a drop: it was never handed over. */
308
+ discard() {
309
+ const transport = this.transport;
310
+ this.transport = null;
311
+ transport?.close();
312
+ }
313
+ /**
314
+ * Closed for good by the server's refusal, which what waits on the
315
+ * connection fails with: the requests in flight, and the transport it came
316
+ * on (a handshake's) let go.
317
+ */
318
+ refused(refusal) {
319
+ if (this.closed)
320
+ return;
321
+ this.closed = true;
322
+ this.refusal = refusal;
323
+ this.rpc.failAll(refusal);
324
+ this.discard();
325
+ this.stopBackoff?.();
326
+ this.host.closed(refusal);
327
+ const { reason } = refusal;
328
+ this.events.emit(reason === "protocol_mismatch"
329
+ ? {
330
+ state: "refused",
331
+ reason,
332
+ protocolVersion: WIRE_PROTOCOL_VERSION,
333
+ supported: refusal instanceof ProtocolVersionMismatchError ? refusal.supported : [],
334
+ }
335
+ : { state: "refused", reason });
336
+ this.events.emit({ state: "closed", reason: refusal.message });
337
+ }
338
+ }
@@ -0,0 +1,49 @@
1
+ import { HISTORY_METHODS, HISTORY_WAIT_TIMEOUT_MS, HistoryError, isHistoryRefusal, wireErrorName, } from "../protocol/index.js";
2
+ import { DEFAULT_REQUEST_TIMEOUT_MS, WireRequestError } from "./rpc.js";
3
+ /** History RPC adaptation has no execution, reconnection or event-cursor state.
4
+ * A refusal fails with the HistoryError a local store would have thrown. */
5
+ export function createHistoryClient(sendRequest, initialize, options) {
6
+ const call = async (method, params) => {
7
+ await initialize();
8
+ try {
9
+ return await sendRequest(method, params);
10
+ }
11
+ catch (error) {
12
+ if (!(error instanceof WireRequestError))
13
+ throw error;
14
+ const code = wireErrorName(error.code);
15
+ throw isHistoryRefusal(code) ? new HistoryError(code, error.message) : error;
16
+ }
17
+ };
18
+ return {
19
+ checkpoint: (request) => call(HISTORY_METHODS.checkpoint, request),
20
+ list: (request = {}) => call(HISTORY_METHODS.list, request),
21
+ head: (ref) => call(HISTORY_METHODS.head, ref),
22
+ // Pages are checked where they are trusted: by `readHistoryPage`, which every
23
+ // helper reads through, and by the store that imports them.
24
+ read: (request) => call(HISTORY_METHODS.read, request),
25
+ import: (page) => call(HISTORY_METHODS.import, page),
26
+ fork: (request) => call(HISTORY_METHODS.fork, request),
27
+ commit: (request) => call(HISTORY_METHODS.commit, request),
28
+ // Abort ends the local wait immediately. The server wait is independently bounded
29
+ // and is also cancelled if this transport closes.
30
+ wait: async (request, signal) => {
31
+ signal?.throwIfAborted();
32
+ const wait = call(HISTORY_METHODS.wait, {
33
+ ...request,
34
+ timeoutMs: Math.min(request.timeoutMs ?? HISTORY_WAIT_TIMEOUT_MS,
35
+ // Answered before the request itself times out.
36
+ Math.max(0, (options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS) - 1000)),
37
+ });
38
+ if (!signal)
39
+ return wait;
40
+ return new Promise((resolve, reject) => {
41
+ const abort = () => reject(signal.reason);
42
+ signal.addEventListener("abort", abort, { once: true });
43
+ wait.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
44
+ if (signal.aborted)
45
+ abort();
46
+ });
47
+ },
48
+ };
49
+ }
@@ -0,0 +1,6 @@
1
+ // @zvada/agent-server/client — typed client for the agent-server wire.
2
+ // With the root export's contract, all a remote consumer imports.
3
+ export { AgentServerClient, ConnectionClosedError, ConnectionRefusedError, EventGapError, ProtocolVersionMismatchError, } from "./client.js";
4
+ export { LoginError } from "./logins.js";
5
+ export { WireRequestError, refusalData } from "./rpc.js";
6
+ export { connectTransport, socketTransport, spawnTransport, } from "./transports.js";
@@ -0,0 +1,19 @@
1
+ /** The handlers of one kind of client event, called in turn: one that throws is ignored. */
2
+ export class Listeners {
3
+ handlers = new Set();
4
+ /** Add a handler; returns its removal. */
5
+ add(handler) {
6
+ this.handlers.add(handler);
7
+ return () => this.handlers.delete(handler);
8
+ }
9
+ emit(value) {
10
+ for (const handler of [...this.handlers]) {
11
+ try {
12
+ handler(value);
13
+ }
14
+ catch {
15
+ // A consumer's callback cannot interrupt dispatch or the other consumers.
16
+ }
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,92 @@
1
+ /** A login that ended without succeeding: `outcome` says how (`failed`, `cancelled`, `expired`), the message why. */
2
+ export class LoginError extends Error {
3
+ end;
4
+ outcome;
5
+ constructor(end) {
6
+ super(end.error ?? `The login ${end.outcome === "expired" ? "expired" : `was ${end.outcome}`}.`);
7
+ this.end = end;
8
+ this.name = "LoginError";
9
+ this.outcome = end.outcome;
10
+ }
11
+ }
12
+ /**
13
+ * Start a login and follow it to its end. Its end, and the connection's, are
14
+ * watched for from before the request: either may come before the answer.
15
+ */
16
+ export async function startLogin(port, request) {
17
+ // Every login's end from before the request: this one's may come before its answer.
18
+ const early = new Map();
19
+ const follow = {};
20
+ /** The connection was lost before the answer was read: no end can be told now. */
21
+ let lostEarly = false;
22
+ const offUpdates = port.updates.add((update) => {
23
+ if (!update.login)
24
+ return;
25
+ if (follow.told)
26
+ follow.told(update);
27
+ else
28
+ early.set(update.login.loginId, update);
29
+ });
30
+ const offConnection = port.connection.add((event) => {
31
+ // Its end may be told while the connection is down: a product reads the login again.
32
+ if (follow.lost) {
33
+ if (event.state === "reconnected" || event.state === "closed")
34
+ follow.lost();
35
+ }
36
+ // Before its answer is read, a drop is what loses it: a request sent
37
+ // during a redial's handshake is followed by that redial's `reconnected`.
38
+ else if (event.state === "disconnected" || event.state === "closed")
39
+ lostEarly = true;
40
+ });
41
+ let login;
42
+ try {
43
+ login = await request();
44
+ }
45
+ catch (error) {
46
+ offUpdates();
47
+ offConnection();
48
+ throw error;
49
+ }
50
+ let resolveDone;
51
+ let rejectDone;
52
+ const done = new Promise((resolve, reject) => {
53
+ resolveDone = resolve;
54
+ rejectDone = reject;
55
+ });
56
+ // A caller that only cancels must not see an unhandled rejection.
57
+ done.catch(() => { });
58
+ const settle = (end, auth) => {
59
+ offUpdates();
60
+ offConnection();
61
+ if (end.outcome === "succeeded" && auth)
62
+ resolveDone(auth);
63
+ else
64
+ rejectDone(new LoginError(end));
65
+ };
66
+ /** Its end as the server told it, with the harness's login after it. */
67
+ const told = (update) => {
68
+ if (update?.login?.loginId === login.loginId)
69
+ settle(update.login, update.auth);
70
+ };
71
+ follow.told = told;
72
+ follow.lost = () => settle({
73
+ loginId: login.loginId,
74
+ outcome: "disconnected",
75
+ error: "The connection to the server was lost: read the login's status again.",
76
+ });
77
+ // An end told early wins: it says how the login ended, a lost connection only that it is unknown.
78
+ told(early.get(login.loginId));
79
+ if (lostEarly)
80
+ follow.lost();
81
+ return {
82
+ ...login,
83
+ done,
84
+ complete: async (code) => {
85
+ told(await port.complete(login.loginId, code));
86
+ return done;
87
+ },
88
+ cancel: async () => {
89
+ await port.cancel(login.loginId);
90
+ },
91
+ };
92
+ }
@@ -0,0 +1,105 @@
1
+ import { WIRE_ERROR_CODES, encodeRequest, readRefusalData, } from "../protocol/index.js";
2
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
3
+ /** The server answered a request with a JSON-RPC error. */
4
+ export class WireRequestError extends Error {
5
+ code;
6
+ data;
7
+ name = "WireRequestError";
8
+ constructor(code, message, data) {
9
+ super(message);
10
+ this.code = code;
11
+ this.data = data;
12
+ }
13
+ }
14
+ /** Where a result failed its schema, as the first issue says: `: harnesses.acp.files: …`. */
15
+ function whereMalformed(error) {
16
+ const issue = error
17
+ ?.issues?.[0];
18
+ if (!issue)
19
+ return "";
20
+ return `: ${issue.path.length ? `${issue.path.map(String).join(".")}: ` : ""}${issue.message}`;
21
+ }
22
+ /**
23
+ * What a refusal carries, read by its name (`WIRE_REFUSAL_DATA`): undefined
24
+ * unless `error` is that refusal and its data is well formed. A
25
+ * `resumeRequired` names the conversation to resume, a `recoveryRequired` the
26
+ * head to confirm at.
27
+ */
28
+ export function refusalData(error, name) {
29
+ return error instanceof WireRequestError ? readRefusalData(error, name) : undefined;
30
+ }
31
+ /**
32
+ * The client's requests in flight: ids, timeouts and their answers. A
33
+ * response settles its request synchronously, as its line is read.
34
+ */
35
+ export class Rpc {
36
+ options;
37
+ nextId = 1;
38
+ pending = new Map();
39
+ constructor(options) {
40
+ this.options = options;
41
+ }
42
+ /** `decode` reads the answer (the method's `WIRE_API` decoder), throwing on what it cannot read. */
43
+ request(transport, method, params, decode, onAnswer) {
44
+ const id = this.nextId++;
45
+ const timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
46
+ return new Promise((resolve, reject) => {
47
+ const timer = setTimeout(() => {
48
+ this.pending.delete(id);
49
+ reject(this.options.timedOut(transport, method));
50
+ }, timeoutMs);
51
+ this.pending.set(id, {
52
+ settle: (raw) => {
53
+ let result;
54
+ try {
55
+ result = decode(raw);
56
+ }
57
+ catch (error) {
58
+ reject(new WireRequestError(WIRE_ERROR_CODES.internalError, `malformed ${method} result${whereMalformed(error)}`));
59
+ return;
60
+ }
61
+ try {
62
+ onAnswer?.(result);
63
+ }
64
+ catch (error) {
65
+ reject(error);
66
+ return;
67
+ }
68
+ resolve(result);
69
+ },
70
+ reject,
71
+ timer,
72
+ });
73
+ try {
74
+ transport.send(encodeRequest(id, method, params));
75
+ }
76
+ catch (error) {
77
+ clearTimeout(timer);
78
+ this.pending.delete(id);
79
+ reject(error);
80
+ }
81
+ });
82
+ }
83
+ /** A response line: settle the request it answers. */
84
+ settle(message) {
85
+ if (message.id === null)
86
+ return; // a protocol-level error for an unparseable line
87
+ const pending = this.pending.get(message.id);
88
+ if (!pending)
89
+ return;
90
+ this.pending.delete(message.id);
91
+ clearTimeout(pending.timer);
92
+ const { error } = message;
93
+ if (error)
94
+ pending.reject(new WireRequestError(error.code, error.message, error.data));
95
+ else
96
+ pending.settle(message.result);
97
+ }
98
+ failAll(error) {
99
+ for (const pending of this.pending.values()) {
100
+ clearTimeout(pending.timer);
101
+ pending.reject(error);
102
+ }
103
+ this.pending.clear();
104
+ }
105
+ }