@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 +48 -0
- package/src/channels/index.d.ts +7 -0
- package/src/channels/index.js +16 -0
- package/src/channels/index.js.map +1 -0
- package/src/channels/memory-channel.d.ts +62 -0
- package/src/channels/memory-channel.js +111 -0
- package/src/channels/memory-channel.js.map +1 -0
- package/src/channels/websocket-channel.d.ts +99 -0
- package/src/channels/websocket-channel.js +208 -0
- package/src/channels/websocket-channel.js.map +1 -0
- package/src/cli.d.ts +19 -0
- package/src/cli.js +121 -0
- package/src/cli.js.map +1 -0
- package/src/index.d.ts +26 -0
- package/src/index.js +41 -0
- package/src/index.js.map +1 -0
- package/src/runtime-worker.d.ts +71 -0
- package/src/runtime-worker.js +222 -0
- package/src/runtime-worker.js.map +1 -0
- package/src/session-executor.d.ts +89 -0
- package/src/session-executor.js +149 -0
- package/src/session-executor.js.map +1 -0
- package/src/types.d.ts +214 -0
- package/src/types.js +10 -0
- package/src/types.js.map +1 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
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
|
+
//# sour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S,CAAC,CAAC,CAAC;IAEjD,mBAAmB;IACnB,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IAErB,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IACzC,OAAO,CAAC,GAAG,CAAC,UAAU,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAErC,2BAA2B;IAC3B,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,WAAW,CAAC,GAAG,EAAE;YACf,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;YAChC,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE;gBACpB,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,aAAa,EAAE,KAAK,CAAC,aAAa;gBAClC,QAAQ,EAAE,KAAK,CAAC,QAAQ;gBACxB,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,QAAQ,GAAG,IAAI,GAAG,IAAI,CAAC;aAC/D,CAAC,CAAC;QACL,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;AACH,CAAC;AAED,WAAW;AACX,IAAI,EAAE,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.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @enclave-vm/runtime
|
|
3
|
+
*
|
|
4
|
+
* Standalone runtime worker for EnclaveJS.
|
|
5
|
+
* Can be deployed as a separate process/worker for distributed execution.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { createRuntimeWorker } from '@enclave-vm/runtime';
|
|
10
|
+
*
|
|
11
|
+
* const worker = createRuntimeWorker({
|
|
12
|
+
* port: 3001,
|
|
13
|
+
* maxSessions: 10,
|
|
14
|
+
* debug: true,
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* await worker.start();
|
|
18
|
+
* console.log('Runtime is ready!');
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @packageDocumentation
|
|
22
|
+
*/
|
|
23
|
+
export type { RuntimeConfig, RuntimeState, RuntimeStats, RuntimeSession, RuntimeWorker, RuntimeChannel, RuntimeRequest, ExecuteRequest, CancelRequest, ToolResultRequest, PingRequest, RuntimeEventHandler, ConnectionHandler, WebSocketServer, } from './types';
|
|
24
|
+
export { RuntimeWorker as RuntimeWorkerImpl, createRuntimeWorker } from './runtime-worker';
|
|
25
|
+
export { SessionExecutor, createSessionExecutor, type SessionExecutorOptions } from './session-executor';
|
|
26
|
+
export { MemoryChannel, createMemoryChannel, createMemoryChannelPair, WebSocketChannel, createWebSocketChannel, type WebSocketChannelConfig, type WebSocketChannelState, } from './channels';
|
package/src/index.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime Worker
|
|
3
|
+
*
|
|
4
|
+
* Standalone worker that executes Enclave sessions.
|
|
5
|
+
* Can run as a separate process/worker and communicate via WebSocket.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
import type { RuntimeConfig, RuntimeStats, RuntimeSession, RuntimeWorker as IRuntimeWorker, RuntimeRequest, RuntimeChannel } from './types';
|
|
10
|
+
/**
|
|
11
|
+
* Runtime worker implementation
|
|
12
|
+
*
|
|
13
|
+
* Manages multiple session executors and provides a WebSocket interface
|
|
14
|
+
* for communication with the broker.
|
|
15
|
+
*/
|
|
16
|
+
export declare class RuntimeWorker implements IRuntimeWorker {
|
|
17
|
+
private readonly config;
|
|
18
|
+
private readonly sessions;
|
|
19
|
+
private state;
|
|
20
|
+
private startedAt;
|
|
21
|
+
private totalSessions;
|
|
22
|
+
constructor(config?: RuntimeConfig);
|
|
23
|
+
/**
|
|
24
|
+
* Check if runtime is running
|
|
25
|
+
*/
|
|
26
|
+
get isRunning(): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Start the runtime worker
|
|
29
|
+
*/
|
|
30
|
+
start(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Stop the runtime worker
|
|
33
|
+
*/
|
|
34
|
+
stop(): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* Get runtime statistics
|
|
37
|
+
*/
|
|
38
|
+
getStats(): RuntimeStats;
|
|
39
|
+
/**
|
|
40
|
+
* Get active sessions
|
|
41
|
+
*/
|
|
42
|
+
getSessions(): RuntimeSession[];
|
|
43
|
+
/**
|
|
44
|
+
* Handle incoming request from channel
|
|
45
|
+
*/
|
|
46
|
+
handleRequest(request: RuntimeRequest, channel: RuntimeChannel): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Handle execute request
|
|
49
|
+
*/
|
|
50
|
+
private handleExecute;
|
|
51
|
+
/**
|
|
52
|
+
* Handle cancel request
|
|
53
|
+
*/
|
|
54
|
+
private handleCancel;
|
|
55
|
+
/**
|
|
56
|
+
* Handle tool result
|
|
57
|
+
*/
|
|
58
|
+
private handleToolResult;
|
|
59
|
+
/**
|
|
60
|
+
* Clean up a session
|
|
61
|
+
*/
|
|
62
|
+
private cleanupSession;
|
|
63
|
+
/**
|
|
64
|
+
* Log debug message
|
|
65
|
+
*/
|
|
66
|
+
private log;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Create a runtime worker
|
|
70
|
+
*/
|
|
71
|
+
export declare function createRuntimeWorker(config?: RuntimeConfig): RuntimeWorker;
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Runtime Worker
|
|
4
|
+
*
|
|
5
|
+
* Standalone worker that executes Enclave sessions.
|
|
6
|
+
* Can run as a separate process/worker and communicate via WebSocket.
|
|
7
|
+
*
|
|
8
|
+
* @packageDocumentation
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.RuntimeWorker = void 0;
|
|
12
|
+
exports.createRuntimeWorker = createRuntimeWorker;
|
|
13
|
+
const session_executor_1 = require("./session-executor");
|
|
14
|
+
/**
|
|
15
|
+
* Default runtime configuration
|
|
16
|
+
*/
|
|
17
|
+
const DEFAULT_CONFIG = {
|
|
18
|
+
port: 3001,
|
|
19
|
+
host: '0.0.0.0',
|
|
20
|
+
wsPath: '/ws',
|
|
21
|
+
maxSessions: 10,
|
|
22
|
+
defaultLimits: {},
|
|
23
|
+
debug: false,
|
|
24
|
+
heartbeatIntervalMs: 15000,
|
|
25
|
+
connectionTimeoutMs: 30000,
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Runtime worker implementation
|
|
29
|
+
*
|
|
30
|
+
* Manages multiple session executors and provides a WebSocket interface
|
|
31
|
+
* for communication with the broker.
|
|
32
|
+
*/
|
|
33
|
+
class RuntimeWorker {
|
|
34
|
+
config;
|
|
35
|
+
sessions;
|
|
36
|
+
state = 'idle';
|
|
37
|
+
startedAt = 0;
|
|
38
|
+
totalSessions = 0;
|
|
39
|
+
constructor(config = {}) {
|
|
40
|
+
this.config = {
|
|
41
|
+
...DEFAULT_CONFIG,
|
|
42
|
+
...config,
|
|
43
|
+
};
|
|
44
|
+
this.sessions = new Map();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Check if runtime is running
|
|
48
|
+
*/
|
|
49
|
+
get isRunning() {
|
|
50
|
+
return this.state === 'running';
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Start the runtime worker
|
|
54
|
+
*/
|
|
55
|
+
async start() {
|
|
56
|
+
if (this.state !== 'idle' && this.state !== 'stopped') {
|
|
57
|
+
throw new Error(`Cannot start runtime in state: ${this.state}`);
|
|
58
|
+
}
|
|
59
|
+
this.state = 'starting';
|
|
60
|
+
this.startedAt = Date.now();
|
|
61
|
+
// In a full implementation, this would start the WebSocket server
|
|
62
|
+
// For now, we mark as running for embedded use
|
|
63
|
+
this.state = 'running';
|
|
64
|
+
this.log('Runtime worker started');
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Stop the runtime worker
|
|
68
|
+
*/
|
|
69
|
+
async stop() {
|
|
70
|
+
if (this.state === 'stopped' || this.state === 'stopping') {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
this.state = 'stopping';
|
|
74
|
+
// Cancel all active sessions
|
|
75
|
+
const cancelPromises = [];
|
|
76
|
+
for (const [_sessionId, executor] of this.sessions) {
|
|
77
|
+
cancelPromises.push(executor.cancel('Runtime stopping').catch(() => {
|
|
78
|
+
// Ignore cancel errors during shutdown
|
|
79
|
+
}));
|
|
80
|
+
}
|
|
81
|
+
await Promise.all(cancelPromises);
|
|
82
|
+
// Dispose all sessions
|
|
83
|
+
for (const executor of this.sessions.values()) {
|
|
84
|
+
executor.dispose();
|
|
85
|
+
}
|
|
86
|
+
this.sessions.clear();
|
|
87
|
+
this.state = 'stopped';
|
|
88
|
+
this.log('Runtime worker stopped');
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Get runtime statistics
|
|
92
|
+
*/
|
|
93
|
+
getStats() {
|
|
94
|
+
const now = Date.now();
|
|
95
|
+
const memoryUsage = process.memoryUsage();
|
|
96
|
+
return {
|
|
97
|
+
state: this.state,
|
|
98
|
+
activeSessions: this.sessions.size,
|
|
99
|
+
totalSessions: this.totalSessions,
|
|
100
|
+
startedAt: this.startedAt,
|
|
101
|
+
uptimeMs: this.startedAt > 0 ? now - this.startedAt : 0,
|
|
102
|
+
memoryUsage: {
|
|
103
|
+
heapUsed: memoryUsage.heapUsed,
|
|
104
|
+
heapTotal: memoryUsage.heapTotal,
|
|
105
|
+
rss: memoryUsage.rss,
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Get active sessions
|
|
111
|
+
*/
|
|
112
|
+
getSessions() {
|
|
113
|
+
return Array.from(this.sessions.values()).map((executor) => executor.getInfo());
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Handle incoming request from channel
|
|
117
|
+
*/
|
|
118
|
+
async handleRequest(request, channel) {
|
|
119
|
+
switch (request.type) {
|
|
120
|
+
case 'execute':
|
|
121
|
+
await this.handleExecute(request, channel);
|
|
122
|
+
break;
|
|
123
|
+
case 'cancel':
|
|
124
|
+
await this.handleCancel(request);
|
|
125
|
+
break;
|
|
126
|
+
case 'tool_result':
|
|
127
|
+
await this.handleToolResult(request);
|
|
128
|
+
break;
|
|
129
|
+
case 'ping':
|
|
130
|
+
// Pong is handled by sending back a heartbeat event
|
|
131
|
+
this.log('Received ping');
|
|
132
|
+
break;
|
|
133
|
+
default:
|
|
134
|
+
this.log(`Unknown request type: ${request.type}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Handle execute request
|
|
139
|
+
*/
|
|
140
|
+
async handleExecute(request, channel) {
|
|
141
|
+
if (!this.isRunning) {
|
|
142
|
+
throw new Error('Runtime is not running');
|
|
143
|
+
}
|
|
144
|
+
if (this.sessions.size >= this.config.maxSessions) {
|
|
145
|
+
throw new Error(`Maximum sessions reached (${this.config.maxSessions})`);
|
|
146
|
+
}
|
|
147
|
+
const { sessionId, code, limits } = request;
|
|
148
|
+
// Check if session already exists
|
|
149
|
+
if (this.sessions.has(sessionId)) {
|
|
150
|
+
throw new Error(`Session ${sessionId} already exists`);
|
|
151
|
+
}
|
|
152
|
+
// Create session executor
|
|
153
|
+
const executor = (0, session_executor_1.createSessionExecutor)({
|
|
154
|
+
sessionId,
|
|
155
|
+
code,
|
|
156
|
+
limits: limits,
|
|
157
|
+
channel,
|
|
158
|
+
debug: this.config.debug,
|
|
159
|
+
});
|
|
160
|
+
this.sessions.set(executor.sessionId, executor);
|
|
161
|
+
this.totalSessions++;
|
|
162
|
+
// Execute asynchronously
|
|
163
|
+
executor
|
|
164
|
+
.execute()
|
|
165
|
+
.catch((error) => {
|
|
166
|
+
this.log(`Session ${executor.sessionId} execution error: ${error}`);
|
|
167
|
+
})
|
|
168
|
+
.finally(() => {
|
|
169
|
+
// Clean up after completion
|
|
170
|
+
this.cleanupSession(executor.sessionId);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Handle cancel request
|
|
175
|
+
*/
|
|
176
|
+
async handleCancel(request) {
|
|
177
|
+
const executor = this.sessions.get(request.sessionId);
|
|
178
|
+
if (!executor) {
|
|
179
|
+
this.log(`Cancel request for unknown session: ${request.sessionId}`);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
await executor.cancel(request.reason);
|
|
183
|
+
this.cleanupSession(request.sessionId);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Handle tool result
|
|
187
|
+
*/
|
|
188
|
+
async handleToolResult(request) {
|
|
189
|
+
const executor = this.sessions.get(request.sessionId);
|
|
190
|
+
if (!executor) {
|
|
191
|
+
this.log(`Tool result for unknown session: ${request.sessionId}`);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
await executor.submitToolResult(request.callId, request.success, request.value, request.error);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Clean up a session
|
|
198
|
+
*/
|
|
199
|
+
cleanupSession(sessionId) {
|
|
200
|
+
const executor = this.sessions.get(sessionId);
|
|
201
|
+
if (executor) {
|
|
202
|
+
executor.dispose();
|
|
203
|
+
this.sessions.delete(sessionId);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Log debug message
|
|
208
|
+
*/
|
|
209
|
+
log(message) {
|
|
210
|
+
if (this.config.debug) {
|
|
211
|
+
console.log(`[RuntimeWorker] ${message}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
exports.RuntimeWorker = RuntimeWorker;
|
|
216
|
+
/**
|
|
217
|
+
* Create a runtime worker
|
|
218
|
+
*/
|
|
219
|
+
function createRuntimeWorker(config) {
|
|
220
|
+
return new RuntimeWorker(config);
|
|
221
|
+
}
|
|
222
|
+
//# sourceMappingURL=runtime-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-worker.js","sourceRoot":"","sources":["../../src/runtime-worker.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAyQH,kDAEC;AA/PD,yDAA4E;AAE5E;;GAEG;AACH,MAAM,cAAc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C;IACzC,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,gBAAgB,CAAC,OAO9B;QACC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACtD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,IAAI,CAAC,GAAG,CAAC,oCAAoC,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;YAClE,OAAO;QACT,CAAC;QAED,MAAM,QAAQ,CAAC,gBAAgB,CAAC,OAAO,CAAC,MAAuB,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IAClH,CAAC;IAED;;OAEG;IACK,cAAc,CAAC,SAAoB;QACzC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAC9C,IAAI,QAAQ,EAAE,CAAC;YACb,QAAQ,CAAC,OAAO,EAAE,CAAC;YACnB,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;IAED;;OAEG;IACK,GAAG,CAAC,OAAe;QACzB,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO,CAAC,GAAG,CAAC,mBAAmB,OAAO,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;CACF;AAlOD,sCAkOC;AAED;;GAEG;AACH,SAAgB,mBAAmB,CAAC,MAAsB;IACxD,OAAO,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Runtime Worker\n *\n * Standalone worker that executes Enclave sessions.\n * Can run as a separate process/worker and communicate via WebSocket.\n *\n * @packageDocumentation\n */\n\nimport type { SessionId } from '@enclave-vm/types';\nimport type {\n RuntimeConfig,\n RuntimeState,\n RuntimeStats,\n RuntimeSession,\n RuntimeWorker as IRuntimeWorker,\n RuntimeRequest,\n RuntimeChannel,\n} from './types';\nimport { SessionExecutor, createSessionExecutor } from './session-executor';\n\n/**\n * Default runtime configuration\n */\nconst DEFAULT_CONFIG: Required<RuntimeConfig> = {\n port: 3001,\n host: '0.0.0.0',\n wsPath: '/ws',\n maxSessions: 10,\n defaultLimits: {},\n debug: false,\n heartbeatIntervalMs: 15000,\n connectionTimeoutMs: 30000,\n};\n\n/**\n * Runtime worker implementation\n *\n * Manages multiple session executors and provides a WebSocket interface\n * for communication with the broker.\n */\nexport class RuntimeWorker implements IRuntimeWorker {\n private readonly config: Required<RuntimeConfig>;\n private readonly sessions: Map<SessionId, SessionExecutor>;\n private state: RuntimeState = 'idle';\n private startedAt = 0;\n private totalSessions = 0;\n\n constructor(config: RuntimeConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n this.sessions = new Map();\n }\n\n /**\n * Check if runtime is running\n */\n get isRunning(): boolean {\n return this.state === 'running';\n }\n\n /**\n * Start the runtime worker\n */\n async start(): Promise<void> {\n if (this.state !== 'idle' && this.state !== 'stopped') {\n throw new Error(`Cannot start runtime in state: ${this.state}`);\n }\n\n this.state = 'starting';\n this.startedAt = Date.now();\n\n // In a full implementation, this would start the WebSocket server\n // For now, we mark as running for embedded use\n this.state = 'running';\n\n this.log('Runtime worker started');\n }\n\n /**\n * Stop the runtime worker\n */\n async stop(): Promise<void> {\n if (this.state === 'stopped' || this.state === 'stopping') {\n return;\n }\n\n this.state = 'stopping';\n\n // Cancel all active sessions\n const cancelPromises: Promise<void>[] = [];\n for (const [_sessionId, executor] of this.sessions) {\n cancelPromises.push(\n executor.cancel('Runtime stopping').catch(() => {\n // Ignore cancel errors during shutdown\n }),\n );\n }\n\n await Promise.all(cancelPromises);\n\n // Dispose all sessions\n for (const executor of this.sessions.values()) {\n executor.dispose();\n }\n this.sessions.clear();\n\n this.state = 'stopped';\n this.log('Runtime worker stopped');\n }\n\n /**\n * Get runtime statistics\n */\n getStats(): RuntimeStats {\n const now = Date.now();\n const memoryUsage = process.memoryUsage();\n\n return {\n state: this.state,\n activeSessions: this.sessions.size,\n totalSessions: this.totalSessions,\n startedAt: this.startedAt,\n uptimeMs: this.startedAt > 0 ? now - this.startedAt : 0,\n memoryUsage: {\n heapUsed: memoryUsage.heapUsed,\n heapTotal: memoryUsage.heapTotal,\n rss: memoryUsage.rss,\n },\n };\n }\n\n /**\n * Get active sessions\n */\n getSessions(): RuntimeSession[] {\n return Array.from(this.sessions.values()).map((executor) => executor.getInfo());\n }\n\n /**\n * Handle incoming request from channel\n */\n async handleRequest(request: RuntimeRequest, channel: RuntimeChannel): Promise<void> {\n switch (request.type) {\n case 'execute':\n await this.handleExecute(request, channel);\n break;\n\n case 'cancel':\n await this.handleCancel(request);\n break;\n\n case 'tool_result':\n await this.handleToolResult(request);\n break;\n\n case 'ping':\n // Pong is handled by sending back a heartbeat event\n this.log('Received ping');\n break;\n\n default:\n this.log(`Unknown request type: ${(request as RuntimeRequest).type}`);\n }\n }\n\n /**\n * Handle execute request\n */\n private async handleExecute(\n request: { type: 'execute'; sessionId: SessionId; code: string; limits?: unknown },\n channel: RuntimeChannel,\n ): Promise<void> {\n if (!this.isRunning) {\n throw new Error('Runtime is not running');\n }\n\n if (this.sessions.size >= this.config.maxSessions) {\n throw new Error(`Maximum sessions reached (${this.config.maxSessions})`);\n }\n\n const { sessionId, code, limits } = request;\n\n // Check if session already exists\n if (this.sessions.has(sessionId)) {\n throw new Error(`Session ${sessionId} already exists`);\n }\n\n // Create session executor\n const executor = createSessionExecutor({\n sessionId,\n code,\n limits: limits as Record<string, unknown>,\n channel,\n debug: this.config.debug,\n });\n\n this.sessions.set(executor.sessionId, executor);\n this.totalSessions++;\n\n // Execute asynchronously\n executor\n .execute()\n .catch((error) => {\n this.log(`Session ${executor.sessionId} execution error: ${error}`);\n })\n .finally(() => {\n // Clean up after completion\n this.cleanupSession(executor.sessionId);\n });\n }\n\n /**\n * Handle cancel request\n */\n private async handleCancel(request: { type: 'cancel'; sessionId: SessionId; reason?: string }): Promise<void> {\n const executor = this.sessions.get(request.sessionId);\n if (!executor) {\n this.log(`Cancel request for unknown session: ${request.sessionId}`);\n return;\n }\n\n await executor.cancel(request.reason);\n this.cleanupSession(request.sessionId);\n }\n\n /**\n * Handle tool result\n */\n private async handleToolResult(request: {\n type: 'tool_result';\n sessionId: SessionId;\n callId: string;\n success: boolean;\n value?: unknown;\n error?: { code?: string; message: string };\n }): Promise<void> {\n const executor = this.sessions.get(request.sessionId);\n if (!executor) {\n this.log(`Tool result for unknown session: ${request.sessionId}`);\n return;\n }\n\n await executor.submitToolResult(request.callId as `c_${string}`, request.success, request.value, request.error);\n }\n\n /**\n * Clean up a session\n */\n private cleanupSession(sessionId: SessionId): void {\n const executor = this.sessions.get(sessionId);\n if (executor) {\n executor.dispose();\n this.sessions.delete(sessionId);\n }\n }\n\n /**\n * Log debug message\n */\n private log(message: string): void {\n if (this.config.debug) {\n console.log(`[RuntimeWorker] ${message}`);\n }\n }\n}\n\n/**\n * Create a runtime worker\n */\nexport function createRuntimeWorker(config?: RuntimeConfig): RuntimeWorker {\n return new RuntimeWorker(config);\n}\n"]}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session Executor
|
|
3
|
+
*
|
|
4
|
+
* Wraps enclave-vm session for runtime execution.
|
|
5
|
+
*
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
*/
|
|
8
|
+
import type { SessionId, CallId, SessionLimits } from '@enclave-vm/types';
|
|
9
|
+
import type { RuntimeChannel, RuntimeSession } from './types';
|
|
10
|
+
/**
|
|
11
|
+
* Session executor options
|
|
12
|
+
*/
|
|
13
|
+
export interface SessionExecutorOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Session ID
|
|
16
|
+
*/
|
|
17
|
+
sessionId?: SessionId;
|
|
18
|
+
/**
|
|
19
|
+
* Code to execute
|
|
20
|
+
*/
|
|
21
|
+
code: string;
|
|
22
|
+
/**
|
|
23
|
+
* Session limits
|
|
24
|
+
*/
|
|
25
|
+
limits?: Partial<SessionLimits>;
|
|
26
|
+
/**
|
|
27
|
+
* Communication channel
|
|
28
|
+
*/
|
|
29
|
+
channel: RuntimeChannel;
|
|
30
|
+
/**
|
|
31
|
+
* Debug mode
|
|
32
|
+
*/
|
|
33
|
+
debug?: boolean;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Session executor
|
|
37
|
+
*
|
|
38
|
+
* Manages execution of a single session, handling communication
|
|
39
|
+
* between the enclave-vm session and the runtime channel.
|
|
40
|
+
*/
|
|
41
|
+
export declare class SessionExecutor {
|
|
42
|
+
readonly sessionId: SessionId;
|
|
43
|
+
private readonly session;
|
|
44
|
+
private readonly channel;
|
|
45
|
+
private readonly code;
|
|
46
|
+
private readonly debug;
|
|
47
|
+
private unsubscribe;
|
|
48
|
+
private executing;
|
|
49
|
+
constructor(options: SessionExecutorOptions);
|
|
50
|
+
/**
|
|
51
|
+
* Get session info
|
|
52
|
+
*/
|
|
53
|
+
getInfo(): RuntimeSession;
|
|
54
|
+
/**
|
|
55
|
+
* Get current state
|
|
56
|
+
*/
|
|
57
|
+
get state(): string;
|
|
58
|
+
/**
|
|
59
|
+
* Check if session is in terminal state
|
|
60
|
+
*/
|
|
61
|
+
get isTerminal(): boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Execute the code
|
|
64
|
+
*/
|
|
65
|
+
execute(): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* Submit a tool result
|
|
68
|
+
*/
|
|
69
|
+
submitToolResult(callId: CallId, success: boolean, value?: unknown, error?: {
|
|
70
|
+
code?: string;
|
|
71
|
+
message: string;
|
|
72
|
+
}): Promise<void>;
|
|
73
|
+
/**
|
|
74
|
+
* Cancel the session
|
|
75
|
+
*/
|
|
76
|
+
cancel(reason?: string): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Dispose of the executor
|
|
79
|
+
*/
|
|
80
|
+
dispose(): void;
|
|
81
|
+
/**
|
|
82
|
+
* Log debug message
|
|
83
|
+
*/
|
|
84
|
+
private log;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Create a session executor
|
|
88
|
+
*/
|
|
89
|
+
export declare function createSessionExecutor(options: SessionExecutorOptions): SessionExecutor;
|