@enclave-vm/broker 2.12.0 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.mjs CHANGED
@@ -30,6 +30,18 @@ var ToolRegistry = class {
30
30
  unregister(name) {
31
31
  return this.tools.delete(name);
32
32
  }
33
+ /**
34
+ * Replace an existing tool with a new definition.
35
+ * If the tool doesn't exist, it registers it as new.
36
+ */
37
+ replace(definition) {
38
+ this.tools.delete(definition.name);
39
+ const argsSchema = definition.argsSchema ?? z.record(z.string(), z.unknown());
40
+ this.tools.set(definition.name, {
41
+ definition,
42
+ argsSchema
43
+ });
44
+ }
33
45
  /**
34
46
  * Check if a tool is registered
35
47
  */
@@ -211,7 +223,13 @@ function createToolRegistry() {
211
223
  }
212
224
 
213
225
  // libs/broker/src/broker-session.ts
214
- import { generateSessionId, generateCallId, DEFAULT_SESSION_LIMITS } from "@enclave-vm/types";
226
+ import {
227
+ generateSessionId,
228
+ generateCallId,
229
+ DEFAULT_SESSION_LIMITS,
230
+ EventType,
231
+ PROTOCOL_VERSION
232
+ } from "@enclave-vm/types";
215
233
  import { createSessionEmitter, Enclave } from "@enclave-vm/core";
216
234
  var BrokerSession = class {
217
235
  sessionId;
@@ -227,6 +245,9 @@ var BrokerSession = class {
227
245
  toolCallCount = 0;
228
246
  stdoutBytes = 0;
229
247
  heartbeatInterval = null;
248
+ deadlineTimer = null;
249
+ _deadlineExceeded = false;
250
+ partialErrors = [];
230
251
  constructor(toolRegistry, config = {}) {
231
252
  this.sessionId = config.sessionId ?? generateSessionId();
232
253
  this.createdAt = Date.now();
@@ -295,6 +316,46 @@ var BrokerSession = class {
295
316
  }
296
317
  }, heartbeatMs);
297
318
  }
319
+ const deadlineMs = this.limits.deadlineMs;
320
+ if (deadlineMs > 0) {
321
+ const remaining = deadlineMs - (Date.now() - this.createdAt);
322
+ if (remaining > 0) {
323
+ this.deadlineTimer = setTimeout(() => {
324
+ this._deadlineExceeded = true;
325
+ this.cancel(`Deadline exceeded: ${deadlineMs}ms budget`);
326
+ }, remaining);
327
+ } else {
328
+ this._deadlineExceeded = true;
329
+ this.stopHeartbeat();
330
+ this._state = "failed";
331
+ const elapsed = Date.now() - this.createdAt;
332
+ this.emitter.emit(
333
+ this.makeCustomEvent(EventType.DeadlineExceeded, { elapsedMs: elapsed, budgetMs: deadlineMs })
334
+ );
335
+ this.emitter.emitFinalError(
336
+ { code: "DEADLINE_EXCEEDED", message: "Deadline exceeded before execution" },
337
+ { durationMs: elapsed, toolCallCount: 0, stdoutBytes: 0 }
338
+ );
339
+ const finalResult = {
340
+ success: false,
341
+ error: {
342
+ message: "Deadline exceeded before execution",
343
+ name: "Error",
344
+ code: "DEADLINE_EXCEEDED"
345
+ },
346
+ stats: {
347
+ duration: elapsed,
348
+ toolCallCount: 0,
349
+ iterationCount: 0,
350
+ startTime: this.createdAt,
351
+ endTime: Date.now()
352
+ },
353
+ finalState: "failed"
354
+ };
355
+ this.executionPromise = Promise.resolve(finalResult);
356
+ return finalResult;
357
+ }
358
+ }
298
359
  this._state = "running";
299
360
  this.executionPromise = this.runExecution(code);
300
361
  return this.executionPromise;
@@ -314,13 +375,34 @@ var BrokerSession = class {
314
375
  });
315
376
  const endTime = Date.now();
316
377
  const stats = this.buildStats(startTime, endTime);
317
- if (enclaveResult.success) {
378
+ const eventStats = {
379
+ durationMs: stats.duration,
380
+ toolCallCount: this.toolCallCount,
381
+ stdoutBytes: this.stdoutBytes
382
+ };
383
+ if (this.isTerminal()) {
384
+ if (this._deadlineExceeded) {
385
+ this.emitter.emit(
386
+ this.makeCustomEvent(EventType.DeadlineExceeded, {
387
+ elapsedMs: Date.now() - this.createdAt,
388
+ budgetMs: this.limits.deadlineMs
389
+ })
390
+ );
391
+ }
392
+ const cancelError = {
393
+ code: this._deadlineExceeded ? "DEADLINE_EXCEEDED" : "SESSION_CANCELLED",
394
+ message: this._deadlineExceeded ? "Deadline exceeded" : "Session was cancelled"
395
+ };
396
+ this.emitter.emitFinalError(cancelError, eventStats, this.getPartialErrors());
397
+ result = {
398
+ success: false,
399
+ error: { message: cancelError.message, name: "Error", code: cancelError.code },
400
+ stats,
401
+ finalState: this._deadlineExceeded ? "failed" : "cancelled"
402
+ };
403
+ } else if (enclaveResult.success) {
318
404
  this._state = "completed";
319
- this.emitter.emitFinalSuccess(enclaveResult.value, {
320
- durationMs: stats.duration,
321
- toolCallCount: this.toolCallCount,
322
- stdoutBytes: this.stdoutBytes
323
- });
405
+ this.emitter.emitFinalSuccess(enclaveResult.value, eventStats, this.getPartialErrors());
324
406
  result = {
325
407
  success: true,
326
408
  value: enclaveResult.value,
@@ -333,11 +415,7 @@ var BrokerSession = class {
333
415
  code: enclaveResult.error?.code ?? "EXECUTION_ERROR",
334
416
  message: enclaveResult.error?.message ?? "Execution failed"
335
417
  };
336
- this.emitter.emitFinalError(errorInfo, {
337
- durationMs: stats.duration,
338
- toolCallCount: this.toolCallCount,
339
- stdoutBytes: this.stdoutBytes
340
- });
418
+ this.emitter.emitFinalError(errorInfo, eventStats, this.getPartialErrors());
341
419
  result = {
342
420
  success: false,
343
421
  error: {
@@ -353,16 +431,28 @@ var BrokerSession = class {
353
431
  const endTime = Date.now();
354
432
  const stats = this.buildStats(startTime, endTime);
355
433
  const err = error instanceof Error ? error : new Error(String(error));
356
- this._state = "failed";
357
- const errorInfo = {
358
- code: err.code ?? "EXECUTION_ERROR",
359
- message: err.message
360
- };
361
- this.emitter.emitFinalError(errorInfo, {
434
+ const eventStats = {
362
435
  durationMs: stats.duration,
363
436
  toolCallCount: this.toolCallCount,
364
437
  stdoutBytes: this.stdoutBytes
365
- });
438
+ };
439
+ if (this._deadlineExceeded) {
440
+ this.emitter.emit(
441
+ this.makeCustomEvent(EventType.DeadlineExceeded, {
442
+ elapsedMs: Date.now() - this.createdAt,
443
+ budgetMs: this.limits.deadlineMs
444
+ })
445
+ );
446
+ }
447
+ if (!this.isTerminal()) {
448
+ this._state = "failed";
449
+ }
450
+ const isCancelled = this._state === "cancelled";
451
+ const errorInfo = {
452
+ code: isCancelled ? this._deadlineExceeded ? "DEADLINE_EXCEEDED" : "SESSION_CANCELLED" : err.code ?? "EXECUTION_ERROR",
453
+ message: err.message
454
+ };
455
+ this.emitter.emitFinalError(errorInfo, eventStats, this.getPartialErrors());
366
456
  result = {
367
457
  success: false,
368
458
  error: {
@@ -371,37 +461,123 @@ var BrokerSession = class {
371
461
  code: errorInfo.code
372
462
  },
373
463
  stats,
374
- finalState: "failed"
464
+ finalState: isCancelled ? "cancelled" : "failed"
375
465
  };
376
466
  } finally {
377
467
  this.stopHeartbeat();
468
+ this.stopDeadline();
378
469
  }
379
470
  return result;
380
471
  }
472
+ /**
473
+ * Emit a tool progress event.
474
+ */
475
+ emitToolProgress(callId, phase, elapsedMs, bytesReceived, totalBytes) {
476
+ this.emitter.emit(
477
+ this.makeCustomEvent(EventType.ToolProgress, {
478
+ callId,
479
+ phase,
480
+ elapsedMs,
481
+ bytesReceived,
482
+ totalBytes
483
+ })
484
+ );
485
+ }
486
+ /**
487
+ * Emit a partial result event.
488
+ */
489
+ emitPartialResult(path, data, error, hasNext = true) {
490
+ if (error) {
491
+ this.partialErrors.push(error);
492
+ }
493
+ this.emitter.emit(
494
+ this.makeCustomEvent(EventType.PartialResult, {
495
+ path,
496
+ data,
497
+ error,
498
+ hasNext
499
+ })
500
+ );
501
+ }
502
+ /**
503
+ * Get accumulated partial errors.
504
+ */
505
+ getPartialErrors() {
506
+ return [...this.partialErrors];
507
+ }
381
508
  /**
382
509
  * Execute a tool call directly
383
510
  */
384
511
  async executeTool(toolName, args) {
385
512
  const callId = generateCallId();
513
+ const toolStartTime = Date.now();
514
+ if (this.limits.deadlineMs > 0) {
515
+ const elapsed = Date.now() - this.createdAt;
516
+ const remaining = this.limits.deadlineMs - elapsed;
517
+ if (remaining <= 0) {
518
+ this._deadlineExceeded = true;
519
+ const err = new Error("Deadline exceeded before tool execution");
520
+ err.code = "DEADLINE_EXCEEDED";
521
+ throw err;
522
+ }
523
+ }
386
524
  this.emitter.emitToolCall(callId, toolName, args);
387
525
  this.toolCallCount++;
526
+ this.emitToolProgress(callId, "connecting", 0);
527
+ let toolTimeout = this.limits.perToolDeadlineMs;
528
+ if (this.limits.deadlineMs > 0) {
529
+ const remaining = this.limits.deadlineMs - (Date.now() - this.createdAt);
530
+ toolTimeout = Math.min(toolTimeout, remaining);
531
+ }
532
+ const toolAbort = new AbortController();
533
+ let toolTimer = null;
534
+ if (toolTimeout > 0) {
535
+ toolTimer = setTimeout(() => toolAbort.abort(), toolTimeout);
536
+ }
537
+ const onSessionAbort = () => toolAbort.abort();
538
+ this.abortController.signal.addEventListener("abort", onSessionAbort);
539
+ if (this.abortController.signal.aborted) {
540
+ toolAbort.abort();
541
+ }
388
542
  const context = {
389
543
  sessionId: this.sessionId,
390
544
  callId,
391
545
  secrets: {},
392
546
  // Resolved by registry
393
- signal: this.abortController.signal
547
+ signal: toolAbort.signal
394
548
  };
395
- const result = await this.toolRegistry.execute(toolName, args, context);
549
+ this.emitToolProgress(callId, "processing", Date.now() - toolStartTime);
550
+ let result;
551
+ try {
552
+ result = await this.toolRegistry.execute(toolName, args, context);
553
+ } finally {
554
+ if (toolTimer) clearTimeout(toolTimer);
555
+ this.abortController.signal.removeEventListener("abort", onSessionAbort);
556
+ }
396
557
  this.emitter.emitToolResultApplied(callId);
397
558
  if (result.success) {
398
559
  return result.value;
399
560
  } else {
561
+ if (this.limits.cancelOnFirstError) {
562
+ this.abortController.abort();
563
+ }
400
564
  const error = new Error(result.error?.message ?? "Tool call failed");
401
565
  error.code = result.error?.code;
402
566
  throw error;
403
567
  }
404
568
  }
569
+ /**
570
+ * Create a custom event with proper base fields and unique sequence number.
571
+ */
572
+ makeCustomEvent(type, payload) {
573
+ return {
574
+ protocolVersion: PROTOCOL_VERSION,
575
+ sessionId: this.sessionId,
576
+ seq: this.emitter.nextSeq(),
577
+ type,
578
+ payload
579
+ };
580
+ }
405
581
  /**
406
582
  * Build execution stats
407
583
  */
@@ -422,17 +598,37 @@ var BrokerSession = class {
422
598
  return;
423
599
  }
424
600
  this.stopHeartbeat();
601
+ this.stopDeadline();
425
602
  this.abortController.abort();
426
603
  this._state = "cancelled";
427
- this.emitter.emitError("SESSION_CANCELLED", reason ?? "Session was cancelled", false);
428
- this.emitter.emitFinalError(
429
- { code: "SESSION_CANCELLED", message: reason ?? "Session was cancelled" },
430
- {
431
- durationMs: Date.now() - this.createdAt,
432
- toolCallCount: this.toolCallCount,
433
- stdoutBytes: this.stdoutBytes
434
- }
435
- );
604
+ if (!this.executionPromise) {
605
+ this.emitter.emitError("SESSION_CANCELLED", reason ?? "Session was cancelled", false);
606
+ this.emitter.emitFinalError(
607
+ { code: "SESSION_CANCELLED", message: reason ?? "Session was cancelled" },
608
+ {
609
+ durationMs: Date.now() - this.createdAt,
610
+ toolCallCount: this.toolCallCount,
611
+ stdoutBytes: this.stdoutBytes
612
+ },
613
+ this.getPartialErrors()
614
+ );
615
+ this.executionPromise = Promise.resolve({
616
+ success: false,
617
+ error: {
618
+ message: reason ?? "Session was cancelled",
619
+ name: "Error",
620
+ code: "SESSION_CANCELLED"
621
+ },
622
+ stats: {
623
+ duration: Date.now() - this.createdAt,
624
+ toolCallCount: this.toolCallCount,
625
+ iterationCount: 0,
626
+ startTime: this.createdAt,
627
+ endTime: Date.now()
628
+ },
629
+ finalState: "cancelled"
630
+ });
631
+ }
436
632
  }
437
633
  /**
438
634
  * Wait for the session to complete
@@ -477,11 +673,21 @@ var BrokerSession = class {
477
673
  this.heartbeatInterval = null;
478
674
  }
479
675
  }
676
+ /**
677
+ * Stop deadline timer
678
+ */
679
+ stopDeadline() {
680
+ if (this.deadlineTimer) {
681
+ clearTimeout(this.deadlineTimer);
682
+ this.deadlineTimer = null;
683
+ }
684
+ }
480
685
  /**
481
686
  * Dispose of the session and its resources
482
687
  */
483
688
  dispose() {
484
689
  this.stopHeartbeat();
690
+ this.stopDeadline();
485
691
  this.abortController.abort();
486
692
  this.enclave.dispose();
487
693
  }
@@ -665,11 +871,777 @@ function createSessionManager(toolRegistry, config) {
665
871
  return new SessionManager(toolRegistry, config);
666
872
  }
667
873
 
874
+ // libs/broker/src/openapi/openapi-source.ts
875
+ import { EventEmitter as EventEmitter2 } from "events";
876
+
877
+ // libs/broker/src/openapi/openapi-spec-poller.ts
878
+ import { EventEmitter } from "events";
879
+
880
+ // libs/broker/src/openapi/hash-utils.ts
881
+ async function sha256Hex(data) {
882
+ const encoded = new TextEncoder().encode(data);
883
+ const hashBuffer = await crypto.subtle.digest("SHA-256", encoded);
884
+ const hashArray = new Uint8Array(hashBuffer);
885
+ return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
886
+ }
887
+
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
894
+ };
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
+ };
919
+ }
920
+ /**
921
+ * Start polling for changes.
922
+ */
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);
932
+ }
933
+ });
934
+ } else {
935
+ this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
936
+ }
937
+ this.intervalTimer = setInterval(() => {
938
+ this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
939
+ }, this.config.intervalMs);
940
+ }
941
+ /**
942
+ * Stop polling.
943
+ */
944
+ stop() {
945
+ this._runAbort.abort();
946
+ if (this._fetchController) {
947
+ this._fetchController.abort();
948
+ this._fetchController = null;
949
+ }
950
+ if (this.intervalTimer) {
951
+ clearInterval(this.intervalTimer);
952
+ this.intervalTimer = null;
953
+ }
954
+ }
955
+ /**
956
+ * Get the current content hash.
957
+ */
958
+ getHash() {
959
+ return this.lastHash;
960
+ }
961
+ /**
962
+ * Get the number of consecutive failures.
963
+ */
964
+ getConsecutiveFailures() {
965
+ return this.consecutiveFailures;
966
+ }
967
+ /**
968
+ * Perform a single poll cycle.
969
+ */
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;
1179
+ }
1180
+ /**
1181
+ * Parse the OpenAPI spec and generate tool definitions.
1182
+ */
1183
+ loadFromSpec(spec) {
1184
+ const paths = spec["paths"];
1185
+ if (!paths) return;
1186
+ const baseUrl = this.options.baseUrl ?? "";
1187
+ const operations = this.extractOperations(paths);
1188
+ for (const op of operations) {
1189
+ if (this.options.includeOperations && !this.options.includeOperations.includes(op.operationId)) {
1190
+ continue;
1191
+ }
1192
+ if (this.options.excludeOperations && this.options.excludeOperations.includes(op.operationId)) {
1193
+ continue;
1194
+ }
1195
+ const baseName = op.operationId || `${op.method}_${op.path.replace(/[^a-zA-Z0-9]/g, "_")}`;
1196
+ const toolName = this.options.namingStrategy ? this.options.namingStrategy(op.method, op.path, op.operationId) : this.options.sourceName ? `${this.options.sourceName}_${baseName}` : baseName;
1197
+ const { schema: argsSchema, bodyMediaType } = this.buildArgsSchema(op);
1198
+ const timeout = this.options.perToolDeadlineMs ?? 3e4;
1199
+ const tool = {
1200
+ name: toolName,
1201
+ description: op.summary || op.description || `${op.method.toUpperCase()} ${op.path}`,
1202
+ argsSchema,
1203
+ config: {
1204
+ timeout
1205
+ },
1206
+ handler: this.createHandler(op, baseUrl, bodyMediaType)
1207
+ };
1208
+ if (this.toolNames.has(toolName)) {
1209
+ throw new Error(
1210
+ `Duplicate tool name "${toolName}" generated for ${op.method.toUpperCase()} ${op.path} (operationId: ${op.operationId}). Use a custom namingStrategy or sourceName to disambiguate.`
1211
+ );
1212
+ }
1213
+ this.tools.push(tool);
1214
+ this.toolNames.add(toolName);
1215
+ }
1216
+ }
1217
+ /**
1218
+ * Extract operations from OpenAPI paths.
1219
+ */
1220
+ extractOperations(paths) {
1221
+ const operations = [];
1222
+ const httpMethods = ["get", "post", "put", "delete", "patch", "head", "options"];
1223
+ for (const [path, pathItem] of Object.entries(paths)) {
1224
+ const pathParams = pathItem["parameters"] ?? [];
1225
+ for (const method of httpMethods) {
1226
+ const operation = pathItem[method];
1227
+ if (!operation) continue;
1228
+ const operationId = operation["operationId"] || `${method}_${path.replace(/[^a-zA-Z0-9]/g, "_")}`;
1229
+ const opParams = operation["parameters"] ?? [];
1230
+ const merged = this.mergeParameters(pathParams, opParams);
1231
+ operations.push({
1232
+ operationId,
1233
+ method,
1234
+ path,
1235
+ summary: operation["summary"],
1236
+ description: operation["description"],
1237
+ parameters: merged.length > 0 ? merged : void 0,
1238
+ requestBody: operation["requestBody"],
1239
+ deprecated: operation["deprecated"]
1240
+ });
1241
+ }
1242
+ }
1243
+ return operations;
1244
+ }
1245
+ /**
1246
+ * Merge path-level and operation-level parameters, de-duplicating by (name, in).
1247
+ * Operation-level entries override path-level ones.
1248
+ */
1249
+ mergeParameters(pathParams, opParams) {
1250
+ const seen = /* @__PURE__ */ new Map();
1251
+ for (const p of pathParams) {
1252
+ seen.set(`${p.in}:${p.name}`, p);
1253
+ }
1254
+ for (const p of opParams) {
1255
+ seen.set(`${p.in}:${p.name}`, p);
1256
+ }
1257
+ return [...seen.values()];
1258
+ }
1259
+ /**
1260
+ * Build a Zod args schema from an OpenAPI operation.
1261
+ */
1262
+ buildArgsSchema(op) {
1263
+ const shape = {};
1264
+ let bodyMediaType;
1265
+ if (op.parameters) {
1266
+ for (const param of op.parameters) {
1267
+ const baseType = this.mapOpenApiType(param.schema);
1268
+ shape[param.name] = param.required ? baseType : baseType.optional();
1269
+ }
1270
+ }
1271
+ if (op.requestBody?.content) {
1272
+ const { schema: bodySchema, mediaType } = this.buildBodySchema(op.requestBody.content);
1273
+ shape["body"] = op.requestBody.required ? bodySchema : bodySchema.optional();
1274
+ bodyMediaType = mediaType;
1275
+ } else if (op.requestBody) {
1276
+ const fallback = z2.record(z2.string(), z2.unknown());
1277
+ shape["body"] = op.requestBody.required ? fallback : fallback.optional();
1278
+ }
1279
+ const schema = Object.keys(shape).length > 0 ? z2.object(shape) : z2.record(z2.string(), z2.unknown());
1280
+ return { schema, bodyMediaType };
1281
+ }
1282
+ /**
1283
+ * Serialize a parameter value for use in URLs/headers.
1284
+ * Arrays and objects are JSON-stringified; primitives use String().
1285
+ */
1286
+ static serializeParam(value) {
1287
+ if (value === null || value === void 0) return "";
1288
+ if (typeof value === "object") return JSON.stringify(value);
1289
+ return String(value);
1290
+ }
1291
+ /**
1292
+ * Check if a content-type string represents a JSON media type.
1293
+ * Matches 'application/json' and structured syntax suffix '+json' (RFC 6838).
1294
+ */
1295
+ static isJsonContentType(contentType) {
1296
+ return contentType.includes("application/json") || contentType.includes("+json");
1297
+ }
1298
+ /**
1299
+ * Map an OpenAPI schema type to the corresponding Zod type.
1300
+ */
1301
+ mapOpenApiType(schema) {
1302
+ if (!schema || !schema["type"]) return z2.unknown();
1303
+ const type = schema["type"];
1304
+ const enumValues = schema["enum"];
1305
+ switch (type) {
1306
+ case "integer":
1307
+ return z2.number().int();
1308
+ case "number":
1309
+ return z2.number();
1310
+ case "boolean":
1311
+ return z2.boolean();
1312
+ case "array":
1313
+ return z2.array(this.mapOpenApiType(schema["items"]));
1314
+ case "object":
1315
+ return z2.record(z2.string(), z2.unknown());
1316
+ case "string":
1317
+ if (enumValues && enumValues.length > 0) {
1318
+ return z2.enum(enumValues);
1319
+ }
1320
+ return z2.string();
1321
+ default:
1322
+ return z2.unknown();
1323
+ }
1324
+ }
1325
+ /**
1326
+ * Build a Zod schema for the request body based on the media type.
1327
+ * Returns both the schema and the chosen media type for correct serialization.
1328
+ */
1329
+ buildBodySchema(content) {
1330
+ const jsonKey = Object.keys(content).find((k) => k.includes("json"));
1331
+ if (jsonKey) {
1332
+ const schema = content[jsonKey].schema;
1333
+ if (schema) return { schema: this.mapOpenApiType(schema), mediaType: jsonKey };
1334
+ return { schema: z2.record(z2.string(), z2.unknown()), mediaType: jsonKey };
1335
+ }
1336
+ if (content["application/x-www-form-urlencoded"]) {
1337
+ return { schema: z2.record(z2.string(), z2.unknown()), mediaType: "application/x-www-form-urlencoded" };
1338
+ }
1339
+ if (content["multipart/form-data"]) {
1340
+ return { schema: z2.record(z2.string(), z2.unknown()), mediaType: "multipart/form-data" };
1341
+ }
1342
+ const textKey = Object.keys(content).find((k) => k.startsWith("text/"));
1343
+ if (textKey) {
1344
+ return { schema: z2.string(), mediaType: textKey };
1345
+ }
1346
+ return { schema: z2.record(z2.string(), z2.unknown()), mediaType: "application/json" };
1347
+ }
1348
+ /**
1349
+ * Create a handler function for an OpenAPI operation.
1350
+ */
1351
+ createHandler(op, baseUrl, bodyMediaType) {
1352
+ const auth = this.auth;
1353
+ const headers = this.options.headers ?? {};
1354
+ return async (args, context) => {
1355
+ const params = args;
1356
+ let normalizedBase = baseUrl;
1357
+ while (normalizedBase.endsWith("/")) normalizedBase = normalizedBase.slice(0, -1);
1358
+ let url = `${normalizedBase}${op.path.startsWith("/") ? op.path : "/" + op.path}`;
1359
+ const queryParams = {};
1360
+ if (op.parameters) {
1361
+ for (const param of op.parameters) {
1362
+ const value = params[param.name];
1363
+ 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") {
1367
+ queryParams[param.name] = _OpenApiToolLoader.serializeParam(value);
1368
+ }
1369
+ }
1370
+ }
1371
+ const queryString = new URLSearchParams(queryParams).toString();
1372
+ if (queryString) {
1373
+ url += `?${queryString}`;
1374
+ }
1375
+ const hasBody = (["post", "put", "patch", "delete"].includes(op.method) || op.requestBody != null) && Object.prototype.hasOwnProperty.call(params, "body") && params["body"] != null;
1376
+ const resolvedMediaType = bodyMediaType ?? "application/json";
1377
+ 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());
1400
+ }
1401
+ if (op.parameters) {
1402
+ for (const param of op.parameters) {
1403
+ 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]);
1406
+ }
1407
+ }
1408
+ }
1409
+ const fetchOptions = {
1410
+ method: op.method.toUpperCase(),
1411
+ headers: requestHeaders,
1412
+ signal: context.signal
1413
+ };
1414
+ if (hasBody) {
1415
+ if (_OpenApiToolLoader.isJsonContentType(resolvedMediaType)) {
1416
+ fetchOptions.body = JSON.stringify(params["body"]);
1417
+ } else if (resolvedMediaType === "application/x-www-form-urlencoded") {
1418
+ fetchOptions.body = new URLSearchParams(params["body"]).toString();
1419
+ } else if (resolvedMediaType === "multipart/form-data") {
1420
+ const formData = new FormData();
1421
+ const bodyObj = params["body"];
1422
+ for (const [key, value] of Object.entries(bodyObj)) {
1423
+ formData.append(key, value instanceof Blob ? value : String(value));
1424
+ }
1425
+ fetchOptions.body = formData;
1426
+ } else if (resolvedMediaType.startsWith("text/")) {
1427
+ fetchOptions.body = String(params["body"]);
1428
+ } else {
1429
+ fetchOptions.body = JSON.stringify(params["body"]);
1430
+ }
1431
+ }
1432
+ const response = await fetch(url, fetchOptions);
1433
+ if (!response.ok) {
1434
+ const contentType2 = response.headers.get("content-type") ?? "";
1435
+ let body;
1436
+ try {
1437
+ body = _OpenApiToolLoader.isJsonContentType(contentType2) ? JSON.stringify(await response.json()) : await response.text();
1438
+ } catch {
1439
+ body = "";
1440
+ }
1441
+ throw new Error(`HTTP ${response.status} ${response.statusText}: ${body}`);
1442
+ }
1443
+ const contentType = response.headers.get("content-type") ?? "";
1444
+ if (_OpenApiToolLoader.isJsonContentType(contentType)) {
1445
+ return response.json();
1446
+ }
1447
+ return response.text();
1448
+ };
1449
+ }
1450
+ };
1451
+
1452
+ // libs/broker/src/openapi/openapi-source.ts
1453
+ var OpenApiSource = class extends EventEmitter2 {
1454
+ toolRegistry;
1455
+ config;
1456
+ poller = null;
1457
+ previousToolNames = /* @__PURE__ */ new Set();
1458
+ lastUpdate = "";
1459
+ specHash = "";
1460
+ health = "unknown";
1461
+ disposed = false;
1462
+ _syncLock = Promise.resolve();
1463
+ constructor(toolRegistry, config) {
1464
+ super();
1465
+ this.toolRegistry = toolRegistry;
1466
+ this.config = config;
1467
+ }
1468
+ /**
1469
+ * Initial load + start polling.
1470
+ */
1471
+ async start() {
1472
+ if (this.disposed) throw new Error("OpenApiSource is disposed");
1473
+ await this.refresh();
1474
+ this.poller = new OpenApiSpecPoller(this.config);
1475
+ this.poller.on("changed", (spec) => {
1476
+ 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)));
1483
+ }
1484
+ });
1485
+ });
1486
+ this.poller.on("unhealthy", (failures) => {
1487
+ this.health = "unhealthy";
1488
+ this.emit("unhealthy", failures);
1489
+ });
1490
+ this.poller.on("recovered", () => {
1491
+ this.health = "healthy";
1492
+ this.emit("recovered");
1493
+ });
1494
+ this.poller.on("pollError", (error) => {
1495
+ this.emit("error", error);
1496
+ });
1497
+ this.poller.start();
1498
+ }
1499
+ /**
1500
+ * Stop polling.
1501
+ */
1502
+ stop() {
1503
+ if (this.poller) {
1504
+ this.poller.stop();
1505
+ }
1506
+ }
1507
+ /**
1508
+ * Manual refresh (for webhook triggers).
1509
+ */
1510
+ async refresh() {
1511
+ 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
+ });
1553
+ }
1554
+ }
1555
+ /**
1556
+ * Sync tools based on a new spec (diff-based update).
1557
+ */
1558
+ async syncTools(spec) {
1559
+ const loader = await OpenApiToolLoader.fromSpec(
1560
+ spec,
1561
+ {
1562
+ ...this.config.loaderOptions,
1563
+ baseUrl: this.config.baseUrl,
1564
+ sourceName: this.config.name
1565
+ },
1566
+ this.config.auth
1567
+ );
1568
+ const newTools = loader.getTools();
1569
+ const newToolNames = loader.getToolNames();
1570
+ const added = [];
1571
+ const removed = [];
1572
+ const updated = [];
1573
+ 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
+ }
1581
+ }
1582
+ for (const name of this.previousToolNames) {
1583
+ if (!newToolNames.has(name)) {
1584
+ this.toolRegistry.unregister(name);
1585
+ removed.push(name);
1586
+ }
1587
+ }
1588
+ this.previousToolNames = newToolNames;
1589
+ this.specHash = loader.getSpecHash();
1590
+ this.lastUpdate = (/* @__PURE__ */ new Date()).toISOString();
1591
+ const event = { added, removed, updated };
1592
+ this.emit("toolsUpdated", event);
1593
+ if (added.length > 0 || removed.length > 0) {
1594
+ this.emit("catalogChanged", {
1595
+ version: this.specHash,
1596
+ addedActions: added,
1597
+ removedActions: removed
1598
+ });
1599
+ }
1600
+ }
1601
+ /**
1602
+ * Get the set of tool names managed by this source.
1603
+ */
1604
+ getToolNames() {
1605
+ return new Set(this.previousToolNames);
1606
+ }
1607
+ /**
1608
+ * Get source statistics.
1609
+ */
1610
+ getStats() {
1611
+ return {
1612
+ toolCount: this.previousToolNames.size,
1613
+ lastUpdate: this.lastUpdate,
1614
+ specHash: this.specHash,
1615
+ pollHealth: this.health
1616
+ };
1617
+ }
1618
+ /**
1619
+ * Get the source name.
1620
+ */
1621
+ getName() {
1622
+ return this.config.name;
1623
+ }
1624
+ /**
1625
+ * Dispose the source and release resources.
1626
+ */
1627
+ dispose() {
1628
+ if (this.disposed) return;
1629
+ this.disposed = true;
1630
+ this.stop();
1631
+ if (this.poller) {
1632
+ this.poller.dispose();
1633
+ this.poller = null;
1634
+ }
1635
+ this.removeAllListeners();
1636
+ }
1637
+ };
1638
+
668
1639
  // libs/broker/src/broker.ts
669
1640
  var Broker = class {
670
1641
  toolRegistry;
671
1642
  sessionManager;
672
1643
  config;
1644
+ openApiSources = [];
673
1645
  disposed = false;
674
1646
  constructor(config = {}) {
675
1647
  this.config = config;
@@ -740,6 +1712,40 @@ var Broker = class {
740
1712
  return this.toolRegistry.unregister(name);
741
1713
  }
742
1714
  // ============================================================================
1715
+ // OpenAPI Sources
1716
+ // ============================================================================
1717
+ /**
1718
+ * Register an OpenAPI source for automatic tool generation and polling.
1719
+ *
1720
+ * @param config - OpenAPI source configuration
1721
+ * @returns The created OpenApiSource instance
1722
+ *
1723
+ * @example
1724
+ * ```typescript
1725
+ * const source = broker.openapi({
1726
+ * name: 'user-service',
1727
+ * url: 'https://api.example.com/openapi.json',
1728
+ * baseUrl: 'https://api.example.com',
1729
+ * intervalMs: 60000,
1730
+ * auth: { type: 'bearer', token: process.env.API_TOKEN },
1731
+ * });
1732
+ *
1733
+ * await source.start();
1734
+ * ```
1735
+ */
1736
+ openapi(config) {
1737
+ this.ensureNotDisposed();
1738
+ const source = new OpenApiSource(this.toolRegistry, config);
1739
+ this.openApiSources.push(source);
1740
+ return source;
1741
+ }
1742
+ /**
1743
+ * Get all registered OpenAPI sources.
1744
+ */
1745
+ getOpenApiSources() {
1746
+ return this.openApiSources;
1747
+ }
1748
+ // ============================================================================
743
1749
  // Secret Management
744
1750
  // ============================================================================
745
1751
  /**
@@ -887,6 +1893,10 @@ var Broker = class {
887
1893
  return;
888
1894
  }
889
1895
  this.disposed = true;
1896
+ for (const source of this.openApiSources) {
1897
+ source.dispose();
1898
+ }
1899
+ this.openApiSources.length = 0;
890
1900
  await this.sessionManager.dispose();
891
1901
  this.toolRegistry.clear();
892
1902
  this.toolRegistry.clearSecrets();
@@ -1549,10 +2559,79 @@ function registerExpressRoutes(router, handler) {
1549
2559
  router[method](route.path, expressHandler);
1550
2560
  }
1551
2561
  }
2562
+
2563
+ // libs/broker/src/openapi/catalog-handler.ts
2564
+ var CatalogHandler = class {
2565
+ toolRegistry;
2566
+ sources;
2567
+ constructor(toolRegistry, sources) {
2568
+ this.toolRegistry = toolRegistry;
2569
+ this.sources = sources;
2570
+ }
2571
+ /**
2572
+ * Get route definitions for the catalog endpoint.
2573
+ */
2574
+ getRoutes() {
2575
+ return [
2576
+ {
2577
+ method: "GET",
2578
+ path: "/code/actions",
2579
+ handler: this.handleGetActions.bind(this)
2580
+ }
2581
+ ];
2582
+ }
2583
+ /**
2584
+ * Handle GET /code/actions request.
2585
+ */
2586
+ async handleGetActions(_req, res) {
2587
+ const catalog = this.buildCatalog();
2588
+ res.status(200);
2589
+ res.json(catalog);
2590
+ }
2591
+ /**
2592
+ * Build the full catalog response.
2593
+ */
2594
+ buildCatalog() {
2595
+ const actions = [];
2596
+ const services = [];
2597
+ const toolToService = /* @__PURE__ */ new Map();
2598
+ for (const source of this.sources) {
2599
+ const stats = source.getStats();
2600
+ const serviceName = source.getName();
2601
+ services.push({
2602
+ name: serviceName,
2603
+ specUrl: "",
2604
+ // URL is internal to the source
2605
+ lastUpdated: stats.lastUpdate,
2606
+ actionCount: stats.toolCount
2607
+ });
2608
+ for (const toolName of source.getToolNames()) {
2609
+ toolToService.set(toolName, serviceName);
2610
+ }
2611
+ }
2612
+ const toolNames = this.toolRegistry.list();
2613
+ for (const name of toolNames) {
2614
+ const tool = this.toolRegistry.get(name);
2615
+ if (!tool) continue;
2616
+ actions.push({
2617
+ name: tool.name,
2618
+ description: tool.description,
2619
+ service: toolToService.get(name) ?? "default"
2620
+ });
2621
+ }
2622
+ const versionParts = this.sources.map((s) => s.getStats().specHash).sort().join(":");
2623
+ const version = versionParts || "empty";
2624
+ return { actions, services, version };
2625
+ }
2626
+ };
1552
2627
  export {
1553
2628
  Broker,
1554
2629
  BrokerSession,
2630
+ CatalogHandler,
1555
2631
  EventFilter,
2632
+ OpenApiSource,
2633
+ OpenApiSpecPoller,
2634
+ OpenApiToolLoader,
1556
2635
  SessionHandler,
1557
2636
  SessionManager,
1558
2637
  ToolRegistry,