@zvada/agent-server 0.3.23 → 0.3.25

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 (280) hide show
  1. package/CHANGELOG.md +64 -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 +745 -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 +331 -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 +92 -0
  91. package/dist/core/processes/lifeline.js +218 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +164 -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 +29 -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 +437 -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 +339 -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 +142 -0
  141. package/dist/protocol/errors.js +190 -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 +292 -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/client/client.d.ts +6 -1
  207. package/dist/types/client/client.d.ts.map +1 -1
  208. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  210. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/options.d.ts +28 -11
  212. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  213. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  214. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  216. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  218. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  219. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  220. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  221. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  222. package/dist/types/core/agents/process-pool.d.ts +8 -0
  223. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  224. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  225. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  226. package/dist/types/core/presets.d.ts +2 -2
  227. package/dist/types/core/presets.d.ts.map +1 -1
  228. package/dist/types/core/processes/identity.d.ts.map +1 -1
  229. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  230. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  231. package/dist/types/core/provision/extract.d.ts.map +1 -1
  232. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  233. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  234. package/dist/types/core/runtime/turn.d.ts +12 -7
  235. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  236. package/dist/types/protocol/clis.d.ts +3 -3
  237. package/dist/types/protocol/conversation.d.ts +6 -6
  238. package/dist/types/protocol/credentials.d.ts +13 -1
  239. package/dist/types/protocol/credentials.d.ts.map +1 -1
  240. package/dist/types/protocol/errors.d.ts +6 -4
  241. package/dist/types/protocol/errors.d.ts.map +1 -1
  242. package/dist/types/protocol/lifecycle.d.ts +4 -4
  243. package/dist/types/protocol/wire-api.d.ts +12 -12
  244. package/dist/types/protocol/wire.d.ts +8 -8
  245. package/dist/types/server/bin.d.ts +3 -0
  246. package/dist/types/server/bin.d.ts.map +1 -0
  247. package/dist/types/server/routes.d.ts.map +1 -1
  248. package/dist/types/server/transports.d.ts +2 -1
  249. package/dist/types/server/transports.d.ts.map +1 -1
  250. package/dist/types/sync/node-sqlite.d.ts +4 -1
  251. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  252. package/docs/consuming.md +56 -7
  253. package/docs/deploy.md +35 -0
  254. package/docs/harnesses.md +30 -5
  255. package/package.json +43 -18
  256. package/src/client/client.ts +114 -44
  257. package/src/core/agents/claude-code/approvals.ts +5 -1
  258. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  259. package/src/core/agents/claude-code/options.ts +28 -11
  260. package/src/core/agents/claude-code/session.ts +13 -0
  261. package/src/core/agents/codex-app-server/homes.ts +11 -2
  262. package/src/core/agents/codex-app-server/login.ts +30 -0
  263. package/src/core/agents/codex-app-server/requests.ts +7 -6
  264. package/src/core/agents/codex-app-server/session.ts +11 -2
  265. package/src/core/agents/process-pool.ts +30 -4
  266. package/src/core/agents/scripted/scripted-agent.ts +2 -1
  267. package/src/core/agents/scripted/steps.ts +1 -1
  268. package/src/core/presets.ts +3 -2
  269. package/src/core/processes/identity.ts +1 -0
  270. package/src/core/processes/lifeline.ts +10 -1
  271. package/src/core/processes/process-table.ts +1 -0
  272. package/src/core/provision/extract.ts +1 -0
  273. package/src/core/runtime/agent-runtime.ts +6 -3
  274. package/src/core/runtime/turn.ts +21 -9
  275. package/src/protocol/credentials.ts +19 -5
  276. package/src/protocol/errors.ts +12 -3
  277. package/src/server/bin.ts +25 -10
  278. package/src/server/routes.ts +3 -2
  279. package/src/server/transports.ts +6 -1
  280. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,669 @@
1
+ import { z } from "zod";
2
+ import { RunConfigSchema } from "./config.js";
3
+ import { AgentCapabilitiesSchema, AgentHarnessSchema } from "./harness.js";
4
+ import { ElicitationOutcomeSchema, LifecycleEventSchema, PermissionOutcomeSchema, TurnEndedEventSchema, decodeLifecycleEvent, } from "./lifecycle.js";
5
+ import { ModelListSchema } from "./models.js";
6
+ import { AgentInputSchema } from "./part-input.js";
7
+ /**
8
+ * The standard wire: JSON-RPC 2.0 over a newline-delimited JSON
9
+ * stream (stdio, WebSocket, or any duplex byte channel). Requests flow
10
+ * client -> server only; the server pushes `event` notifications. Turns are
11
+ * quick-ack: `turn/start` acknowledges immediately and completion is observed
12
+ * via the `turn.ended` lifecycle event, mirroring the engine's event-driven
13
+ * model (and ACP v2's prompt lifecycle).
14
+ *
15
+ * Version 3: a `message.part.delta` is no longer sequenced. It carries the
16
+ * `seq` of the session's last kept event, and replay and history never return
17
+ * it (see `MessagePartDeltaEventSchema`).
18
+ *
19
+ * Version 4: one vocabulary — snake_case values (`in_session`), `history/read`,
20
+ * `unknownTurn`.
21
+ *
22
+ * Version 5: a connection receives the sessions it subscribes to
23
+ * (`session/subscribe`; `turn/start` subscribes its caller), and a frame the
24
+ * server does not keep says so (`live: true`): token deltas, and the open
25
+ * parts that follow a subscription. The engine no longer checkpoints a
26
+ * streaming part. A peer of another version is refused at `initialize`, never
27
+ * half served by values it cannot read.
28
+ *
29
+ * Version 6: a connection watches a session (`session/subscribe {sessionId}`)
30
+ * or follows one of its running turns (`turn/start`, `session/subscribe
31
+ * {sessionId, turnId}`), and a turn's subscription ends with the turn.
32
+ * `session/subscribe` takes no `afterSeq`: a client catches up with
33
+ * `events/replay`. Every session is `session/subscribeAll` and
34
+ * `session/unsubscribeAll`, each with its own answer, not `{all: true}`.
35
+ */
36
+ export const WIRE_PROTOCOL_VERSION = 6;
37
+ // ---- JSON-RPC 2.0 envelopes --------------------------------------------------
38
+ export const JsonRpcIdSchema = z.union([z.string(), z.number()]);
39
+ export const JsonRpcErrorSchema = z.object({
40
+ code: z.number().int(),
41
+ message: z.string(),
42
+ data: z.unknown().optional(),
43
+ });
44
+ /** JSON-RPC error codes used on this wire (standard + implementation range). */
45
+ export const WIRE_ERROR_CODES = {
46
+ parseError: -32700,
47
+ invalidRequest: -32600,
48
+ methodNotFound: -32601,
49
+ invalidParams: -32602,
50
+ internalError: -32603,
51
+ /** `config.harness` is not registered/available in this server process. */
52
+ harnessNotAvailable: -32000,
53
+ /** The sessionId is unknown to this server process (e.g. it restarted). */
54
+ unknownSession: -32001,
55
+ /** The session already has an active turn — one turn per session at a time. */
56
+ turnActive: -32002,
57
+ /** The server is shutting down and no longer accepts turns. */
58
+ shuttingDown: -32003,
59
+ /** The peer requested a wire version this implementation cannot speak. */
60
+ protocolVersionMismatch: -32004,
61
+ /** A session/close for this session is still in flight; retry after it settles. */
62
+ sessionClosing: -32005,
63
+ /**
64
+ * A turn with this turnId already ran (or is running) with DIFFERENT input,
65
+ * or a steerId was reused with different input or in another turn.
66
+ */
67
+ turnConflict: -32006,
68
+ /** A durable session was closed; its id is not reused. */
69
+ sessionClosed: -32007,
70
+ /**
71
+ * A server restart cut off the session's last turn and could not confirm
72
+ * its native process stopped (`data.reason`, a `RecoveryReason`). Check it
73
+ * stopped, then confirm (`session/confirmStopped` with `data.headSeq`)
74
+ * before starting another turn.
75
+ */
76
+ recoveryRequired: -32008,
77
+ /**
78
+ * This server process has not run the durable session yet: pass its
79
+ * `data.nativeSessionId` as `config.resumeSessionId`, or use a new session.
80
+ */
81
+ resumeRequired: -32009,
82
+ /** The host refused this caller the history operation. */
83
+ notAuthorized: -32010,
84
+ /** No such history, or it does not hold the requested version. */
85
+ unknownHistory: -32011,
86
+ /** The request contradicts committed history (payload, hash, expected head or commit id). */
87
+ historyConflict: -32012,
88
+ /** The session is known, but no turn with this turnId was admitted to it. */
89
+ unknownTurn: -32013,
90
+ /** The connection watches `maxSubscriptions` sessions already (`data.limit`): unsubscribe one first. */
91
+ subscriptionLimit: -32014,
92
+ /** No login under way has this loginId: it ended, expired, was cancelled or never started. */
93
+ unknownLogin: -32015,
94
+ };
95
+ const WIRE_ERROR_NAMES = new Map(Object.entries(WIRE_ERROR_CODES).map(([name, code]) => [code, name]));
96
+ /** Whether a name is one of `WIRE_ERROR_CODES`'. */
97
+ export function isWireErrorName(name) {
98
+ return Object.hasOwn(WIRE_ERROR_CODES, name);
99
+ }
100
+ /** The name `WIRE_ERROR_CODES` gives an error response's code, if it is one of them. */
101
+ export function wireErrorName(code) {
102
+ return WIRE_ERROR_NAMES.get(code);
103
+ }
104
+ /**
105
+ * A refusal: a request this side will not carry out, answered with the wire
106
+ * error it names — as opposed to a fault, which answers `internalError`. The
107
+ * history port's and the journal's refusals are refusals of this kind, so a
108
+ * caller in-process and one over the wire see the same code.
109
+ */
110
+ export class WireRefusal extends Error {
111
+ code;
112
+ data;
113
+ name = "WireRefusal";
114
+ constructor(code, message,
115
+ /** What the caller needs to act on the refusal, e.g. the `headSeq` to confirm. */
116
+ data) {
117
+ super(message);
118
+ this.code = code;
119
+ this.data = data;
120
+ }
121
+ }
122
+ // ---- methods -----------------------------------------------------------------
123
+ export const WIRE_METHODS = {
124
+ initialize: "initialize",
125
+ turnStart: "turn/start",
126
+ turnCancel: "turn/cancel",
127
+ turnSteer: "turn/steer",
128
+ sessionClose: "session/close",
129
+ permissionRespond: "permission/respond",
130
+ elicitationRespond: "elicitation/respond",
131
+ eventsReplay: "events/replay",
132
+ modelsList: "models/list",
133
+ clisList: "clis/list",
134
+ clisPrepare: "clis/prepare",
135
+ authStatus: "auth/status",
136
+ authLogin: "auth/login",
137
+ authComplete: "auth/complete",
138
+ authCancel: "auth/cancel",
139
+ authLogout: "auth/logout",
140
+ /** Durable servers only (`historyId` in `initialize`); others answer methodNotFound. */
141
+ turnGet: "turn/get",
142
+ sessionGet: "session/get",
143
+ sessionConfirmStopped: "session/confirmStopped",
144
+ sessionRelease: "session/release",
145
+ sessionSubscribe: "session/subscribe",
146
+ sessionUnsubscribe: "session/unsubscribe",
147
+ sessionSubscribeAll: "session/subscribeAll",
148
+ sessionUnsubscribeAll: "session/unsubscribeAll",
149
+ shutdown: "shutdown",
150
+ /** Server -> client notification carrying one sequenced lifecycle event. */
151
+ event: "event",
152
+ /** Server -> client notification: a subscription the server dropped because the connection fell behind. */
153
+ sessionOverflow: "session/overflow",
154
+ /** Server -> client notification: a harness's CLI being installed. */
155
+ clisProgress: "clis/progress",
156
+ /** Server -> client notification: a harness's login changed, or a login ended. */
157
+ authUpdated: "auth/updated",
158
+ };
159
+ export const WireImplementationInfoSchema = z.object({
160
+ name: z.string(),
161
+ version: z.string().optional(),
162
+ });
163
+ export const InitializeParamsSchema = z.object({
164
+ protocolVersion: z.number().int().positive(),
165
+ client: WireImplementationInfoSchema.optional(),
166
+ });
167
+ export const InitializeResultSchema = z.object({
168
+ protocolVersion: z.number().int().positive(),
169
+ server: WireImplementationInfoSchema,
170
+ /**
171
+ * Minted once per server PROCESS. A reconnecting client re-initializes and
172
+ * compares: a changed id means every session log it was tracking belongs to
173
+ * a dead process — adopt the fresh logs (reset cursors, resync) instead of
174
+ * inferring the restart from seq patterns. The handshake STATES the one
175
+ * fact four downstream heuristics used to guess.
176
+ */
177
+ instanceId: z.string(),
178
+ /**
179
+ * Durable servers only: the journal's identity, the `sourceId` of every
180
+ * session history it serves. It outlives the process, and so do the session
181
+ * logs: a client keeps its seq cursors while this is unchanged.
182
+ */
183
+ historyId: z.string().optional(),
184
+ /** Capabilities per registered harness — only available harnesses appear. */
185
+ harnesses: z.record(z.string(), AgentCapabilitiesSchema),
186
+ });
187
+ /**
188
+ * `turn/start` params are a RunRequest whose ids may be omitted — the server
189
+ * mints UUIDv7s for missing ones and echoes the effective ids in the ack.
190
+ * (The bundled client always mints ids itself so it can route events that
191
+ * arrive before the ack's promise continuation runs.)
192
+ */
193
+ export const TurnStartParamsSchema = z.object({
194
+ sessionId: z.string().min(1).optional(),
195
+ turnId: z.string().min(1).optional(),
196
+ input: AgentInputSchema,
197
+ config: RunConfigSchema,
198
+ /**
199
+ * Stream the session to the caller from the head at admission until the
200
+ * turn ends, as `session/subscribe {sessionId, turnId}` does. Default true;
201
+ * a deduplicated start of a running turn subscribes too, a refused one
202
+ * changes nothing.
203
+ */
204
+ subscribe: z.boolean().optional(),
205
+ });
206
+ /** Quick-ack: the turn is accepted and running; completion = `turn.ended`. */
207
+ export const TurnStartResultSchema = z.object({
208
+ sessionId: z.string(),
209
+ turnId: z.string(),
210
+ /**
211
+ * The request converged onto an already-admitted turn with the same turnId
212
+ * and identical input (a retried `turn/start` after a lost ack). No second
213
+ * execution happened; catch up on its events via `events/replay`.
214
+ */
215
+ deduplicated: z.boolean().optional(),
216
+ /** A deduplicated turn that already ended: its `turn.ended`. */
217
+ terminal: TurnEndedEventSchema.optional(),
218
+ /**
219
+ * The session's last kept seq at admission, the subscription point: a new
220
+ * turn's first event follows it. A client with no cursor for the session
221
+ * starts one here, so it downloads none of the session's history.
222
+ */
223
+ headSeq: z.number().int().nonnegative(),
224
+ /** A deduplicated turn whose `turn.started` is kept: its seq, to catch up from. */
225
+ startedSeq: z.number().int().positive().optional(),
226
+ });
227
+ export const TurnCancelParamsSchema = z.object({
228
+ sessionId: z.string().min(1),
229
+ /**
230
+ * Cancel only if THIS turn is the active one — a late cancel meant for a
231
+ * finished turn must not kill its successor. Omitted: cancel whatever turn
232
+ * the session is running. Empty ids are rejected rather than silently
233
+ * treated as unstamped.
234
+ */
235
+ turnId: z.string().min(1).optional(),
236
+ });
237
+ /**
238
+ * What a cancel did, as one outcome:
239
+ * - `cancelled` — the harness confirmed the interrupt.
240
+ * - `unconfirmed` — best-effort dispatched but unacknowledged; the agent
241
+ * process may still be running and the turn's `turn.ended` remains the
242
+ * source of truth.
243
+ * - `no_active_turn` — nothing to cancel: the session had no active turn, or
244
+ * `turnId` was given and a DIFFERENT turn is active (see `activeTurnId`).
245
+ */
246
+ export const TurnCancelResultSchema = z.discriminatedUnion("outcome", [
247
+ z.object({ outcome: z.literal("cancelled"), turnId: z.string() }),
248
+ z.object({ outcome: z.literal("unconfirmed"), turnId: z.string() }),
249
+ z.object({ outcome: z.literal("no_active_turn"), activeTurnId: z.string().optional() }),
250
+ ]);
251
+ /**
252
+ * More input for a running turn. `turnId` is required: a steer meant for one
253
+ * turn must never land in the next. `steerId` names the user message the steer
254
+ * becomes (`steerMessageId`), so it is unique in the session, as a turn id is;
255
+ * the server mints one when it is omitted. A retry with the same `steerId` and
256
+ * input converges instead of steering twice; reusing it otherwise is
257
+ * `turnConflict`.
258
+ */
259
+ export const TurnSteerParamsSchema = z.object({
260
+ sessionId: z.string().min(1),
261
+ turnId: z.string().min(1),
262
+ steerId: z.string().min(1).optional(),
263
+ input: AgentInputSchema.refine((input) => (typeof input === "string" ? input.trim() !== "" : input.length > 0), "a steer carries input"),
264
+ });
265
+ /**
266
+ * What a steer did, as one outcome:
267
+ * - `steered` — accepted. It reaches the agent at its next step and
268
+ * appears as a user message in the turn, or, if the turn ends first, in
269
+ * the turn's `turn.ended.undeliveredSteers`.
270
+ * - `no_active_turn` — the turn is not taking input: it ended or is ending,
271
+ * or another turn is active (`activeTurnId`). Send it as a new turn.
272
+ * - `unsupported` — this harness cannot take input mid-turn
273
+ * (`AgentCapabilities.steering`).
274
+ */
275
+ export const TurnSteerResultSchema = z.discriminatedUnion("outcome", [
276
+ z.object({
277
+ outcome: z.literal("steered"),
278
+ steerId: z.string(),
279
+ /** A retry of a steer already accepted: nothing was sent twice. */
280
+ deduplicated: z.boolean().optional(),
281
+ }),
282
+ z.object({ outcome: z.literal("no_active_turn"), activeTurnId: z.string().optional() }),
283
+ z.object({ outcome: z.literal("unsupported") }),
284
+ ]);
285
+ export const SessionCloseParamsSchema = z.object({ sessionId: z.string() });
286
+ /** `closed: false` means the server did not know the session (idempotent). */
287
+ export const SessionCloseResultSchema = z.object({ closed: z.boolean() });
288
+ export const PermissionRespondParamsSchema = z.object({
289
+ sessionId: z.string(),
290
+ requestId: z.string(),
291
+ outcome: PermissionOutcomeSchema,
292
+ });
293
+ /** `accepted: false` means the request was unknown or already resolved. */
294
+ export const PermissionRespondResultSchema = z.object({ accepted: z.boolean() });
295
+ export const ElicitationRespondParamsSchema = z.object({
296
+ sessionId: z.string(),
297
+ requestId: z.string(),
298
+ outcome: ElicitationOutcomeSchema,
299
+ });
300
+ /** `accepted: false` means the request was unknown or already resolved. */
301
+ export const ElicitationRespondResultSchema = z.object({ accepted: z.boolean() });
302
+ /** The routing fields of an envelope — strict, because the wire owns them. */
303
+ const WireEventEnvelopeHeaderSchema = z.object({
304
+ sessionId: z.string(),
305
+ seq: z.number().int().positive(),
306
+ live: z.literal(true).optional(),
307
+ });
308
+ // @ref LLP 0002#snapshots-win-over-deltas — a frame no one keeps says so
309
+ /**
310
+ * One frame of a session as sent on the wire. `seq` is per-session,
311
+ * monotonic, and starts at 1. A frame the server does not keep says
312
+ * `live: true`: a token delta, or an open part sent after a subscription (a
313
+ * `message.part` carrying the part's content so far). It takes no seq of its
314
+ * own, carries that of the last kept event before it (fold it with
315
+ * `SeqCursor.advanceLive`; `isLiveEnvelope` tells), and replay and history
316
+ * never return it. The envelope duplicates `sessionId` so consumers can route
317
+ * without parsing the event body.
318
+ */
319
+ export const WireEventEnvelopeSchema = WireEventEnvelopeHeaderSchema.extend({
320
+ event: LifecycleEventSchema,
321
+ });
322
+ /**
323
+ * Decode one `event` notification: envelope strict, event lenient. A consumer
324
+ * that instead drops an unknown event type does not degrade gracefully — it
325
+ * leaves a hole where a `seq` was, and every seq-tracking client then reads
326
+ * the next event as an unfillable gap.
327
+ */
328
+ export function decodeWireEventEnvelope(value) {
329
+ const header = WireEventEnvelopeHeaderSchema.parse(value);
330
+ return {
331
+ sessionId: header.sessionId,
332
+ seq: header.seq,
333
+ ...(header.live && { live: true }),
334
+ event: decodeLifecycleEvent(value.event),
335
+ };
336
+ }
337
+ export const EventsReplayParamsSchema = z.object({
338
+ sessionId: z.string(),
339
+ /** Replay buffered events with `seq >= fromSeq`. */
340
+ fromSeq: z.number().int().positive(),
341
+ });
342
+ /**
343
+ * Replay is served from a bounded per-session ring buffer. When
344
+ * `firstAvailableSeq > fromSeq`, the requested prefix was evicted and the gap
345
+ * is unfillable — the consumer must treat its local view as stale. A durable
346
+ * server keeps every event and answers in pages: `hasMore` asks for the next.
347
+ */
348
+ export const EventsReplayResultSchema = z.object({
349
+ events: z.array(WireEventEnvelopeSchema),
350
+ firstAvailableSeq: z.number().int().positive().nullable(),
351
+ latestSeq: z.number().int().positive().nullable(),
352
+ hasMore: z.boolean().optional(),
353
+ });
354
+ /** A replay result with its events left to decode one by one. */
355
+ const ReplayResultFrameSchema = EventsReplayResultSchema.extend({ events: z.array(z.unknown()) });
356
+ /**
357
+ * The replay result, decoded envelope-by-envelope. `EventsReplayResultSchema`
358
+ * embeds the CLOSED event union, so parsing a buffer with it makes one unknown
359
+ * event type poison the whole replay — the healing path for a gap must not be
360
+ * the thing that cannot survive an unknown.
361
+ */
362
+ export function decodeEventsReplayResult(value) {
363
+ const parsed = ReplayResultFrameSchema.parse(value);
364
+ return { ...parsed, events: parsed.events.map((event) => decodeWireEventEnvelope(event)) };
365
+ }
366
+ /**
367
+ * `models/list`: the models a harness offers, read from its CLI for the login
368
+ * and folder a turn with the same `cwd`, `env` and `apiKey` would use (Claude
369
+ * narrows the list by the folder's `availableModels`; Codex by the account).
370
+ * Served from a cache; `refresh` reads the CLI again, e.g. after a login.
371
+ */
372
+ export const ModelsListParamsSchema = z.object({
373
+ harness: AgentHarnessSchema,
374
+ /** The folder whose settings apply. Defaults to the server's working directory. */
375
+ cwd: z.string().optional(),
376
+ /** List with this session's credentials (host-managed Codex auth resolves per session). */
377
+ sessionId: z.string().min(1).optional(),
378
+ env: z.record(z.string(), z.string()).optional(),
379
+ apiKey: z.string().optional(),
380
+ refresh: z.boolean().optional(),
381
+ });
382
+ /**
383
+ * `turn/get`: a durable turn's receipt. Admission records it, with the input,
384
+ * before the `turn/start` ack, so a turn whose process died before its first
385
+ * event is still known; `interrupted` means a restart cut it off.
386
+ */
387
+ export const TurnGetParamsSchema = z.object({ sessionId: z.string(), turnId: z.string() });
388
+ export const TurnReceiptSchema = TurnGetParamsSchema.extend({
389
+ state: z.enum(["admitted", "completed", "interrupted"]),
390
+ input: AgentInputSchema.optional(),
391
+ terminal: TurnEndedEventSchema.optional(),
392
+ });
393
+ /** `session/get`: what a durable server knows about a session. */
394
+ export const SessionGetParamsSchema = z.object({ sessionId: z.string() });
395
+ /**
396
+ * Why a restart could not lift a session's fence: `not_owned`, a host's own
397
+ * spawner started its agent; `not_verified`, nothing could tell whether its
398
+ * process still runs (no sweep, no process table, a pid it may not signal);
399
+ * `not_stopped`, it was still there after SIGKILL.
400
+ */
401
+ export const RECOVERY_REASONS = ["not_owned", "not_verified", "not_stopped"];
402
+ export const RecoveryReasonSchema = z.enum(RECOVERY_REASONS);
403
+ /**
404
+ * A session's latest turn: `stopReason` and `error` as its `turn.ended` said,
405
+ * both absent while it runs. One a restart cut off ended `error`, category
406
+ * `server_restart`.
407
+ */
408
+ export const LastTurnSchema = TurnEndedEventSchema.pick({
409
+ turnId: true,
410
+ stopReason: true,
411
+ error: true,
412
+ }).partial({ stopReason: true });
413
+ export const DurableSessionSchema = z.object({
414
+ sessionId: z.string(),
415
+ harness: AgentHarnessSchema,
416
+ /** The seq of its latest event; 0 before the first. */
417
+ headSeq: z.number().int().nonnegative(),
418
+ nativeSessionId: z.string().nullable(),
419
+ closed: z.boolean(),
420
+ /**
421
+ * A restart cut off a turn and could not confirm its agent stopped: see
422
+ * `recoveryRequired` and `session/confirmStopped`.
423
+ */
424
+ recoveryRequired: z.boolean(),
425
+ /** Why, while `recoveryRequired` is set. */
426
+ recoveryReason: RecoveryReasonSchema.optional(),
427
+ /** Its latest turn, once it has admitted one (`session/get` only). */
428
+ lastTurn: LastTurnSchema.optional(),
429
+ });
430
+ /**
431
+ * `session/confirmStopped`: the caller checked that the native execution a
432
+ * restart cut off is no longer running (history alone cannot prove that a
433
+ * detached agent or tool process died). `expectedHeadSeq` fences a stale
434
+ * confirmation against a newer interruption.
435
+ */
436
+ export const SessionConfirmStoppedParamsSchema = z.object({
437
+ sessionId: z.string(),
438
+ expectedHeadSeq: z.number().int().nonnegative(),
439
+ confirmedStopped: z.literal(true),
440
+ });
441
+ /** `recovered: false` when nothing awaited confirmation. */
442
+ export const SessionConfirmStoppedResultSchema = z.object({ recovered: z.boolean() });
443
+ /**
444
+ * `session/release`: let an idle session's agent go (its process and what it
445
+ * holds, a Codex home included) while the session stays open. Its next turn
446
+ * names its native conversation (`config.resumeSessionId`; until then
447
+ * `resumeRequired`), as after a restart. `session/close` ends a session;
448
+ * this only frees what it runs on. Nothing is broadcast: another client of
449
+ * the session learns of it when its next turn is refused `resumeRequired`,
450
+ * whose data names the conversation, the answer a client that survives a
451
+ * restart already handles.
452
+ */
453
+ export const SessionReleaseParamsSchema = z.object({ sessionId: z.string() });
454
+ /** `released: false` when the server holds no open session by that id. */
455
+ export const SessionReleaseResultSchema = z.object({ released: z.boolean() });
456
+ // @ref LLP 0008#ordering-joining-without-a-gap-or-a-duplicate — the answer marks the point
457
+ /**
458
+ * `session/subscribe`: stream a session to this connection. The answer marks
459
+ * the subscription point in the connection's frames. After it come, first,
460
+ * the session's open parts (`live` `message.part` frames at `headSeq`), then
461
+ * every kept event after `headSeq` and every delta after the point, each
462
+ * once. Kept events up to `headSeq` the caller does not hold it reads with
463
+ * `events/replay`: the server pushes no catch-up. Subscribing again answers
464
+ * a new point and sends the open parts again; no other frame is sent twice.
465
+ *
466
+ * Without `turnId` the connection watches the session until it unsubscribes
467
+ * or the session ends; with one it follows that turn, while it runs, until
468
+ * its `turn.ended` (a turn that is not running subscribes nothing, and the
469
+ * answer's `activeTurn` says so). Refused `unknownSession` when the server has
470
+ * no log for the session (it never ran, or it was closed), and
471
+ * `subscriptionLimit` past the connection's cap, which counts the sessions it
472
+ * watches (`session/subscribeAll` once), never the turns it follows.
473
+ */
474
+ export const SessionSubscribeParamsSchema = z.object({
475
+ sessionId: z.string().min(1),
476
+ /** Follow this running turn of the session, until it ends, instead of watching the session. */
477
+ turnId: z.string().min(1).optional(),
478
+ });
479
+ /** The turn a session runs at a subscription point. */
480
+ export const RunningTurnSchema = z.object({
481
+ turnId: z.string(),
482
+ /** Once its `turn.started` is kept: where to catch up on the turn from. */
483
+ startedSeq: z.number().int().positive().optional(),
484
+ });
485
+ export const SessionSubscribeResultSchema = z.object({
486
+ /** The session's last kept seq at the subscription point (0: none yet). */
487
+ headSeq: z.number().int().nonnegative(),
488
+ /** The oldest kept seq replay still holds (null: none): a ring may have evicted what a catch-up needs. */
489
+ firstAvailableSeq: z.number().int().positive().nullable(),
490
+ /** The turn running at the point. */
491
+ activeTurn: RunningTurnSchema.optional(),
492
+ });
493
+ /**
494
+ * `session/subscribeAll`: stream every session to this connection, live from
495
+ * now, with no catch-up: for observers. It counts once against the cap.
496
+ */
497
+ export const SessionSubscribeAllParamsSchema = z.object({});
498
+ /** Each session with a running turn, at its point; their open parts follow. */
499
+ export const SessionSubscribeAllResultSchema = z.object({
500
+ sessions: z.array(SessionSubscribeResultSchema.extend({ sessionId: z.string() })),
501
+ });
502
+ /**
503
+ * `session/unsubscribe`: stop watching a session. A turn the connection
504
+ * follows streams on until it ends.
505
+ */
506
+ export const SessionUnsubscribeParamsSchema = z.object({ sessionId: z.string().min(1) });
507
+ /** `session/unsubscribeAll`: stop streaming every session; those watched by name stream on. */
508
+ export const SessionUnsubscribeAllParamsSchema = z.object({});
509
+ /** `unsubscribed: false` when this connection did not watch it (or every session). */
510
+ export const SessionUnsubscribeResultSchema = z.object({ unsubscribed: z.boolean() });
511
+ /**
512
+ * `session/overflow` (server -> client): this connection fell
513
+ * `maxBacklogBytes` behind, so the server stopped sending the session after
514
+ * `lastSeq`, the last kept seq it sent, and dropped the subscription.
515
+ * Subscribe again after the last seq you hold; its open parts come with it.
516
+ * `{all: true}`: the subscription to every session was dropped.
517
+ */
518
+ export const SessionOverflowParamsSchema = z.union([
519
+ z.object({ sessionId: z.string(), lastSeq: z.number().int().nonnegative() }),
520
+ z.object({ all: z.literal(true) }),
521
+ ]);
522
+ export const ShutdownResultSchema = z.object({});
523
+ /** Decode one NDJSON line into a JSON-RPC message (never throws). */
524
+ export function decodeWireMessage(line) {
525
+ let raw;
526
+ try {
527
+ raw = JSON.parse(line);
528
+ }
529
+ catch {
530
+ return { kind: "invalid", error: "not valid JSON", parseError: true };
531
+ }
532
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
533
+ return { kind: "invalid", error: "not a JSON-RPC object", parseError: false };
534
+ }
535
+ const msg = raw;
536
+ if (msg.jsonrpc !== "2.0")
537
+ return { kind: "invalid", error: "missing jsonrpc: '2.0'", parseError: false };
538
+ const id = JsonRpcIdSchema.safeParse(msg.id);
539
+ if (typeof msg.method === "string") {
540
+ return id.success
541
+ ? { kind: "request", id: id.data, method: msg.method, params: msg.params }
542
+ : { kind: "notification", method: msg.method, params: msg.params };
543
+ }
544
+ if ((id.success || msg.id === null) && ("result" in msg || "error" in msg)) {
545
+ const error = JsonRpcErrorSchema.safeParse(msg.error);
546
+ return {
547
+ kind: "response",
548
+ id: id.success ? id.data : null,
549
+ result: msg.result,
550
+ error: error.success ? error.data : undefined,
551
+ };
552
+ }
553
+ return {
554
+ kind: "invalid",
555
+ error: "neither request, notification, nor response",
556
+ parseError: false,
557
+ };
558
+ }
559
+ export function encodeRequest(id, method, params) {
560
+ return JSON.stringify({ jsonrpc: "2.0", id, method, params });
561
+ }
562
+ export function encodeNotification(method, params) {
563
+ return JSON.stringify({ jsonrpc: "2.0", method, params });
564
+ }
565
+ export function encodeResponse(id, result) {
566
+ return JSON.stringify({ jsonrpc: "2.0", id, result });
567
+ }
568
+ export function encodeErrorResponse(id, code, message, data) {
569
+ return JSON.stringify({ jsonrpc: "2.0", id, error: { code, message, data } });
570
+ }
571
+ /**
572
+ * Split an inbound transport message into NDJSON lines, defensively: peers
573
+ * may batch several lines per frame, and WebSocket implementations deliver
574
+ * text, Uint8Array, or ArrayBuffer depending on runtime. Blank lines are
575
+ * skipped.
576
+ */
577
+ export function pushNdjsonLines(push, data) {
578
+ let text;
579
+ if (typeof data === "string")
580
+ text = data;
581
+ else if (data instanceof Uint8Array)
582
+ text = new TextDecoder().decode(data);
583
+ else if (data instanceof ArrayBuffer)
584
+ text = new TextDecoder().decode(new Uint8Array(data));
585
+ else
586
+ text = String(data);
587
+ for (const line of text.split("\n"))
588
+ if (line.trim())
589
+ push(line);
590
+ }
591
+ /**
592
+ * Build a WireTransport from a raw byte-channel binding: the caller supplies
593
+ * the outbound `send`/`close`, and pushes inbound lines / close through the
594
+ * returned handles. Every concrete transport (stdio, WebSocket, `channelPair`)
595
+ * is this bridge plus platform wiring.
596
+ */
597
+ export function channelTransport(io) {
598
+ const lineHandlers = new Set();
599
+ const closeHandlers = new Set();
600
+ let closed = false;
601
+ const end = (reason) => {
602
+ if (closed)
603
+ return;
604
+ closed = true;
605
+ for (const handler of [...closeHandlers])
606
+ handler(reason);
607
+ lineHandlers.clear();
608
+ closeHandlers.clear();
609
+ };
610
+ const { bufferedAmount } = io;
611
+ const transport = {
612
+ send(line) {
613
+ if (!closed)
614
+ io.send(line);
615
+ },
616
+ ...(bufferedAmount && { bufferedAmount: () => bufferedAmount.call(io) }),
617
+ onLine(handler) {
618
+ lineHandlers.add(handler);
619
+ return () => lineHandlers.delete(handler);
620
+ },
621
+ onClose(handler) {
622
+ closeHandlers.add(handler);
623
+ return () => closeHandlers.delete(handler);
624
+ },
625
+ close() {
626
+ if (closed)
627
+ return;
628
+ io.close?.();
629
+ end("closed locally");
630
+ },
631
+ get closed() {
632
+ return closed;
633
+ },
634
+ };
635
+ return {
636
+ transport,
637
+ push(line) {
638
+ if (closed)
639
+ return;
640
+ for (const handler of [...lineHandlers])
641
+ handler(line);
642
+ },
643
+ end,
644
+ };
645
+ }
646
+ /**
647
+ * Two transports wired to each other in one process: the in-process wire
648
+ * between an `AgentServer` and its client (`server.attach(pair.server)`,
649
+ * `AgentServerClient.attach(pair.client)`). `deliver` schedules each line's
650
+ * arrival, a microtask later by default, as a socket's arrives on a later
651
+ * tick; `kill` drops the connection at both ends.
652
+ */
653
+ export function channelPair(deliver = queueMicrotask) {
654
+ const ends = [];
655
+ const end = (peer) => channelTransport({
656
+ send: (line) => deliver(() => ends[peer]?.push(line)),
657
+ close: () => deliver(() => ends[peer]?.end("peer closed")),
658
+ });
659
+ ends.push(end(1), end(0));
660
+ const [client, server] = ends;
661
+ return {
662
+ client: client.transport,
663
+ server: server.transport,
664
+ kill(reason = "connection dropped") {
665
+ client.end(reason);
666
+ server.end(reason);
667
+ },
668
+ };
669
+ }