@enclave-vm/core 0.0.1 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/index.mjs +11172 -0
- package/esm/package.json +6 -0
- package/index.js +11268 -0
- package/package.json +11 -10
- package/src/adapters/vm-adapter.js +0 -1140
- package/src/adapters/vm-adapter.js.map +0 -1
- package/src/adapters/worker-pool/config.js +0 -129
- package/src/adapters/worker-pool/config.js.map +0 -1
- package/src/adapters/worker-pool/errors.js +0 -181
- package/src/adapters/worker-pool/errors.js.map +0 -1
- package/src/adapters/worker-pool/execution-queue.js +0 -179
- package/src/adapters/worker-pool/execution-queue.js.map +0 -1
- package/src/adapters/worker-pool/index.js +0 -73
- package/src/adapters/worker-pool/index.js.map +0 -1
- package/src/adapters/worker-pool/memory-monitor.js +0 -184
- package/src/adapters/worker-pool/memory-monitor.js.map +0 -1
- package/src/adapters/worker-pool/protocol.js +0 -143
- package/src/adapters/worker-pool/protocol.js.map +0 -1
- package/src/adapters/worker-pool/rate-limiter.js +0 -101
- package/src/adapters/worker-pool/rate-limiter.js.map +0 -1
- package/src/adapters/worker-pool/safe-deserialize.js +0 -141
- package/src/adapters/worker-pool/safe-deserialize.js.map +0 -1
- package/src/adapters/worker-pool/worker-pool-adapter.js +0 -506
- package/src/adapters/worker-pool/worker-pool-adapter.js.map +0 -1
- package/src/adapters/worker-pool/worker-script.js +0 -770
- package/src/adapters/worker-pool/worker-script.js.map +0 -1
- package/src/adapters/worker-pool/worker-slot.js +0 -301
- package/src/adapters/worker-pool/worker-slot.js.map +0 -1
- package/src/babel/babel-wrapper.js +0 -395
- package/src/babel/babel-wrapper.js.map +0 -1
- package/src/babel/index.js +0 -17
- package/src/babel/index.js.map +0 -1
- package/src/babel/multi-file-transform.js +0 -344
- package/src/babel/multi-file-transform.js.map +0 -1
- package/src/double-vm/double-vm-wrapper.js +0 -523
- package/src/double-vm/double-vm-wrapper.js.map +0 -1
- package/src/double-vm/index.js +0 -34
- package/src/double-vm/index.js.map +0 -1
- package/src/double-vm/parent-vm-bootstrap.js +0 -1695
- package/src/double-vm/parent-vm-bootstrap.js.map +0 -1
- package/src/double-vm/suspicious-patterns.js +0 -304
- package/src/double-vm/suspicious-patterns.js.map +0 -1
- package/src/double-vm/types.js +0 -11
- package/src/double-vm/types.js.map +0 -1
- package/src/double-vm/wrap-adapter.js +0 -59
- package/src/double-vm/wrap-adapter.js.map +0 -1
- package/src/enclave.js +0 -671
- package/src/enclave.js.map +0 -1
- package/src/globals-validator.js +0 -206
- package/src/globals-validator.js.map +0 -1
- package/src/index.js +0 -130
- package/src/index.js.map +0 -1
- package/src/memory-proxy.js +0 -310
- package/src/memory-proxy.js.map +0 -1
- package/src/memory-tracker.js +0 -230
- package/src/memory-tracker.js.map +0 -1
- package/src/safe-error.js +0 -76
- package/src/safe-error.js.map +0 -1
- package/src/safe-runtime.js +0 -656
- package/src/safe-runtime.js.map +0 -1
- package/src/scoring/cache.js +0 -158
- package/src/scoring/cache.js.map +0 -1
- package/src/scoring/feature-extractor.js +0 -366
- package/src/scoring/feature-extractor.js.map +0 -1
- package/src/scoring/index.js +0 -53
- package/src/scoring/index.js.map +0 -1
- package/src/scoring/scorer.interface.js +0 -49
- package/src/scoring/scorer.interface.js.map +0 -1
- package/src/scoring/scorers/disabled.scorer.js +0 -34
- package/src/scoring/scorers/disabled.scorer.js.map +0 -1
- package/src/scoring/scorers/external-api.scorer.js +0 -141
- package/src/scoring/scorers/external-api.scorer.js.map +0 -1
- package/src/scoring/scorers/index.js +0 -22
- package/src/scoring/scorers/index.js.map +0 -1
- package/src/scoring/scorers/local-llm.scorer.js +0 -474
- package/src/scoring/scorers/local-llm.scorer.js.map +0 -1
- package/src/scoring/scorers/progressive.scorer.js +0 -199
- package/src/scoring/scorers/progressive.scorer.js.map +0 -1
- package/src/scoring/scorers/rule-based.scorer.js +0 -316
- package/src/scoring/scorers/rule-based.scorer.js.map +0 -1
- package/src/scoring/scoring-gate.js +0 -246
- package/src/scoring/scoring-gate.js.map +0 -1
- package/src/scoring/types.js +0 -107
- package/src/scoring/types.js.map +0 -1
- package/src/secure-proxy.js +0 -609
- package/src/secure-proxy.js.map +0 -1
- package/src/session/channels/embedded-channel.js +0 -130
- package/src/session/channels/embedded-channel.js.map +0 -1
- package/src/session/channels/index.js +0 -14
- package/src/session/channels/index.js.map +0 -1
- package/src/session/index.js +0 -27
- package/src/session/index.js.map +0 -1
- package/src/session/session-emitter.js +0 -253
- package/src/session/session-emitter.js.map +0 -1
- package/src/session/session-state-machine.js +0 -182
- package/src/session/session-state-machine.js.map +0 -1
- package/src/session/session.js +0 -398
- package/src/session/session.js.map +0 -1
- package/src/session-types.js +0 -39
- package/src/session-types.js.map +0 -1
- package/src/sidecar/index.js +0 -31
- package/src/sidecar/index.js.map +0 -1
- package/src/sidecar/reference-config.js +0 -118
- package/src/sidecar/reference-config.js.map +0 -1
- package/src/sidecar/reference-resolver.js +0 -262
- package/src/sidecar/reference-resolver.js.map +0 -1
- package/src/sidecar/reference-sidecar.js +0 -226
- package/src/sidecar/reference-sidecar.js.map +0 -1
- package/src/tool-bridge.js +0 -306
- package/src/tool-bridge.js.map +0 -1
- package/src/types.js +0 -187
- package/src/types.js.map +0 -1
- package/src/value-sanitizer.js +0 -421
- package/src/value-sanitizer.js.map +0 -1
- /package/{src/adapters → adapters}/vm-adapter.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/config.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/errors.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/execution-queue.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/index.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/memory-monitor.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/protocol.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/rate-limiter.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/safe-deserialize.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/worker-pool-adapter.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/worker-script.d.ts +0 -0
- /package/{src/adapters → adapters}/worker-pool/worker-slot.d.ts +0 -0
- /package/{src/babel → babel}/babel-wrapper.d.ts +0 -0
- /package/{src/babel → babel}/index.d.ts +0 -0
- /package/{src/babel → babel}/multi-file-transform.d.ts +0 -0
- /package/{src/double-vm → double-vm}/double-vm-wrapper.d.ts +0 -0
- /package/{src/double-vm → double-vm}/index.d.ts +0 -0
- /package/{src/double-vm → double-vm}/parent-vm-bootstrap.d.ts +0 -0
- /package/{src/double-vm → double-vm}/suspicious-patterns.d.ts +0 -0
- /package/{src/double-vm → double-vm}/types.d.ts +0 -0
- /package/{src/double-vm → double-vm}/wrap-adapter.d.ts +0 -0
- /package/{src/enclave.d.ts → enclave.d.ts} +0 -0
- /package/{src/globals-validator.d.ts → globals-validator.d.ts} +0 -0
- /package/{src/index.d.ts → index.d.ts} +0 -0
- /package/{src/memory-proxy.d.ts → memory-proxy.d.ts} +0 -0
- /package/{src/memory-tracker.d.ts → memory-tracker.d.ts} +0 -0
- /package/{src/safe-error.d.ts → safe-error.d.ts} +0 -0
- /package/{src/safe-runtime.d.ts → safe-runtime.d.ts} +0 -0
- /package/{src/scoring → scoring}/cache.d.ts +0 -0
- /package/{src/scoring → scoring}/feature-extractor.d.ts +0 -0
- /package/{src/scoring → scoring}/index.d.ts +0 -0
- /package/{src/scoring → scoring}/scorer.interface.d.ts +0 -0
- /package/{src/scoring → scoring}/scorers/disabled.scorer.d.ts +0 -0
- /package/{src/scoring → scoring}/scorers/external-api.scorer.d.ts +0 -0
- /package/{src/scoring → scoring}/scorers/index.d.ts +0 -0
- /package/{src/scoring → scoring}/scorers/local-llm.scorer.d.ts +0 -0
- /package/{src/scoring → scoring}/scorers/progressive.scorer.d.ts +0 -0
- /package/{src/scoring → scoring}/scorers/rule-based.scorer.d.ts +0 -0
- /package/{src/scoring → scoring}/scoring-gate.d.ts +0 -0
- /package/{src/scoring → scoring}/types.d.ts +0 -0
- /package/{src/secure-proxy.d.ts → secure-proxy.d.ts} +0 -0
- /package/{src/session → session}/channels/embedded-channel.d.ts +0 -0
- /package/{src/session → session}/channels/index.d.ts +0 -0
- /package/{src/session → session}/index.d.ts +0 -0
- /package/{src/session → session}/session-emitter.d.ts +0 -0
- /package/{src/session → session}/session-state-machine.d.ts +0 -0
- /package/{src/session → session}/session.d.ts +0 -0
- /package/{src/session-types.d.ts → session-types.d.ts} +0 -0
- /package/{src/sidecar → sidecar}/index.d.ts +0 -0
- /package/{src/sidecar → sidecar}/reference-config.d.ts +0 -0
- /package/{src/sidecar → sidecar}/reference-resolver.d.ts +0 -0
- /package/{src/sidecar → sidecar}/reference-sidecar.d.ts +0 -0
- /package/{src/tool-bridge.d.ts → tool-bridge.d.ts} +0 -0
- /package/{src/types.d.ts → types.d.ts} +0 -0
- /package/{src/value-sanitizer.d.ts → value-sanitizer.d.ts} +0 -0
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Execution Queue
|
|
4
|
-
*
|
|
5
|
-
* Handles backpressure when the worker pool is exhausted.
|
|
6
|
-
* Queues execution requests and dispatches them when workers become available.
|
|
7
|
-
*
|
|
8
|
-
* @packageDocumentation
|
|
9
|
-
*/
|
|
10
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
-
exports.ExecutionQueue = void 0;
|
|
12
|
-
const errors_1 = require("./errors");
|
|
13
|
-
/**
|
|
14
|
-
* Execution queue with configurable limits and timeout handling
|
|
15
|
-
*/
|
|
16
|
-
class ExecutionQueue {
|
|
17
|
-
queue = [];
|
|
18
|
-
config;
|
|
19
|
-
// Statistics
|
|
20
|
-
_totalQueued = 0;
|
|
21
|
-
_totalFulfilled = 0;
|
|
22
|
-
_totalTimedOut = 0;
|
|
23
|
-
_totalAborted = 0;
|
|
24
|
-
_longestWaitMs = 0;
|
|
25
|
-
_totalWaitMs = 0;
|
|
26
|
-
constructor(config) {
|
|
27
|
-
this.config = config;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Get current queue length
|
|
31
|
-
*/
|
|
32
|
-
get length() {
|
|
33
|
-
return this.queue.length;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Check if queue is full
|
|
37
|
-
*/
|
|
38
|
-
get isFull() {
|
|
39
|
-
return this.queue.length >= this.config.maxQueueSize;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Enqueue an execution request
|
|
43
|
-
*
|
|
44
|
-
* @param signal Optional abort signal
|
|
45
|
-
* @returns Promise that resolves with a slot ID when a worker is available
|
|
46
|
-
* @throws QueueFullError if queue is at capacity
|
|
47
|
-
* @throws QueueTimeoutError if queue wait times out
|
|
48
|
-
* @throws ExecutionAbortedError if aborted via signal
|
|
49
|
-
*/
|
|
50
|
-
async enqueue(signal) {
|
|
51
|
-
// Check queue capacity
|
|
52
|
-
if (this.queue.length >= this.config.maxQueueSize) {
|
|
53
|
-
throw new errors_1.QueueFullError(this.queue.length, this.config.maxQueueSize);
|
|
54
|
-
}
|
|
55
|
-
// Check if already aborted
|
|
56
|
-
if (signal?.aborted) {
|
|
57
|
-
throw new errors_1.ExecutionAbortedError('Execution aborted before queuing');
|
|
58
|
-
}
|
|
59
|
-
const id = `queue-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
60
|
-
this._totalQueued++;
|
|
61
|
-
return new Promise((resolve, reject) => {
|
|
62
|
-
const execution = {
|
|
63
|
-
id,
|
|
64
|
-
resolve,
|
|
65
|
-
reject,
|
|
66
|
-
enqueuedAt: Date.now(),
|
|
67
|
-
signal,
|
|
68
|
-
};
|
|
69
|
-
// Set up timeout
|
|
70
|
-
execution.timeoutId = setTimeout(() => {
|
|
71
|
-
this.removeFromQueue(id);
|
|
72
|
-
this._totalTimedOut++;
|
|
73
|
-
reject(new errors_1.QueueTimeoutError(Date.now() - execution.enqueuedAt));
|
|
74
|
-
}, this.config.queueTimeoutMs);
|
|
75
|
-
// Set up abort handling
|
|
76
|
-
if (signal) {
|
|
77
|
-
const abortHandler = () => {
|
|
78
|
-
this.removeFromQueue(id);
|
|
79
|
-
clearTimeout(execution.timeoutId);
|
|
80
|
-
this._totalAborted++;
|
|
81
|
-
reject(new errors_1.ExecutionAbortedError('Execution aborted while queued'));
|
|
82
|
-
};
|
|
83
|
-
signal.addEventListener('abort', abortHandler, { once: true });
|
|
84
|
-
execution.abortCleanup = () => {
|
|
85
|
-
signal.removeEventListener('abort', abortHandler);
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
this.queue.push(execution);
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Notify the queue that a worker slot is available
|
|
93
|
-
*
|
|
94
|
-
* @param slotId ID of the available slot
|
|
95
|
-
* @returns true if a queued request was fulfilled, false if queue was empty
|
|
96
|
-
*/
|
|
97
|
-
notifySlotAvailable(slotId) {
|
|
98
|
-
const execution = this.queue.shift();
|
|
99
|
-
if (!execution) {
|
|
100
|
-
return false;
|
|
101
|
-
}
|
|
102
|
-
// Clean up timeout and abort listener
|
|
103
|
-
if (execution.timeoutId) {
|
|
104
|
-
clearTimeout(execution.timeoutId);
|
|
105
|
-
}
|
|
106
|
-
if (execution.abortCleanup) {
|
|
107
|
-
execution.abortCleanup();
|
|
108
|
-
}
|
|
109
|
-
// Track statistics
|
|
110
|
-
const waitTime = Date.now() - execution.enqueuedAt;
|
|
111
|
-
this._totalWaitMs += waitTime;
|
|
112
|
-
this._totalFulfilled++;
|
|
113
|
-
if (waitTime > this._longestWaitMs) {
|
|
114
|
-
this._longestWaitMs = waitTime;
|
|
115
|
-
}
|
|
116
|
-
// Fulfill the request
|
|
117
|
-
execution.resolve(slotId);
|
|
118
|
-
return true;
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Remove a specific request from the queue
|
|
122
|
-
*/
|
|
123
|
-
removeFromQueue(id) {
|
|
124
|
-
const index = this.queue.findIndex((e) => e.id === id);
|
|
125
|
-
if (index !== -1) {
|
|
126
|
-
const [execution] = this.queue.splice(index, 1);
|
|
127
|
-
// Clean up
|
|
128
|
-
if (execution.timeoutId) {
|
|
129
|
-
clearTimeout(execution.timeoutId);
|
|
130
|
-
}
|
|
131
|
-
if (execution.abortCleanup) {
|
|
132
|
-
execution.abortCleanup();
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Clear the queue, rejecting all pending requests
|
|
138
|
-
*/
|
|
139
|
-
clear() {
|
|
140
|
-
for (const execution of this.queue) {
|
|
141
|
-
if (execution.timeoutId) {
|
|
142
|
-
clearTimeout(execution.timeoutId);
|
|
143
|
-
}
|
|
144
|
-
if (execution.abortCleanup) {
|
|
145
|
-
execution.abortCleanup();
|
|
146
|
-
}
|
|
147
|
-
execution.reject(new errors_1.ExecutionAbortedError('Queue cleared'));
|
|
148
|
-
}
|
|
149
|
-
this.queue.length = 0;
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Get queue statistics
|
|
153
|
-
*/
|
|
154
|
-
getStats() {
|
|
155
|
-
return {
|
|
156
|
-
length: this.queue.length,
|
|
157
|
-
maxSize: this.config.maxQueueSize,
|
|
158
|
-
totalQueued: this._totalQueued,
|
|
159
|
-
totalFulfilled: this._totalFulfilled,
|
|
160
|
-
totalTimedOut: this._totalTimedOut,
|
|
161
|
-
totalAborted: this._totalAborted,
|
|
162
|
-
longestWaitMs: this._longestWaitMs,
|
|
163
|
-
avgWaitMs: this._totalFulfilled > 0 ? this._totalWaitMs / this._totalFulfilled : 0,
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Reset statistics
|
|
168
|
-
*/
|
|
169
|
-
resetStats() {
|
|
170
|
-
this._totalQueued = 0;
|
|
171
|
-
this._totalFulfilled = 0;
|
|
172
|
-
this._totalTimedOut = 0;
|
|
173
|
-
this._totalAborted = 0;
|
|
174
|
-
this._longestWaitMs = 0;
|
|
175
|
-
this._totalWaitMs = 0;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
exports.ExecutionQueue = ExecutionQueue;
|
|
179
|
-
//# sourceMappingURL=execution-queue.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"execution-queue.js","sourceRoot":"","sources":["../../../../src/adapters/worker-pool/execution-queue.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAEH,qCAAoF;AA6CpF;;GAEG;AACH,MAAa,cAAc;IACR,KAAK,GAAsB,EAAE,CAAC;IAC9B,MAAM,CAA4D;IAEnF,aAAa;IACL,YAAY,GAAG,CAAC,CAAC;IACjB,eAAe,GAAG,CAAC,CAAC;IACpB,cAAc,GAAG,CAAC,CAAC;IACnB,aAAa,GAAG,CAAC,CAAC;IAClB,cAAc,GAAG,CAAC,CAAC;IACnB,YAAY,GAAG,CAAC,CAAC;IAEzB,YAAY,MAAiE;QAC3E,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC;IACvD,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,OAAO,CAAC,MAAoB;QAChC,uBAAuB;QACvB,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC;YAClD,MAAM,IAAI,uBAAc,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QACxE,CAAC;QAED,2BAA2B;QAC3B,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACpB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AAC,eAAe,GAAG,CAAC,CAAC;QACzB,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;IACxB,CAAC;CACF;AArLD,wCAqLC","sourcesContent":["/**\n * Execution Queue\n *\n * Handles backpressure when the worker pool is exhausted.\n * Queues execution requests and dispatches them when workers become available.\n *\n * @packageDocumentation\n */\n\nimport { QueueFullError, QueueTimeoutError, ExecutionAbortedError } from './errors';\nimport type { WorkerPoolConfig } from './config';\n\n/**\n * Queued execution request\n */\ninterface QueuedExecution {\n /** Unique identifier */\n id: string;\n /** Resolve function to call when a worker is available */\n resolve: (slotId: string) => void;\n /** Reject function to call on error/timeout */\n reject: (error: Error) => void;\n /** Timestamp when queued */\n enqueuedAt: number;\n /** Abort signal */\n signal?: AbortSignal;\n /** Timeout timer ID */\n timeoutId?: ReturnType<typeof setTimeout>;\n /** Abort listener cleanup function */\n abortCleanup?: () => void;\n}\n\n/**\n * Queue statistics\n */\nexport interface QueueStats {\n /** Current queue length */\n length: number;\n /** Maximum queue size */\n maxSize: number;\n /** Total requests ever queued */\n totalQueued: number;\n /** Total requests fulfilled */\n totalFulfilled: number;\n /** Total requests timed out */\n totalTimedOut: number;\n /** Total requests aborted */\n totalAborted: number;\n /** Longest wait time in milliseconds */\n longestWaitMs: number;\n /** Average wait time in milliseconds */\n avgWaitMs: number;\n}\n\n/**\n * Execution queue with configurable limits and timeout handling\n */\nexport class ExecutionQueue {\n private readonly queue: QueuedExecution[] = [];\n private readonly config: Pick<WorkerPoolConfig, 'maxQueueSize' | 'queueTimeoutMs'>;\n\n // Statistics\n private _totalQueued = 0;\n private _totalFulfilled = 0;\n private _totalTimedOut = 0;\n private _totalAborted = 0;\n private _longestWaitMs = 0;\n private _totalWaitMs = 0;\n\n constructor(config: Pick<WorkerPoolConfig, 'maxQueueSize' | 'queueTimeoutMs'>) {\n this.config = config;\n }\n\n /**\n * Get current queue length\n */\n get length(): number {\n return this.queue.length;\n }\n\n /**\n * Check if queue is full\n */\n get isFull(): boolean {\n return this.queue.length >= this.config.maxQueueSize;\n }\n\n /**\n * Enqueue an execution request\n *\n * @param signal Optional abort signal\n * @returns Promise that resolves with a slot ID when a worker is available\n * @throws QueueFullError if queue is at capacity\n * @throws QueueTimeoutError if queue wait times out\n * @throws ExecutionAbortedError if aborted via signal\n */\n async enqueue(signal?: AbortSignal): Promise<string> {\n // Check queue capacity\n if (this.queue.length >= this.config.maxQueueSize) {\n throw new QueueFullError(this.queue.length, this.config.maxQueueSize);\n }\n\n // Check if already aborted\n if (signal?.aborted) {\n throw new ExecutionAbortedError('Execution aborted before queuing');\n }\n\n const id = `queue-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n this._totalQueued++;\n\n return new Promise<string>((resolve, reject) => {\n const execution: QueuedExecution = {\n id,\n resolve,\n reject,\n enqueuedAt: Date.now(),\n signal,\n };\n\n // Set up timeout\n execution.timeoutId = setTimeout(() => {\n this.removeFromQueue(id);\n this._totalTimedOut++;\n reject(new QueueTimeoutError(Date.now() - execution.enqueuedAt));\n }, this.config.queueTimeoutMs);\n\n // Set up abort handling\n if (signal) {\n const abortHandler = () => {\n this.removeFromQueue(id);\n clearTimeout(execution.timeoutId);\n this._totalAborted++;\n reject(new ExecutionAbortedError('Execution aborted while queued'));\n };\n signal.addEventListener('abort', abortHandler, { once: true });\n execution.abortCleanup = () => {\n signal.removeEventListener('abort', abortHandler);\n };\n }\n\n this.queue.push(execution);\n });\n }\n\n /**\n * Notify the queue that a worker slot is available\n *\n * @param slotId ID of the available slot\n * @returns true if a queued request was fulfilled, false if queue was empty\n */\n notifySlotAvailable(slotId: string): boolean {\n const execution = this.queue.shift();\n if (!execution) {\n return false;\n }\n\n // Clean up timeout and abort listener\n if (execution.timeoutId) {\n clearTimeout(execution.timeoutId);\n }\n if (execution.abortCleanup) {\n execution.abortCleanup();\n }\n\n // Track statistics\n const waitTime = Date.now() - execution.enqueuedAt;\n this._totalWaitMs += waitTime;\n this._totalFulfilled++;\n if (waitTime > this._longestWaitMs) {\n this._longestWaitMs = waitTime;\n }\n\n // Fulfill the request\n execution.resolve(slotId);\n return true;\n }\n\n /**\n * Remove a specific request from the queue\n */\n private removeFromQueue(id: string): void {\n const index = this.queue.findIndex((e) => e.id === id);\n if (index !== -1) {\n const [execution] = this.queue.splice(index, 1);\n\n // Clean up\n if (execution.timeoutId) {\n clearTimeout(execution.timeoutId);\n }\n if (execution.abortCleanup) {\n execution.abortCleanup();\n }\n }\n }\n\n /**\n * Clear the queue, rejecting all pending requests\n */\n clear(): void {\n for (const execution of this.queue) {\n if (execution.timeoutId) {\n clearTimeout(execution.timeoutId);\n }\n if (execution.abortCleanup) {\n execution.abortCleanup();\n }\n execution.reject(new ExecutionAbortedError('Queue cleared'));\n }\n this.queue.length = 0;\n }\n\n /**\n * Get queue statistics\n */\n getStats(): QueueStats {\n return {\n length: this.queue.length,\n maxSize: this.config.maxQueueSize,\n totalQueued: this._totalQueued,\n totalFulfilled: this._totalFulfilled,\n totalTimedOut: this._totalTimedOut,\n totalAborted: this._totalAborted,\n longestWaitMs: this._longestWaitMs,\n avgWaitMs: this._totalFulfilled > 0 ? this._totalWaitMs / this._totalFulfilled : 0,\n };\n }\n\n /**\n * Reset statistics\n */\n resetStats(): void {\n this._totalQueued = 0;\n this._totalFulfilled = 0;\n this._totalTimedOut = 0;\n this._totalAborted = 0;\n this._longestWaitMs = 0;\n this._totalWaitMs = 0;\n }\n}\n"]}
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Worker Pool Adapter
|
|
4
|
-
*
|
|
5
|
-
* Provides a worker thread-based sandbox adapter with:
|
|
6
|
-
* - OS-level memory isolation
|
|
7
|
-
* - Hard halt capability via worker.terminate()
|
|
8
|
-
* - Pool management with min/max workers
|
|
9
|
-
* - Memory monitoring and enforcement
|
|
10
|
-
* - Rate limiting for message flood protection
|
|
11
|
-
*
|
|
12
|
-
* @packageDocumentation
|
|
13
|
-
*/
|
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.sanitizeObject = exports.safeSerialize = exports.safeDeserialize = exports.createRateLimiter = exports.RateLimiter = exports.MemoryMonitor = exports.ExecutionQueue = exports.WorkerSlot = exports.TooManyPendingCallsError = exports.WorkerStartupError = exports.MessageSizeError = exports.MessageValidationError = exports.MessageFloodError = exports.ExecutionAbortedError = exports.QueueTimeoutError = exports.QueueFullError = exports.WorkerPoolDisposedError = exports.WorkerCrashedError = exports.WorkerMemoryError = exports.WorkerTimeoutError = exports.WorkerPoolError = exports.buildWorkerPoolConfig = exports.WORKER_POOL_PRESETS = exports.DEFAULT_WORKER_POOL_CONFIG = exports.WorkerPoolAdapter = void 0;
|
|
16
|
-
/**
|
|
17
|
-
* Main worker pool adapter class
|
|
18
|
-
*/
|
|
19
|
-
var worker_pool_adapter_1 = require("./worker-pool-adapter");
|
|
20
|
-
Object.defineProperty(exports, "WorkerPoolAdapter", { enumerable: true, get: function () { return worker_pool_adapter_1.WorkerPoolAdapter; } });
|
|
21
|
-
/**
|
|
22
|
-
* Configuration types and defaults for worker pool
|
|
23
|
-
*/
|
|
24
|
-
var config_1 = require("./config");
|
|
25
|
-
Object.defineProperty(exports, "DEFAULT_WORKER_POOL_CONFIG", { enumerable: true, get: function () { return config_1.DEFAULT_WORKER_POOL_CONFIG; } });
|
|
26
|
-
Object.defineProperty(exports, "WORKER_POOL_PRESETS", { enumerable: true, get: function () { return config_1.WORKER_POOL_PRESETS; } });
|
|
27
|
-
Object.defineProperty(exports, "buildWorkerPoolConfig", { enumerable: true, get: function () { return config_1.buildWorkerPoolConfig; } });
|
|
28
|
-
/**
|
|
29
|
-
* Error classes for worker pool operations
|
|
30
|
-
*/
|
|
31
|
-
var errors_1 = require("./errors");
|
|
32
|
-
Object.defineProperty(exports, "WorkerPoolError", { enumerable: true, get: function () { return errors_1.WorkerPoolError; } });
|
|
33
|
-
Object.defineProperty(exports, "WorkerTimeoutError", { enumerable: true, get: function () { return errors_1.WorkerTimeoutError; } });
|
|
34
|
-
Object.defineProperty(exports, "WorkerMemoryError", { enumerable: true, get: function () { return errors_1.WorkerMemoryError; } });
|
|
35
|
-
Object.defineProperty(exports, "WorkerCrashedError", { enumerable: true, get: function () { return errors_1.WorkerCrashedError; } });
|
|
36
|
-
Object.defineProperty(exports, "WorkerPoolDisposedError", { enumerable: true, get: function () { return errors_1.WorkerPoolDisposedError; } });
|
|
37
|
-
Object.defineProperty(exports, "QueueFullError", { enumerable: true, get: function () { return errors_1.QueueFullError; } });
|
|
38
|
-
Object.defineProperty(exports, "QueueTimeoutError", { enumerable: true, get: function () { return errors_1.QueueTimeoutError; } });
|
|
39
|
-
Object.defineProperty(exports, "ExecutionAbortedError", { enumerable: true, get: function () { return errors_1.ExecutionAbortedError; } });
|
|
40
|
-
Object.defineProperty(exports, "MessageFloodError", { enumerable: true, get: function () { return errors_1.MessageFloodError; } });
|
|
41
|
-
Object.defineProperty(exports, "MessageValidationError", { enumerable: true, get: function () { return errors_1.MessageValidationError; } });
|
|
42
|
-
Object.defineProperty(exports, "MessageSizeError", { enumerable: true, get: function () { return errors_1.MessageSizeError; } });
|
|
43
|
-
Object.defineProperty(exports, "WorkerStartupError", { enumerable: true, get: function () { return errors_1.WorkerStartupError; } });
|
|
44
|
-
Object.defineProperty(exports, "TooManyPendingCallsError", { enumerable: true, get: function () { return errors_1.TooManyPendingCallsError; } });
|
|
45
|
-
/**
|
|
46
|
-
* Worker slot management for advanced usage
|
|
47
|
-
*/
|
|
48
|
-
var worker_slot_1 = require("./worker-slot");
|
|
49
|
-
Object.defineProperty(exports, "WorkerSlot", { enumerable: true, get: function () { return worker_slot_1.WorkerSlot; } });
|
|
50
|
-
/**
|
|
51
|
-
* Execution queue for request management
|
|
52
|
-
*/
|
|
53
|
-
var execution_queue_1 = require("./execution-queue");
|
|
54
|
-
Object.defineProperty(exports, "ExecutionQueue", { enumerable: true, get: function () { return execution_queue_1.ExecutionQueue; } });
|
|
55
|
-
/**
|
|
56
|
-
* Memory monitoring utilities
|
|
57
|
-
*/
|
|
58
|
-
var memory_monitor_1 = require("./memory-monitor");
|
|
59
|
-
Object.defineProperty(exports, "MemoryMonitor", { enumerable: true, get: function () { return memory_monitor_1.MemoryMonitor; } });
|
|
60
|
-
/**
|
|
61
|
-
* Rate limiting utilities
|
|
62
|
-
*/
|
|
63
|
-
var rate_limiter_1 = require("./rate-limiter");
|
|
64
|
-
Object.defineProperty(exports, "RateLimiter", { enumerable: true, get: function () { return rate_limiter_1.RateLimiter; } });
|
|
65
|
-
Object.defineProperty(exports, "createRateLimiter", { enumerable: true, get: function () { return rate_limiter_1.createRateLimiter; } });
|
|
66
|
-
/**
|
|
67
|
-
* Safe serialization utilities for cross-thread communication
|
|
68
|
-
*/
|
|
69
|
-
var safe_deserialize_1 = require("./safe-deserialize");
|
|
70
|
-
Object.defineProperty(exports, "safeDeserialize", { enumerable: true, get: function () { return safe_deserialize_1.safeDeserialize; } });
|
|
71
|
-
Object.defineProperty(exports, "safeSerialize", { enumerable: true, get: function () { return safe_deserialize_1.safeSerialize; } });
|
|
72
|
-
Object.defineProperty(exports, "sanitizeObject", { enumerable: true, get: function () { return safe_deserialize_1.sanitizeObject; } });
|
|
73
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/adapters/worker-pool/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;;AAEH;;GAEG;AACH,6DAA0D;AAAjD,wHAAA,iBAAiB,OAAA;AAE1B;;GAEG;AACH,mCAQkB;AAHhB,oHAAA,0BAA0B,OAAA;AAC1B,6GAAA,mBAAmB,OAAA;AACnB,+GAAA,qBAAqB,OAAA;AAGvB;;GAEG;AACH,mCAckB;AAbhB,yGAAA,eAAe,OAAA;AACf,4GAAA,kBAAkB,OAAA;AAClB,2GAAA,iBAAiB,OAAA;AACjB,4GAAA,kBAAkB,OAAA;AAClB,iHAAA,uBAAuB,OAAA;AACvB,wGAAA,cAAc,OAAA;AACd,2GAAA,iBAAiB,OAAA;AACjB,+GAAA,qBAAqB,OAAA;AACrB,2GAAA,iBAAiB,OAAA;AACjB,gHAAA,sBAAsB,OAAA;AACtB,0GAAA,gBAAgB,OAAA;AAChB,4GAAA,kBAAkB,OAAA;AAClB,kHAAA,wBAAwB,OAAA;AAkB1B;;GAEG;AACH,6CAA2C;AAAlC,yGAAA,UAAU,OAAA;AAEnB;;GAEG;AACH,qDAA+D;AAAtD,iHAAA,cAAc,OAAA;AAEvB;;GAEG;AACH,mDAAqE;AAA5D,+GAAA,aAAa,OAAA;AAEtB;;GAEG;AACH,+CAAgE;AAAvD,2GAAA,WAAW,OAAA;AAAE,iHAAA,iBAAiB,OAAA;AAEvC;;GAEG;AACH,uDAAoF;AAA3E,mHAAA,eAAe,OAAA;AAAE,iHAAA,aAAa,OAAA;AAAE,kHAAA,cAAc,OAAA","sourcesContent":["/**\n * Worker Pool Adapter\n *\n * Provides a worker thread-based sandbox adapter with:\n * - OS-level memory isolation\n * - Hard halt capability via worker.terminate()\n * - Pool management with min/max workers\n * - Memory monitoring and enforcement\n * - Rate limiting for message flood protection\n *\n * @packageDocumentation\n */\n\n/**\n * Main worker pool adapter class\n */\nexport { WorkerPoolAdapter } from './worker-pool-adapter';\n\n/**\n * Configuration types and defaults for worker pool\n */\nexport {\n WorkerPoolConfig,\n WorkerSlotStatus,\n ResourceUsage,\n WorkerPoolMetrics,\n DEFAULT_WORKER_POOL_CONFIG,\n WORKER_POOL_PRESETS,\n buildWorkerPoolConfig,\n} from './config';\n\n/**\n * Error classes for worker pool operations\n */\nexport {\n WorkerPoolError,\n WorkerTimeoutError,\n WorkerMemoryError,\n WorkerCrashedError,\n WorkerPoolDisposedError,\n QueueFullError,\n QueueTimeoutError,\n ExecutionAbortedError,\n MessageFloodError,\n MessageValidationError,\n MessageSizeError,\n WorkerStartupError,\n TooManyPendingCallsError,\n} from './errors';\n\n/**\n * Protocol types for main thread to worker communication\n */\nexport type {\n SerializedError,\n SerializedConfig,\n WorkerExecutionStats,\n MainToWorkerMessage,\n WorkerToMainMessage,\n ExecuteMessage,\n ToolCallMessage,\n ExecutionResultMessage,\n ToolResponseMessage,\n} from './protocol';\n\n/**\n * Worker slot management for advanced usage\n */\nexport { WorkerSlot } from './worker-slot';\n\n/**\n * Execution queue for request management\n */\nexport { ExecutionQueue, QueueStats } from './execution-queue';\n\n/**\n * Memory monitoring utilities\n */\nexport { MemoryMonitor, MemoryMonitorStats } from './memory-monitor';\n\n/**\n * Rate limiting utilities\n */\nexport { RateLimiter, createRateLimiter } from './rate-limiter';\n\n/**\n * Safe serialization utilities for cross-thread communication\n */\nexport { safeDeserialize, safeSerialize, sanitizeObject } from './safe-deserialize';\n"]}
|
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Memory Monitor
|
|
4
|
-
*
|
|
5
|
-
* Monitors memory usage across all worker slots and enforces limits.
|
|
6
|
-
*
|
|
7
|
-
* @packageDocumentation
|
|
8
|
-
*/
|
|
9
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
-
exports.MemoryMonitor = void 0;
|
|
11
|
-
const events_1 = require("events");
|
|
12
|
-
/**
|
|
13
|
-
* Monitors worker memory usage and enforces limits
|
|
14
|
-
*/
|
|
15
|
-
class MemoryMonitor extends events_1.EventEmitter {
|
|
16
|
-
config;
|
|
17
|
-
slots;
|
|
18
|
-
intervalId = null;
|
|
19
|
-
running = false;
|
|
20
|
-
// Statistics
|
|
21
|
-
_checksPerformed = 0;
|
|
22
|
-
_memoryExceededCount = 0;
|
|
23
|
-
_checkFailureCount = 0;
|
|
24
|
-
_peakMemoryBytes = 0;
|
|
25
|
-
_totalMemoryBytes = 0;
|
|
26
|
-
_totalSamples = 0;
|
|
27
|
-
constructor(config, slots) {
|
|
28
|
-
super();
|
|
29
|
-
this.config = {
|
|
30
|
-
memoryLimitPerWorker: config.memoryLimitPerWorker,
|
|
31
|
-
memoryCheckIntervalMs: config.memoryCheckIntervalMs,
|
|
32
|
-
memoryReportTimeoutMs: config.memoryReportTimeoutMs ?? 2000,
|
|
33
|
-
};
|
|
34
|
-
this.slots = slots;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Start periodic memory monitoring
|
|
38
|
-
*/
|
|
39
|
-
start() {
|
|
40
|
-
if (this.running) {
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
this.running = true;
|
|
44
|
-
this.intervalId = setInterval(() => {
|
|
45
|
-
this.checkAllSlots().catch((error) => {
|
|
46
|
-
console.error('Memory monitor error:', error);
|
|
47
|
-
});
|
|
48
|
-
}, this.config.memoryCheckIntervalMs);
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Stop memory monitoring
|
|
52
|
-
*/
|
|
53
|
-
stop() {
|
|
54
|
-
if (!this.running) {
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
this.running = false;
|
|
58
|
-
if (this.intervalId) {
|
|
59
|
-
clearInterval(this.intervalId);
|
|
60
|
-
this.intervalId = null;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Check if monitoring is active
|
|
65
|
-
*/
|
|
66
|
-
get isRunning() {
|
|
67
|
-
return this.running;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Perform a single check of all worker slots
|
|
71
|
-
*/
|
|
72
|
-
async checkAllSlots() {
|
|
73
|
-
this._checksPerformed++;
|
|
74
|
-
const results = new Map();
|
|
75
|
-
const promises = [];
|
|
76
|
-
for (const [slotId, slot] of this.slots) {
|
|
77
|
-
// Only check idle or executing slots with a worker
|
|
78
|
-
if ((slot.isIdle || slot.isExecuting) && slot.worker) {
|
|
79
|
-
promises.push(this.checkSlot(slotId, slot, results));
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
await Promise.allSettled(promises);
|
|
83
|
-
this.emit('checkComplete', results);
|
|
84
|
-
return results;
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Check a single slot's memory usage
|
|
88
|
-
*/
|
|
89
|
-
async checkSlot(slotId, slot, results) {
|
|
90
|
-
try {
|
|
91
|
-
const usage = await slot.requestMemoryReport(this.config.memoryReportTimeoutMs);
|
|
92
|
-
results.set(slotId, usage);
|
|
93
|
-
// Track statistics
|
|
94
|
-
this._totalMemoryBytes += usage.rss;
|
|
95
|
-
this._totalSamples++;
|
|
96
|
-
if (usage.rss > this._peakMemoryBytes) {
|
|
97
|
-
this._peakMemoryBytes = usage.rss;
|
|
98
|
-
}
|
|
99
|
-
// Check limit
|
|
100
|
-
if (usage.rss > this.config.memoryLimitPerWorker) {
|
|
101
|
-
this._memoryExceededCount++;
|
|
102
|
-
this.emit('memoryExceeded', slotId, usage, this.config.memoryLimitPerWorker);
|
|
103
|
-
// Mark slot for recycling
|
|
104
|
-
slot.markForRecycle();
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
catch (error) {
|
|
108
|
-
this._checkFailureCount++;
|
|
109
|
-
this.emit('checkFailed', slotId, error);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Check a specific slot immediately (not part of periodic checks)
|
|
114
|
-
*/
|
|
115
|
-
async checkSlotImmediate(slotId) {
|
|
116
|
-
const slot = this.slots.get(slotId);
|
|
117
|
-
if (!slot || !slot.worker) {
|
|
118
|
-
return null;
|
|
119
|
-
}
|
|
120
|
-
try {
|
|
121
|
-
const usage = await slot.requestMemoryReport(this.config.memoryReportTimeoutMs);
|
|
122
|
-
// Track statistics
|
|
123
|
-
this._totalMemoryBytes += usage.rss;
|
|
124
|
-
this._totalSamples++;
|
|
125
|
-
if (usage.rss > this._peakMemoryBytes) {
|
|
126
|
-
this._peakMemoryBytes = usage.rss;
|
|
127
|
-
}
|
|
128
|
-
return usage;
|
|
129
|
-
}
|
|
130
|
-
catch {
|
|
131
|
-
this._checkFailureCount++;
|
|
132
|
-
return null;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Get memory statistics
|
|
137
|
-
*/
|
|
138
|
-
getStats() {
|
|
139
|
-
return {
|
|
140
|
-
checksPerformed: this._checksPerformed,
|
|
141
|
-
memoryExceededCount: this._memoryExceededCount,
|
|
142
|
-
checkFailureCount: this._checkFailureCount,
|
|
143
|
-
peakMemoryBytes: this._peakMemoryBytes,
|
|
144
|
-
avgMemoryBytes: this._totalSamples > 0 ? this._totalMemoryBytes / this._totalSamples : 0,
|
|
145
|
-
totalSamples: this._totalSamples,
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* Reset statistics
|
|
150
|
-
*/
|
|
151
|
-
resetStats() {
|
|
152
|
-
this._checksPerformed = 0;
|
|
153
|
-
this._memoryExceededCount = 0;
|
|
154
|
-
this._checkFailureCount = 0;
|
|
155
|
-
this._peakMemoryBytes = 0;
|
|
156
|
-
this._totalMemoryBytes = 0;
|
|
157
|
-
this._totalSamples = 0;
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Get current memory usage summary
|
|
161
|
-
*/
|
|
162
|
-
getCurrentUsageSummary() {
|
|
163
|
-
let totalRss = 0;
|
|
164
|
-
let maxRss = 0;
|
|
165
|
-
let slotCount = 0;
|
|
166
|
-
for (const slot of this.slots.values()) {
|
|
167
|
-
if (slot.memoryUsage) {
|
|
168
|
-
totalRss += slot.memoryUsage.rss;
|
|
169
|
-
if (slot.memoryUsage.rss > maxRss) {
|
|
170
|
-
maxRss = slot.memoryUsage.rss;
|
|
171
|
-
}
|
|
172
|
-
slotCount++;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return {
|
|
176
|
-
totalRss,
|
|
177
|
-
avgRss: slotCount > 0 ? totalRss / slotCount : 0,
|
|
178
|
-
maxRss,
|
|
179
|
-
slotCount,
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
exports.MemoryMonitor = MemoryMonitor;
|
|
184
|
-
//# sourceMappingURL=memory-monitor.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"memory-monitor.js","sourceRoot":"","sources":["../../../../src/adapters/worker-pool/memory-monitor.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,mCAAsC;AA8CtC;;GAEG;AACH,MAAa,aAAc,SAAQ,qBAAY;IAC5B,MAAM,CAAgC;IACtC,KAAK,CAA0B;IACxC,UAAU,GAA0C,IAAI,CAAC;IACzD,OAAO,GAAG,KAAK,CAAC;IAExB,aAAa;IACL,gBAAgB,GAAG,CAAC,CAAC;IACrB,oBAAoB,GAAG,CAAC,CAAC;IACzB,kBAAkB,GAAG,CAAC,CAAC;IACvB,gBAAgB,GAAG,CAAC,CAAC;IACrB,iBAAiB,GAAG,CAAC,CAAC;IACtB,aAAa,GAAG,CAAC,CAAC;IAE1B,YAAY,MAA2B,EAAE,KAA8B;QACrE,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,MAAM,GAAG;YACZ,oBAAoB,EAAE,MAAM,CAAC,oBAAoB;YACjD,qBAAqB,EAAE,MAAM,CAAC,qBAAqB;YACnD,qBAAqB,EAAE,MAAM,CAAC,qBAAqB,IAAI,IAAI;SAC5D,CAAC;QACF,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE;YACjC,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE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AAG,CAAC,CAAC;QAElB,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YACvC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;gBACrB,QAAQ,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC;gBACjC,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,GAAG,MAAM,EAAE,CAAC;oBAClC,MAAM,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC;gBAChC,CAAC;gBACD,SAAS,EAAE,CAAC;YACd,CAAC;QACH,CAAC;QAED,OAAO;YACL,QAAQ;YACR,MAAM,EAAE,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;YAChD,MAAM;YACN,SAAS;SACV,CAAC;IACJ,CAAC;CACF;AAjMD,sCAiMC","sourcesContent":["/**\n * Memory Monitor\n *\n * Monitors memory usage across all worker slots and enforces limits.\n *\n * @packageDocumentation\n */\n\nimport { EventEmitter } from 'events';\nimport type { ResourceUsage } from './config';\nimport type { WorkerSlot } from './worker-slot';\n\n/**\n * Events emitted by MemoryMonitor\n */\nexport interface MemoryMonitorEvents {\n /** A worker exceeded memory limit */\n memoryExceeded: [slotId: string, usage: ResourceUsage, limit: number];\n /** Memory check failed for a worker */\n checkFailed: [slotId: string, error: Error];\n /** Memory check completed */\n checkComplete: [results: Map<string, ResourceUsage>];\n}\n\n/**\n * Memory monitor configuration\n */\nexport interface MemoryMonitorConfig {\n /** Memory limit per worker in bytes */\n memoryLimitPerWorker: number;\n /** Check interval in milliseconds */\n memoryCheckIntervalMs: number;\n /** Timeout for memory report requests */\n memoryReportTimeoutMs?: number;\n}\n\n/**\n * Memory monitor statistics\n */\nexport interface MemoryMonitorStats {\n /** Number of checks performed */\n checksPerformed: number;\n /** Number of memory exceeded events */\n memoryExceededCount: number;\n /** Number of check failures */\n checkFailureCount: number;\n /** Peak memory usage observed (bytes) */\n peakMemoryBytes: number;\n /** Average memory usage (bytes) */\n avgMemoryBytes: number;\n /** Total samples collected */\n totalSamples: number;\n}\n\n/**\n * Monitors worker memory usage and enforces limits\n */\nexport class MemoryMonitor extends EventEmitter {\n private readonly config: Required<MemoryMonitorConfig>;\n private readonly slots: Map<string, WorkerSlot>;\n private intervalId: ReturnType<typeof setInterval> | null = null;\n private running = false;\n\n // Statistics\n private _checksPerformed = 0;\n private _memoryExceededCount = 0;\n private _checkFailureCount = 0;\n private _peakMemoryBytes = 0;\n private _totalMemoryBytes = 0;\n private _totalSamples = 0;\n\n constructor(config: MemoryMonitorConfig, slots: Map<string, WorkerSlot>) {\n super();\n this.config = {\n memoryLimitPerWorker: config.memoryLimitPerWorker,\n memoryCheckIntervalMs: config.memoryCheckIntervalMs,\n memoryReportTimeoutMs: config.memoryReportTimeoutMs ?? 2000,\n };\n this.slots = slots;\n }\n\n /**\n * Start periodic memory monitoring\n */\n start(): void {\n if (this.running) {\n return;\n }\n\n this.running = true;\n this.intervalId = setInterval(() => {\n this.checkAllSlots().catch((error) => {\n console.error('Memory monitor error:', error);\n });\n }, this.config.memoryCheckIntervalMs);\n }\n\n /**\n * Stop memory monitoring\n */\n stop(): void {\n if (!this.running) {\n return;\n }\n\n this.running = false;\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n }\n\n /**\n * Check if monitoring is active\n */\n get isRunning(): boolean {\n return this.running;\n }\n\n /**\n * Perform a single check of all worker slots\n */\n async checkAllSlots(): Promise<Map<string, ResourceUsage>> {\n this._checksPerformed++;\n const results = new Map<string, ResourceUsage>();\n const promises: Promise<void>[] = [];\n\n for (const [slotId, slot] of this.slots) {\n // Only check idle or executing slots with a worker\n if ((slot.isIdle || slot.isExecuting) && slot.worker) {\n promises.push(this.checkSlot(slotId, slot, results));\n }\n }\n\n await Promise.allSettled(promises);\n this.emit('checkComplete', results);\n return results;\n }\n\n /**\n * Check a single slot's memory usage\n */\n private async checkSlot(slotId: string, slot: WorkerSlot, results: Map<string, ResourceUsage>): Promise<void> {\n try {\n const usage = await slot.requestMemoryReport(this.config.memoryReportTimeoutMs);\n results.set(slotId, usage);\n\n // Track statistics\n this._totalMemoryBytes += usage.rss;\n this._totalSamples++;\n if (usage.rss > this._peakMemoryBytes) {\n this._peakMemoryBytes = usage.rss;\n }\n\n // Check limit\n if (usage.rss > this.config.memoryLimitPerWorker) {\n this._memoryExceededCount++;\n this.emit('memoryExceeded', slotId, usage, this.config.memoryLimitPerWorker);\n\n // Mark slot for recycling\n slot.markForRecycle();\n }\n } catch (error) {\n this._checkFailureCount++;\n this.emit('checkFailed', slotId, error as Error);\n }\n }\n\n /**\n * Check a specific slot immediately (not part of periodic checks)\n */\n async checkSlotImmediate(slotId: string): Promise<ResourceUsage | null> {\n const slot = this.slots.get(slotId);\n if (!slot || !slot.worker) {\n return null;\n }\n\n try {\n const usage = await slot.requestMemoryReport(this.config.memoryReportTimeoutMs);\n\n // Track statistics\n this._totalMemoryBytes += usage.rss;\n this._totalSamples++;\n if (usage.rss > this._peakMemoryBytes) {\n this._peakMemoryBytes = usage.rss;\n }\n\n return usage;\n } catch {\n this._checkFailureCount++;\n return null;\n }\n }\n\n /**\n * Get memory statistics\n */\n getStats(): MemoryMonitorStats {\n return {\n checksPerformed: this._checksPerformed,\n memoryExceededCount: this._memoryExceededCount,\n checkFailureCount: this._checkFailureCount,\n peakMemoryBytes: this._peakMemoryBytes,\n avgMemoryBytes: this._totalSamples > 0 ? this._totalMemoryBytes / this._totalSamples : 0,\n totalSamples: this._totalSamples,\n };\n }\n\n /**\n * Reset statistics\n */\n resetStats(): void {\n this._checksPerformed = 0;\n this._memoryExceededCount = 0;\n this._checkFailureCount = 0;\n this._peakMemoryBytes = 0;\n this._totalMemoryBytes = 0;\n this._totalSamples = 0;\n }\n\n /**\n * Get current memory usage summary\n */\n getCurrentUsageSummary(): {\n totalRss: number;\n avgRss: number;\n maxRss: number;\n slotCount: number;\n } {\n let totalRss = 0;\n let maxRss = 0;\n let slotCount = 0;\n\n for (const slot of this.slots.values()) {\n if (slot.memoryUsage) {\n totalRss += slot.memoryUsage.rss;\n if (slot.memoryUsage.rss > maxRss) {\n maxRss = slot.memoryUsage.rss;\n }\n slotCount++;\n }\n }\n\n return {\n totalRss,\n avgRss: slotCount > 0 ? totalRss / slotCount : 0,\n maxRss,\n slotCount,\n };\n }\n}\n"]}
|
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Worker Pool Message Protocol
|
|
4
|
-
*
|
|
5
|
-
* Type definitions for messages exchanged between main thread and worker threads.
|
|
6
|
-
* All messages are JSON-serialized to prevent structured clone attacks.
|
|
7
|
-
*
|
|
8
|
-
* @packageDocumentation
|
|
9
|
-
*/
|
|
10
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
-
exports.workerToMainMessageSchema = exports.workerReadyMessageSchema = exports.consoleMessageSchema = exports.memoryReportResultMessageSchema = exports.executionResultMessageSchema = exports.toolCallMessageSchema = void 0;
|
|
12
|
-
exports.isToolCallMessage = isToolCallMessage;
|
|
13
|
-
exports.isExecutionResultMessage = isExecutionResultMessage;
|
|
14
|
-
exports.isMemoryReportResultMessage = isMemoryReportResultMessage;
|
|
15
|
-
exports.isConsoleMessage = isConsoleMessage;
|
|
16
|
-
exports.isWorkerReadyMessage = isWorkerReadyMessage;
|
|
17
|
-
const zod_1 = require("zod");
|
|
18
|
-
// ============================================================================
|
|
19
|
-
// Message Validation Schemas
|
|
20
|
-
// ============================================================================
|
|
21
|
-
/**
|
|
22
|
-
* Tool name regex pattern
|
|
23
|
-
* Allows: letters, numbers, colons, underscores, hyphens
|
|
24
|
-
* Must start with a letter
|
|
25
|
-
*/
|
|
26
|
-
const TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;
|
|
27
|
-
/**
|
|
28
|
-
* UUID-like pattern for request/call IDs
|
|
29
|
-
*/
|
|
30
|
-
const ID_PATTERN = /^[a-zA-Z0-9-]+$/;
|
|
31
|
-
/**
|
|
32
|
-
* Zod schema for tool call messages
|
|
33
|
-
*/
|
|
34
|
-
exports.toolCallMessageSchema = zod_1.z
|
|
35
|
-
.object({
|
|
36
|
-
type: zod_1.z.literal('tool-call'),
|
|
37
|
-
requestId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
|
|
38
|
-
callId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
|
|
39
|
-
toolName: zod_1.z.string().min(1).max(256).regex(TOOL_NAME_PATTERN),
|
|
40
|
-
args: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()),
|
|
41
|
-
})
|
|
42
|
-
.strict();
|
|
43
|
-
/**
|
|
44
|
-
* Zod schema for execution result messages
|
|
45
|
-
*/
|
|
46
|
-
exports.executionResultMessageSchema = zod_1.z
|
|
47
|
-
.object({
|
|
48
|
-
type: zod_1.z.literal('result'),
|
|
49
|
-
requestId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
|
|
50
|
-
success: zod_1.z.boolean(),
|
|
51
|
-
value: zod_1.z.unknown().optional(),
|
|
52
|
-
error: zod_1.z
|
|
53
|
-
.object({
|
|
54
|
-
name: zod_1.z.string().max(100),
|
|
55
|
-
message: zod_1.z.string().max(10000),
|
|
56
|
-
code: zod_1.z.string().max(100).optional(),
|
|
57
|
-
stack: zod_1.z.string().max(10000).optional(),
|
|
58
|
-
})
|
|
59
|
-
.optional(),
|
|
60
|
-
stats: zod_1.z.object({
|
|
61
|
-
duration: zod_1.z.number().nonnegative(),
|
|
62
|
-
toolCallCount: zod_1.z.number().nonnegative().int(),
|
|
63
|
-
iterationCount: zod_1.z.number().nonnegative().int(),
|
|
64
|
-
startTime: zod_1.z.number().nonnegative(),
|
|
65
|
-
endTime: zod_1.z.number().nonnegative(),
|
|
66
|
-
}),
|
|
67
|
-
})
|
|
68
|
-
.strict();
|
|
69
|
-
/**
|
|
70
|
-
* Zod schema for memory report result messages
|
|
71
|
-
*/
|
|
72
|
-
exports.memoryReportResultMessageSchema = zod_1.z
|
|
73
|
-
.object({
|
|
74
|
-
type: zod_1.z.literal('memory-report-result'),
|
|
75
|
-
usage: zod_1.z.object({
|
|
76
|
-
rss: zod_1.z.number().nonnegative(),
|
|
77
|
-
heapTotal: zod_1.z.number().nonnegative(),
|
|
78
|
-
heapUsed: zod_1.z.number().nonnegative(),
|
|
79
|
-
external: zod_1.z.number().nonnegative(),
|
|
80
|
-
arrayBuffers: zod_1.z.number().nonnegative(),
|
|
81
|
-
}),
|
|
82
|
-
})
|
|
83
|
-
.strict();
|
|
84
|
-
/**
|
|
85
|
-
* Zod schema for console messages
|
|
86
|
-
*/
|
|
87
|
-
exports.consoleMessageSchema = zod_1.z
|
|
88
|
-
.object({
|
|
89
|
-
type: zod_1.z.literal('console'),
|
|
90
|
-
requestId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
|
|
91
|
-
level: zod_1.z.enum(['log', 'warn', 'error', 'info']),
|
|
92
|
-
args: zod_1.z.array(zod_1.z.unknown()).max(100),
|
|
93
|
-
})
|
|
94
|
-
.strict();
|
|
95
|
-
/**
|
|
96
|
-
* Zod schema for worker ready messages
|
|
97
|
-
*/
|
|
98
|
-
exports.workerReadyMessageSchema = zod_1.z
|
|
99
|
-
.object({
|
|
100
|
-
type: zod_1.z.literal('ready'),
|
|
101
|
-
})
|
|
102
|
-
.strict();
|
|
103
|
-
/**
|
|
104
|
-
* Union schema for all worker-to-main messages
|
|
105
|
-
*/
|
|
106
|
-
exports.workerToMainMessageSchema = zod_1.z.discriminatedUnion('type', [
|
|
107
|
-
exports.workerReadyMessageSchema,
|
|
108
|
-
exports.toolCallMessageSchema,
|
|
109
|
-
exports.executionResultMessageSchema,
|
|
110
|
-
exports.memoryReportResultMessageSchema,
|
|
111
|
-
exports.consoleMessageSchema,
|
|
112
|
-
]);
|
|
113
|
-
/**
|
|
114
|
-
* Type guard for tool call messages
|
|
115
|
-
*/
|
|
116
|
-
function isToolCallMessage(msg) {
|
|
117
|
-
return msg.type === 'tool-call';
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Type guard for execution result messages
|
|
121
|
-
*/
|
|
122
|
-
function isExecutionResultMessage(msg) {
|
|
123
|
-
return msg.type === 'result';
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* Type guard for memory report result messages
|
|
127
|
-
*/
|
|
128
|
-
function isMemoryReportResultMessage(msg) {
|
|
129
|
-
return msg.type === 'memory-report-result';
|
|
130
|
-
}
|
|
131
|
-
/**
|
|
132
|
-
* Type guard for console messages
|
|
133
|
-
*/
|
|
134
|
-
function isConsoleMessage(msg) {
|
|
135
|
-
return msg.type === 'console';
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Type guard for worker ready messages
|
|
139
|
-
*/
|
|
140
|
-
function isWorkerReadyMessage(msg) {
|
|
141
|
-
return msg.type === 'ready';
|
|
142
|
-
}
|
|
143
|
-
//# sourceMappingURL=protocol.js.map
|