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