@enclave-vm/broker 2.11.1 → 2.13.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/broker-session.d.ts +24 -1
- package/broker.d.ts +27 -0
- package/esm/index.mjs +1110 -31
- package/index.d.ts +2 -0
- package/index.js +1107 -30
- package/openapi/catalog-handler.d.ts +63 -0
- package/openapi/hash-utils.d.ts +12 -0
- package/openapi/index.d.ts +13 -0
- package/openapi/openapi-source.d.ts +93 -0
- package/openapi/openapi-spec-poller.d.ts +100 -0
- package/openapi/openapi-tool-loader.d.ts +107 -0
- package/package.json +5 -5
- package/tool-registry.d.ts +5 -0
package/index.js
CHANGED
|
@@ -22,7 +22,11 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
Broker: () => Broker,
|
|
24
24
|
BrokerSession: () => BrokerSession,
|
|
25
|
+
CatalogHandler: () => CatalogHandler,
|
|
25
26
|
EventFilter: () => EventFilter,
|
|
27
|
+
OpenApiSource: () => OpenApiSource,
|
|
28
|
+
OpenApiSpecPoller: () => OpenApiSpecPoller,
|
|
29
|
+
OpenApiToolLoader: () => OpenApiToolLoader,
|
|
26
30
|
SessionHandler: () => SessionHandler,
|
|
27
31
|
SessionManager: () => SessionManager,
|
|
28
32
|
ToolRegistry: () => ToolRegistry,
|
|
@@ -71,6 +75,18 @@ var ToolRegistry = class {
|
|
|
71
75
|
unregister(name) {
|
|
72
76
|
return this.tools.delete(name);
|
|
73
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Replace an existing tool with a new definition.
|
|
80
|
+
* If the tool doesn't exist, it registers it as new.
|
|
81
|
+
*/
|
|
82
|
+
replace(definition) {
|
|
83
|
+
this.tools.delete(definition.name);
|
|
84
|
+
const argsSchema = definition.argsSchema ?? import_zod.z.record(import_zod.z.string(), import_zod.z.unknown());
|
|
85
|
+
this.tools.set(definition.name, {
|
|
86
|
+
definition,
|
|
87
|
+
argsSchema
|
|
88
|
+
});
|
|
89
|
+
}
|
|
74
90
|
/**
|
|
75
91
|
* Check if a tool is registered
|
|
76
92
|
*/
|
|
@@ -268,6 +284,9 @@ var BrokerSession = class {
|
|
|
268
284
|
toolCallCount = 0;
|
|
269
285
|
stdoutBytes = 0;
|
|
270
286
|
heartbeatInterval = null;
|
|
287
|
+
deadlineTimer = null;
|
|
288
|
+
_deadlineExceeded = false;
|
|
289
|
+
partialErrors = [];
|
|
271
290
|
constructor(toolRegistry, config = {}) {
|
|
272
291
|
this.sessionId = config.sessionId ?? (0, import_types.generateSessionId)();
|
|
273
292
|
this.createdAt = Date.now();
|
|
@@ -336,6 +355,46 @@ var BrokerSession = class {
|
|
|
336
355
|
}
|
|
337
356
|
}, heartbeatMs);
|
|
338
357
|
}
|
|
358
|
+
const deadlineMs = this.limits.deadlineMs;
|
|
359
|
+
if (deadlineMs > 0) {
|
|
360
|
+
const remaining = deadlineMs - (Date.now() - this.createdAt);
|
|
361
|
+
if (remaining > 0) {
|
|
362
|
+
this.deadlineTimer = setTimeout(() => {
|
|
363
|
+
this._deadlineExceeded = true;
|
|
364
|
+
this.cancel(`Deadline exceeded: ${deadlineMs}ms budget`);
|
|
365
|
+
}, remaining);
|
|
366
|
+
} else {
|
|
367
|
+
this._deadlineExceeded = true;
|
|
368
|
+
this.stopHeartbeat();
|
|
369
|
+
this._state = "failed";
|
|
370
|
+
const elapsed = Date.now() - this.createdAt;
|
|
371
|
+
this.emitter.emit(
|
|
372
|
+
this.makeCustomEvent(import_types.EventType.DeadlineExceeded, { elapsedMs: elapsed, budgetMs: deadlineMs })
|
|
373
|
+
);
|
|
374
|
+
this.emitter.emitFinalError(
|
|
375
|
+
{ code: "DEADLINE_EXCEEDED", message: "Deadline exceeded before execution" },
|
|
376
|
+
{ durationMs: elapsed, toolCallCount: 0, stdoutBytes: 0 }
|
|
377
|
+
);
|
|
378
|
+
const finalResult = {
|
|
379
|
+
success: false,
|
|
380
|
+
error: {
|
|
381
|
+
message: "Deadline exceeded before execution",
|
|
382
|
+
name: "Error",
|
|
383
|
+
code: "DEADLINE_EXCEEDED"
|
|
384
|
+
},
|
|
385
|
+
stats: {
|
|
386
|
+
duration: elapsed,
|
|
387
|
+
toolCallCount: 0,
|
|
388
|
+
iterationCount: 0,
|
|
389
|
+
startTime: this.createdAt,
|
|
390
|
+
endTime: Date.now()
|
|
391
|
+
},
|
|
392
|
+
finalState: "failed"
|
|
393
|
+
};
|
|
394
|
+
this.executionPromise = Promise.resolve(finalResult);
|
|
395
|
+
return finalResult;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
339
398
|
this._state = "running";
|
|
340
399
|
this.executionPromise = this.runExecution(code);
|
|
341
400
|
return this.executionPromise;
|
|
@@ -355,13 +414,34 @@ var BrokerSession = class {
|
|
|
355
414
|
});
|
|
356
415
|
const endTime = Date.now();
|
|
357
416
|
const stats = this.buildStats(startTime, endTime);
|
|
358
|
-
|
|
417
|
+
const eventStats = {
|
|
418
|
+
durationMs: stats.duration,
|
|
419
|
+
toolCallCount: this.toolCallCount,
|
|
420
|
+
stdoutBytes: this.stdoutBytes
|
|
421
|
+
};
|
|
422
|
+
if (this.isTerminal()) {
|
|
423
|
+
if (this._deadlineExceeded) {
|
|
424
|
+
this.emitter.emit(
|
|
425
|
+
this.makeCustomEvent(import_types.EventType.DeadlineExceeded, {
|
|
426
|
+
elapsedMs: Date.now() - this.createdAt,
|
|
427
|
+
budgetMs: this.limits.deadlineMs
|
|
428
|
+
})
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
const cancelError = {
|
|
432
|
+
code: this._deadlineExceeded ? "DEADLINE_EXCEEDED" : "SESSION_CANCELLED",
|
|
433
|
+
message: this._deadlineExceeded ? "Deadline exceeded" : "Session was cancelled"
|
|
434
|
+
};
|
|
435
|
+
this.emitter.emitFinalError(cancelError, eventStats, this.getPartialErrors());
|
|
436
|
+
result = {
|
|
437
|
+
success: false,
|
|
438
|
+
error: { message: cancelError.message, name: "Error", code: cancelError.code },
|
|
439
|
+
stats,
|
|
440
|
+
finalState: this._deadlineExceeded ? "failed" : "cancelled"
|
|
441
|
+
};
|
|
442
|
+
} else if (enclaveResult.success) {
|
|
359
443
|
this._state = "completed";
|
|
360
|
-
this.emitter.emitFinalSuccess(enclaveResult.value,
|
|
361
|
-
durationMs: stats.duration,
|
|
362
|
-
toolCallCount: this.toolCallCount,
|
|
363
|
-
stdoutBytes: this.stdoutBytes
|
|
364
|
-
});
|
|
444
|
+
this.emitter.emitFinalSuccess(enclaveResult.value, eventStats, this.getPartialErrors());
|
|
365
445
|
result = {
|
|
366
446
|
success: true,
|
|
367
447
|
value: enclaveResult.value,
|
|
@@ -374,11 +454,7 @@ var BrokerSession = class {
|
|
|
374
454
|
code: enclaveResult.error?.code ?? "EXECUTION_ERROR",
|
|
375
455
|
message: enclaveResult.error?.message ?? "Execution failed"
|
|
376
456
|
};
|
|
377
|
-
this.emitter.emitFinalError(errorInfo,
|
|
378
|
-
durationMs: stats.duration,
|
|
379
|
-
toolCallCount: this.toolCallCount,
|
|
380
|
-
stdoutBytes: this.stdoutBytes
|
|
381
|
-
});
|
|
457
|
+
this.emitter.emitFinalError(errorInfo, eventStats, this.getPartialErrors());
|
|
382
458
|
result = {
|
|
383
459
|
success: false,
|
|
384
460
|
error: {
|
|
@@ -394,16 +470,28 @@ var BrokerSession = class {
|
|
|
394
470
|
const endTime = Date.now();
|
|
395
471
|
const stats = this.buildStats(startTime, endTime);
|
|
396
472
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
397
|
-
|
|
398
|
-
const errorInfo = {
|
|
399
|
-
code: err.code ?? "EXECUTION_ERROR",
|
|
400
|
-
message: err.message
|
|
401
|
-
};
|
|
402
|
-
this.emitter.emitFinalError(errorInfo, {
|
|
473
|
+
const eventStats = {
|
|
403
474
|
durationMs: stats.duration,
|
|
404
475
|
toolCallCount: this.toolCallCount,
|
|
405
476
|
stdoutBytes: this.stdoutBytes
|
|
406
|
-
}
|
|
477
|
+
};
|
|
478
|
+
if (this._deadlineExceeded) {
|
|
479
|
+
this.emitter.emit(
|
|
480
|
+
this.makeCustomEvent(import_types.EventType.DeadlineExceeded, {
|
|
481
|
+
elapsedMs: Date.now() - this.createdAt,
|
|
482
|
+
budgetMs: this.limits.deadlineMs
|
|
483
|
+
})
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
if (!this.isTerminal()) {
|
|
487
|
+
this._state = "failed";
|
|
488
|
+
}
|
|
489
|
+
const isCancelled = this._state === "cancelled";
|
|
490
|
+
const errorInfo = {
|
|
491
|
+
code: isCancelled ? this._deadlineExceeded ? "DEADLINE_EXCEEDED" : "SESSION_CANCELLED" : err.code ?? "EXECUTION_ERROR",
|
|
492
|
+
message: err.message
|
|
493
|
+
};
|
|
494
|
+
this.emitter.emitFinalError(errorInfo, eventStats, this.getPartialErrors());
|
|
407
495
|
result = {
|
|
408
496
|
success: false,
|
|
409
497
|
error: {
|
|
@@ -412,37 +500,123 @@ var BrokerSession = class {
|
|
|
412
500
|
code: errorInfo.code
|
|
413
501
|
},
|
|
414
502
|
stats,
|
|
415
|
-
finalState: "failed"
|
|
503
|
+
finalState: isCancelled ? "cancelled" : "failed"
|
|
416
504
|
};
|
|
417
505
|
} finally {
|
|
418
506
|
this.stopHeartbeat();
|
|
507
|
+
this.stopDeadline();
|
|
419
508
|
}
|
|
420
509
|
return result;
|
|
421
510
|
}
|
|
511
|
+
/**
|
|
512
|
+
* Emit a tool progress event.
|
|
513
|
+
*/
|
|
514
|
+
emitToolProgress(callId, phase, elapsedMs, bytesReceived, totalBytes) {
|
|
515
|
+
this.emitter.emit(
|
|
516
|
+
this.makeCustomEvent(import_types.EventType.ToolProgress, {
|
|
517
|
+
callId,
|
|
518
|
+
phase,
|
|
519
|
+
elapsedMs,
|
|
520
|
+
bytesReceived,
|
|
521
|
+
totalBytes
|
|
522
|
+
})
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Emit a partial result event.
|
|
527
|
+
*/
|
|
528
|
+
emitPartialResult(path, data, error, hasNext = true) {
|
|
529
|
+
if (error) {
|
|
530
|
+
this.partialErrors.push(error);
|
|
531
|
+
}
|
|
532
|
+
this.emitter.emit(
|
|
533
|
+
this.makeCustomEvent(import_types.EventType.PartialResult, {
|
|
534
|
+
path,
|
|
535
|
+
data,
|
|
536
|
+
error,
|
|
537
|
+
hasNext
|
|
538
|
+
})
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Get accumulated partial errors.
|
|
543
|
+
*/
|
|
544
|
+
getPartialErrors() {
|
|
545
|
+
return [...this.partialErrors];
|
|
546
|
+
}
|
|
422
547
|
/**
|
|
423
548
|
* Execute a tool call directly
|
|
424
549
|
*/
|
|
425
550
|
async executeTool(toolName, args) {
|
|
426
551
|
const callId = (0, import_types.generateCallId)();
|
|
552
|
+
const toolStartTime = Date.now();
|
|
553
|
+
if (this.limits.deadlineMs > 0) {
|
|
554
|
+
const elapsed = Date.now() - this.createdAt;
|
|
555
|
+
const remaining = this.limits.deadlineMs - elapsed;
|
|
556
|
+
if (remaining <= 0) {
|
|
557
|
+
this._deadlineExceeded = true;
|
|
558
|
+
const err = new Error("Deadline exceeded before tool execution");
|
|
559
|
+
err.code = "DEADLINE_EXCEEDED";
|
|
560
|
+
throw err;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
427
563
|
this.emitter.emitToolCall(callId, toolName, args);
|
|
428
564
|
this.toolCallCount++;
|
|
565
|
+
this.emitToolProgress(callId, "connecting", 0);
|
|
566
|
+
let toolTimeout = this.limits.perToolDeadlineMs;
|
|
567
|
+
if (this.limits.deadlineMs > 0) {
|
|
568
|
+
const remaining = this.limits.deadlineMs - (Date.now() - this.createdAt);
|
|
569
|
+
toolTimeout = Math.min(toolTimeout, remaining);
|
|
570
|
+
}
|
|
571
|
+
const toolAbort = new AbortController();
|
|
572
|
+
let toolTimer = null;
|
|
573
|
+
if (toolTimeout > 0) {
|
|
574
|
+
toolTimer = setTimeout(() => toolAbort.abort(), toolTimeout);
|
|
575
|
+
}
|
|
576
|
+
const onSessionAbort = () => toolAbort.abort();
|
|
577
|
+
this.abortController.signal.addEventListener("abort", onSessionAbort);
|
|
578
|
+
if (this.abortController.signal.aborted) {
|
|
579
|
+
toolAbort.abort();
|
|
580
|
+
}
|
|
429
581
|
const context = {
|
|
430
582
|
sessionId: this.sessionId,
|
|
431
583
|
callId,
|
|
432
584
|
secrets: {},
|
|
433
585
|
// Resolved by registry
|
|
434
|
-
signal:
|
|
586
|
+
signal: toolAbort.signal
|
|
435
587
|
};
|
|
436
|
-
|
|
588
|
+
this.emitToolProgress(callId, "processing", Date.now() - toolStartTime);
|
|
589
|
+
let result;
|
|
590
|
+
try {
|
|
591
|
+
result = await this.toolRegistry.execute(toolName, args, context);
|
|
592
|
+
} finally {
|
|
593
|
+
if (toolTimer) clearTimeout(toolTimer);
|
|
594
|
+
this.abortController.signal.removeEventListener("abort", onSessionAbort);
|
|
595
|
+
}
|
|
437
596
|
this.emitter.emitToolResultApplied(callId);
|
|
438
597
|
if (result.success) {
|
|
439
598
|
return result.value;
|
|
440
599
|
} else {
|
|
600
|
+
if (this.limits.cancelOnFirstError) {
|
|
601
|
+
this.abortController.abort();
|
|
602
|
+
}
|
|
441
603
|
const error = new Error(result.error?.message ?? "Tool call failed");
|
|
442
604
|
error.code = result.error?.code;
|
|
443
605
|
throw error;
|
|
444
606
|
}
|
|
445
607
|
}
|
|
608
|
+
/**
|
|
609
|
+
* Create a custom event with proper base fields and unique sequence number.
|
|
610
|
+
*/
|
|
611
|
+
makeCustomEvent(type, payload) {
|
|
612
|
+
return {
|
|
613
|
+
protocolVersion: import_types.PROTOCOL_VERSION,
|
|
614
|
+
sessionId: this.sessionId,
|
|
615
|
+
seq: this.emitter.nextSeq(),
|
|
616
|
+
type,
|
|
617
|
+
payload
|
|
618
|
+
};
|
|
619
|
+
}
|
|
446
620
|
/**
|
|
447
621
|
* Build execution stats
|
|
448
622
|
*/
|
|
@@ -463,17 +637,37 @@ var BrokerSession = class {
|
|
|
463
637
|
return;
|
|
464
638
|
}
|
|
465
639
|
this.stopHeartbeat();
|
|
640
|
+
this.stopDeadline();
|
|
466
641
|
this.abortController.abort();
|
|
467
642
|
this._state = "cancelled";
|
|
468
|
-
this.
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
643
|
+
if (!this.executionPromise) {
|
|
644
|
+
this.emitter.emitError("SESSION_CANCELLED", reason ?? "Session was cancelled", false);
|
|
645
|
+
this.emitter.emitFinalError(
|
|
646
|
+
{ code: "SESSION_CANCELLED", message: reason ?? "Session was cancelled" },
|
|
647
|
+
{
|
|
648
|
+
durationMs: Date.now() - this.createdAt,
|
|
649
|
+
toolCallCount: this.toolCallCount,
|
|
650
|
+
stdoutBytes: this.stdoutBytes
|
|
651
|
+
},
|
|
652
|
+
this.getPartialErrors()
|
|
653
|
+
);
|
|
654
|
+
this.executionPromise = Promise.resolve({
|
|
655
|
+
success: false,
|
|
656
|
+
error: {
|
|
657
|
+
message: reason ?? "Session was cancelled",
|
|
658
|
+
name: "Error",
|
|
659
|
+
code: "SESSION_CANCELLED"
|
|
660
|
+
},
|
|
661
|
+
stats: {
|
|
662
|
+
duration: Date.now() - this.createdAt,
|
|
663
|
+
toolCallCount: this.toolCallCount,
|
|
664
|
+
iterationCount: 0,
|
|
665
|
+
startTime: this.createdAt,
|
|
666
|
+
endTime: Date.now()
|
|
667
|
+
},
|
|
668
|
+
finalState: "cancelled"
|
|
669
|
+
});
|
|
670
|
+
}
|
|
477
671
|
}
|
|
478
672
|
/**
|
|
479
673
|
* Wait for the session to complete
|
|
@@ -518,11 +712,21 @@ var BrokerSession = class {
|
|
|
518
712
|
this.heartbeatInterval = null;
|
|
519
713
|
}
|
|
520
714
|
}
|
|
715
|
+
/**
|
|
716
|
+
* Stop deadline timer
|
|
717
|
+
*/
|
|
718
|
+
stopDeadline() {
|
|
719
|
+
if (this.deadlineTimer) {
|
|
720
|
+
clearTimeout(this.deadlineTimer);
|
|
721
|
+
this.deadlineTimer = null;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
521
724
|
/**
|
|
522
725
|
* Dispose of the session and its resources
|
|
523
726
|
*/
|
|
524
727
|
dispose() {
|
|
525
728
|
this.stopHeartbeat();
|
|
729
|
+
this.stopDeadline();
|
|
526
730
|
this.abortController.abort();
|
|
527
731
|
this.enclave.dispose();
|
|
528
732
|
}
|
|
@@ -706,11 +910,777 @@ function createSessionManager(toolRegistry, config) {
|
|
|
706
910
|
return new SessionManager(toolRegistry, config);
|
|
707
911
|
}
|
|
708
912
|
|
|
913
|
+
// libs/broker/src/openapi/openapi-source.ts
|
|
914
|
+
var import_events2 = require("events");
|
|
915
|
+
|
|
916
|
+
// libs/broker/src/openapi/openapi-spec-poller.ts
|
|
917
|
+
var import_events = require("events");
|
|
918
|
+
|
|
919
|
+
// libs/broker/src/openapi/hash-utils.ts
|
|
920
|
+
async function sha256Hex(data) {
|
|
921
|
+
const encoded = new TextEncoder().encode(data);
|
|
922
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", encoded);
|
|
923
|
+
const hashArray = new Uint8Array(hashBuffer);
|
|
924
|
+
return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// libs/broker/src/openapi/openapi-spec-poller.ts
|
|
928
|
+
var DEFAULT_RETRY = {
|
|
929
|
+
maxRetries: 3,
|
|
930
|
+
initialDelayMs: 1e3,
|
|
931
|
+
maxDelayMs: 1e4,
|
|
932
|
+
backoffMultiplier: 2
|
|
933
|
+
};
|
|
934
|
+
var OpenApiSpecPoller = class extends import_events.EventEmitter {
|
|
935
|
+
config;
|
|
936
|
+
intervalTimer = null;
|
|
937
|
+
lastHash = null;
|
|
938
|
+
lastEtag = null;
|
|
939
|
+
lastModified = null;
|
|
940
|
+
consecutiveFailures = 0;
|
|
941
|
+
isPolling = false;
|
|
942
|
+
wasUnhealthy = false;
|
|
943
|
+
/** Per-run abort controller — aborted on stop(), recreated on start() */
|
|
944
|
+
_runAbort = new AbortController();
|
|
945
|
+
_fetchController = null;
|
|
946
|
+
_activePoll = null;
|
|
947
|
+
constructor(config) {
|
|
948
|
+
super();
|
|
949
|
+
this.config = {
|
|
950
|
+
url: config.url,
|
|
951
|
+
intervalMs: config.intervalMs ?? 6e4,
|
|
952
|
+
fetchTimeoutMs: config.fetchTimeoutMs ?? 1e4,
|
|
953
|
+
changeDetection: config.changeDetection ?? "auto",
|
|
954
|
+
unhealthyThreshold: config.unhealthyThreshold ?? 3,
|
|
955
|
+
retry: { ...DEFAULT_RETRY, ...config.retry },
|
|
956
|
+
headers: config.headers ?? {}
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Start polling for changes.
|
|
961
|
+
*/
|
|
962
|
+
start() {
|
|
963
|
+
if (this.intervalTimer) return;
|
|
964
|
+
this._runAbort = new AbortController();
|
|
965
|
+
const runSignal = this._runAbort.signal;
|
|
966
|
+
const pendingPoll = this._activePoll;
|
|
967
|
+
if (pendingPoll) {
|
|
968
|
+
pendingPoll.finally(() => {
|
|
969
|
+
if (!runSignal.aborted) {
|
|
970
|
+
this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
|
|
971
|
+
}
|
|
972
|
+
});
|
|
973
|
+
} else {
|
|
974
|
+
this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
|
|
975
|
+
}
|
|
976
|
+
this.intervalTimer = setInterval(() => {
|
|
977
|
+
this._activePoll = this.pollWithSignal(runSignal).catch(() => void 0);
|
|
978
|
+
}, this.config.intervalMs);
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* Stop polling.
|
|
982
|
+
*/
|
|
983
|
+
stop() {
|
|
984
|
+
this._runAbort.abort();
|
|
985
|
+
if (this._fetchController) {
|
|
986
|
+
this._fetchController.abort();
|
|
987
|
+
this._fetchController = null;
|
|
988
|
+
}
|
|
989
|
+
if (this.intervalTimer) {
|
|
990
|
+
clearInterval(this.intervalTimer);
|
|
991
|
+
this.intervalTimer = null;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Get the current content hash.
|
|
996
|
+
*/
|
|
997
|
+
getHash() {
|
|
998
|
+
return this.lastHash;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Get the number of consecutive failures.
|
|
1002
|
+
*/
|
|
1003
|
+
getConsecutiveFailures() {
|
|
1004
|
+
return this.consecutiveFailures;
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Perform a single poll cycle.
|
|
1008
|
+
*/
|
|
1009
|
+
async poll() {
|
|
1010
|
+
return this.pollWithSignal(this._runAbort.signal);
|
|
1011
|
+
}
|
|
1012
|
+
async pollWithSignal(runSignal) {
|
|
1013
|
+
if (this.isPolling) return;
|
|
1014
|
+
this.isPolling = true;
|
|
1015
|
+
try {
|
|
1016
|
+
await this.fetchWithRetry(runSignal);
|
|
1017
|
+
} finally {
|
|
1018
|
+
this.isPolling = false;
|
|
1019
|
+
this._activePoll = null;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
async fetchWithRetry(runSignal) {
|
|
1023
|
+
const { maxRetries, initialDelayMs, maxDelayMs, backoffMultiplier } = this.config.retry;
|
|
1024
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1025
|
+
if (runSignal.aborted) return;
|
|
1026
|
+
try {
|
|
1027
|
+
await this.doFetch(runSignal);
|
|
1028
|
+
if (runSignal.aborted) return;
|
|
1029
|
+
if (this.consecutiveFailures > 0) {
|
|
1030
|
+
this.consecutiveFailures = 0;
|
|
1031
|
+
if (this.wasUnhealthy) {
|
|
1032
|
+
this.wasUnhealthy = false;
|
|
1033
|
+
this.emit("recovered");
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
return;
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
if (runSignal.aborted) return;
|
|
1039
|
+
if (attempt === maxRetries) {
|
|
1040
|
+
this.consecutiveFailures++;
|
|
1041
|
+
this.emit("pollError", error instanceof Error ? error : new Error(String(error)));
|
|
1042
|
+
if (this.consecutiveFailures >= this.config.unhealthyThreshold && !this.wasUnhealthy) {
|
|
1043
|
+
this.wasUnhealthy = true;
|
|
1044
|
+
this.emit("unhealthy", this.consecutiveFailures);
|
|
1045
|
+
}
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
const delay = Math.min(initialDelayMs * Math.pow(backoffMultiplier, attempt), maxDelayMs);
|
|
1049
|
+
await new Promise((resolve) => {
|
|
1050
|
+
const onAbort = () => {
|
|
1051
|
+
clearTimeout(timer);
|
|
1052
|
+
resolve();
|
|
1053
|
+
};
|
|
1054
|
+
const timer = setTimeout(() => {
|
|
1055
|
+
runSignal.removeEventListener("abort", onAbort);
|
|
1056
|
+
resolve();
|
|
1057
|
+
}, delay);
|
|
1058
|
+
runSignal.addEventListener("abort", onAbort, { once: true });
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
async doFetch(runSignal) {
|
|
1064
|
+
if (runSignal.aborted) return;
|
|
1065
|
+
const headers = { ...this.config.headers };
|
|
1066
|
+
if (this.config.changeDetection !== "content-hash") {
|
|
1067
|
+
if (this.lastEtag) {
|
|
1068
|
+
headers["If-None-Match"] = this.lastEtag;
|
|
1069
|
+
}
|
|
1070
|
+
if (this.lastModified) {
|
|
1071
|
+
headers["If-Modified-Since"] = this.lastModified;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
const controller = new AbortController();
|
|
1075
|
+
this._fetchController = controller;
|
|
1076
|
+
const timeout = setTimeout(() => controller.abort(), this.config.fetchTimeoutMs);
|
|
1077
|
+
try {
|
|
1078
|
+
const response = await fetch(this.config.url, {
|
|
1079
|
+
headers,
|
|
1080
|
+
signal: controller.signal
|
|
1081
|
+
});
|
|
1082
|
+
if (runSignal.aborted) return;
|
|
1083
|
+
if (response.status === 304) {
|
|
1084
|
+
this.emit("unchanged");
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
if (!response.ok) {
|
|
1088
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1089
|
+
}
|
|
1090
|
+
const etag = response.headers.get("etag");
|
|
1091
|
+
const lastModified = response.headers.get("last-modified");
|
|
1092
|
+
const body = await response.text();
|
|
1093
|
+
if (runSignal.aborted) return;
|
|
1094
|
+
const hash = await sha256Hex(body);
|
|
1095
|
+
if (runSignal.aborted) return;
|
|
1096
|
+
if (this.lastHash && this.lastHash === hash) {
|
|
1097
|
+
this.emit("unchanged");
|
|
1098
|
+
if (etag) this.lastEtag = etag;
|
|
1099
|
+
if (lastModified) this.lastModified = lastModified;
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
this.emit("changed", body, hash);
|
|
1103
|
+
this.lastHash = hash;
|
|
1104
|
+
if (etag) this.lastEtag = etag;
|
|
1105
|
+
if (lastModified) this.lastModified = lastModified;
|
|
1106
|
+
} finally {
|
|
1107
|
+
clearTimeout(timeout);
|
|
1108
|
+
if (this._fetchController === controller) {
|
|
1109
|
+
this._fetchController = null;
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Dispose the poller and release resources.
|
|
1115
|
+
*/
|
|
1116
|
+
dispose() {
|
|
1117
|
+
this.stop();
|
|
1118
|
+
this.removeAllListeners();
|
|
1119
|
+
}
|
|
1120
|
+
};
|
|
1121
|
+
|
|
1122
|
+
// libs/broker/src/openapi/openapi-tool-loader.ts
|
|
1123
|
+
var import_zod2 = require("zod");
|
|
1124
|
+
var OpenApiToolLoader = class _OpenApiToolLoader {
|
|
1125
|
+
tools = [];
|
|
1126
|
+
toolNames = /* @__PURE__ */ new Set();
|
|
1127
|
+
specHash;
|
|
1128
|
+
options;
|
|
1129
|
+
auth;
|
|
1130
|
+
constructor(spec, hash, options = {}, auth) {
|
|
1131
|
+
this.options = options;
|
|
1132
|
+
this.auth = auth;
|
|
1133
|
+
this.specHash = hash;
|
|
1134
|
+
this.loadFromSpec(spec);
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Create a loader from a URL.
|
|
1138
|
+
*/
|
|
1139
|
+
static async fromURL(url, options, auth) {
|
|
1140
|
+
const headers = { ...options?.headers };
|
|
1141
|
+
if (auth) {
|
|
1142
|
+
switch (auth.type) {
|
|
1143
|
+
case "bearer":
|
|
1144
|
+
if (auth.token) headers["Authorization"] = `Bearer ${auth.token}`;
|
|
1145
|
+
break;
|
|
1146
|
+
case "api-key":
|
|
1147
|
+
if (auth.token) headers[auth.header ?? "X-API-Key"] = auth.token;
|
|
1148
|
+
break;
|
|
1149
|
+
case "basic":
|
|
1150
|
+
if (auth.token) headers["Authorization"] = `Basic ${auth.token}`;
|
|
1151
|
+
break;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
const response = await fetch(url, { headers });
|
|
1155
|
+
if (!response.ok) {
|
|
1156
|
+
throw new Error(`Failed to fetch OpenAPI spec from ${url}: ${response.status}`);
|
|
1157
|
+
}
|
|
1158
|
+
const spec = await response.json();
|
|
1159
|
+
const hash = await sha256Hex(JSON.stringify(spec));
|
|
1160
|
+
let resolvedBaseUrl = options?.baseUrl;
|
|
1161
|
+
if (!resolvedBaseUrl) {
|
|
1162
|
+
const servers = spec["servers"];
|
|
1163
|
+
if (servers?.[0]?.url) {
|
|
1164
|
+
try {
|
|
1165
|
+
resolvedBaseUrl = new URL(servers[0].url, url).origin + new URL(servers[0].url, url).pathname;
|
|
1166
|
+
} catch {
|
|
1167
|
+
resolvedBaseUrl = new URL(url).origin;
|
|
1168
|
+
}
|
|
1169
|
+
} else {
|
|
1170
|
+
resolvedBaseUrl = new URL(url).origin;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
return new _OpenApiToolLoader(spec, hash, { ...options, baseUrl: resolvedBaseUrl }, auth);
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Create a loader from a spec object.
|
|
1177
|
+
*/
|
|
1178
|
+
static async fromSpec(spec, options, auth) {
|
|
1179
|
+
const hash = await sha256Hex(JSON.stringify(spec));
|
|
1180
|
+
let resolvedBaseUrl = options?.baseUrl;
|
|
1181
|
+
if (!resolvedBaseUrl) {
|
|
1182
|
+
const servers = spec["servers"];
|
|
1183
|
+
if (servers?.[0]?.url) {
|
|
1184
|
+
try {
|
|
1185
|
+
const serverUrl = new URL(servers[0].url);
|
|
1186
|
+
resolvedBaseUrl = serverUrl.origin + serverUrl.pathname;
|
|
1187
|
+
} catch {
|
|
1188
|
+
throw new Error(
|
|
1189
|
+
`Cannot resolve relative server URL "${servers[0].url}" without a source URL. Use fromURL() or provide an explicit baseUrl option.`
|
|
1190
|
+
);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
return new _OpenApiToolLoader(
|
|
1195
|
+
spec,
|
|
1196
|
+
hash,
|
|
1197
|
+
resolvedBaseUrl ? { ...options, baseUrl: resolvedBaseUrl } : options,
|
|
1198
|
+
auth
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Get all loaded tool definitions.
|
|
1203
|
+
*/
|
|
1204
|
+
getTools() {
|
|
1205
|
+
return [...this.tools];
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Get all tool names.
|
|
1209
|
+
*/
|
|
1210
|
+
getToolNames() {
|
|
1211
|
+
return new Set(this.toolNames);
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1214
|
+
* Get the hash of the loaded spec.
|
|
1215
|
+
*/
|
|
1216
|
+
getSpecHash() {
|
|
1217
|
+
return this.specHash;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Parse the OpenAPI spec and generate tool definitions.
|
|
1221
|
+
*/
|
|
1222
|
+
loadFromSpec(spec) {
|
|
1223
|
+
const paths = spec["paths"];
|
|
1224
|
+
if (!paths) return;
|
|
1225
|
+
const baseUrl = this.options.baseUrl ?? "";
|
|
1226
|
+
const operations = this.extractOperations(paths);
|
|
1227
|
+
for (const op of operations) {
|
|
1228
|
+
if (this.options.includeOperations && !this.options.includeOperations.includes(op.operationId)) {
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
if (this.options.excludeOperations && this.options.excludeOperations.includes(op.operationId)) {
|
|
1232
|
+
continue;
|
|
1233
|
+
}
|
|
1234
|
+
const baseName = op.operationId || `${op.method}_${op.path.replace(/[^a-zA-Z0-9]/g, "_")}`;
|
|
1235
|
+
const toolName = this.options.namingStrategy ? this.options.namingStrategy(op.method, op.path, op.operationId) : this.options.sourceName ? `${this.options.sourceName}_${baseName}` : baseName;
|
|
1236
|
+
const { schema: argsSchema, bodyMediaType } = this.buildArgsSchema(op);
|
|
1237
|
+
const timeout = this.options.perToolDeadlineMs ?? 3e4;
|
|
1238
|
+
const tool = {
|
|
1239
|
+
name: toolName,
|
|
1240
|
+
description: op.summary || op.description || `${op.method.toUpperCase()} ${op.path}`,
|
|
1241
|
+
argsSchema,
|
|
1242
|
+
config: {
|
|
1243
|
+
timeout
|
|
1244
|
+
},
|
|
1245
|
+
handler: this.createHandler(op, baseUrl, bodyMediaType)
|
|
1246
|
+
};
|
|
1247
|
+
if (this.toolNames.has(toolName)) {
|
|
1248
|
+
throw new Error(
|
|
1249
|
+
`Duplicate tool name "${toolName}" generated for ${op.method.toUpperCase()} ${op.path} (operationId: ${op.operationId}). Use a custom namingStrategy or sourceName to disambiguate.`
|
|
1250
|
+
);
|
|
1251
|
+
}
|
|
1252
|
+
this.tools.push(tool);
|
|
1253
|
+
this.toolNames.add(toolName);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Extract operations from OpenAPI paths.
|
|
1258
|
+
*/
|
|
1259
|
+
extractOperations(paths) {
|
|
1260
|
+
const operations = [];
|
|
1261
|
+
const httpMethods = ["get", "post", "put", "delete", "patch", "head", "options"];
|
|
1262
|
+
for (const [path, pathItem] of Object.entries(paths)) {
|
|
1263
|
+
const pathParams = pathItem["parameters"] ?? [];
|
|
1264
|
+
for (const method of httpMethods) {
|
|
1265
|
+
const operation = pathItem[method];
|
|
1266
|
+
if (!operation) continue;
|
|
1267
|
+
const operationId = operation["operationId"] || `${method}_${path.replace(/[^a-zA-Z0-9]/g, "_")}`;
|
|
1268
|
+
const opParams = operation["parameters"] ?? [];
|
|
1269
|
+
const merged = this.mergeParameters(pathParams, opParams);
|
|
1270
|
+
operations.push({
|
|
1271
|
+
operationId,
|
|
1272
|
+
method,
|
|
1273
|
+
path,
|
|
1274
|
+
summary: operation["summary"],
|
|
1275
|
+
description: operation["description"],
|
|
1276
|
+
parameters: merged.length > 0 ? merged : void 0,
|
|
1277
|
+
requestBody: operation["requestBody"],
|
|
1278
|
+
deprecated: operation["deprecated"]
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
return operations;
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Merge path-level and operation-level parameters, de-duplicating by (name, in).
|
|
1286
|
+
* Operation-level entries override path-level ones.
|
|
1287
|
+
*/
|
|
1288
|
+
mergeParameters(pathParams, opParams) {
|
|
1289
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1290
|
+
for (const p of pathParams) {
|
|
1291
|
+
seen.set(`${p.in}:${p.name}`, p);
|
|
1292
|
+
}
|
|
1293
|
+
for (const p of opParams) {
|
|
1294
|
+
seen.set(`${p.in}:${p.name}`, p);
|
|
1295
|
+
}
|
|
1296
|
+
return [...seen.values()];
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* Build a Zod args schema from an OpenAPI operation.
|
|
1300
|
+
*/
|
|
1301
|
+
buildArgsSchema(op) {
|
|
1302
|
+
const shape = {};
|
|
1303
|
+
let bodyMediaType;
|
|
1304
|
+
if (op.parameters) {
|
|
1305
|
+
for (const param of op.parameters) {
|
|
1306
|
+
const baseType = this.mapOpenApiType(param.schema);
|
|
1307
|
+
shape[param.name] = param.required ? baseType : baseType.optional();
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
if (op.requestBody?.content) {
|
|
1311
|
+
const { schema: bodySchema, mediaType } = this.buildBodySchema(op.requestBody.content);
|
|
1312
|
+
shape["body"] = op.requestBody.required ? bodySchema : bodySchema.optional();
|
|
1313
|
+
bodyMediaType = mediaType;
|
|
1314
|
+
} else if (op.requestBody) {
|
|
1315
|
+
const fallback = import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown());
|
|
1316
|
+
shape["body"] = op.requestBody.required ? fallback : fallback.optional();
|
|
1317
|
+
}
|
|
1318
|
+
const schema = Object.keys(shape).length > 0 ? import_zod2.z.object(shape) : import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown());
|
|
1319
|
+
return { schema, bodyMediaType };
|
|
1320
|
+
}
|
|
1321
|
+
/**
|
|
1322
|
+
* Serialize a parameter value for use in URLs/headers.
|
|
1323
|
+
* Arrays and objects are JSON-stringified; primitives use String().
|
|
1324
|
+
*/
|
|
1325
|
+
static serializeParam(value) {
|
|
1326
|
+
if (value === null || value === void 0) return "";
|
|
1327
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
1328
|
+
return String(value);
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Check if a content-type string represents a JSON media type.
|
|
1332
|
+
* Matches 'application/json' and structured syntax suffix '+json' (RFC 6838).
|
|
1333
|
+
*/
|
|
1334
|
+
static isJsonContentType(contentType) {
|
|
1335
|
+
return contentType.includes("application/json") || contentType.includes("+json");
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* Map an OpenAPI schema type to the corresponding Zod type.
|
|
1339
|
+
*/
|
|
1340
|
+
mapOpenApiType(schema) {
|
|
1341
|
+
if (!schema || !schema["type"]) return import_zod2.z.unknown();
|
|
1342
|
+
const type = schema["type"];
|
|
1343
|
+
const enumValues = schema["enum"];
|
|
1344
|
+
switch (type) {
|
|
1345
|
+
case "integer":
|
|
1346
|
+
return import_zod2.z.number().int();
|
|
1347
|
+
case "number":
|
|
1348
|
+
return import_zod2.z.number();
|
|
1349
|
+
case "boolean":
|
|
1350
|
+
return import_zod2.z.boolean();
|
|
1351
|
+
case "array":
|
|
1352
|
+
return import_zod2.z.array(this.mapOpenApiType(schema["items"]));
|
|
1353
|
+
case "object":
|
|
1354
|
+
return import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown());
|
|
1355
|
+
case "string":
|
|
1356
|
+
if (enumValues && enumValues.length > 0) {
|
|
1357
|
+
return import_zod2.z.enum(enumValues);
|
|
1358
|
+
}
|
|
1359
|
+
return import_zod2.z.string();
|
|
1360
|
+
default:
|
|
1361
|
+
return import_zod2.z.unknown();
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
/**
|
|
1365
|
+
* Build a Zod schema for the request body based on the media type.
|
|
1366
|
+
* Returns both the schema and the chosen media type for correct serialization.
|
|
1367
|
+
*/
|
|
1368
|
+
buildBodySchema(content) {
|
|
1369
|
+
const jsonKey = Object.keys(content).find((k) => k.includes("json"));
|
|
1370
|
+
if (jsonKey) {
|
|
1371
|
+
const schema = content[jsonKey].schema;
|
|
1372
|
+
if (schema) return { schema: this.mapOpenApiType(schema), mediaType: jsonKey };
|
|
1373
|
+
return { schema: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()), mediaType: jsonKey };
|
|
1374
|
+
}
|
|
1375
|
+
if (content["application/x-www-form-urlencoded"]) {
|
|
1376
|
+
return { schema: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()), mediaType: "application/x-www-form-urlencoded" };
|
|
1377
|
+
}
|
|
1378
|
+
if (content["multipart/form-data"]) {
|
|
1379
|
+
return { schema: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()), mediaType: "multipart/form-data" };
|
|
1380
|
+
}
|
|
1381
|
+
const textKey = Object.keys(content).find((k) => k.startsWith("text/"));
|
|
1382
|
+
if (textKey) {
|
|
1383
|
+
return { schema: import_zod2.z.string(), mediaType: textKey };
|
|
1384
|
+
}
|
|
1385
|
+
return { schema: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()), mediaType: "application/json" };
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Create a handler function for an OpenAPI operation.
|
|
1389
|
+
*/
|
|
1390
|
+
createHandler(op, baseUrl, bodyMediaType) {
|
|
1391
|
+
const auth = this.auth;
|
|
1392
|
+
const headers = this.options.headers ?? {};
|
|
1393
|
+
return async (args, context) => {
|
|
1394
|
+
const params = args;
|
|
1395
|
+
let normalizedBase = baseUrl;
|
|
1396
|
+
while (normalizedBase.endsWith("/")) normalizedBase = normalizedBase.slice(0, -1);
|
|
1397
|
+
let url = `${normalizedBase}${op.path.startsWith("/") ? op.path : "/" + op.path}`;
|
|
1398
|
+
const queryParams = {};
|
|
1399
|
+
if (op.parameters) {
|
|
1400
|
+
for (const param of op.parameters) {
|
|
1401
|
+
const value = params[param.name];
|
|
1402
|
+
if (value === void 0) continue;
|
|
1403
|
+
if (param.in === "path") {
|
|
1404
|
+
url = url.replace(`{${param.name}}`, encodeURIComponent(_OpenApiToolLoader.serializeParam(value)));
|
|
1405
|
+
} else if (param.in === "query") {
|
|
1406
|
+
queryParams[param.name] = _OpenApiToolLoader.serializeParam(value);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
const queryString = new URLSearchParams(queryParams).toString();
|
|
1411
|
+
if (queryString) {
|
|
1412
|
+
url += `?${queryString}`;
|
|
1413
|
+
}
|
|
1414
|
+
const hasBody = (["post", "put", "patch", "delete"].includes(op.method) || op.requestBody != null) && Object.prototype.hasOwnProperty.call(params, "body") && params["body"] != null;
|
|
1415
|
+
const resolvedMediaType = bodyMediaType ?? "application/json";
|
|
1416
|
+
const isMultipart = resolvedMediaType === "multipart/form-data";
|
|
1417
|
+
const requestHeaders = {
|
|
1418
|
+
// Omit Content-Type for multipart/form-data to let the runtime set the boundary
|
|
1419
|
+
...hasBody && !isMultipart && { "Content-Type": resolvedMediaType },
|
|
1420
|
+
...headers
|
|
1421
|
+
};
|
|
1422
|
+
if (auth) {
|
|
1423
|
+
switch (auth.type) {
|
|
1424
|
+
case "bearer":
|
|
1425
|
+
if (auth.token) requestHeaders["Authorization"] = `Bearer ${auth.token}`;
|
|
1426
|
+
break;
|
|
1427
|
+
case "api-key":
|
|
1428
|
+
if (auth.token) requestHeaders[auth.header ?? "X-API-Key"] = auth.token;
|
|
1429
|
+
break;
|
|
1430
|
+
case "basic":
|
|
1431
|
+
if (auth.token) requestHeaders["Authorization"] = `Basic ${auth.token}`;
|
|
1432
|
+
break;
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
const protectedHeaders = /* @__PURE__ */ new Set();
|
|
1436
|
+
if (auth) {
|
|
1437
|
+
if (auth.type === "bearer" || auth.type === "basic") protectedHeaders.add("authorization");
|
|
1438
|
+
if (auth.type === "api-key") protectedHeaders.add((auth.header ?? "X-API-Key").toLowerCase());
|
|
1439
|
+
}
|
|
1440
|
+
if (op.parameters) {
|
|
1441
|
+
for (const param of op.parameters) {
|
|
1442
|
+
if (param.in === "header" && params[param.name] !== void 0) {
|
|
1443
|
+
if (protectedHeaders.has(param.name.toLowerCase())) continue;
|
|
1444
|
+
requestHeaders[param.name] = _OpenApiToolLoader.serializeParam(params[param.name]);
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
const fetchOptions = {
|
|
1449
|
+
method: op.method.toUpperCase(),
|
|
1450
|
+
headers: requestHeaders,
|
|
1451
|
+
signal: context.signal
|
|
1452
|
+
};
|
|
1453
|
+
if (hasBody) {
|
|
1454
|
+
if (_OpenApiToolLoader.isJsonContentType(resolvedMediaType)) {
|
|
1455
|
+
fetchOptions.body = JSON.stringify(params["body"]);
|
|
1456
|
+
} else if (resolvedMediaType === "application/x-www-form-urlencoded") {
|
|
1457
|
+
fetchOptions.body = new URLSearchParams(params["body"]).toString();
|
|
1458
|
+
} else if (resolvedMediaType === "multipart/form-data") {
|
|
1459
|
+
const formData = new FormData();
|
|
1460
|
+
const bodyObj = params["body"];
|
|
1461
|
+
for (const [key, value] of Object.entries(bodyObj)) {
|
|
1462
|
+
formData.append(key, value instanceof Blob ? value : String(value));
|
|
1463
|
+
}
|
|
1464
|
+
fetchOptions.body = formData;
|
|
1465
|
+
} else if (resolvedMediaType.startsWith("text/")) {
|
|
1466
|
+
fetchOptions.body = String(params["body"]);
|
|
1467
|
+
} else {
|
|
1468
|
+
fetchOptions.body = JSON.stringify(params["body"]);
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
const response = await fetch(url, fetchOptions);
|
|
1472
|
+
if (!response.ok) {
|
|
1473
|
+
const contentType2 = response.headers.get("content-type") ?? "";
|
|
1474
|
+
let body;
|
|
1475
|
+
try {
|
|
1476
|
+
body = _OpenApiToolLoader.isJsonContentType(contentType2) ? JSON.stringify(await response.json()) : await response.text();
|
|
1477
|
+
} catch {
|
|
1478
|
+
body = "";
|
|
1479
|
+
}
|
|
1480
|
+
throw new Error(`HTTP ${response.status} ${response.statusText}: ${body}`);
|
|
1481
|
+
}
|
|
1482
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
1483
|
+
if (_OpenApiToolLoader.isJsonContentType(contentType)) {
|
|
1484
|
+
return response.json();
|
|
1485
|
+
}
|
|
1486
|
+
return response.text();
|
|
1487
|
+
};
|
|
1488
|
+
}
|
|
1489
|
+
};
|
|
1490
|
+
|
|
1491
|
+
// libs/broker/src/openapi/openapi-source.ts
|
|
1492
|
+
var OpenApiSource = class extends import_events2.EventEmitter {
|
|
1493
|
+
toolRegistry;
|
|
1494
|
+
config;
|
|
1495
|
+
poller = null;
|
|
1496
|
+
previousToolNames = /* @__PURE__ */ new Set();
|
|
1497
|
+
lastUpdate = "";
|
|
1498
|
+
specHash = "";
|
|
1499
|
+
health = "unknown";
|
|
1500
|
+
disposed = false;
|
|
1501
|
+
_syncLock = Promise.resolve();
|
|
1502
|
+
constructor(toolRegistry, config) {
|
|
1503
|
+
super();
|
|
1504
|
+
this.toolRegistry = toolRegistry;
|
|
1505
|
+
this.config = config;
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Initial load + start polling.
|
|
1509
|
+
*/
|
|
1510
|
+
async start() {
|
|
1511
|
+
if (this.disposed) throw new Error("OpenApiSource is disposed");
|
|
1512
|
+
await this.refresh();
|
|
1513
|
+
this.poller = new OpenApiSpecPoller(this.config);
|
|
1514
|
+
this.poller.on("changed", (spec) => {
|
|
1515
|
+
this._syncLock = this._syncLock.then(async () => {
|
|
1516
|
+
try {
|
|
1517
|
+
const parsed = JSON.parse(spec);
|
|
1518
|
+
await this.syncTools(parsed);
|
|
1519
|
+
this.health = "healthy";
|
|
1520
|
+
} catch (error) {
|
|
1521
|
+
this.emit("error", error instanceof Error ? error : new Error(String(error)));
|
|
1522
|
+
}
|
|
1523
|
+
});
|
|
1524
|
+
});
|
|
1525
|
+
this.poller.on("unhealthy", (failures) => {
|
|
1526
|
+
this.health = "unhealthy";
|
|
1527
|
+
this.emit("unhealthy", failures);
|
|
1528
|
+
});
|
|
1529
|
+
this.poller.on("recovered", () => {
|
|
1530
|
+
this.health = "healthy";
|
|
1531
|
+
this.emit("recovered");
|
|
1532
|
+
});
|
|
1533
|
+
this.poller.on("pollError", (error) => {
|
|
1534
|
+
this.emit("error", error);
|
|
1535
|
+
});
|
|
1536
|
+
this.poller.start();
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Stop polling.
|
|
1540
|
+
*/
|
|
1541
|
+
stop() {
|
|
1542
|
+
if (this.poller) {
|
|
1543
|
+
this.poller.stop();
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* Manual refresh (for webhook triggers).
|
|
1548
|
+
*/
|
|
1549
|
+
async refresh() {
|
|
1550
|
+
if (this.disposed) throw new Error("OpenApiSource is disposed");
|
|
1551
|
+
const loader = await OpenApiToolLoader.fromURL(
|
|
1552
|
+
this.config.url,
|
|
1553
|
+
{
|
|
1554
|
+
...this.config.loaderOptions,
|
|
1555
|
+
baseUrl: this.config.baseUrl,
|
|
1556
|
+
sourceName: this.config.name
|
|
1557
|
+
},
|
|
1558
|
+
this.config.auth
|
|
1559
|
+
);
|
|
1560
|
+
const tools = loader.getTools();
|
|
1561
|
+
const newToolNames = loader.getToolNames();
|
|
1562
|
+
const oldToolNames = this.previousToolNames;
|
|
1563
|
+
for (const tool of tools) {
|
|
1564
|
+
if (this.toolRegistry.has(tool.name)) {
|
|
1565
|
+
this.toolRegistry.replace(tool);
|
|
1566
|
+
} else {
|
|
1567
|
+
this.toolRegistry.register(tool);
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
for (const name of oldToolNames) {
|
|
1571
|
+
if (!newToolNames.has(name)) {
|
|
1572
|
+
this.toolRegistry.unregister(name);
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
this.previousToolNames = newToolNames;
|
|
1576
|
+
this.specHash = loader.getSpecHash();
|
|
1577
|
+
this.lastUpdate = (/* @__PURE__ */ new Date()).toISOString();
|
|
1578
|
+
this.health = "healthy";
|
|
1579
|
+
const added = [...newToolNames].filter((n) => !oldToolNames.has(n));
|
|
1580
|
+
const removed = [...oldToolNames].filter((n) => !newToolNames.has(n));
|
|
1581
|
+
this.emit("toolsUpdated", {
|
|
1582
|
+
added,
|
|
1583
|
+
removed,
|
|
1584
|
+
updated: [...newToolNames].filter((n) => oldToolNames.has(n))
|
|
1585
|
+
});
|
|
1586
|
+
if (added.length > 0 || removed.length > 0) {
|
|
1587
|
+
this.emit("catalogChanged", {
|
|
1588
|
+
version: this.specHash,
|
|
1589
|
+
addedActions: added,
|
|
1590
|
+
removedActions: removed
|
|
1591
|
+
});
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* Sync tools based on a new spec (diff-based update).
|
|
1596
|
+
*/
|
|
1597
|
+
async syncTools(spec) {
|
|
1598
|
+
const loader = await OpenApiToolLoader.fromSpec(
|
|
1599
|
+
spec,
|
|
1600
|
+
{
|
|
1601
|
+
...this.config.loaderOptions,
|
|
1602
|
+
baseUrl: this.config.baseUrl,
|
|
1603
|
+
sourceName: this.config.name
|
|
1604
|
+
},
|
|
1605
|
+
this.config.auth
|
|
1606
|
+
);
|
|
1607
|
+
const newTools = loader.getTools();
|
|
1608
|
+
const newToolNames = loader.getToolNames();
|
|
1609
|
+
const added = [];
|
|
1610
|
+
const removed = [];
|
|
1611
|
+
const updated = [];
|
|
1612
|
+
for (const tool of newTools) {
|
|
1613
|
+
if (this.previousToolNames.has(tool.name)) {
|
|
1614
|
+
this.toolRegistry.replace(tool);
|
|
1615
|
+
updated.push(tool.name);
|
|
1616
|
+
} else {
|
|
1617
|
+
this.toolRegistry.register(tool);
|
|
1618
|
+
added.push(tool.name);
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
for (const name of this.previousToolNames) {
|
|
1622
|
+
if (!newToolNames.has(name)) {
|
|
1623
|
+
this.toolRegistry.unregister(name);
|
|
1624
|
+
removed.push(name);
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
this.previousToolNames = newToolNames;
|
|
1628
|
+
this.specHash = loader.getSpecHash();
|
|
1629
|
+
this.lastUpdate = (/* @__PURE__ */ new Date()).toISOString();
|
|
1630
|
+
const event = { added, removed, updated };
|
|
1631
|
+
this.emit("toolsUpdated", event);
|
|
1632
|
+
if (added.length > 0 || removed.length > 0) {
|
|
1633
|
+
this.emit("catalogChanged", {
|
|
1634
|
+
version: this.specHash,
|
|
1635
|
+
addedActions: added,
|
|
1636
|
+
removedActions: removed
|
|
1637
|
+
});
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Get the set of tool names managed by this source.
|
|
1642
|
+
*/
|
|
1643
|
+
getToolNames() {
|
|
1644
|
+
return new Set(this.previousToolNames);
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Get source statistics.
|
|
1648
|
+
*/
|
|
1649
|
+
getStats() {
|
|
1650
|
+
return {
|
|
1651
|
+
toolCount: this.previousToolNames.size,
|
|
1652
|
+
lastUpdate: this.lastUpdate,
|
|
1653
|
+
specHash: this.specHash,
|
|
1654
|
+
pollHealth: this.health
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
/**
|
|
1658
|
+
* Get the source name.
|
|
1659
|
+
*/
|
|
1660
|
+
getName() {
|
|
1661
|
+
return this.config.name;
|
|
1662
|
+
}
|
|
1663
|
+
/**
|
|
1664
|
+
* Dispose the source and release resources.
|
|
1665
|
+
*/
|
|
1666
|
+
dispose() {
|
|
1667
|
+
if (this.disposed) return;
|
|
1668
|
+
this.disposed = true;
|
|
1669
|
+
this.stop();
|
|
1670
|
+
if (this.poller) {
|
|
1671
|
+
this.poller.dispose();
|
|
1672
|
+
this.poller = null;
|
|
1673
|
+
}
|
|
1674
|
+
this.removeAllListeners();
|
|
1675
|
+
}
|
|
1676
|
+
};
|
|
1677
|
+
|
|
709
1678
|
// libs/broker/src/broker.ts
|
|
710
1679
|
var Broker = class {
|
|
711
1680
|
toolRegistry;
|
|
712
1681
|
sessionManager;
|
|
713
1682
|
config;
|
|
1683
|
+
openApiSources = [];
|
|
714
1684
|
disposed = false;
|
|
715
1685
|
constructor(config = {}) {
|
|
716
1686
|
this.config = config;
|
|
@@ -781,6 +1751,40 @@ var Broker = class {
|
|
|
781
1751
|
return this.toolRegistry.unregister(name);
|
|
782
1752
|
}
|
|
783
1753
|
// ============================================================================
|
|
1754
|
+
// OpenAPI Sources
|
|
1755
|
+
// ============================================================================
|
|
1756
|
+
/**
|
|
1757
|
+
* Register an OpenAPI source for automatic tool generation and polling.
|
|
1758
|
+
*
|
|
1759
|
+
* @param config - OpenAPI source configuration
|
|
1760
|
+
* @returns The created OpenApiSource instance
|
|
1761
|
+
*
|
|
1762
|
+
* @example
|
|
1763
|
+
* ```typescript
|
|
1764
|
+
* const source = broker.openapi({
|
|
1765
|
+
* name: 'user-service',
|
|
1766
|
+
* url: 'https://api.example.com/openapi.json',
|
|
1767
|
+
* baseUrl: 'https://api.example.com',
|
|
1768
|
+
* intervalMs: 60000,
|
|
1769
|
+
* auth: { type: 'bearer', token: process.env.API_TOKEN },
|
|
1770
|
+
* });
|
|
1771
|
+
*
|
|
1772
|
+
* await source.start();
|
|
1773
|
+
* ```
|
|
1774
|
+
*/
|
|
1775
|
+
openapi(config) {
|
|
1776
|
+
this.ensureNotDisposed();
|
|
1777
|
+
const source = new OpenApiSource(this.toolRegistry, config);
|
|
1778
|
+
this.openApiSources.push(source);
|
|
1779
|
+
return source;
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* Get all registered OpenAPI sources.
|
|
1783
|
+
*/
|
|
1784
|
+
getOpenApiSources() {
|
|
1785
|
+
return this.openApiSources;
|
|
1786
|
+
}
|
|
1787
|
+
// ============================================================================
|
|
784
1788
|
// Secret Management
|
|
785
1789
|
// ============================================================================
|
|
786
1790
|
/**
|
|
@@ -928,6 +1932,10 @@ var Broker = class {
|
|
|
928
1932
|
return;
|
|
929
1933
|
}
|
|
930
1934
|
this.disposed = true;
|
|
1935
|
+
for (const source of this.openApiSources) {
|
|
1936
|
+
source.dispose();
|
|
1937
|
+
}
|
|
1938
|
+
this.openApiSources.length = 0;
|
|
931
1939
|
await this.sessionManager.dispose();
|
|
932
1940
|
this.toolRegistry.clear();
|
|
933
1941
|
this.toolRegistry.clearSecrets();
|
|
@@ -1590,11 +2598,80 @@ function registerExpressRoutes(router, handler) {
|
|
|
1590
2598
|
router[method](route.path, expressHandler);
|
|
1591
2599
|
}
|
|
1592
2600
|
}
|
|
2601
|
+
|
|
2602
|
+
// libs/broker/src/openapi/catalog-handler.ts
|
|
2603
|
+
var CatalogHandler = class {
|
|
2604
|
+
toolRegistry;
|
|
2605
|
+
sources;
|
|
2606
|
+
constructor(toolRegistry, sources) {
|
|
2607
|
+
this.toolRegistry = toolRegistry;
|
|
2608
|
+
this.sources = sources;
|
|
2609
|
+
}
|
|
2610
|
+
/**
|
|
2611
|
+
* Get route definitions for the catalog endpoint.
|
|
2612
|
+
*/
|
|
2613
|
+
getRoutes() {
|
|
2614
|
+
return [
|
|
2615
|
+
{
|
|
2616
|
+
method: "GET",
|
|
2617
|
+
path: "/code/actions",
|
|
2618
|
+
handler: this.handleGetActions.bind(this)
|
|
2619
|
+
}
|
|
2620
|
+
];
|
|
2621
|
+
}
|
|
2622
|
+
/**
|
|
2623
|
+
* Handle GET /code/actions request.
|
|
2624
|
+
*/
|
|
2625
|
+
async handleGetActions(_req, res) {
|
|
2626
|
+
const catalog = this.buildCatalog();
|
|
2627
|
+
res.status(200);
|
|
2628
|
+
res.json(catalog);
|
|
2629
|
+
}
|
|
2630
|
+
/**
|
|
2631
|
+
* Build the full catalog response.
|
|
2632
|
+
*/
|
|
2633
|
+
buildCatalog() {
|
|
2634
|
+
const actions = [];
|
|
2635
|
+
const services = [];
|
|
2636
|
+
const toolToService = /* @__PURE__ */ new Map();
|
|
2637
|
+
for (const source of this.sources) {
|
|
2638
|
+
const stats = source.getStats();
|
|
2639
|
+
const serviceName = source.getName();
|
|
2640
|
+
services.push({
|
|
2641
|
+
name: serviceName,
|
|
2642
|
+
specUrl: "",
|
|
2643
|
+
// URL is internal to the source
|
|
2644
|
+
lastUpdated: stats.lastUpdate,
|
|
2645
|
+
actionCount: stats.toolCount
|
|
2646
|
+
});
|
|
2647
|
+
for (const toolName of source.getToolNames()) {
|
|
2648
|
+
toolToService.set(toolName, serviceName);
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
const toolNames = this.toolRegistry.list();
|
|
2652
|
+
for (const name of toolNames) {
|
|
2653
|
+
const tool = this.toolRegistry.get(name);
|
|
2654
|
+
if (!tool) continue;
|
|
2655
|
+
actions.push({
|
|
2656
|
+
name: tool.name,
|
|
2657
|
+
description: tool.description,
|
|
2658
|
+
service: toolToService.get(name) ?? "default"
|
|
2659
|
+
});
|
|
2660
|
+
}
|
|
2661
|
+
const versionParts = this.sources.map((s) => s.getStats().specHash).sort().join(":");
|
|
2662
|
+
const version = versionParts || "empty";
|
|
2663
|
+
return { actions, services, version };
|
|
2664
|
+
}
|
|
2665
|
+
};
|
|
1593
2666
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1594
2667
|
0 && (module.exports = {
|
|
1595
2668
|
Broker,
|
|
1596
2669
|
BrokerSession,
|
|
2670
|
+
CatalogHandler,
|
|
1597
2671
|
EventFilter,
|
|
2672
|
+
OpenApiSource,
|
|
2673
|
+
OpenApiSpecPoller,
|
|
2674
|
+
OpenApiToolLoader,
|
|
1598
2675
|
SessionHandler,
|
|
1599
2676
|
SessionManager,
|
|
1600
2677
|
ToolRegistry,
|