@enclave-vm/broker 0.0.1 → 2.8.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/README.md +202 -0
- package/esm/index.mjs +1569 -0
- package/esm/package.json +6 -0
- package/index.js +1611 -0
- package/package.json +12 -11
- package/src/broker-session.js +0 -312
- package/src/broker-session.js.map +0 -1
- package/src/broker.js +0 -290
- package/src/broker.js.map +0 -1
- package/src/event-filter.js +0 -305
- package/src/event-filter.js.map +0 -1
- package/src/http/express-adapter.js +0 -172
- package/src/http/express-adapter.js.map +0 -1
- package/src/http/index.js +0 -14
- package/src/http/index.js.map +0 -1
- package/src/http/session-handler.js +0 -351
- package/src/http/session-handler.js.map +0 -1
- package/src/http/types.js +0 -10
- package/src/http/types.js.map +0 -1
- package/src/index.js +0 -39
- package/src/index.js.map +0 -1
- package/src/session-manager.js +0 -203
- package/src/session-manager.js.map +0 -1
- package/src/tool-registry.js +0 -240
- package/src/tool-registry.js.map +0 -1
- /package/{src/broker-session.d.ts → broker-session.d.ts} +0 -0
- /package/{src/broker.d.ts → broker.d.ts} +0 -0
- /package/{src/event-filter.d.ts → event-filter.d.ts} +0 -0
- /package/{src/http → http}/express-adapter.d.ts +0 -0
- /package/{src/http → http}/index.d.ts +0 -0
- /package/{src/http → http}/session-handler.d.ts +0 -0
- /package/{src/http → http}/types.d.ts +0 -0
- /package/{src/index.d.ts → index.d.ts} +0 -0
- /package/{src/session-manager.d.ts → session-manager.d.ts} +0 -0
- /package/{src/tool-registry.d.ts → tool-registry.d.ts} +0 -0
package/index.js
ADDED
|
@@ -0,0 +1,1611 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// libs/enclavejs-broker/src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
Broker: () => Broker,
|
|
24
|
+
BrokerSession: () => BrokerSession,
|
|
25
|
+
EventFilter: () => EventFilter,
|
|
26
|
+
SessionHandler: () => SessionHandler,
|
|
27
|
+
SessionManager: () => SessionManager,
|
|
28
|
+
ToolRegistry: () => ToolRegistry,
|
|
29
|
+
createBroker: () => createBroker,
|
|
30
|
+
createBrokerSession: () => createBrokerSession,
|
|
31
|
+
createContentFilter: () => createContentFilter,
|
|
32
|
+
createEventFilter: () => createEventFilter,
|
|
33
|
+
createExpressRouter: () => createExpressRouter,
|
|
34
|
+
createSessionHandler: () => createSessionHandler,
|
|
35
|
+
createSessionManager: () => createSessionManager,
|
|
36
|
+
createToolRegistry: () => createToolRegistry,
|
|
37
|
+
createTypeFilter: () => createTypeFilter,
|
|
38
|
+
registerExpressRoutes: () => registerExpressRoutes
|
|
39
|
+
});
|
|
40
|
+
module.exports = __toCommonJS(index_exports);
|
|
41
|
+
|
|
42
|
+
// libs/enclavejs-broker/src/tool-registry.ts
|
|
43
|
+
var import_zod = require("zod");
|
|
44
|
+
var ToolRegistry = class {
|
|
45
|
+
tools;
|
|
46
|
+
secretStore;
|
|
47
|
+
constructor() {
|
|
48
|
+
this.tools = /* @__PURE__ */ new Map();
|
|
49
|
+
this.secretStore = /* @__PURE__ */ new Map();
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Register a tool
|
|
53
|
+
*
|
|
54
|
+
* @throws Error if tool with same name already exists
|
|
55
|
+
*/
|
|
56
|
+
register(definition) {
|
|
57
|
+
if (this.tools.has(definition.name)) {
|
|
58
|
+
throw new Error(`Tool "${definition.name}" is already registered`);
|
|
59
|
+
}
|
|
60
|
+
const argsSchema = definition.argsSchema ?? import_zod.z.record(import_zod.z.string(), import_zod.z.unknown());
|
|
61
|
+
this.tools.set(definition.name, {
|
|
62
|
+
definition,
|
|
63
|
+
argsSchema
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Unregister a tool
|
|
68
|
+
*
|
|
69
|
+
* @returns true if tool was removed, false if not found
|
|
70
|
+
*/
|
|
71
|
+
unregister(name) {
|
|
72
|
+
return this.tools.delete(name);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Check if a tool is registered
|
|
76
|
+
*/
|
|
77
|
+
has(name) {
|
|
78
|
+
return this.tools.has(name);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Get a tool definition
|
|
82
|
+
*/
|
|
83
|
+
get(name) {
|
|
84
|
+
return this.tools.get(name)?.definition;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* List all registered tool names
|
|
88
|
+
*/
|
|
89
|
+
list() {
|
|
90
|
+
return Array.from(this.tools.keys());
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Get tool configurations for all registered tools
|
|
94
|
+
*/
|
|
95
|
+
getConfigs() {
|
|
96
|
+
const configs = {};
|
|
97
|
+
for (const [name, tool] of this.tools) {
|
|
98
|
+
if (tool.definition.config) {
|
|
99
|
+
configs[name] = tool.definition.config;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return configs;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Validate tool arguments
|
|
106
|
+
*/
|
|
107
|
+
validate(name, args) {
|
|
108
|
+
const tool = this.tools.get(name);
|
|
109
|
+
if (!tool) {
|
|
110
|
+
return {
|
|
111
|
+
success: false,
|
|
112
|
+
error: `Unknown tool: ${name}`
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
const result = tool.argsSchema.safeParse(args);
|
|
116
|
+
if (!result.success) {
|
|
117
|
+
return {
|
|
118
|
+
success: false,
|
|
119
|
+
error: `Invalid arguments: ${result.error.message}`
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
success: true,
|
|
124
|
+
validatedArgs: result.data
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Set a secret value
|
|
129
|
+
*/
|
|
130
|
+
setSecret(key, value) {
|
|
131
|
+
this.secretStore.set(key, value);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Remove a secret
|
|
135
|
+
*/
|
|
136
|
+
removeSecret(key) {
|
|
137
|
+
return this.secretStore.delete(key);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Check if a secret exists
|
|
141
|
+
*/
|
|
142
|
+
hasSecret(key) {
|
|
143
|
+
return this.secretStore.has(key);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Get required secrets for a tool
|
|
147
|
+
*/
|
|
148
|
+
getRequiredSecrets(name) {
|
|
149
|
+
const tool = this.tools.get(name);
|
|
150
|
+
return tool?.definition.secrets ?? [];
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Resolve secrets for a tool
|
|
154
|
+
*
|
|
155
|
+
* @throws Error if required secret is missing
|
|
156
|
+
*/
|
|
157
|
+
resolveSecrets(name) {
|
|
158
|
+
const requiredSecrets = this.getRequiredSecrets(name);
|
|
159
|
+
const resolved = {};
|
|
160
|
+
for (const key of requiredSecrets) {
|
|
161
|
+
const value = this.secretStore.get(key);
|
|
162
|
+
if (value === void 0) {
|
|
163
|
+
throw new Error(`Missing required secret "${key}" for tool "${name}"`);
|
|
164
|
+
}
|
|
165
|
+
resolved[key] = value;
|
|
166
|
+
}
|
|
167
|
+
return resolved;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Execute a tool
|
|
171
|
+
*/
|
|
172
|
+
async execute(name, args, context) {
|
|
173
|
+
const startTime = Date.now();
|
|
174
|
+
const tool = this.tools.get(name);
|
|
175
|
+
if (!tool) {
|
|
176
|
+
return {
|
|
177
|
+
success: false,
|
|
178
|
+
error: {
|
|
179
|
+
code: "UNKNOWN_TOOL",
|
|
180
|
+
message: `Unknown tool: ${name}`
|
|
181
|
+
},
|
|
182
|
+
durationMs: Date.now() - startTime
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const validation = this.validate(name, args);
|
|
186
|
+
if (!validation.success) {
|
|
187
|
+
return {
|
|
188
|
+
success: false,
|
|
189
|
+
error: {
|
|
190
|
+
code: "VALIDATION_ERROR",
|
|
191
|
+
message: validation.error
|
|
192
|
+
},
|
|
193
|
+
durationMs: Date.now() - startTime
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
let secrets;
|
|
197
|
+
try {
|
|
198
|
+
secrets = this.resolveSecrets(name);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
return {
|
|
201
|
+
success: false,
|
|
202
|
+
error: {
|
|
203
|
+
code: "SECRET_ERROR",
|
|
204
|
+
message: error instanceof Error ? error.message : "Failed to resolve secrets"
|
|
205
|
+
},
|
|
206
|
+
durationMs: Date.now() - startTime
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
const result = await tool.definition.handler(validation.validatedArgs, {
|
|
211
|
+
...context,
|
|
212
|
+
secrets
|
|
213
|
+
});
|
|
214
|
+
return {
|
|
215
|
+
success: true,
|
|
216
|
+
value: result,
|
|
217
|
+
durationMs: Date.now() - startTime
|
|
218
|
+
};
|
|
219
|
+
} catch (error) {
|
|
220
|
+
const err = error;
|
|
221
|
+
return {
|
|
222
|
+
success: false,
|
|
223
|
+
error: {
|
|
224
|
+
code: err.code ?? "EXECUTION_ERROR",
|
|
225
|
+
message: err.message
|
|
226
|
+
},
|
|
227
|
+
durationMs: Date.now() - startTime
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Clear all registered tools
|
|
233
|
+
*/
|
|
234
|
+
clear() {
|
|
235
|
+
this.tools.clear();
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Clear all secrets
|
|
239
|
+
*/
|
|
240
|
+
clearSecrets() {
|
|
241
|
+
this.secretStore.clear();
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Get count of registered tools
|
|
245
|
+
*/
|
|
246
|
+
get size() {
|
|
247
|
+
return this.tools.size;
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
function createToolRegistry() {
|
|
251
|
+
return new ToolRegistry();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// libs/enclavejs-broker/src/broker-session.ts
|
|
255
|
+
var import_types = require("@enclave-vm/types");
|
|
256
|
+
var import_core = require("@enclave-vm/core");
|
|
257
|
+
var BrokerSession = class {
|
|
258
|
+
sessionId;
|
|
259
|
+
createdAt;
|
|
260
|
+
expiresAt;
|
|
261
|
+
emitter;
|
|
262
|
+
toolRegistry;
|
|
263
|
+
enclave;
|
|
264
|
+
abortController;
|
|
265
|
+
limits;
|
|
266
|
+
_state = "starting";
|
|
267
|
+
executionPromise = null;
|
|
268
|
+
toolCallCount = 0;
|
|
269
|
+
stdoutBytes = 0;
|
|
270
|
+
heartbeatInterval = null;
|
|
271
|
+
constructor(toolRegistry, config = {}) {
|
|
272
|
+
this.sessionId = config.sessionId ?? (0, import_types.generateSessionId)();
|
|
273
|
+
this.createdAt = Date.now();
|
|
274
|
+
this.toolRegistry = toolRegistry;
|
|
275
|
+
this.abortController = new AbortController();
|
|
276
|
+
this.limits = {
|
|
277
|
+
...import_types.DEFAULT_SESSION_LIMITS,
|
|
278
|
+
...config.limits
|
|
279
|
+
};
|
|
280
|
+
this.expiresAt = this.createdAt + this.limits.sessionTtlMs;
|
|
281
|
+
this.emitter = (0, import_core.createSessionEmitter)(this.sessionId, {
|
|
282
|
+
expiresAt: new Date(this.expiresAt)
|
|
283
|
+
});
|
|
284
|
+
this.enclave = new import_core.Enclave({
|
|
285
|
+
...config.enclaveConfig,
|
|
286
|
+
timeout: this.limits.toolTimeoutMs,
|
|
287
|
+
maxToolCalls: this.limits.maxToolCalls
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Get current session state
|
|
292
|
+
*/
|
|
293
|
+
get state() {
|
|
294
|
+
return this._state;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Get current sequence number
|
|
298
|
+
*/
|
|
299
|
+
get seq() {
|
|
300
|
+
return this.emitter.getSeq();
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Get the event emitter
|
|
304
|
+
*/
|
|
305
|
+
get events() {
|
|
306
|
+
return this.emitter;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Subscribe to stream events
|
|
310
|
+
*/
|
|
311
|
+
onEvent(handler) {
|
|
312
|
+
return this.emitter.on(handler);
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Get all emitted events
|
|
316
|
+
*/
|
|
317
|
+
getEvents() {
|
|
318
|
+
return this.emitter.getEmittedEvents();
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Execute code in this session
|
|
322
|
+
*
|
|
323
|
+
* @param code - Code to execute
|
|
324
|
+
* @returns Promise that resolves when execution completes
|
|
325
|
+
*/
|
|
326
|
+
async execute(code) {
|
|
327
|
+
if (this.executionPromise) {
|
|
328
|
+
throw new Error("Session is already executing");
|
|
329
|
+
}
|
|
330
|
+
this.emitter.emitSessionInit();
|
|
331
|
+
const heartbeatMs = this.limits.heartbeatIntervalMs;
|
|
332
|
+
if (heartbeatMs > 0) {
|
|
333
|
+
this.heartbeatInterval = setInterval(() => {
|
|
334
|
+
if (!this.isTerminal()) {
|
|
335
|
+
this.emitter.emitHeartbeat();
|
|
336
|
+
}
|
|
337
|
+
}, heartbeatMs);
|
|
338
|
+
}
|
|
339
|
+
this._state = "running";
|
|
340
|
+
this.executionPromise = this.runExecution(code);
|
|
341
|
+
return this.executionPromise;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Run the actual execution
|
|
345
|
+
*/
|
|
346
|
+
async runExecution(code) {
|
|
347
|
+
const startTime = Date.now();
|
|
348
|
+
let result;
|
|
349
|
+
try {
|
|
350
|
+
const enclaveResult = await this.enclave.run(code, async (toolName, args) => {
|
|
351
|
+
if (this.abortController.signal.aborted) {
|
|
352
|
+
throw new Error("Session cancelled");
|
|
353
|
+
}
|
|
354
|
+
return this.executeTool(toolName, args);
|
|
355
|
+
});
|
|
356
|
+
const endTime = Date.now();
|
|
357
|
+
const stats = this.buildStats(startTime, endTime);
|
|
358
|
+
if (enclaveResult.success) {
|
|
359
|
+
this._state = "completed";
|
|
360
|
+
this.emitter.emitFinalSuccess(enclaveResult.value, {
|
|
361
|
+
durationMs: stats.duration,
|
|
362
|
+
toolCallCount: this.toolCallCount,
|
|
363
|
+
stdoutBytes: this.stdoutBytes
|
|
364
|
+
});
|
|
365
|
+
result = {
|
|
366
|
+
success: true,
|
|
367
|
+
value: enclaveResult.value,
|
|
368
|
+
stats,
|
|
369
|
+
finalState: "completed"
|
|
370
|
+
};
|
|
371
|
+
} else {
|
|
372
|
+
this._state = "failed";
|
|
373
|
+
const errorInfo = {
|
|
374
|
+
code: enclaveResult.error?.code ?? "EXECUTION_ERROR",
|
|
375
|
+
message: enclaveResult.error?.message ?? "Execution failed"
|
|
376
|
+
};
|
|
377
|
+
this.emitter.emitFinalError(errorInfo, {
|
|
378
|
+
durationMs: stats.duration,
|
|
379
|
+
toolCallCount: this.toolCallCount,
|
|
380
|
+
stdoutBytes: this.stdoutBytes
|
|
381
|
+
});
|
|
382
|
+
result = {
|
|
383
|
+
success: false,
|
|
384
|
+
error: {
|
|
385
|
+
message: errorInfo.message,
|
|
386
|
+
name: enclaveResult.error?.name ?? "Error",
|
|
387
|
+
code: errorInfo.code
|
|
388
|
+
},
|
|
389
|
+
stats,
|
|
390
|
+
finalState: "failed"
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
} catch (error) {
|
|
394
|
+
const endTime = Date.now();
|
|
395
|
+
const stats = this.buildStats(startTime, endTime);
|
|
396
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
397
|
+
this._state = "failed";
|
|
398
|
+
const errorInfo = {
|
|
399
|
+
code: err.code ?? "EXECUTION_ERROR",
|
|
400
|
+
message: err.message
|
|
401
|
+
};
|
|
402
|
+
this.emitter.emitFinalError(errorInfo, {
|
|
403
|
+
durationMs: stats.duration,
|
|
404
|
+
toolCallCount: this.toolCallCount,
|
|
405
|
+
stdoutBytes: this.stdoutBytes
|
|
406
|
+
});
|
|
407
|
+
result = {
|
|
408
|
+
success: false,
|
|
409
|
+
error: {
|
|
410
|
+
message: err.message,
|
|
411
|
+
name: err.name,
|
|
412
|
+
code: errorInfo.code
|
|
413
|
+
},
|
|
414
|
+
stats,
|
|
415
|
+
finalState: "failed"
|
|
416
|
+
};
|
|
417
|
+
} finally {
|
|
418
|
+
this.stopHeartbeat();
|
|
419
|
+
}
|
|
420
|
+
return result;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Execute a tool call directly
|
|
424
|
+
*/
|
|
425
|
+
async executeTool(toolName, args) {
|
|
426
|
+
const callId = (0, import_types.generateCallId)();
|
|
427
|
+
this.emitter.emitToolCall(callId, toolName, args);
|
|
428
|
+
this.toolCallCount++;
|
|
429
|
+
const context = {
|
|
430
|
+
sessionId: this.sessionId,
|
|
431
|
+
callId,
|
|
432
|
+
secrets: {},
|
|
433
|
+
// Resolved by registry
|
|
434
|
+
signal: this.abortController.signal
|
|
435
|
+
};
|
|
436
|
+
const result = await this.toolRegistry.execute(toolName, args, context);
|
|
437
|
+
this.emitter.emitToolResultApplied(callId);
|
|
438
|
+
if (result.success) {
|
|
439
|
+
return result.value;
|
|
440
|
+
} else {
|
|
441
|
+
const error = new Error(result.error?.message ?? "Tool call failed");
|
|
442
|
+
error.code = result.error?.code;
|
|
443
|
+
throw error;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Build execution stats
|
|
448
|
+
*/
|
|
449
|
+
buildStats(startTime, endTime) {
|
|
450
|
+
return {
|
|
451
|
+
duration: endTime - startTime,
|
|
452
|
+
toolCallCount: this.toolCallCount,
|
|
453
|
+
iterationCount: 0,
|
|
454
|
+
startTime,
|
|
455
|
+
endTime
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Cancel the session
|
|
460
|
+
*/
|
|
461
|
+
async cancel(reason) {
|
|
462
|
+
if (this.isTerminal()) {
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
this.stopHeartbeat();
|
|
466
|
+
this.abortController.abort();
|
|
467
|
+
this._state = "cancelled";
|
|
468
|
+
this.emitter.emitError("SESSION_CANCELLED", reason ?? "Session was cancelled", false);
|
|
469
|
+
this.emitter.emitFinalError(
|
|
470
|
+
{ code: "SESSION_CANCELLED", message: reason ?? "Session was cancelled" },
|
|
471
|
+
{
|
|
472
|
+
durationMs: Date.now() - this.createdAt,
|
|
473
|
+
toolCallCount: this.toolCallCount,
|
|
474
|
+
stdoutBytes: this.stdoutBytes
|
|
475
|
+
}
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Wait for the session to complete
|
|
480
|
+
*/
|
|
481
|
+
async wait() {
|
|
482
|
+
if (this.executionPromise) {
|
|
483
|
+
return this.executionPromise;
|
|
484
|
+
}
|
|
485
|
+
throw new Error("Session has not started execution");
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Check if session is expired
|
|
489
|
+
*/
|
|
490
|
+
isExpired() {
|
|
491
|
+
return Date.now() > this.expiresAt;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Check if session is in terminal state
|
|
495
|
+
*/
|
|
496
|
+
isTerminal() {
|
|
497
|
+
return this._state === "completed" || this._state === "cancelled" || this._state === "failed";
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Get session statistics
|
|
501
|
+
*/
|
|
502
|
+
getStats() {
|
|
503
|
+
const now = Date.now();
|
|
504
|
+
return {
|
|
505
|
+
duration: this.isTerminal() ? now - this.createdAt : now - this.createdAt,
|
|
506
|
+
toolCallCount: this.toolCallCount,
|
|
507
|
+
iterationCount: 0,
|
|
508
|
+
startTime: this.createdAt,
|
|
509
|
+
endTime: this.isTerminal() ? now : 0
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Stop heartbeat timer
|
|
514
|
+
*/
|
|
515
|
+
stopHeartbeat() {
|
|
516
|
+
if (this.heartbeatInterval) {
|
|
517
|
+
clearInterval(this.heartbeatInterval);
|
|
518
|
+
this.heartbeatInterval = null;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Dispose of the session and its resources
|
|
523
|
+
*/
|
|
524
|
+
dispose() {
|
|
525
|
+
this.stopHeartbeat();
|
|
526
|
+
this.abortController.abort();
|
|
527
|
+
this.enclave.dispose();
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
function createBrokerSession(toolRegistry, config) {
|
|
531
|
+
return new BrokerSession(toolRegistry, config);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// libs/enclavejs-broker/src/session-manager.ts
|
|
535
|
+
var SessionManager = class {
|
|
536
|
+
sessions;
|
|
537
|
+
toolRegistry;
|
|
538
|
+
config;
|
|
539
|
+
cleanupInterval = null;
|
|
540
|
+
disposed = false;
|
|
541
|
+
constructor(toolRegistry, config = {}) {
|
|
542
|
+
this.sessions = /* @__PURE__ */ new Map();
|
|
543
|
+
this.toolRegistry = toolRegistry;
|
|
544
|
+
this.config = {
|
|
545
|
+
maxSessions: config.maxSessions ?? 100,
|
|
546
|
+
cleanupIntervalMs: config.cleanupIntervalMs ?? 6e4,
|
|
547
|
+
defaultSessionConfig: config.defaultSessionConfig ?? {}
|
|
548
|
+
};
|
|
549
|
+
this.startCleanup();
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Create a new session
|
|
553
|
+
*
|
|
554
|
+
* @throws Error if max sessions reached or manager is disposed
|
|
555
|
+
*/
|
|
556
|
+
create(config) {
|
|
557
|
+
if (this.disposed) {
|
|
558
|
+
throw new Error("Session manager is disposed");
|
|
559
|
+
}
|
|
560
|
+
if (this.sessions.size >= this.config.maxSessions) {
|
|
561
|
+
throw new Error(
|
|
562
|
+
`Maximum sessions reached (${this.config.maxSessions}). Wait for existing sessions to complete or increase maxSessions.`
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
const sessionConfig = {
|
|
566
|
+
...this.config.defaultSessionConfig,
|
|
567
|
+
...config
|
|
568
|
+
};
|
|
569
|
+
const session = createBrokerSession(this.toolRegistry, sessionConfig);
|
|
570
|
+
this.sessions.set(session.sessionId, session);
|
|
571
|
+
return {
|
|
572
|
+
session,
|
|
573
|
+
sessionId: session.sessionId
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Get a session by ID
|
|
578
|
+
*/
|
|
579
|
+
get(sessionId) {
|
|
580
|
+
return this.sessions.get(sessionId);
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Check if a session exists
|
|
584
|
+
*/
|
|
585
|
+
has(sessionId) {
|
|
586
|
+
return this.sessions.has(sessionId);
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* List all sessions
|
|
590
|
+
*/
|
|
591
|
+
list() {
|
|
592
|
+
return Array.from(this.sessions.values()).map((session) => ({
|
|
593
|
+
sessionId: session.sessionId,
|
|
594
|
+
state: session.state,
|
|
595
|
+
createdAt: session.createdAt,
|
|
596
|
+
expiresAt: session.expiresAt,
|
|
597
|
+
isExpired: session.isExpired()
|
|
598
|
+
}));
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* List active (non-terminal) sessions
|
|
602
|
+
*/
|
|
603
|
+
listActive() {
|
|
604
|
+
return this.list().filter((info) => !["completed", "cancelled", "failed"].includes(info.state));
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Terminate a session
|
|
608
|
+
*/
|
|
609
|
+
async terminate(sessionId, reason) {
|
|
610
|
+
const session = this.sessions.get(sessionId);
|
|
611
|
+
if (!session) {
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
await session.cancel(reason ?? "Terminated by session manager");
|
|
615
|
+
session.dispose();
|
|
616
|
+
this.sessions.delete(sessionId);
|
|
617
|
+
return true;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Execute code in a new session and wait for completion
|
|
621
|
+
*
|
|
622
|
+
* This is a convenience method that creates a session, executes code,
|
|
623
|
+
* waits for completion, and cleans up.
|
|
624
|
+
*/
|
|
625
|
+
async executeAndWait(code, config, eventHandler) {
|
|
626
|
+
const { session, sessionId } = this.create(config);
|
|
627
|
+
try {
|
|
628
|
+
if (eventHandler) {
|
|
629
|
+
session.onEvent(eventHandler);
|
|
630
|
+
}
|
|
631
|
+
const result = await session.execute(code);
|
|
632
|
+
return result;
|
|
633
|
+
} finally {
|
|
634
|
+
session.dispose();
|
|
635
|
+
this.sessions.delete(sessionId);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Get count of active sessions
|
|
640
|
+
*/
|
|
641
|
+
get activeCount() {
|
|
642
|
+
return this.listActive().length;
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Get total session count
|
|
646
|
+
*/
|
|
647
|
+
get totalCount() {
|
|
648
|
+
return this.sessions.size;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Clean up expired and terminal sessions
|
|
652
|
+
*/
|
|
653
|
+
cleanup() {
|
|
654
|
+
let cleaned = 0;
|
|
655
|
+
for (const [sessionId, session] of this.sessions) {
|
|
656
|
+
if (session.isExpired() || session.isTerminal()) {
|
|
657
|
+
session.dispose();
|
|
658
|
+
this.sessions.delete(sessionId);
|
|
659
|
+
cleaned++;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return cleaned;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Start automatic cleanup
|
|
666
|
+
*/
|
|
667
|
+
startCleanup() {
|
|
668
|
+
if (this.cleanupInterval) {
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
this.cleanupInterval = setInterval(() => {
|
|
672
|
+
this.cleanup();
|
|
673
|
+
}, this.config.cleanupIntervalMs);
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Stop automatic cleanup
|
|
677
|
+
*/
|
|
678
|
+
stopCleanup() {
|
|
679
|
+
if (this.cleanupInterval) {
|
|
680
|
+
clearInterval(this.cleanupInterval);
|
|
681
|
+
this.cleanupInterval = null;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Dispose of the manager and all sessions
|
|
686
|
+
*/
|
|
687
|
+
async dispose() {
|
|
688
|
+
if (this.disposed) {
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
this.disposed = true;
|
|
692
|
+
this.stopCleanup();
|
|
693
|
+
const promises = [];
|
|
694
|
+
for (const [_sessionId, session] of this.sessions) {
|
|
695
|
+
promises.push(
|
|
696
|
+
session.cancel("Session manager disposed").catch(() => {
|
|
697
|
+
})
|
|
698
|
+
);
|
|
699
|
+
session.dispose();
|
|
700
|
+
}
|
|
701
|
+
await Promise.all(promises);
|
|
702
|
+
this.sessions.clear();
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
function createSessionManager(toolRegistry, config) {
|
|
706
|
+
return new SessionManager(toolRegistry, config);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// libs/enclavejs-broker/src/broker.ts
|
|
710
|
+
var Broker = class {
|
|
711
|
+
toolRegistry;
|
|
712
|
+
sessionManager;
|
|
713
|
+
config;
|
|
714
|
+
disposed = false;
|
|
715
|
+
constructor(config = {}) {
|
|
716
|
+
this.config = config;
|
|
717
|
+
this.toolRegistry = createToolRegistry();
|
|
718
|
+
this.sessionManager = createSessionManager(this.toolRegistry, {
|
|
719
|
+
...config.sessions,
|
|
720
|
+
defaultSessionConfig: {
|
|
721
|
+
limits: config.limits,
|
|
722
|
+
enclaveConfig: config.enclave
|
|
723
|
+
}
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
// ============================================================================
|
|
727
|
+
// Tool Registration
|
|
728
|
+
// ============================================================================
|
|
729
|
+
/**
|
|
730
|
+
* Register a tool with the broker
|
|
731
|
+
*
|
|
732
|
+
* @param name - Tool name
|
|
733
|
+
* @param definition - Tool definition (handler, schema, secrets)
|
|
734
|
+
*
|
|
735
|
+
* @example
|
|
736
|
+
* ```typescript
|
|
737
|
+
* broker.tool('fetchUrl', {
|
|
738
|
+
* argsSchema: z.object({ url: z.string().url() }),
|
|
739
|
+
* secrets: ['API_KEY'],
|
|
740
|
+
* handler: async ({ url }, { secrets }) => {
|
|
741
|
+
* const response = await fetch(url, {
|
|
742
|
+
* headers: { Authorization: secrets.API_KEY },
|
|
743
|
+
* });
|
|
744
|
+
* return response.json();
|
|
745
|
+
* },
|
|
746
|
+
* });
|
|
747
|
+
* ```
|
|
748
|
+
*/
|
|
749
|
+
tool(name, definition) {
|
|
750
|
+
this.toolRegistry.register({
|
|
751
|
+
name,
|
|
752
|
+
...definition
|
|
753
|
+
});
|
|
754
|
+
return this;
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Register multiple tools at once
|
|
758
|
+
*/
|
|
759
|
+
tools(definitions) {
|
|
760
|
+
for (const [name, def] of Object.entries(definitions)) {
|
|
761
|
+
this.tool(name, def);
|
|
762
|
+
}
|
|
763
|
+
return this;
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Check if a tool is registered
|
|
767
|
+
*/
|
|
768
|
+
hasTool(name) {
|
|
769
|
+
return this.toolRegistry.has(name);
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* List all registered tool names
|
|
773
|
+
*/
|
|
774
|
+
listTools() {
|
|
775
|
+
return this.toolRegistry.list();
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Unregister a tool
|
|
779
|
+
*/
|
|
780
|
+
removeTool(name) {
|
|
781
|
+
return this.toolRegistry.unregister(name);
|
|
782
|
+
}
|
|
783
|
+
// ============================================================================
|
|
784
|
+
// Secret Management
|
|
785
|
+
// ============================================================================
|
|
786
|
+
/**
|
|
787
|
+
* Set a secret value
|
|
788
|
+
*
|
|
789
|
+
* @param key - Secret key
|
|
790
|
+
* @param value - Secret value
|
|
791
|
+
*
|
|
792
|
+
* @example
|
|
793
|
+
* ```typescript
|
|
794
|
+
* broker.secret('API_KEY', process.env.API_KEY!);
|
|
795
|
+
* broker.secret('DATABASE_URL', process.env.DATABASE_URL!);
|
|
796
|
+
* ```
|
|
797
|
+
*/
|
|
798
|
+
secret(key, value) {
|
|
799
|
+
this.toolRegistry.setSecret(key, value);
|
|
800
|
+
return this;
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Set multiple secrets at once
|
|
804
|
+
*/
|
|
805
|
+
secrets(values) {
|
|
806
|
+
for (const [key, value] of Object.entries(values)) {
|
|
807
|
+
this.secret(key, value);
|
|
808
|
+
}
|
|
809
|
+
return this;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Check if a secret exists
|
|
813
|
+
*/
|
|
814
|
+
hasSecret(key) {
|
|
815
|
+
return this.toolRegistry.hasSecret(key);
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Remove a secret
|
|
819
|
+
*/
|
|
820
|
+
removeSecret(key) {
|
|
821
|
+
return this.toolRegistry.removeSecret(key);
|
|
822
|
+
}
|
|
823
|
+
// ============================================================================
|
|
824
|
+
// Session Management
|
|
825
|
+
// ============================================================================
|
|
826
|
+
/**
|
|
827
|
+
* Create a new session
|
|
828
|
+
*
|
|
829
|
+
* @param config - Session configuration
|
|
830
|
+
* @returns The created session
|
|
831
|
+
*
|
|
832
|
+
* @example
|
|
833
|
+
* ```typescript
|
|
834
|
+
* const session = broker.createSession({
|
|
835
|
+
* limits: { sessionTtlMs: 60000 },
|
|
836
|
+
* });
|
|
837
|
+
*
|
|
838
|
+
* session.onEvent((event) => {
|
|
839
|
+
* console.log('Event:', event.type);
|
|
840
|
+
* });
|
|
841
|
+
*
|
|
842
|
+
* const result = await session.execute('return await callTool("greet", { name: "World" })');
|
|
843
|
+
* ```
|
|
844
|
+
*/
|
|
845
|
+
createSession(config) {
|
|
846
|
+
this.ensureNotDisposed();
|
|
847
|
+
return this.sessionManager.create(config).session;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Get a session by ID
|
|
851
|
+
*/
|
|
852
|
+
getSession(sessionId) {
|
|
853
|
+
return this.sessionManager.get(sessionId);
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* List all sessions
|
|
857
|
+
*/
|
|
858
|
+
listSessions() {
|
|
859
|
+
return this.sessionManager.list();
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* List active (non-terminal) sessions
|
|
863
|
+
*/
|
|
864
|
+
listActiveSessions() {
|
|
865
|
+
return this.sessionManager.listActive();
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* Terminate a session
|
|
869
|
+
*/
|
|
870
|
+
async terminateSession(sessionId, reason) {
|
|
871
|
+
return this.sessionManager.terminate(sessionId, reason);
|
|
872
|
+
}
|
|
873
|
+
// ============================================================================
|
|
874
|
+
// Quick Execution
|
|
875
|
+
// ============================================================================
|
|
876
|
+
/**
|
|
877
|
+
* Execute code and wait for result
|
|
878
|
+
*
|
|
879
|
+
* This is a convenience method that creates a session, executes code,
|
|
880
|
+
* streams events, and returns the final result.
|
|
881
|
+
*
|
|
882
|
+
* @param code - Code to execute
|
|
883
|
+
* @param options - Execution options
|
|
884
|
+
* @returns Final execution result
|
|
885
|
+
*
|
|
886
|
+
* @example
|
|
887
|
+
* ```typescript
|
|
888
|
+
* const result = await broker.execute(`
|
|
889
|
+
* const data = await callTool('fetchData', { id: 123 });
|
|
890
|
+
* return data.processed;
|
|
891
|
+
* `, {
|
|
892
|
+
* onEvent: (event) => console.log(event.type),
|
|
893
|
+
* });
|
|
894
|
+
*
|
|
895
|
+
* if (result.success) {
|
|
896
|
+
* console.log('Result:', result.value);
|
|
897
|
+
* }
|
|
898
|
+
* ```
|
|
899
|
+
*/
|
|
900
|
+
async execute(code, options = {}) {
|
|
901
|
+
this.ensureNotDisposed();
|
|
902
|
+
return this.sessionManager.executeAndWait(code, options.session, options.onEvent);
|
|
903
|
+
}
|
|
904
|
+
// ============================================================================
|
|
905
|
+
// Statistics & Lifecycle
|
|
906
|
+
// ============================================================================
|
|
907
|
+
/**
|
|
908
|
+
* Get broker statistics
|
|
909
|
+
*/
|
|
910
|
+
stats() {
|
|
911
|
+
return {
|
|
912
|
+
tools: this.toolRegistry.size,
|
|
913
|
+
activeSessions: this.sessionManager.activeCount,
|
|
914
|
+
totalSessions: this.sessionManager.totalCount
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Clean up expired and completed sessions
|
|
919
|
+
*/
|
|
920
|
+
cleanup() {
|
|
921
|
+
return this.sessionManager.cleanup();
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Dispose of the broker and all resources
|
|
925
|
+
*/
|
|
926
|
+
async dispose() {
|
|
927
|
+
if (this.disposed) {
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
this.disposed = true;
|
|
931
|
+
await this.sessionManager.dispose();
|
|
932
|
+
this.toolRegistry.clear();
|
|
933
|
+
this.toolRegistry.clearSecrets();
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Check if broker is disposed
|
|
937
|
+
*/
|
|
938
|
+
get isDisposed() {
|
|
939
|
+
return this.disposed;
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Ensure broker is not disposed
|
|
943
|
+
*/
|
|
944
|
+
ensureNotDisposed() {
|
|
945
|
+
if (this.disposed) {
|
|
946
|
+
throw new Error("Broker is disposed");
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
};
|
|
950
|
+
function createBroker(config) {
|
|
951
|
+
return new Broker(config);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
// libs/enclavejs-broker/src/event-filter.ts
|
|
955
|
+
var import_types2 = require("@enclave-vm/types");
|
|
956
|
+
var import_minimatch = require("minimatch");
|
|
957
|
+
var MAX_REGEX_INPUT_LENGTH = 1e4;
|
|
958
|
+
var MAX_PATTERN_LENGTH_FOR_REDOS_CHECK = 500;
|
|
959
|
+
var REDOS_DETECTION_PATTERNS = {
|
|
960
|
+
/** Check for nested quantifiers: (a+)+ or (a*)* */
|
|
961
|
+
nestedQuantifiers: /\([^)]{0,100}[*+{][^)]{0,100}\)[*+{]/,
|
|
962
|
+
/** Check for alternation with overlapping patterns: (a|ab)* */
|
|
963
|
+
alternationOverlap: /\([^|]{0,100}\|[^)]{0,100}\)[*+{]/,
|
|
964
|
+
/** Check for repeated groups with quantifiers: (a+)+ */
|
|
965
|
+
repeatedGroups: /\([^)]{0,100}[*+][^)]{0,100}\)[*+]/
|
|
966
|
+
};
|
|
967
|
+
function isPotentiallyVulnerableRegex(pattern) {
|
|
968
|
+
const safePattern = pattern.length > MAX_PATTERN_LENGTH_FOR_REDOS_CHECK ? pattern.slice(0, MAX_PATTERN_LENGTH_FOR_REDOS_CHECK) : pattern;
|
|
969
|
+
try {
|
|
970
|
+
if (REDOS_DETECTION_PATTERNS.nestedQuantifiers.test(safePattern)) return true;
|
|
971
|
+
if (REDOS_DETECTION_PATTERNS.alternationOverlap.test(safePattern)) return true;
|
|
972
|
+
if (REDOS_DETECTION_PATTERNS.repeatedGroups.test(safePattern)) return true;
|
|
973
|
+
} catch {
|
|
974
|
+
return false;
|
|
975
|
+
}
|
|
976
|
+
return false;
|
|
977
|
+
}
|
|
978
|
+
var EventFilter = class {
|
|
979
|
+
config;
|
|
980
|
+
alwaysAllow;
|
|
981
|
+
compiledRegexes;
|
|
982
|
+
onError;
|
|
983
|
+
constructor(options) {
|
|
984
|
+
this.config = options.config;
|
|
985
|
+
this.onError = options.onError;
|
|
986
|
+
this.alwaysAllow = new Set(options.config.alwaysAllow ?? import_types2.DEFAULT_ALWAYS_ALLOW);
|
|
987
|
+
this.compiledRegexes = /* @__PURE__ */ new Map();
|
|
988
|
+
this.compilePatterns();
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Check if an event should be sent to the client.
|
|
992
|
+
*/
|
|
993
|
+
shouldSend(event) {
|
|
994
|
+
if (this.alwaysAllow.has(event.type)) {
|
|
995
|
+
return true;
|
|
996
|
+
}
|
|
997
|
+
const matches = this.matchesAnyRule(event);
|
|
998
|
+
if (this.config.mode === import_types2.FilterMode.Include) {
|
|
999
|
+
return matches;
|
|
1000
|
+
} else {
|
|
1001
|
+
return !matches;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Filter an array of events.
|
|
1006
|
+
*/
|
|
1007
|
+
filter(events) {
|
|
1008
|
+
return events.filter((event) => this.shouldSend(event));
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Check if event matches any filter rule.
|
|
1012
|
+
*/
|
|
1013
|
+
matchesAnyRule(event) {
|
|
1014
|
+
return this.config.rules.some((rule) => this.matchesRule(event, rule));
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Check if event matches a specific rule.
|
|
1018
|
+
*/
|
|
1019
|
+
matchesRule(event, rule) {
|
|
1020
|
+
const typeMatch = rule.types ? this.matchesTypeFilter(event, rule.types) : true;
|
|
1021
|
+
const contentMatch = rule.content ? this.matchesContentFilter(event, rule.content) : true;
|
|
1022
|
+
if (rule.types && rule.content) {
|
|
1023
|
+
return typeMatch && contentMatch;
|
|
1024
|
+
}
|
|
1025
|
+
return rule.types ? typeMatch : contentMatch;
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Check if event type matches filter.
|
|
1029
|
+
*/
|
|
1030
|
+
matchesTypeFilter(event, filter) {
|
|
1031
|
+
return filter.types.includes(event.type);
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Check if event content matches filter.
|
|
1035
|
+
*/
|
|
1036
|
+
matchesContentFilter(event, filter) {
|
|
1037
|
+
const matchMode = filter.match ?? "any";
|
|
1038
|
+
if (matchMode === "all") {
|
|
1039
|
+
return filter.patterns.every((pattern) => this.matchesPattern(event, pattern));
|
|
1040
|
+
} else {
|
|
1041
|
+
return filter.patterns.some((pattern) => this.matchesPattern(event, pattern));
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Check if event matches a content pattern.
|
|
1046
|
+
*/
|
|
1047
|
+
matchesPattern(event, pattern) {
|
|
1048
|
+
const value = this.getFieldValue(event, pattern.field);
|
|
1049
|
+
if (value === void 0) {
|
|
1050
|
+
return false;
|
|
1051
|
+
}
|
|
1052
|
+
const stringValue = this.stringify(value);
|
|
1053
|
+
const patternValue = pattern.caseInsensitive ? pattern.pattern.toLowerCase() : pattern.pattern;
|
|
1054
|
+
const matchValue = pattern.caseInsensitive ? stringValue.toLowerCase() : stringValue;
|
|
1055
|
+
try {
|
|
1056
|
+
switch (pattern.type) {
|
|
1057
|
+
case import_types2.PatternType.Exact:
|
|
1058
|
+
return matchValue === patternValue;
|
|
1059
|
+
case import_types2.PatternType.Prefix:
|
|
1060
|
+
return matchValue.startsWith(patternValue);
|
|
1061
|
+
case import_types2.PatternType.Regex:
|
|
1062
|
+
return this.matchRegex(pattern.pattern, matchValue, pattern.caseInsensitive);
|
|
1063
|
+
case import_types2.PatternType.Glob:
|
|
1064
|
+
return (0, import_minimatch.minimatch)(matchValue, patternValue, {
|
|
1065
|
+
nocase: pattern.caseInsensitive
|
|
1066
|
+
});
|
|
1067
|
+
default:
|
|
1068
|
+
return false;
|
|
1069
|
+
}
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
this.onError?.(error, event);
|
|
1072
|
+
return false;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Get field value from event using dot notation.
|
|
1077
|
+
*/
|
|
1078
|
+
getFieldValue(event, field) {
|
|
1079
|
+
if (!field) {
|
|
1080
|
+
return event.payload;
|
|
1081
|
+
}
|
|
1082
|
+
const parts = field.split(".");
|
|
1083
|
+
let value = event;
|
|
1084
|
+
for (const part of parts) {
|
|
1085
|
+
if (value === null || value === void 0) {
|
|
1086
|
+
return void 0;
|
|
1087
|
+
}
|
|
1088
|
+
if (typeof value !== "object") {
|
|
1089
|
+
return void 0;
|
|
1090
|
+
}
|
|
1091
|
+
value = value[part];
|
|
1092
|
+
}
|
|
1093
|
+
return value;
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Stringify a value for matching.
|
|
1097
|
+
*/
|
|
1098
|
+
stringify(value) {
|
|
1099
|
+
if (typeof value === "string") {
|
|
1100
|
+
return value;
|
|
1101
|
+
}
|
|
1102
|
+
if (value === null || value === void 0) {
|
|
1103
|
+
return "";
|
|
1104
|
+
}
|
|
1105
|
+
return JSON.stringify(value);
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Match against a compiled regex with ReDoS protection.
|
|
1109
|
+
* Enforces input length limits to prevent catastrophic backtracking.
|
|
1110
|
+
*/
|
|
1111
|
+
matchRegex(pattern, value, caseInsensitive) {
|
|
1112
|
+
if (value.length > MAX_REGEX_INPUT_LENGTH) {
|
|
1113
|
+
return false;
|
|
1114
|
+
}
|
|
1115
|
+
const cacheKey = `${pattern}:${caseInsensitive ? "i" : ""}`;
|
|
1116
|
+
const compiled = this.compiledRegexes.get(cacheKey);
|
|
1117
|
+
if (!compiled) {
|
|
1118
|
+
try {
|
|
1119
|
+
const flags = caseInsensitive ? "i" : "";
|
|
1120
|
+
return new RegExp(pattern, flags).test(value);
|
|
1121
|
+
} catch {
|
|
1122
|
+
return false;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
try {
|
|
1126
|
+
return compiled.regex.test(value);
|
|
1127
|
+
} catch {
|
|
1128
|
+
return false;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
/**
|
|
1132
|
+
* Pre-compile all regex patterns for efficiency.
|
|
1133
|
+
* Includes ReDoS vulnerability detection and logging.
|
|
1134
|
+
*/
|
|
1135
|
+
compilePatterns() {
|
|
1136
|
+
for (const rule of this.config.rules) {
|
|
1137
|
+
if (!rule.content?.patterns) continue;
|
|
1138
|
+
for (const pattern of rule.content.patterns) {
|
|
1139
|
+
if (pattern.type !== import_types2.PatternType.Regex) continue;
|
|
1140
|
+
const cacheKey = `${pattern.pattern}:${pattern.caseInsensitive ? "i" : ""}`;
|
|
1141
|
+
if (this.compiledRegexes.has(cacheKey)) continue;
|
|
1142
|
+
if (isPotentiallyVulnerableRegex(pattern.pattern)) {
|
|
1143
|
+
console.warn(
|
|
1144
|
+
`[EventFilter] Potentially vulnerable regex pattern detected: ${pattern.pattern}. Input length will be limited to ${MAX_REGEX_INPUT_LENGTH} characters for protection.`
|
|
1145
|
+
);
|
|
1146
|
+
}
|
|
1147
|
+
try {
|
|
1148
|
+
const flags = pattern.caseInsensitive ? "i" : "";
|
|
1149
|
+
const regex = new RegExp(pattern.pattern, flags);
|
|
1150
|
+
this.compiledRegexes.set(cacheKey, { regex });
|
|
1151
|
+
} catch (error) {
|
|
1152
|
+
console.error(`Invalid regex pattern: ${pattern.pattern}`, error);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
function createEventFilter(options) {
|
|
1159
|
+
return new EventFilter(options);
|
|
1160
|
+
}
|
|
1161
|
+
function createTypeFilter(mode, types) {
|
|
1162
|
+
return {
|
|
1163
|
+
mode: mode === "include" ? import_types2.FilterMode.Include : import_types2.FilterMode.Exclude,
|
|
1164
|
+
rules: [{ types: { types } }]
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
function createContentFilter(mode, pattern, patternType = import_types2.PatternType.Regex) {
|
|
1168
|
+
return {
|
|
1169
|
+
mode: mode === "include" ? import_types2.FilterMode.Include : import_types2.FilterMode.Exclude,
|
|
1170
|
+
rules: [
|
|
1171
|
+
{
|
|
1172
|
+
content: {
|
|
1173
|
+
patterns: [{ type: patternType, pattern }]
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
]
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
// libs/enclavejs-broker/src/http/session-handler.ts
|
|
1181
|
+
var SessionHandler = class {
|
|
1182
|
+
broker;
|
|
1183
|
+
cors;
|
|
1184
|
+
allowedOrigins;
|
|
1185
|
+
constructor(config) {
|
|
1186
|
+
this.broker = config.broker;
|
|
1187
|
+
this.cors = config.cors ?? true;
|
|
1188
|
+
this.allowedOrigins = config.allowedOrigins ?? ["*"];
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Get route definitions for registration with HTTP frameworks
|
|
1192
|
+
*/
|
|
1193
|
+
getRoutes() {
|
|
1194
|
+
return [
|
|
1195
|
+
{ method: "GET", path: "/sessions", handler: this.listSessions.bind(this) },
|
|
1196
|
+
{ method: "POST", path: "/sessions", handler: this.createSession.bind(this) },
|
|
1197
|
+
{ method: "GET", path: "/sessions/:sessionId", handler: this.getSession.bind(this) },
|
|
1198
|
+
{ method: "GET", path: "/sessions/:sessionId/stream", handler: this.streamSession.bind(this) },
|
|
1199
|
+
{ method: "DELETE", path: "/sessions/:sessionId", handler: this.terminateSession.bind(this) },
|
|
1200
|
+
{ method: "OPTIONS", path: "/sessions", handler: this.handleCors.bind(this) },
|
|
1201
|
+
{ method: "OPTIONS", path: "/sessions/:sessionId", handler: this.handleCors.bind(this) },
|
|
1202
|
+
{ method: "OPTIONS", path: "/sessions/:sessionId/stream", handler: this.handleCors.bind(this) }
|
|
1203
|
+
];
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Add CORS headers to response
|
|
1207
|
+
*/
|
|
1208
|
+
addCorsHeaders(req, res) {
|
|
1209
|
+
if (!this.cors) return;
|
|
1210
|
+
const origin = req.headers["origin"];
|
|
1211
|
+
if (this.allowedOrigins.includes("*")) {
|
|
1212
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
1213
|
+
} else if (origin && this.allowedOrigins.includes(origin)) {
|
|
1214
|
+
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
1215
|
+
res.setHeader("Vary", "Origin");
|
|
1216
|
+
} else {
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
1220
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Last-Event-ID");
|
|
1221
|
+
res.setHeader("Access-Control-Max-Age", "86400");
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Handle CORS preflight requests
|
|
1225
|
+
*/
|
|
1226
|
+
async handleCors(req, res) {
|
|
1227
|
+
this.addCorsHeaders(req, res);
|
|
1228
|
+
res.status(204).end();
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* List all active sessions
|
|
1232
|
+
*
|
|
1233
|
+
* GET /sessions
|
|
1234
|
+
*/
|
|
1235
|
+
async listSessions(req, res) {
|
|
1236
|
+
this.addCorsHeaders(req, res);
|
|
1237
|
+
try {
|
|
1238
|
+
const sessions = this.broker.listSessions();
|
|
1239
|
+
const response = {
|
|
1240
|
+
sessions: sessions.map((info) => this.sessionInfoToResponse(info)),
|
|
1241
|
+
total: sessions.length
|
|
1242
|
+
};
|
|
1243
|
+
res.status(200).json(response);
|
|
1244
|
+
} catch {
|
|
1245
|
+
this.sendError(res, 500, "INTERNAL_ERROR", "Failed to list sessions");
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Create a new session and start execution
|
|
1250
|
+
*
|
|
1251
|
+
* POST /sessions
|
|
1252
|
+
* Body: { code: string, sessionId?: string, config?: {...} }
|
|
1253
|
+
*
|
|
1254
|
+
* Returns NDJSON stream of events
|
|
1255
|
+
*/
|
|
1256
|
+
async createSession(req, res) {
|
|
1257
|
+
this.addCorsHeaders(req, res);
|
|
1258
|
+
const body = req.body;
|
|
1259
|
+
if (!body || typeof body.code !== "string") {
|
|
1260
|
+
this.sendError(res, 400, "INVALID_REQUEST", 'Missing or invalid "code" field');
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
if (this.broker.isDisposed) {
|
|
1264
|
+
this.sendError(res, 503, "SERVICE_UNAVAILABLE", "Broker is disposed");
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
try {
|
|
1268
|
+
const limits = {};
|
|
1269
|
+
if (body.config?.maxExecutionMs !== void 0) {
|
|
1270
|
+
limits["sessionTtlMs"] = body.config.maxExecutionMs;
|
|
1271
|
+
}
|
|
1272
|
+
if (body.config?.maxToolCalls !== void 0) {
|
|
1273
|
+
limits["maxToolCalls"] = body.config.maxToolCalls;
|
|
1274
|
+
}
|
|
1275
|
+
if (body.config?.heartbeatIntervalMs !== void 0) {
|
|
1276
|
+
limits["heartbeatIntervalMs"] = body.config.heartbeatIntervalMs;
|
|
1277
|
+
}
|
|
1278
|
+
let eventFilter;
|
|
1279
|
+
if (body.filter) {
|
|
1280
|
+
eventFilter = createEventFilter({ config: body.filter });
|
|
1281
|
+
}
|
|
1282
|
+
const session = this.broker.createSession({
|
|
1283
|
+
sessionId: body.sessionId,
|
|
1284
|
+
limits: Object.keys(limits).length > 0 ? limits : void 0
|
|
1285
|
+
});
|
|
1286
|
+
res.setHeader("Content-Type", "application/x-ndjson");
|
|
1287
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
1288
|
+
res.setHeader("Connection", "keep-alive");
|
|
1289
|
+
res.setHeader("X-Session-ID", session.sessionId);
|
|
1290
|
+
const unsubscribe = session.onEvent((event) => {
|
|
1291
|
+
if (eventFilter && !eventFilter.shouldSend(event)) {
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
this.writeEvent(res, event);
|
|
1295
|
+
});
|
|
1296
|
+
let cleanedUp = false;
|
|
1297
|
+
const cleanup = () => {
|
|
1298
|
+
if (cleanedUp) return;
|
|
1299
|
+
cleanedUp = true;
|
|
1300
|
+
unsubscribe();
|
|
1301
|
+
if (!session.isTerminal()) {
|
|
1302
|
+
session.cancel("Client disconnected").catch(() => {
|
|
1303
|
+
});
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
if (req.signal) {
|
|
1307
|
+
req.signal.addEventListener("abort", cleanup, { once: true });
|
|
1308
|
+
}
|
|
1309
|
+
try {
|
|
1310
|
+
await session.execute(body.code);
|
|
1311
|
+
} catch {
|
|
1312
|
+
} finally {
|
|
1313
|
+
cleanup();
|
|
1314
|
+
res.end();
|
|
1315
|
+
}
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
1318
|
+
this.sendError(res, 500, "SESSION_CREATE_ERROR", message);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
/**
|
|
1322
|
+
* Get session information
|
|
1323
|
+
*
|
|
1324
|
+
* GET /sessions/:sessionId
|
|
1325
|
+
*/
|
|
1326
|
+
async getSession(req, res) {
|
|
1327
|
+
this.addCorsHeaders(req, res);
|
|
1328
|
+
const sessionId = req.params["sessionId"];
|
|
1329
|
+
if (!sessionId) {
|
|
1330
|
+
this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
const session = this.broker.getSession(sessionId);
|
|
1334
|
+
if (!session) {
|
|
1335
|
+
this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
res.status(200).json(this.sessionToInfo(session));
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Stream session events (for reconnection)
|
|
1342
|
+
*
|
|
1343
|
+
* GET /sessions/:sessionId/stream?fromSeq=N&filter=JSON
|
|
1344
|
+
*/
|
|
1345
|
+
async streamSession(req, res) {
|
|
1346
|
+
this.addCorsHeaders(req, res);
|
|
1347
|
+
const sessionId = req.params["sessionId"];
|
|
1348
|
+
if (!sessionId) {
|
|
1349
|
+
this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
const session = this.broker.getSession(sessionId);
|
|
1353
|
+
if (!session) {
|
|
1354
|
+
this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
const parsedFromSeq = parseInt(req.query["fromSeq"] ?? "0", 10);
|
|
1358
|
+
const fromSeq = Number.isFinite(parsedFromSeq) && parsedFromSeq >= 0 ? parsedFromSeq : 0;
|
|
1359
|
+
let eventFilter;
|
|
1360
|
+
if (req.query["filter"]) {
|
|
1361
|
+
try {
|
|
1362
|
+
const filterConfig = JSON.parse(req.query["filter"]);
|
|
1363
|
+
eventFilter = createEventFilter({ config: filterConfig });
|
|
1364
|
+
} catch {
|
|
1365
|
+
this.sendError(res, 400, "INVALID_FILTER", "Invalid filter configuration");
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
res.setHeader("Content-Type", "application/x-ndjson");
|
|
1370
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
1371
|
+
res.setHeader("Connection", "keep-alive");
|
|
1372
|
+
res.setHeader("X-Session-ID", session.sessionId);
|
|
1373
|
+
const pastEvents = session.getEvents();
|
|
1374
|
+
for (const event of pastEvents) {
|
|
1375
|
+
if (event.seq >= fromSeq) {
|
|
1376
|
+
if (eventFilter && !eventFilter.shouldSend(event)) {
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
this.writeEvent(res, event);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
if (session.isTerminal()) {
|
|
1383
|
+
res.end();
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
const unsubscribe = session.onEvent((event) => {
|
|
1387
|
+
if (event.seq >= fromSeq) {
|
|
1388
|
+
if (eventFilter && !eventFilter.shouldSend(event)) {
|
|
1389
|
+
if (event.type === "final") {
|
|
1390
|
+
unsubscribe();
|
|
1391
|
+
res.end();
|
|
1392
|
+
}
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
this.writeEvent(res, event);
|
|
1396
|
+
}
|
|
1397
|
+
if (event.type === "final") {
|
|
1398
|
+
unsubscribe();
|
|
1399
|
+
res.end();
|
|
1400
|
+
}
|
|
1401
|
+
});
|
|
1402
|
+
if (req.signal) {
|
|
1403
|
+
req.signal.addEventListener(
|
|
1404
|
+
"abort",
|
|
1405
|
+
() => {
|
|
1406
|
+
unsubscribe();
|
|
1407
|
+
},
|
|
1408
|
+
{ once: true }
|
|
1409
|
+
);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Terminate a session
|
|
1414
|
+
*
|
|
1415
|
+
* DELETE /sessions/:sessionId
|
|
1416
|
+
*/
|
|
1417
|
+
async terminateSession(req, res) {
|
|
1418
|
+
this.addCorsHeaders(req, res);
|
|
1419
|
+
const sessionId = req.params["sessionId"];
|
|
1420
|
+
if (!sessionId) {
|
|
1421
|
+
this.sendError(res, 400, "INVALID_REQUEST", "Missing sessionId");
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
const success = await this.broker.terminateSession(sessionId);
|
|
1425
|
+
if (!success) {
|
|
1426
|
+
this.sendError(res, 404, "NOT_FOUND", `Session ${sessionId} not found`);
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
res.status(200).json({ success: true, sessionId });
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* Convert BrokerSession to info response
|
|
1433
|
+
*/
|
|
1434
|
+
sessionToInfo(session) {
|
|
1435
|
+
const stats = session.getStats();
|
|
1436
|
+
return {
|
|
1437
|
+
sessionId: session.sessionId,
|
|
1438
|
+
state: session.state,
|
|
1439
|
+
createdAt: session.createdAt,
|
|
1440
|
+
expiresAt: session.expiresAt,
|
|
1441
|
+
stats: {
|
|
1442
|
+
duration: stats.duration,
|
|
1443
|
+
toolCallCount: stats.toolCallCount
|
|
1444
|
+
}
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* Convert SessionInfo to response format
|
|
1449
|
+
*/
|
|
1450
|
+
sessionInfoToResponse(info) {
|
|
1451
|
+
return {
|
|
1452
|
+
sessionId: info.sessionId,
|
|
1453
|
+
state: info.state,
|
|
1454
|
+
createdAt: info.createdAt,
|
|
1455
|
+
expiresAt: info.expiresAt,
|
|
1456
|
+
stats: {
|
|
1457
|
+
duration: Date.now() - info.createdAt,
|
|
1458
|
+
toolCallCount: 0
|
|
1459
|
+
// Not available from SessionInfo
|
|
1460
|
+
}
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Write a stream event as NDJSON
|
|
1465
|
+
*/
|
|
1466
|
+
writeEvent(res, event) {
|
|
1467
|
+
res.write(JSON.stringify(event) + "\n");
|
|
1468
|
+
if (res.flush) {
|
|
1469
|
+
res.flush();
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* Send an error response
|
|
1474
|
+
*/
|
|
1475
|
+
sendError(res, status, code, message) {
|
|
1476
|
+
const error = { code, message };
|
|
1477
|
+
res.status(status).json(error);
|
|
1478
|
+
}
|
|
1479
|
+
};
|
|
1480
|
+
function createSessionHandler(config) {
|
|
1481
|
+
return new SessionHandler(config);
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
// libs/enclavejs-broker/src/http/express-adapter.ts
|
|
1485
|
+
function adaptRequest(req) {
|
|
1486
|
+
const abortController = new AbortController();
|
|
1487
|
+
if (req.on && req.socket) {
|
|
1488
|
+
req.on("close", () => {
|
|
1489
|
+
if (req.socket?.destroyed) {
|
|
1490
|
+
abortController.abort();
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
return {
|
|
1495
|
+
method: req.method,
|
|
1496
|
+
path: req.path,
|
|
1497
|
+
params: req.params,
|
|
1498
|
+
query: req.query,
|
|
1499
|
+
body: req.body,
|
|
1500
|
+
headers: req.headers,
|
|
1501
|
+
signal: abortController.signal
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
function adaptResponse(res) {
|
|
1505
|
+
return {
|
|
1506
|
+
status(code) {
|
|
1507
|
+
res.status(code);
|
|
1508
|
+
return this;
|
|
1509
|
+
},
|
|
1510
|
+
json(data) {
|
|
1511
|
+
res.json(data);
|
|
1512
|
+
},
|
|
1513
|
+
setHeader(name, value) {
|
|
1514
|
+
res.setHeader(name, value);
|
|
1515
|
+
return this;
|
|
1516
|
+
},
|
|
1517
|
+
write(data) {
|
|
1518
|
+
res.write(data);
|
|
1519
|
+
},
|
|
1520
|
+
end() {
|
|
1521
|
+
res.end();
|
|
1522
|
+
},
|
|
1523
|
+
flush() {
|
|
1524
|
+
if (res.flushHeaders) {
|
|
1525
|
+
res.flushHeaders();
|
|
1526
|
+
}
|
|
1527
|
+
if (res.flush) {
|
|
1528
|
+
res.flush();
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
function createExpressRouter(handler) {
|
|
1534
|
+
const routes = [];
|
|
1535
|
+
for (const route of handler.getRoutes()) {
|
|
1536
|
+
const method = route.method.toLowerCase();
|
|
1537
|
+
routes.push({
|
|
1538
|
+
method,
|
|
1539
|
+
path: route.path,
|
|
1540
|
+
handler: (req, res) => {
|
|
1541
|
+
const brokerReq = adaptRequest(req);
|
|
1542
|
+
const brokerRes = adaptResponse(res);
|
|
1543
|
+
route.handler(brokerReq, brokerRes).catch((error) => {
|
|
1544
|
+
console.error("Route handler error:", error);
|
|
1545
|
+
if (!res.setHeader) return;
|
|
1546
|
+
res.status(500).json({
|
|
1547
|
+
code: "INTERNAL_ERROR",
|
|
1548
|
+
message: "Internal server error"
|
|
1549
|
+
});
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
return {
|
|
1555
|
+
get(path, routeHandler) {
|
|
1556
|
+
const route = routes.find((r) => r.method === "get" && r.path === path);
|
|
1557
|
+
if (route) routeHandler = route.handler;
|
|
1558
|
+
},
|
|
1559
|
+
post(path, routeHandler) {
|
|
1560
|
+
const route = routes.find((r) => r.method === "post" && r.path === path);
|
|
1561
|
+
if (route) routeHandler = route.handler;
|
|
1562
|
+
},
|
|
1563
|
+
delete(path, routeHandler) {
|
|
1564
|
+
const route = routes.find((r) => r.method === "delete" && r.path === path);
|
|
1565
|
+
if (route) routeHandler = route.handler;
|
|
1566
|
+
},
|
|
1567
|
+
options(path, routeHandler) {
|
|
1568
|
+
const route = routes.find((r) => r.method === "options" && r.path === path);
|
|
1569
|
+
if (route) routeHandler = route.handler;
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
function registerExpressRoutes(router, handler) {
|
|
1574
|
+
for (const route of handler.getRoutes()) {
|
|
1575
|
+
const method = route.method.toLowerCase();
|
|
1576
|
+
const expressHandler = (req, res) => {
|
|
1577
|
+
const brokerReq = adaptRequest(req);
|
|
1578
|
+
const brokerRes = adaptResponse(res);
|
|
1579
|
+
route.handler(brokerReq, brokerRes).catch((error) => {
|
|
1580
|
+
console.error("Route handler error:", error);
|
|
1581
|
+
try {
|
|
1582
|
+
res.status(500).json({
|
|
1583
|
+
code: "INTERNAL_ERROR",
|
|
1584
|
+
message: "Internal server error"
|
|
1585
|
+
});
|
|
1586
|
+
} catch {
|
|
1587
|
+
}
|
|
1588
|
+
});
|
|
1589
|
+
};
|
|
1590
|
+
router[method](route.path, expressHandler);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1594
|
+
0 && (module.exports = {
|
|
1595
|
+
Broker,
|
|
1596
|
+
BrokerSession,
|
|
1597
|
+
EventFilter,
|
|
1598
|
+
SessionHandler,
|
|
1599
|
+
SessionManager,
|
|
1600
|
+
ToolRegistry,
|
|
1601
|
+
createBroker,
|
|
1602
|
+
createBrokerSession,
|
|
1603
|
+
createContentFilter,
|
|
1604
|
+
createEventFilter,
|
|
1605
|
+
createExpressRouter,
|
|
1606
|
+
createSessionHandler,
|
|
1607
|
+
createSessionManager,
|
|
1608
|
+
createToolRegistry,
|
|
1609
|
+
createTypeFilter,
|
|
1610
|
+
registerExpressRoutes
|
|
1611
|
+
});
|