@lostgradient/backchannel 0.0.0-stage → 0.1.0

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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/access-policy-metadata.d.ts +92 -0
  4. package/dist/access-policy-metadata.js +87 -0
  5. package/dist/asyncapi-channels.d.ts +46 -0
  6. package/dist/asyncapi-channels.js +399 -0
  7. package/dist/asyncapi.d.ts +40 -0
  8. package/dist/asyncapi.js +165 -0
  9. package/dist/authentication/api-key.d.ts +4 -0
  10. package/dist/authentication/api-key.js +114 -0
  11. package/dist/authentication/audit.d.ts +115 -0
  12. package/dist/authentication/audit.js +75 -0
  13. package/dist/authentication/credential-verifiers.d.ts +60 -0
  14. package/dist/authentication/credential-verifiers.js +102 -0
  15. package/dist/authentication/crypto.d.ts +7 -0
  16. package/dist/authentication/crypto.js +140 -0
  17. package/dist/authentication/index.d.ts +80 -0
  18. package/dist/authentication/index.js +212 -0
  19. package/dist/authentication/rate-limiter.d.ts +133 -0
  20. package/dist/authentication/rate-limiter.js +124 -0
  21. package/dist/authentication/redaction.d.ts +72 -0
  22. package/dist/authentication/redaction.js +118 -0
  23. package/dist/authentication/rotating-api-key-store.d.ts +127 -0
  24. package/dist/authentication/rotating-api-key-store.js +126 -0
  25. package/dist/authentication/types.d.ts +337 -0
  26. package/dist/authentication/types.js +26 -0
  27. package/dist/authentication.d.ts +1 -0
  28. package/dist/authentication.js +1 -0
  29. package/dist/authorization-scope.d.ts +109 -0
  30. package/dist/authorization-scope.js +144 -0
  31. package/dist/authorization.d.ts +55 -0
  32. package/dist/authorization.js +134 -0
  33. package/dist/bind-feed-lifetime.d.ts +45 -0
  34. package/dist/bind-feed-lifetime.js +55 -0
  35. package/dist/byte-arrays.d.ts +5 -0
  36. package/dist/byte-arrays.js +9 -0
  37. package/dist/client/catalog-client.d.ts +285 -0
  38. package/dist/client/catalog-client.js +74 -0
  39. package/dist/client/in-process-transport.d.ts +19 -0
  40. package/dist/client/in-process-transport.js +136 -0
  41. package/dist/client/index.d.ts +14 -0
  42. package/dist/client/index.js +14 -0
  43. package/dist/client/json-rpc-http-transport.d.ts +118 -0
  44. package/dist/client/json-rpc-http-transport.js +127 -0
  45. package/dist/client/server-sent-event-parser.d.ts +55 -0
  46. package/dist/client/server-sent-event-parser.js +78 -0
  47. package/dist/client/sse-subscription-transport.d.ts +72 -0
  48. package/dist/client/sse-subscription-transport.js +224 -0
  49. package/dist/client/subscription-client.d.ts +122 -0
  50. package/dist/client/subscription-client.js +28 -0
  51. package/dist/connection-lease.d.ts +10 -0
  52. package/dist/connection-lease.js +8 -0
  53. package/dist/discovery-filter.d.ts +13 -0
  54. package/dist/discovery-filter.js +16 -0
  55. package/dist/discovery-info.d.ts +94 -0
  56. package/dist/discovery-info.js +38 -0
  57. package/dist/event-selector.d.ts +7 -0
  58. package/dist/event-selector.js +7 -0
  59. package/dist/fault-code.d.ts +84 -0
  60. package/dist/fault-code.js +114 -0
  61. package/dist/fault-remediation.d.ts +30 -0
  62. package/dist/fault-remediation.js +52 -0
  63. package/dist/fault-to-http.d.ts +11 -0
  64. package/dist/fault-to-http.js +13 -0
  65. package/dist/fault-to-json-rpc.d.ts +53 -0
  66. package/dist/fault-to-json-rpc.js +143 -0
  67. package/dist/fault-wire-safety.d.ts +45 -0
  68. package/dist/fault-wire-safety.js +72 -0
  69. package/dist/generator.d.ts +9 -0
  70. package/dist/generator.js +9 -0
  71. package/dist/handler/auth-context-principal.d.ts +37 -0
  72. package/dist/handler/auth-context-principal.js +67 -0
  73. package/dist/handler/authentication-responses.d.ts +23 -0
  74. package/dist/handler/authentication-responses.js +34 -0
  75. package/dist/handler/json-responses.d.ts +15 -0
  76. package/dist/handler/json-responses.js +32 -0
  77. package/dist/handler/operation-handler-authentication.d.ts +64 -0
  78. package/dist/handler/operation-handler-authentication.js +58 -0
  79. package/dist/handler/operation-handler-discovery.d.ts +29 -0
  80. package/dist/handler/operation-handler-discovery.js +55 -0
  81. package/dist/handler/operation-handler-mounts.d.ts +100 -0
  82. package/dist/handler/operation-handler-mounts.js +134 -0
  83. package/dist/handler/operation-handler-subscription.d.ts +34 -0
  84. package/dist/handler/operation-handler-subscription.js +112 -0
  85. package/dist/handler/operation-handler.d.ts +162 -0
  86. package/dist/handler/operation-handler.js +236 -0
  87. package/dist/handler/workspace-release.d.ts +6 -0
  88. package/dist/handler/workspace-release.js +75 -0
  89. package/dist/in-memory-replay-live-backend.d.ts +47 -0
  90. package/dist/in-memory-replay-live-backend.js +129 -0
  91. package/dist/index.d.ts +37 -0
  92. package/dist/index.js +30 -0
  93. package/dist/internal/cryptography/encryption.d.ts +108 -0
  94. package/dist/internal/cryptography/encryption.js +241 -0
  95. package/dist/internal/cryptography/hash.d.ts +72 -0
  96. package/dist/internal/cryptography/hash.js +233 -0
  97. package/dist/internal/cryptography/index.d.ts +4 -0
  98. package/dist/internal/cryptography/index.js +2 -0
  99. package/dist/internals.d.ts +58 -0
  100. package/dist/internals.js +54 -0
  101. package/dist/json-rpc-dispatch.d.ts +88 -0
  102. package/dist/json-rpc-dispatch.js +154 -0
  103. package/dist/json-rpc-framing.d.ts +42 -0
  104. package/dist/json-rpc-framing.js +50 -0
  105. package/dist/json-rpc-http.d.ts +36 -0
  106. package/dist/json-rpc-http.js +191 -0
  107. package/dist/json-rpc-parse.d.ts +69 -0
  108. package/dist/json-rpc-parse.js +206 -0
  109. package/dist/json-rpc-protocol.d.ts +76 -0
  110. package/dist/json-rpc-protocol.js +54 -0
  111. package/dist/json-rpc-session-runtime.d.ts +55 -0
  112. package/dist/json-rpc-session-runtime.js +111 -0
  113. package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
  114. package/dist/json-rpc-websocket-subscription-pump.js +46 -0
  115. package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
  116. package/dist/json-rpc-websocket-subscriptions.js +33 -0
  117. package/dist/json-rpc-websocket-types.d.ts +34 -0
  118. package/dist/json-rpc-websocket-types.js +1 -0
  119. package/dist/json-rpc-websocket-validation.d.ts +45 -0
  120. package/dist/json-rpc-websocket-validation.js +154 -0
  121. package/dist/json-rpc-websocket.d.ts +20 -0
  122. package/dist/json-rpc-websocket.js +363 -0
  123. package/dist/json-schema-utilities.d.ts +5 -0
  124. package/dist/json-schema-utilities.js +17 -0
  125. package/dist/mcp-discovery-names.d.ts +11 -0
  126. package/dist/mcp-discovery-names.js +11 -0
  127. package/dist/openapi-canonical-json.d.ts +10 -0
  128. package/dist/openapi-canonical-json.js +23 -0
  129. package/dist/openapi-error-responses.d.ts +15 -0
  130. package/dist/openapi-error-responses.js +104 -0
  131. package/dist/openapi-schemas.d.ts +17 -0
  132. package/dist/openapi-schemas.js +94 -0
  133. package/dist/openapi.d.ts +60 -0
  134. package/dist/openapi.js +351 -0
  135. package/dist/openrpc-document-schema.d.ts +255 -0
  136. package/dist/openrpc-document-schema.js +84 -0
  137. package/dist/openrpc-errors.d.ts +93 -0
  138. package/dist/openrpc-errors.js +134 -0
  139. package/dist/openrpc.d.ts +66 -0
  140. package/dist/openrpc.js +260 -0
  141. package/dist/operation-catalog/behavior-types.d.ts +34 -0
  142. package/dist/operation-catalog/behavior-types.js +1 -0
  143. package/dist/operation-catalog/behavior-validation.d.ts +3 -0
  144. package/dist/operation-catalog/behavior-validation.js +298 -0
  145. package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
  146. package/dist/operation-catalog/dispatch-allowlist.js +7 -0
  147. package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
  148. package/dist/operation-catalog/dispatch-preparation.js +49 -0
  149. package/dist/operation-catalog/index.d.ts +19 -0
  150. package/dist/operation-catalog/index.js +17 -0
  151. package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
  152. package/dist/operation-catalog/operation-dispatch.js +115 -0
  153. package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
  154. package/dist/operation-catalog/operation-interceptors.js +1 -0
  155. package/dist/operation-catalog/operation-metadata.d.ts +5 -0
  156. package/dist/operation-catalog/operation-metadata.js +104 -0
  157. package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
  158. package/dist/operation-catalog/pipeline-helpers.js +242 -0
  159. package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
  160. package/dist/operation-catalog/pipeline-stages.js +226 -0
  161. package/dist/operation-catalog/pipeline.d.ts +7 -0
  162. package/dist/operation-catalog/pipeline.js +33 -0
  163. package/dist/operation-catalog/registry.d.ts +17 -0
  164. package/dist/operation-catalog/registry.js +132 -0
  165. package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
  166. package/dist/operation-catalog/stream-pipeline.js +129 -0
  167. package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
  168. package/dist/operation-catalog/subscription-lifecycle.js +27 -0
  169. package/dist/operation-catalog/types.d.ts +392 -0
  170. package/dist/operation-catalog/types.js +40 -0
  171. package/dist/operation-catalog/universal-faults.d.ts +11 -0
  172. package/dist/operation-catalog/universal-faults.js +15 -0
  173. package/dist/operation-catalog-snapshot.d.ts +215 -0
  174. package/dist/operation-catalog-snapshot.js +128 -0
  175. package/dist/operation-catalog.d.ts +1 -0
  176. package/dist/operation-catalog.js +1 -0
  177. package/dist/operation-description-audit.d.ts +44 -0
  178. package/dist/operation-description-audit.js +90 -0
  179. package/dist/operation-fault-helpers.d.ts +21 -0
  180. package/dist/operation-fault-helpers.js +32 -0
  181. package/dist/operation-fault.d.ts +245 -0
  182. package/dist/operation-fault.js +235 -0
  183. package/dist/operation-registry.d.ts +46 -0
  184. package/dist/operation-registry.js +46 -0
  185. package/dist/operations/closable-iterable.d.ts +23 -0
  186. package/dist/operations/closable-iterable.js +51 -0
  187. package/dist/operations/get-principal.d.ts +106 -0
  188. package/dist/operations/get-principal.js +107 -0
  189. package/dist/operations/sse-stream.d.ts +67 -0
  190. package/dist/operations/sse-stream.js +264 -0
  191. package/dist/principal.d.ts +253 -0
  192. package/dist/principal.js +254 -0
  193. package/dist/replay-live-feed-internals.d.ts +47 -0
  194. package/dist/replay-live-feed-internals.js +215 -0
  195. package/dist/replay-live-feed-types.d.ts +66 -0
  196. package/dist/replay-live-feed-types.js +7 -0
  197. package/dist/replay-live-feed.d.ts +49 -0
  198. package/dist/replay-live-feed.js +126 -0
  199. package/dist/rest-binding.d.ts +215 -0
  200. package/dist/rest-binding.js +95 -0
  201. package/dist/rest-body.d.ts +17 -0
  202. package/dist/rest-body.js +95 -0
  203. package/dist/route-model.d.ts +305 -0
  204. package/dist/route-model.js +320 -0
  205. package/dist/runtime/cors.d.ts +161 -0
  206. package/dist/runtime/cors.js +265 -0
  207. package/dist/scripts/generate-operation-client.d.ts +186 -0
  208. package/dist/scripts/generate-operation-client.js +561 -0
  209. package/dist/scripts/operation-behaviors.d.ts +3 -0
  210. package/dist/scripts/operation-behaviors.js +16 -0
  211. package/dist/scripts/operation-client-aliases.d.ts +32 -0
  212. package/dist/scripts/operation-client-aliases.js +255 -0
  213. package/dist/scripts/operation-client-domains.d.ts +21 -0
  214. package/dist/scripts/operation-client-domains.js +74 -0
  215. package/dist/scripts/operation-client-schema.d.ts +46 -0
  216. package/dist/scripts/operation-client-schema.js +310 -0
  217. package/dist/scripts/operation-client-svelte.d.ts +3 -0
  218. package/dist/scripts/operation-client-svelte.js +61 -0
  219. package/dist/sequence-cursor.d.ts +46 -0
  220. package/dist/sequence-cursor.js +62 -0
  221. package/dist/sse-error-payload-schema.d.ts +12 -0
  222. package/dist/sse-error-payload-schema.js +33 -0
  223. package/dist/stdio-session.d.ts +71 -0
  224. package/dist/stdio-session.js +347 -0
  225. package/dist/zod-json-schema.d.ts +22 -0
  226. package/dist/zod-json-schema.js +49 -0
  227. package/package.json +38 -3
@@ -0,0 +1,363 @@
1
+ /**
2
+ * WebSocket JSON-RPC session adapter.
3
+ *
4
+ * Each `/jsonrpc` WebSocket connection gets one `JsonRpcWebSocketSession`
5
+ * that binds the authenticated principal at upgrade time and reuses it
6
+ * for every frame. The session:
7
+ * - Parses incoming frames as single JSON-RPC requests (batches over
8
+ * WS are rejected per stable operation-catalog contract).
9
+ * - Dispatches `weft.workflows.subscribe` / `weft.workflows.unsubscribe`
10
+ * as first-class session primitives against the `WorkflowEventFeed`.
11
+ * - Delegates all other methods to the standard `dispatchJsonRpc`.
12
+ * - Emits live envelopes as `weft.events.deliver` notifications keyed
13
+ * by the assigned `subscriptionId`.
14
+ * - Guarantees every active subscription is torn down on `close()`
15
+ * (or socket disconnect at the transport layer).
16
+ */
17
+ import { faultErrorData, faultToJsonRpcError } from "./fault-to-json-rpc.js";
18
+ import { dispatchJsonRpc } from "./json-rpc-dispatch.js";
19
+ import { parseJsonRpcRequest } from "./json-rpc-parse.js";
20
+ import { JSON_RPC_ERROR_CODES, JSON_RPC_VERSION, } from "./json-rpc-protocol.js";
21
+ import { pumpSubscriptionIterable } from "./json-rpc-websocket-subscription-pump.js";
22
+ import { FLEET_EVENTS_OPERATION_NAME, SESSION_METHODS, WORKFLOW_EVENTS_OPERATION_NAME, } from "./json-rpc-websocket-subscriptions.js";
23
+ import { validateMessageFrame, validateSessionPrimitiveFrame, validateSubscribeParams, } from "./json-rpc-websocket-validation.js";
24
+ import { executeSubscription, } from "./operation-catalog.js";
25
+ const DEFAULT_MAX_SUBSCRIPTIONS = 100;
26
+ const DEFAULT_MAX_FRAME_BYTES = 1 * 1024 * 1024;
27
+ async function closeSubscriptionAfterClose(closeSubscription) {
28
+ await closeSubscription().catch(() => { });
29
+ }
30
+ async function startLegacySubscription(request, execution) {
31
+ const result = await execution;
32
+ const id = request.id ?? null;
33
+ if (!result.ok) {
34
+ const error = faultToJsonRpcError(result.fault);
35
+ return { response: { jsonrpc: JSON_RPC_VERSION, id, error } };
36
+ }
37
+ const subscription = result.value;
38
+ return {
39
+ subscription,
40
+ response: {
41
+ jsonrpc: JSON_RPC_VERSION,
42
+ id,
43
+ result: {
44
+ subscriptionId: subscription.subscriptionId,
45
+ cursor: subscription.envelope.cursor,
46
+ },
47
+ },
48
+ };
49
+ }
50
+ function requiresSubscriptionClose(disposed, signal) {
51
+ return disposed || signal.aborted;
52
+ }
53
+ function releaseSubscriptionLease(lease) {
54
+ lease?.release();
55
+ }
56
+ function acquireSubscriptionLease(acquire) {
57
+ return acquire?.();
58
+ }
59
+ function isSessionPrimitive(method) {
60
+ return (method === SESSION_METHODS.SUBSCRIBE ||
61
+ method === WORKFLOW_EVENTS_OPERATION_NAME ||
62
+ method === SESSION_METHODS.FLEET_SUBSCRIBE ||
63
+ method === SESSION_METHODS.UNSUBSCRIBE);
64
+ }
65
+ /** Builds a JSON-RPC session over an emitter and an operation registry. */
66
+ export function createJsonRpcWebSocketSession(options) {
67
+ const { registry, engine, principal, emitter, feed, fleetFeed, discoverDocument, acquireWorkflowSubscription, acquireFleetSubscription, } = options;
68
+ const maxSubscriptions = options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS;
69
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
70
+ const transport = options.transport ?? 'jsonRpcWebSocket';
71
+ const subscriptions = new Map();
72
+ const pendingSubscriptions = new Set();
73
+ // Keep emitter failure separate from disposal so close() still tears down
74
+ // active subscriptions after a socket send fails.
75
+ let emitterBroken = false;
76
+ let disposed = false;
77
+ /** Send a frame while containing closed-socket failures. */
78
+ function emit(message) {
79
+ if (disposed || emitterBroken)
80
+ return;
81
+ try {
82
+ emitter.send(JSON.stringify(message));
83
+ }
84
+ catch {
85
+ emitterBroken = true;
86
+ }
87
+ }
88
+ function shouldSuppressOutput() {
89
+ return disposed || emitterBroken;
90
+ }
91
+ function emitResponse(request, message) {
92
+ if (request.expectsResponse)
93
+ emit(message);
94
+ }
95
+ // AUDIT-EXEMPT: stateful WebSocket session lifecycle primitive. Listed in
96
+ // `src/server/operation-catalog/dispatch-allowlist.ts`. The cataloged
97
+ // `weft.workflows.events` subscription operation (introduced in PR 3) will
98
+ // route through `executeSubscription`; this handler remains the lifecycle
99
+ // wrapper.
100
+ async function handleSubscribe(request, params) {
101
+ const validation = validateSubscribeParams(params);
102
+ if (!validation.ok) {
103
+ emitResponse(request, {
104
+ jsonrpc: JSON_RPC_VERSION,
105
+ error: validation.error,
106
+ id: request.id ?? null,
107
+ });
108
+ return;
109
+ }
110
+ await startSubscription(request, (signal) => startLegacySubscription(request, executeSubscription(WORKFLOW_EVENTS_OPERATION_NAME, {
111
+ workflowId: validation.workflowId,
112
+ selector: validation.selector,
113
+ ...(validation.fromCursor === undefined ? {} : { fromCursor: validation.fromCursor }),
114
+ }, {
115
+ principal,
116
+ host: { feed },
117
+ // Subscribe is a session primitive, but the transport identity still
118
+ // needs to reflect the adapter reusing this implementation so
119
+ // availability checks enforce stdio-only and websocket-only policies.
120
+ transport,
121
+ registry,
122
+ signal,
123
+ })), acquireWorkflowSubscription);
124
+ }
125
+ async function handleFleetSubscribe(request, params) {
126
+ await startSubscription(request, (signal) => startLegacySubscription(request, executeSubscription(FLEET_EVENTS_OPERATION_NAME, params ?? {}, {
127
+ principal,
128
+ host: { fleetFeed },
129
+ transport,
130
+ registry,
131
+ signal,
132
+ })), acquireFleetSubscription);
133
+ }
134
+ async function startSubscription(request, execute, acquire) {
135
+ if (subscriptions.size >= maxSubscriptions) {
136
+ emitResponse(request, {
137
+ jsonrpc: JSON_RPC_VERSION,
138
+ error: {
139
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
140
+ message: `maximum concurrent subscriptions per session (${maxSubscriptions}) exceeded`,
141
+ data: faultErrorData('Unprocessable', {
142
+ reason: 'per-session subscription cap exceeded',
143
+ }),
144
+ },
145
+ id: request.id ?? null,
146
+ });
147
+ return;
148
+ }
149
+ const controller = new AbortController();
150
+ const pending = { controller };
151
+ pendingSubscriptions.add(pending);
152
+ let result;
153
+ try {
154
+ result = await execute(controller.signal);
155
+ }
156
+ finally {
157
+ pendingSubscriptions.delete(pending);
158
+ }
159
+ if (result.subscription === undefined) {
160
+ if (result.response !== undefined)
161
+ emitResponse(request, result.response);
162
+ return;
163
+ }
164
+ const { subscriptionId, iterable, close: closeSubscription } = result.subscription;
165
+ let closeStarted = false;
166
+ const closeOnce = async () => {
167
+ if (closeStarted)
168
+ return;
169
+ closeStarted = true;
170
+ await closeSubscription();
171
+ };
172
+ if (requiresSubscriptionClose(disposed, controller.signal)) {
173
+ await closeSubscriptionAfterClose(closeOnce);
174
+ return;
175
+ }
176
+ const lease = acquireSubscriptionLease(acquire);
177
+ if (result.response !== undefined)
178
+ emitResponse(request, result.response);
179
+ const pump = pumpSubscriptionIterable({
180
+ subscriptionId,
181
+ iterable,
182
+ signal: controller.signal,
183
+ closeSubscription: closeOnce,
184
+ shouldSuppressOutput,
185
+ emit,
186
+ onComplete: () => {
187
+ releaseSubscriptionLease(lease);
188
+ subscriptions.delete(subscriptionId);
189
+ },
190
+ });
191
+ subscriptions.set(subscriptionId, {
192
+ id: subscriptionId,
193
+ controller,
194
+ pump,
195
+ isTerminating: false,
196
+ });
197
+ }
198
+ // AUDIT-EXEMPT: stateful WebSocket session lifecycle primitive. Listed in
199
+ // `src/server/operation-catalog/dispatch-allowlist.ts`. The cataloged
200
+ // `weft.workflows.events` subscription operation (introduced in PR 3) will
201
+ // route through `executeSubscription`; this handler remains the lifecycle
202
+ // wrapper.
203
+ function handleUnsubscribe(request, params) {
204
+ const subscriptionId = params?.['subscriptionId'];
205
+ if (typeof subscriptionId !== 'string') {
206
+ emitResponse(request, {
207
+ jsonrpc: JSON_RPC_VERSION,
208
+ error: {
209
+ code: JSON_RPC_ERROR_CODES.INVALID_PARAMS,
210
+ message: 'params.subscriptionId must be a string',
211
+ data: faultErrorData('InvalidParams'),
212
+ },
213
+ id: request.id ?? null,
214
+ });
215
+ return;
216
+ }
217
+ const active = subscriptions.get(subscriptionId);
218
+ if (!active || active.isTerminating) {
219
+ emitResponse(request, {
220
+ jsonrpc: JSON_RPC_VERSION,
221
+ error: {
222
+ code: JSON_RPC_ERROR_CODES.NOT_FOUND,
223
+ message: 'subscription not found',
224
+ data: faultErrorData('NotFound', {
225
+ resource: 'subscription',
226
+ identifier: subscriptionId,
227
+ }),
228
+ },
229
+ id: request.id ?? null,
230
+ });
231
+ return;
232
+ }
233
+ active.isTerminating = true;
234
+ active.controller.abort();
235
+ // Success response (empty result per spec — the side-effect IS
236
+ // the termination notification that follows).
237
+ emitResponse(request, { jsonrpc: JSON_RPC_VERSION, result: {}, id: request.id ?? null });
238
+ emit({
239
+ jsonrpc: JSON_RPC_VERSION,
240
+ method: SESSION_METHODS.TERMINATED,
241
+ params: { subscriptionId, reason: 'client-unsubscribed' },
242
+ });
243
+ }
244
+ async function handleSessionPrimitive(validation) {
245
+ const sessionPrimitiveError = validateSessionPrimitiveFrame(validation);
246
+ if (sessionPrimitiveError !== null) {
247
+ emit({
248
+ jsonrpc: JSON_RPC_VERSION,
249
+ error: sessionPrimitiveError.error,
250
+ id: sessionPrimitiveError.id,
251
+ });
252
+ return;
253
+ }
254
+ const request = {
255
+ id: validation.id,
256
+ expectsResponse: validation.hasRequestId,
257
+ };
258
+ if (validation.method === SESSION_METHODS.SUBSCRIBE ||
259
+ validation.method === WORKFLOW_EVENTS_OPERATION_NAME) {
260
+ await handleSubscribe(request, validation.params);
261
+ }
262
+ else if (validation.method === SESSION_METHODS.FLEET_SUBSCRIBE) {
263
+ await handleFleetSubscribe(request, validation.params);
264
+ }
265
+ else {
266
+ handleUnsubscribe(request, validation.params);
267
+ }
268
+ }
269
+ async function handleCatalogMethod(validation) {
270
+ if (isSessionPrimitive(validation.method)) {
271
+ const feedDependentPrimitive = validation.method === SESSION_METHODS.SUBSCRIBE ||
272
+ validation.method === WORKFLOW_EVENTS_OPERATION_NAME;
273
+ if (feed === undefined && feedDependentPrimitive) {
274
+ return false;
275
+ }
276
+ await handleSessionPrimitive(validation);
277
+ return true;
278
+ }
279
+ const method = validation.method;
280
+ if (typeof method === 'string' && registry.get(method)?.kind === 'subscription') {
281
+ const request = {
282
+ id: validation.id,
283
+ expectsResponse: validation.hasRequestId,
284
+ };
285
+ const parsed = parseJsonRpcRequest(validation.parsed);
286
+ if (parsed.kind === 'invalid-request') {
287
+ emit({
288
+ jsonrpc: JSON_RPC_VERSION,
289
+ error: { code: parsed.code, message: parsed.message },
290
+ id: parsed.id,
291
+ });
292
+ return true;
293
+ }
294
+ await startSubscription(request, async (signal) => {
295
+ let subscription;
296
+ const result = await dispatchJsonRpc(validation.parsed, {
297
+ registry,
298
+ host: engine,
299
+ principal,
300
+ transport,
301
+ signal,
302
+ acceptSubscription(started) {
303
+ subscription = started;
304
+ },
305
+ });
306
+ return {
307
+ ...(subscription === undefined ? {} : { subscription }),
308
+ ...(result.kind === 'single' ? { response: result.response } : {}),
309
+ };
310
+ });
311
+ return true;
312
+ }
313
+ return false;
314
+ }
315
+ async function handleMessage(frame) {
316
+ if (disposed || emitterBroken)
317
+ return;
318
+ const validation = validateMessageFrame(frame, maxFrameBytes);
319
+ if (!validation.ok) {
320
+ emit({
321
+ jsonrpc: JSON_RPC_VERSION,
322
+ error: validation.error,
323
+ id: validation.id,
324
+ });
325
+ return;
326
+ }
327
+ if (await handleCatalogMethod(validation))
328
+ return;
329
+ await dispatchStandard(validation);
330
+ }
331
+ async function dispatchStandard(validation) {
332
+ // Standard dispatch — the dispatcher handles parse-error / invalid-
333
+ // request / notification elision / success / error mapping.
334
+ const result = await dispatchJsonRpc(validation.parsed, {
335
+ registry,
336
+ host: engine,
337
+ principal,
338
+ transport,
339
+ ...(discoverDocument === undefined ? {} : { discoverDocument }),
340
+ });
341
+ if (result.kind === 'single') {
342
+ emit(result.response);
343
+ }
344
+ // Notifications over WS are fire-and-forget (no response frame).
345
+ // Batch / notification-batch paths are unreachable because we rejected arrays above.
346
+ }
347
+ async function close() {
348
+ if (disposed)
349
+ return;
350
+ disposed = true;
351
+ const pendingCloses = [];
352
+ for (const sub of subscriptions.values()) {
353
+ sub.controller.abort();
354
+ pendingCloses.push(sub.pump.catch(() => { }));
355
+ }
356
+ for (const pending of pendingSubscriptions) {
357
+ pending.controller.abort();
358
+ }
359
+ subscriptions.clear();
360
+ await Promise.all(pendingCloses);
361
+ }
362
+ return { handleMessage, close };
363
+ }
@@ -0,0 +1,5 @@
1
+ /** Orders two strings by code unit, so sorted output is the same in every locale. */
2
+ export declare function compareStrings(left: string, right: string): number;
3
+ export declare function asPlainObject(value: unknown): Record<string, unknown>;
4
+ export declare function normalizeJsonObject(value: unknown): Record<string, unknown>;
5
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,17 @@
1
+ import { canonicalJson } from "./openapi-canonical-json.js";
2
+ /** Orders two strings by code unit, so sorted output is the same in every locale. */
3
+ export function compareStrings(left, right) {
4
+ return left < right ? -1 : left > right ? 1 : 0;
5
+ }
6
+ export function asPlainObject(value) {
7
+ if (isPlainObject(value))
8
+ return value;
9
+ return {};
10
+ }
11
+ export function normalizeJsonObject(value) {
12
+ const parsed = JSON.parse(canonicalJson(value));
13
+ return asPlainObject(parsed);
14
+ }
15
+ export function isPlainObject(value) {
16
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
17
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The two names an OpenRPC document gives an MCP-aware server: where its MCP discovery document is
3
+ * served and which MCP method lists its tools. Constants only, so the document generators need not
4
+ * import the MCP discovery generator.
5
+ *
6
+ * @module server/mcp-discovery-names
7
+ */
8
+ /** Root-stable discovery document path (RFC 9264 / well-known convention). */
9
+ export declare const MCP_DISCOVERY_PATH = "/.well-known/mcp.json";
10
+ /** MCP method used for live tool introspection. */
11
+ export declare const MCP_TOOLS_LIST_METHOD = "tools/list";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The two names an OpenRPC document gives an MCP-aware server: where its MCP discovery document is
3
+ * served and which MCP method lists its tools. Constants only, so the document generators need not
4
+ * import the MCP discovery generator.
5
+ *
6
+ * @module server/mcp-discovery-names
7
+ */
8
+ /** Root-stable discovery document path (RFC 9264 / well-known convention). */
9
+ export const MCP_DISCOVERY_PATH = '/.well-known/mcp.json';
10
+ /** MCP method used for live tool introspection. */
11
+ export const MCP_TOOLS_LIST_METHOD = 'tools/list';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Canonical JSON utilities for OpenAPI schema deduplication.
3
+ *
4
+ * @module server/openapi-canonical-json
5
+ */
6
+ /**
7
+ * Produce a stable JSON string with object keys sorted recursively and array
8
+ * order preserved.
9
+ */
10
+ export declare function canonicalJson(value: unknown): string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Canonical JSON utilities for OpenAPI schema deduplication.
3
+ *
4
+ * @module server/openapi-canonical-json
5
+ */
6
+ /**
7
+ * Produce a stable JSON string with object keys sorted recursively and array
8
+ * order preserved.
9
+ */
10
+ export function canonicalJson(value) {
11
+ return JSON.stringify(sortKeys(value));
12
+ }
13
+ function sortKeys(value) {
14
+ if (value === null || typeof value !== 'object')
15
+ return value;
16
+ if (Array.isArray(value))
17
+ return value.map(sortKeys);
18
+ const sorted = {};
19
+ for (const [key, entry] of Object.entries(value).toSorted(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)) {
20
+ sorted[key] = sortKeys(entry);
21
+ }
22
+ return sorted;
23
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * OpenAPI response helpers for catalogued operation faults.
3
+ *
4
+ * @module server/openapi-error-responses
5
+ */
6
+ import type { ErasedOperation } from "./operation-catalog.js";
7
+ /**
8
+ * Shared JSON error schema emitted as `#/components/schemas/Error`.
9
+ */
10
+ export declare const ERROR_SCHEMA: Record<string, unknown>;
11
+ /**
12
+ * Build OpenAPI error responses for an operation's declared producible faults
13
+ * plus the universal pipeline fault defaults.
14
+ */
15
+ export declare function buildErrorResponses(operation: ErasedOperation): Record<string, unknown>;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * OpenAPI response helpers for catalogued operation faults.
3
+ *
4
+ * @module server/openapi-error-responses
5
+ */
6
+ import { MAX_REMEDIATION_LENGTH } from "./fault-remediation.js";
7
+ import { UNIVERSAL_FAULT_DEFAULTS } from "./operation-catalog/universal-faults.js";
8
+ import { FAULT_CODE_TO_HTTP_STATUS } from "./operation-fault.js";
9
+ /**
10
+ * Shared JSON error schema emitted as `#/components/schemas/Error`.
11
+ */
12
+ export const ERROR_SCHEMA = {
13
+ type: 'object',
14
+ required: ['error'],
15
+ additionalProperties: false,
16
+ properties: {
17
+ error: { type: 'string', description: 'Human-readable error description' },
18
+ weftCode: {
19
+ type: 'string',
20
+ description: 'Fine-grained public Weft error code when one is available',
21
+ },
22
+ retryable: {
23
+ type: 'boolean',
24
+ description: 'Whether repeating the identical call later can succeed; present on every operation fault',
25
+ },
26
+ remediation: {
27
+ type: 'string',
28
+ minLength: 1,
29
+ maxLength: MAX_REMEDIATION_LENGTH,
30
+ description: 'One line of plain text saying what to do next; omitted when none is known',
31
+ },
32
+ data: {
33
+ type: 'object',
34
+ description: 'Audited fault-specific context; omitted when no fields are safe to expose',
35
+ additionalProperties: false,
36
+ properties: {
37
+ resource: { type: 'string' },
38
+ identifier: { type: 'string' },
39
+ missingTypes: { type: 'array', items: { type: 'string' } },
40
+ missingWorkflowCount: { type: 'integer', minimum: 0 },
41
+ samplesTruncated: { type: 'boolean' },
42
+ maxBytes: { type: 'integer', minimum: 0 },
43
+ operationName: { type: 'string' },
44
+ updateId: { type: 'string' },
45
+ transport: { type: 'string' },
46
+ supported: { type: 'array', items: { type: 'string' } },
47
+ droppedCount: { type: 'integer', minimum: 0 },
48
+ issues: {
49
+ type: 'array',
50
+ items: {
51
+ type: 'object',
52
+ required: ['path', 'message', 'code'],
53
+ additionalProperties: false,
54
+ properties: {
55
+ path: {
56
+ type: 'array',
57
+ items: { oneOf: [{ type: 'string' }, { type: 'number' }] },
58
+ },
59
+ message: { type: 'string' },
60
+ code: { type: 'string' },
61
+ },
62
+ },
63
+ },
64
+ method: { type: 'string' },
65
+ expectedRevision: { oneOf: [{ type: 'string' }, { type: 'number' }] },
66
+ currentRevision: { oneOf: [{ type: 'string' }, { type: 'number' }] },
67
+ retryAfterSeconds: { type: 'number', minimum: 0 },
68
+ capability: { type: 'string' },
69
+ },
70
+ },
71
+ },
72
+ };
73
+ /**
74
+ * Build OpenAPI error responses for an operation's declared producible faults
75
+ * plus the universal pipeline fault defaults.
76
+ */
77
+ export function buildErrorResponses(operation) {
78
+ const codes = new Set([
79
+ ...UNIVERSAL_FAULT_DEFAULTS,
80
+ ...(operation.producibleFaults ?? []),
81
+ ]);
82
+ const codesByStatus = new Map();
83
+ for (const code of codes) {
84
+ const status = String(FAULT_CODE_TO_HTTP_STATUS[code]);
85
+ const existingCodes = codesByStatus.get(status);
86
+ if (existingCodes === undefined) {
87
+ codesByStatus.set(status, [code]);
88
+ continue;
89
+ }
90
+ existingCodes.push(code);
91
+ }
92
+ const responses = {};
93
+ for (const [status, statusCodes] of [...codesByStatus.entries()].toSorted(([left], [right]) => Number(left) - Number(right))) {
94
+ responses[status] = {
95
+ description: statusCodes.toSorted().join(', '),
96
+ content: {
97
+ 'application/json': {
98
+ schema: { $ref: '#/components/schemas/Error' },
99
+ },
100
+ },
101
+ };
102
+ }
103
+ return responses;
104
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * JSON Schema extraction and component deduplication for OpenAPI documents.
3
+ *
4
+ * @module server/openapi-schemas
5
+ */
6
+ import type { OperationRegistry } from "./operation-catalog.js";
7
+ /** Schema slots owned by an operation definition. */
8
+ export type OpenApiSchemaSlot = 'Input' | 'Output' | 'Event';
9
+ export type OpenApiSchemaHelper = {
10
+ readonly components: Record<string, unknown>;
11
+ refFor(operationName: string, slot: OpenApiSchemaSlot): unknown;
12
+ };
13
+ /**
14
+ * Extract JSON Schemas for every discoverable operation and hoist duplicate
15
+ * schemas into `components.schemas` using canonical-JSON equality.
16
+ */
17
+ export declare function extractComponentsSchemas(registry: OperationRegistry): OpenApiSchemaHelper;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * JSON Schema extraction and component deduplication for OpenAPI documents.
3
+ *
4
+ * @module server/openapi-schemas
5
+ */
6
+ import { z } from 'zod';
7
+ import { isDiscoverable } from "./discovery-filter.js";
8
+ import { compareStrings, normalizeJsonObject } from "./json-schema-utilities.js";
9
+ import { canonicalJson } from "./openapi-canonical-json.js";
10
+ import { zodToJsonSchema } from "./zod-json-schema.js";
11
+ /**
12
+ * Extract JSON Schemas for every discoverable operation and hoist duplicate
13
+ * schemas into `components.schemas` using canonical-JSON equality.
14
+ */
15
+ export function extractComponentsSchemas(registry) {
16
+ const byCanonical = new Map();
17
+ const operationSlotToCanonical = new Map();
18
+ for (const operation of registry.list()) {
19
+ if (!isDiscoverable(operation))
20
+ continue;
21
+ const slots = [
22
+ ['Input', operation.inputSchema],
23
+ ['Output', operation.outputSchema],
24
+ ['Event', operation.eventSchema],
25
+ ];
26
+ for (const [slot, schema] of slots) {
27
+ if (schema === undefined)
28
+ continue;
29
+ const jsonSchema = zodToJsonSchema(schema, directionForSlot(slot));
30
+ const canonical = canonicalJson(jsonSchema);
31
+ const owner = { operationName: operation.name, slot };
32
+ operationSlotToCanonical.set(ownerKey(owner.operationName, owner.slot), canonical);
33
+ const existing = byCanonical.get(canonical);
34
+ if (existing === undefined) {
35
+ byCanonical.set(canonical, { schema: normalizeJsonObject(jsonSchema), owners: [owner] });
36
+ }
37
+ else {
38
+ existing.owners.push(owner);
39
+ }
40
+ }
41
+ }
42
+ const components = {};
43
+ const hoistedKeys = new Map();
44
+ const hoistCandidates = [...byCanonical.entries()]
45
+ .filter(([, entry]) => entry.owners.length >= 2)
46
+ .map(([canonical, entry]) => {
47
+ const firstOwner = [...entry.owners].toSorted(compareOwners)[0];
48
+ return {
49
+ canonical,
50
+ entry,
51
+ baseName: operationSlotToComponentName(firstOwner.operationName, firstOwner.slot),
52
+ };
53
+ })
54
+ .toSorted((left, right) => compareStrings(left.baseName, right.baseName) ||
55
+ compareStrings(left.canonical, right.canonical));
56
+ for (const candidate of hoistCandidates) {
57
+ let componentName = candidate.baseName;
58
+ let suffix = 2;
59
+ while (Object.hasOwn(components, componentName)) {
60
+ componentName = `${candidate.baseName}_${suffix}`;
61
+ suffix += 1;
62
+ }
63
+ components[componentName] = candidate.entry.schema;
64
+ hoistedKeys.set(candidate.canonical, componentName);
65
+ }
66
+ return {
67
+ components,
68
+ refFor(operationName, slot) {
69
+ const canonical = operationSlotToCanonical.get(ownerKey(operationName, slot));
70
+ if (canonical === undefined)
71
+ return undefined;
72
+ const componentName = hoistedKeys.get(canonical);
73
+ if (componentName !== undefined) {
74
+ return { $ref: `#/components/schemas/${componentName}` };
75
+ }
76
+ return byCanonical.get(canonical)?.schema;
77
+ },
78
+ };
79
+ }
80
+ function ownerKey(operationName, slot) {
81
+ return `${operationName}:${slot}`;
82
+ }
83
+ function directionForSlot(slot) {
84
+ return slot === 'Input' ? 'input' : 'output';
85
+ }
86
+ function compareOwners(left, right) {
87
+ return (compareStrings(left.operationName, right.operationName) || compareStrings(left.slot, right.slot));
88
+ }
89
+ function operationSlotToComponentName(operationName, slot) {
90
+ return (operationName
91
+ .split('.')
92
+ .map((segment) => `${segment.charAt(0).toUpperCase()}${segment.slice(1)}`)
93
+ .join('') + slot);
94
+ }