@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,686 @@
1
+ import { AuthUpdatedSchema, HarnessCliProgressSchema, SessionOverflowParamsSchema, WIRE_ERROR_CODES, WIRE_METHODS, decodeWireEventEnvelope, decodeWireMessage, generateUUIDv7, } from "../protocol/index.js";
2
+ import { Connection, ConnectionClosedError, ConnectionRefusedError, ProtocolVersionMismatchError, } from "./connection.js";
3
+ import { createHistoryClient } from "./history.js";
4
+ import { Listeners } from "./listeners.js";
5
+ import { startLogin } from "./logins.js";
6
+ import { WireRequestError } from "./rpc.js";
7
+ import { EventGapError, Streams } from "./streams.js";
8
+ import { connectTransport, socketTransport, spawnTransport, } from "./transports.js";
9
+ import { Turns } from "./turns.js";
10
+ export { ConnectionClosedError, ConnectionRefusedError, EventGapError, ProtocolVersionMismatchError, };
11
+ /** `signal` stops the handle following its turn. */
12
+ function stopOn(handle, signal) {
13
+ if (!signal)
14
+ return;
15
+ const stop = () => handle.fail(signal.reason ?? new Error("stopped following the turn"));
16
+ if (signal.aborted) {
17
+ stop();
18
+ return;
19
+ }
20
+ signal.addEventListener("abort", stop, { once: true });
21
+ const off = () => signal.removeEventListener("abort", stop);
22
+ void handle.result.then(off, off);
23
+ }
24
+ /** How often `prepareClis` asks again while an install runs, besides when one ends. */
25
+ const PREPARE_POLL_MS = 2_000;
26
+ /**
27
+ * Typed client for the agent-server wire. Turns are quick-ack: `runTurn`
28
+ * resolves once the server accepts the turn and hands back an async iterable
29
+ * of its events, from its `turn.started` to its `turn.ended`. The client
30
+ * follows the sessions it subscribed to (and its turns subscribe): each
31
+ * session's `seq` is tracked so duplicates are dropped and gaps healed via
32
+ * `events/replay`, and — in `connect` mode — a dropped socket is redialed and
33
+ * its sessions subscribed again.
34
+ */
35
+ export class AgentServerClient {
36
+ options;
37
+ connection;
38
+ turns = new Turns();
39
+ progress = new Listeners();
40
+ authUpdates = new Listeners();
41
+ streams;
42
+ /** `subscribeAll` calls whose ask no server has answered yet: across redials, the next answer settles them. */
43
+ allAsked = [];
44
+ /** Portable history operations (`history/*`), independent of execution subscriptions. */
45
+ history;
46
+ constructor(factory, options, redials, url) {
47
+ this.options = options;
48
+ this.connection = new Connection(factory, options, redials, {
49
+ line: (line, transport) => this.handleLine(line, transport),
50
+ opened: (redialed) => this.streams.reconnected(redialed),
51
+ serverChanged: () => this.streams.adoptFreshLogs(),
52
+ reconnected: () => {
53
+ this.streams.resume();
54
+ this.subscribeAgain();
55
+ },
56
+ closed: (error) => {
57
+ this.turns.failAll(error);
58
+ this.answeredAll(error);
59
+ },
60
+ }, url);
61
+ this.streams = new Streams({
62
+ transport: () => this.connection.transport,
63
+ open: () => !this.connection.closed,
64
+ replay: (sessionId, fromSeq) => this.replay(sessionId, fromSeq),
65
+ resubscribe: (sessionId, turnId) => void this.resubscribe(sessionId, turnId),
66
+ resubscribeAll: () => void this.requestAll(),
67
+ maxReplayAttempts: options.maxReplayAttempts ?? 3,
68
+ replayRetryDelayMs: options.replayRetryDelayMs ?? options.reconnectDelayMs ?? 250,
69
+ }, this.turns);
70
+ this.history = createHistoryClient((method, params) => this.connection.request(method, params), () => this.initialize(), options);
71
+ }
72
+ /**
73
+ * Bring your own transport: the factory is invoked for the initial
74
+ * connection and for every reconnect attempt (reconnect defaults to true).
75
+ */
76
+ static async fromTransportFactory(factory, options = {}) {
77
+ const client = new AgentServerClient(factory, options, options.reconnect ?? true);
78
+ await client.connection.open();
79
+ return client;
80
+ }
81
+ /** Spawn an agent-server subprocess and talk over its stdio. */
82
+ static async spawn(spawnOpts, options = {}) {
83
+ const client = new AgentServerClient(() => spawnTransport(spawnOpts), options, options.reconnect ?? false);
84
+ await client.connection.open();
85
+ return client;
86
+ }
87
+ /**
88
+ * Dial a listening agent-server (reconnects by default). One that refuses
89
+ * the client (401: the token it sent, or that it sent none) fails it with
90
+ * `ConnectionRefusedError`, and is not redialed.
91
+ */
92
+ static async connect(url, options = {}) {
93
+ const headers = options.token === undefined ? undefined : { authorization: `Bearer ${options.token}` };
94
+ const client = new AgentServerClient(() => connectTransport(url, headers), options, options.reconnect ?? true, url);
95
+ await client.connection.open();
96
+ return client;
97
+ }
98
+ /** Wrap an already-connected socket (e.g. the accepted end of a dial-out). */
99
+ static async attach(socket, options = {}) {
100
+ const transport = "onLine" in socket ? socket : socketTransport(socket);
101
+ let used = false;
102
+ const client = new AgentServerClient(() => {
103
+ if (used)
104
+ throw new ConnectionClosedError("attached socket cannot be re-opened");
105
+ used = true;
106
+ return transport;
107
+ }, options, false);
108
+ await client.connection.open();
109
+ return client;
110
+ }
111
+ // ---- turns ---------------------------------------------------------------
112
+ /** Handshake (memoized). Called lazily by `runTurn`/`startTurn`. */
113
+ initialize() {
114
+ return this.connection.initialize();
115
+ }
116
+ /**
117
+ * Start a turn and stream it, from its `turn.started` to its `turn.ended`.
118
+ * Ids are minted client-side when omitted. The start subscribes this client
119
+ * to the session from its head until the turn ends, so it downloads none
120
+ * of its history; a start re-sent after a redial converges on the turn the
121
+ * server admitted and catches up on it from its `turn.started`. `signal`
122
+ * stops the handle, as on `joinTurn`: the turn runs on (`cancelTurn` stops
123
+ * it), and `onEvent` hears it to its end.
124
+ */
125
+ async runTurn(params, options = {}) {
126
+ await this.initialize();
127
+ const sessionId = params.sessionId ?? generateUUIDv7();
128
+ const turnId = params.turnId ?? generateUUIDv7();
129
+ if (this.turns.running(sessionId))
130
+ throw new Error(`session ${sessionId} already has an active turn`);
131
+ const handle = this.turns.open(sessionId, turnId, true);
132
+ stopOn(handle, options.signal);
133
+ try {
134
+ const accepted = await this.connection.resend(WIRE_METHODS.turnStart, { ...params, sessionId, turnId, subscribe: true },
135
+ // A turn that already ended streams nothing: its end is in the ack.
136
+ (ack) => {
137
+ if (!ack.terminal)
138
+ this.joinAt(handle, ack.headSeq, { turnId });
139
+ });
140
+ const { terminal } = accepted;
141
+ if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
142
+ throw new Error("Turn receipt belongs to a different request");
143
+ // A retried start of a turn that already ended: its end, without its events
144
+ // (`replay` or `history` serve its transcript).
145
+ if (terminal)
146
+ handle.push(terminal);
147
+ else
148
+ await this.catchUp(handle, accepted.deduplicated
149
+ ? (accepted.startedSeq ?? accepted.headSeq + 1)
150
+ : accepted.headSeq + 1, accepted.headSeq);
151
+ }
152
+ catch (error) {
153
+ handle.fail(error);
154
+ throw error;
155
+ }
156
+ return this.handleOf(handle);
157
+ }
158
+ /**
159
+ * Quick-ack only: the turn's events reach `onEvent` through its
160
+ * `turn.ended` (unless `subscribe: false`), and `replay` serves what came
161
+ * before.
162
+ */
163
+ async startTurn(params) {
164
+ await this.initialize();
165
+ const sessionId = params.sessionId ?? generateUUIDv7();
166
+ const turnId = params.turnId ?? generateUUIDv7();
167
+ return this.connection.request(WIRE_METHODS.turnStart, { ...params, sessionId, turnId }, (ack) => {
168
+ if (params.subscribe !== false && !ack.terminal)
169
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
170
+ });
171
+ }
172
+ /**
173
+ * Join the turn running in `sessionId`. Yields, each once and in seq
174
+ * order: the session's kept events from `fromSeq` (default: the turn's
175
+ * `turn.started`), the turn's open parts as of the join, then live frames
176
+ * through the turn's `turn.ended` — so even when this client already
177
+ * follows the session or another handle joined earlier. Resolves once the
178
+ * catch-up is replayed (`catchUp` counts it); `undefined` when no turn is
179
+ * running. `steer` and `result` work as on `runTurn`'s handle. Joining
180
+ * watches the session (`subscribe`).
181
+ */
182
+ async joinTurn(sessionId, options = {}) {
183
+ await this.initialize();
184
+ let handle;
185
+ const answer = await this.subscribeTo({ sessionId }, (ack) => {
186
+ if (!ack.activeTurn)
187
+ return this.streams.joined(sessionId, ack.headSeq, "watch");
188
+ handle = this.turns.open(sessionId, ack.activeTurn.turnId, false);
189
+ this.joinAt(handle, ack.headSeq, "watch");
190
+ });
191
+ if (!handle)
192
+ return undefined;
193
+ stopOn(handle, options.signal);
194
+ const fromSeq = options.fromSeq ?? answer.activeTurn?.startedSeq ?? answer.headSeq + 1;
195
+ await this.catchUp(handle, fromSeq, answer.headSeq);
196
+ return this.handleOf(handle);
197
+ }
198
+ // @ref LLP 0001#d13--input-while-a-turn-runs-steers-it — the client half
199
+ /**
200
+ * Add input to a running turn. The agent reads it at its next step, where
201
+ * the turn's stream shows it as a user message (`steerMessageId(steerId)`);
202
+ * a turn that ends first lists it in `turn.ended.undeliveredSteers`.
203
+ * `no_active_turn` means the turn takes no more input — send it as a new
204
+ * turn; `unsupported` means the harness cannot steer. `steerId` is minted
205
+ * when omitted; a re-send with the same one converges, so a steer whose
206
+ * answer was lost to a reconnect is re-sent, never doubled. A session this
207
+ * client does not follow is followed first, until the turn ends, so the
208
+ * steer's user message, its receipt, reaches it.
209
+ */
210
+ async steerTurn(params) {
211
+ await this.initialize();
212
+ const { sessionId, turnId } = params;
213
+ // One it cannot subscribe to still takes the steer; only its receipt is lost.
214
+ if (!this.streams.follows(sessionId))
215
+ await this.subscribeTo({ sessionId, turnId }, (ack) => {
216
+ // A turn that is not running subscribes nothing, and is not followed.
217
+ if (ack.activeTurn?.turnId === turnId)
218
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
219
+ }).catch(() => undefined);
220
+ return this.connection.resend(WIRE_METHODS.turnSteer, {
221
+ ...params,
222
+ steerId: params.steerId ?? generateUUIDv7(),
223
+ });
224
+ }
225
+ /**
226
+ * Cancel the session's active turn; resolves once cancellation propagated.
227
+ * Pass `turnId` to make the cancel turn-stamped: a late cancel meant for a
228
+ * finished turn then returns `{outcome: "no_active_turn", activeTurnId}`
229
+ * instead of killing the turn that replaced it. `{outcome: "unconfirmed"}`
230
+ * means the harness did not acknowledge the interrupt — the agent may still
231
+ * be running; `turn.ended` remains the source of truth.
232
+ */
233
+ cancelTurn(sessionId, turnId) {
234
+ return this.connection.request(WIRE_METHODS.turnCancel, {
235
+ sessionId,
236
+ ...(turnId !== undefined ? { turnId } : {}),
237
+ });
238
+ }
239
+ /** Answer a `permission.requested` event. */
240
+ async respondPermission(sessionId, requestId, outcome) {
241
+ const { accepted } = await this.connection.request(WIRE_METHODS.permissionRespond, {
242
+ sessionId,
243
+ requestId,
244
+ outcome,
245
+ });
246
+ return accepted;
247
+ }
248
+ /** Answer an `elicitation.requested` event. */
249
+ async respondElicitation(sessionId, requestId, outcome) {
250
+ const { accepted } = await this.connection.request(WIRE_METHODS.elicitationRespond, {
251
+ sessionId,
252
+ requestId,
253
+ outcome,
254
+ });
255
+ return accepted;
256
+ }
257
+ // ---- sessions ------------------------------------------------------------
258
+ /**
259
+ * Watch a session until `unsubscribe` (or its end): its kept events after
260
+ * `afterSeq` reach `onEvent` (and the session's handles), each once and in
261
+ * order, then its open parts, then its frames live; after a redial, what a
262
+ * dropped connection missed. Refused `unknownSession` when the server has
263
+ * no log for it, and `subscriptionLimit` past the sessions a connection may
264
+ * watch.
265
+ */
266
+ async subscribe(sessionId, options = {}) {
267
+ await this.initialize();
268
+ // What it holds, or `afterSeq`, it catches up from with `events/replay`.
269
+ const answer = await this.subscribeTo({ sessionId }, (ack) => this.streams.joined(sessionId, ack.headSeq, "watch", options.afterSeq));
270
+ return {
271
+ sessionId,
272
+ headSeq: answer.headSeq,
273
+ ...(answer.activeTurn && { activeTurn: answer.activeTurn }),
274
+ };
275
+ }
276
+ /**
277
+ * Stop watching a session; `false` when this client did not. A turn of
278
+ * this client's that runs there is still followed to its end.
279
+ */
280
+ async unsubscribe(sessionId) {
281
+ const watched = this.streams.watches(sessionId);
282
+ this.streams.unwatch(sessionId);
283
+ const { unsubscribed } = await this.connection.request(WIRE_METHODS.sessionUnsubscribe, {
284
+ sessionId,
285
+ });
286
+ return unsubscribed || watched;
287
+ }
288
+ /**
289
+ * Every session's frames, live from now, to `onEvent` (observers): no
290
+ * history, the open parts of running turns, and after a redial, the gaps a
291
+ * dropped connection left healed. The client follows every session from
292
+ * the ask until `unsubscribeAll`: a connection that drops before the
293
+ * answer asks the server it redials, whose answer this waits for; it fails
294
+ * when the server refuses it or the client closes.
295
+ */
296
+ async subscribeAll() {
297
+ // @ref LLP 0008#what-requests-do-to-subscriptions — the intent is recorded at the ask, so every later server is asked
298
+ this.streams.followAll();
299
+ const answered = new Promise((resolve, reject) => this.allAsked.push({ resolve, reject }));
300
+ try {
301
+ await this.initialize();
302
+ }
303
+ catch (error) {
304
+ // A dropped connection: its redial asks every session (`subscribeAgain`).
305
+ if (!this.redialing(error))
306
+ this.answeredAll(error);
307
+ return answered;
308
+ }
309
+ void this.requestAll();
310
+ return answered;
311
+ }
312
+ /** Stop following every session (`subscribeAll`); those subscribed by name stay. */
313
+ async unsubscribeAll() {
314
+ this.streams.unfollowAll();
315
+ this.answeredAll();
316
+ const { unsubscribed } = await this.connection.request(WIRE_METHODS.sessionUnsubscribeAll, {});
317
+ return unsubscribed;
318
+ }
319
+ /** Release an idle session's replay history and harness-native resources. */
320
+ async closeSession(sessionId) {
321
+ if (this.turns.running(sessionId))
322
+ throw new Error(`cannot close session ${sessionId} while its turn is active`);
323
+ const { closed } = await this.connection.request(WIRE_METHODS.sessionClose, { sessionId });
324
+ this.streams.forget(sessionId);
325
+ return closed;
326
+ }
327
+ /**
328
+ * Durable servers: let an idle session's agent go (its process, a Codex
329
+ * home it holds) while the session stays open, as after a restart. Its
330
+ * next turn names its native conversation (`config.resumeSessionId`; a turn
331
+ * that does not is refused `resumeRequired`, whose data names it), also a
332
+ * turn another client of the session sends: nothing tells it of the
333
+ * release. `false` when the server holds no open session by that id.
334
+ */
335
+ async releaseSession(sessionId) {
336
+ await this.initialize();
337
+ const { released } = await this.connection.request(WIRE_METHODS.sessionRelease, {
338
+ sessionId,
339
+ });
340
+ return released;
341
+ }
342
+ /**
343
+ * The models a harness offers for the login and folder a turn with the same
344
+ * `cwd`, `env` and `apiKey` would use. `source: "catalog"` (with `error`)
345
+ * means the CLI did not answer and the list is agent-server's built-in one,
346
+ * as it is while the harness's CLI is not installed yet: a read installs
347
+ * nothing (`prepareClis` does), and the first list after the install is live.
348
+ */
349
+ listModels(params) {
350
+ return this.connection.request(WIRE_METHODS.modelsList, params);
351
+ }
352
+ /**
353
+ * Where each harness's CLI is on the server (every harness when absent):
354
+ * `ready`, `missing` (what its first turn installs), `installing`,
355
+ * `failed` (with `error`) or `unmanaged`. Installs nothing.
356
+ */
357
+ async listClis(harnesses) {
358
+ await this.initialize();
359
+ const { clis } = await this.connection.request(WIRE_METHODS.clisList, {
360
+ ...(harnesses && { harnesses }),
361
+ });
362
+ return clis;
363
+ }
364
+ /**
365
+ * Install each harness's CLI on the server now, so a first turn does not
366
+ * wait for it, and answer once each is ready or failed. The server answers
367
+ * `clis/prepare` at once, since an install outlasts a request's timeout;
368
+ * this waits for `clis/progress` to say an install ended, asking
369
+ * `clis/list` then and every few seconds, across a redial to the same
370
+ * server. Safe to call again: a running install is joined. `signal` stops
371
+ * the waiting, not the install.
372
+ */
373
+ async prepareClis(harnesses, options = {}) {
374
+ const { signal } = options;
375
+ signal?.throwIfAborted();
376
+ // Before the first request: a redial asks again only of the server it knows.
377
+ await this.initialize();
378
+ const which = { ...(harnesses && { harnesses }) };
379
+ let wake = () => { };
380
+ const off = this.progress.add(({ phase }) => {
381
+ if (phase === "ready" || phase === "failed")
382
+ wake();
383
+ });
384
+ /** `work`, or the signal's reason once it aborts. */
385
+ const unlessAborted = (work) => {
386
+ if (!signal)
387
+ return work(new Promise(() => { }));
388
+ let stop = () => { };
389
+ const aborted = new Promise((_, reject) => {
390
+ stop = () => reject(signal.reason);
391
+ signal.addEventListener("abort", stop, { once: true });
392
+ });
393
+ return work(aborted).finally(() => signal.removeEventListener("abort", stop));
394
+ };
395
+ try {
396
+ let { clis } = await unlessAborted((aborted) => Promise.race([this.connection.resend(WIRE_METHODS.clisPrepare, which), aborted]));
397
+ while (clis.some((cli) => cli.state === "installing")) {
398
+ ({ clis } = await unlessAborted(async (aborted) => {
399
+ let timer;
400
+ try {
401
+ await Promise.race([
402
+ new Promise((resolve) => {
403
+ timer = setTimeout(resolve, PREPARE_POLL_MS);
404
+ wake = resolve;
405
+ }),
406
+ aborted,
407
+ ]);
408
+ }
409
+ finally {
410
+ clearTimeout(timer);
411
+ }
412
+ return Promise.race([this.connection.resend(WIRE_METHODS.clisList, which), aborted]);
413
+ }));
414
+ }
415
+ return clis;
416
+ }
417
+ finally {
418
+ off();
419
+ }
420
+ }
421
+ /** Fetch kept events (`seq >= fromSeq`) without touching what the client follows.
422
+ * A durable server answers a page at a time: `hasMore` asks for the next. */
423
+ replay(sessionId, fromSeq) {
424
+ return this.connection.request(WIRE_METHODS.eventsReplay, { sessionId, fromSeq });
425
+ }
426
+ /**
427
+ * The session's kept events from `fromSeq` through `throughSeq` (default:
428
+ * the last), oldest first: every page `replay` answers. Fails
429
+ * `EventGapError` when some of them were evicted.
430
+ */
431
+ async replayAll(sessionId, fromSeq, throughSeq = Number.POSITIVE_INFINITY) {
432
+ const kept = [];
433
+ for (let from = fromSeq; from <= throughSeq;) {
434
+ const page = await this.replay(sessionId, from);
435
+ if (page.firstAvailableSeq !== null && page.firstAvailableSeq > from)
436
+ throw new EventGapError(`events ${from}..${page.firstAvailableSeq - 1} for session ${sessionId} were evicted`);
437
+ for (const envelope of page.events)
438
+ if (envelope.seq >= from && envelope.seq <= throughSeq)
439
+ kept.push(envelope);
440
+ const last = page.events.at(-1)?.seq;
441
+ if (!page.hasMore || last === undefined || last >= throughSeq)
442
+ break;
443
+ from = last + 1;
444
+ }
445
+ return kept;
446
+ }
447
+ /** Durable servers: a turn's receipt, even for a turn a restart cut off. */
448
+ async getTurn(sessionId, turnId) {
449
+ await this.initialize();
450
+ return this.connection.request(WIRE_METHODS.turnGet, { sessionId, turnId });
451
+ }
452
+ /** Durable servers: the session's head, native id, and whether a restart cut off its last turn. */
453
+ async getSession(sessionId) {
454
+ await this.initialize();
455
+ return this.connection.request(WIRE_METHODS.sessionGet, { sessionId });
456
+ }
457
+ /** Durable servers: lift the fence a restart put on a session. Check first
458
+ * that its native execution stopped: history alone cannot prove that a
459
+ * detached agent or tool process is dead. */
460
+ async confirmSessionStopped(params) {
461
+ await this.initialize();
462
+ const { recovered } = await this.connection.request(WIRE_METHODS.sessionConfirmStopped, params);
463
+ return recovered;
464
+ }
465
+ // ---- logins ----------------------------------------------------------------
466
+ /**
467
+ * Each harness's login on the server (every harness when `harnesses` is
468
+ * absent), for the store and environment a turn with `env` would use:
469
+ * signed in, with what and as whom, signed out, or unknown and why; the
470
+ * logins it offers; and the login under way to that store
471
+ * (`loginUnderWay`), whoever started it, so a second window or a handle
472
+ * whose connection dropped finds it. A read installs nothing: a harness
473
+ * whose CLI is not installed yet is `unknown` with no methods
474
+ * (`prepareClis` installs it, as `login` does).
475
+ */
476
+ async authStatus(options = {}) {
477
+ await this.initialize();
478
+ const { auth } = await this.connection.request(WIRE_METHODS.authStatus, options);
479
+ return auth;
480
+ }
481
+ /**
482
+ * Start one of a harness's logins through its CLI's own flow: answered
483
+ * once the CLI says where the user signs in (`url`, `userCode`, or from
484
+ * another device `codeUrl`, then `complete` with the code it shows).
485
+ * `done` resolves with the harness's login once it succeeded. Every
486
+ * connection hears it start (`onAuthUpdated`, `auth.loginUnderWay`), and
487
+ * a newer login to the same store cancels it. It installs the harness's
488
+ * CLI first when it is not there yet, inside the 20 s the CLI has to
489
+ * start the login: on a slow network, `prepareClis` first.
490
+ */
491
+ async login(harness, method, options = {}) {
492
+ await this.initialize();
493
+ return startLogin({
494
+ updates: this.authUpdates,
495
+ connection: this.connection.events,
496
+ complete: (loginId, code) => this.connection.request(WIRE_METHODS.authComplete, { loginId, code }),
497
+ cancel: (loginId) => this.connection.request(WIRE_METHODS.authCancel, { loginId }),
498
+ }, () => this.connection.request(WIRE_METHODS.authLogin, { harness, method, ...options }));
499
+ }
500
+ /** Remove a harness's CLI login on the server; answers its login after. */
501
+ async logout(harness, options = {}) {
502
+ await this.initialize();
503
+ return this.connection.request(WIRE_METHODS.authLogout, { harness, ...options });
504
+ }
505
+ // ---- observing -----------------------------------------------------------
506
+ /** The frames of the sessions this client follows, each once and in order (post-dedupe). */
507
+ onEvent(handler) {
508
+ return this.streams.events.add(handler);
509
+ }
510
+ /** A harness's CLI being installed on the server, whatever caused it (`clis/progress`). */
511
+ onCliProgress(handler) {
512
+ return this.progress.add(handler);
513
+ }
514
+ /**
515
+ * A harness's login changed on the server, a login started (no `login`;
516
+ * `auth.loginUnderWay` is it), or a login ended (`login`), whoever caused
517
+ * it (`auth/updated`). Every update's `auth` carries the login then under
518
+ * way to that harness, if any.
519
+ */
520
+ onAuthUpdated(handler) {
521
+ return this.authUpdates.add(handler);
522
+ }
523
+ /** Observe unrecoverable delivery gaps even when using startTurn without a handle. */
524
+ onEventGap(handler) {
525
+ return this.streams.gaps.add(handler);
526
+ }
527
+ /**
528
+ * Observe the connection: a drop, each redial attempt, the reconnect (and
529
+ * whether the server is still the one whose logs this client followed),
530
+ * and the end. Handlers run synchronously, before requests waiting on the
531
+ * redial are sent again; one that throws is ignored.
532
+ */
533
+ onConnection(handler) {
534
+ return this.connection.events.add(handler);
535
+ }
536
+ /** Ask the server to shut down, then close this client. */
537
+ async shutdownServer() {
538
+ await this.connection.request(WIRE_METHODS.shutdown, {}).catch(() => undefined);
539
+ await this.close();
540
+ }
541
+ async close() {
542
+ this.connection.close();
543
+ }
544
+ // ---- internals -------------------------------------------------------------
545
+ handleLine(line, transport) {
546
+ const message = decodeWireMessage(line);
547
+ if (message.kind === "response") {
548
+ this.connection.rpc.settle(message);
549
+ return;
550
+ }
551
+ if (message.kind !== "notification")
552
+ return;
553
+ if (message.method === WIRE_METHODS.event) {
554
+ try {
555
+ // An unknown event TYPE is preserved and still advances seq. Only a
556
+ // malformed envelope or a malformed KNOWN event lands in the catch —
557
+ // a server bug, which must not be papered over by advancing past it.
558
+ this.streams.accept(decodeWireEventEnvelope(message.params), transport);
559
+ }
560
+ catch {
561
+ // undeliverable; the next event's seq gap raises it honestly
562
+ }
563
+ }
564
+ else if (message.method === WIRE_METHODS.sessionOverflow) {
565
+ const notice = SessionOverflowParamsSchema.safeParse(message.params);
566
+ if (notice.success)
567
+ this.streams.overflowed(notice.data);
568
+ }
569
+ else if (message.method === WIRE_METHODS.clisProgress) {
570
+ const progress = HarnessCliProgressSchema.safeParse(message.params);
571
+ if (progress.success)
572
+ this.progress.emit(progress.data);
573
+ }
574
+ else if (message.method === WIRE_METHODS.authUpdated) {
575
+ const update = AuthUpdatedSchema.safeParse(message.params);
576
+ if (update.success)
577
+ this.authUpdates.emit(update.data);
578
+ }
579
+ }
580
+ /**
581
+ * A start or join's answer, the moment it arrives: the handle's point
582
+ * among the frames. What follows the point waits for the catch-up before it.
583
+ */
584
+ joinAt(handle, headSeq, follow) {
585
+ this.streams.joined(handle.sessionId, headSeq, follow);
586
+ handle.point = { headSeq, position: this.streams.position };
587
+ handle.catchingUp();
588
+ }
589
+ /** The kept events from `fromSeq` through `headSeq`, replayed into the handle before what followed its point. */
590
+ async catchUp(handle, fromSeq, headSeq) {
591
+ let replayed;
592
+ try {
593
+ replayed = await this.replayAll(handle.sessionId, fromSeq, headSeq);
594
+ }
595
+ catch (error) {
596
+ handle.fail(error instanceof WireRequestError && error.code === WIRE_ERROR_CODES.unknownSession
597
+ ? new EventGapError(`session ${handle.sessionId} is unknown to the server (restarted?)`)
598
+ : error);
599
+ throw error;
600
+ }
601
+ handle.caughtUp(replayed.map((envelope) => envelope.event));
602
+ }
603
+ handleOf(handle) {
604
+ const { sessionId, turnId } = handle;
605
+ return {
606
+ sessionId,
607
+ turnId,
608
+ events: handle.queue,
609
+ result: handle.result,
610
+ get catchUp() {
611
+ return handle.catchUp;
612
+ },
613
+ steer: (input, steerId) => this.steerTurn({ sessionId, turnId, input, ...(steerId !== undefined && { steerId }) }),
614
+ };
615
+ }
616
+ /**
617
+ * Subscribe to the session again (a redial, an overflow), for the turn of
618
+ * this client's it runs or, without one, watching it; what it missed heals
619
+ * by replay. A turn the answer says runs no more ended by its `headSeq`:
620
+ * the session is followed through there, then let go. A refusal is the
621
+ * server's answer: the session is followed no more.
622
+ */
623
+ async resubscribe(sessionId, turnId) {
624
+ try {
625
+ await this.subscribeTo({ sessionId, ...(turnId !== undefined && { turnId }) }, (ack) => {
626
+ if (turnId === undefined)
627
+ this.streams.joined(sessionId, ack.headSeq, "watch");
628
+ else if (ack.activeTurn?.turnId === turnId)
629
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
630
+ // @ref LLP 0008#client-api — followed through the head, then let go
631
+ else
632
+ this.streams.turnEnded(sessionId, turnId, ack.headSeq);
633
+ });
634
+ }
635
+ catch (error) {
636
+ // Any other failure: a dropped connection subscribes again once redialed.
637
+ if (!(error instanceof WireRequestError))
638
+ return;
639
+ if (error.code === WIRE_ERROR_CODES.unknownSession)
640
+ this.streams.missing(sessionId);
641
+ else
642
+ this.streams.refused(sessionId, error.message);
643
+ }
644
+ }
645
+ /** A failure a redial heals: the connection dropped and will be redialed, which subscribes again. */
646
+ redialing(error) {
647
+ return (error instanceof ConnectionClosedError && this.connection.redials && !this.connection.closed);
648
+ }
649
+ /** Settle the `subscribeAll` calls waiting for an answer: answered, or failed with `error`. */
650
+ answeredAll(error) {
651
+ for (const waiter of this.allAsked.splice(0))
652
+ if (error === undefined)
653
+ waiter.resolve();
654
+ else
655
+ waiter.reject(error);
656
+ }
657
+ // @ref LLP 0008#what-requests-do-to-subscriptions — a redial subscribes the running turns first
658
+ /** After a redial: every session followed, from what the client holds, pipelined. */
659
+ subscribeAgain() {
660
+ for (const { sessionId, turnId } of this.streams.resubscriptions())
661
+ void this.resubscribe(sessionId, turnId);
662
+ if (this.streams.followsAll)
663
+ void this.requestAll();
664
+ }
665
+ /**
666
+ * `session/subscribeAll`, sent now; its answer settles the `subscribeAll`
667
+ * calls waiting. Refused, the client follows every session no more; dropped,
668
+ * the redial asks again.
669
+ */
670
+ async requestAll() {
671
+ try {
672
+ await this.connection.request(WIRE_METHODS.sessionSubscribeAll, {}, ({ sessions }) => this.streams.joinedAll(sessions));
673
+ this.answeredAll();
674
+ }
675
+ catch (error) {
676
+ if (error instanceof WireRequestError)
677
+ this.streams.refusedAll(error.message);
678
+ if (!this.redialing(error))
679
+ this.answeredAll(error);
680
+ }
681
+ }
682
+ /** `session/subscribe` for one session, `onAnswer` given its point the moment it arrives. */
683
+ subscribeTo(params, onAnswer) {
684
+ return this.connection.request(WIRE_METHODS.sessionSubscribe, params, onAnswer);
685
+ }
686
+ }