@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,432 @@
1
+ import { WIRE_ERROR_CODES, createSeqCursor, isLiveEnvelope, isUnknownEvent, } from "../protocol/index.js";
2
+ import { Listeners } from "./listeners.js";
3
+ import { WireRequestError } from "./rpc.js";
4
+ /**
5
+ * Events were lost irrecoverably: the replay window was evicted or the server
6
+ * restarted. The consumer's local view of the session is stale.
7
+ */
8
+ export class EventGapError extends Error {
9
+ name = "EventGapError";
10
+ }
11
+ /** What the client keeps of one session it follows. */
12
+ class SessionStream {
13
+ /** Frames waiting for the kept events before them. */
14
+ held = [];
15
+ /** Parts whose snapshot this transport delivered: their live deltas are contiguous from it. */
16
+ snapshots = new Map();
17
+ /** The transport a replay of the session is in flight on. */
18
+ healingOn;
19
+ /** This client watches it: it follows the session until it unsubscribes or the session ends. */
20
+ watched = false;
21
+ /**
22
+ * The running turn this client follows it for, until the turn's
23
+ * `turn.ended`; or, once an answer said it runs no more, through `endsBy`,
24
+ * the seq it ended by, its end evicted or not.
25
+ */
26
+ turn;
27
+ /** Followed by name, watched or for one of this client's turns: not only as one of every session. */
28
+ get named() {
29
+ return this.watched || this.turn !== undefined;
30
+ }
31
+ }
32
+ // @ref LLP 0008#client-api — one accept-then-drain path per session
33
+ /**
34
+ * The sessions the client follows, each delivered once and in order: a frame
35
+ * is held, then everything contiguous with what was delivered drains, and a
36
+ * gap heals by replay. A session is followed from a subscription's answer
37
+ * (`subscribe`, `joinTurn`, `runTurn`, `startTurn`) — or, under a
38
+ * subscription to every session, from its first frame — for as long as the
39
+ * server streams it: while it is watched, or one of this client's turns runs
40
+ * in it, or every session is. Then what the client kept of it is let go.
41
+ */
42
+ export class Streams {
43
+ host;
44
+ turns;
45
+ /** Per-session seq discipline — the shared `/protocol` implementation. */
46
+ cursor = createSeqCursor();
47
+ streams = new Map();
48
+ /** Follows every session (`subscribeAll`): from the ask, not its answer, until `unsubscribeAll` or a refusal. */
49
+ all = false;
50
+ /** A redialed transport's handshake is pending: frames wait for it to say which server this is. */
51
+ paused = false;
52
+ /** The frames received so far: a subscription's answer marks a point among them. */
53
+ position = 0;
54
+ events = new Listeners();
55
+ gaps = new Listeners();
56
+ constructor(host, turns) {
57
+ this.host = host;
58
+ this.turns = turns;
59
+ }
60
+ /**
61
+ * What to subscribe to again after a redial: the sessions its turns run in
62
+ * first (a turn's subscription never counts against the server's cap), then
63
+ * those it watches.
64
+ */
65
+ resubscriptions() {
66
+ const turns = [];
67
+ const watches = [];
68
+ for (const [sessionId, { watched, turn }] of this.streams) {
69
+ if (watched)
70
+ watches.push({ sessionId });
71
+ else if (turn)
72
+ turns.push({ sessionId, turnId: turn.id });
73
+ }
74
+ return [...turns, ...watches];
75
+ }
76
+ get followsAll() {
77
+ return this.all;
78
+ }
79
+ follows(sessionId) {
80
+ return this.streams.has(sessionId);
81
+ }
82
+ watches(sessionId) {
83
+ return this.streams.get(sessionId)?.watched ?? false;
84
+ }
85
+ /** A frame from the transport. */
86
+ accept(envelope, transport) {
87
+ const arrival = ++this.position;
88
+ const { sessionId, event } = envelope;
89
+ let stream = this.streams.get(sessionId);
90
+ if (!stream) {
91
+ // Not followed: a frame the server sent before it read an unsubscribe.
92
+ if (!this.all)
93
+ return;
94
+ // One of every session's, heard for the first time: live from here, no history.
95
+ stream = this.follow(sessionId);
96
+ this.cursor.seek(sessionId, isLiveEnvelope(envelope) ? envelope.seq : envelope.seq - 1);
97
+ }
98
+ if (!isUnknownEvent(event) && event.type === "message.part")
99
+ stream.snapshots.set(event.part.id, { seq: envelope.seq, turnId: event.turnId });
100
+ stream.held.push({ envelope, transport, arrival });
101
+ this.drain(sessionId, stream);
102
+ }
103
+ /**
104
+ * A subscription's answer, the moment it arrives: the point it marks, and
105
+ * why the session is followed from then on. A session followed already
106
+ * keeps its place; a new one starts at `afterSeq`, or at the head and
107
+ * downloads no history. What was kept before the point and the client does
108
+ * not hold is replayed.
109
+ */
110
+ joined(sessionId, headSeq, follow, afterSeq) {
111
+ let stream = this.streams.get(sessionId);
112
+ if (!stream) {
113
+ stream = this.follow(sessionId);
114
+ this.cursor.seek(sessionId, Math.min(afterSeq ?? headSeq, headSeq));
115
+ }
116
+ if (follow === "watch")
117
+ stream.watched = true;
118
+ else if (follow !== "all")
119
+ stream.turn = { id: follow.turnId };
120
+ if (this.cursor.last(sessionId) < headSeq)
121
+ void this.heal(sessionId);
122
+ }
123
+ /**
124
+ * A subscription's answer says the turn the session is followed for runs
125
+ * no more, so the server streams none of it: it ended by `headSeq`. What
126
+ * the client missed up to there heals, the turn's end with it unless that
127
+ * was evicted; then the session is let go, unless something else follows it.
128
+ */
129
+ turnEnded(sessionId, turnId, headSeq) {
130
+ const turn = this.streams.get(sessionId)?.turn;
131
+ if (turn?.id !== turnId)
132
+ return;
133
+ // The first answer bounds it: a redial while it heals moves nothing.
134
+ turn.endsBy = Math.min(turn.endsBy ?? headSeq, headSeq);
135
+ if (!this.pastTurn(sessionId))
136
+ void this.heal(sessionId);
137
+ }
138
+ /** `subscribeAll` asked: every server from now on is asked for every session, until `unfollowAll`. */
139
+ followAll() {
140
+ this.all = true;
141
+ }
142
+ /**
143
+ * Every session's frames, from now: those with a running turn start at
144
+ * their head. An answer to an ask `unfollowAll` withdrew follows nothing.
145
+ */
146
+ joinedAll(sessions) {
147
+ if (!this.all)
148
+ return;
149
+ for (const { sessionId, headSeq } of sessions)
150
+ this.joined(sessionId, headSeq, "all");
151
+ }
152
+ unfollowAll() {
153
+ this.all = false;
154
+ for (const [sessionId, stream] of [...this.streams])
155
+ this.release(sessionId, stream);
156
+ }
157
+ /** Stop watching the session: a turn of this client's that runs there is followed to its end. */
158
+ unwatch(sessionId) {
159
+ const stream = this.streams.get(sessionId);
160
+ if (!stream)
161
+ return;
162
+ stream.watched = false;
163
+ this.release(sessionId, stream);
164
+ }
165
+ /** The server stopped streaming to this connection: subscribe again from what the client holds. */
166
+ overflowed(notice) {
167
+ if ("all" in notice) {
168
+ if (!this.all)
169
+ return;
170
+ for (const stream of this.streams.values())
171
+ if (!stream.named)
172
+ stream.snapshots.clear();
173
+ this.host.resubscribeAll();
174
+ return;
175
+ }
176
+ const stream = this.streams.get(notice.sessionId);
177
+ if (!stream?.named)
178
+ return;
179
+ // Its deltas since were dropped: its next ones wait for the open parts that come with the subscription.
180
+ stream.snapshots.clear();
181
+ this.host.resubscribe(notice.sessionId, stream.watched ? undefined : stream.turn?.id);
182
+ }
183
+ /** No longer followed: its frames are dropped, and a later subscription starts afresh. */
184
+ forget(sessionId) {
185
+ this.streams.delete(sessionId);
186
+ this.cursor.reset(sessionId);
187
+ }
188
+ /**
189
+ * A new transport: replay cannot recover deltas lost during an outage, so
190
+ * each part's next deltas wait for its next snapshot on this one (the open
191
+ * parts a subscription sends).
192
+ */
193
+ reconnected(redialed) {
194
+ for (const stream of this.streams.values())
195
+ stream.snapshots.clear();
196
+ this.paused = redialed;
197
+ }
198
+ /** The redial's handshake is done (fresh logs adopted, if any): what waited for it drains. */
199
+ resume() {
200
+ this.paused = false;
201
+ for (const [sessionId, stream] of [...this.streams])
202
+ this.drain(sessionId, stream);
203
+ }
204
+ /**
205
+ * The server behind the transport is another one: every log the client
206
+ * followed died with the old process. Their turns fail, and each followed
207
+ * session replays its fresh log from its start, if the new server has one.
208
+ */
209
+ adoptFreshLogs() {
210
+ for (const sessionId of new Set([...this.streams.keys(), ...this.turns.sessions()]))
211
+ this.reportGap(sessionId, "server_restarted", new EventGapError("server instance changed; the turn's session log died with the old process"));
212
+ // Frames the fresh process already sent stay: they may have left its replay window.
213
+ for (const [sessionId, stream] of this.streams) {
214
+ stream.held = stream.held.filter((entry) => entry.transport === this.host.transport());
215
+ this.cursor.seek(sessionId, 0);
216
+ }
217
+ }
218
+ /** A session's subscription was refused: the server does not know it. */
219
+ missing(sessionId) {
220
+ if (!this.streams.has(sessionId))
221
+ return;
222
+ this.reportGap(sessionId, "session_missing", new EventGapError(`session ${sessionId} is unknown to the server (restarted?)`));
223
+ this.forget(sessionId);
224
+ }
225
+ /**
226
+ * The server refused to stream the session again: it is followed no more,
227
+ * and its turns fail instead of waiting for frames that will not come.
228
+ */
229
+ refused(sessionId, why) {
230
+ if (!this.streams.has(sessionId))
231
+ return;
232
+ this.reportGap(sessionId, "subscription_refused", new EventGapError(`the server refused to stream session ${sessionId}: ${why}`));
233
+ this.forget(sessionId);
234
+ }
235
+ /** The server refused to stream every session again: the sessions heard only that way are let go. */
236
+ refusedAll(why) {
237
+ this.all = false;
238
+ for (const [sessionId, stream] of [...this.streams])
239
+ if (!stream.named)
240
+ this.refused(sessionId, why);
241
+ }
242
+ reportGap(sessionId, reason, error) {
243
+ this.turns.fail(sessionId, error);
244
+ this.gaps.emit({ sessionId, reason, error });
245
+ }
246
+ follow(sessionId) {
247
+ const stream = new SessionStream();
248
+ this.streams.set(sessionId, stream);
249
+ return stream;
250
+ }
251
+ /** Let a session go once nothing follows it: it is not watched, runs no turn of this client's, and not every session is followed. */
252
+ release(sessionId, stream) {
253
+ if (!stream.named && !this.all)
254
+ this.forget(sessionId);
255
+ }
256
+ /** The turn the session is followed for is over: so is following it for the turn. */
257
+ endTurn(sessionId, stream) {
258
+ stream.turn = undefined;
259
+ this.release(sessionId, stream);
260
+ }
261
+ /** Through the seq its turn ended by, the session is followed for it no more. */
262
+ pastTurn(sessionId) {
263
+ const stream = this.streams.get(sessionId);
264
+ const endsBy = stream?.turn?.endsBy;
265
+ if (!stream || endsBy === undefined || this.cursor.last(sessionId) < endsBy)
266
+ return false;
267
+ this.endTurn(sessionId, stream);
268
+ return true;
269
+ }
270
+ /** Deliver what is contiguous; a gap heals by replay, unless a replay is already under way. */
271
+ drain(sessionId, stream) {
272
+ if (this.paused || (stream.healingOn && stream.healingOn === this.host.transport()))
273
+ return;
274
+ if (this.settle(sessionId, stream) !== "drained")
275
+ void this.heal(sessionId);
276
+ }
277
+ /**
278
+ * Deliver the held frames contiguous with what was delivered, in seq
279
+ * order, a kept event before the live frames that carry its seq (which keep
280
+ * the order they arrived in, open parts first). The verdicts come from the
281
+ * shared `SeqCursor`.
282
+ */
283
+ settle(sessionId, stream) {
284
+ const { held } = stream;
285
+ held.sort((a, b) => a.envelope.seq - b.envelope.seq ||
286
+ Number(isLiveEnvelope(a.envelope)) - Number(isLiveEnvelope(b.envelope)));
287
+ while (held.length && this.streams.get(sessionId) === stream) {
288
+ const entry = held[0];
289
+ const { envelope } = entry;
290
+ if (isLiveEnvelope(envelope)) {
291
+ // A live frame of a transport since replaced: the new one's open parts restate it.
292
+ if (entry.transport !== this.host.transport()) {
293
+ held.shift();
294
+ continue;
295
+ }
296
+ const verdict = this.cursor.advanceLive(sessionId, envelope.seq);
297
+ if (verdict === "gap")
298
+ return "gap";
299
+ held.shift();
300
+ if (verdict === "deliver")
301
+ this.deliver(stream, entry);
302
+ continue;
303
+ }
304
+ // `gap` leaves the cursor untouched: the frame stays held for the replay that fills the hole.
305
+ const verdict = this.cursor.advance(sessionId, envelope.seq);
306
+ if (verdict === "gap")
307
+ return "gap";
308
+ held.shift();
309
+ if (verdict === "reset") {
310
+ // Defense in depth: a restart is detected by the handshake
311
+ // (`instanceId`) before any frame flows, so this fires only if a
312
+ // fresh log appears with no transport drop. The held frames are the
313
+ // dead log's; the fresh frame is authoritative, and a replay follows.
314
+ this.reportGap(sessionId, "log_reset", new EventGapError(`session ${sessionId} log reset`));
315
+ held.length = 0;
316
+ this.deliver(stream, entry);
317
+ return "reset";
318
+ }
319
+ if (verdict === "deliver")
320
+ this.deliver(stream, entry);
321
+ this.pastTurn(sessionId);
322
+ }
323
+ return "drained";
324
+ }
325
+ /** A frame the cursor accepted: to `onEvent`, then to the session's turn handles. */
326
+ deliver(stream, { envelope, arrival }) {
327
+ const { event } = envelope;
328
+ if (!isUnknownEvent(event)) {
329
+ if (event.type === "message.part.delta") {
330
+ // @ref LLP 0003#deltas-are-live-only — a delta renders after a snapshot this transport delivered
331
+ const snapshot = stream.snapshots.get(event.partId);
332
+ // A replayed snapshot may predate tokens this client never received.
333
+ if (!snapshot || snapshot.turnId !== event.turnId || snapshot.seq > envelope.seq)
334
+ return;
335
+ }
336
+ else if (event.type === "turn.ended") {
337
+ for (const [partId, snapshot] of stream.snapshots)
338
+ if (snapshot.turnId === event.turnId)
339
+ stream.snapshots.delete(partId);
340
+ }
341
+ }
342
+ this.events.emit(envelope);
343
+ this.turns.deliver(envelope, arrival);
344
+ if (isUnknownEvent(event))
345
+ return;
346
+ if (event.type === "session.ended")
347
+ this.forget(envelope.sessionId);
348
+ // The server's subscription for the turn ended with it, and so does this one.
349
+ else if (event.type === "turn.ended" && event.turnId === stream.turn?.id)
350
+ this.endTurn(envelope.sessionId, stream);
351
+ }
352
+ /** Replay the session from what was delivered, page by page, until its held frames drain. */
353
+ async heal(sessionId) {
354
+ const stream = this.streams.get(sessionId);
355
+ const transport = this.host.transport();
356
+ if (!stream || !transport || !this.host.open() || stream.healingOn === transport)
357
+ return;
358
+ stream.healingOn = transport;
359
+ const current = () => this.host.open() &&
360
+ this.host.transport() === transport &&
361
+ this.streams.get(sessionId) === stream;
362
+ const maxAttempts = Math.max(1, this.host.maxReplayAttempts);
363
+ /** A log reset seen while healing: what the fresh log holds after it is replayed next. */
364
+ let reset = false;
365
+ const settle = () => {
366
+ if (this.settle(sessionId, stream) === "reset")
367
+ reset = true;
368
+ };
369
+ try {
370
+ for (let attempt = 1; attempt <= maxAttempts && current(); attempt++) {
371
+ settle();
372
+ if (!current())
373
+ return;
374
+ const fromSeq = this.cursor.last(sessionId) + 1;
375
+ try {
376
+ const page = await this.host.replay(sessionId, fromSeq);
377
+ if (!current())
378
+ return;
379
+ // The cursor can move while the replay is in flight: rows it has
380
+ // passed are duplicates, never a log that restarted.
381
+ const last = this.cursor.last(sessionId);
382
+ for (const envelope of page.events)
383
+ if (envelope.seq > last)
384
+ stream.held.push({ envelope, transport: null, arrival: 0 });
385
+ settle();
386
+ // What it delivered let the session go (its turn's end, or its own): nothing is missing.
387
+ if (!current())
388
+ return;
389
+ const missingFrom = this.cursor.last(sessionId) + 1;
390
+ if (page.firstAvailableSeq !== null && page.firstAvailableSeq > missingFrom) {
391
+ // The prefix was evicted: the gap is unfillable. Fail the turns
392
+ // (their part reconstruction is broken) and jump forward.
393
+ this.reportGap(sessionId, "evicted", new EventGapError(`events ${missingFrom}..${page.firstAvailableSeq - 1} for session ${sessionId} were evicted`));
394
+ this.cursor.seek(sessionId, page.firstAvailableSeq - 1);
395
+ }
396
+ if (page.hasMore) {
397
+ if (this.cursor.last(sessionId) < fromSeq)
398
+ throw new Error("Replay made no progress");
399
+ attempt = 0; // successful pages do not consume the retry budget
400
+ continue;
401
+ }
402
+ break;
403
+ }
404
+ catch (error) {
405
+ if (!current())
406
+ return;
407
+ if (error instanceof WireRequestError && error.code === WIRE_ERROR_CODES.unknownSession) {
408
+ this.missing(sessionId);
409
+ return;
410
+ }
411
+ if (!this.host.transport() || !this.host.open())
412
+ break; // a redial subscribes again
413
+ if (attempt === maxAttempts) {
414
+ this.reportGap(sessionId, "replay_failed", new EventGapError(`failed to replay events from ${fromSeq} for session ${sessionId} after ${maxAttempts} attempts`));
415
+ stream.held = [];
416
+ break;
417
+ }
418
+ await new Promise((resolve) => setTimeout(resolve, this.host.replayRetryDelayMs));
419
+ }
420
+ }
421
+ }
422
+ finally {
423
+ if (stream.healingOn === transport)
424
+ stream.healingOn = undefined;
425
+ }
426
+ if (!current())
427
+ return;
428
+ settle();
429
+ if (reset)
430
+ void this.heal(sessionId);
431
+ }
432
+ }
@@ -0,0 +1,118 @@
1
+ import { spawn as nodeSpawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { channelTransport, pushNdjsonLines } from "../protocol/index.js";
4
+ import { ConnectionRefusedError } from "./connection.js";
5
+ /**
6
+ * Spawn an agent-server subprocess and talk NDJSON over its stdio
7
+ * (deus-machine's model). The child's stderr passes through to ours.
8
+ */
9
+ export function spawnTransport(opts) {
10
+ const child = nodeSpawn(opts.command, opts.args ?? [], {
11
+ cwd: opts.cwd,
12
+ env: opts.env ? { ...process.env, ...opts.env } : process.env,
13
+ stdio: ["pipe", "pipe", "inherit"],
14
+ });
15
+ if (!child.stdin || !child.stdout)
16
+ throw new Error("failed to open child stdio pipes");
17
+ const stdin = child.stdin;
18
+ const { transport, push, end } = channelTransport({
19
+ send: (line) => void stdin.write(`${line}\n`),
20
+ close: () => void child.kill(),
21
+ });
22
+ const rl = createInterface({ input: child.stdout, terminal: false });
23
+ rl.on("line", push);
24
+ // Close on `close`, not `exit`: `exit` can fire before the child's stdout
25
+ // pipe drains its final buffered data, so closing here would drop the
26
+ // trailing NDJSON lines (e.g. a cancelled turn's drain `turn.ended`).
27
+ // `close` is guaranteed only after the stdio streams are fully drained
28
+ // and destroyed, so every buffered line is delivered before `end()`.
29
+ child.on("close", (code, signal) => end(`server exited (code ${code}, signal ${signal})`));
30
+ child.on("error", (err) => end(err.message));
31
+ // A dead server pipe (EPIPE) must route through the close path — an
32
+ // unhandled stream 'error' would crash the consumer process instead.
33
+ stdin.on("error", (err) => end(`server stdin error: ${err.message}`));
34
+ child.stdout.on("error", (err) => end(`server stdout error: ${err.message}`));
35
+ return transport;
36
+ }
37
+ /**
38
+ * Dial a listening agent-server; resolves once the socket is open. `headers`
39
+ * go with the upgrade (Bun and Node; a browser's WebSocket sends none). A
40
+ * server that refuses the client rejects it with `ConnectionRefusedError`.
41
+ */
42
+ export function connectTransport(url, headers) {
43
+ return new Promise((resolve, reject) => {
44
+ const ws = headers ? new WebSocket(url, { headers }) : new WebSocket(url);
45
+ const { transport, push, end } = channelTransport({
46
+ send: (line) => void ws.send(line),
47
+ close: () => ws.close(),
48
+ });
49
+ let opened = false;
50
+ let failed = false;
51
+ const fail = () => {
52
+ end("socket closed");
53
+ if (opened || failed)
54
+ return;
55
+ failed = true;
56
+ void refusal(url, headers).then((refused) => reject(refused ?? new Error(`websocket connect failed: ${url}`)));
57
+ };
58
+ ws.addEventListener("open", () => {
59
+ opened = true;
60
+ resolve(transport);
61
+ });
62
+ ws.addEventListener("message", (ev) => pushNdjsonLines(push, ev.data));
63
+ ws.addEventListener("close", fail);
64
+ // Browsers and Bun follow an error with a close; Node's WebSocket
65
+ // reports a refused connection by the error alone, which would leave
66
+ // the dial (and a client redialing) waiting forever.
67
+ ws.addEventListener("error", () => {
68
+ if (!opened)
69
+ fail();
70
+ });
71
+ });
72
+ }
73
+ /** How long a failed dial waits to hear why. */
74
+ const REFUSAL_PROBE_MS = 2_000;
75
+ /**
76
+ * Why the server would not upgrade, when it refused this client. Neither
77
+ * Bun's WebSocket nor Node's tells a handshake's status, so one plain request
78
+ * with the same headers asks: `listen` answers it as it answered the upgrade,
79
+ * 401 for the token, and only then 426. Anything else, or no answer, is no
80
+ * refusal: no server yet, or a transient one. A 403 is none either: `listen`
81
+ * sends it only for an `Origin`, which a native client never sends, so it
82
+ * comes from something in front of the server (a proxy refusing plain
83
+ * requests), and the next dial may be answered.
84
+ */
85
+ async function refusal(url, headers) {
86
+ let status;
87
+ try {
88
+ // @ref LLP 0001#d16--a-listener-answers-native-clients-only-and-needs-a-token-beyond-loopback
89
+ // What the upgrade carried, without the upgrade; never redirected, so the token goes nowhere else.
90
+ const response = await fetch(url.replace(/^ws/, "http"), {
91
+ headers,
92
+ redirect: "manual",
93
+ signal: AbortSignal.timeout(REFUSAL_PROBE_MS),
94
+ });
95
+ status = response.status;
96
+ await response.body?.cancel().catch(() => undefined);
97
+ }
98
+ catch {
99
+ return undefined;
100
+ }
101
+ if (status !== 401)
102
+ return undefined;
103
+ const sent = Object.keys(headers ?? {}).some((name) => name.toLowerCase() === "authorization");
104
+ return new ConnectionRefusedError(sent ? "token_refused" : "token_required", url);
105
+ }
106
+ /**
107
+ * Wrap an already-accepted socket (echo's model: the sandboxed server dialed
108
+ * out to us and this is the accepted end).
109
+ */
110
+ export function socketTransport(socket) {
111
+ const { transport, push, end } = channelTransport({
112
+ send: (line) => socket.send(line),
113
+ close: () => socket.close(),
114
+ });
115
+ socket.addEventListener("message", (ev) => pushNdjsonLines(push, ev.data));
116
+ socket.addEventListener("close", () => end("socket closed"));
117
+ return transport;
118
+ }
@@ -0,0 +1,122 @@
1
+ import { AsyncQueue, isLiveEnvelope, isUnknownEvent, } from "../protocol/index.js";
2
+ /** One handle's view of its session, from its point through its turn's end. */
3
+ class Handle {
4
+ sessionId;
5
+ turnId;
6
+ own;
7
+ settled;
8
+ queue = new AsyncQueue();
9
+ result;
10
+ catchUp = 0;
11
+ point;
12
+ done = false;
13
+ /** Frames after the point, waiting for the catch-up before them. */
14
+ waiting;
15
+ resolve;
16
+ reject;
17
+ constructor(sessionId, turnId,
18
+ /** This client started the turn (`runTurn`), as opposed to joining it. */
19
+ own, settled) {
20
+ this.sessionId = sessionId;
21
+ this.turnId = turnId;
22
+ this.own = own;
23
+ this.settled = settled;
24
+ this.result = new Promise((resolve, reject) => {
25
+ this.resolve = resolve;
26
+ this.reject = reject;
27
+ });
28
+ // Consumers may only iterate `events`; don't surface an unhandled rejection.
29
+ this.result.catch(() => undefined);
30
+ }
31
+ /** A frame the client delivered for the session: the handle's if it is after its point. */
32
+ take(envelope, arrival) {
33
+ const point = this.point;
34
+ if (this.done || !point)
35
+ return;
36
+ const before = isLiveEnvelope(envelope)
37
+ ? arrival <= point.position
38
+ : envelope.seq <= point.headSeq;
39
+ if (before)
40
+ return;
41
+ if (this.waiting)
42
+ this.waiting.push(envelope.event);
43
+ else
44
+ this.push(envelope.event);
45
+ }
46
+ /** Hold what comes after the point until the catch-up before it is in. */
47
+ catchingUp() {
48
+ this.waiting ??= [];
49
+ }
50
+ /** The catch-up is in: it goes first, then what waited for it. */
51
+ caughtUp(replayed) {
52
+ const waiting = this.waiting ?? [];
53
+ this.waiting = undefined;
54
+ this.catchUp = replayed.length;
55
+ for (const event of [...replayed, ...waiting])
56
+ this.push(event);
57
+ }
58
+ push(event) {
59
+ if (this.done)
60
+ return;
61
+ this.queue.push(event);
62
+ if (!isUnknownEvent(event) && event.type === "turn.ended" && event.turnId === this.turnId)
63
+ this.end(event);
64
+ }
65
+ end(ended) {
66
+ if (this.done)
67
+ return;
68
+ this.done = true;
69
+ this.resolve(ended);
70
+ this.queue.end();
71
+ this.settled(this);
72
+ }
73
+ fail(error) {
74
+ if (this.done)
75
+ return;
76
+ this.done = true;
77
+ this.reject(error);
78
+ this.queue.fail(error);
79
+ this.settled(this);
80
+ }
81
+ }
82
+ /** The turn handles of a client, by session; a session may have several (`joinTurn`). */
83
+ export class Turns {
84
+ bySession = new Map();
85
+ /** A handle for a turn of the session: it takes frames once it `join`s a point. */
86
+ open(sessionId, turnId, own) {
87
+ const handle = new Handle(sessionId, turnId, own, (done) => this.close(done));
88
+ const handles = this.bySession.get(sessionId) ?? new Set();
89
+ handles.add(handle);
90
+ this.bySession.set(sessionId, handles);
91
+ return handle;
92
+ }
93
+ /** Whether this client runs a turn of the session (one at a time). */
94
+ running(sessionId) {
95
+ for (const handle of this.bySession.get(sessionId) ?? [])
96
+ if (handle.own)
97
+ return true;
98
+ return false;
99
+ }
100
+ sessions() {
101
+ return [...this.bySession.keys()];
102
+ }
103
+ /** A frame the client delivered: to each handle of its session. */
104
+ deliver(envelope, arrival) {
105
+ for (const handle of [...(this.bySession.get(envelope.sessionId) ?? [])])
106
+ handle.take(envelope, arrival);
107
+ }
108
+ fail(sessionId, error) {
109
+ for (const handle of [...(this.bySession.get(sessionId) ?? [])])
110
+ handle.fail(error);
111
+ }
112
+ failAll(error) {
113
+ for (const sessionId of this.sessions())
114
+ this.fail(sessionId, error);
115
+ }
116
+ close(handle) {
117
+ const handles = this.bySession.get(handle.sessionId);
118
+ handles?.delete(handle);
119
+ if (handles?.size === 0)
120
+ this.bySession.delete(handle.sessionId);
121
+ }
122
+ }