@enclave-vm/broker 2.19.1 → 2.19.2

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/index.js CHANGED
@@ -21,8 +21,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  Broker: () => Broker,
24
+ BrokerError: () => BrokerError,
25
+ BrokerErrorCode: () => BrokerErrorCode,
24
26
  BrokerSession: () => BrokerSession,
25
27
  CatalogHandler: () => CatalogHandler,
28
+ DEFAULT_SESSION_HISTORY_LIMITS: () => DEFAULT_SESSION_HISTORY_LIMITS,
26
29
  EventFilter: () => EventFilter,
27
30
  OpenApiSource: () => OpenApiSource,
28
31
  OpenApiSpecPoller: () => OpenApiSpecPoller,
@@ -43,6 +46,133 @@ __export(index_exports, {
43
46
  });
44
47
  module.exports = __toCommonJS(index_exports);
45
48
 
49
+ // libs/broker/src/limits.ts
50
+ var import_types = require("@enclave-vm/types");
51
+ var LIMIT_KEYS = Object.keys(import_types.DEFAULT_SESSION_LIMITS);
52
+ var MAX_TIMER_MS = 2 ** 31 - 1;
53
+ function timerDelay(ms) {
54
+ return Math.min(Math.max(ms, 1), MAX_TIMER_MS);
55
+ }
56
+ function mergeSessionLimits(...layers) {
57
+ const merged = {};
58
+ for (const layer of layers) {
59
+ if (layer === void 0 || layer === null) continue;
60
+ if (typeof layer !== "object") {
61
+ throw new TypeError("Session limits must be an object");
62
+ }
63
+ for (const key of LIMIT_KEYS) {
64
+ const value = layer[key];
65
+ if (value !== void 0 && value !== null) merged[key] = value;
66
+ }
67
+ }
68
+ return merged;
69
+ }
70
+ function resolveSessionLimits(limits) {
71
+ const resolved = { ...import_types.DEFAULT_SESSION_LIMITS, ...mergeSessionLimits(limits) };
72
+ for (const key of LIMIT_KEYS) {
73
+ const value = resolved[key];
74
+ if (key === "cancelOnFirstError") {
75
+ if (typeof value !== "boolean") {
76
+ throw new TypeError(`Session limit "${key}" must be a boolean`);
77
+ }
78
+ } else if (typeof value !== "number" || Number.isNaN(value)) {
79
+ throw new TypeError(`Session limit "${key}" must be a number`);
80
+ }
81
+ }
82
+ return resolved;
83
+ }
84
+
85
+ // libs/broker/src/session-history.ts
86
+ var import_core = require("@enclave-vm/core");
87
+ var DEFAULT_SESSION_HISTORY_LIMITS = {
88
+ maxEvents: 1e4,
89
+ maxBytes: 4 * 1024 * 1024
90
+ };
91
+ var UNMEASURED_EVENT_BYTES = 1024;
92
+ function resolveHistoryLimits(limits) {
93
+ const resolved = { ...DEFAULT_SESSION_HISTORY_LIMITS };
94
+ if (limits === void 0 || limits === null) return resolved;
95
+ if (typeof limits !== "object") {
96
+ throw new TypeError("Session history limits must be an object");
97
+ }
98
+ for (const key of ["maxEvents", "maxBytes"]) {
99
+ const value = limits[key];
100
+ if (value === void 0) continue;
101
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
102
+ throw new TypeError(`Session history limit "${key}" must be a non-negative number`);
103
+ }
104
+ resolved[key] = value;
105
+ }
106
+ return resolved;
107
+ }
108
+ var BoundedSessionEmitter = class extends import_core.SessionEmitter {
109
+ limits;
110
+ kept = [];
111
+ keptBytes = 0;
112
+ droppedThrough = 0;
113
+ /**
114
+ * Size of the event that is emitted next, when the caller knows it already. Used once.
115
+ */
116
+ nextEventSize;
117
+ constructor(config, limits) {
118
+ super(config);
119
+ this.limits = resolveHistoryLimits(limits);
120
+ }
121
+ /**
122
+ * Emit a stream event: keep it within the bounds, then hand it to the listeners.
123
+ */
124
+ emit(event) {
125
+ this.keep(event);
126
+ try {
127
+ super.emit(event);
128
+ } finally {
129
+ super.clearHistory();
130
+ }
131
+ }
132
+ /**
133
+ * The kept events, oldest first.
134
+ */
135
+ getEmittedEvents() {
136
+ return this.kept.map((entry) => entry.event);
137
+ }
138
+ /**
139
+ * Drop every kept event.
140
+ */
141
+ clearHistory() {
142
+ super.clearHistory();
143
+ const last = this.kept[this.kept.length - 1];
144
+ if (last) {
145
+ this.droppedThrough = Math.max(this.droppedThrough, last.event.seq);
146
+ }
147
+ this.kept = [];
148
+ this.keptBytes = 0;
149
+ }
150
+ /**
151
+ * The lowest sequence number a replay can start from: every event from there on is kept.
152
+ */
153
+ get firstReplayableSeq() {
154
+ return this.droppedThrough + 1;
155
+ }
156
+ keep(event) {
157
+ let size = this.nextEventSize;
158
+ this.nextEventSize = void 0;
159
+ if (size === void 0) {
160
+ try {
161
+ size = JSON.stringify(event).length;
162
+ } catch {
163
+ size = UNMEASURED_EVENT_BYTES;
164
+ }
165
+ }
166
+ this.kept.push({ event, size });
167
+ this.keptBytes += size;
168
+ while (this.kept.length > 0 && (this.kept.length > this.limits.maxEvents || this.keptBytes > this.limits.maxBytes)) {
169
+ const oldest = this.kept.shift();
170
+ this.keptBytes -= oldest.size;
171
+ this.droppedThrough = Math.max(this.droppedThrough, oldest.event.seq);
172
+ }
173
+ }
174
+ };
175
+
46
176
  // libs/broker/src/tool-registry.ts
47
177
  var import_zod = require("zod");
48
178
  var ToolRegistry = class {
@@ -109,7 +239,7 @@ var ToolRegistry = class {
109
239
  * Get tool configurations for all registered tools
110
240
  */
111
241
  getConfigs() {
112
- const configs = {};
242
+ const configs = /* @__PURE__ */ Object.create(null);
113
243
  for (const [name, tool] of this.tools) {
114
244
  if (tool.definition.config) {
115
245
  configs[name] = tool.definition.config;
@@ -268,17 +398,23 @@ function createToolRegistry() {
268
398
  }
269
399
 
270
400
  // libs/broker/src/broker-session.ts
271
- var import_types = require("@enclave-vm/types");
272
- var import_core = require("@enclave-vm/core");
401
+ var import_types2 = require("@enclave-vm/types");
402
+ var import_core2 = require("@enclave-vm/core");
403
+ var DEFAULT_BRIDGE_PAYLOAD_BYTES = 5 * 1024 * 1024;
273
404
  var BrokerSession = class {
274
405
  sessionId;
275
406
  createdAt;
276
407
  expiresAt;
408
+ /**
409
+ * The caller this session belongs to, if any.
410
+ */
411
+ owner;
277
412
  emitter;
278
413
  toolRegistry;
279
414
  enclave;
280
415
  abortController;
281
416
  limits;
417
+ checkResultSize;
282
418
  _state = "starting";
283
419
  executionPromise = null;
284
420
  toolCallCount = 0;
@@ -288,19 +424,29 @@ var BrokerSession = class {
288
424
  _deadlineExceeded = false;
289
425
  partialErrors = [];
290
426
  constructor(toolRegistry, config = {}) {
291
- this.sessionId = config.sessionId ?? (0, import_types.generateSessionId)();
427
+ this.sessionId = config.sessionId ?? (0, import_types2.generateSessionId)();
428
+ if (config.owner !== void 0) {
429
+ if (typeof config.owner !== "string" || config.owner.length === 0) {
430
+ throw new TypeError("Session owner must be a non-empty string");
431
+ }
432
+ this.owner = config.owner;
433
+ }
292
434
  this.createdAt = Date.now();
293
435
  this.toolRegistry = toolRegistry;
294
436
  this.abortController = new AbortController();
295
- this.limits = {
296
- ...import_types.DEFAULT_SESSION_LIMITS,
297
- ...config.limits
298
- };
437
+ this.limits = resolveSessionLimits(config.limits);
438
+ const bridge = config.enclaveConfig?.toolBridge;
439
+ this.checkResultSize = (bridge?.mode ?? "string") !== "string" || this.limits.maxToolResultBytes < (bridge?.maxPayloadBytes ?? DEFAULT_BRIDGE_PAYLOAD_BYTES);
299
440
  this.expiresAt = this.createdAt + this.limits.sessionTtlMs;
300
- this.emitter = (0, import_core.createSessionEmitter)(this.sessionId, {
301
- expiresAt: new Date(this.expiresAt)
302
- });
303
- this.enclave = new import_core.Enclave({
441
+ this.emitter = new BoundedSessionEmitter(
442
+ {
443
+ sessionId: this.sessionId,
444
+ cancelUrl: `/sessions/${this.sessionId}/cancel`,
445
+ expiresAt: new Date(this.expiresAt).toISOString()
446
+ },
447
+ config.history
448
+ );
449
+ this.enclave = new import_core2.Enclave({
304
450
  ...config.enclaveConfig,
305
451
  timeout: this.limits.toolTimeoutMs,
306
452
  maxToolCalls: this.limits.maxToolCalls
@@ -331,11 +477,19 @@ var BrokerSession = class {
331
477
  return this.emitter.on(handler);
332
478
  }
333
479
  /**
334
- * Get all emitted events
480
+ * Get the events the session keeps: all of them, or the most recent ones once a bound of
481
+ * the history was reached (see `firstReplayableSeq`)
335
482
  */
336
483
  getEvents() {
337
484
  return this.emitter.getEmittedEvents();
338
485
  }
486
+ /**
487
+ * The lowest sequence number from which every event is still kept. It is 1 until the history
488
+ * reaches a bound; from then on, events below it cannot be replayed.
489
+ */
490
+ get firstReplayableSeq() {
491
+ return this.emitter.firstReplayableSeq;
492
+ }
339
493
  /**
340
494
  * Execute code in this session
341
495
  *
@@ -347,13 +501,16 @@ var BrokerSession = class {
347
501
  throw new Error("Session is already executing");
348
502
  }
349
503
  this.emitter.emitSessionInit();
504
+ if (this.executionPromise) {
505
+ return this.executionPromise;
506
+ }
350
507
  const heartbeatMs = this.limits.heartbeatIntervalMs;
351
508
  if (heartbeatMs > 0) {
352
509
  this.heartbeatInterval = setInterval(() => {
353
510
  if (!this.isTerminal()) {
354
511
  this.emitter.emitHeartbeat();
355
512
  }
356
- }, heartbeatMs);
513
+ }, timerDelay(heartbeatMs));
357
514
  }
358
515
  const deadlineMs = this.limits.deadlineMs;
359
516
  if (deadlineMs > 0) {
@@ -362,14 +519,14 @@ var BrokerSession = class {
362
519
  this.deadlineTimer = setTimeout(() => {
363
520
  this._deadlineExceeded = true;
364
521
  this.cancel(`Deadline exceeded: ${deadlineMs}ms budget`);
365
- }, remaining);
522
+ }, timerDelay(remaining));
366
523
  } else {
367
524
  this._deadlineExceeded = true;
368
525
  this.stopHeartbeat();
369
526
  this._state = "failed";
370
527
  const elapsed = Date.now() - this.createdAt;
371
528
  this.emitter.emit(
372
- this.makeCustomEvent(import_types.EventType.DeadlineExceeded, { elapsedMs: elapsed, budgetMs: deadlineMs })
529
+ this.makeCustomEvent(import_types2.EventType.DeadlineExceeded, { elapsedMs: elapsed, budgetMs: deadlineMs })
373
530
  );
374
531
  this.emitter.emitFinalError(
375
532
  { code: "DEADLINE_EXCEEDED", message: "Deadline exceeded before execution" },
@@ -422,7 +579,7 @@ var BrokerSession = class {
422
579
  if (this.isTerminal()) {
423
580
  if (this._deadlineExceeded) {
424
581
  this.emitter.emit(
425
- this.makeCustomEvent(import_types.EventType.DeadlineExceeded, {
582
+ this.makeCustomEvent(import_types2.EventType.DeadlineExceeded, {
426
583
  elapsedMs: Date.now() - this.createdAt,
427
584
  budgetMs: this.limits.deadlineMs
428
585
  })
@@ -477,7 +634,7 @@ var BrokerSession = class {
477
634
  };
478
635
  if (this._deadlineExceeded) {
479
636
  this.emitter.emit(
480
- this.makeCustomEvent(import_types.EventType.DeadlineExceeded, {
637
+ this.makeCustomEvent(import_types2.EventType.DeadlineExceeded, {
481
638
  elapsedMs: Date.now() - this.createdAt,
482
639
  budgetMs: this.limits.deadlineMs
483
640
  })
@@ -513,7 +670,7 @@ var BrokerSession = class {
513
670
  */
514
671
  emitToolProgress(callId, phase, elapsedMs, bytesReceived, totalBytes) {
515
672
  this.emitter.emit(
516
- this.makeCustomEvent(import_types.EventType.ToolProgress, {
673
+ this.makeCustomEvent(import_types2.EventType.ToolProgress, {
517
674
  callId,
518
675
  phase,
519
676
  elapsedMs,
@@ -530,7 +687,7 @@ var BrokerSession = class {
530
687
  this.partialErrors.push(error);
531
688
  }
532
689
  this.emitter.emit(
533
- this.makeCustomEvent(import_types.EventType.PartialResult, {
690
+ this.makeCustomEvent(import_types2.EventType.PartialResult, {
534
691
  path,
535
692
  data,
536
693
  error,
@@ -548,7 +705,7 @@ var BrokerSession = class {
548
705
  * Execute a tool call directly
549
706
  */
550
707
  async executeTool(toolName, args) {
551
- const callId = (0, import_types.generateCallId)();
708
+ const callId = (0, import_types2.generateCallId)();
552
709
  const toolStartTime = Date.now();
553
710
  if (this.limits.deadlineMs > 0) {
554
711
  const elapsed = Date.now() - this.createdAt;
@@ -560,10 +717,16 @@ var BrokerSession = class {
560
717
  throw err;
561
718
  }
562
719
  }
563
- this.emitter.emitToolCall(callId, toolName, args);
720
+ const snapshot = snapshotArguments(args);
721
+ this.emitter.nextEventSize = snapshot.size + TOOL_CALL_EVENT_OVERHEAD_BYTES;
722
+ this.emitter.emitToolCall(callId, toolName, snapshot.copy);
564
723
  this.toolCallCount++;
565
724
  this.emitToolProgress(callId, "connecting", 0);
566
725
  let toolTimeout = this.limits.perToolDeadlineMs;
726
+ const ownTimeout = this.toolRegistry.get(toolName)?.config?.timeout;
727
+ if (typeof ownTimeout === "number" && ownTimeout > 0) {
728
+ toolTimeout = toolTimeout > 0 ? Math.min(toolTimeout, ownTimeout) : ownTimeout;
729
+ }
567
730
  if (this.limits.deadlineMs > 0) {
568
731
  const remaining = this.limits.deadlineMs - (Date.now() - this.createdAt);
569
732
  toolTimeout = Math.min(toolTimeout, remaining);
@@ -571,7 +734,7 @@ var BrokerSession = class {
571
734
  const toolAbort = new AbortController();
572
735
  let toolTimer = null;
573
736
  if (toolTimeout > 0) {
574
- toolTimer = setTimeout(() => toolAbort.abort(), toolTimeout);
737
+ toolTimer = setTimeout(() => toolAbort.abort(), timerDelay(toolTimeout));
575
738
  }
576
739
  const onSessionAbort = () => toolAbort.abort();
577
740
  this.abortController.signal.addEventListener("abort", onSessionAbort);
@@ -593,6 +756,16 @@ var BrokerSession = class {
593
756
  if (toolTimer) clearTimeout(toolTimer);
594
757
  this.abortController.signal.removeEventListener("abort", onSessionAbort);
595
758
  }
759
+ if (result.success && !this.resultWithinLimit(result.value)) {
760
+ result = {
761
+ success: false,
762
+ error: {
763
+ code: "TOOL_RESULT_TOO_LARGE",
764
+ message: `Tool result exceeds the limit of ${this.limits.maxToolResultBytes} bytes`
765
+ },
766
+ durationMs: result.durationMs
767
+ };
768
+ }
596
769
  this.emitter.emitToolResultApplied(callId);
597
770
  if (result.success) {
598
771
  return result.value;
@@ -605,12 +778,27 @@ var BrokerSession = class {
605
778
  throw error;
606
779
  }
607
780
  }
781
+ /**
782
+ * Whether a tool result is within `limits.maxToolResultBytes`, measured as serialized JSON.
783
+ */
784
+ resultWithinLimit(value) {
785
+ if (!this.checkResultSize) return true;
786
+ const limit = this.limits.maxToolResultBytes;
787
+ if (!(limit > 0) || limit === Infinity) return true;
788
+ let serialized;
789
+ try {
790
+ serialized = JSON.stringify(value);
791
+ } catch {
792
+ return true;
793
+ }
794
+ return serialized === void 0 || Buffer.byteLength(serialized, "utf8") <= limit;
795
+ }
608
796
  /**
609
797
  * Create a custom event with proper base fields and unique sequence number.
610
798
  */
611
799
  makeCustomEvent(type, payload) {
612
800
  return {
613
- protocolVersion: import_types.PROTOCOL_VERSION,
801
+ protocolVersion: import_types2.PROTOCOL_VERSION,
614
802
  sessionId: this.sessionId,
615
803
  seq: this.emitter.nextSeq(),
616
804
  type,
@@ -731,11 +919,41 @@ var BrokerSession = class {
731
919
  this.enclave.dispose();
732
920
  }
733
921
  };
922
+ var TOOL_CALL_EVENT_OVERHEAD_BYTES = 256;
923
+ function snapshotArguments(args) {
924
+ try {
925
+ const serialized = JSON.stringify(args);
926
+ if (serialized !== void 0) {
927
+ return { copy: JSON.parse(serialized), size: serialized.length };
928
+ }
929
+ } catch {
930
+ }
931
+ return { copy: {}, size: 2 };
932
+ }
734
933
  function createBrokerSession(toolRegistry, config) {
735
934
  return new BrokerSession(toolRegistry, config);
736
935
  }
737
936
 
937
+ // libs/broker/src/errors.ts
938
+ var BrokerErrorCode = {
939
+ /** The session id is not a usable id */
940
+ InvalidSessionId: "INVALID_SESSION_ID",
941
+ /** A session with this id is registered */
942
+ SessionExists: "SESSION_EXISTS",
943
+ /** The broker holds as many sessions as `maxSessions` allows */
944
+ MaxSessionsReached: "MAX_SESSIONS_REACHED"
945
+ };
946
+ var BrokerError = class extends Error {
947
+ code;
948
+ constructor(code, message) {
949
+ super(message);
950
+ this.name = "BrokerError";
951
+ this.code = code;
952
+ }
953
+ };
954
+
738
955
  // libs/broker/src/session-manager.ts
956
+ var MAX_SESSION_ID_LENGTH = 256;
739
957
  var SessionManager = class {
740
958
  sessions;
741
959
  toolRegistry;
@@ -755,21 +973,39 @@ var SessionManager = class {
755
973
  /**
756
974
  * Create a new session
757
975
  *
758
- * @throws Error if max sessions reached or manager is disposed
976
+ * A session id names one session for as long as that session is registered: an id that is in
977
+ * use is refused.
978
+ *
979
+ * @throws BrokerError if the id is not usable or is in use, or if max sessions is reached
980
+ * @throws Error if the manager is disposed
759
981
  */
760
982
  create(config) {
761
983
  if (this.disposed) {
762
984
  throw new Error("Session manager is disposed");
763
985
  }
986
+ const requestedId = config?.sessionId;
987
+ if (requestedId !== void 0) {
988
+ if (typeof requestedId !== "string" || requestedId.length === 0 || requestedId.length > MAX_SESSION_ID_LENGTH) {
989
+ throw new BrokerError(BrokerErrorCode.InvalidSessionId, "Session id must be a non-empty string");
990
+ }
991
+ if (this.sessions.has(requestedId)) {
992
+ throw new BrokerError(BrokerErrorCode.SessionExists, "A session with this id already exists");
993
+ }
994
+ }
764
995
  if (this.sessions.size >= this.config.maxSessions) {
765
- throw new Error(
996
+ throw new BrokerError(
997
+ BrokerErrorCode.MaxSessionsReached,
766
998
  `Maximum sessions reached (${this.config.maxSessions}). Wait for existing sessions to complete or increase maxSessions.`
767
999
  );
768
1000
  }
769
- const sessionConfig = {
770
- ...this.config.defaultSessionConfig,
771
- ...config
772
- };
1001
+ const defaults = this.config.defaultSessionConfig;
1002
+ const sessionConfig = { ...defaults };
1003
+ for (const [key, value] of Object.entries(config ?? {})) {
1004
+ if (value !== void 0) {
1005
+ sessionConfig[key] = value;
1006
+ }
1007
+ }
1008
+ sessionConfig.limits = mergeSessionLimits(defaults.limits, config?.limits);
773
1009
  const session = createBrokerSession(this.toolRegistry, sessionConfig);
774
1010
  this.sessions.set(session.sessionId, session);
775
1011
  return {
@@ -798,7 +1034,8 @@ var SessionManager = class {
798
1034
  state: session.state,
799
1035
  createdAt: session.createdAt,
800
1036
  expiresAt: session.expiresAt,
801
- isExpired: session.isExpired()
1037
+ isExpired: session.isExpired(),
1038
+ ...session.owner !== void 0 && { owner: session.owner }
802
1039
  }));
803
1040
  }
804
1041
  /**
@@ -858,6 +1095,10 @@ var SessionManager = class {
858
1095
  let cleaned = 0;
859
1096
  for (const [sessionId, session] of this.sessions) {
860
1097
  if (session.isExpired() || session.isTerminal()) {
1098
+ if (!session.isTerminal()) {
1099
+ session.cancel("Session expired").catch(() => {
1100
+ });
1101
+ }
861
1102
  session.dispose();
862
1103
  this.sessions.delete(sessionId);
863
1104
  cleaned++;
@@ -875,6 +1116,7 @@ var SessionManager = class {
875
1116
  this.cleanupInterval = setInterval(() => {
876
1117
  this.cleanup();
877
1118
  }, this.config.cleanupIntervalMs);
1119
+ this.cleanupInterval.unref?.();
878
1120
  }
879
1121
  /**
880
1122
  * Stop automatic cleanup
@@ -924,291 +1166,245 @@ async function sha256Hex(data) {
924
1166
  return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
925
1167
  }
926
1168
 
927
- // libs/broker/src/openapi/openapi-spec-poller.ts
928
- var DEFAULT_RETRY = {
929
- maxRetries: 3,
930
- initialDelayMs: 1e3,
931
- maxDelayMs: 1e4,
932
- backoffMultiplier: 2
1169
+ // libs/broker/src/openapi/http-utils.ts
1170
+ var MAX_REDIRECTS = 5;
1171
+ var REDIRECT_STATUS = [301, 302, 303, 307, 308];
1172
+ var ResponseTooLargeError = class extends Error {
1173
+ code = "RESPONSE_TOO_LARGE";
1174
+ constructor(maxBytes) {
1175
+ super(`Response body exceeds the limit of ${maxBytes} bytes`);
1176
+ this.name = "ResponseTooLargeError";
1177
+ }
933
1178
  };
934
- var OpenApiSpecPoller = class extends import_events.EventEmitter {
935
- config;
936
- intervalTimer = null;
937
- lastHash = null;
938
- lastEtag = null;
939
- lastModified = null;
940
- consecutiveFailures = 0;
941
- isPolling = false;
942
- wasUnhealthy = false;
943
- /** Per-run abort controller — aborted on stop(), recreated on start() */
944
- _runAbort = new AbortController();
945
- _fetchController = null;
946
- _activePoll = null;
947
- constructor(config) {
948
- super();
949
- this.config = {
950
- url: config.url,
951
- intervalMs: config.intervalMs ?? 6e4,
952
- fetchTimeoutMs: config.fetchTimeoutMs ?? 1e4,
953
- changeDetection: config.changeDetection ?? "auto",
954
- unhealthyThreshold: config.unhealthyThreshold ?? 3,
955
- retry: { ...DEFAULT_RETRY, ...config.retry },
956
- headers: config.headers ?? {}
957
- };
1179
+ function sameOrigin(a, b) {
1180
+ try {
1181
+ return new URL(a).origin === new URL(b).origin;
1182
+ } catch {
1183
+ return false;
1184
+ }
1185
+ }
1186
+ async function discard(response) {
1187
+ try {
1188
+ await response.body?.cancel();
1189
+ } catch {
1190
+ }
1191
+ }
1192
+ async function readBodyText(response, maxBytes, truncate = false) {
1193
+ if (!truncate) {
1194
+ const declared = Number(response.headers.get("content-length"));
1195
+ if (Number.isFinite(declared) && declared > maxBytes) {
1196
+ await discard(response);
1197
+ throw new ResponseTooLargeError(maxBytes);
1198
+ }
1199
+ }
1200
+ if (!response.body) {
1201
+ return "";
1202
+ }
1203
+ const reader = response.body.getReader();
1204
+ const decoder = new TextDecoder();
1205
+ let total = 0;
1206
+ let text = "";
1207
+ for (; ; ) {
1208
+ const { done, value } = await reader.read();
1209
+ if (done) break;
1210
+ total += value.byteLength;
1211
+ if (total > maxBytes) {
1212
+ await reader.cancel().catch(() => void 0);
1213
+ if (!truncate) {
1214
+ throw new ResponseTooLargeError(maxBytes);
1215
+ }
1216
+ text += decoder.decode(value.subarray(0, value.byteLength - (total - maxBytes)), { stream: true });
1217
+ break;
1218
+ }
1219
+ text += decoder.decode(value, { stream: true });
1220
+ }
1221
+ return text + decoder.decode();
1222
+ }
1223
+ async function fetchOriginBound(url, request) {
1224
+ const origin = new URL(url).origin;
1225
+ let current = url;
1226
+ let method = request.method;
1227
+ let body = request.body;
1228
+ let headers = request.headers;
1229
+ for (let hop = 0; ; hop++) {
1230
+ const response = await fetch(current, { method, headers, body, signal: request.signal, redirect: "manual" });
1231
+ const location = REDIRECT_STATUS.includes(response.status) ? response.headers.get("location") : null;
1232
+ if (!location) {
1233
+ return response;
1234
+ }
1235
+ await discard(response);
1236
+ if (hop >= MAX_REDIRECTS) {
1237
+ throw new Error(`Too many redirects (more than ${MAX_REDIRECTS})`);
1238
+ }
1239
+ let next;
1240
+ try {
1241
+ next = new URL(location, current);
1242
+ } catch {
1243
+ throw new Error("Redirect to an invalid URL");
1244
+ }
1245
+ if (next.protocol !== "http:" && next.protocol !== "https:") {
1246
+ throw new Error("Redirect to an unsupported URL");
1247
+ }
1248
+ if (response.status === 303 && method !== "GET" && method !== "HEAD" || (response.status === 301 || response.status === 302) && method === "POST") {
1249
+ method = "GET";
1250
+ body = void 0;
1251
+ headers = withoutContentType(headers);
1252
+ }
1253
+ if (next.origin !== origin) {
1254
+ headers = body === void 0 ? {} : onlyContentType(headers);
1255
+ }
1256
+ current = next.href;
1257
+ }
1258
+ }
1259
+ function withoutContentType(headers) {
1260
+ const kept = {};
1261
+ for (const [name, value] of Object.entries(headers)) {
1262
+ if (name.toLowerCase() !== "content-type") kept[name] = value;
1263
+ }
1264
+ return kept;
1265
+ }
1266
+ function onlyContentType(headers) {
1267
+ const kept = {};
1268
+ for (const [name, value] of Object.entries(headers)) {
1269
+ if (name.toLowerCase() === "content-type") kept[name] = value;
1270
+ }
1271
+ return kept;
1272
+ }
1273
+
1274
+ // libs/broker/src/openapi/openapi-tool-loader.ts
1275
+ var import_zod2 = require("zod");
1276
+ var DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
1277
+ var DEFAULT_MAX_SPEC_BYTES = 32 * 1024 * 1024;
1278
+ var DEFAULT_SPEC_TIMEOUT_MS = 3e4;
1279
+ var MAX_ERROR_BODY_BYTES = 4096;
1280
+ var OpenApiToolLoader = class _OpenApiToolLoader {
1281
+ tools = [];
1282
+ toolNames = /* @__PURE__ */ new Set();
1283
+ specHash;
1284
+ options;
1285
+ auth;
1286
+ constructor(spec, hash, options = {}, auth) {
1287
+ this.options = options;
1288
+ this.auth = auth;
1289
+ this.specHash = hash;
1290
+ this.loadFromSpec(spec);
958
1291
  }
959
1292
  /**
960
- * Start polling for changes.
1293
+ * Create a loader from a URL.
1294
+ *
1295
+ * `auth` and `options.headers` belong to the upstream API. They go with the request for the
1296
+ * specification only when the specification is on the origin of `options.baseUrl`, or when
1297
+ * no base URL is given: the specification then decides where the tools send their requests,
1298
+ * so its host is trusted with the credential either way. What the specification host itself
1299
+ * needs goes into `options.specHeaders`.
961
1300
  */
962
- start() {
963
- if (this.intervalTimer) return;
964
- this._runAbort = new AbortController();
965
- const runSignal = this._runAbort.signal;
966
- const pendingPoll = this._activePoll;
967
- if (pendingPoll) {
968
- pendingPoll.finally(() => {
969
- if (!runSignal.aborted) {
970
- this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
1301
+ static async fromURL(url, options, auth) {
1302
+ const headers = {};
1303
+ if (!options?.baseUrl || sameOrigin(url, options.baseUrl)) {
1304
+ for (const [name, value] of Object.entries(options?.headers ?? {})) {
1305
+ setHeader(headers, name, value);
1306
+ }
1307
+ _OpenApiToolLoader.applyAuth(headers, auth);
1308
+ }
1309
+ for (const [name, value] of Object.entries(options?.specHeaders ?? {})) {
1310
+ setHeader(headers, name, value);
1311
+ }
1312
+ const controller = new AbortController();
1313
+ const timer = setTimeout(
1314
+ () => controller.abort(),
1315
+ timerDelay(positive(options?.specTimeoutMs) ?? DEFAULT_SPEC_TIMEOUT_MS)
1316
+ );
1317
+ let parsed;
1318
+ try {
1319
+ const response = await fetchOriginBound(url, { method: "GET", headers, signal: controller.signal });
1320
+ if (!response.ok) {
1321
+ await response.body?.cancel().catch(() => void 0);
1322
+ throw new Error(`Failed to fetch OpenAPI spec from ${url}: ${response.status}`);
1323
+ }
1324
+ const text = await readBodyText(response, positive(options?.maxSpecBytes) ?? DEFAULT_MAX_SPEC_BYTES);
1325
+ parsed = JSON.parse(text);
1326
+ } catch (error) {
1327
+ if (controller.signal.aborted) {
1328
+ throw new Error(`Timed out fetching OpenAPI spec from ${url}`);
1329
+ }
1330
+ throw error;
1331
+ } finally {
1332
+ clearTimeout(timer);
1333
+ }
1334
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1335
+ throw new Error(`The OpenAPI spec from ${url} is not a JSON object`);
1336
+ }
1337
+ const spec = parsed;
1338
+ const hash = await sha256Hex(JSON.stringify(spec));
1339
+ let resolvedBaseUrl = options?.baseUrl;
1340
+ if (!resolvedBaseUrl) {
1341
+ const servers = spec["servers"];
1342
+ if (servers?.[0]?.url) {
1343
+ try {
1344
+ resolvedBaseUrl = new URL(servers[0].url, url).origin + new URL(servers[0].url, url).pathname;
1345
+ } catch {
1346
+ resolvedBaseUrl = new URL(url).origin;
971
1347
  }
972
- });
973
- } else {
974
- this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
1348
+ } else {
1349
+ resolvedBaseUrl = new URL(url).origin;
1350
+ }
975
1351
  }
976
- this.intervalTimer = setInterval(() => {
977
- this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
978
- }, this.config.intervalMs);
1352
+ return new _OpenApiToolLoader(spec, hash, { ...options, baseUrl: resolvedBaseUrl }, auth);
979
1353
  }
980
1354
  /**
981
- * Stop polling.
1355
+ * Create a loader from a spec object.
982
1356
  */
983
- stop() {
984
- this._runAbort.abort();
985
- if (this._fetchController) {
986
- this._fetchController.abort();
987
- this._fetchController = null;
988
- }
989
- if (this.intervalTimer) {
990
- clearInterval(this.intervalTimer);
991
- this.intervalTimer = null;
1357
+ static async fromSpec(spec, options, auth) {
1358
+ const hash = await sha256Hex(JSON.stringify(spec));
1359
+ let resolvedBaseUrl = options?.baseUrl;
1360
+ if (!resolvedBaseUrl) {
1361
+ const servers = spec["servers"];
1362
+ if (servers?.[0]?.url) {
1363
+ try {
1364
+ const serverUrl = new URL(servers[0].url);
1365
+ resolvedBaseUrl = serverUrl.origin + serverUrl.pathname;
1366
+ } catch {
1367
+ throw new Error(
1368
+ `Cannot resolve relative server URL "${servers[0].url}" without a source URL. Use fromURL() or provide an explicit baseUrl option.`
1369
+ );
1370
+ }
1371
+ }
992
1372
  }
1373
+ return new _OpenApiToolLoader(
1374
+ spec,
1375
+ hash,
1376
+ resolvedBaseUrl ? { ...options, baseUrl: resolvedBaseUrl } : options,
1377
+ auth
1378
+ );
993
1379
  }
994
1380
  /**
995
- * Get the current content hash.
1381
+ * Put the upstream credential into a set of request headers.
996
1382
  */
997
- getHash() {
998
- return this.lastHash;
1383
+ static applyAuth(headers, auth) {
1384
+ if (!auth?.token) return;
1385
+ switch (auth.type) {
1386
+ case "bearer":
1387
+ setHeader(headers, "Authorization", `Bearer ${auth.token}`);
1388
+ break;
1389
+ case "api-key":
1390
+ setHeader(headers, auth.header ?? "X-API-Key", auth.token);
1391
+ break;
1392
+ case "basic":
1393
+ setHeader(headers, "Authorization", `Basic ${auth.token}`);
1394
+ break;
1395
+ }
999
1396
  }
1000
1397
  /**
1001
- * Get the number of consecutive failures.
1398
+ * Get all loaded tool definitions.
1002
1399
  */
1003
- getConsecutiveFailures() {
1004
- return this.consecutiveFailures;
1400
+ getTools() {
1401
+ return [...this.tools];
1005
1402
  }
1006
1403
  /**
1007
- * Perform a single poll cycle.
1404
+ * Get all tool names.
1008
1405
  */
1009
- async poll() {
1010
- return this.pollWithSignal(this._runAbort.signal);
1011
- }
1012
- async pollWithSignal(runSignal) {
1013
- if (this.isPolling) return;
1014
- this.isPolling = true;
1015
- try {
1016
- await this.fetchWithRetry(runSignal);
1017
- } finally {
1018
- this.isPolling = false;
1019
- this._activePoll = null;
1020
- }
1021
- }
1022
- async fetchWithRetry(runSignal) {
1023
- const { maxRetries, initialDelayMs, maxDelayMs, backoffMultiplier } = this.config.retry;
1024
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1025
- if (runSignal.aborted) return;
1026
- try {
1027
- await this.doFetch(runSignal);
1028
- if (runSignal.aborted) return;
1029
- if (this.consecutiveFailures > 0) {
1030
- this.consecutiveFailures = 0;
1031
- if (this.wasUnhealthy) {
1032
- this.wasUnhealthy = false;
1033
- this.emit("recovered");
1034
- }
1035
- }
1036
- return;
1037
- } catch (error) {
1038
- if (runSignal.aborted) return;
1039
- if (attempt === maxRetries) {
1040
- this.consecutiveFailures++;
1041
- this.emit("pollError", error instanceof Error ? error : new Error(String(error)));
1042
- if (this.consecutiveFailures >= this.config.unhealthyThreshold && !this.wasUnhealthy) {
1043
- this.wasUnhealthy = true;
1044
- this.emit("unhealthy", this.consecutiveFailures);
1045
- }
1046
- return;
1047
- }
1048
- const delay = Math.min(initialDelayMs * Math.pow(backoffMultiplier, attempt), maxDelayMs);
1049
- await new Promise((resolve) => {
1050
- const onAbort = () => {
1051
- clearTimeout(timer);
1052
- resolve();
1053
- };
1054
- const timer = setTimeout(() => {
1055
- runSignal.removeEventListener("abort", onAbort);
1056
- resolve();
1057
- }, delay);
1058
- runSignal.addEventListener("abort", onAbort, { once: true });
1059
- });
1060
- }
1061
- }
1062
- }
1063
- async doFetch(runSignal) {
1064
- if (runSignal.aborted) return;
1065
- const headers = { ...this.config.headers };
1066
- if (this.config.changeDetection !== "content-hash") {
1067
- if (this.lastEtag) {
1068
- headers["If-None-Match"] = this.lastEtag;
1069
- }
1070
- if (this.lastModified) {
1071
- headers["If-Modified-Since"] = this.lastModified;
1072
- }
1073
- }
1074
- const controller = new AbortController();
1075
- this._fetchController = controller;
1076
- const timeout = setTimeout(() => controller.abort(), this.config.fetchTimeoutMs);
1077
- try {
1078
- const response = await fetch(this.config.url, {
1079
- headers,
1080
- signal: controller.signal
1081
- });
1082
- if (runSignal.aborted) return;
1083
- if (response.status === 304) {
1084
- this.emit("unchanged");
1085
- return;
1086
- }
1087
- if (!response.ok) {
1088
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1089
- }
1090
- const etag = response.headers.get("etag");
1091
- const lastModified = response.headers.get("last-modified");
1092
- const body = await response.text();
1093
- if (runSignal.aborted) return;
1094
- const hash = await sha256Hex(body);
1095
- if (runSignal.aborted) return;
1096
- if (this.lastHash && this.lastHash === hash) {
1097
- this.emit("unchanged");
1098
- if (etag) this.lastEtag = etag;
1099
- if (lastModified) this.lastModified = lastModified;
1100
- return;
1101
- }
1102
- this.emit("changed", body, hash);
1103
- this.lastHash = hash;
1104
- if (etag) this.lastEtag = etag;
1105
- if (lastModified) this.lastModified = lastModified;
1106
- } finally {
1107
- clearTimeout(timeout);
1108
- if (this._fetchController === controller) {
1109
- this._fetchController = null;
1110
- }
1111
- }
1112
- }
1113
- /**
1114
- * Dispose the poller and release resources.
1115
- */
1116
- dispose() {
1117
- this.stop();
1118
- this.removeAllListeners();
1119
- }
1120
- };
1121
-
1122
- // libs/broker/src/openapi/openapi-tool-loader.ts
1123
- var import_zod2 = require("zod");
1124
- var OpenApiToolLoader = class _OpenApiToolLoader {
1125
- tools = [];
1126
- toolNames = /* @__PURE__ */ new Set();
1127
- specHash;
1128
- options;
1129
- auth;
1130
- constructor(spec, hash, options = {}, auth) {
1131
- this.options = options;
1132
- this.auth = auth;
1133
- this.specHash = hash;
1134
- this.loadFromSpec(spec);
1135
- }
1136
- /**
1137
- * Create a loader from a URL.
1138
- */
1139
- static async fromURL(url, options, auth) {
1140
- const headers = { ...options?.headers };
1141
- if (auth) {
1142
- switch (auth.type) {
1143
- case "bearer":
1144
- if (auth.token) headers["Authorization"] = `Bearer ${auth.token}`;
1145
- break;
1146
- case "api-key":
1147
- if (auth.token) headers[auth.header ?? "X-API-Key"] = auth.token;
1148
- break;
1149
- case "basic":
1150
- if (auth.token) headers["Authorization"] = `Basic ${auth.token}`;
1151
- break;
1152
- }
1153
- }
1154
- const response = await fetch(url, { headers });
1155
- if (!response.ok) {
1156
- throw new Error(`Failed to fetch OpenAPI spec from ${url}: ${response.status}`);
1157
- }
1158
- const spec = await response.json();
1159
- const hash = await sha256Hex(JSON.stringify(spec));
1160
- let resolvedBaseUrl = options?.baseUrl;
1161
- if (!resolvedBaseUrl) {
1162
- const servers = spec["servers"];
1163
- if (servers?.[0]?.url) {
1164
- try {
1165
- resolvedBaseUrl = new URL(servers[0].url, url).origin + new URL(servers[0].url, url).pathname;
1166
- } catch {
1167
- resolvedBaseUrl = new URL(url).origin;
1168
- }
1169
- } else {
1170
- resolvedBaseUrl = new URL(url).origin;
1171
- }
1172
- }
1173
- return new _OpenApiToolLoader(spec, hash, { ...options, baseUrl: resolvedBaseUrl }, auth);
1174
- }
1175
- /**
1176
- * Create a loader from a spec object.
1177
- */
1178
- static async fromSpec(spec, options, auth) {
1179
- const hash = await sha256Hex(JSON.stringify(spec));
1180
- let resolvedBaseUrl = options?.baseUrl;
1181
- if (!resolvedBaseUrl) {
1182
- const servers = spec["servers"];
1183
- if (servers?.[0]?.url) {
1184
- try {
1185
- const serverUrl = new URL(servers[0].url);
1186
- resolvedBaseUrl = serverUrl.origin + serverUrl.pathname;
1187
- } catch {
1188
- throw new Error(
1189
- `Cannot resolve relative server URL "${servers[0].url}" without a source URL. Use fromURL() or provide an explicit baseUrl option.`
1190
- );
1191
- }
1192
- }
1193
- }
1194
- return new _OpenApiToolLoader(
1195
- spec,
1196
- hash,
1197
- resolvedBaseUrl ? { ...options, baseUrl: resolvedBaseUrl } : options,
1198
- auth
1199
- );
1200
- }
1201
- /**
1202
- * Get all loaded tool definitions.
1203
- */
1204
- getTools() {
1205
- return [...this.tools];
1206
- }
1207
- /**
1208
- * Get all tool names.
1209
- */
1210
- getToolNames() {
1211
- return new Set(this.toolNames);
1406
+ getToolNames() {
1407
+ return new Set(this.toolNames);
1212
1408
  }
1213
1409
  /**
1214
1410
  * Get the hash of the loaded spec.
@@ -1390,19 +1586,46 @@ var OpenApiToolLoader = class _OpenApiToolLoader {
1390
1586
  createHandler(op, baseUrl, bodyMediaType) {
1391
1587
  const auth = this.auth;
1392
1588
  const headers = this.options.headers ?? {};
1589
+ const maxResponseBytes = positive(this.options.maxResponseBytes) ?? DEFAULT_MAX_RESPONSE_BYTES;
1590
+ const pathParams = (op.parameters ?? []).filter((param) => param.in === "path");
1393
1591
  return async (args, context) => {
1394
1592
  const params = args;
1593
+ const template = op.path.startsWith("/") ? op.path : "/" + op.path;
1594
+ const path = template.split("/").map((segment) => {
1595
+ if (!segment.includes("{")) return segment;
1596
+ let filled = segment;
1597
+ for (const param of pathParams) {
1598
+ const value = params[param.name];
1599
+ if (value === void 0) continue;
1600
+ filled = filled.split(`{${param.name}}`).join(encodeURIComponent(_OpenApiToolLoader.serializeParam(value)));
1601
+ }
1602
+ const plain = filled.replace(/%2e/gi, ".");
1603
+ if (plain === "" || plain === "." || plain === "..") {
1604
+ throw invalidPathParameter(op);
1605
+ }
1606
+ return filled;
1607
+ }).join("/");
1395
1608
  let normalizedBase = baseUrl;
1396
1609
  while (normalizedBase.endsWith("/")) normalizedBase = normalizedBase.slice(0, -1);
1397
- let url = `${normalizedBase}${op.path.startsWith("/") ? op.path : "/" + op.path}`;
1610
+ let url = `${normalizedBase}${path}`;
1611
+ let basePath;
1612
+ let requestPath;
1613
+ try {
1614
+ basePath = new URL(normalizedBase).pathname.replace(/\/+$/, "");
1615
+ requestPath = new URL(url).pathname;
1616
+ } catch {
1617
+ throw new Error(`Invalid request URL for ${op.method.toUpperCase()} ${op.path}`);
1618
+ }
1619
+ const expectedPath = basePath + path.split(/[?#]/)[0];
1620
+ if (requestPath.split("/").length !== expectedPath.split("/").length) {
1621
+ throw invalidPathParameter(op);
1622
+ }
1398
1623
  const queryParams = {};
1399
1624
  if (op.parameters) {
1400
1625
  for (const param of op.parameters) {
1401
1626
  const value = params[param.name];
1402
1627
  if (value === void 0) continue;
1403
- if (param.in === "path") {
1404
- url = url.replace(`{${param.name}}`, encodeURIComponent(_OpenApiToolLoader.serializeParam(value)));
1405
- } else if (param.in === "query") {
1628
+ if (param.in === "query") {
1406
1629
  queryParams[param.name] = _OpenApiToolLoader.serializeParam(value);
1407
1630
  }
1408
1631
  }
@@ -1414,81 +1637,285 @@ var OpenApiToolLoader = class _OpenApiToolLoader {
1414
1637
  const hasBody = (["post", "put", "patch", "delete"].includes(op.method) || op.requestBody != null) && Object.prototype.hasOwnProperty.call(params, "body") && params["body"] != null;
1415
1638
  const resolvedMediaType = bodyMediaType ?? "application/json";
1416
1639
  const isMultipart = resolvedMediaType === "multipart/form-data";
1417
- const requestHeaders = {
1418
- // Omit Content-Type for multipart/form-data to let the runtime set the boundary
1419
- ...hasBody && !isMultipart && { "Content-Type": resolvedMediaType },
1420
- ...headers
1421
- };
1422
- if (auth) {
1423
- switch (auth.type) {
1424
- case "bearer":
1425
- if (auth.token) requestHeaders["Authorization"] = `Bearer ${auth.token}`;
1426
- break;
1427
- case "api-key":
1428
- if (auth.token) requestHeaders[auth.header ?? "X-API-Key"] = auth.token;
1429
- break;
1430
- case "basic":
1431
- if (auth.token) requestHeaders["Authorization"] = `Basic ${auth.token}`;
1432
- break;
1433
- }
1434
- }
1435
- const protectedHeaders = /* @__PURE__ */ new Set();
1436
- if (auth) {
1437
- if (auth.type === "bearer" || auth.type === "basic") protectedHeaders.add("authorization");
1438
- if (auth.type === "api-key") protectedHeaders.add((auth.header ?? "X-API-Key").toLowerCase());
1640
+ const requestHeaders = {};
1641
+ if (hasBody && !isMultipart) {
1642
+ requestHeaders["Content-Type"] = resolvedMediaType;
1439
1643
  }
1440
1644
  if (op.parameters) {
1441
1645
  for (const param of op.parameters) {
1442
1646
  if (param.in === "header" && params[param.name] !== void 0) {
1443
- if (protectedHeaders.has(param.name.toLowerCase())) continue;
1444
- requestHeaders[param.name] = _OpenApiToolLoader.serializeParam(params[param.name]);
1647
+ setHeader(requestHeaders, param.name, _OpenApiToolLoader.serializeParam(params[param.name]));
1445
1648
  }
1446
1649
  }
1447
1650
  }
1448
- const fetchOptions = {
1449
- method: op.method.toUpperCase(),
1450
- headers: requestHeaders,
1451
- signal: context.signal
1452
- };
1651
+ for (const [name, value] of Object.entries(headers)) {
1652
+ setHeader(requestHeaders, name, value);
1653
+ }
1654
+ _OpenApiToolLoader.applyAuth(requestHeaders, auth);
1655
+ let body;
1453
1656
  if (hasBody) {
1454
1657
  if (_OpenApiToolLoader.isJsonContentType(resolvedMediaType)) {
1455
- fetchOptions.body = JSON.stringify(params["body"]);
1658
+ body = JSON.stringify(params["body"]);
1456
1659
  } else if (resolvedMediaType === "application/x-www-form-urlencoded") {
1457
- fetchOptions.body = new URLSearchParams(params["body"]).toString();
1660
+ body = new URLSearchParams(params["body"]).toString();
1458
1661
  } else if (resolvedMediaType === "multipart/form-data") {
1459
1662
  const formData = new FormData();
1460
1663
  const bodyObj = params["body"];
1461
1664
  for (const [key, value] of Object.entries(bodyObj)) {
1462
1665
  formData.append(key, value instanceof Blob ? value : String(value));
1463
1666
  }
1464
- fetchOptions.body = formData;
1667
+ body = formData;
1465
1668
  } else if (resolvedMediaType.startsWith("text/")) {
1466
- fetchOptions.body = String(params["body"]);
1669
+ body = String(params["body"]);
1467
1670
  } else {
1468
- fetchOptions.body = JSON.stringify(params["body"]);
1671
+ body = JSON.stringify(params["body"]);
1469
1672
  }
1470
1673
  }
1471
- const response = await fetch(url, fetchOptions);
1674
+ const response = await fetchOriginBound(url, {
1675
+ method: op.method.toUpperCase(),
1676
+ headers: requestHeaders,
1677
+ body,
1678
+ signal: context.signal
1679
+ });
1472
1680
  if (!response.ok) {
1473
1681
  const contentType2 = response.headers.get("content-type") ?? "";
1474
- let body;
1682
+ let errorBody;
1475
1683
  try {
1476
- body = _OpenApiToolLoader.isJsonContentType(contentType2) ? JSON.stringify(await response.json()) : await response.text();
1684
+ errorBody = await readBodyText(response, MAX_ERROR_BODY_BYTES, true);
1685
+ if (_OpenApiToolLoader.isJsonContentType(contentType2)) {
1686
+ try {
1687
+ errorBody = JSON.stringify(JSON.parse(errorBody));
1688
+ } catch {
1689
+ }
1690
+ }
1477
1691
  } catch {
1478
- body = "";
1692
+ errorBody = "";
1479
1693
  }
1480
- throw new Error(`HTTP ${response.status} ${response.statusText}: ${body}`);
1694
+ throw new Error(`HTTP ${response.status} ${response.statusText.slice(0, 128)}: ${errorBody}`);
1481
1695
  }
1482
1696
  const contentType = response.headers.get("content-type") ?? "";
1697
+ const text = await readBodyText(response, maxResponseBytes);
1483
1698
  if (_OpenApiToolLoader.isJsonContentType(contentType)) {
1484
- return response.json();
1699
+ return JSON.parse(text);
1485
1700
  }
1486
- return response.text();
1701
+ return text;
1702
+ };
1703
+ }
1704
+ };
1705
+ function positive(value) {
1706
+ return typeof value === "number" && value > 0 ? value : void 0;
1707
+ }
1708
+ function setHeader(headers, name, value) {
1709
+ const lower = name.toLowerCase();
1710
+ for (const existing of Object.keys(headers)) {
1711
+ if (existing.toLowerCase() === lower) delete headers[existing];
1712
+ }
1713
+ headers[name] = value;
1714
+ }
1715
+ function invalidPathParameter(op) {
1716
+ const error = new Error(`Invalid path parameter for ${op.method.toUpperCase()} ${op.path}`);
1717
+ error.code = "INVALID_PATH_PARAMETER";
1718
+ return error;
1719
+ }
1720
+
1721
+ // libs/broker/src/openapi/openapi-spec-poller.ts
1722
+ var DEFAULT_RETRY = {
1723
+ maxRetries: 3,
1724
+ initialDelayMs: 1e3,
1725
+ maxDelayMs: 1e4,
1726
+ backoffMultiplier: 2
1727
+ };
1728
+ var OpenApiSpecPoller = class extends import_events.EventEmitter {
1729
+ config;
1730
+ intervalTimer = null;
1731
+ lastHash = null;
1732
+ lastEtag = null;
1733
+ lastModified = null;
1734
+ consecutiveFailures = 0;
1735
+ isPolling = false;
1736
+ wasUnhealthy = false;
1737
+ /** Per-run abort controller — aborted on stop(), recreated on start() */
1738
+ _runAbort = new AbortController();
1739
+ _fetchController = null;
1740
+ _activePoll = null;
1741
+ constructor(config) {
1742
+ super();
1743
+ this.config = {
1744
+ url: config.url,
1745
+ intervalMs: config.intervalMs ?? 6e4,
1746
+ fetchTimeoutMs: config.fetchTimeoutMs ?? 1e4,
1747
+ changeDetection: config.changeDetection ?? "auto",
1748
+ unhealthyThreshold: config.unhealthyThreshold ?? 3,
1749
+ retry: { ...DEFAULT_RETRY, ...config.retry },
1750
+ headers: config.headers ?? {},
1751
+ maxSpecBytes: typeof config.maxSpecBytes === "number" && config.maxSpecBytes > 0 ? config.maxSpecBytes : DEFAULT_MAX_SPEC_BYTES
1487
1752
  };
1488
1753
  }
1754
+ /**
1755
+ * Start polling for changes.
1756
+ */
1757
+ start() {
1758
+ if (this.intervalTimer) return;
1759
+ this._runAbort = new AbortController();
1760
+ const runSignal = this._runAbort.signal;
1761
+ const pendingPoll = this._activePoll;
1762
+ if (pendingPoll) {
1763
+ pendingPoll.finally(() => {
1764
+ if (!runSignal.aborted) {
1765
+ this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
1766
+ }
1767
+ });
1768
+ } else {
1769
+ this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
1770
+ }
1771
+ this.intervalTimer = setInterval(() => {
1772
+ this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
1773
+ }, this.config.intervalMs);
1774
+ }
1775
+ /**
1776
+ * Stop polling.
1777
+ */
1778
+ stop() {
1779
+ this._runAbort.abort();
1780
+ if (this._fetchController) {
1781
+ this._fetchController.abort();
1782
+ this._fetchController = null;
1783
+ }
1784
+ if (this.intervalTimer) {
1785
+ clearInterval(this.intervalTimer);
1786
+ this.intervalTimer = null;
1787
+ }
1788
+ }
1789
+ /**
1790
+ * Get the current content hash.
1791
+ */
1792
+ getHash() {
1793
+ return this.lastHash;
1794
+ }
1795
+ /**
1796
+ * Get the number of consecutive failures.
1797
+ */
1798
+ getConsecutiveFailures() {
1799
+ return this.consecutiveFailures;
1800
+ }
1801
+ /**
1802
+ * Perform a single poll cycle.
1803
+ */
1804
+ async poll() {
1805
+ return this.pollWithSignal(this._runAbort.signal);
1806
+ }
1807
+ async pollWithSignal(runSignal) {
1808
+ if (this.isPolling) return;
1809
+ this.isPolling = true;
1810
+ try {
1811
+ await this.fetchWithRetry(runSignal);
1812
+ } finally {
1813
+ this.isPolling = false;
1814
+ this._activePoll = null;
1815
+ }
1816
+ }
1817
+ async fetchWithRetry(runSignal) {
1818
+ const { maxRetries, initialDelayMs, maxDelayMs, backoffMultiplier } = this.config.retry;
1819
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
1820
+ if (runSignal.aborted) return;
1821
+ try {
1822
+ await this.doFetch(runSignal);
1823
+ if (runSignal.aborted) return;
1824
+ if (this.consecutiveFailures > 0) {
1825
+ this.consecutiveFailures = 0;
1826
+ if (this.wasUnhealthy) {
1827
+ this.wasUnhealthy = false;
1828
+ this.emit("recovered");
1829
+ }
1830
+ }
1831
+ return;
1832
+ } catch (error) {
1833
+ if (runSignal.aborted) return;
1834
+ if (attempt === maxRetries) {
1835
+ this.consecutiveFailures++;
1836
+ this.emit("pollError", error instanceof Error ? error : new Error(String(error)));
1837
+ if (this.consecutiveFailures >= this.config.unhealthyThreshold && !this.wasUnhealthy) {
1838
+ this.wasUnhealthy = true;
1839
+ this.emit("unhealthy", this.consecutiveFailures);
1840
+ }
1841
+ return;
1842
+ }
1843
+ const delay = Math.min(initialDelayMs * Math.pow(backoffMultiplier, attempt), maxDelayMs);
1844
+ await new Promise((resolve) => {
1845
+ const onAbort = () => {
1846
+ clearTimeout(timer);
1847
+ resolve();
1848
+ };
1849
+ const timer = setTimeout(() => {
1850
+ runSignal.removeEventListener("abort", onAbort);
1851
+ resolve();
1852
+ }, delay);
1853
+ runSignal.addEventListener("abort", onAbort, { once: true });
1854
+ });
1855
+ }
1856
+ }
1857
+ }
1858
+ async doFetch(runSignal) {
1859
+ if (runSignal.aborted) return;
1860
+ const headers = { ...this.config.headers };
1861
+ if (this.config.changeDetection !== "content-hash") {
1862
+ if (this.lastEtag) {
1863
+ headers["If-None-Match"] = this.lastEtag;
1864
+ }
1865
+ if (this.lastModified) {
1866
+ headers["If-Modified-Since"] = this.lastModified;
1867
+ }
1868
+ }
1869
+ const controller = new AbortController();
1870
+ this._fetchController = controller;
1871
+ const timeout = setTimeout(() => controller.abort(), this.config.fetchTimeoutMs);
1872
+ try {
1873
+ const response = await fetch(this.config.url, {
1874
+ headers,
1875
+ signal: controller.signal
1876
+ });
1877
+ if (runSignal.aborted) return;
1878
+ if (response.status === 304) {
1879
+ this.emit("unchanged");
1880
+ return;
1881
+ }
1882
+ if (!response.ok) {
1883
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1884
+ }
1885
+ const etag = response.headers.get("etag");
1886
+ const lastModified = response.headers.get("last-modified");
1887
+ const body = await readBodyText(response, this.config.maxSpecBytes);
1888
+ if (runSignal.aborted) return;
1889
+ const hash = await sha256Hex(body);
1890
+ if (runSignal.aborted) return;
1891
+ if (this.lastHash && this.lastHash === hash) {
1892
+ this.emit("unchanged");
1893
+ if (etag) this.lastEtag = etag;
1894
+ if (lastModified) this.lastModified = lastModified;
1895
+ return;
1896
+ }
1897
+ this.emit("changed", body, hash);
1898
+ this.lastHash = hash;
1899
+ if (etag) this.lastEtag = etag;
1900
+ if (lastModified) this.lastModified = lastModified;
1901
+ } finally {
1902
+ clearTimeout(timeout);
1903
+ if (this._fetchController === controller) {
1904
+ this._fetchController = null;
1905
+ }
1906
+ }
1907
+ }
1908
+ /**
1909
+ * Dispose the poller and release resources.
1910
+ */
1911
+ dispose() {
1912
+ this.stop();
1913
+ this.removeAllListeners();
1914
+ }
1489
1915
  };
1490
1916
 
1491
1917
  // libs/broker/src/openapi/openapi-source.ts
1918
+ var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
1492
1919
  var OpenApiSource = class extends import_events2.EventEmitter {
1493
1920
  toolRegistry;
1494
1921
  config;
@@ -1496,7 +1923,10 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1496
1923
  previousToolNames = /* @__PURE__ */ new Set();
1497
1924
  lastUpdate = "";
1498
1925
  specHash = "";
1499
- health = "unknown";
1926
+ loaded = false;
1927
+ syncFailed = false;
1928
+ pollFailing = false;
1929
+ lastError;
1500
1930
  disposed = false;
1501
1931
  _syncLock = Promise.resolve();
1502
1932
  constructor(toolRegistry, config) {
@@ -1506,6 +1936,11 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1506
1936
  }
1507
1937
  /**
1508
1938
  * Initial load + start polling.
1939
+ *
1940
+ * A failure while polling (a specification that cannot be fetched, parsed or applied) is
1941
+ * reported with the `error` event when it has a listener, and always through `getStats()`:
1942
+ * `pollHealth` becomes `unhealthy` and `lastError` holds the message. The tools of the last
1943
+ * specification that was applied stay registered.
1509
1944
  */
1510
1945
  async start() {
1511
1946
  if (this.disposed) throw new Error("OpenApiSource is disposed");
@@ -1513,25 +1948,30 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1513
1948
  this.poller = new OpenApiSpecPoller(this.config);
1514
1949
  this.poller.on("changed", (spec) => {
1515
1950
  this._syncLock = this._syncLock.then(async () => {
1516
- try {
1517
- const parsed = JSON.parse(spec);
1518
- await this.syncTools(parsed);
1519
- this.health = "healthy";
1520
- } catch (error) {
1521
- this.emit("error", error instanceof Error ? error : new Error(String(error)));
1951
+ if (this.disposed) return;
1952
+ const parsed = JSON.parse(spec);
1953
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1954
+ throw new Error("The OpenAPI spec is not a JSON object");
1522
1955
  }
1956
+ await this.syncTools(parsed);
1957
+ }).catch((error) => {
1958
+ this.syncFailed = true;
1959
+ this.reportError(error);
1523
1960
  });
1524
1961
  });
1525
1962
  this.poller.on("unhealthy", (failures) => {
1526
- this.health = "unhealthy";
1527
- this.emit("unhealthy", failures);
1963
+ this.pollFailing = true;
1964
+ this.notify("unhealthy", failures);
1528
1965
  });
1529
1966
  this.poller.on("recovered", () => {
1530
- this.health = "healthy";
1531
- this.emit("recovered");
1967
+ this.pollFailing = false;
1968
+ this.notify("recovered");
1532
1969
  });
1533
1970
  this.poller.on("pollError", (error) => {
1534
- this.emit("error", error);
1971
+ this.reportError(error);
1972
+ });
1973
+ this.poller.on("unchanged", () => {
1974
+ if (!this.syncFailed) this.lastError = void 0;
1535
1975
  });
1536
1976
  this.poller.start();
1537
1977
  }
@@ -1545,50 +1985,32 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1545
1985
  }
1546
1986
  /**
1547
1987
  * Manual refresh (for webhook triggers).
1988
+ *
1989
+ * @throws when the specification cannot be fetched or applied; the registered tools are
1990
+ * then what they were before
1548
1991
  */
1549
1992
  async refresh() {
1550
1993
  if (this.disposed) throw new Error("OpenApiSource is disposed");
1551
- const loader = await OpenApiToolLoader.fromURL(
1552
- this.config.url,
1553
- {
1554
- ...this.config.loaderOptions,
1555
- baseUrl: this.config.baseUrl,
1556
- sourceName: this.config.name
1557
- },
1558
- this.config.auth
1559
- );
1560
- const tools = loader.getTools();
1561
- const newToolNames = loader.getToolNames();
1562
- const oldToolNames = this.previousToolNames;
1563
- for (const tool of tools) {
1564
- if (this.toolRegistry.has(tool.name)) {
1565
- this.toolRegistry.replace(tool);
1566
- } else {
1567
- this.toolRegistry.register(tool);
1568
- }
1569
- }
1570
- for (const name of oldToolNames) {
1571
- if (!newToolNames.has(name)) {
1572
- this.toolRegistry.unregister(name);
1573
- }
1574
- }
1575
- this.previousToolNames = newToolNames;
1576
- this.specHash = loader.getSpecHash();
1577
- this.lastUpdate = (/* @__PURE__ */ new Date()).toISOString();
1578
- this.health = "healthy";
1579
- const added = [...newToolNames].filter((n) => !oldToolNames.has(n));
1580
- const removed = [...oldToolNames].filter((n) => !newToolNames.has(n));
1581
- this.emit("toolsUpdated", {
1582
- added,
1583
- removed,
1584
- updated: [...newToolNames].filter((n) => oldToolNames.has(n))
1585
- });
1586
- if (added.length > 0 || removed.length > 0) {
1587
- this.emit("catalogChanged", {
1588
- version: this.specHash,
1589
- addedActions: added,
1590
- removedActions: removed
1591
- });
1994
+ try {
1995
+ const loader = await OpenApiToolLoader.fromURL(
1996
+ this.config.url,
1997
+ {
1998
+ // The request for the specification is the one the poller sends: same headers,
1999
+ // same timeout, same size limit.
2000
+ specHeaders: this.config.headers,
2001
+ specTimeoutMs: this.config.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
2002
+ maxSpecBytes: this.config.maxSpecBytes,
2003
+ ...this.config.loaderOptions,
2004
+ baseUrl: this.config.baseUrl,
2005
+ sourceName: this.config.name
2006
+ },
2007
+ this.config.auth
2008
+ );
2009
+ this.applyTools(loader);
2010
+ } catch (error) {
2011
+ this.syncFailed = true;
2012
+ this.lastError = error instanceof Error ? error : new Error(String(error));
2013
+ throw error;
1592
2014
  }
1593
2015
  }
1594
2016
  /**
@@ -1604,21 +2026,32 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1604
2026
  },
1605
2027
  this.config.auth
1606
2028
  );
2029
+ this.applyTools(loader);
2030
+ }
2031
+ /**
2032
+ * Replace the tools of this source with the tools of a loaded specification, in one step:
2033
+ * either every tool of the new specification is registered and every tool that is gone is
2034
+ * removed, or nothing changes. A tool this source does not manage is never replaced.
2035
+ */
2036
+ applyTools(loader) {
1607
2037
  const newTools = loader.getTools();
1608
2038
  const newToolNames = loader.getToolNames();
2039
+ const oldToolNames = this.previousToolNames;
2040
+ for (const tool of newTools) {
2041
+ if (!oldToolNames.has(tool.name) && this.toolRegistry.has(tool.name)) {
2042
+ throw new Error(
2043
+ `Tool "${tool.name}" is already registered and is not managed by OpenAPI source "${this.config.name}"`
2044
+ );
2045
+ }
2046
+ }
1609
2047
  const added = [];
1610
2048
  const removed = [];
1611
2049
  const updated = [];
1612
2050
  for (const tool of newTools) {
1613
- if (this.previousToolNames.has(tool.name)) {
1614
- this.toolRegistry.replace(tool);
1615
- updated.push(tool.name);
1616
- } else {
1617
- this.toolRegistry.register(tool);
1618
- added.push(tool.name);
1619
- }
2051
+ this.toolRegistry.replace(tool);
2052
+ (oldToolNames.has(tool.name) ? updated : added).push(tool.name);
1620
2053
  }
1621
- for (const name of this.previousToolNames) {
2054
+ for (const name of oldToolNames) {
1622
2055
  if (!newToolNames.has(name)) {
1623
2056
  this.toolRegistry.unregister(name);
1624
2057
  removed.push(name);
@@ -1627,16 +2060,39 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1627
2060
  this.previousToolNames = newToolNames;
1628
2061
  this.specHash = loader.getSpecHash();
1629
2062
  this.lastUpdate = (/* @__PURE__ */ new Date()).toISOString();
2063
+ this.loaded = true;
2064
+ this.syncFailed = false;
2065
+ this.lastError = void 0;
1630
2066
  const event = { added, removed, updated };
1631
- this.emit("toolsUpdated", event);
2067
+ this.notify("toolsUpdated", event);
1632
2068
  if (added.length > 0 || removed.length > 0) {
1633
- this.emit("catalogChanged", {
2069
+ this.notify("catalogChanged", {
1634
2070
  version: this.specHash,
1635
2071
  addedActions: added,
1636
2072
  removedActions: removed
1637
2073
  });
1638
2074
  }
1639
2075
  }
2076
+ /**
2077
+ * Record a failure and tell the `error` listeners, if there are any. Without a listener the
2078
+ * failure is kept for `getStats()`; it is never raised from here.
2079
+ */
2080
+ reportError(error) {
2081
+ this.lastError = error instanceof Error ? error : new Error(String(error));
2082
+ if (this.listenerCount("error") > 0) {
2083
+ this.notify("error", this.lastError);
2084
+ }
2085
+ }
2086
+ /**
2087
+ * Emit an event. A listener that throws does not stop the source.
2088
+ */
2089
+ notify(event, ...args) {
2090
+ if (event === "error" && this.listenerCount("error") === 0) return;
2091
+ try {
2092
+ this.emit(event, ...args);
2093
+ } catch {
2094
+ }
2095
+ }
1640
2096
  /**
1641
2097
  * Get the set of tool names managed by this source.
1642
2098
  */
@@ -1647,11 +2103,13 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1647
2103
  * Get source statistics.
1648
2104
  */
1649
2105
  getStats() {
2106
+ const failing = this.syncFailed || this.pollFailing;
1650
2107
  return {
1651
2108
  toolCount: this.previousToolNames.size,
1652
2109
  lastUpdate: this.lastUpdate,
1653
2110
  specHash: this.specHash,
1654
- pollHealth: this.health
2111
+ pollHealth: failing ? "unhealthy" : this.loaded ? "healthy" : "unknown",
2112
+ ...this.lastError && { lastError: this.lastError.message }
1655
2113
  };
1656
2114
  }
1657
2115
  /**
@@ -1676,23 +2134,44 @@ var OpenApiSource = class extends import_events2.EventEmitter {
1676
2134
  };
1677
2135
 
1678
2136
  // libs/broker/src/broker.ts
2137
+ var KNOWN_CONFIG_KEYS = ["sessions", "enclave", "limits", "history"];
1679
2138
  var Broker = class {
1680
2139
  toolRegistry;
1681
2140
  sessionManager;
1682
2141
  config;
1683
2142
  openApiSources = [];
2143
+ defaultLimits;
1684
2144
  disposed = false;
1685
2145
  constructor(config = {}) {
2146
+ for (const key of Object.keys(config)) {
2147
+ if (!KNOWN_CONFIG_KEYS.includes(key)) {
2148
+ console.warn(
2149
+ `[@enclave-vm/broker] Broker: unknown configuration key ${JSON.stringify(key.slice(0, 64))} is ignored`
2150
+ );
2151
+ }
2152
+ }
1686
2153
  this.config = config;
1687
2154
  this.toolRegistry = createToolRegistry();
2155
+ const sessionDefaults = config.sessions?.defaultSessionConfig ?? {};
2156
+ const limits = mergeSessionLimits(sessionDefaults.limits, config.limits);
2157
+ this.defaultLimits = Object.freeze(resolveSessionLimits(limits));
1688
2158
  this.sessionManager = createSessionManager(this.toolRegistry, {
1689
2159
  ...config.sessions,
1690
2160
  defaultSessionConfig: {
1691
- limits: config.limits,
1692
- enclaveConfig: config.enclave
2161
+ ...sessionDefaults,
2162
+ limits,
2163
+ enclaveConfig: config.enclave ?? sessionDefaults.enclaveConfig,
2164
+ history: resolveHistoryLimits({ ...sessionDefaults.history, ...config.history })
1693
2165
  }
1694
2166
  });
1695
2167
  }
2168
+ /**
2169
+ * The limits of a session that names none: the broker's configuration over the package
2170
+ * defaults. The HTTP routes use them as the ceiling of what a request may ask for.
2171
+ */
2172
+ get sessionLimits() {
2173
+ return this.defaultLimits;
2174
+ }
1696
2175
  // ============================================================================
1697
2176
  // Tool Registration
1698
2177
  // ============================================================================
@@ -1959,41 +2438,72 @@ function createBroker(config) {
1959
2438
  return new Broker(config);
1960
2439
  }
1961
2440
 
2441
+ // libs/broker/src/http/session-handler.ts
2442
+ var import_types5 = require("@enclave-vm/types");
2443
+
1962
2444
  // libs/broker/src/event-filter.ts
1963
- var import_types2 = require("@enclave-vm/types");
2445
+ var import_node_vm = require("node:vm");
2446
+ var import_types3 = require("@enclave-vm/types");
1964
2447
  var import_minimatch = require("minimatch");
1965
- var MAX_REGEX_INPUT_LENGTH = 1e4;
1966
- var MAX_PATTERN_LENGTH_FOR_REDOS_CHECK = 500;
1967
- var REDOS_DETECTION_PATTERNS = {
1968
- /** Check for nested quantifiers: (a+)+ or (a*)* */
1969
- nestedQuantifiers: /\([^)]{0,100}[*+{][^)]{0,100}\)[*+{]/,
1970
- /** Check for alternation with overlapping patterns: (a|ab)* */
1971
- alternationOverlap: /\([^|]{0,100}\|[^)]{0,100}\)[*+{]/,
1972
- /** Check for repeated groups with quantifiers: (a+)+ */
1973
- repeatedGroups: /\([^)]{0,100}[*+][^)]{0,100}\)[*+]/
1974
- };
1975
- function isPotentiallyVulnerableRegex(pattern) {
1976
- const safePattern = pattern.length > MAX_PATTERN_LENGTH_FOR_REDOS_CHECK ? pattern.slice(0, MAX_PATTERN_LENGTH_FOR_REDOS_CHECK) : pattern;
2448
+ var DEFAULT_EVALUATION_TIMEOUT_MS = 100;
2449
+ var MAX_EVALUATION_TIMEOUT_MS = 1e4;
2450
+ var MAX_EVALUATION_ATTEMPTS = 5;
2451
+ var STARVED_CPU_SHARE = 0.5;
2452
+ function cpuTimeMs() {
2453
+ const perThread = process.threadCpuUsage;
2454
+ const usage = typeof perThread === "function" ? perThread.call(process) : process.cpuUsage();
2455
+ return (usage.user + usage.system) / 1e3;
2456
+ }
2457
+ var ANY = 0;
2458
+ var ONE = 1;
2459
+ var boundedRealm = {};
2460
+ var boundedScript;
2461
+ var insideBounded = false;
2462
+ function runBounded(fn, timeoutMs) {
2463
+ if (insideBounded) {
2464
+ return { done: true, value: fn() };
2465
+ }
2466
+ if (!boundedScript) {
2467
+ (0, import_node_vm.createContext)(boundedRealm);
2468
+ boundedScript = new import_node_vm.Script("run()");
2469
+ }
2470
+ boundedRealm.run = fn;
2471
+ insideBounded = true;
1977
2472
  try {
1978
- if (REDOS_DETECTION_PATTERNS.nestedQuantifiers.test(safePattern)) return true;
1979
- if (REDOS_DETECTION_PATTERNS.alternationOverlap.test(safePattern)) return true;
1980
- if (REDOS_DETECTION_PATTERNS.repeatedGroups.test(safePattern)) return true;
1981
- } catch {
1982
- return false;
2473
+ return { done: true, value: boundedScript.runInContext(boundedRealm, { timeout: timeoutMs }) };
2474
+ } catch (error) {
2475
+ if (error?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") {
2476
+ return { done: false };
2477
+ }
2478
+ throw error;
2479
+ } finally {
2480
+ insideBounded = false;
2481
+ boundedRealm.run = void 0;
1983
2482
  }
1984
- return false;
1985
2483
  }
1986
2484
  var EventFilter = class {
1987
- config;
2485
+ exclude;
1988
2486
  alwaysAllow;
1989
- compiledRegexes;
2487
+ rules;
2488
+ timeoutMs;
2489
+ budgetMs;
2490
+ expandGlobs;
1990
2491
  onError;
2492
+ spentMs = 0;
1991
2493
  constructor(options) {
1992
- this.config = options.config;
2494
+ const config = options.config;
2495
+ if (typeof config !== "object" || config === null || !Array.isArray(config.rules)) {
2496
+ throw new TypeError('EventFilter: the configuration needs a "rules" array');
2497
+ }
1993
2498
  this.onError = options.onError;
1994
- this.alwaysAllow = new Set(options.config.alwaysAllow ?? import_types2.DEFAULT_ALWAYS_ALLOW);
1995
- this.compiledRegexes = /* @__PURE__ */ new Map();
1996
- this.compilePatterns();
2499
+ this.exclude = config.mode !== import_types3.FilterMode.Include;
2500
+ this.alwaysAllow = new Set(config.alwaysAllow ?? import_types3.DEFAULT_ALWAYS_ALLOW);
2501
+ this.expandGlobs = options.expandGlobs ?? true;
2502
+ const timeout = config.regexTimeoutMs;
2503
+ this.timeoutMs = typeof timeout === "number" && timeout > 0 ? Math.min(Math.max(Math.ceil(timeout), 1), MAX_EVALUATION_TIMEOUT_MS) : DEFAULT_EVALUATION_TIMEOUT_MS;
2504
+ const budget = options.budgetMs;
2505
+ this.budgetMs = typeof budget === "number" && budget >= 0 ? budget : void 0;
2506
+ this.rules = config.rules.map((rule) => this.compileRule(rule));
1997
2507
  }
1998
2508
  /**
1999
2509
  * Check if an event should be sent to the client.
@@ -2002,12 +2512,30 @@ var EventFilter = class {
2002
2512
  if (this.alwaysAllow.has(event.type)) {
2003
2513
  return true;
2004
2514
  }
2005
- const matches = this.matchesAnyRule(event);
2006
- if (this.config.mode === import_types2.FilterMode.Include) {
2007
- return matches;
2008
- } else {
2009
- return !matches;
2515
+ const subjects = /* @__PURE__ */ new Map();
2516
+ const send = this.decide(event, subjects);
2517
+ if (this.onError) {
2518
+ for (const subject of subjects.values()) {
2519
+ if (subject.error) this.onError(subject.error, event);
2520
+ }
2521
+ }
2522
+ return send;
2523
+ }
2524
+ /**
2525
+ * Decide one event that is not always allowed.
2526
+ */
2527
+ decide(event, subjects) {
2528
+ let matches = this.matchesAnyRule(event, subjects, false);
2529
+ if (matches === void 0) {
2530
+ if (this.budgetUsedUp()) {
2531
+ return false;
2532
+ }
2533
+ matches = this.evaluateWithinLimit(event, subjects);
2534
+ if (matches === void 0) {
2535
+ return false;
2536
+ }
2010
2537
  }
2538
+ return this.exclude ? !matches : matches;
2011
2539
  }
2012
2540
  /**
2013
2541
  * Filter an array of events.
@@ -2016,165 +2544,308 @@ var EventFilter = class {
2016
2544
  return events.filter((event) => this.shouldSend(event));
2017
2545
  }
2018
2546
  /**
2019
- * Check if event matches any filter rule.
2547
+ * Whether the budget of this filter is used up.
2020
2548
  */
2021
- matchesAnyRule(event) {
2022
- return this.config.rules.some((rule) => this.matchesRule(event, rule));
2549
+ budgetUsedUp() {
2550
+ return this.budgetMs !== void 0 && this.spentMs >= this.budgetMs;
2551
+ }
2552
+ /**
2553
+ * Evaluate all rules, slow patterns included, under the time limit. Returns undefined when
2554
+ * the evaluation did not finish.
2555
+ *
2556
+ * The limit is a limit on elapsed time. When it is reached although the thread got little
2557
+ * processor time meanwhile (the machine was busy with something else), the evaluation is
2558
+ * tried again, a bounded number of times, so that a busy machine does not drop events. An
2559
+ * evaluation that used its time on a processor is not tried again.
2560
+ */
2561
+ evaluateWithinLimit(event, subjects) {
2562
+ for (let attempt = 1; ; attempt++) {
2563
+ let limit = this.timeoutMs;
2564
+ if (this.budgetMs !== void 0) {
2565
+ limit = Math.max(1, Math.min(limit, Math.ceil(this.budgetMs - this.spentMs)));
2566
+ }
2567
+ const cpuBefore = cpuTimeMs();
2568
+ const outcome = runBounded(() => {
2569
+ const started = cpuTimeMs();
2570
+ const matches = this.matchesAnyRule(event, subjects, true) === true;
2571
+ return { matches, used: cpuTimeMs() - started };
2572
+ }, limit);
2573
+ if (outcome.done) {
2574
+ this.spentMs += outcome.value.used;
2575
+ return outcome.value.matches;
2576
+ }
2577
+ this.recompileGlobs();
2578
+ const cpuMs = cpuTimeMs() - cpuBefore;
2579
+ const starved = cpuMs < limit * STARVED_CPU_SHARE;
2580
+ this.spentMs += starved ? cpuMs : limit;
2581
+ if (starved && attempt < MAX_EVALUATION_ATTEMPTS && !this.budgetUsedUp()) {
2582
+ continue;
2583
+ }
2584
+ this.onError?.(new Error("Event filter evaluation exceeded its time limit"), event);
2585
+ return void 0;
2586
+ }
2587
+ }
2588
+ /**
2589
+ * Check if event matches any filter rule. With `slow` false, patterns that need the time
2590
+ * limit are put off and the answer is undefined when it depends on one of them.
2591
+ */
2592
+ matchesAnyRule(event, subjects, slow) {
2593
+ let putOff = false;
2594
+ for (const rule of this.rules) {
2595
+ const match = this.matchesRule(event, rule, subjects, slow);
2596
+ if (match === true) return true;
2597
+ if (match === void 0) putOff = true;
2598
+ }
2599
+ return putOff ? void 0 : false;
2600
+ }
2601
+ /**
2602
+ * Check if event matches a specific rule. If the rule has both a type filter and a content
2603
+ * filter, both must match.
2604
+ */
2605
+ matchesRule(event, rule, subjects, slow) {
2606
+ if (rule.types && !rule.types.has(event.type)) {
2607
+ return false;
2608
+ }
2609
+ if (!rule.patterns) {
2610
+ return true;
2611
+ }
2612
+ let putOff = false;
2613
+ for (const pattern of rule.patterns) {
2614
+ const match = this.matchesPattern(event, pattern, subjects, slow);
2615
+ if (match === void 0) {
2616
+ putOff = true;
2617
+ } else if (match !== rule.matchAll) {
2618
+ return match;
2619
+ }
2620
+ }
2621
+ return putOff ? void 0 : rule.matchAll;
2023
2622
  }
2024
2623
  /**
2025
- * Check if event matches a specific rule.
2624
+ * Check if event matches a content pattern.
2026
2625
  */
2027
- matchesRule(event, rule) {
2028
- const typeMatch = rule.types ? this.matchesTypeFilter(event, rule.types) : true;
2029
- const contentMatch = rule.content ? this.matchesContentFilter(event, rule.content) : true;
2030
- if (rule.types && rule.content) {
2031
- return typeMatch && contentMatch;
2626
+ matchesPattern(event, pattern, subjects, slow) {
2627
+ const subject = this.subjectOf(event, pattern, subjects);
2628
+ if (subject.failed) {
2629
+ return this.notEvaluable();
2630
+ }
2631
+ if (subject.text === void 0) {
2632
+ return false;
2633
+ }
2634
+ switch (pattern.type) {
2635
+ case import_types3.PatternType.Exact:
2636
+ return this.textOf(subject, pattern) === pattern.text;
2637
+ case import_types3.PatternType.Prefix:
2638
+ return this.textOf(subject, pattern).startsWith(pattern.text);
2639
+ case import_types3.PatternType.Regex:
2640
+ if (!pattern.regex) return this.notEvaluable();
2641
+ if (!slow) return void 0;
2642
+ return pattern.regex.test(subject.text);
2643
+ case import_types3.PatternType.Glob:
2644
+ if (!pattern.glob) return this.notEvaluable();
2645
+ if (!slow) return void 0;
2646
+ if (pattern.glob.match(subject.text)) return true;
2647
+ return pattern.wildcard ? matchesWildcard(this.textOf(subject, pattern), pattern.wildcard) : false;
2648
+ default:
2649
+ return this.notEvaluable();
2032
2650
  }
2033
- return rule.types ? typeMatch : contentMatch;
2034
2651
  }
2035
2652
  /**
2036
- * Check if event type matches filter.
2653
+ * What a pattern that cannot be evaluated counts as: a match when matching keeps an event
2654
+ * back (exclude), no match when matching lets it through (include).
2037
2655
  */
2038
- matchesTypeFilter(event, filter) {
2039
- return filter.types.includes(event.type);
2656
+ notEvaluable() {
2657
+ return this.exclude;
2040
2658
  }
2041
2659
  /**
2042
- * Check if event content matches filter.
2660
+ * The subject text in the case the pattern compares in.
2043
2661
  */
2044
- matchesContentFilter(event, filter) {
2045
- const matchMode = filter.match ?? "any";
2046
- if (matchMode === "all") {
2047
- return filter.patterns.every((pattern) => this.matchesPattern(event, pattern));
2048
- } else {
2049
- return filter.patterns.some((pattern) => this.matchesPattern(event, pattern));
2050
- }
2662
+ textOf(subject, pattern) {
2663
+ if (!pattern.caseInsensitive) return subject.text;
2664
+ if (subject.lower === void 0) subject.lower = subject.text.toLowerCase();
2665
+ return subject.lower;
2051
2666
  }
2052
2667
  /**
2053
- * Check if event matches a content pattern.
2668
+ * The text of the field a pattern reads, computed once per event.
2054
2669
  */
2055
- matchesPattern(event, pattern) {
2056
- const value = this.getFieldValue(event, pattern.field);
2057
- if (value === void 0) {
2058
- return false;
2059
- }
2060
- const stringValue = this.stringify(value);
2061
- const patternValue = pattern.caseInsensitive ? pattern.pattern.toLowerCase() : pattern.pattern;
2062
- const matchValue = pattern.caseInsensitive ? stringValue.toLowerCase() : stringValue;
2063
- try {
2064
- switch (pattern.type) {
2065
- case import_types2.PatternType.Exact:
2066
- return matchValue === patternValue;
2067
- case import_types2.PatternType.Prefix:
2068
- return matchValue.startsWith(patternValue);
2069
- case import_types2.PatternType.Regex:
2070
- return this.matchRegex(pattern.pattern, matchValue, pattern.caseInsensitive);
2071
- case import_types2.PatternType.Glob:
2072
- return (0, import_minimatch.minimatch)(matchValue, patternValue, {
2073
- nocase: pattern.caseInsensitive
2074
- });
2075
- default:
2076
- return false;
2670
+ subjectOf(event, pattern, subjects) {
2671
+ let subject = subjects.get(pattern.key);
2672
+ if (subject) return subject;
2673
+ subject = { failed: false };
2674
+ const value = pattern.path ? readField(event, pattern.path) : event.payload;
2675
+ if (typeof value === "string") {
2676
+ subject.text = value;
2677
+ } else if (value === null) {
2678
+ subject.text = "";
2679
+ } else if (value !== void 0) {
2680
+ try {
2681
+ subject.text = JSON.stringify(value) ?? "";
2682
+ } catch (error) {
2683
+ subject.failed = true;
2684
+ subject.error = error;
2077
2685
  }
2078
- } catch (error) {
2079
- this.onError?.(error, event);
2080
- return false;
2081
2686
  }
2687
+ subjects.set(pattern.key, subject);
2688
+ return subject;
2082
2689
  }
2083
2690
  /**
2084
- * Get field value from event using dot notation.
2691
+ * Compile one rule.
2085
2692
  */
2086
- getFieldValue(event, field) {
2087
- if (!field) {
2088
- return event.payload;
2693
+ compileRule(rule) {
2694
+ const compiled = { matchAll: false };
2695
+ if (typeof rule !== "object" || rule === null) {
2696
+ throw new TypeError("EventFilter: a rule must be an object");
2089
2697
  }
2090
- const parts = field.split(".");
2091
- let value = event;
2092
- for (const part of parts) {
2093
- if (value === null || value === void 0) {
2094
- return void 0;
2698
+ if (rule.types) {
2699
+ if (!Array.isArray(rule.types.types)) {
2700
+ throw new TypeError('EventFilter: a type filter needs a "types" array');
2095
2701
  }
2096
- if (typeof value !== "object") {
2097
- return void 0;
2702
+ compiled.types = new Set(rule.types.types);
2703
+ }
2704
+ if (rule.content) {
2705
+ const content = rule.content;
2706
+ if (!Array.isArray(content.patterns)) {
2707
+ throw new TypeError('EventFilter: a content filter needs a "patterns" array');
2098
2708
  }
2099
- value = value[part];
2709
+ compiled.patterns = content.patterns.map((pattern) => this.compilePattern(pattern));
2710
+ compiled.matchAll = content.match === "all";
2100
2711
  }
2101
- return value;
2712
+ return compiled;
2102
2713
  }
2103
2714
  /**
2104
- * Stringify a value for matching.
2715
+ * Compile a glob. Returns null when the pattern does not compile.
2105
2716
  */
2106
- stringify(value) {
2107
- if (typeof value === "string") {
2108
- return value;
2717
+ compileGlob(source, caseInsensitive) {
2718
+ try {
2719
+ return new import_minimatch.Minimatch(source, {
2720
+ nocase: caseInsensitive,
2721
+ nobrace: !this.expandGlobs,
2722
+ noext: !this.expandGlobs,
2723
+ // An exclude glob is matched as text: also against a leading dot.
2724
+ dot: this.exclude
2725
+ });
2726
+ } catch {
2727
+ return null;
2109
2728
  }
2110
- if (value === null || value === void 0) {
2111
- return "";
2729
+ }
2730
+ /**
2731
+ * Compile every glob of this filter again.
2732
+ */
2733
+ recompileGlobs() {
2734
+ for (const rule of this.rules) {
2735
+ for (const pattern of rule.patterns ?? []) {
2736
+ if (pattern.glob) {
2737
+ pattern.glob = this.compileGlob(pattern.source, pattern.caseInsensitive);
2738
+ }
2739
+ }
2112
2740
  }
2113
- return JSON.stringify(value);
2114
2741
  }
2115
2742
  /**
2116
- * Match against a compiled regex with ReDoS protection.
2117
- * Enforces input length limits to prevent catastrophic backtracking.
2743
+ * Compile one content pattern. A pattern that does not compile is kept as "cannot be
2744
+ * evaluated"; its text is not logged.
2118
2745
  */
2119
- matchRegex(pattern, value, caseInsensitive) {
2120
- if (value.length > MAX_REGEX_INPUT_LENGTH) {
2121
- return false;
2746
+ compilePattern(pattern) {
2747
+ if (typeof pattern !== "object" || pattern === null || typeof pattern.pattern !== "string") {
2748
+ throw new TypeError('EventFilter: a content pattern needs a "pattern" string');
2122
2749
  }
2123
- const cacheKey = `${pattern}:${caseInsensitive ? "i" : ""}`;
2124
- const compiled = this.compiledRegexes.get(cacheKey);
2125
- if (!compiled) {
2750
+ const caseInsensitive = pattern.caseInsensitive === true;
2751
+ const field2 = typeof pattern.field === "string" && pattern.field.length > 0 ? pattern.field : void 0;
2752
+ const compiled = {
2753
+ type: pattern.type,
2754
+ path: field2?.split("."),
2755
+ key: field2 ?? "",
2756
+ caseInsensitive,
2757
+ text: caseInsensitive ? pattern.pattern.toLowerCase() : pattern.pattern,
2758
+ source: pattern.pattern
2759
+ };
2760
+ if (pattern.type === import_types3.PatternType.Regex) {
2126
2761
  try {
2127
- const flags = caseInsensitive ? "i" : "";
2128
- return new RegExp(pattern, flags).test(value);
2762
+ compiled.regex = new RegExp(pattern.pattern, caseInsensitive ? "i" : "");
2129
2763
  } catch {
2130
- return false;
2764
+ compiled.regex = null;
2765
+ }
2766
+ } else if (pattern.type === import_types3.PatternType.Glob) {
2767
+ compiled.glob = this.compileGlob(pattern.pattern, caseInsensitive);
2768
+ if (this.exclude) {
2769
+ compiled.wildcard = compileWildcard(compiled.text);
2131
2770
  }
2132
2771
  }
2133
- try {
2134
- return compiled.regex.test(value);
2135
- } catch {
2136
- return false;
2772
+ return compiled;
2773
+ }
2774
+ };
2775
+ function readField(event, path) {
2776
+ let value = event;
2777
+ for (const part of path) {
2778
+ if (value === null || typeof value !== "object") {
2779
+ return void 0;
2137
2780
  }
2781
+ if (!Object.prototype.hasOwnProperty.call(value, part)) {
2782
+ return void 0;
2783
+ }
2784
+ value = value[part];
2138
2785
  }
2139
- /**
2140
- * Pre-compile all regex patterns for efficiency.
2141
- * Includes ReDoS vulnerability detection and logging.
2142
- */
2143
- compilePatterns() {
2144
- for (const rule of this.config.rules) {
2145
- if (!rule.content?.patterns) continue;
2146
- for (const pattern of rule.content.patterns) {
2147
- if (pattern.type !== import_types2.PatternType.Regex) continue;
2148
- const cacheKey = `${pattern.pattern}:${pattern.caseInsensitive ? "i" : ""}`;
2149
- if (this.compiledRegexes.has(cacheKey)) continue;
2150
- if (isPotentiallyVulnerableRegex(pattern.pattern)) {
2151
- console.warn(
2152
- `[EventFilter] Potentially vulnerable regex pattern detected: ${pattern.pattern}. Input length will be limited to ${MAX_REGEX_INPUT_LENGTH} characters for protection.`
2153
- );
2154
- }
2155
- try {
2156
- const flags = pattern.caseInsensitive ? "i" : "";
2157
- const regex = new RegExp(pattern.pattern, flags);
2158
- this.compiledRegexes.set(cacheKey, { regex });
2159
- } catch (error) {
2160
- console.error(`Invalid regex pattern: ${pattern.pattern}`, error);
2161
- }
2162
- }
2786
+ return value;
2787
+ }
2788
+ function compileWildcard(pattern) {
2789
+ const tokens = [];
2790
+ for (let i = 0; i < pattern.length; i++) {
2791
+ const char = pattern[i];
2792
+ if (char === "*") {
2793
+ if (tokens[tokens.length - 1] !== ANY) tokens.push(ANY);
2794
+ } else if (char === "?") {
2795
+ tokens.push(ONE);
2796
+ } else if (char === "\\" && i + 1 < pattern.length) {
2797
+ tokens.push(pattern[++i]);
2798
+ } else {
2799
+ tokens.push(char);
2163
2800
  }
2164
2801
  }
2165
- };
2802
+ const inner = tokens.slice(1, -1);
2803
+ if (tokens.length >= 3 && tokens[0] === ANY && tokens[tokens.length - 1] === ANY && inner.every((token) => typeof token === "string")) {
2804
+ return { contains: inner.join("") };
2805
+ }
2806
+ return { tokens };
2807
+ }
2808
+ function matchesWildcard(text, wildcard) {
2809
+ if ("contains" in wildcard) {
2810
+ return text.includes(wildcard.contains);
2811
+ }
2812
+ const tokens = wildcard.tokens;
2813
+ let t = 0;
2814
+ let p = 0;
2815
+ let star = -1;
2816
+ let mark = 0;
2817
+ while (t < text.length) {
2818
+ const token = tokens[p];
2819
+ if (p < tokens.length && (token === ONE || token === text[t])) {
2820
+ t++;
2821
+ p++;
2822
+ } else if (p < tokens.length && token === ANY) {
2823
+ star = p;
2824
+ mark = t;
2825
+ p++;
2826
+ } else if (star !== -1) {
2827
+ p = star + 1;
2828
+ mark++;
2829
+ t = mark;
2830
+ } else {
2831
+ return false;
2832
+ }
2833
+ }
2834
+ while (p < tokens.length && tokens[p] === ANY) p++;
2835
+ return p === tokens.length;
2836
+ }
2166
2837
  function createEventFilter(options) {
2167
2838
  return new EventFilter(options);
2168
2839
  }
2169
2840
  function createTypeFilter(mode, types) {
2170
2841
  return {
2171
- mode: mode === "include" ? import_types2.FilterMode.Include : import_types2.FilterMode.Exclude,
2842
+ mode: mode === "include" ? import_types3.FilterMode.Include : import_types3.FilterMode.Exclude,
2172
2843
  rules: [{ types: { types } }]
2173
2844
  };
2174
2845
  }
2175
- function createContentFilter(mode, pattern, patternType = import_types2.PatternType.Regex) {
2846
+ function createContentFilter(mode, pattern, patternType = import_types3.PatternType.Regex) {
2176
2847
  return {
2177
- mode: mode === "include" ? import_types2.FilterMode.Include : import_types2.FilterMode.Exclude,
2848
+ mode: mode === "include" ? import_types3.FilterMode.Include : import_types3.FilterMode.Exclude,
2178
2849
  rules: [
2179
2850
  {
2180
2851
  content: {
@@ -2185,15 +2856,279 @@ function createContentFilter(mode, pattern, patternType = import_types2.PatternT
2185
2856
  };
2186
2857
  }
2187
2858
 
2859
+ // libs/broker/src/http/request-validation.ts
2860
+ var import_types4 = require("@enclave-vm/types");
2861
+ var REQUEST_FILTER_LIMITS = {
2862
+ /** Rules per filter */
2863
+ maxRules: 16,
2864
+ /** Content patterns per filter, over all rules */
2865
+ maxPatterns: 32,
2866
+ /** Characters per pattern */
2867
+ maxPatternLength: 256,
2868
+ /** Characters per field path */
2869
+ maxFieldLength: 128,
2870
+ /** Event types per type filter and per always-allow list */
2871
+ maxTypes: 32,
2872
+ /** Characters per event type */
2873
+ maxTypeLength: 64,
2874
+ /** Characters of the JSON text in the `filter` query parameter */
2875
+ maxQueryLength: 8192,
2876
+ /** Time limit for the evaluation of one event, in milliseconds */
2877
+ evaluationTimeoutMs: 100,
2878
+ /** Time all evaluations of one filter may take together, in milliseconds */
2879
+ budgetMs: 500
2880
+ };
2881
+ var SESSION_ID_PATTERN = /^s_[A-Za-z0-9._:~-]{1,128}$/;
2882
+ function isRequestSessionId(value) {
2883
+ return typeof value === "string" && SESSION_ID_PATTERN.test(value);
2884
+ }
2885
+ var invalid = (message, code = "INVALID_REQUEST") => ({
2886
+ ok: false,
2887
+ code,
2888
+ message
2889
+ });
2890
+ function isPlainObject(value) {
2891
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2892
+ }
2893
+ function field(object, key) {
2894
+ if (!Object.prototype.hasOwnProperty.call(object, key)) return void 0;
2895
+ const value = object[key];
2896
+ return value === null ? void 0 : value;
2897
+ }
2898
+ function isPositiveInteger(value) {
2899
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
2900
+ }
2901
+ var LIMIT_FIELDS = ["maxExecutionMs", "maxToolCalls", "heartbeatIntervalMs"];
2902
+ function parseCreateSessionRequest(body) {
2903
+ if (!isPlainObject(body)) {
2904
+ return invalid('Missing or invalid "code" field');
2905
+ }
2906
+ const code = field(body, "code");
2907
+ if (typeof code !== "string") {
2908
+ return invalid('Missing or invalid "code" field');
2909
+ }
2910
+ const sessionId = field(body, "sessionId");
2911
+ if (sessionId !== void 0 && !isRequestSessionId(sessionId)) {
2912
+ return invalid('Invalid "sessionId" field');
2913
+ }
2914
+ let filter;
2915
+ const rawFilter = field(body, "filter");
2916
+ if (rawFilter !== void 0) {
2917
+ const parsedFilter = parseFilterConfig(rawFilter);
2918
+ if (!parsedFilter.ok) return parsedFilter;
2919
+ filter = parsedFilter.value;
2920
+ }
2921
+ const config = {};
2922
+ const rawConfig = field(body, "config");
2923
+ if (rawConfig !== void 0) {
2924
+ if (!isPlainObject(rawConfig)) {
2925
+ return invalid('Invalid "config" field: expected an object');
2926
+ }
2927
+ for (const key of LIMIT_FIELDS) {
2928
+ const value = field(rawConfig, key);
2929
+ if (value === void 0) continue;
2930
+ if (!isPositiveInteger(value)) {
2931
+ return invalid(`Invalid "config.${key}" field: expected a positive integer`);
2932
+ }
2933
+ config[key] = value;
2934
+ }
2935
+ }
2936
+ const encryption = field(body, "encryption");
2937
+ if (encryption !== void 0) {
2938
+ if (!isPlainObject(encryption)) {
2939
+ return invalid('Invalid "encryption" field: expected an object');
2940
+ }
2941
+ if (field(encryption, "mode") === "required") {
2942
+ return invalid("Encrypted sessions are not supported by this broker", "ENCRYPTION_NOT_SUPPORTED");
2943
+ }
2944
+ }
2945
+ return { ok: true, value: { code, sessionId, config, filter } };
2946
+ }
2947
+ var invalidFilter = (message) => invalid(`Invalid filter configuration: ${message}`, "INVALID_FILTER");
2948
+ var PATTERN_TYPES = Object.values(import_types4.PatternType);
2949
+ function parseTypeList(value) {
2950
+ if (!Array.isArray(value) || value.length > REQUEST_FILTER_LIMITS.maxTypes) return void 0;
2951
+ for (const entry of value) {
2952
+ if (typeof entry !== "string" || entry.length === 0 || entry.length > REQUEST_FILTER_LIMITS.maxTypeLength) {
2953
+ return void 0;
2954
+ }
2955
+ }
2956
+ return [...value];
2957
+ }
2958
+ function parseFilterConfig(value) {
2959
+ if (!isPlainObject(value)) {
2960
+ return invalidFilter("expected an object");
2961
+ }
2962
+ const mode = field(value, "mode");
2963
+ if (mode !== import_types4.FilterMode.Include && mode !== import_types4.FilterMode.Exclude) {
2964
+ return invalidFilter('"mode" must be "include" or "exclude"');
2965
+ }
2966
+ const rawRules = field(value, "rules");
2967
+ if (!Array.isArray(rawRules) || rawRules.length > REQUEST_FILTER_LIMITS.maxRules) {
2968
+ return invalidFilter(`"rules" must be a list of at most ${REQUEST_FILTER_LIMITS.maxRules} rules`);
2969
+ }
2970
+ const rules = [];
2971
+ let patternCount = 0;
2972
+ for (const rawRule of rawRules) {
2973
+ if (!isPlainObject(rawRule)) {
2974
+ return invalidFilter("a rule must be an object");
2975
+ }
2976
+ const rule = {};
2977
+ const rawTypes = field(rawRule, "types");
2978
+ if (rawTypes !== void 0) {
2979
+ const types = isPlainObject(rawTypes) ? parseTypeList(field(rawTypes, "types")) : void 0;
2980
+ if (!types) {
2981
+ return invalidFilter(`"types" must hold a list of at most ${REQUEST_FILTER_LIMITS.maxTypes} event types`);
2982
+ }
2983
+ rule.types = { types };
2984
+ }
2985
+ const rawContent = field(rawRule, "content");
2986
+ if (rawContent !== void 0) {
2987
+ if (!isPlainObject(rawContent)) {
2988
+ return invalidFilter('"content" must be an object');
2989
+ }
2990
+ const rawPatterns = field(rawContent, "patterns");
2991
+ if (!Array.isArray(rawPatterns)) {
2992
+ return invalidFilter('"content.patterns" must be a list');
2993
+ }
2994
+ patternCount += rawPatterns.length;
2995
+ if (patternCount > REQUEST_FILTER_LIMITS.maxPatterns) {
2996
+ return invalidFilter(`a filter may hold at most ${REQUEST_FILTER_LIMITS.maxPatterns} patterns`);
2997
+ }
2998
+ const patterns = [];
2999
+ for (const rawPattern of rawPatterns) {
3000
+ const pattern = parseContentPattern(rawPattern);
3001
+ if (!pattern.ok) return pattern;
3002
+ patterns.push(pattern.value);
3003
+ }
3004
+ const match = field(rawContent, "match");
3005
+ if (match !== void 0 && match !== "any" && match !== "all") {
3006
+ return invalidFilter('"content.match" must be "any" or "all"');
3007
+ }
3008
+ rule.content = match === void 0 ? { patterns } : { patterns, match };
3009
+ }
3010
+ rules.push(rule);
3011
+ }
3012
+ const config = { mode, rules, regexTimeoutMs: REQUEST_FILTER_LIMITS.evaluationTimeoutMs };
3013
+ const rawAlwaysAllow = field(value, "alwaysAllow");
3014
+ if (rawAlwaysAllow !== void 0) {
3015
+ const alwaysAllow = parseTypeList(rawAlwaysAllow);
3016
+ if (!alwaysAllow) {
3017
+ return invalidFilter(`"alwaysAllow" must be a list of at most ${REQUEST_FILTER_LIMITS.maxTypes} event types`);
3018
+ }
3019
+ config.alwaysAllow = alwaysAllow;
3020
+ }
3021
+ const rawTimeout = field(value, "regexTimeoutMs");
3022
+ if (rawTimeout !== void 0) {
3023
+ if (!isPositiveInteger(rawTimeout)) {
3024
+ return invalidFilter('"regexTimeoutMs" must be a positive integer');
3025
+ }
3026
+ config.regexTimeoutMs = Math.min(rawTimeout, REQUEST_FILTER_LIMITS.evaluationTimeoutMs);
3027
+ }
3028
+ return { ok: true, value: config };
3029
+ }
3030
+ function parseContentPattern(value) {
3031
+ if (!isPlainObject(value)) {
3032
+ return invalidFilter("a pattern must be an object");
3033
+ }
3034
+ const type = field(value, "type");
3035
+ if (typeof type !== "string" || !PATTERN_TYPES.includes(type)) {
3036
+ return invalidFilter('"type" of a pattern must be "exact", "prefix", "regex" or "glob"');
3037
+ }
3038
+ const text = field(value, "pattern");
3039
+ if (typeof text !== "string" || text.length > REQUEST_FILTER_LIMITS.maxPatternLength) {
3040
+ return invalidFilter(`"pattern" must be a string of at most ${REQUEST_FILTER_LIMITS.maxPatternLength} characters`);
3041
+ }
3042
+ const pattern = { type, pattern: text };
3043
+ const path = field(value, "field");
3044
+ if (path !== void 0) {
3045
+ if (typeof path !== "string" || path.length === 0 || path.length > REQUEST_FILTER_LIMITS.maxFieldLength) {
3046
+ return invalidFilter(`"field" must be a string of at most ${REQUEST_FILTER_LIMITS.maxFieldLength} characters`);
3047
+ }
3048
+ pattern.field = path;
3049
+ }
3050
+ const caseInsensitive = field(value, "caseInsensitive");
3051
+ if (caseInsensitive !== void 0) {
3052
+ if (typeof caseInsensitive !== "boolean") {
3053
+ return invalidFilter('"caseInsensitive" must be a boolean');
3054
+ }
3055
+ pattern.caseInsensitive = caseInsensitive;
3056
+ }
3057
+ if (type === import_types4.PatternType.Regex) {
3058
+ try {
3059
+ new RegExp(text, pattern.caseInsensitive ? "i" : "");
3060
+ } catch {
3061
+ return invalidFilter('a "regex" pattern must be a valid regular expression');
3062
+ }
3063
+ }
3064
+ return { ok: true, value: pattern };
3065
+ }
3066
+ function parseFilterParameter(value) {
3067
+ if (typeof value !== "string" || value.length > REQUEST_FILTER_LIMITS.maxQueryLength) {
3068
+ return invalidFilter(`expected JSON text of at most ${REQUEST_FILTER_LIMITS.maxQueryLength} characters`);
3069
+ }
3070
+ let parsed;
3071
+ try {
3072
+ parsed = JSON.parse(value);
3073
+ } catch {
3074
+ return invalidFilter("expected JSON text");
3075
+ }
3076
+ return parseFilterConfig(parsed);
3077
+ }
3078
+
2188
3079
  // libs/broker/src/http/session-handler.ts
3080
+ var CORS_REQUEST_HEADERS = ["Content-Type", "Accept", "Last-Event-ID", "Authorization"];
3081
+ var HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
3082
+ function corsRequestHeaders(configured) {
3083
+ if (configured !== void 0 && !Array.isArray(configured)) {
3084
+ throw new TypeError('SessionHandler: "allowedHeaders" must be an array of header names');
3085
+ }
3086
+ const names = [...CORS_REQUEST_HEADERS];
3087
+ for (const name of configured ?? []) {
3088
+ if (typeof name !== "string" || !HEADER_NAME.test(name)) {
3089
+ throw new TypeError('SessionHandler: "allowedHeaders" must be an array of header names');
3090
+ }
3091
+ if (!names.some((known) => known.toLowerCase() === name.toLowerCase())) {
3092
+ names.push(name);
3093
+ }
3094
+ }
3095
+ return names.join(", ");
3096
+ }
3097
+ var MIN_REQUEST_HEARTBEAT_MS = 1e3;
3098
+ var MAX_REQUEST_HEARTBEAT_MS = 3e5;
3099
+ var MAX_CALLER_LENGTH = 1024;
2189
3100
  var SessionHandler = class {
2190
3101
  broker;
2191
3102
  cors;
2192
3103
  allowedOrigins;
3104
+ allowedRequestHeaders;
3105
+ identify;
3106
+ sessionList;
3107
+ maxStreamsPerSession;
3108
+ maxBufferedBytes;
3109
+ streams = /* @__PURE__ */ new WeakMap();
2193
3110
  constructor(config) {
2194
3111
  this.broker = config.broker;
2195
3112
  this.cors = config.cors ?? true;
2196
3113
  this.allowedOrigins = config.allowedOrigins ?? ["*"];
3114
+ this.allowedRequestHeaders = corsRequestHeaders(config.allowedHeaders);
3115
+ if (config.identify !== void 0 && typeof config.identify !== "function") {
3116
+ throw new TypeError('SessionHandler: "identify" must be a function');
3117
+ }
3118
+ this.identify = config.identify;
3119
+ this.sessionList = config.sessionList ?? true;
3120
+ this.maxStreamsPerSession = positiveNumber(config.maxStreamsPerSession, "maxStreamsPerSession", 8);
3121
+ this.maxBufferedBytes = positiveNumber(config.maxBufferedBytes, "maxBufferedBytes", 8 * 1024 * 1024);
3122
+ warnUnknownKeys("SessionHandler", config, [
3123
+ "broker",
3124
+ "cors",
3125
+ "allowedOrigins",
3126
+ "allowedHeaders",
3127
+ "identify",
3128
+ "sessionList",
3129
+ "maxStreamsPerSession",
3130
+ "maxBufferedBytes"
3131
+ ]);
2197
3132
  }
2198
3133
  /**
2199
3134
  * Get route definitions for registration with HTTP frameworks
@@ -2205,9 +3140,11 @@ var SessionHandler = class {
2205
3140
  { method: "GET", path: "/sessions/:sessionId", handler: this.getSession.bind(this) },
2206
3141
  { method: "GET", path: "/sessions/:sessionId/stream", handler: this.streamSession.bind(this) },
2207
3142
  { method: "DELETE", path: "/sessions/:sessionId", handler: this.terminateSession.bind(this) },
3143
+ { method: "POST", path: "/sessions/:sessionId/cancel", handler: this.terminateSession.bind(this) },
2208
3144
  { method: "OPTIONS", path: "/sessions", handler: this.handleCors.bind(this) },
2209
3145
  { method: "OPTIONS", path: "/sessions/:sessionId", handler: this.handleCors.bind(this) },
2210
- { method: "OPTIONS", path: "/sessions/:sessionId/stream", handler: this.handleCors.bind(this) }
3146
+ { method: "OPTIONS", path: "/sessions/:sessionId/stream", handler: this.handleCors.bind(this) },
3147
+ { method: "OPTIONS", path: "/sessions/:sessionId/cancel", handler: this.handleCors.bind(this) }
2211
3148
  ];
2212
3149
  }
2213
3150
  /**
@@ -2225,7 +3162,7 @@ var SessionHandler = class {
2225
3162
  return;
2226
3163
  }
2227
3164
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
2228
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Last-Event-ID");
3165
+ res.setHeader("Access-Control-Allow-Headers", this.allowedRequestHeaders);
2229
3166
  res.setHeader("Access-Control-Max-Age", "86400");
2230
3167
  }
2231
3168
  /**
@@ -2236,14 +3173,70 @@ var SessionHandler = class {
2236
3173
  res.status(204).end();
2237
3174
  }
2238
3175
  /**
2239
- * List all active sessions
3176
+ * Who the caller of a request is.
3177
+ *
3178
+ * Without an `identify` hook there is no caller identity and every request passes. With one,
3179
+ * a request without an identity is answered with 401 here and `undefined` is returned.
3180
+ */
3181
+ async callerOf(req, res) {
3182
+ if (!this.identify) {
3183
+ return { caller: void 0 };
3184
+ }
3185
+ let caller;
3186
+ try {
3187
+ caller = await this.identify(req);
3188
+ } catch {
3189
+ caller = void 0;
3190
+ }
3191
+ if (typeof caller !== "string" || caller.length === 0 || caller.length > MAX_CALLER_LENGTH) {
3192
+ this.sendError(res, 401, "UNAUTHORIZED", "The caller of this request could not be identified");
3193
+ return void 0;
3194
+ }
3195
+ return { caller };
3196
+ }
3197
+ /**
3198
+ * Whether a caller may reach a session: always without an `identify` hook, otherwise only the
3199
+ * caller that owns it. A session without an owner belongs to no caller.
3200
+ */
3201
+ mayReach(session, caller) {
3202
+ if (!this.identify) return true;
3203
+ return caller !== void 0 && session.owner === caller;
3204
+ }
3205
+ /**
3206
+ * The session a request names, if it exists and its caller may reach it. Otherwise the answer
3207
+ * has been sent (401, 400 or 404) and `undefined` is returned. A session of another caller is
3208
+ * answered exactly like an id that does not exist.
3209
+ */
3210
+ async sessionOf(req, res) {
3211
+ const identity = await this.callerOf(req, res);
3212
+ if (!identity) return void 0;
3213
+ const sessionId = req.params["sessionId"];
3214
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
3215
+ this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
3216
+ return void 0;
3217
+ }
3218
+ const session = this.broker.getSession(sessionId);
3219
+ if (!session || !this.mayReach(session, identity.caller)) {
3220
+ this.sendError(res, 404, "NOT_FOUND", "Session not found");
3221
+ return void 0;
3222
+ }
3223
+ return session;
3224
+ }
3225
+ /**
3226
+ * List sessions: all of them, or the caller's own when callers are identified
2240
3227
  *
2241
3228
  * GET /sessions
2242
3229
  */
2243
3230
  async listSessions(req, res) {
2244
3231
  this.addCorsHeaders(req, res);
3232
+ if (!this.sessionList) {
3233
+ this.sendError(res, 404, "NOT_FOUND", "Not found");
3234
+ return;
3235
+ }
3236
+ const identity = await this.callerOf(req, res);
3237
+ if (!identity) return;
2245
3238
  try {
2246
- const sessions = this.broker.listSessions();
3239
+ const sessions = this.broker.listSessions().filter((info) => this.mayReach(info, identity.caller));
2247
3240
  const response = {
2248
3241
  sessions: sessions.map((info) => this.sessionInfoToResponse(info)),
2249
3242
  total: sessions.length
@@ -2263,67 +3256,97 @@ var SessionHandler = class {
2263
3256
  */
2264
3257
  async createSession(req, res) {
2265
3258
  this.addCorsHeaders(req, res);
2266
- const body = req.body;
2267
- if (!body || typeof body.code !== "string") {
2268
- this.sendError(res, 400, "INVALID_REQUEST", 'Missing or invalid "code" field');
3259
+ const identity = await this.callerOf(req, res);
3260
+ if (!identity) return;
3261
+ const parsed = parseCreateSessionRequest(req.body);
3262
+ if (!parsed.ok) {
3263
+ this.sendError(res, 400, parsed.code, parsed.message);
2269
3264
  return;
2270
3265
  }
3266
+ const { code, sessionId, config, filter } = parsed.value;
2271
3267
  if (this.broker.isDisposed) {
2272
3268
  this.sendError(res, 503, "SERVICE_UNAVAILABLE", "Broker is disposed");
2273
3269
  return;
2274
3270
  }
3271
+ let session;
3272
+ let eventFilter;
2275
3273
  try {
2276
- const limits = {};
2277
- if (body.config?.maxExecutionMs !== void 0) {
2278
- limits["sessionTtlMs"] = body.config.maxExecutionMs;
3274
+ const limits = this.boundLimits(config);
3275
+ if (filter) {
3276
+ eventFilter = this.requestFilter(filter);
2279
3277
  }
2280
- if (body.config?.maxToolCalls !== void 0) {
2281
- limits["maxToolCalls"] = body.config.maxToolCalls;
2282
- }
2283
- if (body.config?.heartbeatIntervalMs !== void 0) {
2284
- limits["heartbeatIntervalMs"] = body.config.heartbeatIntervalMs;
2285
- }
2286
- let eventFilter;
2287
- if (body.filter) {
2288
- eventFilter = createEventFilter({ config: body.filter });
3278
+ session = this.broker.createSession({ sessionId, limits, owner: identity.caller });
3279
+ } catch (error) {
3280
+ this.sendCreateFailure(res, error);
3281
+ return;
3282
+ }
3283
+ const release = this.acquireStream(session);
3284
+ let unsubscribe = () => void 0;
3285
+ let cleanedUp = false;
3286
+ let dropped = false;
3287
+ const cleanup = (reason = "Client disconnected") => {
3288
+ if (cleanedUp) return;
3289
+ cleanedUp = true;
3290
+ unsubscribe();
3291
+ release?.();
3292
+ if (!session.isTerminal()) {
3293
+ session.cancel(reason).catch(() => {
3294
+ });
2289
3295
  }
2290
- const session = this.broker.createSession({
2291
- sessionId: body.sessionId,
2292
- limits: Object.keys(limits).length > 0 ? limits : void 0
2293
- });
3296
+ };
3297
+ try {
2294
3298
  res.setHeader("Content-Type", "application/x-ndjson");
2295
3299
  res.setHeader("Cache-Control", "no-cache");
2296
3300
  res.setHeader("Connection", "keep-alive");
2297
3301
  res.setHeader("X-Session-ID", session.sessionId);
2298
- const unsubscribe = session.onEvent((event) => {
3302
+ unsubscribe = session.onEvent((event) => {
3303
+ if (dropped) return;
2299
3304
  if (eventFilter && !eventFilter.shouldSend(event)) {
2300
3305
  return;
2301
3306
  }
2302
- this.writeEvent(res, event);
2303
- });
2304
- let cleanedUp = false;
2305
- const cleanup = () => {
2306
- if (cleanedUp) return;
2307
- cleanedUp = true;
2308
- unsubscribe();
2309
- if (!session.isTerminal()) {
2310
- session.cancel("Client disconnected").catch(() => {
2311
- });
3307
+ if (!this.writeEvent(res, event)) {
3308
+ dropped = true;
3309
+ cleanup("Client is not reading its stream");
3310
+ this.dropReader(res);
2312
3311
  }
2313
- };
3312
+ });
2314
3313
  if (req.signal) {
2315
- req.signal.addEventListener("abort", cleanup, { once: true });
3314
+ req.signal.addEventListener("abort", () => cleanup(), { once: true });
3315
+ if (req.signal.aborted) cleanup();
2316
3316
  }
2317
- try {
2318
- await session.execute(body.code);
2319
- } catch {
2320
- } finally {
2321
- cleanup();
3317
+ } catch {
3318
+ cleanup();
3319
+ await this.broker.terminateSession(session.sessionId).catch(() => false);
3320
+ this.sendError(res, 500, "SESSION_CREATE_ERROR", "Failed to create session");
3321
+ return;
3322
+ }
3323
+ try {
3324
+ await session.execute(code);
3325
+ } catch {
3326
+ } finally {
3327
+ cleanup();
3328
+ if (!dropped) {
2322
3329
  res.end();
2323
3330
  }
2324
- } catch (error) {
2325
- const message = error instanceof Error ? error.message : "Unknown error";
2326
- this.sendError(res, 500, "SESSION_CREATE_ERROR", message);
3331
+ }
3332
+ }
3333
+ /**
3334
+ * Answer a failed session creation with a code and a fixed text.
3335
+ */
3336
+ sendCreateFailure(res, error) {
3337
+ const code = error instanceof BrokerError ? error.code : void 0;
3338
+ switch (code) {
3339
+ case BrokerErrorCode.SessionExists:
3340
+ this.sendError(res, 409, "SESSION_EXISTS", "A session with this id already exists");
3341
+ return;
3342
+ case BrokerErrorCode.InvalidSessionId:
3343
+ this.sendError(res, 400, "INVALID_REQUEST", 'Invalid "sessionId" field');
3344
+ return;
3345
+ case BrokerErrorCode.MaxSessionsReached:
3346
+ this.sendError(res, 503, "MAX_SESSIONS_REACHED", "The broker has reached its session limit");
3347
+ return;
3348
+ default:
3349
+ this.sendError(res, 500, "SESSION_CREATE_ERROR", "Failed to create session");
2327
3350
  }
2328
3351
  }
2329
3352
  /**
@@ -2333,16 +3356,8 @@ var SessionHandler = class {
2333
3356
  */
2334
3357
  async getSession(req, res) {
2335
3358
  this.addCorsHeaders(req, res);
2336
- const sessionId = req.params["sessionId"];
2337
- if (!sessionId) {
2338
- this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
2339
- return;
2340
- }
2341
- const session = this.broker.getSession(sessionId);
2342
- if (!session) {
2343
- this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
2344
- return;
2345
- }
3359
+ const session = await this.sessionOf(req, res);
3360
+ if (!session) return;
2346
3361
  res.status(200).json(this.sessionToInfo(session));
2347
3362
  }
2348
3363
  /**
@@ -2352,90 +3367,136 @@ var SessionHandler = class {
2352
3367
  */
2353
3368
  async streamSession(req, res) {
2354
3369
  this.addCorsHeaders(req, res);
2355
- const sessionId = req.params["sessionId"];
2356
- if (!sessionId) {
2357
- this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
2358
- return;
2359
- }
2360
- const session = this.broker.getSession(sessionId);
2361
- if (!session) {
2362
- this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
2363
- return;
2364
- }
2365
- const parsedFromSeq = parseInt(req.query["fromSeq"] ?? "0", 10);
2366
- const fromSeq = Number.isFinite(parsedFromSeq) && parsedFromSeq >= 0 ? parsedFromSeq : 0;
3370
+ const session = await this.sessionOf(req, res);
3371
+ if (!session) return;
3372
+ const rawFromSeq = req.query["fromSeq"];
3373
+ const parsedFromSeq = typeof rawFromSeq === "string" ? parseInt(rawFromSeq, 10) : 0;
3374
+ const fromSeq = Number.isSafeInteger(parsedFromSeq) && parsedFromSeq >= 0 ? parsedFromSeq : 0;
2367
3375
  let eventFilter;
2368
- if (req.query["filter"]) {
3376
+ const rawFilter = req.query["filter"];
3377
+ if (rawFilter !== void 0 && rawFilter !== "") {
3378
+ const parsedFilter = parseFilterParameter(rawFilter);
3379
+ if (!parsedFilter.ok) {
3380
+ this.sendError(res, 400, parsedFilter.code, parsedFilter.message);
3381
+ return;
3382
+ }
2369
3383
  try {
2370
- const filterConfig = JSON.parse(req.query["filter"]);
2371
- eventFilter = createEventFilter({ config: filterConfig });
3384
+ eventFilter = this.requestFilter(parsedFilter.value);
2372
3385
  } catch {
2373
3386
  this.sendError(res, 400, "INVALID_FILTER", "Invalid filter configuration");
2374
3387
  return;
2375
3388
  }
2376
3389
  }
2377
- res.setHeader("Content-Type", "application/x-ndjson");
2378
- res.setHeader("Cache-Control", "no-cache");
2379
- res.setHeader("Connection", "keep-alive");
2380
- res.setHeader("X-Session-ID", session.sessionId);
2381
- const pastEvents = session.getEvents();
2382
- for (const event of pastEvents) {
2383
- if (event.seq >= fromSeq) {
2384
- if (eventFilter && !eventFilter.shouldSend(event)) {
2385
- continue;
2386
- }
2387
- this.writeEvent(res, event);
2388
- }
3390
+ const firstReplayable = session.firstReplayableSeq;
3391
+ if (firstReplayable > 1 && fromSeq < firstReplayable) {
3392
+ this.sendError(res, 410, "EVENTS_GONE", "The requested events are no longer kept for this session");
3393
+ return;
2389
3394
  }
2390
- if (session.isTerminal()) {
2391
- res.end();
3395
+ const release = this.acquireStream(session);
3396
+ if (!release) {
3397
+ this.sendError(res, 429, "TOO_MANY_STREAMS", "This session has too many open streams");
2392
3398
  return;
2393
3399
  }
2394
- const unsubscribe = session.onEvent((event) => {
2395
- if (event.seq >= fromSeq) {
2396
- if (eventFilter && !eventFilter.shouldSend(event)) {
2397
- if (event.type === "final") {
2398
- unsubscribe();
2399
- res.end();
3400
+ let unsubscribe = () => void 0;
3401
+ let closed = false;
3402
+ const close = (drop = false) => {
3403
+ if (closed) return;
3404
+ closed = true;
3405
+ unsubscribe();
3406
+ release();
3407
+ if (drop) {
3408
+ this.dropReader(res);
3409
+ } else {
3410
+ res.end();
3411
+ }
3412
+ };
3413
+ try {
3414
+ res.setHeader("Content-Type", "application/x-ndjson");
3415
+ res.setHeader("Cache-Control", "no-cache");
3416
+ res.setHeader("Connection", "keep-alive");
3417
+ res.setHeader("X-Session-ID", session.sessionId);
3418
+ const pastEvents = session.getEvents();
3419
+ for (const event of pastEvents) {
3420
+ if (event.seq >= fromSeq) {
3421
+ if (eventFilter && !eventFilter.shouldSend(event)) {
3422
+ continue;
3423
+ }
3424
+ if (!this.writeEvent(res, event)) {
3425
+ close(true);
3426
+ return;
2400
3427
  }
2401
- return;
2402
3428
  }
2403
- this.writeEvent(res, event);
2404
3429
  }
2405
- if (event.type === "final") {
2406
- unsubscribe();
2407
- res.end();
3430
+ if (session.isTerminal()) {
3431
+ close();
3432
+ return;
2408
3433
  }
2409
- });
2410
- if (req.signal) {
2411
- req.signal.addEventListener(
2412
- "abort",
2413
- () => {
2414
- unsubscribe();
2415
- },
2416
- { once: true }
2417
- );
3434
+ unsubscribe = session.onEvent((event) => {
3435
+ if (closed) return;
3436
+ if (event.seq >= fromSeq && (!eventFilter || eventFilter.shouldSend(event))) {
3437
+ if (!this.writeEvent(res, event)) {
3438
+ close(true);
3439
+ return;
3440
+ }
3441
+ }
3442
+ if (event.type === "final") {
3443
+ close();
3444
+ }
3445
+ });
3446
+ if (req.signal) {
3447
+ req.signal.addEventListener("abort", () => close(), { once: true });
3448
+ if (req.signal.aborted) close();
3449
+ }
3450
+ } catch (error) {
3451
+ close(true);
3452
+ throw error;
2418
3453
  }
2419
3454
  }
2420
3455
  /**
2421
3456
  * Terminate a session
2422
3457
  *
2423
3458
  * DELETE /sessions/:sessionId
3459
+ * POST /sessions/:sessionId/cancel (the URL a session announces in its first event)
2424
3460
  */
2425
3461
  async terminateSession(req, res) {
2426
3462
  this.addCorsHeaders(req, res);
2427
- const sessionId = req.params["sessionId"];
2428
- if (!sessionId) {
2429
- this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
2430
- return;
2431
- }
3463
+ const session = await this.sessionOf(req, res);
3464
+ if (!session) return;
3465
+ const sessionId = session.sessionId;
2432
3466
  const success = await this.broker.terminateSession(sessionId);
2433
3467
  if (!success) {
2434
- this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
3468
+ this.sendError(res, 404, "NOT_FOUND", "Session not found");
2435
3469
  return;
2436
3470
  }
2437
3471
  res.status(200).json({ success: true, sessionId });
2438
3472
  }
3473
+ /**
3474
+ * The filter for a configuration that arrived in a request and passed validation. It gets a
3475
+ * budget for the whole stream, and its globs are matched without expansion.
3476
+ */
3477
+ requestFilter(config) {
3478
+ return createEventFilter({ config, budgetMs: REQUEST_FILTER_LIMITS.budgetMs, expandGlobs: false });
3479
+ }
3480
+ /**
3481
+ * The limits a request gets: what it asks for, never above what the broker is configured
3482
+ * with. A request may lower a limit; it cannot raise one.
3483
+ */
3484
+ boundLimits(requested) {
3485
+ const ceiling = this.broker.sessionLimits ?? import_types5.DEFAULT_SESSION_LIMITS;
3486
+ const limits = {};
3487
+ if (requested.maxExecutionMs !== void 0) {
3488
+ limits.sessionTtlMs = Math.min(requested.maxExecutionMs, ceiling.sessionTtlMs);
3489
+ }
3490
+ if (requested.maxToolCalls !== void 0) {
3491
+ limits.maxToolCalls = Math.min(requested.maxToolCalls, ceiling.maxToolCalls);
3492
+ }
3493
+ if (requested.heartbeatIntervalMs !== void 0 && ceiling.heartbeatIntervalMs > 0) {
3494
+ const shortest = Math.min(MIN_REQUEST_HEARTBEAT_MS, ceiling.heartbeatIntervalMs);
3495
+ const longest = Math.max(MAX_REQUEST_HEARTBEAT_MS, ceiling.heartbeatIntervalMs);
3496
+ limits.heartbeatIntervalMs = Math.min(Math.max(requested.heartbeatIntervalMs, shortest), longest);
3497
+ }
3498
+ return limits;
3499
+ }
2439
3500
  /**
2440
3501
  * Convert BrokerSession to info response
2441
3502
  */
@@ -2469,13 +3530,51 @@ var SessionHandler = class {
2469
3530
  };
2470
3531
  }
2471
3532
  /**
2472
- * Write a stream event as NDJSON
3533
+ * Count one more stream of a session. Returns the function that gives the place back, or
3534
+ * undefined when the session has as many streams as `maxStreamsPerSession` allows.
3535
+ */
3536
+ acquireStream(session) {
3537
+ const open = this.streams.get(session) ?? 0;
3538
+ if (open >= this.maxStreamsPerSession) {
3539
+ return void 0;
3540
+ }
3541
+ this.streams.set(session, open + 1);
3542
+ let released = false;
3543
+ return () => {
3544
+ if (released) return;
3545
+ released = true;
3546
+ this.streams.set(session, Math.max(0, (this.streams.get(session) ?? 1) - 1));
3547
+ };
3548
+ }
3549
+ /**
3550
+ * Write a stream event as NDJSON. Returns false when the reader of this response has fallen
3551
+ * behind by more than `maxBufferedBytes`: it must be dropped, nothing more is written to it.
2473
3552
  */
2474
3553
  writeEvent(res, event) {
2475
- res.write(JSON.stringify(event) + "\n");
3554
+ let line;
3555
+ try {
3556
+ line = JSON.stringify(event);
3557
+ } catch {
3558
+ return true;
3559
+ }
3560
+ res.write(line + "\n");
2476
3561
  if (res.flush) {
2477
3562
  res.flush();
2478
3563
  }
3564
+ return !res.bufferedBytes || res.bufferedBytes() <= this.maxBufferedBytes;
3565
+ }
3566
+ /**
3567
+ * Close the connection of a reader that does not take what it is sent.
3568
+ */
3569
+ dropReader(res) {
3570
+ try {
3571
+ if (res.destroy) {
3572
+ res.destroy();
3573
+ } else {
3574
+ res.end();
3575
+ }
3576
+ } catch {
3577
+ }
2479
3578
  }
2480
3579
  /**
2481
3580
  * Send an error response
@@ -2485,14 +3584,36 @@ var SessionHandler = class {
2485
3584
  res.status(status).json(error);
2486
3585
  }
2487
3586
  };
3587
+ function positiveNumber(value, name, fallback) {
3588
+ if (value === void 0) return fallback;
3589
+ if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
3590
+ throw new TypeError(`SessionHandler: "${name}" must be a number above zero`);
3591
+ }
3592
+ return value;
3593
+ }
3594
+ function warnUnknownKeys(owner, config, known) {
3595
+ for (const key of Object.keys(config)) {
3596
+ if (!known.includes(key)) {
3597
+ console.warn(
3598
+ `[@enclave-vm/broker] ${owner}: unknown configuration key ${JSON.stringify(key.slice(0, 64))} is ignored`
3599
+ );
3600
+ }
3601
+ }
3602
+ }
2488
3603
  function createSessionHandler(config) {
2489
3604
  return new SessionHandler(config);
2490
3605
  }
2491
3606
 
2492
3607
  // libs/broker/src/http/express-adapter.ts
2493
- function adaptRequest(req) {
3608
+ function adaptRequest(req, res) {
2494
3609
  const abortController = new AbortController();
2495
- if (req.on && req.socket) {
3610
+ if (res?.on) {
3611
+ res.on("close", () => {
3612
+ if (!res.writableFinished) {
3613
+ abortController.abort();
3614
+ }
3615
+ });
3616
+ } else if (req.on && req.socket) {
2496
3617
  req.on("close", () => {
2497
3618
  if (req.socket?.destroyed) {
2498
3619
  abortController.abort();
@@ -2506,7 +3627,8 @@ function adaptRequest(req) {
2506
3627
  query: req.query,
2507
3628
  body: req.body,
2508
3629
  headers: req.headers,
2509
- signal: abortController.signal
3630
+ signal: abortController.signal,
3631
+ raw: req
2510
3632
  };
2511
3633
  }
2512
3634
  function adaptResponse(res) {
@@ -2523,11 +3645,21 @@ function adaptResponse(res) {
2523
3645
  return this;
2524
3646
  },
2525
3647
  write(data) {
2526
- res.write(data);
3648
+ return res.write(data);
2527
3649
  },
2528
3650
  end() {
2529
3651
  res.end();
2530
3652
  },
3653
+ bufferedBytes() {
3654
+ return res.writableLength ?? 0;
3655
+ },
3656
+ destroy() {
3657
+ if (res.destroy) {
3658
+ res.destroy();
3659
+ } else {
3660
+ res.end();
3661
+ }
3662
+ },
2531
3663
  flush() {
2532
3664
  if (res.flushHeaders) {
2533
3665
  res.flushHeaders();
@@ -2546,7 +3678,7 @@ function createExpressRouter(handler) {
2546
3678
  method,
2547
3679
  path: route.path,
2548
3680
  handler: (req, res) => {
2549
- const brokerReq = adaptRequest(req);
3681
+ const brokerReq = adaptRequest(req, res);
2550
3682
  const brokerRes = adaptResponse(res);
2551
3683
  route.handler(brokerReq, brokerRes).catch((error) => {
2552
3684
  console.error("Route handler error:", error);
@@ -2582,7 +3714,7 @@ function registerExpressRoutes(router, handler) {
2582
3714
  for (const route of handler.getRoutes()) {
2583
3715
  const method = route.method.toLowerCase();
2584
3716
  const expressHandler = (req, res) => {
2585
- const brokerReq = adaptRequest(req);
3717
+ const brokerReq = adaptRequest(req, res);
2586
3718
  const brokerRes = adaptResponse(res);
2587
3719
  route.handler(brokerReq, brokerRes).catch((error) => {
2588
3720
  console.error("Route handler error:", error);
@@ -2666,8 +3798,11 @@ var CatalogHandler = class {
2666
3798
  // Annotate the CommonJS export names for ESM import in node:
2667
3799
  0 && (module.exports = {
2668
3800
  Broker,
3801
+ BrokerError,
3802
+ BrokerErrorCode,
2669
3803
  BrokerSession,
2670
3804
  CatalogHandler,
3805
+ DEFAULT_SESSION_HISTORY_LIMITS,
2671
3806
  EventFilter,
2672
3807
  OpenApiSource,
2673
3808
  OpenApiSpecPoller,