@enclave-vm/core 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.
Files changed (169) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +732 -0
  3. package/SECURITY-AUDIT.md +916 -0
  4. package/package.json +59 -0
  5. package/src/adapters/vm-adapter.d.ts +32 -0
  6. package/src/adapters/vm-adapter.js +1140 -0
  7. package/src/adapters/vm-adapter.js.map +1 -0
  8. package/src/adapters/worker-pool/config.d.ts +149 -0
  9. package/src/adapters/worker-pool/config.js +129 -0
  10. package/src/adapters/worker-pool/config.js.map +1 -0
  11. package/src/adapters/worker-pool/errors.d.ts +109 -0
  12. package/src/adapters/worker-pool/errors.js +181 -0
  13. package/src/adapters/worker-pool/errors.js.map +1 -0
  14. package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
  15. package/src/adapters/worker-pool/execution-queue.js +179 -0
  16. package/src/adapters/worker-pool/execution-queue.js.map +1 -0
  17. package/src/adapters/worker-pool/index.d.ts +48 -0
  18. package/src/adapters/worker-pool/index.js +73 -0
  19. package/src/adapters/worker-pool/index.js.map +1 -0
  20. package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
  21. package/src/adapters/worker-pool/memory-monitor.js +184 -0
  22. package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
  23. package/src/adapters/worker-pool/protocol.d.ts +314 -0
  24. package/src/adapters/worker-pool/protocol.js +143 -0
  25. package/src/adapters/worker-pool/protocol.js.map +1 -0
  26. package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
  27. package/src/adapters/worker-pool/rate-limiter.js +101 -0
  28. package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
  29. package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
  30. package/src/adapters/worker-pool/safe-deserialize.js +141 -0
  31. package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
  32. package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
  33. package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
  34. package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
  35. package/src/adapters/worker-pool/worker-script.d.ts +12 -0
  36. package/src/adapters/worker-pool/worker-script.js +770 -0
  37. package/src/adapters/worker-pool/worker-script.js.map +1 -0
  38. package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
  39. package/src/adapters/worker-pool/worker-slot.js +301 -0
  40. package/src/adapters/worker-pool/worker-slot.js.map +1 -0
  41. package/src/babel/babel-wrapper.d.ts +118 -0
  42. package/src/babel/babel-wrapper.js +395 -0
  43. package/src/babel/babel-wrapper.js.map +1 -0
  44. package/src/babel/index.d.ts +9 -0
  45. package/src/babel/index.js +17 -0
  46. package/src/babel/index.js.map +1 -0
  47. package/src/babel/multi-file-transform.d.ts +122 -0
  48. package/src/babel/multi-file-transform.js +344 -0
  49. package/src/babel/multi-file-transform.js.map +1 -0
  50. package/src/double-vm/double-vm-wrapper.d.ts +65 -0
  51. package/src/double-vm/double-vm-wrapper.js +523 -0
  52. package/src/double-vm/double-vm-wrapper.js.map +1 -0
  53. package/src/double-vm/index.d.ts +31 -0
  54. package/src/double-vm/index.js +34 -0
  55. package/src/double-vm/index.js.map +1 -0
  56. package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
  57. package/src/double-vm/parent-vm-bootstrap.js +1695 -0
  58. package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
  59. package/src/double-vm/suspicious-patterns.d.ts +57 -0
  60. package/src/double-vm/suspicious-patterns.js +304 -0
  61. package/src/double-vm/suspicious-patterns.js.map +1 -0
  62. package/src/double-vm/types.d.ts +178 -0
  63. package/src/double-vm/types.js +11 -0
  64. package/src/double-vm/types.js.map +1 -0
  65. package/src/double-vm/wrap-adapter.d.ts +36 -0
  66. package/src/double-vm/wrap-adapter.js +59 -0
  67. package/src/double-vm/wrap-adapter.js.map +1 -0
  68. package/src/enclave.d.ts +159 -0
  69. package/src/enclave.js +671 -0
  70. package/src/enclave.js.map +1 -0
  71. package/src/globals-validator.d.ts +80 -0
  72. package/src/globals-validator.js +206 -0
  73. package/src/globals-validator.js.map +1 -0
  74. package/src/index.d.ts +29 -0
  75. package/src/index.js +130 -0
  76. package/src/index.js.map +1 -0
  77. package/src/memory-proxy.d.ts +69 -0
  78. package/src/memory-proxy.js +310 -0
  79. package/src/memory-proxy.js.map +1 -0
  80. package/src/memory-tracker.d.ts +170 -0
  81. package/src/memory-tracker.js +230 -0
  82. package/src/memory-tracker.js.map +1 -0
  83. package/src/safe-error.d.ts +18 -0
  84. package/src/safe-error.js +76 -0
  85. package/src/safe-error.js.map +1 -0
  86. package/src/safe-runtime.d.ts +72 -0
  87. package/src/safe-runtime.js +656 -0
  88. package/src/safe-runtime.js.map +1 -0
  89. package/src/scoring/cache.d.ts +68 -0
  90. package/src/scoring/cache.js +158 -0
  91. package/src/scoring/cache.js.map +1 -0
  92. package/src/scoring/feature-extractor.d.ts +61 -0
  93. package/src/scoring/feature-extractor.js +366 -0
  94. package/src/scoring/feature-extractor.js.map +1 -0
  95. package/src/scoring/index.d.ts +33 -0
  96. package/src/scoring/index.js +53 -0
  97. package/src/scoring/index.js.map +1 -0
  98. package/src/scoring/scorer.interface.d.ts +65 -0
  99. package/src/scoring/scorer.interface.js +49 -0
  100. package/src/scoring/scorer.interface.js.map +1 -0
  101. package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
  102. package/src/scoring/scorers/disabled.scorer.js +34 -0
  103. package/src/scoring/scorers/disabled.scorer.js.map +1 -0
  104. package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
  105. package/src/scoring/scorers/external-api.scorer.js +141 -0
  106. package/src/scoring/scorers/external-api.scorer.js.map +1 -0
  107. package/src/scoring/scorers/index.d.ts +10 -0
  108. package/src/scoring/scorers/index.js +22 -0
  109. package/src/scoring/scorers/index.js.map +1 -0
  110. package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
  111. package/src/scoring/scorers/local-llm.scorer.js +474 -0
  112. package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
  113. package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
  114. package/src/scoring/scorers/progressive.scorer.js +199 -0
  115. package/src/scoring/scorers/progressive.scorer.js.map +1 -0
  116. package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
  117. package/src/scoring/scorers/rule-based.scorer.js +316 -0
  118. package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
  119. package/src/scoring/scoring-gate.d.ts +76 -0
  120. package/src/scoring/scoring-gate.js +246 -0
  121. package/src/scoring/scoring-gate.js.map +1 -0
  122. package/src/scoring/types.d.ts +690 -0
  123. package/src/scoring/types.js +107 -0
  124. package/src/scoring/types.js.map +1 -0
  125. package/src/secure-proxy.d.ts +157 -0
  126. package/src/secure-proxy.js +609 -0
  127. package/src/secure-proxy.js.map +1 -0
  128. package/src/session/channels/embedded-channel.d.ts +76 -0
  129. package/src/session/channels/embedded-channel.js +130 -0
  130. package/src/session/channels/embedded-channel.js.map +1 -0
  131. package/src/session/channels/index.d.ts +9 -0
  132. package/src/session/channels/index.js +14 -0
  133. package/src/session/channels/index.js.map +1 -0
  134. package/src/session/index.d.ts +15 -0
  135. package/src/session/index.js +27 -0
  136. package/src/session/index.js.map +1 -0
  137. package/src/session/session-emitter.d.ts +119 -0
  138. package/src/session/session-emitter.js +253 -0
  139. package/src/session/session-emitter.js.map +1 -0
  140. package/src/session/session-state-machine.d.ts +108 -0
  141. package/src/session/session-state-machine.js +182 -0
  142. package/src/session/session-state-machine.js.map +1 -0
  143. package/src/session/session.d.ts +135 -0
  144. package/src/session/session.js +398 -0
  145. package/src/session/session.js.map +1 -0
  146. package/src/session-types.d.ts +313 -0
  147. package/src/session-types.js +39 -0
  148. package/src/session-types.js.map +1 -0
  149. package/src/sidecar/index.d.ts +12 -0
  150. package/src/sidecar/index.js +31 -0
  151. package/src/sidecar/index.js.map +1 -0
  152. package/src/sidecar/reference-config.d.ts +81 -0
  153. package/src/sidecar/reference-config.js +118 -0
  154. package/src/sidecar/reference-config.js.map +1 -0
  155. package/src/sidecar/reference-resolver.d.ts +115 -0
  156. package/src/sidecar/reference-resolver.js +262 -0
  157. package/src/sidecar/reference-resolver.js.map +1 -0
  158. package/src/sidecar/reference-sidecar.d.ts +161 -0
  159. package/src/sidecar/reference-sidecar.js +226 -0
  160. package/src/sidecar/reference-sidecar.js.map +1 -0
  161. package/src/tool-bridge.d.ts +4 -0
  162. package/src/tool-bridge.js +306 -0
  163. package/src/tool-bridge.js.map +1 -0
  164. package/src/types.d.ts +775 -0
  165. package/src/types.js +187 -0
  166. package/src/types.js.map +1 -0
  167. package/src/value-sanitizer.d.ts +133 -0
  168. package/src/value-sanitizer.js +421 -0
  169. package/src/value-sanitizer.js.map +1 -0
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ /**
3
+ * Worker Pool Error Classes
4
+ *
5
+ * Specialized errors for worker pool operations.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ 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 = void 0;
11
+ /**
12
+ * Base class for worker pool errors
13
+ */
14
+ class WorkerPoolError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = 'WorkerPoolError';
18
+ // Maintain proper stack trace in V8
19
+ if (Error.captureStackTrace) {
20
+ Error.captureStackTrace(this, this.constructor);
21
+ }
22
+ }
23
+ }
24
+ exports.WorkerPoolError = WorkerPoolError;
25
+ /**
26
+ * Worker execution timed out and was terminated
27
+ */
28
+ class WorkerTimeoutError extends WorkerPoolError {
29
+ constructor(message = 'Worker execution timeout - worker terminated') {
30
+ super(message);
31
+ this.name = 'WorkerTimeoutError';
32
+ }
33
+ }
34
+ exports.WorkerTimeoutError = WorkerTimeoutError;
35
+ /**
36
+ * Worker exceeded memory limits and was terminated
37
+ */
38
+ class WorkerMemoryError extends WorkerPoolError {
39
+ /** Memory usage that triggered the error */
40
+ memoryBytes;
41
+ /** Configured limit */
42
+ limitBytes;
43
+ constructor(memoryBytes, limitBytes) {
44
+ super(`Worker exceeded memory limit: ${Math.round(memoryBytes / 1024 / 1024)}MB > ${Math.round(limitBytes / 1024 / 1024)}MB`);
45
+ this.name = 'WorkerMemoryError';
46
+ this.memoryBytes = memoryBytes;
47
+ this.limitBytes = limitBytes;
48
+ }
49
+ }
50
+ exports.WorkerMemoryError = WorkerMemoryError;
51
+ /**
52
+ * Worker crashed or was terminated unexpectedly
53
+ */
54
+ class WorkerCrashedError extends WorkerPoolError {
55
+ /** Exit code if available */
56
+ exitCode;
57
+ constructor(message, exitCode) {
58
+ super(message);
59
+ this.name = 'WorkerCrashedError';
60
+ this.exitCode = exitCode;
61
+ }
62
+ }
63
+ exports.WorkerCrashedError = WorkerCrashedError;
64
+ /**
65
+ * Worker pool is disposed and cannot accept new executions
66
+ */
67
+ class WorkerPoolDisposedError extends WorkerPoolError {
68
+ constructor() {
69
+ super('Worker pool has been disposed');
70
+ this.name = 'WorkerPoolDisposedError';
71
+ }
72
+ }
73
+ exports.WorkerPoolDisposedError = WorkerPoolDisposedError;
74
+ /**
75
+ * Execution queue is full
76
+ */
77
+ class QueueFullError extends WorkerPoolError {
78
+ /** Current queue size */
79
+ queueSize;
80
+ /** Maximum queue size */
81
+ maxSize;
82
+ constructor(queueSize, maxSize) {
83
+ super(`Execution queue is full: ${queueSize}/${maxSize} requests waiting`);
84
+ this.name = 'QueueFullError';
85
+ this.queueSize = queueSize;
86
+ this.maxSize = maxSize;
87
+ }
88
+ }
89
+ exports.QueueFullError = QueueFullError;
90
+ /**
91
+ * Queue wait timed out
92
+ */
93
+ class QueueTimeoutError extends WorkerPoolError {
94
+ /** Time waited in milliseconds */
95
+ waitedMs;
96
+ constructor(waitedMs) {
97
+ super(`Queue timeout after ${waitedMs}ms`);
98
+ this.name = 'QueueTimeoutError';
99
+ this.waitedMs = waitedMs;
100
+ }
101
+ }
102
+ exports.QueueTimeoutError = QueueTimeoutError;
103
+ /**
104
+ * Execution was aborted
105
+ */
106
+ class ExecutionAbortedError extends WorkerPoolError {
107
+ constructor(reason = 'Execution aborted') {
108
+ super(reason);
109
+ this.name = 'ExecutionAbortedError';
110
+ }
111
+ }
112
+ exports.ExecutionAbortedError = ExecutionAbortedError;
113
+ /**
114
+ * Message rate limit exceeded
115
+ */
116
+ class MessageFloodError extends WorkerPoolError {
117
+ /** Worker slot ID */
118
+ slotId;
119
+ constructor(slotId) {
120
+ super('Message rate limit exceeded');
121
+ this.name = 'MessageFloodError';
122
+ this.slotId = slotId;
123
+ }
124
+ }
125
+ exports.MessageFloodError = MessageFloodError;
126
+ /**
127
+ * Message validation failed
128
+ */
129
+ class MessageValidationError extends WorkerPoolError {
130
+ constructor(details) {
131
+ super(details ? `Invalid message: ${details}` : 'Invalid message format');
132
+ this.name = 'MessageValidationError';
133
+ }
134
+ }
135
+ exports.MessageValidationError = MessageValidationError;
136
+ /**
137
+ * Message size exceeded limit
138
+ */
139
+ class MessageSizeError extends WorkerPoolError {
140
+ /** Actual message size */
141
+ sizeBytes;
142
+ /** Maximum allowed size */
143
+ maxBytes;
144
+ constructor(sizeBytes, maxBytes) {
145
+ super(`Message size ${Math.round(sizeBytes / 1024)}KB exceeds limit ${Math.round(maxBytes / 1024)}KB`);
146
+ this.name = 'MessageSizeError';
147
+ this.sizeBytes = sizeBytes;
148
+ this.maxBytes = maxBytes;
149
+ }
150
+ }
151
+ exports.MessageSizeError = MessageSizeError;
152
+ /**
153
+ * Worker failed to start
154
+ */
155
+ class WorkerStartupError extends WorkerPoolError {
156
+ /** Original error that caused startup failure */
157
+ cause;
158
+ constructor(message, cause) {
159
+ super(message);
160
+ this.name = 'WorkerStartupError';
161
+ this.cause = cause;
162
+ }
163
+ }
164
+ exports.WorkerStartupError = WorkerStartupError;
165
+ /**
166
+ * Too many pending tool calls
167
+ */
168
+ class TooManyPendingCallsError extends WorkerPoolError {
169
+ /** Current pending count */
170
+ pending;
171
+ /** Maximum allowed */
172
+ max;
173
+ constructor(pending, max) {
174
+ super(`Too many pending tool calls: ${pending}/${max}`);
175
+ this.name = 'TooManyPendingCallsError';
176
+ this.pending = pending;
177
+ this.max = max;
178
+ }
179
+ }
180
+ exports.TooManyPendingCallsError = TooManyPendingCallsError;
181
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/adapters/worker-pool/errors.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH;;GAEG;AACH,MAAa,eAAgB,SAAQ,KAAK;IACxC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,oCAAoC;QACpC,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;YAC5B,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;CACF;AATD,0CASC;AAED;;GAEG;AACH,MAAa,kBAAmB,SAAQ,eAAe;IACrD,YAAY,OAAO,GAAG,8CAA8C;QAClE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AALD,gDAKC;AAED;;GAEG;AACH,MAAa,iBAAkB,SAAQ,eAAe;IACpD,4CAA4C;IACnC,WAAW,CAAS;IAC7B,uBAAuB;IACd,UAAU,CAAS;IAE5B,YAAY,WAAmB,EAAE,UAAkB;QACjD,KAAK,CACH,iCAAiC,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,IAAI,GAAG,IAAI,CAAC,QAAQ,IAAI,CAAC,KAAK,CACtF,UAAU,GAAG,IAAI,GAAG,I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,CAAS;IAEhC,YAAY,OAAe,EAAE,KAAa;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AATD,gDASC;AAED;;GAEG;AACH,MAAa,wBAAyB,SAAQ,eAAe;IAC3D,4BAA4B;IACnB,OAAO,CAAS;IACzB,sBAAsB;IACb,GAAG,CAAS;IAErB,YAAY,OAAe,EAAE,GAAW;QACtC,KAAK,CAAC,gCAAgC,OAAO,IAAI,GAAG,EAAE,CAAC,CAAC;QACxD,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;CACF;AAZD,4DAYC","sourcesContent":["/**\n * Worker Pool Error Classes\n *\n * Specialized errors for worker pool operations.\n *\n * @packageDocumentation\n */\n\n/**\n * Base class for worker pool errors\n */\nexport class WorkerPoolError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WorkerPoolError';\n // Maintain proper stack trace in V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Worker execution timed out and was terminated\n */\nexport class WorkerTimeoutError extends WorkerPoolError {\n constructor(message = 'Worker execution timeout - worker terminated') {\n super(message);\n this.name = 'WorkerTimeoutError';\n }\n}\n\n/**\n * Worker exceeded memory limits and was terminated\n */\nexport class WorkerMemoryError extends WorkerPoolError {\n /** Memory usage that triggered the error */\n readonly memoryBytes: number;\n /** Configured limit */\n readonly limitBytes: number;\n\n constructor(memoryBytes: number, limitBytes: number) {\n super(\n `Worker exceeded memory limit: ${Math.round(memoryBytes / 1024 / 1024)}MB > ${Math.round(\n limitBytes / 1024 / 1024,\n )}MB`,\n );\n this.name = 'WorkerMemoryError';\n this.memoryBytes = memoryBytes;\n this.limitBytes = limitBytes;\n }\n}\n\n/**\n * Worker crashed or was terminated unexpectedly\n */\nexport class WorkerCrashedError extends WorkerPoolError {\n /** Exit code if available */\n readonly exitCode?: number;\n\n constructor(message: string, exitCode?: number) {\n super(message);\n this.name = 'WorkerCrashedError';\n this.exitCode = exitCode;\n }\n}\n\n/**\n * Worker pool is disposed and cannot accept new executions\n */\nexport class WorkerPoolDisposedError extends WorkerPoolError {\n constructor() {\n super('Worker pool has been disposed');\n this.name = 'WorkerPoolDisposedError';\n }\n}\n\n/**\n * Execution queue is full\n */\nexport class QueueFullError extends WorkerPoolError {\n /** Current queue size */\n readonly queueSize: number;\n /** Maximum queue size */\n readonly maxSize: number;\n\n constructor(queueSize: number, maxSize: number) {\n super(`Execution queue is full: ${queueSize}/${maxSize} requests waiting`);\n this.name = 'QueueFullError';\n this.queueSize = queueSize;\n this.maxSize = maxSize;\n }\n}\n\n/**\n * Queue wait timed out\n */\nexport class QueueTimeoutError extends WorkerPoolError {\n /** Time waited in milliseconds */\n readonly waitedMs: number;\n\n constructor(waitedMs: number) {\n super(`Queue timeout after ${waitedMs}ms`);\n this.name = 'QueueTimeoutError';\n this.waitedMs = waitedMs;\n }\n}\n\n/**\n * Execution was aborted\n */\nexport class ExecutionAbortedError extends WorkerPoolError {\n constructor(reason = 'Execution aborted') {\n super(reason);\n this.name = 'ExecutionAbortedError';\n }\n}\n\n/**\n * Message rate limit exceeded\n */\nexport class MessageFloodError extends WorkerPoolError {\n /** Worker slot ID */\n readonly slotId: string;\n\n constructor(slotId: string) {\n super('Message rate limit exceeded');\n this.name = 'MessageFloodError';\n this.slotId = slotId;\n }\n}\n\n/**\n * Message validation failed\n */\nexport class MessageValidationError extends WorkerPoolError {\n constructor(details?: string) {\n super(details ? `Invalid message: ${details}` : 'Invalid message format');\n this.name = 'MessageValidationError';\n }\n}\n\n/**\n * Message size exceeded limit\n */\nexport class MessageSizeError extends WorkerPoolError {\n /** Actual message size */\n readonly sizeBytes: number;\n /** Maximum allowed size */\n readonly maxBytes: number;\n\n constructor(sizeBytes: number, maxBytes: number) {\n super(`Message size ${Math.round(sizeBytes / 1024)}KB exceeds limit ${Math.round(maxBytes / 1024)}KB`);\n this.name = 'MessageSizeError';\n this.sizeBytes = sizeBytes;\n this.maxBytes = maxBytes;\n }\n}\n\n/**\n * Worker failed to start\n */\nexport class WorkerStartupError extends WorkerPoolError {\n /** Original error that caused startup failure */\n override readonly cause?: Error;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = 'WorkerStartupError';\n this.cause = cause;\n }\n}\n\n/**\n * Too many pending tool calls\n */\nexport class TooManyPendingCallsError extends WorkerPoolError {\n /** Current pending count */\n readonly pending: number;\n /** Maximum allowed */\n readonly max: number;\n\n constructor(pending: number, max: number) {\n super(`Too many pending tool calls: ${pending}/${max}`);\n this.name = 'TooManyPendingCallsError';\n this.pending = pending;\n this.max = max;\n }\n}\n"]}
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Execution Queue
3
+ *
4
+ * Handles backpressure when the worker pool is exhausted.
5
+ * Queues execution requests and dispatches them when workers become available.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ import type { WorkerPoolConfig } from './config';
10
+ /**
11
+ * Queue statistics
12
+ */
13
+ export interface QueueStats {
14
+ /** Current queue length */
15
+ length: number;
16
+ /** Maximum queue size */
17
+ maxSize: number;
18
+ /** Total requests ever queued */
19
+ totalQueued: number;
20
+ /** Total requests fulfilled */
21
+ totalFulfilled: number;
22
+ /** Total requests timed out */
23
+ totalTimedOut: number;
24
+ /** Total requests aborted */
25
+ totalAborted: number;
26
+ /** Longest wait time in milliseconds */
27
+ longestWaitMs: number;
28
+ /** Average wait time in milliseconds */
29
+ avgWaitMs: number;
30
+ }
31
+ /**
32
+ * Execution queue with configurable limits and timeout handling
33
+ */
34
+ export declare class ExecutionQueue {
35
+ private readonly queue;
36
+ private readonly config;
37
+ private _totalQueued;
38
+ private _totalFulfilled;
39
+ private _totalTimedOut;
40
+ private _totalAborted;
41
+ private _longestWaitMs;
42
+ private _totalWaitMs;
43
+ constructor(config: Pick<WorkerPoolConfig, 'maxQueueSize' | 'queueTimeoutMs'>);
44
+ /**
45
+ * Get current queue length
46
+ */
47
+ get length(): number;
48
+ /**
49
+ * Check if queue is full
50
+ */
51
+ get isFull(): boolean;
52
+ /**
53
+ * Enqueue an execution request
54
+ *
55
+ * @param signal Optional abort signal
56
+ * @returns Promise that resolves with a slot ID when a worker is available
57
+ * @throws QueueFullError if queue is at capacity
58
+ * @throws QueueTimeoutError if queue wait times out
59
+ * @throws ExecutionAbortedError if aborted via signal
60
+ */
61
+ enqueue(signal?: AbortSignal): Promise<string>;
62
+ /**
63
+ * Notify the queue that a worker slot is available
64
+ *
65
+ * @param slotId ID of the available slot
66
+ * @returns true if a queued request was fulfilled, false if queue was empty
67
+ */
68
+ notifySlotAvailable(slotId: string): boolean;
69
+ /**
70
+ * Remove a specific request from the queue
71
+ */
72
+ private removeFromQueue;
73
+ /**
74
+ * Clear the queue, rejecting all pending requests
75
+ */
76
+ clear(): void;
77
+ /**
78
+ * Get queue statistics
79
+ */
80
+ getStats(): QueueStats;
81
+ /**
82
+ * Reset statistics
83
+ */
84
+ resetStats(): void;
85
+ }
@@ -0,0 +1,179 @@
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
@@ -0,0 +1 @@
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;Q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AI,CAAC,YAAY,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,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"]}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Worker Pool Adapter
3
+ *
4
+ * Provides a worker thread-based sandbox adapter with:
5
+ * - OS-level memory isolation
6
+ * - Hard halt capability via worker.terminate()
7
+ * - Pool management with min/max workers
8
+ * - Memory monitoring and enforcement
9
+ * - Rate limiting for message flood protection
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ /**
14
+ * Main worker pool adapter class
15
+ */
16
+ export { WorkerPoolAdapter } from './worker-pool-adapter';
17
+ /**
18
+ * Configuration types and defaults for worker pool
19
+ */
20
+ export { WorkerPoolConfig, WorkerSlotStatus, ResourceUsage, WorkerPoolMetrics, DEFAULT_WORKER_POOL_CONFIG, WORKER_POOL_PRESETS, buildWorkerPoolConfig, } from './config';
21
+ /**
22
+ * Error classes for worker pool operations
23
+ */
24
+ export { WorkerPoolError, WorkerTimeoutError, WorkerMemoryError, WorkerCrashedError, WorkerPoolDisposedError, QueueFullError, QueueTimeoutError, ExecutionAbortedError, MessageFloodError, MessageValidationError, MessageSizeError, WorkerStartupError, TooManyPendingCallsError, } from './errors';
25
+ /**
26
+ * Protocol types for main thread to worker communication
27
+ */
28
+ export type { SerializedError, SerializedConfig, WorkerExecutionStats, MainToWorkerMessage, WorkerToMainMessage, ExecuteMessage, ToolCallMessage, ExecutionResultMessage, ToolResponseMessage, } from './protocol';
29
+ /**
30
+ * Worker slot management for advanced usage
31
+ */
32
+ export { WorkerSlot } from './worker-slot';
33
+ /**
34
+ * Execution queue for request management
35
+ */
36
+ export { ExecutionQueue, QueueStats } from './execution-queue';
37
+ /**
38
+ * Memory monitoring utilities
39
+ */
40
+ export { MemoryMonitor, MemoryMonitorStats } from './memory-monitor';
41
+ /**
42
+ * Rate limiting utilities
43
+ */
44
+ export { RateLimiter, createRateLimiter } from './rate-limiter';
45
+ /**
46
+ * Safe serialization utilities for cross-thread communication
47
+ */
48
+ export { safeDeserialize, safeSerialize, sanitizeObject } from './safe-deserialize';
@@ -0,0 +1,73 @@
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
@@ -0,0 +1 @@
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"]}