@enclave-vm/runtime 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.
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@enclave-vm/runtime",
3
+ "version": "0.0.1",
4
+ "description": "Standalone runtime worker for EnclaveJS - deployable execution environment",
5
+ "author": "AgentFront <info@agentfront.dev>",
6
+ "homepage": "https://github.com/agentfront/enclave",
7
+ "license": "Apache-2.0",
8
+ "keywords": [
9
+ "enclavejs",
10
+ "enclave",
11
+ "runtime",
12
+ "worker",
13
+ "sandbox",
14
+ "vm"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/agentfront/enclave.git"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/agentfront/enclave/issues"
22
+ },
23
+ "main": "./src/index.js",
24
+ "types": "./src/index.d.ts",
25
+ "exports": {
26
+ "./package.json": "./package.json",
27
+ ".": {
28
+ "types": "./src/index.d.ts",
29
+ "import": "./src/index.js",
30
+ "default": "./src/index.js"
31
+ }
32
+ },
33
+ "bin": {
34
+ "enclave-runtime": "./src/cli.js"
35
+ },
36
+ "dependencies": {
37
+ "@enclave-vm/types": "0.0.1",
38
+ "@enclave-vm/stream": "0.0.1",
39
+ "@enclave-vm/core": "0.0.1"
40
+ },
41
+ "devDependencies": {
42
+ "ws": "^8.0.0"
43
+ },
44
+ "type": "commonjs",
45
+ "engines": {
46
+ "node": ">=18.0.0"
47
+ }
48
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Channel Implementations
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ export { MemoryChannel, createMemoryChannel, createMemoryChannelPair } from './memory-channel';
7
+ export { WebSocketChannel, createWebSocketChannel, type WebSocketChannelConfig, type WebSocketChannelState, } from './websocket-channel';
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ /**
3
+ * Channel Implementations
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.createWebSocketChannel = exports.WebSocketChannel = exports.createMemoryChannelPair = exports.createMemoryChannel = exports.MemoryChannel = void 0;
9
+ var memory_channel_1 = require("./memory-channel");
10
+ Object.defineProperty(exports, "MemoryChannel", { enumerable: true, get: function () { return memory_channel_1.MemoryChannel; } });
11
+ Object.defineProperty(exports, "createMemoryChannel", { enumerable: true, get: function () { return memory_channel_1.createMemoryChannel; } });
12
+ Object.defineProperty(exports, "createMemoryChannelPair", { enumerable: true, get: function () { return memory_channel_1.createMemoryChannelPair; } });
13
+ var websocket_channel_1 = require("./websocket-channel");
14
+ Object.defineProperty(exports, "WebSocketChannel", { enumerable: true, get: function () { return websocket_channel_1.WebSocketChannel; } });
15
+ Object.defineProperty(exports, "createWebSocketChannel", { enumerable: true, get: function () { return websocket_channel_1.createWebSocketChannel; } });
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/channels/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH,mDAA+F;AAAtF,+GAAA,aAAa,OAAA;AAAE,qHAAA,mBAAmB,OAAA;AAAE,yHAAA,uBAAuB,OAAA;AACpE,yDAK6B;AAJ3B,qHAAA,gBAAgB,OAAA;AAChB,2HAAA,sBAAsB,OAAA","sourcesContent":["/**\n * Channel Implementations\n *\n * @packageDocumentation\n */\n\nexport { MemoryChannel, createMemoryChannel, createMemoryChannelPair } from './memory-channel';\nexport {\n WebSocketChannel,\n createWebSocketChannel,\n type WebSocketChannelConfig,\n type WebSocketChannelState,\n} from './websocket-channel';\n"]}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * In-Memory Channel
3
+ *
4
+ * Simple in-process channel for testing and embedded use.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import type { StreamEvent, RuntimeChannelMessage } from '@enclave-vm/types';
9
+ import type { RuntimeChannel } from '../types';
10
+ /**
11
+ * In-memory channel implementation
12
+ *
13
+ * Provides a simple channel that stores events in memory.
14
+ * Useful for testing and embedded runtime scenarios.
15
+ */
16
+ export declare class MemoryChannel implements RuntimeChannel {
17
+ private readonly eventQueue;
18
+ private readonly messageHandlers;
19
+ private _isOpen;
20
+ /**
21
+ * Whether the channel is open
22
+ */
23
+ get isOpen(): boolean;
24
+ /**
25
+ * Send a stream event
26
+ */
27
+ send(event: StreamEvent): void;
28
+ /**
29
+ * Get all queued events
30
+ */
31
+ getEvents(): StreamEvent[];
32
+ /**
33
+ * Clear the event queue
34
+ */
35
+ clearEvents(): void;
36
+ /**
37
+ * Receive messages
38
+ */
39
+ onMessage(handler: (message: RuntimeChannelMessage) => void): () => void;
40
+ /**
41
+ * Inject a message (simulate incoming message)
42
+ */
43
+ injectMessage(message: RuntimeChannelMessage): void;
44
+ /**
45
+ * Close the channel
46
+ */
47
+ close(): void;
48
+ }
49
+ /**
50
+ * Create a memory channel
51
+ */
52
+ export declare function createMemoryChannel(): MemoryChannel;
53
+ /**
54
+ * Create a pair of connected memory channels
55
+ *
56
+ * Messages sent to one channel are received by the other.
57
+ * Useful for simulating bidirectional communication.
58
+ */
59
+ export declare function createMemoryChannelPair(): {
60
+ client: MemoryChannel;
61
+ server: MemoryChannel;
62
+ };
@@ -0,0 +1,111 @@
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
@@ -0,0 +1 @@
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,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAClC,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACvC,CAAC,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,OAA8B;QAC1C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACvC,CAAC;QACD,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YAC3C,OAAO,CAAC,OAAO,CAAC,CAAC;QACnB,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;CACF;AAjED,sCAiEC;AAED;;GAEG;AACH,SAAgB,mBAAmB;IACjC,OAAO,IAAI,aAAa,EAAE,CAAC;AAC7B,CAAC;AAED;;;;;GAKG;AACH,SAAgB,uBAAuB;IAIrC,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IACnC,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IAEnC,+BAA+B;IAC/B,qCAAqC;IACrC,MAAM,kBAAkB,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,CAAC,IAAI,GAAG,CAAC,KAAkB,EAAE,EAAE;QACnC,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAC1B,uCAAuC;QACvC,MAAM,CAAC,aAAa,CAAC,KAAyC,CAAC,CAAC;IAClE,CAAC,CAAC;IAEF,qCAAqC;IACrC,MAAM,kBAAkB,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,CAAC,IAAI,GAAG,CAAC,KAAkB,EAAE,EAAE;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"]}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * WebSocket Channel
3
+ *
4
+ * WebSocket-based channel for remote runtime communication.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import type { StreamEvent, RuntimeChannelMessage } from '@enclave-vm/types';
9
+ import type { RuntimeChannel } from '../types';
10
+ /**
11
+ * WebSocket channel configuration
12
+ */
13
+ export interface WebSocketChannelConfig {
14
+ /**
15
+ * WebSocket URL to connect to
16
+ */
17
+ url: string;
18
+ /**
19
+ * Reconnection options
20
+ */
21
+ reconnect?: {
22
+ enabled?: boolean;
23
+ maxRetries?: number;
24
+ initialDelayMs?: number;
25
+ maxDelayMs?: number;
26
+ };
27
+ /**
28
+ * Connection timeout in milliseconds
29
+ * @default 10000
30
+ */
31
+ connectionTimeoutMs?: number;
32
+ /**
33
+ * Debug mode
34
+ */
35
+ debug?: boolean;
36
+ }
37
+ /**
38
+ * WebSocket channel state
39
+ */
40
+ export type WebSocketChannelState = 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'closed';
41
+ /**
42
+ * WebSocket channel implementation
43
+ *
44
+ * Provides a channel over WebSocket for remote runtime communication.
45
+ */
46
+ export declare class WebSocketChannel implements RuntimeChannel {
47
+ private readonly config;
48
+ private ws;
49
+ private state;
50
+ private readonly messageHandlers;
51
+ private retryCount;
52
+ private retryTimeout;
53
+ private messageBuffer;
54
+ constructor(config: WebSocketChannelConfig);
55
+ /**
56
+ * Whether the channel is open
57
+ */
58
+ get isOpen(): boolean;
59
+ /**
60
+ * Get current state
61
+ */
62
+ get channelState(): WebSocketChannelState;
63
+ /**
64
+ * Connect to the WebSocket server
65
+ */
66
+ connect(): Promise<void>;
67
+ /**
68
+ * Send a stream event
69
+ */
70
+ send(event: StreamEvent): void;
71
+ /**
72
+ * Receive messages
73
+ */
74
+ onMessage(handler: (message: RuntimeChannelMessage) => void): () => void;
75
+ /**
76
+ * Close the channel
77
+ */
78
+ close(): void;
79
+ /**
80
+ * Handle incoming message
81
+ */
82
+ private handleMessage;
83
+ /**
84
+ * Handle disconnect
85
+ */
86
+ private handleDisconnect;
87
+ /**
88
+ * Flush message buffer
89
+ */
90
+ private flushBuffer;
91
+ /**
92
+ * Log debug message
93
+ */
94
+ private log;
95
+ }
96
+ /**
97
+ * Create a WebSocket channel
98
+ */
99
+ export declare function createWebSocketChannel(config: WebSocketChannelConfig): WebSocketChannel;
@@ -0,0 +1,208 @@
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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket-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gB,CAAC,MAAM,CAAC,CAAC;AACtC,CAAC","sourcesContent":["/**\n * WebSocket 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.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Enclave Runtime CLI
4
+ *
5
+ * Standalone runtime worker that can be deployed independently.
6
+ *
7
+ * Usage:
8
+ * npx enclave-runtime [options]
9
+ *
10
+ * Options:
11
+ * --port <port> Port to listen on (default: 3001)
12
+ * --host <host> Host to bind to (default: 0.0.0.0)
13
+ * --max-sessions <n> Maximum concurrent sessions (default: 10)
14
+ * --debug Enable debug logging
15
+ * --help Show help
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ export {};