@enclave-vm/broker 0.0.1 → 2.8.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.
package/esm/index.mjs ADDED
@@ -0,0 +1,1569 @@
1
+ // libs/enclavejs-broker/src/tool-registry.ts
2
+ import { z } from "zod";
3
+ var ToolRegistry = class {
4
+ tools;
5
+ secretStore;
6
+ constructor() {
7
+ this.tools = /* @__PURE__ */ new Map();
8
+ this.secretStore = /* @__PURE__ */ new Map();
9
+ }
10
+ /**
11
+ * Register a tool
12
+ *
13
+ * @throws Error if tool with same name already exists
14
+ */
15
+ register(definition) {
16
+ if (this.tools.has(definition.name)) {
17
+ throw new Error(`Tool "${definition.name}" is already registered`);
18
+ }
19
+ const argsSchema = definition.argsSchema ?? z.record(z.string(), z.unknown());
20
+ this.tools.set(definition.name, {
21
+ definition,
22
+ argsSchema
23
+ });
24
+ }
25
+ /**
26
+ * Unregister a tool
27
+ *
28
+ * @returns true if tool was removed, false if not found
29
+ */
30
+ unregister(name) {
31
+ return this.tools.delete(name);
32
+ }
33
+ /**
34
+ * Check if a tool is registered
35
+ */
36
+ has(name) {
37
+ return this.tools.has(name);
38
+ }
39
+ /**
40
+ * Get a tool definition
41
+ */
42
+ get(name) {
43
+ return this.tools.get(name)?.definition;
44
+ }
45
+ /**
46
+ * List all registered tool names
47
+ */
48
+ list() {
49
+ return Array.from(this.tools.keys());
50
+ }
51
+ /**
52
+ * Get tool configurations for all registered tools
53
+ */
54
+ getConfigs() {
55
+ const configs = {};
56
+ for (const [name, tool] of this.tools) {
57
+ if (tool.definition.config) {
58
+ configs[name] = tool.definition.config;
59
+ }
60
+ }
61
+ return configs;
62
+ }
63
+ /**
64
+ * Validate tool arguments
65
+ */
66
+ validate(name, args) {
67
+ const tool = this.tools.get(name);
68
+ if (!tool) {
69
+ return {
70
+ success: false,
71
+ error: `Unknown tool: ${name}`
72
+ };
73
+ }
74
+ const result = tool.argsSchema.safeParse(args);
75
+ if (!result.success) {
76
+ return {
77
+ success: false,
78
+ error: `Invalid arguments: ${result.error.message}`
79
+ };
80
+ }
81
+ return {
82
+ success: true,
83
+ validatedArgs: result.data
84
+ };
85
+ }
86
+ /**
87
+ * Set a secret value
88
+ */
89
+ setSecret(key, value) {
90
+ this.secretStore.set(key, value);
91
+ }
92
+ /**
93
+ * Remove a secret
94
+ */
95
+ removeSecret(key) {
96
+ return this.secretStore.delete(key);
97
+ }
98
+ /**
99
+ * Check if a secret exists
100
+ */
101
+ hasSecret(key) {
102
+ return this.secretStore.has(key);
103
+ }
104
+ /**
105
+ * Get required secrets for a tool
106
+ */
107
+ getRequiredSecrets(name) {
108
+ const tool = this.tools.get(name);
109
+ return tool?.definition.secrets ?? [];
110
+ }
111
+ /**
112
+ * Resolve secrets for a tool
113
+ *
114
+ * @throws Error if required secret is missing
115
+ */
116
+ resolveSecrets(name) {
117
+ const requiredSecrets = this.getRequiredSecrets(name);
118
+ const resolved = {};
119
+ for (const key of requiredSecrets) {
120
+ const value = this.secretStore.get(key);
121
+ if (value === void 0) {
122
+ throw new Error(`Missing required secret "${key}" for tool "${name}"`);
123
+ }
124
+ resolved[key] = value;
125
+ }
126
+ return resolved;
127
+ }
128
+ /**
129
+ * Execute a tool
130
+ */
131
+ async execute(name, args, context) {
132
+ const startTime = Date.now();
133
+ const tool = this.tools.get(name);
134
+ if (!tool) {
135
+ return {
136
+ success: false,
137
+ error: {
138
+ code: "UNKNOWN_TOOL",
139
+ message: `Unknown tool: ${name}`
140
+ },
141
+ durationMs: Date.now() - startTime
142
+ };
143
+ }
144
+ const validation = this.validate(name, args);
145
+ if (!validation.success) {
146
+ return {
147
+ success: false,
148
+ error: {
149
+ code: "VALIDATION_ERROR",
150
+ message: validation.error
151
+ },
152
+ durationMs: Date.now() - startTime
153
+ };
154
+ }
155
+ let secrets;
156
+ try {
157
+ secrets = this.resolveSecrets(name);
158
+ } catch (error) {
159
+ return {
160
+ success: false,
161
+ error: {
162
+ code: "SECRET_ERROR",
163
+ message: error instanceof Error ? error.message : "Failed to resolve secrets"
164
+ },
165
+ durationMs: Date.now() - startTime
166
+ };
167
+ }
168
+ try {
169
+ const result = await tool.definition.handler(validation.validatedArgs, {
170
+ ...context,
171
+ secrets
172
+ });
173
+ return {
174
+ success: true,
175
+ value: result,
176
+ durationMs: Date.now() - startTime
177
+ };
178
+ } catch (error) {
179
+ const err = error;
180
+ return {
181
+ success: false,
182
+ error: {
183
+ code: err.code ?? "EXECUTION_ERROR",
184
+ message: err.message
185
+ },
186
+ durationMs: Date.now() - startTime
187
+ };
188
+ }
189
+ }
190
+ /**
191
+ * Clear all registered tools
192
+ */
193
+ clear() {
194
+ this.tools.clear();
195
+ }
196
+ /**
197
+ * Clear all secrets
198
+ */
199
+ clearSecrets() {
200
+ this.secretStore.clear();
201
+ }
202
+ /**
203
+ * Get count of registered tools
204
+ */
205
+ get size() {
206
+ return this.tools.size;
207
+ }
208
+ };
209
+ function createToolRegistry() {
210
+ return new ToolRegistry();
211
+ }
212
+
213
+ // libs/enclavejs-broker/src/broker-session.ts
214
+ import { generateSessionId, generateCallId, DEFAULT_SESSION_LIMITS } from "@enclave-vm/types";
215
+ import { createSessionEmitter, Enclave } from "@enclave-vm/core";
216
+ var BrokerSession = class {
217
+ sessionId;
218
+ createdAt;
219
+ expiresAt;
220
+ emitter;
221
+ toolRegistry;
222
+ enclave;
223
+ abortController;
224
+ limits;
225
+ _state = "starting";
226
+ executionPromise = null;
227
+ toolCallCount = 0;
228
+ stdoutBytes = 0;
229
+ heartbeatInterval = null;
230
+ constructor(toolRegistry, config = {}) {
231
+ this.sessionId = config.sessionId ?? generateSessionId();
232
+ this.createdAt = Date.now();
233
+ this.toolRegistry = toolRegistry;
234
+ this.abortController = new AbortController();
235
+ this.limits = {
236
+ ...DEFAULT_SESSION_LIMITS,
237
+ ...config.limits
238
+ };
239
+ this.expiresAt = this.createdAt + this.limits.sessionTtlMs;
240
+ this.emitter = createSessionEmitter(this.sessionId, {
241
+ expiresAt: new Date(this.expiresAt)
242
+ });
243
+ this.enclave = new Enclave({
244
+ ...config.enclaveConfig,
245
+ timeout: this.limits.toolTimeoutMs,
246
+ maxToolCalls: this.limits.maxToolCalls
247
+ });
248
+ }
249
+ /**
250
+ * Get current session state
251
+ */
252
+ get state() {
253
+ return this._state;
254
+ }
255
+ /**
256
+ * Get current sequence number
257
+ */
258
+ get seq() {
259
+ return this.emitter.getSeq();
260
+ }
261
+ /**
262
+ * Get the event emitter
263
+ */
264
+ get events() {
265
+ return this.emitter;
266
+ }
267
+ /**
268
+ * Subscribe to stream events
269
+ */
270
+ onEvent(handler) {
271
+ return this.emitter.on(handler);
272
+ }
273
+ /**
274
+ * Get all emitted events
275
+ */
276
+ getEvents() {
277
+ return this.emitter.getEmittedEvents();
278
+ }
279
+ /**
280
+ * Execute code in this session
281
+ *
282
+ * @param code - Code to execute
283
+ * @returns Promise that resolves when execution completes
284
+ */
285
+ async execute(code) {
286
+ if (this.executionPromise) {
287
+ throw new Error("Session is already executing");
288
+ }
289
+ this.emitter.emitSessionInit();
290
+ const heartbeatMs = this.limits.heartbeatIntervalMs;
291
+ if (heartbeatMs > 0) {
292
+ this.heartbeatInterval = setInterval(() => {
293
+ if (!this.isTerminal()) {
294
+ this.emitter.emitHeartbeat();
295
+ }
296
+ }, heartbeatMs);
297
+ }
298
+ this._state = "running";
299
+ this.executionPromise = this.runExecution(code);
300
+ return this.executionPromise;
301
+ }
302
+ /**
303
+ * Run the actual execution
304
+ */
305
+ async runExecution(code) {
306
+ const startTime = Date.now();
307
+ let result;
308
+ try {
309
+ const enclaveResult = await this.enclave.run(code, async (toolName, args) => {
310
+ if (this.abortController.signal.aborted) {
311
+ throw new Error("Session cancelled");
312
+ }
313
+ return this.executeTool(toolName, args);
314
+ });
315
+ const endTime = Date.now();
316
+ const stats = this.buildStats(startTime, endTime);
317
+ if (enclaveResult.success) {
318
+ this._state = "completed";
319
+ this.emitter.emitFinalSuccess(enclaveResult.value, {
320
+ durationMs: stats.duration,
321
+ toolCallCount: this.toolCallCount,
322
+ stdoutBytes: this.stdoutBytes
323
+ });
324
+ result = {
325
+ success: true,
326
+ value: enclaveResult.value,
327
+ stats,
328
+ finalState: "completed"
329
+ };
330
+ } else {
331
+ this._state = "failed";
332
+ const errorInfo = {
333
+ code: enclaveResult.error?.code ?? "EXECUTION_ERROR",
334
+ message: enclaveResult.error?.message ?? "Execution failed"
335
+ };
336
+ this.emitter.emitFinalError(errorInfo, {
337
+ durationMs: stats.duration,
338
+ toolCallCount: this.toolCallCount,
339
+ stdoutBytes: this.stdoutBytes
340
+ });
341
+ result = {
342
+ success: false,
343
+ error: {
344
+ message: errorInfo.message,
345
+ name: enclaveResult.error?.name ?? "Error",
346
+ code: errorInfo.code
347
+ },
348
+ stats,
349
+ finalState: "failed"
350
+ };
351
+ }
352
+ } catch (error) {
353
+ const endTime = Date.now();
354
+ const stats = this.buildStats(startTime, endTime);
355
+ const err = error instanceof Error ? error : new Error(String(error));
356
+ this._state = "failed";
357
+ const errorInfo = {
358
+ code: err.code ?? "EXECUTION_ERROR",
359
+ message: err.message
360
+ };
361
+ this.emitter.emitFinalError(errorInfo, {
362
+ durationMs: stats.duration,
363
+ toolCallCount: this.toolCallCount,
364
+ stdoutBytes: this.stdoutBytes
365
+ });
366
+ result = {
367
+ success: false,
368
+ error: {
369
+ message: err.message,
370
+ name: err.name,
371
+ code: errorInfo.code
372
+ },
373
+ stats,
374
+ finalState: "failed"
375
+ };
376
+ } finally {
377
+ this.stopHeartbeat();
378
+ }
379
+ return result;
380
+ }
381
+ /**
382
+ * Execute a tool call directly
383
+ */
384
+ async executeTool(toolName, args) {
385
+ const callId = generateCallId();
386
+ this.emitter.emitToolCall(callId, toolName, args);
387
+ this.toolCallCount++;
388
+ const context = {
389
+ sessionId: this.sessionId,
390
+ callId,
391
+ secrets: {},
392
+ // Resolved by registry
393
+ signal: this.abortController.signal
394
+ };
395
+ const result = await this.toolRegistry.execute(toolName, args, context);
396
+ this.emitter.emitToolResultApplied(callId);
397
+ if (result.success) {
398
+ return result.value;
399
+ } else {
400
+ const error = new Error(result.error?.message ?? "Tool call failed");
401
+ error.code = result.error?.code;
402
+ throw error;
403
+ }
404
+ }
405
+ /**
406
+ * Build execution stats
407
+ */
408
+ buildStats(startTime, endTime) {
409
+ return {
410
+ duration: endTime - startTime,
411
+ toolCallCount: this.toolCallCount,
412
+ iterationCount: 0,
413
+ startTime,
414
+ endTime
415
+ };
416
+ }
417
+ /**
418
+ * Cancel the session
419
+ */
420
+ async cancel(reason) {
421
+ if (this.isTerminal()) {
422
+ return;
423
+ }
424
+ this.stopHeartbeat();
425
+ this.abortController.abort();
426
+ this._state = "cancelled";
427
+ this.emitter.emitError("SESSION_CANCELLED", reason ?? "Session was cancelled", false);
428
+ this.emitter.emitFinalError(
429
+ { code: "SESSION_CANCELLED", message: reason ?? "Session was cancelled" },
430
+ {
431
+ durationMs: Date.now() - this.createdAt,
432
+ toolCallCount: this.toolCallCount,
433
+ stdoutBytes: this.stdoutBytes
434
+ }
435
+ );
436
+ }
437
+ /**
438
+ * Wait for the session to complete
439
+ */
440
+ async wait() {
441
+ if (this.executionPromise) {
442
+ return this.executionPromise;
443
+ }
444
+ throw new Error("Session has not started execution");
445
+ }
446
+ /**
447
+ * Check if session is expired
448
+ */
449
+ isExpired() {
450
+ return Date.now() > this.expiresAt;
451
+ }
452
+ /**
453
+ * Check if session is in terminal state
454
+ */
455
+ isTerminal() {
456
+ return this._state === "completed" || this._state === "cancelled" || this._state === "failed";
457
+ }
458
+ /**
459
+ * Get session statistics
460
+ */
461
+ getStats() {
462
+ const now = Date.now();
463
+ return {
464
+ duration: this.isTerminal() ? now - this.createdAt : now - this.createdAt,
465
+ toolCallCount: this.toolCallCount,
466
+ iterationCount: 0,
467
+ startTime: this.createdAt,
468
+ endTime: this.isTerminal() ? now : 0
469
+ };
470
+ }
471
+ /**
472
+ * Stop heartbeat timer
473
+ */
474
+ stopHeartbeat() {
475
+ if (this.heartbeatInterval) {
476
+ clearInterval(this.heartbeatInterval);
477
+ this.heartbeatInterval = null;
478
+ }
479
+ }
480
+ /**
481
+ * Dispose of the session and its resources
482
+ */
483
+ dispose() {
484
+ this.stopHeartbeat();
485
+ this.abortController.abort();
486
+ this.enclave.dispose();
487
+ }
488
+ };
489
+ function createBrokerSession(toolRegistry, config) {
490
+ return new BrokerSession(toolRegistry, config);
491
+ }
492
+
493
+ // libs/enclavejs-broker/src/session-manager.ts
494
+ var SessionManager = class {
495
+ sessions;
496
+ toolRegistry;
497
+ config;
498
+ cleanupInterval = null;
499
+ disposed = false;
500
+ constructor(toolRegistry, config = {}) {
501
+ this.sessions = /* @__PURE__ */ new Map();
502
+ this.toolRegistry = toolRegistry;
503
+ this.config = {
504
+ maxSessions: config.maxSessions ?? 100,
505
+ cleanupIntervalMs: config.cleanupIntervalMs ?? 6e4,
506
+ defaultSessionConfig: config.defaultSessionConfig ?? {}
507
+ };
508
+ this.startCleanup();
509
+ }
510
+ /**
511
+ * Create a new session
512
+ *
513
+ * @throws Error if max sessions reached or manager is disposed
514
+ */
515
+ create(config) {
516
+ if (this.disposed) {
517
+ throw new Error("Session manager is disposed");
518
+ }
519
+ if (this.sessions.size >= this.config.maxSessions) {
520
+ throw new Error(
521
+ `Maximum sessions reached (${this.config.maxSessions}). Wait for existing sessions to complete or increase maxSessions.`
522
+ );
523
+ }
524
+ const sessionConfig = {
525
+ ...this.config.defaultSessionConfig,
526
+ ...config
527
+ };
528
+ const session = createBrokerSession(this.toolRegistry, sessionConfig);
529
+ this.sessions.set(session.sessionId, session);
530
+ return {
531
+ session,
532
+ sessionId: session.sessionId
533
+ };
534
+ }
535
+ /**
536
+ * Get a session by ID
537
+ */
538
+ get(sessionId) {
539
+ return this.sessions.get(sessionId);
540
+ }
541
+ /**
542
+ * Check if a session exists
543
+ */
544
+ has(sessionId) {
545
+ return this.sessions.has(sessionId);
546
+ }
547
+ /**
548
+ * List all sessions
549
+ */
550
+ list() {
551
+ return Array.from(this.sessions.values()).map((session) => ({
552
+ sessionId: session.sessionId,
553
+ state: session.state,
554
+ createdAt: session.createdAt,
555
+ expiresAt: session.expiresAt,
556
+ isExpired: session.isExpired()
557
+ }));
558
+ }
559
+ /**
560
+ * List active (non-terminal) sessions
561
+ */
562
+ listActive() {
563
+ return this.list().filter((info) => !["completed", "cancelled", "failed"].includes(info.state));
564
+ }
565
+ /**
566
+ * Terminate a session
567
+ */
568
+ async terminate(sessionId, reason) {
569
+ const session = this.sessions.get(sessionId);
570
+ if (!session) {
571
+ return false;
572
+ }
573
+ await session.cancel(reason ?? "Terminated by session manager");
574
+ session.dispose();
575
+ this.sessions.delete(sessionId);
576
+ return true;
577
+ }
578
+ /**
579
+ * Execute code in a new session and wait for completion
580
+ *
581
+ * This is a convenience method that creates a session, executes code,
582
+ * waits for completion, and cleans up.
583
+ */
584
+ async executeAndWait(code, config, eventHandler) {
585
+ const { session, sessionId } = this.create(config);
586
+ try {
587
+ if (eventHandler) {
588
+ session.onEvent(eventHandler);
589
+ }
590
+ const result = await session.execute(code);
591
+ return result;
592
+ } finally {
593
+ session.dispose();
594
+ this.sessions.delete(sessionId);
595
+ }
596
+ }
597
+ /**
598
+ * Get count of active sessions
599
+ */
600
+ get activeCount() {
601
+ return this.listActive().length;
602
+ }
603
+ /**
604
+ * Get total session count
605
+ */
606
+ get totalCount() {
607
+ return this.sessions.size;
608
+ }
609
+ /**
610
+ * Clean up expired and terminal sessions
611
+ */
612
+ cleanup() {
613
+ let cleaned = 0;
614
+ for (const [sessionId, session] of this.sessions) {
615
+ if (session.isExpired() || session.isTerminal()) {
616
+ session.dispose();
617
+ this.sessions.delete(sessionId);
618
+ cleaned++;
619
+ }
620
+ }
621
+ return cleaned;
622
+ }
623
+ /**
624
+ * Start automatic cleanup
625
+ */
626
+ startCleanup() {
627
+ if (this.cleanupInterval) {
628
+ return;
629
+ }
630
+ this.cleanupInterval = setInterval(() => {
631
+ this.cleanup();
632
+ }, this.config.cleanupIntervalMs);
633
+ }
634
+ /**
635
+ * Stop automatic cleanup
636
+ */
637
+ stopCleanup() {
638
+ if (this.cleanupInterval) {
639
+ clearInterval(this.cleanupInterval);
640
+ this.cleanupInterval = null;
641
+ }
642
+ }
643
+ /**
644
+ * Dispose of the manager and all sessions
645
+ */
646
+ async dispose() {
647
+ if (this.disposed) {
648
+ return;
649
+ }
650
+ this.disposed = true;
651
+ this.stopCleanup();
652
+ const promises = [];
653
+ for (const [_sessionId, session] of this.sessions) {
654
+ promises.push(
655
+ session.cancel("Session manager disposed").catch(() => {
656
+ })
657
+ );
658
+ session.dispose();
659
+ }
660
+ await Promise.all(promises);
661
+ this.sessions.clear();
662
+ }
663
+ };
664
+ function createSessionManager(toolRegistry, config) {
665
+ return new SessionManager(toolRegistry, config);
666
+ }
667
+
668
+ // libs/enclavejs-broker/src/broker.ts
669
+ var Broker = class {
670
+ toolRegistry;
671
+ sessionManager;
672
+ config;
673
+ disposed = false;
674
+ constructor(config = {}) {
675
+ this.config = config;
676
+ this.toolRegistry = createToolRegistry();
677
+ this.sessionManager = createSessionManager(this.toolRegistry, {
678
+ ...config.sessions,
679
+ defaultSessionConfig: {
680
+ limits: config.limits,
681
+ enclaveConfig: config.enclave
682
+ }
683
+ });
684
+ }
685
+ // ============================================================================
686
+ // Tool Registration
687
+ // ============================================================================
688
+ /**
689
+ * Register a tool with the broker
690
+ *
691
+ * @param name - Tool name
692
+ * @param definition - Tool definition (handler, schema, secrets)
693
+ *
694
+ * @example
695
+ * ```typescript
696
+ * broker.tool('fetchUrl', {
697
+ * argsSchema: z.object({ url: z.string().url() }),
698
+ * secrets: ['API_KEY'],
699
+ * handler: async ({ url }, { secrets }) => {
700
+ * const response = await fetch(url, {
701
+ * headers: { Authorization: secrets.API_KEY },
702
+ * });
703
+ * return response.json();
704
+ * },
705
+ * });
706
+ * ```
707
+ */
708
+ tool(name, definition) {
709
+ this.toolRegistry.register({
710
+ name,
711
+ ...definition
712
+ });
713
+ return this;
714
+ }
715
+ /**
716
+ * Register multiple tools at once
717
+ */
718
+ tools(definitions) {
719
+ for (const [name, def] of Object.entries(definitions)) {
720
+ this.tool(name, def);
721
+ }
722
+ return this;
723
+ }
724
+ /**
725
+ * Check if a tool is registered
726
+ */
727
+ hasTool(name) {
728
+ return this.toolRegistry.has(name);
729
+ }
730
+ /**
731
+ * List all registered tool names
732
+ */
733
+ listTools() {
734
+ return this.toolRegistry.list();
735
+ }
736
+ /**
737
+ * Unregister a tool
738
+ */
739
+ removeTool(name) {
740
+ return this.toolRegistry.unregister(name);
741
+ }
742
+ // ============================================================================
743
+ // Secret Management
744
+ // ============================================================================
745
+ /**
746
+ * Set a secret value
747
+ *
748
+ * @param key - Secret key
749
+ * @param value - Secret value
750
+ *
751
+ * @example
752
+ * ```typescript
753
+ * broker.secret('API_KEY', process.env.API_KEY!);
754
+ * broker.secret('DATABASE_URL', process.env.DATABASE_URL!);
755
+ * ```
756
+ */
757
+ secret(key, value) {
758
+ this.toolRegistry.setSecret(key, value);
759
+ return this;
760
+ }
761
+ /**
762
+ * Set multiple secrets at once
763
+ */
764
+ secrets(values) {
765
+ for (const [key, value] of Object.entries(values)) {
766
+ this.secret(key, value);
767
+ }
768
+ return this;
769
+ }
770
+ /**
771
+ * Check if a secret exists
772
+ */
773
+ hasSecret(key) {
774
+ return this.toolRegistry.hasSecret(key);
775
+ }
776
+ /**
777
+ * Remove a secret
778
+ */
779
+ removeSecret(key) {
780
+ return this.toolRegistry.removeSecret(key);
781
+ }
782
+ // ============================================================================
783
+ // Session Management
784
+ // ============================================================================
785
+ /**
786
+ * Create a new session
787
+ *
788
+ * @param config - Session configuration
789
+ * @returns The created session
790
+ *
791
+ * @example
792
+ * ```typescript
793
+ * const session = broker.createSession({
794
+ * limits: { sessionTtlMs: 60000 },
795
+ * });
796
+ *
797
+ * session.onEvent((event) => {
798
+ * console.log('Event:', event.type);
799
+ * });
800
+ *
801
+ * const result = await session.execute('return await callTool("greet", { name: "World" })');
802
+ * ```
803
+ */
804
+ createSession(config) {
805
+ this.ensureNotDisposed();
806
+ return this.sessionManager.create(config).session;
807
+ }
808
+ /**
809
+ * Get a session by ID
810
+ */
811
+ getSession(sessionId) {
812
+ return this.sessionManager.get(sessionId);
813
+ }
814
+ /**
815
+ * List all sessions
816
+ */
817
+ listSessions() {
818
+ return this.sessionManager.list();
819
+ }
820
+ /**
821
+ * List active (non-terminal) sessions
822
+ */
823
+ listActiveSessions() {
824
+ return this.sessionManager.listActive();
825
+ }
826
+ /**
827
+ * Terminate a session
828
+ */
829
+ async terminateSession(sessionId, reason) {
830
+ return this.sessionManager.terminate(sessionId, reason);
831
+ }
832
+ // ============================================================================
833
+ // Quick Execution
834
+ // ============================================================================
835
+ /**
836
+ * Execute code and wait for result
837
+ *
838
+ * This is a convenience method that creates a session, executes code,
839
+ * streams events, and returns the final result.
840
+ *
841
+ * @param code - Code to execute
842
+ * @param options - Execution options
843
+ * @returns Final execution result
844
+ *
845
+ * @example
846
+ * ```typescript
847
+ * const result = await broker.execute(`
848
+ * const data = await callTool('fetchData', { id: 123 });
849
+ * return data.processed;
850
+ * `, {
851
+ * onEvent: (event) => console.log(event.type),
852
+ * });
853
+ *
854
+ * if (result.success) {
855
+ * console.log('Result:', result.value);
856
+ * }
857
+ * ```
858
+ */
859
+ async execute(code, options = {}) {
860
+ this.ensureNotDisposed();
861
+ return this.sessionManager.executeAndWait(code, options.session, options.onEvent);
862
+ }
863
+ // ============================================================================
864
+ // Statistics & Lifecycle
865
+ // ============================================================================
866
+ /**
867
+ * Get broker statistics
868
+ */
869
+ stats() {
870
+ return {
871
+ tools: this.toolRegistry.size,
872
+ activeSessions: this.sessionManager.activeCount,
873
+ totalSessions: this.sessionManager.totalCount
874
+ };
875
+ }
876
+ /**
877
+ * Clean up expired and completed sessions
878
+ */
879
+ cleanup() {
880
+ return this.sessionManager.cleanup();
881
+ }
882
+ /**
883
+ * Dispose of the broker and all resources
884
+ */
885
+ async dispose() {
886
+ if (this.disposed) {
887
+ return;
888
+ }
889
+ this.disposed = true;
890
+ await this.sessionManager.dispose();
891
+ this.toolRegistry.clear();
892
+ this.toolRegistry.clearSecrets();
893
+ }
894
+ /**
895
+ * Check if broker is disposed
896
+ */
897
+ get isDisposed() {
898
+ return this.disposed;
899
+ }
900
+ /**
901
+ * Ensure broker is not disposed
902
+ */
903
+ ensureNotDisposed() {
904
+ if (this.disposed) {
905
+ throw new Error("Broker is disposed");
906
+ }
907
+ }
908
+ };
909
+ function createBroker(config) {
910
+ return new Broker(config);
911
+ }
912
+
913
+ // libs/enclavejs-broker/src/event-filter.ts
914
+ import { FilterMode, PatternType, DEFAULT_ALWAYS_ALLOW } from "@enclave-vm/types";
915
+ import { minimatch } from "minimatch";
916
+ var MAX_REGEX_INPUT_LENGTH = 1e4;
917
+ var MAX_PATTERN_LENGTH_FOR_REDOS_CHECK = 500;
918
+ var REDOS_DETECTION_PATTERNS = {
919
+ /** Check for nested quantifiers: (a+)+ or (a*)* */
920
+ nestedQuantifiers: /\([^)]{0,100}[*+{][^)]{0,100}\)[*+{]/,
921
+ /** Check for alternation with overlapping patterns: (a|ab)* */
922
+ alternationOverlap: /\([^|]{0,100}\|[^)]{0,100}\)[*+{]/,
923
+ /** Check for repeated groups with quantifiers: (a+)+ */
924
+ repeatedGroups: /\([^)]{0,100}[*+][^)]{0,100}\)[*+]/
925
+ };
926
+ function isPotentiallyVulnerableRegex(pattern) {
927
+ const safePattern = pattern.length > MAX_PATTERN_LENGTH_FOR_REDOS_CHECK ? pattern.slice(0, MAX_PATTERN_LENGTH_FOR_REDOS_CHECK) : pattern;
928
+ try {
929
+ if (REDOS_DETECTION_PATTERNS.nestedQuantifiers.test(safePattern)) return true;
930
+ if (REDOS_DETECTION_PATTERNS.alternationOverlap.test(safePattern)) return true;
931
+ if (REDOS_DETECTION_PATTERNS.repeatedGroups.test(safePattern)) return true;
932
+ } catch {
933
+ return false;
934
+ }
935
+ return false;
936
+ }
937
+ var EventFilter = class {
938
+ config;
939
+ alwaysAllow;
940
+ compiledRegexes;
941
+ onError;
942
+ constructor(options) {
943
+ this.config = options.config;
944
+ this.onError = options.onError;
945
+ this.alwaysAllow = new Set(options.config.alwaysAllow ?? DEFAULT_ALWAYS_ALLOW);
946
+ this.compiledRegexes = /* @__PURE__ */ new Map();
947
+ this.compilePatterns();
948
+ }
949
+ /**
950
+ * Check if an event should be sent to the client.
951
+ */
952
+ shouldSend(event) {
953
+ if (this.alwaysAllow.has(event.type)) {
954
+ return true;
955
+ }
956
+ const matches = this.matchesAnyRule(event);
957
+ if (this.config.mode === FilterMode.Include) {
958
+ return matches;
959
+ } else {
960
+ return !matches;
961
+ }
962
+ }
963
+ /**
964
+ * Filter an array of events.
965
+ */
966
+ filter(events) {
967
+ return events.filter((event) => this.shouldSend(event));
968
+ }
969
+ /**
970
+ * Check if event matches any filter rule.
971
+ */
972
+ matchesAnyRule(event) {
973
+ return this.config.rules.some((rule) => this.matchesRule(event, rule));
974
+ }
975
+ /**
976
+ * Check if event matches a specific rule.
977
+ */
978
+ matchesRule(event, rule) {
979
+ const typeMatch = rule.types ? this.matchesTypeFilter(event, rule.types) : true;
980
+ const contentMatch = rule.content ? this.matchesContentFilter(event, rule.content) : true;
981
+ if (rule.types && rule.content) {
982
+ return typeMatch && contentMatch;
983
+ }
984
+ return rule.types ? typeMatch : contentMatch;
985
+ }
986
+ /**
987
+ * Check if event type matches filter.
988
+ */
989
+ matchesTypeFilter(event, filter) {
990
+ return filter.types.includes(event.type);
991
+ }
992
+ /**
993
+ * Check if event content matches filter.
994
+ */
995
+ matchesContentFilter(event, filter) {
996
+ const matchMode = filter.match ?? "any";
997
+ if (matchMode === "all") {
998
+ return filter.patterns.every((pattern) => this.matchesPattern(event, pattern));
999
+ } else {
1000
+ return filter.patterns.some((pattern) => this.matchesPattern(event, pattern));
1001
+ }
1002
+ }
1003
+ /**
1004
+ * Check if event matches a content pattern.
1005
+ */
1006
+ matchesPattern(event, pattern) {
1007
+ const value = this.getFieldValue(event, pattern.field);
1008
+ if (value === void 0) {
1009
+ return false;
1010
+ }
1011
+ const stringValue = this.stringify(value);
1012
+ const patternValue = pattern.caseInsensitive ? pattern.pattern.toLowerCase() : pattern.pattern;
1013
+ const matchValue = pattern.caseInsensitive ? stringValue.toLowerCase() : stringValue;
1014
+ try {
1015
+ switch (pattern.type) {
1016
+ case PatternType.Exact:
1017
+ return matchValue === patternValue;
1018
+ case PatternType.Prefix:
1019
+ return matchValue.startsWith(patternValue);
1020
+ case PatternType.Regex:
1021
+ return this.matchRegex(pattern.pattern, matchValue, pattern.caseInsensitive);
1022
+ case PatternType.Glob:
1023
+ return minimatch(matchValue, patternValue, {
1024
+ nocase: pattern.caseInsensitive
1025
+ });
1026
+ default:
1027
+ return false;
1028
+ }
1029
+ } catch (error) {
1030
+ this.onError?.(error, event);
1031
+ return false;
1032
+ }
1033
+ }
1034
+ /**
1035
+ * Get field value from event using dot notation.
1036
+ */
1037
+ getFieldValue(event, field) {
1038
+ if (!field) {
1039
+ return event.payload;
1040
+ }
1041
+ const parts = field.split(".");
1042
+ let value = event;
1043
+ for (const part of parts) {
1044
+ if (value === null || value === void 0) {
1045
+ return void 0;
1046
+ }
1047
+ if (typeof value !== "object") {
1048
+ return void 0;
1049
+ }
1050
+ value = value[part];
1051
+ }
1052
+ return value;
1053
+ }
1054
+ /**
1055
+ * Stringify a value for matching.
1056
+ */
1057
+ stringify(value) {
1058
+ if (typeof value === "string") {
1059
+ return value;
1060
+ }
1061
+ if (value === null || value === void 0) {
1062
+ return "";
1063
+ }
1064
+ return JSON.stringify(value);
1065
+ }
1066
+ /**
1067
+ * Match against a compiled regex with ReDoS protection.
1068
+ * Enforces input length limits to prevent catastrophic backtracking.
1069
+ */
1070
+ matchRegex(pattern, value, caseInsensitive) {
1071
+ if (value.length > MAX_REGEX_INPUT_LENGTH) {
1072
+ return false;
1073
+ }
1074
+ const cacheKey = `${pattern}:${caseInsensitive ? "i" : ""}`;
1075
+ const compiled = this.compiledRegexes.get(cacheKey);
1076
+ if (!compiled) {
1077
+ try {
1078
+ const flags = caseInsensitive ? "i" : "";
1079
+ return new RegExp(pattern, flags).test(value);
1080
+ } catch {
1081
+ return false;
1082
+ }
1083
+ }
1084
+ try {
1085
+ return compiled.regex.test(value);
1086
+ } catch {
1087
+ return false;
1088
+ }
1089
+ }
1090
+ /**
1091
+ * Pre-compile all regex patterns for efficiency.
1092
+ * Includes ReDoS vulnerability detection and logging.
1093
+ */
1094
+ compilePatterns() {
1095
+ for (const rule of this.config.rules) {
1096
+ if (!rule.content?.patterns) continue;
1097
+ for (const pattern of rule.content.patterns) {
1098
+ if (pattern.type !== PatternType.Regex) continue;
1099
+ const cacheKey = `${pattern.pattern}:${pattern.caseInsensitive ? "i" : ""}`;
1100
+ if (this.compiledRegexes.has(cacheKey)) continue;
1101
+ if (isPotentiallyVulnerableRegex(pattern.pattern)) {
1102
+ console.warn(
1103
+ `[EventFilter] Potentially vulnerable regex pattern detected: ${pattern.pattern}. Input length will be limited to ${MAX_REGEX_INPUT_LENGTH} characters for protection.`
1104
+ );
1105
+ }
1106
+ try {
1107
+ const flags = pattern.caseInsensitive ? "i" : "";
1108
+ const regex = new RegExp(pattern.pattern, flags);
1109
+ this.compiledRegexes.set(cacheKey, { regex });
1110
+ } catch (error) {
1111
+ console.error(`Invalid regex pattern: ${pattern.pattern}`, error);
1112
+ }
1113
+ }
1114
+ }
1115
+ }
1116
+ };
1117
+ function createEventFilter(options) {
1118
+ return new EventFilter(options);
1119
+ }
1120
+ function createTypeFilter(mode, types) {
1121
+ return {
1122
+ mode: mode === "include" ? FilterMode.Include : FilterMode.Exclude,
1123
+ rules: [{ types: { types } }]
1124
+ };
1125
+ }
1126
+ function createContentFilter(mode, pattern, patternType = PatternType.Regex) {
1127
+ return {
1128
+ mode: mode === "include" ? FilterMode.Include : FilterMode.Exclude,
1129
+ rules: [
1130
+ {
1131
+ content: {
1132
+ patterns: [{ type: patternType, pattern }]
1133
+ }
1134
+ }
1135
+ ]
1136
+ };
1137
+ }
1138
+
1139
+ // libs/enclavejs-broker/src/http/session-handler.ts
1140
+ var SessionHandler = class {
1141
+ broker;
1142
+ cors;
1143
+ allowedOrigins;
1144
+ constructor(config) {
1145
+ this.broker = config.broker;
1146
+ this.cors = config.cors ?? true;
1147
+ this.allowedOrigins = config.allowedOrigins ?? ["*"];
1148
+ }
1149
+ /**
1150
+ * Get route definitions for registration with HTTP frameworks
1151
+ */
1152
+ getRoutes() {
1153
+ return [
1154
+ { method: "GET", path: "/sessions", handler: this.listSessions.bind(this) },
1155
+ { method: "POST", path: "/sessions", handler: this.createSession.bind(this) },
1156
+ { method: "GET", path: "/sessions/:sessionId", handler: this.getSession.bind(this) },
1157
+ { method: "GET", path: "/sessions/:sessionId/stream", handler: this.streamSession.bind(this) },
1158
+ { method: "DELETE", path: "/sessions/:sessionId", handler: this.terminateSession.bind(this) },
1159
+ { method: "OPTIONS", path: "/sessions", handler: this.handleCors.bind(this) },
1160
+ { method: "OPTIONS", path: "/sessions/:sessionId", handler: this.handleCors.bind(this) },
1161
+ { method: "OPTIONS", path: "/sessions/:sessionId/stream", handler: this.handleCors.bind(this) }
1162
+ ];
1163
+ }
1164
+ /**
1165
+ * Add CORS headers to response
1166
+ */
1167
+ addCorsHeaders(req, res) {
1168
+ if (!this.cors) return;
1169
+ const origin = req.headers["origin"];
1170
+ if (this.allowedOrigins.includes("*")) {
1171
+ res.setHeader("Access-Control-Allow-Origin", "*");
1172
+ } else if (origin && this.allowedOrigins.includes(origin)) {
1173
+ res.setHeader("Access-Control-Allow-Origin", origin);
1174
+ res.setHeader("Vary", "Origin");
1175
+ } else {
1176
+ return;
1177
+ }
1178
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
1179
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Last-Event-ID");
1180
+ res.setHeader("Access-Control-Max-Age", "86400");
1181
+ }
1182
+ /**
1183
+ * Handle CORS preflight requests
1184
+ */
1185
+ async handleCors(req, res) {
1186
+ this.addCorsHeaders(req, res);
1187
+ res.status(204).end();
1188
+ }
1189
+ /**
1190
+ * List all active sessions
1191
+ *
1192
+ * GET /sessions
1193
+ */
1194
+ async listSessions(req, res) {
1195
+ this.addCorsHeaders(req, res);
1196
+ try {
1197
+ const sessions = this.broker.listSessions();
1198
+ const response = {
1199
+ sessions: sessions.map((info) => this.sessionInfoToResponse(info)),
1200
+ total: sessions.length
1201
+ };
1202
+ res.status(200).json(response);
1203
+ } catch {
1204
+ this.sendError(res, 500, "INTERNAL_ERROR", "Failed to list sessions");
1205
+ }
1206
+ }
1207
+ /**
1208
+ * Create a new session and start execution
1209
+ *
1210
+ * POST /sessions
1211
+ * Body: { code: string, sessionId?: string, config?: {...} }
1212
+ *
1213
+ * Returns NDJSON stream of events
1214
+ */
1215
+ async createSession(req, res) {
1216
+ this.addCorsHeaders(req, res);
1217
+ const body = req.body;
1218
+ if (!body || typeof body.code !== "string") {
1219
+ this.sendError(res, 400, "INVALID_REQUEST", 'Missing or invalid "code" field');
1220
+ return;
1221
+ }
1222
+ if (this.broker.isDisposed) {
1223
+ this.sendError(res, 503, "SERVICE_UNAVAILABLE", "Broker is disposed");
1224
+ return;
1225
+ }
1226
+ try {
1227
+ const limits = {};
1228
+ if (body.config?.maxExecutionMs !== void 0) {
1229
+ limits["sessionTtlMs"] = body.config.maxExecutionMs;
1230
+ }
1231
+ if (body.config?.maxToolCalls !== void 0) {
1232
+ limits["maxToolCalls"] = body.config.maxToolCalls;
1233
+ }
1234
+ if (body.config?.heartbeatIntervalMs !== void 0) {
1235
+ limits["heartbeatIntervalMs"] = body.config.heartbeatIntervalMs;
1236
+ }
1237
+ let eventFilter;
1238
+ if (body.filter) {
1239
+ eventFilter = createEventFilter({ config: body.filter });
1240
+ }
1241
+ const session = this.broker.createSession({
1242
+ sessionId: body.sessionId,
1243
+ limits: Object.keys(limits).length > 0 ? limits : void 0
1244
+ });
1245
+ res.setHeader("Content-Type", "application/x-ndjson");
1246
+ res.setHeader("Cache-Control", "no-cache");
1247
+ res.setHeader("Connection", "keep-alive");
1248
+ res.setHeader("X-Session-ID", session.sessionId);
1249
+ const unsubscribe = session.onEvent((event) => {
1250
+ if (eventFilter && !eventFilter.shouldSend(event)) {
1251
+ return;
1252
+ }
1253
+ this.writeEvent(res, event);
1254
+ });
1255
+ let cleanedUp = false;
1256
+ const cleanup = () => {
1257
+ if (cleanedUp) return;
1258
+ cleanedUp = true;
1259
+ unsubscribe();
1260
+ if (!session.isTerminal()) {
1261
+ session.cancel("Client disconnected").catch(() => {
1262
+ });
1263
+ }
1264
+ };
1265
+ if (req.signal) {
1266
+ req.signal.addEventListener("abort", cleanup, { once: true });
1267
+ }
1268
+ try {
1269
+ await session.execute(body.code);
1270
+ } catch {
1271
+ } finally {
1272
+ cleanup();
1273
+ res.end();
1274
+ }
1275
+ } catch (error) {
1276
+ const message = error instanceof Error ? error.message : "Unknown error";
1277
+ this.sendError(res, 500, "SESSION_CREATE_ERROR", message);
1278
+ }
1279
+ }
1280
+ /**
1281
+ * Get session information
1282
+ *
1283
+ * GET /sessions/:sessionId
1284
+ */
1285
+ async getSession(req, res) {
1286
+ this.addCorsHeaders(req, res);
1287
+ const sessionId = req.params["sessionId"];
1288
+ if (!sessionId) {
1289
+ this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
1290
+ return;
1291
+ }
1292
+ const session = this.broker.getSession(sessionId);
1293
+ if (!session) {
1294
+ this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
1295
+ return;
1296
+ }
1297
+ res.status(200).json(this.sessionToInfo(session));
1298
+ }
1299
+ /**
1300
+ * Stream session events (for reconnection)
1301
+ *
1302
+ * GET /sessions/:sessionId/stream?fromSeq=N&filter=JSON
1303
+ */
1304
+ async streamSession(req, res) {
1305
+ this.addCorsHeaders(req, res);
1306
+ const sessionId = req.params["sessionId"];
1307
+ if (!sessionId) {
1308
+ this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
1309
+ return;
1310
+ }
1311
+ const session = this.broker.getSession(sessionId);
1312
+ if (!session) {
1313
+ this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
1314
+ return;
1315
+ }
1316
+ const parsedFromSeq = parseInt(req.query["fromSeq"] ?? "0", 10);
1317
+ const fromSeq = Number.isFinite(parsedFromSeq) && parsedFromSeq >= 0 ? parsedFromSeq : 0;
1318
+ let eventFilter;
1319
+ if (req.query["filter"]) {
1320
+ try {
1321
+ const filterConfig = JSON.parse(req.query["filter"]);
1322
+ eventFilter = createEventFilter({ config: filterConfig });
1323
+ } catch {
1324
+ this.sendError(res, 400, "INVALID_FILTER", "Invalid filter configuration");
1325
+ return;
1326
+ }
1327
+ }
1328
+ res.setHeader("Content-Type", "application/x-ndjson");
1329
+ res.setHeader("Cache-Control", "no-cache");
1330
+ res.setHeader("Connection", "keep-alive");
1331
+ res.setHeader("X-Session-ID", session.sessionId);
1332
+ const pastEvents = session.getEvents();
1333
+ for (const event of pastEvents) {
1334
+ if (event.seq >= fromSeq) {
1335
+ if (eventFilter && !eventFilter.shouldSend(event)) {
1336
+ continue;
1337
+ }
1338
+ this.writeEvent(res, event);
1339
+ }
1340
+ }
1341
+ if (session.isTerminal()) {
1342
+ res.end();
1343
+ return;
1344
+ }
1345
+ const unsubscribe = session.onEvent((event) => {
1346
+ if (event.seq >= fromSeq) {
1347
+ if (eventFilter && !eventFilter.shouldSend(event)) {
1348
+ if (event.type === "final") {
1349
+ unsubscribe();
1350
+ res.end();
1351
+ }
1352
+ return;
1353
+ }
1354
+ this.writeEvent(res, event);
1355
+ }
1356
+ if (event.type === "final") {
1357
+ unsubscribe();
1358
+ res.end();
1359
+ }
1360
+ });
1361
+ if (req.signal) {
1362
+ req.signal.addEventListener(
1363
+ "abort",
1364
+ () => {
1365
+ unsubscribe();
1366
+ },
1367
+ { once: true }
1368
+ );
1369
+ }
1370
+ }
1371
+ /**
1372
+ * Terminate a session
1373
+ *
1374
+ * DELETE /sessions/:sessionId
1375
+ */
1376
+ async terminateSession(req, res) {
1377
+ this.addCorsHeaders(req, res);
1378
+ const sessionId = req.params["sessionId"];
1379
+ if (!sessionId) {
1380
+ this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
1381
+ return;
1382
+ }
1383
+ const success = await this.broker.terminateSession(sessionId);
1384
+ if (!success) {
1385
+ this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
1386
+ return;
1387
+ }
1388
+ res.status(200).json({ success: true, sessionId });
1389
+ }
1390
+ /**
1391
+ * Convert BrokerSession to info response
1392
+ */
1393
+ sessionToInfo(session) {
1394
+ const stats = session.getStats();
1395
+ return {
1396
+ sessionId: session.sessionId,
1397
+ state: session.state,
1398
+ createdAt: session.createdAt,
1399
+ expiresAt: session.expiresAt,
1400
+ stats: {
1401
+ duration: stats.duration,
1402
+ toolCallCount: stats.toolCallCount
1403
+ }
1404
+ };
1405
+ }
1406
+ /**
1407
+ * Convert SessionInfo to response format
1408
+ */
1409
+ sessionInfoToResponse(info) {
1410
+ return {
1411
+ sessionId: info.sessionId,
1412
+ state: info.state,
1413
+ createdAt: info.createdAt,
1414
+ expiresAt: info.expiresAt,
1415
+ stats: {
1416
+ duration: Date.now() - info.createdAt,
1417
+ toolCallCount: 0
1418
+ // Not available from SessionInfo
1419
+ }
1420
+ };
1421
+ }
1422
+ /**
1423
+ * Write a stream event as NDJSON
1424
+ */
1425
+ writeEvent(res, event) {
1426
+ res.write(JSON.stringify(event) + "\n");
1427
+ if (res.flush) {
1428
+ res.flush();
1429
+ }
1430
+ }
1431
+ /**
1432
+ * Send an error response
1433
+ */
1434
+ sendError(res, status, code, message) {
1435
+ const error = { code, message };
1436
+ res.status(status).json(error);
1437
+ }
1438
+ };
1439
+ function createSessionHandler(config) {
1440
+ return new SessionHandler(config);
1441
+ }
1442
+
1443
+ // libs/enclavejs-broker/src/http/express-adapter.ts
1444
+ function adaptRequest(req) {
1445
+ const abortController = new AbortController();
1446
+ if (req.on && req.socket) {
1447
+ req.on("close", () => {
1448
+ if (req.socket?.destroyed) {
1449
+ abortController.abort();
1450
+ }
1451
+ });
1452
+ }
1453
+ return {
1454
+ method: req.method,
1455
+ path: req.path,
1456
+ params: req.params,
1457
+ query: req.query,
1458
+ body: req.body,
1459
+ headers: req.headers,
1460
+ signal: abortController.signal
1461
+ };
1462
+ }
1463
+ function adaptResponse(res) {
1464
+ return {
1465
+ status(code) {
1466
+ res.status(code);
1467
+ return this;
1468
+ },
1469
+ json(data) {
1470
+ res.json(data);
1471
+ },
1472
+ setHeader(name, value) {
1473
+ res.setHeader(name, value);
1474
+ return this;
1475
+ },
1476
+ write(data) {
1477
+ res.write(data);
1478
+ },
1479
+ end() {
1480
+ res.end();
1481
+ },
1482
+ flush() {
1483
+ if (res.flushHeaders) {
1484
+ res.flushHeaders();
1485
+ }
1486
+ if (res.flush) {
1487
+ res.flush();
1488
+ }
1489
+ }
1490
+ };
1491
+ }
1492
+ function createExpressRouter(handler) {
1493
+ const routes = [];
1494
+ for (const route of handler.getRoutes()) {
1495
+ const method = route.method.toLowerCase();
1496
+ routes.push({
1497
+ method,
1498
+ path: route.path,
1499
+ handler: (req, res) => {
1500
+ const brokerReq = adaptRequest(req);
1501
+ const brokerRes = adaptResponse(res);
1502
+ route.handler(brokerReq, brokerRes).catch((error) => {
1503
+ console.error("Route handler error:", error);
1504
+ if (!res.setHeader) return;
1505
+ res.status(500).json({
1506
+ code: "INTERNAL_ERROR",
1507
+ message: "Internal server error"
1508
+ });
1509
+ });
1510
+ }
1511
+ });
1512
+ }
1513
+ return {
1514
+ get(path, routeHandler) {
1515
+ const route = routes.find((r) => r.method === "get" && r.path === path);
1516
+ if (route) routeHandler = route.handler;
1517
+ },
1518
+ post(path, routeHandler) {
1519
+ const route = routes.find((r) => r.method === "post" && r.path === path);
1520
+ if (route) routeHandler = route.handler;
1521
+ },
1522
+ delete(path, routeHandler) {
1523
+ const route = routes.find((r) => r.method === "delete" && r.path === path);
1524
+ if (route) routeHandler = route.handler;
1525
+ },
1526
+ options(path, routeHandler) {
1527
+ const route = routes.find((r) => r.method === "options" && r.path === path);
1528
+ if (route) routeHandler = route.handler;
1529
+ }
1530
+ };
1531
+ }
1532
+ function registerExpressRoutes(router, handler) {
1533
+ for (const route of handler.getRoutes()) {
1534
+ const method = route.method.toLowerCase();
1535
+ const expressHandler = (req, res) => {
1536
+ const brokerReq = adaptRequest(req);
1537
+ const brokerRes = adaptResponse(res);
1538
+ route.handler(brokerReq, brokerRes).catch((error) => {
1539
+ console.error("Route handler error:", error);
1540
+ try {
1541
+ res.status(500).json({
1542
+ code: "INTERNAL_ERROR",
1543
+ message: "Internal server error"
1544
+ });
1545
+ } catch {
1546
+ }
1547
+ });
1548
+ };
1549
+ router[method](route.path, expressHandler);
1550
+ }
1551
+ }
1552
+ export {
1553
+ Broker,
1554
+ BrokerSession,
1555
+ EventFilter,
1556
+ SessionHandler,
1557
+ SessionManager,
1558
+ ToolRegistry,
1559
+ createBroker,
1560
+ createBrokerSession,
1561
+ createContentFilter,
1562
+ createEventFilter,
1563
+ createExpressRouter,
1564
+ createSessionHandler,
1565
+ createSessionManager,
1566
+ createToolRegistry,
1567
+ createTypeFilter,
1568
+ registerExpressRoutes
1569
+ };