@enclave-vm/broker 0.0.1

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.
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ /**
3
+ * HTTP Types for Broker API
4
+ *
5
+ * Framework-agnostic types for HTTP request/response handling.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/http/types.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG","sourcesContent":["/**\n * HTTP Types for Broker API\n *\n * Framework-agnostic types for HTTP request/response handling.\n *\n * @packageDocumentation\n */\n\nimport type { SessionId, EventFilterConfig } from '@enclave-vm/types';\n\n/**\n * HTTP request abstraction\n */\nexport interface BrokerRequest {\n /**\n * Request method\n */\n method: string;\n\n /**\n * Request path\n */\n path: string;\n\n /**\n * URL parameters (e.g., :sessionId)\n */\n params: Record<string, string>;\n\n /**\n * Query parameters\n */\n query: Record<string, string>;\n\n /**\n * Request body (parsed JSON)\n */\n body: unknown;\n\n /**\n * Request headers\n */\n headers: Record<string, string | string[] | undefined>;\n\n /**\n * Abort signal for cancellation\n */\n signal?: AbortSignal;\n}\n\n/**\n * HTTP response abstraction\n */\nexport interface BrokerResponse {\n /**\n * Set HTTP status code\n */\n status(code: number): BrokerResponse;\n\n /**\n * Send JSON response\n */\n json(data: unknown): void;\n\n /**\n * Set response header\n */\n setHeader(name: string, value: string): BrokerResponse;\n\n /**\n * Write data to response stream\n */\n write(data: string): void;\n\n /**\n * End the response\n */\n end(): void;\n\n /**\n * Flush the response buffer (for streaming)\n */\n flush?(): void;\n}\n\n/**\n * Create session request body\n */\nexport interface CreateSessionRequest {\n /**\n * Code to execute\n */\n code: string;\n\n /**\n * Optional session ID (generated if not provided)\n */\n sessionId?: SessionId;\n\n /**\n * Session configuration\n */\n config?: {\n /**\n * Maximum execution time in milliseconds\n */\n maxExecutionMs?: number;\n\n /**\n * Maximum tool calls\n */\n maxToolCalls?: number;\n\n /**\n * Heartbeat interval in milliseconds\n */\n heartbeatIntervalMs?: number;\n };\n\n /**\n * Event filter configuration (server-side filtering).\n * Controls which events are sent to the client.\n */\n filter?: EventFilterConfig;\n}\n\n/**\n * Session info response\n */\nexport interface SessionInfoResponse {\n /**\n * Session ID\n */\n sessionId: SessionId;\n\n /**\n * Current session state\n */\n state: string;\n\n /**\n * Creation timestamp\n */\n createdAt: number;\n\n /**\n * Expiration timestamp\n */\n expiresAt: number;\n\n /**\n * Session statistics\n */\n stats: {\n duration: number;\n toolCallCount: number;\n };\n}\n\n/**\n * List sessions response\n */\nexport interface ListSessionsResponse {\n /**\n * Active sessions\n */\n sessions: SessionInfoResponse[];\n\n /**\n * Total count\n */\n total: number;\n}\n\n/**\n * Error response\n */\nexport interface ErrorResponse {\n /**\n * Error code\n */\n code: string;\n\n /**\n * Error message\n */\n message: string;\n\n /**\n * Optional error details\n */\n details?: unknown;\n}\n\n/**\n * Stream options for session execution\n */\nexport interface StreamOptions {\n /**\n * Resume from sequence number (for reconnection)\n */\n fromSeq?: number;\n\n /**\n * Include heartbeats in stream\n */\n heartbeats?: boolean;\n\n /**\n * Event filter configuration (server-side filtering).\n * Controls which events are sent to the client.\n */\n filter?: EventFilterConfig;\n}\n"]}
package/src/index.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @enclave-vm/broker
3
+ *
4
+ * Tool broker and session management for the Enclave VM streaming runtime.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ export { Broker, createBroker } from './broker';
9
+ export type { BrokerConfig, ExecuteOptions } from './broker';
10
+ export { ToolRegistry, createToolRegistry } from './tool-registry';
11
+ export type { ToolDefinition, ToolHandler, ToolContext, ToolValidationResult, ToolExecutionResult, } from './tool-registry';
12
+ export { BrokerSession, createBrokerSession } from './broker-session';
13
+ export type { BrokerSessionConfig } from './broker-session';
14
+ export { SessionManager, createSessionManager } from './session-manager';
15
+ export type { SessionManagerConfig, SessionInfo, CreateSessionResult } from './session-manager';
16
+ export { SessionHandler, createSessionHandler, registerExpressRoutes, createExpressRouter } from './http';
17
+ export type { SessionHandlerConfig, RouteHandler, BrokerRequest, BrokerResponse, CreateSessionRequest, SessionInfoResponse, ListSessionsResponse, ErrorResponse, StreamOptions, } from './http';
18
+ export { EventFilter, createEventFilter, createTypeFilter, createContentFilter } from './event-filter';
19
+ export type { EventFilterOptions } from './event-filter';
package/src/index.js ADDED
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /**
3
+ * @enclave-vm/broker
4
+ *
5
+ * Tool broker and session management for the Enclave VM streaming runtime.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.createContentFilter = exports.createTypeFilter = exports.createEventFilter = exports.EventFilter = exports.createExpressRouter = exports.registerExpressRoutes = exports.createSessionHandler = exports.SessionHandler = exports.createSessionManager = exports.SessionManager = exports.createBrokerSession = exports.BrokerSession = exports.createToolRegistry = exports.ToolRegistry = exports.createBroker = exports.Broker = void 0;
11
+ // Main Broker
12
+ var broker_1 = require("./broker");
13
+ Object.defineProperty(exports, "Broker", { enumerable: true, get: function () { return broker_1.Broker; } });
14
+ Object.defineProperty(exports, "createBroker", { enumerable: true, get: function () { return broker_1.createBroker; } });
15
+ // Tool Registry
16
+ var tool_registry_1 = require("./tool-registry");
17
+ Object.defineProperty(exports, "ToolRegistry", { enumerable: true, get: function () { return tool_registry_1.ToolRegistry; } });
18
+ Object.defineProperty(exports, "createToolRegistry", { enumerable: true, get: function () { return tool_registry_1.createToolRegistry; } });
19
+ // Broker Session
20
+ var broker_session_1 = require("./broker-session");
21
+ Object.defineProperty(exports, "BrokerSession", { enumerable: true, get: function () { return broker_session_1.BrokerSession; } });
22
+ Object.defineProperty(exports, "createBrokerSession", { enumerable: true, get: function () { return broker_session_1.createBrokerSession; } });
23
+ // Session Manager
24
+ var session_manager_1 = require("./session-manager");
25
+ Object.defineProperty(exports, "SessionManager", { enumerable: true, get: function () { return session_manager_1.SessionManager; } });
26
+ Object.defineProperty(exports, "createSessionManager", { enumerable: true, get: function () { return session_manager_1.createSessionManager; } });
27
+ // HTTP API
28
+ var http_1 = require("./http");
29
+ Object.defineProperty(exports, "SessionHandler", { enumerable: true, get: function () { return http_1.SessionHandler; } });
30
+ Object.defineProperty(exports, "createSessionHandler", { enumerable: true, get: function () { return http_1.createSessionHandler; } });
31
+ Object.defineProperty(exports, "registerExpressRoutes", { enumerable: true, get: function () { return http_1.registerExpressRoutes; } });
32
+ Object.defineProperty(exports, "createExpressRouter", { enumerable: true, get: function () { return http_1.createExpressRouter; } });
33
+ // Event Filtering
34
+ var event_filter_1 = require("./event-filter");
35
+ Object.defineProperty(exports, "EventFilter", { enumerable: true, get: function () { return event_filter_1.EventFilter; } });
36
+ Object.defineProperty(exports, "createEventFilter", { enumerable: true, get: function () { return event_filter_1.createEventFilter; } });
37
+ Object.defineProperty(exports, "createTypeFilter", { enumerable: true, get: function () { return event_filter_1.createTypeFilter; } });
38
+ Object.defineProperty(exports, "createContentFilter", { enumerable: true, get: function () { return event_filter_1.createContentFilter; } });
39
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,cAAc;AACd,mCAAgD;AAAvC,gGAAA,MAAM,OAAA;AAAE,sGAAA,YAAY,OAAA;AAG7B,gBAAgB;AAChB,iDAAmE;AAA1D,6GAAA,YAAY,OAAA;AAAE,mHAAA,kBAAkB,OAAA;AASzC,iBAAiB;AACjB,mDAAsE;AAA7D,+GAAA,aAAa,OAAA;AAAE,qHAAA,mBAAmB,OAAA;AAG3C,kBAAkB;AAClB,qDAAyE;AAAhE,iHAAA,cAAc,OAAA;AAAE,uHAAA,oBAAoB,OAAA;AAG7C,WAAW;AACX,+BAA0G;AAAjG,sGAAA,cAAc,OAAA;AAAE,4GAAA,oBAAoB,OAAA;AAAE,6GAAA,qBAAqB,OAAA;AAAE,2GAAA,mBAAmB,OAAA;AAazF,kBAAkB;AAClB,+CAAuG;AAA9F,2GAAA,WAAW,OAAA;AAAE,iHAAA,iBAAiB,OAAA;AAAE,gHAAA,gBAAgB,OAAA;AAAE,mHAAA,mBAAmB,OAAA","sourcesContent":["/**\n * @enclave-vm/broker\n *\n * Tool broker and session management for the Enclave VM streaming runtime.\n *\n * @packageDocumentation\n */\n\n// Main Broker\nexport { Broker, createBroker } from './broker';\nexport type { BrokerConfig, ExecuteOptions } from './broker';\n\n// Tool Registry\nexport { ToolRegistry, createToolRegistry } from './tool-registry';\nexport type {\n ToolDefinition,\n ToolHandler,\n ToolContext,\n ToolValidationResult,\n ToolExecutionResult,\n} from './tool-registry';\n\n// Broker Session\nexport { BrokerSession, createBrokerSession } from './broker-session';\nexport type { BrokerSessionConfig } from './broker-session';\n\n// Session Manager\nexport { SessionManager, createSessionManager } from './session-manager';\nexport type { SessionManagerConfig, SessionInfo, CreateSessionResult } from './session-manager';\n\n// HTTP API\nexport { SessionHandler, createSessionHandler, registerExpressRoutes, createExpressRouter } from './http';\nexport type {\n SessionHandlerConfig,\n RouteHandler,\n BrokerRequest,\n BrokerResponse,\n CreateSessionRequest,\n SessionInfoResponse,\n ListSessionsResponse,\n ErrorResponse,\n StreamOptions,\n} from './http';\n\n// Event Filtering\nexport { EventFilter, createEventFilter, createTypeFilter, createContentFilter } from './event-filter';\nexport type { EventFilterOptions } from './event-filter';\n"]}
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Session Manager
3
+ *
4
+ * Manages multiple broker sessions with lifecycle management.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import type { SessionId, StreamEvent } from '@enclave-vm/types';
9
+ import type { SessionFinalResult } from '@enclave-vm/core';
10
+ import { BrokerSession } from './broker-session';
11
+ import type { BrokerSessionConfig } from './broker-session';
12
+ import type { ToolRegistry } from './tool-registry';
13
+ /**
14
+ * Session manager configuration
15
+ */
16
+ export interface SessionManagerConfig {
17
+ /**
18
+ * Maximum number of concurrent sessions
19
+ * @default 100
20
+ */
21
+ maxSessions?: number;
22
+ /**
23
+ * Interval for cleanup of expired sessions (ms)
24
+ * @default 60000
25
+ */
26
+ cleanupIntervalMs?: number;
27
+ /**
28
+ * Default session configuration
29
+ */
30
+ defaultSessionConfig?: Partial<BrokerSessionConfig>;
31
+ }
32
+ /**
33
+ * Session info for listing
34
+ */
35
+ export interface SessionInfo {
36
+ sessionId: SessionId;
37
+ state: string;
38
+ createdAt: number;
39
+ expiresAt: number;
40
+ isExpired: boolean;
41
+ }
42
+ /**
43
+ * Session creation result
44
+ */
45
+ export interface CreateSessionResult {
46
+ session: BrokerSession;
47
+ sessionId: SessionId;
48
+ }
49
+ /**
50
+ * Session Manager
51
+ *
52
+ * Manages the lifecycle of multiple broker sessions:
53
+ * - Session creation and tracking
54
+ * - Automatic cleanup of expired sessions
55
+ * - Session lookup and listing
56
+ * - Resource limits (max sessions)
57
+ */
58
+ export declare class SessionManager {
59
+ private readonly sessions;
60
+ private readonly toolRegistry;
61
+ private readonly config;
62
+ private cleanupInterval;
63
+ private disposed;
64
+ constructor(toolRegistry: ToolRegistry, config?: SessionManagerConfig);
65
+ /**
66
+ * Create a new session
67
+ *
68
+ * @throws Error if max sessions reached or manager is disposed
69
+ */
70
+ create(config?: BrokerSessionConfig): CreateSessionResult;
71
+ /**
72
+ * Get a session by ID
73
+ */
74
+ get(sessionId: SessionId): BrokerSession | undefined;
75
+ /**
76
+ * Check if a session exists
77
+ */
78
+ has(sessionId: SessionId): boolean;
79
+ /**
80
+ * List all sessions
81
+ */
82
+ list(): SessionInfo[];
83
+ /**
84
+ * List active (non-terminal) sessions
85
+ */
86
+ listActive(): SessionInfo[];
87
+ /**
88
+ * Terminate a session
89
+ */
90
+ terminate(sessionId: SessionId, reason?: string): Promise<boolean>;
91
+ /**
92
+ * Execute code in a new session and wait for completion
93
+ *
94
+ * This is a convenience method that creates a session, executes code,
95
+ * waits for completion, and cleans up.
96
+ */
97
+ executeAndWait(code: string, config?: BrokerSessionConfig, eventHandler?: (event: StreamEvent) => void): Promise<SessionFinalResult>;
98
+ /**
99
+ * Get count of active sessions
100
+ */
101
+ get activeCount(): number;
102
+ /**
103
+ * Get total session count
104
+ */
105
+ get totalCount(): number;
106
+ /**
107
+ * Clean up expired and terminal sessions
108
+ */
109
+ cleanup(): number;
110
+ /**
111
+ * Start automatic cleanup
112
+ */
113
+ private startCleanup;
114
+ /**
115
+ * Stop automatic cleanup
116
+ */
117
+ private stopCleanup;
118
+ /**
119
+ * Dispose of the manager and all sessions
120
+ */
121
+ dispose(): Promise<void>;
122
+ }
123
+ /**
124
+ * Create a new session manager
125
+ */
126
+ export declare function createSessionManager(toolRegistry: ToolRegistry, config?: SessionManagerConfig): SessionManager;
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ /**
3
+ * Session Manager
4
+ *
5
+ * Manages multiple broker sessions with lifecycle management.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.SessionManager = void 0;
11
+ exports.createSessionManager = createSessionManager;
12
+ const broker_session_1 = require("./broker-session");
13
+ /**
14
+ * Session Manager
15
+ *
16
+ * Manages the lifecycle of multiple broker sessions:
17
+ * - Session creation and tracking
18
+ * - Automatic cleanup of expired sessions
19
+ * - Session lookup and listing
20
+ * - Resource limits (max sessions)
21
+ */
22
+ class SessionManager {
23
+ sessions;
24
+ toolRegistry;
25
+ config;
26
+ cleanupInterval = null;
27
+ disposed = false;
28
+ constructor(toolRegistry, config = {}) {
29
+ this.sessions = new Map();
30
+ this.toolRegistry = toolRegistry;
31
+ this.config = {
32
+ maxSessions: config.maxSessions ?? 100,
33
+ cleanupIntervalMs: config.cleanupIntervalMs ?? 60000,
34
+ defaultSessionConfig: config.defaultSessionConfig ?? {},
35
+ };
36
+ // Start cleanup interval
37
+ this.startCleanup();
38
+ }
39
+ /**
40
+ * Create a new session
41
+ *
42
+ * @throws Error if max sessions reached or manager is disposed
43
+ */
44
+ create(config) {
45
+ if (this.disposed) {
46
+ throw new Error('Session manager is disposed');
47
+ }
48
+ if (this.sessions.size >= this.config.maxSessions) {
49
+ throw new Error(`Maximum sessions reached (${this.config.maxSessions}). ` +
50
+ 'Wait for existing sessions to complete or increase maxSessions.');
51
+ }
52
+ const sessionConfig = {
53
+ ...this.config.defaultSessionConfig,
54
+ ...config,
55
+ };
56
+ const session = (0, broker_session_1.createBrokerSession)(this.toolRegistry, sessionConfig);
57
+ this.sessions.set(session.sessionId, session);
58
+ return {
59
+ session,
60
+ sessionId: session.sessionId,
61
+ };
62
+ }
63
+ /**
64
+ * Get a session by ID
65
+ */
66
+ get(sessionId) {
67
+ return this.sessions.get(sessionId);
68
+ }
69
+ /**
70
+ * Check if a session exists
71
+ */
72
+ has(sessionId) {
73
+ return this.sessions.has(sessionId);
74
+ }
75
+ /**
76
+ * List all sessions
77
+ */
78
+ list() {
79
+ return Array.from(this.sessions.values()).map((session) => ({
80
+ sessionId: session.sessionId,
81
+ state: session.state,
82
+ createdAt: session.createdAt,
83
+ expiresAt: session.expiresAt,
84
+ isExpired: session.isExpired(),
85
+ }));
86
+ }
87
+ /**
88
+ * List active (non-terminal) sessions
89
+ */
90
+ listActive() {
91
+ return this.list().filter((info) => !['completed', 'cancelled', 'failed'].includes(info.state));
92
+ }
93
+ /**
94
+ * Terminate a session
95
+ */
96
+ async terminate(sessionId, reason) {
97
+ const session = this.sessions.get(sessionId);
98
+ if (!session) {
99
+ return false;
100
+ }
101
+ await session.cancel(reason ?? 'Terminated by session manager');
102
+ session.dispose();
103
+ this.sessions.delete(sessionId);
104
+ return true;
105
+ }
106
+ /**
107
+ * Execute code in a new session and wait for completion
108
+ *
109
+ * This is a convenience method that creates a session, executes code,
110
+ * waits for completion, and cleans up.
111
+ */
112
+ async executeAndWait(code, config, eventHandler) {
113
+ const { session, sessionId } = this.create(config);
114
+ try {
115
+ // Subscribe to events if handler provided
116
+ if (eventHandler) {
117
+ session.onEvent(eventHandler);
118
+ }
119
+ // Execute and wait
120
+ const result = await session.execute(code);
121
+ return result;
122
+ }
123
+ finally {
124
+ // Clean up
125
+ session.dispose();
126
+ this.sessions.delete(sessionId);
127
+ }
128
+ }
129
+ /**
130
+ * Get count of active sessions
131
+ */
132
+ get activeCount() {
133
+ return this.listActive().length;
134
+ }
135
+ /**
136
+ * Get total session count
137
+ */
138
+ get totalCount() {
139
+ return this.sessions.size;
140
+ }
141
+ /**
142
+ * Clean up expired and terminal sessions
143
+ */
144
+ cleanup() {
145
+ let cleaned = 0;
146
+ for (const [sessionId, session] of this.sessions) {
147
+ if (session.isExpired() || session.isTerminal()) {
148
+ session.dispose();
149
+ this.sessions.delete(sessionId);
150
+ cleaned++;
151
+ }
152
+ }
153
+ return cleaned;
154
+ }
155
+ /**
156
+ * Start automatic cleanup
157
+ */
158
+ startCleanup() {
159
+ if (this.cleanupInterval) {
160
+ return;
161
+ }
162
+ this.cleanupInterval = setInterval(() => {
163
+ this.cleanup();
164
+ }, this.config.cleanupIntervalMs);
165
+ }
166
+ /**
167
+ * Stop automatic cleanup
168
+ */
169
+ stopCleanup() {
170
+ if (this.cleanupInterval) {
171
+ clearInterval(this.cleanupInterval);
172
+ this.cleanupInterval = null;
173
+ }
174
+ }
175
+ /**
176
+ * Dispose of the manager and all sessions
177
+ */
178
+ async dispose() {
179
+ if (this.disposed) {
180
+ return;
181
+ }
182
+ this.disposed = true;
183
+ this.stopCleanup();
184
+ // Cancel and dispose all sessions
185
+ const promises = [];
186
+ for (const [_sessionId, session] of this.sessions) {
187
+ promises.push(session.cancel('Session manager disposed').catch(() => {
188
+ // Ignore cancel errors during disposal
189
+ }));
190
+ session.dispose();
191
+ }
192
+ await Promise.all(promises);
193
+ this.sessions.clear();
194
+ }
195
+ }
196
+ exports.SessionManager = SessionManager;
197
+ /**
198
+ * Create a new session manager
199
+ */
200
+ function createSessionManager(toolRegistry, config) {
201
+ return new SessionManager(toolRegistry, config);
202
+ }
203
+ //# sourceMappingURL=session-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-manager.js","sourceRoot":"","sources":["../../src/session-manager.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AA+QH,oDAEC;AA7QD,qDAAsE;AA6CtE;;;;;;;;GAQG;AACH,MAAa,cAAc;IACR,QAAQ,CAAgC;IACxC,YAAY,CAAe;IAC3B,MAAM,CAAiC;IAChD,eAAe,GAA0C,IAAI,CAAC;IAC9D,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAY,YAA0B,EAAE,SAA+B,EAAE;QACvE,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG;YACZ,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG;YACtC,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,KAAK;YACpD,oBAAoB,EAAE,MAAM,CAAC,oBAAoB,IAAI,EAAE;SACxD,CAAC;QAEF,yBAAyB;QACzB,IAAI,CAAC,YAAY,EAAE,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAA4B;QACjC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QACjD,CAAC;QAED,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;YAClD,MAAM,IAAI,KAAK,CACb,6BAA6B,IAAI,CAAC,MAAM,CAAC,WAAW,KAAK;gBACvD,iEAAiE,CACpE,CAAC;QACJ,CAAC;QAED,MAAM,aAAa,GAAG;YACpB,GAAG,IAAI,CAAC,MAAM,CAAC,oBAAoB;YACnC,GAAG,MAAM;SACV,CAAC;QA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ACxB,CAAC;CACF;AAhND,wCAgNC;AAED;;GAEG;AACH,SAAgB,oBAAoB,CAAC,YAA0B,EAAE,MAA6B;IAC5F,OAAO,IAAI,cAAc,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;AAClD,CAAC","sourcesContent":["/**\n * Session Manager\n *\n * Manages multiple broker sessions with lifecycle management.\n *\n * @packageDocumentation\n */\n\nimport type { SessionId, StreamEvent } from '@enclave-vm/types';\nimport type { SessionFinalResult } from '@enclave-vm/core';\nimport { BrokerSession, createBrokerSession } from './broker-session';\nimport type { BrokerSessionConfig } from './broker-session';\nimport type { ToolRegistry } from './tool-registry';\n\n/**\n * Session manager configuration\n */\nexport interface SessionManagerConfig {\n /**\n * Maximum number of concurrent sessions\n * @default 100\n */\n maxSessions?: number;\n\n /**\n * Interval for cleanup of expired sessions (ms)\n * @default 60000\n */\n cleanupIntervalMs?: number;\n\n /**\n * Default session configuration\n */\n defaultSessionConfig?: Partial<BrokerSessionConfig>;\n}\n\n/**\n * Session info for listing\n */\nexport interface SessionInfo {\n sessionId: SessionId;\n state: string;\n createdAt: number;\n expiresAt: number;\n isExpired: boolean;\n}\n\n/**\n * Session creation result\n */\nexport interface CreateSessionResult {\n session: BrokerSession;\n sessionId: SessionId;\n}\n\n/**\n * Session Manager\n *\n * Manages the lifecycle of multiple broker sessions:\n * - Session creation and tracking\n * - Automatic cleanup of expired sessions\n * - Session lookup and listing\n * - Resource limits (max sessions)\n */\nexport class SessionManager {\n private readonly sessions: Map<SessionId, BrokerSession>;\n private readonly toolRegistry: ToolRegistry;\n private readonly config: Required<SessionManagerConfig>;\n private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n private disposed = false;\n\n constructor(toolRegistry: ToolRegistry, config: SessionManagerConfig = {}) {\n this.sessions = new Map();\n this.toolRegistry = toolRegistry;\n this.config = {\n maxSessions: config.maxSessions ?? 100,\n cleanupIntervalMs: config.cleanupIntervalMs ?? 60000,\n defaultSessionConfig: config.defaultSessionConfig ?? {},\n };\n\n // Start cleanup interval\n this.startCleanup();\n }\n\n /**\n * Create a new session\n *\n * @throws Error if max sessions reached or manager is disposed\n */\n create(config?: BrokerSessionConfig): CreateSessionResult {\n if (this.disposed) {\n throw new Error('Session manager is disposed');\n }\n\n if (this.sessions.size >= this.config.maxSessions) {\n throw new Error(\n `Maximum sessions reached (${this.config.maxSessions}). ` +\n 'Wait for existing sessions to complete or increase maxSessions.',\n );\n }\n\n const sessionConfig = {\n ...this.config.defaultSessionConfig,\n ...config,\n };\n\n const session = createBrokerSession(this.toolRegistry, sessionConfig);\n this.sessions.set(session.sessionId, session);\n\n return {\n session,\n sessionId: session.sessionId,\n };\n }\n\n /**\n * Get a session by ID\n */\n get(sessionId: SessionId): BrokerSession | undefined {\n return this.sessions.get(sessionId);\n }\n\n /**\n * Check if a session exists\n */\n has(sessionId: SessionId): boolean {\n return this.sessions.has(sessionId);\n }\n\n /**\n * List all sessions\n */\n list(): SessionInfo[] {\n return Array.from(this.sessions.values()).map((session) => ({\n sessionId: session.sessionId,\n state: session.state,\n createdAt: session.createdAt,\n expiresAt: session.expiresAt,\n isExpired: session.isExpired(),\n }));\n }\n\n /**\n * List active (non-terminal) sessions\n */\n listActive(): SessionInfo[] {\n return this.list().filter((info) => !['completed', 'cancelled', 'failed'].includes(info.state));\n }\n\n /**\n * Terminate a session\n */\n async terminate(sessionId: SessionId, reason?: string): Promise<boolean> {\n const session = this.sessions.get(sessionId);\n if (!session) {\n return false;\n }\n\n await session.cancel(reason ?? 'Terminated by session manager');\n session.dispose();\n this.sessions.delete(sessionId);\n return true;\n }\n\n /**\n * Execute code in a new session and wait for completion\n *\n * This is a convenience method that creates a session, executes code,\n * waits for completion, and cleans up.\n */\n async executeAndWait(\n code: string,\n config?: BrokerSessionConfig,\n eventHandler?: (event: StreamEvent) => void,\n ): Promise<SessionFinalResult> {\n const { session, sessionId } = this.create(config);\n\n try {\n // Subscribe to events if handler provided\n if (eventHandler) {\n session.onEvent(eventHandler);\n }\n\n // Execute and wait\n const result = await session.execute(code);\n return result;\n } finally {\n // Clean up\n session.dispose();\n this.sessions.delete(sessionId);\n }\n }\n\n /**\n * Get count of active sessions\n */\n get activeCount(): number {\n return this.listActive().length;\n }\n\n /**\n * Get total session count\n */\n get totalCount(): number {\n return this.sessions.size;\n }\n\n /**\n * Clean up expired and terminal sessions\n */\n cleanup(): number {\n let cleaned = 0;\n\n for (const [sessionId, session] of this.sessions) {\n if (session.isExpired() || session.isTerminal()) {\n session.dispose();\n this.sessions.delete(sessionId);\n cleaned++;\n }\n }\n\n return cleaned;\n }\n\n /**\n * Start automatic cleanup\n */\n private startCleanup(): void {\n if (this.cleanupInterval) {\n return;\n }\n\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, this.config.cleanupIntervalMs);\n }\n\n /**\n * Stop automatic cleanup\n */\n private stopCleanup(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n\n /**\n * Dispose of the manager and all sessions\n */\n async dispose(): Promise<void> {\n if (this.disposed) {\n return;\n }\n\n this.disposed = true;\n this.stopCleanup();\n\n // Cancel and dispose all sessions\n const promises: Promise<void>[] = [];\n for (const [_sessionId, session] of this.sessions) {\n promises.push(\n session.cancel('Session manager disposed').catch(() => {\n // Ignore cancel errors during disposal\n }),\n );\n session.dispose();\n }\n\n await Promise.all(promises);\n this.sessions.clear();\n }\n}\n\n/**\n * Create a new session manager\n */\nexport function createSessionManager(toolRegistry: ToolRegistry, config?: SessionManagerConfig): SessionManager {\n return new SessionManager(toolRegistry, config);\n}\n"]}
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Tool Registry
3
+ *
4
+ * Manages tool definitions with Zod validation for the broker.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import { z } from 'zod';
9
+ import type { ToolConfig } from '@enclave-vm/types';
10
+ /**
11
+ * Tool definition for registration
12
+ */
13
+ export interface ToolDefinition<TArgs = unknown, TResult = unknown> {
14
+ /**
15
+ * Tool name (must be unique)
16
+ */
17
+ name: string;
18
+ /**
19
+ * Tool description for documentation
20
+ */
21
+ description?: string;
22
+ /**
23
+ * Zod schema for argument validation
24
+ */
25
+ argsSchema?: z.ZodType<TArgs>;
26
+ /**
27
+ * Tool handler function
28
+ */
29
+ handler: ToolHandler<TArgs, TResult>;
30
+ /**
31
+ * Tool configuration
32
+ */
33
+ config?: ToolConfig;
34
+ /**
35
+ * Required secrets (keys from secret store)
36
+ */
37
+ secrets?: string[];
38
+ }
39
+ /**
40
+ * Tool handler function type
41
+ */
42
+ export type ToolHandler<TArgs = unknown, TResult = unknown> = (args: TArgs, context: ToolContext) => Promise<TResult>;
43
+ /**
44
+ * Context provided to tool handlers
45
+ */
46
+ export interface ToolContext {
47
+ /**
48
+ * Session ID
49
+ */
50
+ sessionId: string;
51
+ /**
52
+ * Call ID for this invocation
53
+ */
54
+ callId: string;
55
+ /**
56
+ * Resolved secrets
57
+ */
58
+ secrets: Record<string, string>;
59
+ /**
60
+ * Abort signal for cancellation
61
+ */
62
+ signal: AbortSignal;
63
+ }
64
+ /**
65
+ * Tool validation result
66
+ */
67
+ export interface ToolValidationResult {
68
+ success: boolean;
69
+ error?: string;
70
+ validatedArgs?: unknown;
71
+ }
72
+ /**
73
+ * Tool execution result
74
+ */
75
+ export interface ToolExecutionResult<T = unknown> {
76
+ success: boolean;
77
+ value?: T;
78
+ error?: {
79
+ code: string;
80
+ message: string;
81
+ data?: Record<string, unknown>;
82
+ };
83
+ durationMs: number;
84
+ }
85
+ /**
86
+ * Tool Registry
87
+ *
88
+ * Manages tool definitions and provides:
89
+ * - Tool registration with Zod schema validation
90
+ * - Argument validation before execution
91
+ * - Tool invocation with context
92
+ */
93
+ export declare class ToolRegistry {
94
+ private readonly tools;
95
+ private readonly secretStore;
96
+ constructor();
97
+ /**
98
+ * Register a tool
99
+ *
100
+ * @throws Error if tool with same name already exists
101
+ */
102
+ register<TArgs = unknown, TResult = unknown>(definition: ToolDefinition<TArgs, TResult>): void;
103
+ /**
104
+ * Unregister a tool
105
+ *
106
+ * @returns true if tool was removed, false if not found
107
+ */
108
+ unregister(name: string): boolean;
109
+ /**
110
+ * Check if a tool is registered
111
+ */
112
+ has(name: string): boolean;
113
+ /**
114
+ * Get a tool definition
115
+ */
116
+ get(name: string): ToolDefinition | undefined;
117
+ /**
118
+ * List all registered tool names
119
+ */
120
+ list(): string[];
121
+ /**
122
+ * Get tool configurations for all registered tools
123
+ */
124
+ getConfigs(): Record<string, ToolConfig>;
125
+ /**
126
+ * Validate tool arguments
127
+ */
128
+ validate(name: string, args: unknown): ToolValidationResult;
129
+ /**
130
+ * Set a secret value
131
+ */
132
+ setSecret(key: string, value: string): void;
133
+ /**
134
+ * Remove a secret
135
+ */
136
+ removeSecret(key: string): boolean;
137
+ /**
138
+ * Check if a secret exists
139
+ */
140
+ hasSecret(key: string): boolean;
141
+ /**
142
+ * Get required secrets for a tool
143
+ */
144
+ getRequiredSecrets(name: string): string[];
145
+ /**
146
+ * Resolve secrets for a tool
147
+ *
148
+ * @throws Error if required secret is missing
149
+ */
150
+ private resolveSecrets;
151
+ /**
152
+ * Execute a tool
153
+ */
154
+ execute<T = unknown>(name: string, args: unknown, context: Omit<ToolContext, 'secrets'>): Promise<ToolExecutionResult<T>>;
155
+ /**
156
+ * Clear all registered tools
157
+ */
158
+ clear(): void;
159
+ /**
160
+ * Clear all secrets
161
+ */
162
+ clearSecrets(): void;
163
+ /**
164
+ * Get count of registered tools
165
+ */
166
+ get size(): number;
167
+ }
168
+ /**
169
+ * Create a new tool registry
170
+ */
171
+ export declare function createToolRegistry(): ToolRegistry;