ai.matey.core 0.2.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/LICENSE +21 -0
- package/dist/cjs/bridge.js +657 -0
- package/dist/cjs/bridge.js.map +1 -0
- package/dist/cjs/capability-inference.js +349 -0
- package/dist/cjs/capability-inference.js.map +1 -0
- package/dist/cjs/capability-matcher.js +216 -0
- package/dist/cjs/capability-matcher.js.map +1 -0
- package/dist/cjs/index.js +31 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/middleware-stack.js +256 -0
- package/dist/cjs/middleware-stack.js.map +1 -0
- package/dist/cjs/model-pricing.js +350 -0
- package/dist/cjs/model-pricing.js.map +1 -0
- package/dist/cjs/model-translation.js +171 -0
- package/dist/cjs/model-translation.js.map +1 -0
- package/dist/cjs/router.js +1388 -0
- package/dist/cjs/router.js.map +1 -0
- package/dist/esm/bridge.js +652 -0
- package/dist/esm/bridge.js.map +1 -0
- package/dist/esm/capability-inference.js +343 -0
- package/dist/esm/capability-inference.js.map +1 -0
- package/dist/esm/capability-matcher.js +210 -0
- package/dist/esm/capability-matcher.js.map +1 -0
- package/dist/esm/index.js +15 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/middleware-stack.js +250 -0
- package/dist/esm/middleware-stack.js.map +1 -0
- package/dist/esm/model-pricing.js +340 -0
- package/dist/esm/model-pricing.js.map +1 -0
- package/dist/esm/model-translation.js +163 -0
- package/dist/esm/model-translation.js.map +1 -0
- package/dist/esm/router.js +1383 -0
- package/dist/esm/router.js.map +1 -0
- package/dist/types/bridge.d.ts +254 -0
- package/dist/types/bridge.d.ts.map +1 -0
- package/dist/types/capability-inference.d.ts +35 -0
- package/dist/types/capability-inference.d.ts.map +1 -0
- package/dist/types/capability-matcher.d.ts +104 -0
- package/dist/types/capability-matcher.d.ts.map +1 -0
- package/dist/types/index.d.ts +15 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/middleware-stack.d.ts +102 -0
- package/dist/types/middleware-stack.d.ts.map +1 -0
- package/dist/types/model-pricing.d.ts +81 -0
- package/dist/types/model-pricing.d.ts.map +1 -0
- package/dist/types/model-translation.d.ts +171 -0
- package/dist/types/model-translation.d.ts.map +1 -0
- package/dist/types/router.d.ts +287 -0
- package/dist/types/router.d.ts.map +1 -0
- package/package.json +70 -0
- package/readme.md +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 AI Matey Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Bridge Implementation
|
|
4
|
+
*
|
|
5
|
+
* The Bridge connects frontend and backend adapters with middleware support.
|
|
6
|
+
* It's the main entry point for making requests through the universal adapter system.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.Bridge = void 0;
|
|
12
|
+
exports.createBridge = createBridge;
|
|
13
|
+
const ai_matey_types_1 = require("ai.matey.types");
|
|
14
|
+
const middleware_stack_js_1 = require("./middleware-stack.js");
|
|
15
|
+
const ai_matey_errors_1 = require("ai.matey.errors");
|
|
16
|
+
const ai_matey_utils_1 = require("ai.matey.utils");
|
|
17
|
+
// ============================================================================
|
|
18
|
+
// Bridge Implementation
|
|
19
|
+
// ============================================================================
|
|
20
|
+
/**
|
|
21
|
+
* Bridge connects frontend and backend adapters.
|
|
22
|
+
*
|
|
23
|
+
* @template TFrontend Frontend adapter type
|
|
24
|
+
*/
|
|
25
|
+
class Bridge {
|
|
26
|
+
frontend;
|
|
27
|
+
backend;
|
|
28
|
+
config;
|
|
29
|
+
middlewareStack;
|
|
30
|
+
// Statistics tracking
|
|
31
|
+
_totalRequests = 0;
|
|
32
|
+
_successfulRequests = 0;
|
|
33
|
+
_failedRequests = 0;
|
|
34
|
+
_streamingRequests = 0;
|
|
35
|
+
_latencies = [];
|
|
36
|
+
static MAX_LATENCY_SAMPLES = 1000; // Prevent unbounded memory growth
|
|
37
|
+
_errorCounts = {};
|
|
38
|
+
_statsResetTimestamp = Date.now();
|
|
39
|
+
// Event listeners (stored for future event emission)
|
|
40
|
+
_eventListeners = new Map();
|
|
41
|
+
/**
|
|
42
|
+
* Create a new Bridge instance.
|
|
43
|
+
*
|
|
44
|
+
* @param frontend Frontend adapter
|
|
45
|
+
* @param backend Backend adapter
|
|
46
|
+
* @param config Bridge configuration
|
|
47
|
+
*/
|
|
48
|
+
constructor(frontend, backend, config = {}) {
|
|
49
|
+
this.frontend = frontend;
|
|
50
|
+
this.backend = backend;
|
|
51
|
+
this.config = {
|
|
52
|
+
debug: config.debug ?? false,
|
|
53
|
+
timeout: config.timeout ?? 30000,
|
|
54
|
+
retries: config.retries ?? 0,
|
|
55
|
+
autoRequestId: config.autoRequestId ?? true,
|
|
56
|
+
defaultModel: config.defaultModel,
|
|
57
|
+
routerConfig: config.routerConfig,
|
|
58
|
+
custom: config.custom,
|
|
59
|
+
};
|
|
60
|
+
this.middlewareStack = new middleware_stack_js_1.MiddlewareStack();
|
|
61
|
+
}
|
|
62
|
+
// ==========================================================================
|
|
63
|
+
// Core Request Methods
|
|
64
|
+
// ==========================================================================
|
|
65
|
+
/**
|
|
66
|
+
* Execute a non-streaming chat completion request.
|
|
67
|
+
*/
|
|
68
|
+
async chat(request, options) {
|
|
69
|
+
const startTime = Date.now();
|
|
70
|
+
this._totalRequests++;
|
|
71
|
+
// Step 1: Convert frontend request to IR
|
|
72
|
+
const irRequest = await this.frontend.toIR(request);
|
|
73
|
+
// Step 2: Ensure metadata has requestId and timestamp
|
|
74
|
+
const enrichedRequest = this.enrichRequest(irRequest, options);
|
|
75
|
+
// Emit REQUEST_START event
|
|
76
|
+
this.emit({
|
|
77
|
+
type: ai_matey_types_1.BridgeEventType.REQUEST_START,
|
|
78
|
+
timestamp: Date.now(),
|
|
79
|
+
requestId: enrichedRequest.metadata.requestId,
|
|
80
|
+
request: enrichedRequest,
|
|
81
|
+
});
|
|
82
|
+
const maxAttempts = (this.config.retries ?? 0) + 1;
|
|
83
|
+
let lastError;
|
|
84
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
85
|
+
try {
|
|
86
|
+
// Step 3: Validate IR request
|
|
87
|
+
(0, ai_matey_utils_1.validateIRChatRequest)(enrichedRequest, {
|
|
88
|
+
frontend: this.frontend.metadata.name,
|
|
89
|
+
});
|
|
90
|
+
// Step 4: Create middleware context
|
|
91
|
+
const context = (0, middleware_stack_js_1.createMiddlewareContext)(enrichedRequest, this.config, options?.signal);
|
|
92
|
+
// Step 5: Execute middleware stack + backend
|
|
93
|
+
const irResponse = await this.middlewareStack.execute(context, async () => {
|
|
94
|
+
// Call backend adapter
|
|
95
|
+
return await this.backend.execute(enrichedRequest, options?.signal);
|
|
96
|
+
});
|
|
97
|
+
// Step 6: Enrich response with provenance
|
|
98
|
+
const enrichedResponse = this.enrichResponse(irResponse, enrichedRequest);
|
|
99
|
+
// Step 7: Convert IR response to frontend format
|
|
100
|
+
const frontendResponse = await this.frontend.fromIR(enrichedResponse);
|
|
101
|
+
// Track success
|
|
102
|
+
this._successfulRequests++;
|
|
103
|
+
const durationMs = Date.now() - startTime;
|
|
104
|
+
this.recordLatency(durationMs);
|
|
105
|
+
// Emit REQUEST_SUCCESS event
|
|
106
|
+
this.emit({
|
|
107
|
+
type: ai_matey_types_1.BridgeEventType.REQUEST_SUCCESS,
|
|
108
|
+
timestamp: Date.now(),
|
|
109
|
+
requestId: enrichedRequest.metadata.requestId,
|
|
110
|
+
request: enrichedRequest,
|
|
111
|
+
response: enrichedResponse,
|
|
112
|
+
durationMs,
|
|
113
|
+
});
|
|
114
|
+
return frontendResponse;
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
118
|
+
// Don't retry on non-retryable errors or if this is the last attempt
|
|
119
|
+
const isRetryable = error instanceof ai_matey_errors_1.AdapterError ? error.isRetryable : true;
|
|
120
|
+
if (!isRetryable || attempt >= maxAttempts) {
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
// Wait before retrying (simple exponential backoff)
|
|
124
|
+
await this.delay(Math.min(1000 * Math.pow(2, attempt - 1), 10000));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// Track failure
|
|
128
|
+
this._failedRequests++;
|
|
129
|
+
const errorCode = lastError instanceof ai_matey_errors_1.AdapterError ? lastError.code : 'UNKNOWN';
|
|
130
|
+
this._errorCounts[errorCode] = (this._errorCounts[errorCode] ?? 0) + 1;
|
|
131
|
+
// Emit REQUEST_ERROR event
|
|
132
|
+
this.emit({
|
|
133
|
+
type: ai_matey_types_1.BridgeEventType.REQUEST_ERROR,
|
|
134
|
+
timestamp: Date.now(),
|
|
135
|
+
requestId: enrichedRequest.metadata.requestId,
|
|
136
|
+
request: enrichedRequest,
|
|
137
|
+
error: lastError,
|
|
138
|
+
durationMs: Date.now() - startTime,
|
|
139
|
+
});
|
|
140
|
+
// Re-throw adapter errors, wrap others
|
|
141
|
+
// lastError is guaranteed to be defined here (we only reach this point if all retries failed)
|
|
142
|
+
if (!lastError) {
|
|
143
|
+
throw new Error('Bridge execution failed with no error information');
|
|
144
|
+
}
|
|
145
|
+
if (lastError instanceof ai_matey_errors_1.AdapterError) {
|
|
146
|
+
throw lastError;
|
|
147
|
+
}
|
|
148
|
+
throw new ai_matey_errors_1.AdapterError({
|
|
149
|
+
code: ai_matey_errors_1.ErrorCode.INTERNAL_ERROR,
|
|
150
|
+
message: `Bridge execution failed: ${lastError.message}`,
|
|
151
|
+
isRetryable: false,
|
|
152
|
+
cause: lastError,
|
|
153
|
+
provenance: {},
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Execute a streaming chat completion request.
|
|
158
|
+
*/
|
|
159
|
+
async *chatStream(request, options) {
|
|
160
|
+
const startTime = Date.now();
|
|
161
|
+
this._totalRequests++;
|
|
162
|
+
this._streamingRequests++;
|
|
163
|
+
// Step 1: Convert frontend request to IR
|
|
164
|
+
const irRequest = await this.frontend.toIR(request);
|
|
165
|
+
// Step 2: Ensure streaming is enabled
|
|
166
|
+
const streamingRequest = {
|
|
167
|
+
...irRequest,
|
|
168
|
+
stream: true,
|
|
169
|
+
};
|
|
170
|
+
// Step 3: Ensure metadata has requestId and timestamp
|
|
171
|
+
const enrichedRequest = this.enrichRequest(streamingRequest, options);
|
|
172
|
+
// Emit STREAM_START event
|
|
173
|
+
this.emit({
|
|
174
|
+
type: ai_matey_types_1.BridgeEventType.STREAM_START,
|
|
175
|
+
timestamp: Date.now(),
|
|
176
|
+
requestId: enrichedRequest.metadata.requestId,
|
|
177
|
+
request: enrichedRequest,
|
|
178
|
+
});
|
|
179
|
+
try {
|
|
180
|
+
// Step 4: Validate IR request
|
|
181
|
+
(0, ai_matey_utils_1.validateIRChatRequest)(enrichedRequest, {
|
|
182
|
+
frontend: this.frontend.metadata.name,
|
|
183
|
+
});
|
|
184
|
+
// Step 5: Create streaming middleware context
|
|
185
|
+
const context = (0, middleware_stack_js_1.createStreamingMiddlewareContext)(enrichedRequest, this.config, options?.signal);
|
|
186
|
+
// Step 6: Execute middleware stack + backend
|
|
187
|
+
const irStream = await this.middlewareStack.executeStream(context, async () => {
|
|
188
|
+
// Call backend adapter streaming
|
|
189
|
+
return this.backend.executeStream(enrichedRequest, options?.signal);
|
|
190
|
+
});
|
|
191
|
+
// Step 7: Convert IR stream to frontend format
|
|
192
|
+
const frontendStream = this.frontend.fromIRStream(irStream);
|
|
193
|
+
// Step 8: Yield chunks to caller
|
|
194
|
+
let chunkSequence = 0;
|
|
195
|
+
for await (const chunk of frontendStream) {
|
|
196
|
+
chunkSequence++;
|
|
197
|
+
yield chunk;
|
|
198
|
+
}
|
|
199
|
+
// Track success (after stream completes)
|
|
200
|
+
this._successfulRequests++;
|
|
201
|
+
const durationMs = Date.now() - startTime;
|
|
202
|
+
this.recordLatency(durationMs);
|
|
203
|
+
// Emit STREAM_COMPLETE event
|
|
204
|
+
this.emit({
|
|
205
|
+
type: ai_matey_types_1.BridgeEventType.STREAM_COMPLETE,
|
|
206
|
+
timestamp: Date.now(),
|
|
207
|
+
requestId: enrichedRequest.metadata.requestId,
|
|
208
|
+
request: enrichedRequest,
|
|
209
|
+
chunkSequence,
|
|
210
|
+
durationMs,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
// Track failure
|
|
215
|
+
this._failedRequests++;
|
|
216
|
+
const errorCode = error instanceof ai_matey_errors_1.AdapterError ? error.code : 'UNKNOWN';
|
|
217
|
+
this._errorCounts[errorCode] = (this._errorCounts[errorCode] ?? 0) + 1;
|
|
218
|
+
// Emit STREAM_ERROR event
|
|
219
|
+
this.emit({
|
|
220
|
+
type: ai_matey_types_1.BridgeEventType.STREAM_ERROR,
|
|
221
|
+
timestamp: Date.now(),
|
|
222
|
+
requestId: enrichedRequest.metadata.requestId,
|
|
223
|
+
request: enrichedRequest,
|
|
224
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
225
|
+
durationMs: Date.now() - startTime,
|
|
226
|
+
});
|
|
227
|
+
// Re-throw adapter errors, wrap others
|
|
228
|
+
if (error instanceof ai_matey_errors_1.AdapterError) {
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
throw new ai_matey_errors_1.AdapterError({
|
|
232
|
+
code: ai_matey_errors_1.ErrorCode.INTERNAL_ERROR,
|
|
233
|
+
message: `Bridge streaming failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
234
|
+
isRetryable: false,
|
|
235
|
+
cause: error instanceof Error ? error : undefined,
|
|
236
|
+
provenance: {},
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// ==========================================================================
|
|
241
|
+
// Model Listing
|
|
242
|
+
// ==========================================================================
|
|
243
|
+
/**
|
|
244
|
+
* List available models from the backend.
|
|
245
|
+
*
|
|
246
|
+
* This delegates directly to the backend adapter's listModels() method.
|
|
247
|
+
* Useful for discovering available models before making requests.
|
|
248
|
+
*
|
|
249
|
+
* @param options Options for listing models (filtering, cache control)
|
|
250
|
+
* @returns List of available models, or null if backend doesn't support listing
|
|
251
|
+
*/
|
|
252
|
+
async listModels(options) {
|
|
253
|
+
if (!this.backend.listModels) {
|
|
254
|
+
return null; // Backend doesn't support model listing
|
|
255
|
+
}
|
|
256
|
+
return await this.backend.listModels(options);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Check if a specific model is available from the backend.
|
|
260
|
+
*
|
|
261
|
+
* @param modelId Model identifier to check
|
|
262
|
+
* @returns true if model is available, false otherwise
|
|
263
|
+
*/
|
|
264
|
+
async hasModel(modelId) {
|
|
265
|
+
const result = await this.listModels();
|
|
266
|
+
if (!result) {
|
|
267
|
+
return true;
|
|
268
|
+
} // Can't check, assume available
|
|
269
|
+
return result.models.some((m) => m.id === modelId);
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Validate that a model is available (optional safety check).
|
|
273
|
+
*
|
|
274
|
+
* Note: This is an optional validation - the system doesn't automatically
|
|
275
|
+
* validate models since cross-provider translation is supported.
|
|
276
|
+
*
|
|
277
|
+
* @param modelId Model identifier to validate
|
|
278
|
+
* @throws {ValidationError} If model is not available
|
|
279
|
+
*/
|
|
280
|
+
async validateModel(modelId) {
|
|
281
|
+
const available = await this.hasModel(modelId);
|
|
282
|
+
if (!available) {
|
|
283
|
+
throw new ai_matey_errors_1.ValidationError({
|
|
284
|
+
code: ai_matey_errors_1.ErrorCode.UNSUPPORTED_MODEL,
|
|
285
|
+
message: `Model "${modelId}" is not available from backend "${this.backend.metadata.name}"`,
|
|
286
|
+
validationDetails: [
|
|
287
|
+
{
|
|
288
|
+
field: 'model',
|
|
289
|
+
value: modelId,
|
|
290
|
+
reason: `Model not available from backend "${this.backend.metadata.name}"`,
|
|
291
|
+
expected: 'Available model ID from backend',
|
|
292
|
+
},
|
|
293
|
+
],
|
|
294
|
+
provenance: {
|
|
295
|
+
frontend: this.frontend.metadata.name,
|
|
296
|
+
backend: this.backend.metadata.name,
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// ==========================================================================
|
|
302
|
+
// Middleware Management
|
|
303
|
+
// ==========================================================================
|
|
304
|
+
/**
|
|
305
|
+
* Add middleware to the bridge's middleware stack.
|
|
306
|
+
*/
|
|
307
|
+
use(middleware) {
|
|
308
|
+
this.middlewareStack.use(middleware);
|
|
309
|
+
return this;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Remove middleware from the stack.
|
|
313
|
+
*
|
|
314
|
+
* @param middleware Middleware to remove
|
|
315
|
+
* @returns This bridge for chaining
|
|
316
|
+
*/
|
|
317
|
+
removeMiddleware(middleware) {
|
|
318
|
+
this.middlewareStack.remove(middleware);
|
|
319
|
+
return this;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Clear all middleware from the stack.
|
|
323
|
+
*/
|
|
324
|
+
clearMiddleware() {
|
|
325
|
+
this.middlewareStack.clear();
|
|
326
|
+
return this;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Get all middleware in the stack.
|
|
330
|
+
*/
|
|
331
|
+
getMiddleware() {
|
|
332
|
+
return this.middlewareStack.getMiddleware();
|
|
333
|
+
}
|
|
334
|
+
// ==========================================================================
|
|
335
|
+
// Event Handling
|
|
336
|
+
// ==========================================================================
|
|
337
|
+
/**
|
|
338
|
+
* Register an event listener.
|
|
339
|
+
*
|
|
340
|
+
* Note: Event emission is not yet implemented. Listeners are stored
|
|
341
|
+
* for future use when event emission is added.
|
|
342
|
+
*
|
|
343
|
+
* @param event Event type to listen for, or '*' for all events
|
|
344
|
+
* @param listener Callback function
|
|
345
|
+
*/
|
|
346
|
+
on(event, listener) {
|
|
347
|
+
const key = event;
|
|
348
|
+
if (!this._eventListeners.has(key)) {
|
|
349
|
+
this._eventListeners.set(key, new Set());
|
|
350
|
+
}
|
|
351
|
+
this._eventListeners.get(key).add(listener);
|
|
352
|
+
return this;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Remove an event listener.
|
|
356
|
+
*
|
|
357
|
+
* @param event Event type
|
|
358
|
+
* @param listener Callback function to remove
|
|
359
|
+
*/
|
|
360
|
+
off(event, listener) {
|
|
361
|
+
const key = event;
|
|
362
|
+
const listeners = this._eventListeners.get(key);
|
|
363
|
+
if (listeners) {
|
|
364
|
+
listeners.delete(listener);
|
|
365
|
+
}
|
|
366
|
+
return this;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Register a one-time event listener.
|
|
370
|
+
*
|
|
371
|
+
* Note: Event emission is not yet implemented. Listeners are stored
|
|
372
|
+
* for future use when event emission is added.
|
|
373
|
+
*
|
|
374
|
+
* @param event Event type to listen for
|
|
375
|
+
* @param listener Callback function
|
|
376
|
+
*/
|
|
377
|
+
once(event, listener) {
|
|
378
|
+
const wrappedListener = (eventData) => {
|
|
379
|
+
this.off(event, wrappedListener);
|
|
380
|
+
return listener(eventData);
|
|
381
|
+
};
|
|
382
|
+
return this.on(event, wrappedListener);
|
|
383
|
+
}
|
|
384
|
+
// ==========================================================================
|
|
385
|
+
// Statistics & Monitoring
|
|
386
|
+
// ==========================================================================
|
|
387
|
+
/**
|
|
388
|
+
* Get runtime statistics for this bridge.
|
|
389
|
+
*
|
|
390
|
+
* @returns Bridge statistics including request counts, latencies, and error breakdown
|
|
391
|
+
*/
|
|
392
|
+
getStats() {
|
|
393
|
+
const sortedLatencies = [...this._latencies].sort((a, b) => a - b);
|
|
394
|
+
const len = sortedLatencies.length;
|
|
395
|
+
const getPercentile = (p) => {
|
|
396
|
+
if (len === 0) {
|
|
397
|
+
return 0;
|
|
398
|
+
}
|
|
399
|
+
const index = Math.ceil((p / 100) * len) - 1;
|
|
400
|
+
return sortedLatencies[Math.max(0, Math.min(index, len - 1))] ?? 0;
|
|
401
|
+
};
|
|
402
|
+
const avgLatency = len > 0 ? sortedLatencies.reduce((a, b) => a + b, 0) / len : 0;
|
|
403
|
+
return {
|
|
404
|
+
totalRequests: this._totalRequests,
|
|
405
|
+
successfulRequests: this._successfulRequests,
|
|
406
|
+
failedRequests: this._failedRequests,
|
|
407
|
+
successRate: this._totalRequests > 0 ? (this._successfulRequests / this._totalRequests) * 100 : 100,
|
|
408
|
+
streamingRequests: this._streamingRequests,
|
|
409
|
+
averageLatencyMs: Math.round(avgLatency),
|
|
410
|
+
p50LatencyMs: getPercentile(50),
|
|
411
|
+
p95LatencyMs: getPercentile(95),
|
|
412
|
+
p99LatencyMs: getPercentile(99),
|
|
413
|
+
backendUsage: {
|
|
414
|
+
[this.backend.metadata.name]: this._successfulRequests,
|
|
415
|
+
},
|
|
416
|
+
errorBreakdown: { ...this._errorCounts },
|
|
417
|
+
sinceTimestamp: this._statsResetTimestamp,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Reset all statistics to zero.
|
|
422
|
+
*/
|
|
423
|
+
resetStats() {
|
|
424
|
+
this._totalRequests = 0;
|
|
425
|
+
this._successfulRequests = 0;
|
|
426
|
+
this._failedRequests = 0;
|
|
427
|
+
this._streamingRequests = 0;
|
|
428
|
+
this._latencies = [];
|
|
429
|
+
this._errorCounts = {};
|
|
430
|
+
this._statsResetTimestamp = Date.now();
|
|
431
|
+
}
|
|
432
|
+
// ==========================================================================
|
|
433
|
+
// Utility Methods
|
|
434
|
+
// ==========================================================================
|
|
435
|
+
/**
|
|
436
|
+
* Get router instance (returns null for basic Bridge).
|
|
437
|
+
*/
|
|
438
|
+
getRouter() {
|
|
439
|
+
return null;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Check health of the backend.
|
|
443
|
+
*
|
|
444
|
+
* @returns true if backend is healthy, false otherwise
|
|
445
|
+
*/
|
|
446
|
+
async checkHealth() {
|
|
447
|
+
if (this.backend.healthCheck) {
|
|
448
|
+
return await this.backend.healthCheck();
|
|
449
|
+
}
|
|
450
|
+
return true; // Assume healthy if no health check is available
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Get a copy of the bridge configuration.
|
|
454
|
+
*
|
|
455
|
+
* @returns Readonly copy of the bridge configuration
|
|
456
|
+
*/
|
|
457
|
+
getConfig() {
|
|
458
|
+
return { ...this.config };
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Clone bridge with new configuration.
|
|
462
|
+
*/
|
|
463
|
+
clone(config) {
|
|
464
|
+
return new Bridge(this.frontend, this.backend, {
|
|
465
|
+
...this.config,
|
|
466
|
+
...config,
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Clean up resources.
|
|
471
|
+
*/
|
|
472
|
+
dispose() {
|
|
473
|
+
// Cleanup logic if needed
|
|
474
|
+
}
|
|
475
|
+
// ==========================================================================
|
|
476
|
+
// Private Helper Methods
|
|
477
|
+
// ==========================================================================
|
|
478
|
+
/**
|
|
479
|
+
* Enrich request with metadata (requestId, timestamp, provenance) and apply defaults.
|
|
480
|
+
*/
|
|
481
|
+
enrichRequest(request, options) {
|
|
482
|
+
// Always generate requestId if missing (frontend adapters should provide it)
|
|
483
|
+
const requestId = request.metadata?.requestId || this.generateRequestId();
|
|
484
|
+
const timestamp = request.metadata?.timestamp ?? Date.now();
|
|
485
|
+
// Apply default model if not specified in request
|
|
486
|
+
const model = request.parameters?.model ?? this.config.defaultModel;
|
|
487
|
+
return {
|
|
488
|
+
...request,
|
|
489
|
+
parameters: {
|
|
490
|
+
...request.parameters,
|
|
491
|
+
...(model && { model }),
|
|
492
|
+
},
|
|
493
|
+
metadata: {
|
|
494
|
+
...request.metadata,
|
|
495
|
+
requestId,
|
|
496
|
+
timestamp,
|
|
497
|
+
provenance: {
|
|
498
|
+
...request.metadata?.provenance,
|
|
499
|
+
frontend: this.frontend.metadata.name,
|
|
500
|
+
},
|
|
501
|
+
custom: {
|
|
502
|
+
...request.metadata?.custom,
|
|
503
|
+
...options?.metadata,
|
|
504
|
+
},
|
|
505
|
+
},
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Enrich response with provenance and timing.
|
|
510
|
+
*/
|
|
511
|
+
enrichResponse(response, request) {
|
|
512
|
+
return {
|
|
513
|
+
...response,
|
|
514
|
+
metadata: {
|
|
515
|
+
...response.metadata,
|
|
516
|
+
requestId: request.metadata.requestId,
|
|
517
|
+
provenance: {
|
|
518
|
+
...response.metadata.provenance,
|
|
519
|
+
frontend: this.frontend.metadata.name,
|
|
520
|
+
backend: this.backend.metadata.name,
|
|
521
|
+
},
|
|
522
|
+
},
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Generate unique request ID.
|
|
527
|
+
*/
|
|
528
|
+
generateRequestId() {
|
|
529
|
+
// Use standard UUID v4 for request IDs
|
|
530
|
+
return crypto.randomUUID();
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Generate a structured object matching a Zod schema using an LLM.
|
|
534
|
+
*
|
|
535
|
+
* This method uses tool calling to extract structured data from the LLM response,
|
|
536
|
+
* validates it against the provided schema, and returns the typed object.
|
|
537
|
+
*
|
|
538
|
+
* @param options Configuration for object generation
|
|
539
|
+
* @returns Promise resolving to the generated and validated object
|
|
540
|
+
*
|
|
541
|
+
* @example
|
|
542
|
+
* ```typescript
|
|
543
|
+
* const UserSchema = z.object({
|
|
544
|
+
* name: z.string(),
|
|
545
|
+
* age: z.number(),
|
|
546
|
+
* email: z.string().email(),
|
|
547
|
+
* });
|
|
548
|
+
*
|
|
549
|
+
* const result = await bridge.generateObject({
|
|
550
|
+
* schema: UserSchema,
|
|
551
|
+
* prompt: 'Generate a user profile for Alice, age 30',
|
|
552
|
+
* model: 'gpt-4',
|
|
553
|
+
* });
|
|
554
|
+
*
|
|
555
|
+
* console.log(result.object); // { name: 'Alice', age: 30, email: '...' }
|
|
556
|
+
* ```
|
|
557
|
+
*/
|
|
558
|
+
generateObject = (0, ai_matey_utils_1.createGenerateObject)(this);
|
|
559
|
+
/**
|
|
560
|
+
* Stream a structured object matching a Zod schema using an LLM.
|
|
561
|
+
*
|
|
562
|
+
* This method uses streaming tool calling to incrementally build up a structured
|
|
563
|
+
* object, yielding partial results as they become available.
|
|
564
|
+
*
|
|
565
|
+
* @param options Configuration for streaming object generation
|
|
566
|
+
* @returns Async generator yielding partial objects and returning the final validated object
|
|
567
|
+
*
|
|
568
|
+
* @example
|
|
569
|
+
* ```typescript
|
|
570
|
+
* const ArticleSchema = z.object({
|
|
571
|
+
* title: z.string(),
|
|
572
|
+
* content: z.string(),
|
|
573
|
+
* tags: z.array(z.string()),
|
|
574
|
+
* });
|
|
575
|
+
*
|
|
576
|
+
* const stream = bridge.streamObject({
|
|
577
|
+
* schema: ArticleSchema,
|
|
578
|
+
* prompt: 'Write a blog post about TypeScript',
|
|
579
|
+
* onPartial: (partial) => {
|
|
580
|
+
* console.log('Partial:', partial);
|
|
581
|
+
* },
|
|
582
|
+
* });
|
|
583
|
+
*
|
|
584
|
+
* for await (const partial of stream) {
|
|
585
|
+
* console.log('Progress:', partial);
|
|
586
|
+
* }
|
|
587
|
+
* ```
|
|
588
|
+
*/
|
|
589
|
+
streamObject = (0, ai_matey_utils_1.createStreamObject)(this);
|
|
590
|
+
/**
|
|
591
|
+
* Emit an event to all registered listeners.
|
|
592
|
+
*
|
|
593
|
+
* @param event Event data to emit
|
|
594
|
+
*/
|
|
595
|
+
emit(event) {
|
|
596
|
+
// Emit to specific event type listeners
|
|
597
|
+
const specificListeners = this._eventListeners.get(event.type);
|
|
598
|
+
if (specificListeners) {
|
|
599
|
+
for (const listener of specificListeners) {
|
|
600
|
+
try {
|
|
601
|
+
void listener(event);
|
|
602
|
+
}
|
|
603
|
+
catch {
|
|
604
|
+
// Ignore listener errors to prevent breaking the chain
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
// Emit to wildcard listeners
|
|
609
|
+
const wildcardListeners = this._eventListeners.get('*');
|
|
610
|
+
if (wildcardListeners) {
|
|
611
|
+
for (const listener of wildcardListeners) {
|
|
612
|
+
try {
|
|
613
|
+
void listener(event);
|
|
614
|
+
}
|
|
615
|
+
catch {
|
|
616
|
+
// Ignore listener errors to prevent breaking the chain
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Record a latency sample, maintaining a rolling window to prevent unbounded memory growth.
|
|
623
|
+
*
|
|
624
|
+
* @param latencyMs Latency in milliseconds
|
|
625
|
+
*/
|
|
626
|
+
recordLatency(latencyMs) {
|
|
627
|
+
this._latencies.push(latencyMs);
|
|
628
|
+
// Maintain rolling window to prevent memory leak in long-running applications
|
|
629
|
+
if (this._latencies.length > Bridge.MAX_LATENCY_SAMPLES) {
|
|
630
|
+
this._latencies.shift();
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Delay execution for a specified number of milliseconds.
|
|
635
|
+
*
|
|
636
|
+
* @param ms Milliseconds to delay
|
|
637
|
+
*/
|
|
638
|
+
delay(ms) {
|
|
639
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
exports.Bridge = Bridge;
|
|
643
|
+
// ============================================================================
|
|
644
|
+
// Factory Functions
|
|
645
|
+
// ============================================================================
|
|
646
|
+
/**
|
|
647
|
+
* Create a new Bridge instance.
|
|
648
|
+
*
|
|
649
|
+
* @param frontend Frontend adapter
|
|
650
|
+
* @param backend Backend adapter
|
|
651
|
+
* @param config Bridge configuration
|
|
652
|
+
* @returns Bridge instance
|
|
653
|
+
*/
|
|
654
|
+
function createBridge(frontend, backend, config) {
|
|
655
|
+
return new Bridge(frontend, backend, config);
|
|
656
|
+
}
|
|
657
|
+
//# sourceMappingURL=bridge.js.map
|