@enclave-vm/runtime 0.0.1 → 2.9.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.
@@ -1,111 +0,0 @@
1
- "use strict";
2
- /**
3
- * In-Memory Channel
4
- *
5
- * Simple in-process channel for testing and embedded use.
6
- *
7
- * @packageDocumentation
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.MemoryChannel = void 0;
11
- exports.createMemoryChannel = createMemoryChannel;
12
- exports.createMemoryChannelPair = createMemoryChannelPair;
13
- /**
14
- * In-memory channel implementation
15
- *
16
- * Provides a simple channel that stores events in memory.
17
- * Useful for testing and embedded runtime scenarios.
18
- */
19
- class MemoryChannel {
20
- eventQueue = [];
21
- messageHandlers = new Set();
22
- _isOpen = true;
23
- /**
24
- * Whether the channel is open
25
- */
26
- get isOpen() {
27
- return this._isOpen;
28
- }
29
- /**
30
- * Send a stream event
31
- */
32
- send(event) {
33
- if (!this._isOpen) {
34
- throw new Error('Channel is closed');
35
- }
36
- this.eventQueue.push(event);
37
- }
38
- /**
39
- * Get all queued events
40
- */
41
- getEvents() {
42
- return [...this.eventQueue];
43
- }
44
- /**
45
- * Clear the event queue
46
- */
47
- clearEvents() {
48
- this.eventQueue.length = 0;
49
- }
50
- /**
51
- * Receive messages
52
- */
53
- onMessage(handler) {
54
- this.messageHandlers.add(handler);
55
- return () => {
56
- this.messageHandlers.delete(handler);
57
- };
58
- }
59
- /**
60
- * Inject a message (simulate incoming message)
61
- */
62
- injectMessage(message) {
63
- if (!this._isOpen) {
64
- throw new Error('Channel is closed');
65
- }
66
- for (const handler of this.messageHandlers) {
67
- handler(message);
68
- }
69
- }
70
- /**
71
- * Close the channel
72
- */
73
- close() {
74
- this._isOpen = false;
75
- this.messageHandlers.clear();
76
- }
77
- }
78
- exports.MemoryChannel = MemoryChannel;
79
- /**
80
- * Create a memory channel
81
- */
82
- function createMemoryChannel() {
83
- return new MemoryChannel();
84
- }
85
- /**
86
- * Create a pair of connected memory channels
87
- *
88
- * Messages sent to one channel are received by the other.
89
- * Useful for simulating bidirectional communication.
90
- */
91
- function createMemoryChannelPair() {
92
- const client = new MemoryChannel();
93
- const server = new MemoryChannel();
94
- // Connect them bidirectionally
95
- // When client sends, server receives
96
- const originalClientSend = client.send.bind(client);
97
- client.send = (event) => {
98
- originalClientSend(event);
99
- // Forward to server's message handlers
100
- server.injectMessage(event);
101
- };
102
- // When server sends, client receives
103
- const originalServerSend = server.send.bind(server);
104
- server.send = (event) => {
105
- originalServerSend(event);
106
- // Forward to client's message handlers
107
- client.injectMessage(event);
108
- };
109
- return { client, server };
110
- }
111
- //# sourceMappingURL=memory-channel.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"memory-channel.js","sourceRoot":"","sources":["../../../src/channels/memory-channel.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAiFH,kDAEC;AAQD,0DAyBC;AA/GD;;;;;GAKG;AACH,MAAa,aAAa;IACP,UAAU,GAAkB,EAAE,CAAC;IAC/B,eAAe,GAAkD,IAAI,GAAG,EAAE,CAAC;IACpF,OAAO,GAAG,IAAI,CAAC;IAEvB;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,KAAkB;QACrB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACvC,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,SAAS;QACP,OAAO,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,WAAW;QACT,IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;IAC7B,CAAC;IAED;;OAEG;IACH,SAAS,CAAC,OAAiD;QACzD,I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QACnC,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAC1B,uCAAuC;QACvC,MAAM,CAAC,aAAa,CAAC,KAAyC,CAAC,CAAC;IAClE,CAAC,CAAC;IAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * In-Memory Channel\n *\n * Simple in-process channel for testing and embedded use.\n *\n * @packageDocumentation\n */\n\nimport type { StreamEvent, RuntimeChannelMessage } from '@enclave-vm/types';\nimport type { RuntimeChannel } from '../types';\n\n/**\n * In-memory channel implementation\n *\n * Provides a simple channel that stores events in memory.\n * Useful for testing and embedded runtime scenarios.\n */\nexport class MemoryChannel implements RuntimeChannel {\n private readonly eventQueue: StreamEvent[] = [];\n private readonly messageHandlers: Set<(message: RuntimeChannelMessage) => void> = new Set();\n private _isOpen = true;\n\n /**\n * Whether the channel is open\n */\n get isOpen(): boolean {\n return this._isOpen;\n }\n\n /**\n * Send a stream event\n */\n send(event: StreamEvent): void {\n if (!this._isOpen) {\n throw new Error('Channel is closed');\n }\n this.eventQueue.push(event);\n }\n\n /**\n * Get all queued events\n */\n getEvents(): StreamEvent[] {\n return [...this.eventQueue];\n }\n\n /**\n * Clear the event queue\n */\n clearEvents(): void {\n this.eventQueue.length = 0;\n }\n\n /**\n * Receive messages\n */\n onMessage(handler: (message: RuntimeChannelMessage) => void): () => void {\n this.messageHandlers.add(handler);\n return () => {\n this.messageHandlers.delete(handler);\n };\n }\n\n /**\n * Inject a message (simulate incoming message)\n */\n injectMessage(message: RuntimeChannelMessage): void {\n if (!this._isOpen) {\n throw new Error('Channel is closed');\n }\n for (const handler of this.messageHandlers) {\n handler(message);\n }\n }\n\n /**\n * Close the channel\n */\n close(): void {\n this._isOpen = false;\n this.messageHandlers.clear();\n }\n}\n\n/**\n * Create a memory channel\n */\nexport function createMemoryChannel(): MemoryChannel {\n return new MemoryChannel();\n}\n\n/**\n * Create a pair of connected memory channels\n *\n * Messages sent to one channel are received by the other.\n * Useful for simulating bidirectional communication.\n */\nexport function createMemoryChannelPair(): {\n client: MemoryChannel;\n server: MemoryChannel;\n} {\n const client = new MemoryChannel();\n const server = new MemoryChannel();\n\n // Connect them bidirectionally\n // When client sends, server receives\n const originalClientSend = client.send.bind(client);\n client.send = (event: StreamEvent) => {\n originalClientSend(event);\n // Forward to server's message handlers\n server.injectMessage(event as unknown as RuntimeChannelMessage);\n };\n\n // When server sends, client receives\n const originalServerSend = server.send.bind(server);\n server.send = (event: StreamEvent) => {\n originalServerSend(event);\n // Forward to client's message handlers\n client.injectMessage(event as unknown as RuntimeChannelMessage);\n };\n\n return { client, server };\n}\n"]}
@@ -1,208 +0,0 @@
1
- "use strict";
2
- /**
3
- * WebSocket Channel
4
- *
5
- * WebSocket-based channel for remote runtime communication.
6
- *
7
- * @packageDocumentation
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.WebSocketChannel = void 0;
11
- exports.createWebSocketChannel = createWebSocketChannel;
12
- const stream_1 = require("@enclave-vm/stream");
13
- /**
14
- * WebSocket channel implementation
15
- *
16
- * Provides a channel over WebSocket for remote runtime communication.
17
- */
18
- class WebSocketChannel {
19
- config;
20
- ws = null;
21
- state = 'disconnected';
22
- messageHandlers = new Set();
23
- retryCount = 0;
24
- retryTimeout = null;
25
- messageBuffer = [];
26
- constructor(config) {
27
- this.config = {
28
- url: config.url,
29
- reconnect: {
30
- enabled: config.reconnect?.enabled ?? true,
31
- maxRetries: config.reconnect?.maxRetries ?? 5,
32
- initialDelayMs: config.reconnect?.initialDelayMs ?? 1000,
33
- maxDelayMs: config.reconnect?.maxDelayMs ?? 30000,
34
- },
35
- connectionTimeoutMs: config.connectionTimeoutMs ?? 10000,
36
- debug: config.debug ?? false,
37
- };
38
- }
39
- /**
40
- * Whether the channel is open
41
- */
42
- get isOpen() {
43
- return this.state === 'connected';
44
- }
45
- /**
46
- * Get current state
47
- */
48
- get channelState() {
49
- return this.state;
50
- }
51
- /**
52
- * Connect to the WebSocket server
53
- */
54
- async connect() {
55
- if (this.state === 'connected' || this.state === 'connecting') {
56
- return;
57
- }
58
- return new Promise((resolve, reject) => {
59
- this.state = 'connecting';
60
- this.log(`Connecting to ${this.config.url}`);
61
- // Create WebSocket (works in both browser and Node.js with ws package)
62
- const WebSocketImpl = typeof WebSocket !== 'undefined' ? WebSocket : require('ws');
63
- const socket = new WebSocketImpl(this.config.url);
64
- this.ws = socket;
65
- const timeout = setTimeout(() => {
66
- if (this.state === 'connecting') {
67
- socket.close();
68
- reject(new Error('Connection timeout'));
69
- }
70
- }, this.config.connectionTimeoutMs);
71
- socket.onopen = () => {
72
- clearTimeout(timeout);
73
- this.state = 'connected';
74
- this.retryCount = 0;
75
- this.log('Connected');
76
- // Send buffered messages
77
- this.flushBuffer();
78
- resolve();
79
- };
80
- socket.onclose = (event) => {
81
- clearTimeout(timeout);
82
- this.log(`Disconnected: ${event.code} ${event.reason}`);
83
- if (this.state !== 'closed') {
84
- this.state = 'disconnected';
85
- this.handleDisconnect();
86
- }
87
- };
88
- socket.onerror = (error) => {
89
- clearTimeout(timeout);
90
- this.log(`Error: ${error}`);
91
- if (this.state === 'connecting') {
92
- reject(new Error('Connection failed'));
93
- }
94
- };
95
- socket.onmessage = (event) => {
96
- this.handleMessage(event.data);
97
- };
98
- });
99
- }
100
- /**
101
- * Send a stream event
102
- */
103
- send(event) {
104
- const data = (0, stream_1.serializeEvent)(event);
105
- if (this.isOpen && this.ws) {
106
- this.ws.send(data);
107
- }
108
- else {
109
- // Buffer message for later
110
- this.messageBuffer.push(data);
111
- }
112
- }
113
- /**
114
- * Receive messages
115
- */
116
- onMessage(handler) {
117
- this.messageHandlers.add(handler);
118
- return () => {
119
- this.messageHandlers.delete(handler);
120
- };
121
- }
122
- /**
123
- * Close the channel
124
- */
125
- close() {
126
- this.state = 'closed';
127
- if (this.retryTimeout) {
128
- clearTimeout(this.retryTimeout);
129
- this.retryTimeout = null;
130
- }
131
- if (this.ws) {
132
- this.ws.close(1000, 'Channel closed');
133
- this.ws = null;
134
- }
135
- this.messageHandlers.clear();
136
- this.messageBuffer = [];
137
- }
138
- /**
139
- * Handle incoming message
140
- */
141
- handleMessage(data) {
142
- try {
143
- // Parse JSON directly - messages can be raw JSON or stream events
144
- const message = JSON.parse(data);
145
- for (const handler of this.messageHandlers) {
146
- try {
147
- handler(message);
148
- }
149
- catch (error) {
150
- this.log(`Message handler error: ${error}`);
151
- }
152
- }
153
- }
154
- catch (error) {
155
- this.log(`Failed to parse message: ${error}`);
156
- }
157
- }
158
- /**
159
- * Handle disconnect
160
- */
161
- handleDisconnect() {
162
- if (!this.config.reconnect.enabled) {
163
- return;
164
- }
165
- if (this.retryCount >= this.config.reconnect.maxRetries) {
166
- this.log('Max reconnection attempts reached');
167
- this.state = 'closed';
168
- return;
169
- }
170
- this.state = 'reconnecting';
171
- this.retryCount++;
172
- const delay = Math.min(this.config.reconnect.initialDelayMs * Math.pow(2, this.retryCount - 1), this.config.reconnect.maxDelayMs);
173
- this.log(`Reconnecting in ${delay}ms (attempt ${this.retryCount})`);
174
- this.retryTimeout = setTimeout(() => {
175
- this.connect().catch((error) => {
176
- this.log(`Reconnection failed: ${error}`);
177
- });
178
- }, delay);
179
- }
180
- /**
181
- * Flush message buffer
182
- */
183
- flushBuffer() {
184
- if (!this.isOpen || !this.ws) {
185
- return;
186
- }
187
- for (const data of this.messageBuffer) {
188
- this.ws.send(data);
189
- }
190
- this.messageBuffer = [];
191
- }
192
- /**
193
- * Log debug message
194
- */
195
- log(message) {
196
- if (this.config.debug) {
197
- console.log(`[WebSocketChannel] ${message}`);
198
- }
199
- }
200
- }
201
- exports.WebSocketChannel = WebSocketChannel;
202
- /**
203
- * Create a WebSocket channel
204
- */
205
- function createWebSocketChannel(config) {
206
- return new WebSocketChannel(config);
207
- }
208
- //# sourceMappingURL=websocket-channel.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"websocket-channel.js","sourceRoot":"","sources":["../../../src/channels/websocket-channel.ts"],"names":[],"mappings":";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Socket Channel\n *\n * WebSocket-based channel for remote runtime communication.\n *\n * @packageDocumentation\n */\n\nimport type { StreamEvent, RuntimeChannelMessage } from '@enclave-vm/types';\nimport { serializeEvent } from '@enclave-vm/stream';\nimport type { RuntimeChannel } from '../types';\n\n/**\n * WebSocket channel configuration\n */\nexport interface WebSocketChannelConfig {\n /**\n * WebSocket URL to connect to\n */\n url: string;\n\n /**\n * Reconnection options\n */\n reconnect?: {\n enabled?: boolean;\n maxRetries?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n };\n\n /**\n * Connection timeout in milliseconds\n * @default 10000\n */\n connectionTimeoutMs?: number;\n\n /**\n * Debug mode\n */\n debug?: boolean;\n}\n\n/**\n * Internal resolved configuration type\n */\ninterface ResolvedConfig {\n url: string;\n reconnect: {\n enabled: boolean;\n maxRetries: number;\n initialDelayMs: number;\n maxDelayMs: number;\n };\n connectionTimeoutMs: number;\n debug: boolean;\n}\n\n/**\n * WebSocket channel state\n */\nexport type WebSocketChannelState = 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'closed';\n\n/**\n * WebSocket channel implementation\n *\n * Provides a channel over WebSocket for remote runtime communication.\n */\nexport class WebSocketChannel implements RuntimeChannel {\n private readonly config: ResolvedConfig;\n private ws: WebSocket | null = null;\n private state: WebSocketChannelState = 'disconnected';\n private readonly messageHandlers: Set<(message: RuntimeChannelMessage) => void> = new Set();\n private retryCount = 0;\n private retryTimeout: ReturnType<typeof setTimeout> | null = null;\n private messageBuffer: string[] = [];\n\n constructor(config: WebSocketChannelConfig) {\n this.config = {\n url: config.url,\n reconnect: {\n enabled: config.reconnect?.enabled ?? true,\n maxRetries: config.reconnect?.maxRetries ?? 5,\n initialDelayMs: config.reconnect?.initialDelayMs ?? 1000,\n maxDelayMs: config.reconnect?.maxDelayMs ?? 30000,\n },\n connectionTimeoutMs: config.connectionTimeoutMs ?? 10000,\n debug: config.debug ?? false,\n };\n }\n\n /**\n * Whether the channel is open\n */\n get isOpen(): boolean {\n return this.state === 'connected';\n }\n\n /**\n * Get current state\n */\n get channelState(): WebSocketChannelState {\n return this.state;\n }\n\n /**\n * Connect to the WebSocket server\n */\n async connect(): Promise<void> {\n if (this.state === 'connected' || this.state === 'connecting') {\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.state = 'connecting';\n this.log(`Connecting to ${this.config.url}`);\n\n // Create WebSocket (works in both browser and Node.js with ws package)\n const WebSocketImpl = typeof WebSocket !== 'undefined' ? WebSocket : require('ws');\n\n const socket: WebSocket = new WebSocketImpl(this.config.url);\n this.ws = socket;\n\n const timeout = setTimeout(() => {\n if (this.state === 'connecting') {\n socket.close();\n reject(new Error('Connection timeout'));\n }\n }, this.config.connectionTimeoutMs);\n\n socket.onopen = () => {\n clearTimeout(timeout);\n this.state = 'connected';\n this.retryCount = 0;\n this.log('Connected');\n\n // Send buffered messages\n this.flushBuffer();\n\n resolve();\n };\n\n socket.onclose = (event: CloseEvent) => {\n clearTimeout(timeout);\n this.log(`Disconnected: ${event.code} ${event.reason}`);\n\n if (this.state !== 'closed') {\n this.state = 'disconnected';\n this.handleDisconnect();\n }\n };\n\n socket.onerror = (error: Event) => {\n clearTimeout(timeout);\n this.log(`Error: ${error}`);\n\n if (this.state === 'connecting') {\n reject(new Error('Connection failed'));\n }\n };\n\n socket.onmessage = (event: MessageEvent) => {\n this.handleMessage(event.data as string);\n };\n });\n }\n\n /**\n * Send a stream event\n */\n send(event: StreamEvent): void {\n const data = serializeEvent(event);\n\n if (this.isOpen && this.ws) {\n this.ws.send(data);\n } else {\n // Buffer message for later\n this.messageBuffer.push(data);\n }\n }\n\n /**\n * Receive messages\n */\n onMessage(handler: (message: RuntimeChannelMessage) => void): () => void {\n this.messageHandlers.add(handler);\n return () => {\n this.messageHandlers.delete(handler);\n };\n }\n\n /**\n * Close the channel\n */\n close(): void {\n this.state = 'closed';\n\n if (this.retryTimeout) {\n clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n\n if (this.ws) {\n this.ws.close(1000, 'Channel closed');\n this.ws = null;\n }\n\n this.messageHandlers.clear();\n this.messageBuffer = [];\n }\n\n /**\n * Handle incoming message\n */\n private handleMessage(data: string): void {\n try {\n // Parse JSON directly - messages can be raw JSON or stream events\n const message = JSON.parse(data) as RuntimeChannelMessage;\n\n for (const handler of this.messageHandlers) {\n try {\n handler(message);\n } catch (error) {\n this.log(`Message handler error: ${error}`);\n }\n }\n } catch (error) {\n this.log(`Failed to parse message: ${error}`);\n }\n }\n\n /**\n * Handle disconnect\n */\n private handleDisconnect(): void {\n if (!this.config.reconnect.enabled) {\n return;\n }\n\n if (this.retryCount >= this.config.reconnect.maxRetries) {\n this.log('Max reconnection attempts reached');\n this.state = 'closed';\n return;\n }\n\n this.state = 'reconnecting';\n this.retryCount++;\n\n const delay = Math.min(\n this.config.reconnect.initialDelayMs * Math.pow(2, this.retryCount - 1),\n this.config.reconnect.maxDelayMs,\n );\n\n this.log(`Reconnecting in ${delay}ms (attempt ${this.retryCount})`);\n\n this.retryTimeout = setTimeout(() => {\n this.connect().catch((error) => {\n this.log(`Reconnection failed: ${error}`);\n });\n }, delay);\n }\n\n /**\n * Flush message buffer\n */\n private flushBuffer(): void {\n if (!this.isOpen || !this.ws) {\n return;\n }\n\n for (const data of this.messageBuffer) {\n this.ws.send(data);\n }\n this.messageBuffer = [];\n }\n\n /**\n * Log debug message\n */\n private log(message: string): void {\n if (this.config.debug) {\n console.log(`[WebSocketChannel] ${message}`);\n }\n }\n}\n\n/**\n * Create a WebSocket channel\n */\nexport function createWebSocketChannel(config: WebSocketChannelConfig): WebSocketChannel {\n return new WebSocketChannel(config);\n}\n"]}
package/src/cli.js DELETED
@@ -1,121 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /**
4
- * Enclave Runtime CLI
5
- *
6
- * Standalone runtime worker that can be deployed independently.
7
- *
8
- * Usage:
9
- * npx enclave-runtime [options]
10
- *
11
- * Options:
12
- * --port <port> Port to listen on (default: 3001)
13
- * --host <host> Host to bind to (default: 0.0.0.0)
14
- * --max-sessions <n> Maximum concurrent sessions (default: 10)
15
- * --debug Enable debug logging
16
- * --help Show help
17
- *
18
- * @packageDocumentation
19
- */
20
- Object.defineProperty(exports, "__esModule", { value: true });
21
- const runtime_worker_1 = require("./runtime-worker");
22
- /**
23
- * Parse command line arguments
24
- */
25
- function parseArgs(args) {
26
- const config = {};
27
- for (let i = 0; i < args.length; i++) {
28
- const arg = args[i];
29
- switch (arg) {
30
- case '--port':
31
- config.port = parseInt(args[++i], 10);
32
- break;
33
- case '--host':
34
- config.host = args[++i];
35
- break;
36
- case '--max-sessions':
37
- config.maxSessions = parseInt(args[++i], 10);
38
- break;
39
- case '--debug':
40
- config.debug = true;
41
- break;
42
- case '--help':
43
- case '-h':
44
- printHelp();
45
- process.exit(0);
46
- break;
47
- default:
48
- if (arg.startsWith('-')) {
49
- console.error(`Unknown option: ${arg}`);
50
- process.exit(1);
51
- }
52
- }
53
- }
54
- return config;
55
- }
56
- /**
57
- * Print help message
58
- */
59
- function printHelp() {
60
- console.log(`
61
- Enclave Runtime Worker
62
-
63
- Usage:
64
- npx enclave-runtime [options]
65
-
66
- Options:
67
- --port <port> Port to listen on (default: 3001)
68
- --host <host> Host to bind to (default: 0.0.0.0)
69
- --max-sessions <n> Maximum concurrent sessions (default: 10)
70
- --debug Enable debug logging
71
- --help, -h Show this help message
72
-
73
- Examples:
74
- npx enclave-runtime --port 3001
75
- npx enclave-runtime --port 8080 --max-sessions 20 --debug
76
- `);
77
- }
78
- /**
79
- * Main entry point
80
- */
81
- async function main() {
82
- const args = process.argv.slice(2);
83
- const config = parseArgs(args);
84
- console.log('Starting Enclave Runtime Worker...');
85
- console.log(` Port: ${config.port ?? 3001}`);
86
- console.log(` Host: ${config.host ?? '0.0.0.0'}`);
87
- console.log(` Max Sessions: ${config.maxSessions ?? 10}`);
88
- console.log(` Debug: ${config.debug ?? false}`);
89
- const worker = (0, runtime_worker_1.createRuntimeWorker)(config);
90
- // Handle shutdown signals
91
- const shutdown = async (signal) => {
92
- console.log(`\nReceived ${signal}, shutting down...`);
93
- await worker.stop();
94
- console.log('Runtime stopped');
95
- process.exit(0);
96
- };
97
- process.on('SIGINT', () => shutdown('SIGINT'));
98
- process.on('SIGTERM', () => shutdown('SIGTERM'));
99
- // Start the worker
100
- await worker.start();
101
- console.log('Runtime worker is running');
102
- console.log(` PID: ${process.pid}`);
103
- // Print stats periodically
104
- if (config.debug) {
105
- setInterval(() => {
106
- const stats = worker.getStats();
107
- console.log('Stats:', {
108
- activeSessions: stats.activeSessions,
109
- totalSessions: stats.totalSessions,
110
- uptimeMs: stats.uptimeMs,
111
- memoryMB: Math.round(stats.memoryUsage.heapUsed / 1024 / 1024),
112
- });
113
- }, 30000);
114
- }
115
- }
116
- // Run main
117
- main().catch((error) => {
118
- console.error('Failed to start runtime:', error);
119
- process.exit(1);
120
- });
121
- //# sourceMappingURL=cli.js.map
package/src/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":";;AACA;;;;;;;;;;;;;;;;GAgBG;;AAEH,qDAAuD;AAGvD;;GAEG;AACH,SAAS,SAAS,CAAC,IAAc;IAC/B,MAAM,MAAM,GAAkB,EAAE,CAAC;IAEjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAEpB,QAAQ,GAAG,EAAE,CAAC;YACZ,KAAK,QAAQ;gBACX,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;gBACtC,MAAM;YAER,KAAK,QAAQ;gBACX,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;gBACxB,MAAM;YAER,KAAK,gBAAgB;gBACnB,MA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AE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;IACjD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * Enclave Runtime CLI\n *\n * Standalone runtime worker that can be deployed independently.\n *\n * Usage:\n * npx enclave-runtime [options]\n *\n * Options:\n * --port <port> Port to listen on (default: 3001)\n * --host <host> Host to bind to (default: 0.0.0.0)\n * --max-sessions <n> Maximum concurrent sessions (default: 10)\n * --debug Enable debug logging\n * --help Show help\n *\n * @packageDocumentation\n */\n\nimport { createRuntimeWorker } from './runtime-worker';\nimport type { RuntimeConfig } from './types';\n\n/**\n * Parse command line arguments\n */\nfunction parseArgs(args: string[]): RuntimeConfig {\n const config: RuntimeConfig = {};\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n\n switch (arg) {\n case '--port':\n config.port = parseInt(args[++i], 10);\n break;\n\n case '--host':\n config.host = args[++i];\n break;\n\n case '--max-sessions':\n config.maxSessions = parseInt(args[++i], 10);\n break;\n\n case '--debug':\n config.debug = true;\n break;\n\n case '--help':\n case '-h':\n printHelp();\n process.exit(0);\n break;\n\n default:\n if (arg.startsWith('-')) {\n console.error(`Unknown option: ${arg}`);\n process.exit(1);\n }\n }\n }\n\n return config;\n}\n\n/**\n * Print help message\n */\nfunction printHelp(): void {\n console.log(`\nEnclave Runtime Worker\n\nUsage:\n npx enclave-runtime [options]\n\nOptions:\n --port <port> Port to listen on (default: 3001)\n --host <host> Host to bind to (default: 0.0.0.0)\n --max-sessions <n> Maximum concurrent sessions (default: 10)\n --debug Enable debug logging\n --help, -h Show this help message\n\nExamples:\n npx enclave-runtime --port 3001\n npx enclave-runtime --port 8080 --max-sessions 20 --debug\n`);\n}\n\n/**\n * Main entry point\n */\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n const config = parseArgs(args);\n\n console.log('Starting Enclave Runtime Worker...');\n console.log(` Port: ${config.port ?? 3001}`);\n console.log(` Host: ${config.host ?? '0.0.0.0'}`);\n console.log(` Max Sessions: ${config.maxSessions ?? 10}`);\n console.log(` Debug: ${config.debug ?? false}`);\n\n const worker = createRuntimeWorker(config);\n\n // Handle shutdown signals\n const shutdown = async (signal: string) => {\n console.log(`\\nReceived ${signal}, shutting down...`);\n await worker.stop();\n console.log('Runtime stopped');\n process.exit(0);\n };\n\n process.on('SIGINT', () => shutdown('SIGINT'));\n process.on('SIGTERM', () => shutdown('SIGTERM'));\n\n // Start the worker\n await worker.start();\n\n console.log('Runtime worker is running');\n console.log(` PID: ${process.pid}`);\n\n // Print stats periodically\n if (config.debug) {\n setInterval(() => {\n const stats = worker.getStats();\n console.log('Stats:', {\n activeSessions: stats.activeSessions,\n totalSessions: stats.totalSessions,\n uptimeMs: stats.uptimeMs,\n memoryMB: Math.round(stats.memoryUsage.heapUsed / 1024 / 1024),\n });\n }, 30000);\n }\n}\n\n// Run main\nmain().catch((error) => {\n console.error('Failed to start runtime:', error);\n process.exit(1);\n});\n"]}
package/src/index.js DELETED
@@ -1,41 +0,0 @@
1
- "use strict";
2
- /**
3
- * @enclave-vm/runtime
4
- *
5
- * Standalone runtime worker for EnclaveJS.
6
- * Can be deployed as a separate process/worker for distributed execution.
7
- *
8
- * @example
9
- * ```typescript
10
- * import { createRuntimeWorker } from '@enclave-vm/runtime';
11
- *
12
- * const worker = createRuntimeWorker({
13
- * port: 3001,
14
- * maxSessions: 10,
15
- * debug: true,
16
- * });
17
- *
18
- * await worker.start();
19
- * console.log('Runtime is ready!');
20
- * ```
21
- *
22
- * @packageDocumentation
23
- */
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.createWebSocketChannel = exports.WebSocketChannel = exports.createMemoryChannelPair = exports.createMemoryChannel = exports.MemoryChannel = exports.createSessionExecutor = exports.SessionExecutor = exports.createRuntimeWorker = exports.RuntimeWorkerImpl = void 0;
26
- // Runtime worker
27
- var runtime_worker_1 = require("./runtime-worker");
28
- Object.defineProperty(exports, "RuntimeWorkerImpl", { enumerable: true, get: function () { return runtime_worker_1.RuntimeWorker; } });
29
- Object.defineProperty(exports, "createRuntimeWorker", { enumerable: true, get: function () { return runtime_worker_1.createRuntimeWorker; } });
30
- // Session executor
31
- var session_executor_1 = require("./session-executor");
32
- Object.defineProperty(exports, "SessionExecutor", { enumerable: true, get: function () { return session_executor_1.SessionExecutor; } });
33
- Object.defineProperty(exports, "createSessionExecutor", { enumerable: true, get: function () { return session_executor_1.createSessionExecutor; } });
34
- // Channels
35
- var channels_1 = require("./channels");
36
- Object.defineProperty(exports, "MemoryChannel", { enumerable: true, get: function () { return channels_1.MemoryChannel; } });
37
- Object.defineProperty(exports, "createMemoryChannel", { enumerable: true, get: function () { return channels_1.createMemoryChannel; } });
38
- Object.defineProperty(exports, "createMemoryChannelPair", { enumerable: true, get: function () { return channels_1.createMemoryChannelPair; } });
39
- Object.defineProperty(exports, "WebSocketChannel", { enumerable: true, get: function () { return channels_1.WebSocketChannel; } });
40
- Object.defineProperty(exports, "createWebSocketChannel", { enumerable: true, get: function () { return channels_1.createWebSocketChannel; } });
41
- //# sourceMappingURL=index.js.map
package/src/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;AAoBH,iBAAiB;AACjB,mDAA2F;AAAlF,mHAAA,aAAa,OAAqB;AAAE,qHAAA,mBAAmB,OAAA;AAEhE,mBAAmB;AACnB,uDAAyG;AAAhG,mHAAA,eAAe,OAAA;AAAE,yHAAA,qBAAqB,OAAA;AAE/C,WAAW;AACX,uCAQoB;AAPlB,yGAAA,aAAa,OAAA;AACb,+GAAA,mBAAmB,OAAA;AACnB,mHAAA,uBAAuB,OAAA;AACvB,4GAAA,gBAAgB,OAAA;AAChB,kHAAA,sBAAsB,OAAA","sourcesContent":["/**\n * @enclave-vm/runtime\n *\n * Standalone runtime worker for EnclaveJS.\n * Can be deployed as a separate process/worker for distributed execution.\n *\n * @example\n * ```typescript\n * import { createRuntimeWorker } from '@enclave-vm/runtime';\n *\n * const worker = createRuntimeWorker({\n * port: 3001,\n * maxSessions: 10,\n * debug: true,\n * });\n *\n * await worker.start();\n * console.log('Runtime is ready!');\n * ```\n *\n * @packageDocumentation\n */\n\n// Types\nexport type {\n RuntimeConfig,\n RuntimeState,\n RuntimeStats,\n RuntimeSession,\n RuntimeWorker,\n RuntimeChannel,\n RuntimeRequest,\n ExecuteRequest,\n CancelRequest,\n ToolResultRequest,\n PingRequest,\n RuntimeEventHandler,\n ConnectionHandler,\n WebSocketServer,\n} from './types';\n\n// Runtime worker\nexport { RuntimeWorker as RuntimeWorkerImpl, createRuntimeWorker } from './runtime-worker';\n\n// Session executor\nexport { SessionExecutor, createSessionExecutor, type SessionExecutorOptions } from './session-executor';\n\n// Channels\nexport {\n MemoryChannel,\n createMemoryChannel,\n createMemoryChannelPair,\n WebSocketChannel,\n createWebSocketChannel,\n type WebSocketChannelConfig,\n type WebSocketChannelState,\n} from './channels';\n"]}