@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,115 @@
1
+ /**
2
+ * Reference Resolver - Resolves reference IDs at callTool boundary
3
+ *
4
+ * The Reference Resolver scans callTool arguments for reference IDs
5
+ * and replaces them with actual data from the sidecar. It includes
6
+ * predictive expansion checking to prevent memory exhaustion attacks.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import { ReferenceSidecar } from './reference-sidecar';
11
+ import { ReferenceConfig } from './reference-config';
12
+ /**
13
+ * Error thrown when resolution limits are exceeded
14
+ */
15
+ export declare class ResolutionLimitError extends Error {
16
+ readonly code: string;
17
+ readonly limit: number;
18
+ readonly actual: number;
19
+ constructor(message: string, code: string, limit: number, actual: number);
20
+ }
21
+ /**
22
+ * Composite handle structure
23
+ *
24
+ * When allowComposites is true, concatenating references produces
25
+ * a composite handle instead of materializing the data.
26
+ */
27
+ export interface CompositeHandle {
28
+ __type: 'composite';
29
+ __operation: 'concat';
30
+ __parts: string[];
31
+ __estimatedSize: number;
32
+ }
33
+ /**
34
+ * Check if a value is a composite handle
35
+ */
36
+ export declare function isCompositeHandle(value: unknown): value is CompositeHandle;
37
+ /**
38
+ * Reference Resolver
39
+ *
40
+ * Resolves reference IDs to actual data at the callTool boundary.
41
+ * Performs predictive expansion checking before allocation.
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const resolver = new ReferenceResolver(sidecar, config);
46
+ *
47
+ * // Check if resolution would exceed limits
48
+ * const size = resolver.predictExpandedSize(args);
49
+ * if (size > config.maxResolvedSize) {
50
+ * throw new Error('Arguments too large');
51
+ * }
52
+ *
53
+ * // Resolve all references
54
+ * const resolvedArgs = resolver.resolve(args);
55
+ * ```
56
+ */
57
+ export declare class ReferenceResolver {
58
+ private readonly sidecar;
59
+ private readonly config;
60
+ constructor(sidecar: ReferenceSidecar, config: ReferenceConfig);
61
+ /**
62
+ * Predict the expanded size of a value WITHOUT allocating memory
63
+ *
64
+ * This calculates the total size if all references were resolved,
65
+ * enabling fail-fast before any memory allocation occurs.
66
+ *
67
+ * @param value - The value to analyze
68
+ * @param depth - Current recursion depth (internal)
69
+ * @returns Estimated size in bytes
70
+ * @throws ResolutionLimitError if depth limit exceeded
71
+ */
72
+ predictExpandedSize(value: unknown, depth?: number): number;
73
+ /**
74
+ * Check if resolution would exceed size limits
75
+ *
76
+ * @param value - The value to check
77
+ * @returns true if resolution would exceed maxResolvedSize
78
+ */
79
+ wouldExceedLimit(value: unknown): boolean;
80
+ /**
81
+ * Resolve all reference IDs in a value tree
82
+ *
83
+ * Recursively walks the value and replaces reference IDs with
84
+ * their actual data from the sidecar.
85
+ *
86
+ * @param value - The value to resolve
87
+ * @param depth - Current recursion depth (internal)
88
+ * @returns The resolved value with references replaced
89
+ * @throws ResolutionLimitError if limits exceeded
90
+ * @throws ReferenceNotFoundError if a reference doesn't exist
91
+ */
92
+ resolve(value: unknown, depth?: number): unknown;
93
+ /**
94
+ * Resolve a composite handle by concatenating its parts
95
+ */
96
+ private resolveComposite;
97
+ /**
98
+ * Check if a value contains any reference IDs
99
+ *
100
+ * @param value - The value to check
101
+ * @param depth - Current recursion depth (internal)
102
+ * @returns true if the value or any nested value is a reference
103
+ */
104
+ containsReferences(value: unknown, depth?: number): boolean;
105
+ /**
106
+ * Create a composite handle from multiple reference parts
107
+ *
108
+ * Used by __safe_concat__ when allowComposites is true.
109
+ *
110
+ * @param parts - Reference IDs or strings to combine
111
+ * @returns A composite handle or the concatenated string
112
+ * @throws Error if composites not allowed or limits exceeded
113
+ */
114
+ createComposite(parts: string[]): CompositeHandle | string;
115
+ }
@@ -0,0 +1,262 @@
1
+ "use strict";
2
+ /**
3
+ * Reference Resolver - Resolves reference IDs at callTool boundary
4
+ *
5
+ * The Reference Resolver scans callTool arguments for reference IDs
6
+ * and replaces them with actual data from the sidecar. It includes
7
+ * predictive expansion checking to prevent memory exhaustion attacks.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ReferenceResolver = exports.ResolutionLimitError = void 0;
13
+ exports.isCompositeHandle = isCompositeHandle;
14
+ const reference_config_1 = require("./reference-config");
15
+ /**
16
+ * Error thrown when resolution limits are exceeded
17
+ */
18
+ class ResolutionLimitError extends Error {
19
+ code;
20
+ limit;
21
+ actual;
22
+ constructor(message, code, limit, actual) {
23
+ super(message);
24
+ this.code = code;
25
+ this.limit = limit;
26
+ this.actual = actual;
27
+ this.name = 'ResolutionLimitError';
28
+ Object.setPrototypeOf(this, ResolutionLimitError.prototype);
29
+ }
30
+ }
31
+ exports.ResolutionLimitError = ResolutionLimitError;
32
+ /**
33
+ * Check if a value is a composite handle
34
+ */
35
+ function isCompositeHandle(value) {
36
+ const obj = value;
37
+ return typeof value === 'object' && value !== null && obj['__type'] === 'composite' && Array.isArray(obj['__parts']);
38
+ }
39
+ /**
40
+ * Reference Resolver
41
+ *
42
+ * Resolves reference IDs to actual data at the callTool boundary.
43
+ * Performs predictive expansion checking before allocation.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const resolver = new ReferenceResolver(sidecar, config);
48
+ *
49
+ * // Check if resolution would exceed limits
50
+ * const size = resolver.predictExpandedSize(args);
51
+ * if (size > config.maxResolvedSize) {
52
+ * throw new Error('Arguments too large');
53
+ * }
54
+ *
55
+ * // Resolve all references
56
+ * const resolvedArgs = resolver.resolve(args);
57
+ * ```
58
+ */
59
+ class ReferenceResolver {
60
+ sidecar;
61
+ config;
62
+ constructor(sidecar, config) {
63
+ this.sidecar = sidecar;
64
+ this.config = config;
65
+ }
66
+ /**
67
+ * Predict the expanded size of a value WITHOUT allocating memory
68
+ *
69
+ * This calculates the total size if all references were resolved,
70
+ * enabling fail-fast before any memory allocation occurs.
71
+ *
72
+ * @param value - The value to analyze
73
+ * @param depth - Current recursion depth (internal)
74
+ * @returns Estimated size in bytes
75
+ * @throws ResolutionLimitError if depth limit exceeded
76
+ */
77
+ predictExpandedSize(value, depth = 0) {
78
+ // Check depth limit
79
+ if (depth > this.config.maxResolutionDepth) {
80
+ throw new ResolutionLimitError(`Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`, 'MAX_RESOLUTION_DEPTH', this.config.maxResolutionDepth, depth);
81
+ }
82
+ // Handle reference IDs
83
+ if ((0, reference_config_1.isReferenceId)(value)) {
84
+ const size = this.sidecar.getSize(value);
85
+ if (size === undefined) {
86
+ // Reference not found - use ID length as fallback
87
+ return value.length;
88
+ }
89
+ return size;
90
+ }
91
+ // Handle composite handles
92
+ if (isCompositeHandle(value)) {
93
+ return value.__parts.reduce((sum, part) => {
94
+ return sum + this.predictExpandedSize(part, depth + 1);
95
+ }, 0);
96
+ }
97
+ // Handle strings (not references)
98
+ if (typeof value === 'string') {
99
+ return Buffer.byteLength(value, 'utf-8');
100
+ }
101
+ // Handle arrays
102
+ if (Array.isArray(value)) {
103
+ return value.reduce((sum, item) => {
104
+ return sum + this.predictExpandedSize(item, depth + 1);
105
+ }, 0);
106
+ }
107
+ // Handle objects
108
+ if (value !== null && typeof value === 'object') {
109
+ return Object.values(value).reduce((sum, val) => {
110
+ return sum + this.predictExpandedSize(val, depth + 1);
111
+ }, 0);
112
+ }
113
+ // Primitives have minimal size
114
+ if (typeof value === 'number')
115
+ return 8;
116
+ if (typeof value === 'boolean')
117
+ return 1;
118
+ if (value === null || value === undefined)
119
+ return 0;
120
+ return 0;
121
+ }
122
+ /**
123
+ * Check if resolution would exceed size limits
124
+ *
125
+ * @param value - The value to check
126
+ * @returns true if resolution would exceed maxResolvedSize
127
+ */
128
+ wouldExceedLimit(value) {
129
+ try {
130
+ const size = this.predictExpandedSize(value);
131
+ return size > this.config.maxResolvedSize;
132
+ }
133
+ catch {
134
+ return true; // Treat errors as exceeding limit
135
+ }
136
+ }
137
+ /**
138
+ * Resolve all reference IDs in a value tree
139
+ *
140
+ * Recursively walks the value and replaces reference IDs with
141
+ * their actual data from the sidecar.
142
+ *
143
+ * @param value - The value to resolve
144
+ * @param depth - Current recursion depth (internal)
145
+ * @returns The resolved value with references replaced
146
+ * @throws ResolutionLimitError if limits exceeded
147
+ * @throws ReferenceNotFoundError if a reference doesn't exist
148
+ */
149
+ resolve(value, depth = 0) {
150
+ // Check depth limit
151
+ if (depth > this.config.maxResolutionDepth) {
152
+ throw new ResolutionLimitError(`Maximum resolution depth exceeded during resolution (${this.config.maxResolutionDepth})`, 'MAX_RESOLUTION_DEPTH', this.config.maxResolutionDepth, depth);
153
+ }
154
+ // Handle reference IDs
155
+ if ((0, reference_config_1.isReferenceId)(value)) {
156
+ const data = this.sidecar.retrieveString(value);
157
+ if (data === undefined) {
158
+ throw new Error(`Unknown reference: ${value}`);
159
+ }
160
+ return data;
161
+ }
162
+ // Handle composite handles
163
+ if (isCompositeHandle(value)) {
164
+ return this.resolveComposite(value, depth);
165
+ }
166
+ // Handle strings (not references) - pass through
167
+ if (typeof value === 'string') {
168
+ return value;
169
+ }
170
+ // Handle arrays
171
+ if (Array.isArray(value)) {
172
+ return value.map((item) => this.resolve(item, depth + 1));
173
+ }
174
+ // Handle objects
175
+ if (value !== null && typeof value === 'object') {
176
+ const resolved = Object.create(null);
177
+ for (const [key, val] of Object.entries(value)) {
178
+ resolved[key] = this.resolve(val, depth + 1);
179
+ }
180
+ return resolved;
181
+ }
182
+ // Primitives pass through
183
+ return value;
184
+ }
185
+ /**
186
+ * Resolve a composite handle by concatenating its parts
187
+ */
188
+ resolveComposite(handle, depth) {
189
+ const parts = [];
190
+ for (const part of handle.__parts) {
191
+ const resolved = this.resolve(part, depth + 1);
192
+ if (typeof resolved !== 'string') {
193
+ throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);
194
+ }
195
+ parts.push(resolved);
196
+ }
197
+ return parts.join('');
198
+ }
199
+ /**
200
+ * Check if a value contains any reference IDs
201
+ *
202
+ * @param value - The value to check
203
+ * @param depth - Current recursion depth (internal)
204
+ * @returns true if the value or any nested value is a reference
205
+ */
206
+ containsReferences(value, depth = 0) {
207
+ if (depth > this.config.maxResolutionDepth) {
208
+ return false;
209
+ }
210
+ if ((0, reference_config_1.isReferenceId)(value) || isCompositeHandle(value)) {
211
+ return true;
212
+ }
213
+ if (Array.isArray(value)) {
214
+ return value.some((item) => this.containsReferences(item, depth + 1));
215
+ }
216
+ if (value !== null && typeof value === 'object') {
217
+ return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
218
+ }
219
+ return false;
220
+ }
221
+ /**
222
+ * Create a composite handle from multiple reference parts
223
+ *
224
+ * Used by __safe_concat__ when allowComposites is true.
225
+ *
226
+ * @param parts - Reference IDs or strings to combine
227
+ * @returns A composite handle or the concatenated string
228
+ * @throws Error if composites not allowed or limits exceeded
229
+ */
230
+ createComposite(parts) {
231
+ // Check if any parts are references
232
+ const hasReferences = parts.some((p) => (0, reference_config_1.isReferenceId)(p));
233
+ if (!hasReferences) {
234
+ // No references - just concatenate normally
235
+ return parts.join('');
236
+ }
237
+ // Check if composites are allowed
238
+ if (!this.config.allowComposites) {
239
+ throw new Error('Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +
240
+ 'Composite handles are disabled in the current security configuration.');
241
+ }
242
+ // Calculate estimated size
243
+ const estimatedSize = parts.reduce((sum, part) => {
244
+ if ((0, reference_config_1.isReferenceId)(part)) {
245
+ return sum + (this.sidecar.getSize(part) ?? part.length);
246
+ }
247
+ return sum + Buffer.byteLength(part, 'utf-8');
248
+ }, 0);
249
+ // Check against limits
250
+ if (estimatedSize > this.config.maxResolvedSize) {
251
+ throw new ResolutionLimitError(`Composite would exceed maximum resolved size: ${estimatedSize} > ${this.config.maxResolvedSize}`, 'MAX_RESOLVED_SIZE', this.config.maxResolvedSize, estimatedSize);
252
+ }
253
+ return {
254
+ __type: 'composite',
255
+ __operation: 'concat',
256
+ __parts: parts,
257
+ __estimatedSize: estimatedSize,
258
+ };
259
+ }
260
+ }
261
+ exports.ReferenceResolver = ReferenceResolver;
262
+ //# sourceMappingURL=reference-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reference-resolver.js","sourceRoot":"","sources":["../../../src/sidecar/reference-resolver.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAqCH,8CAGC;AArCD,yDAAoE;AAEpE;;GAEG;AACH,MAAa,oBAAqB,SAAQ,KAAK;IAG3B;IACA;IACA;IAJlB,YACE,OAAe,EACC,IAAY,EACZ,KAAa,EACb,MAAc;QAE9B,KAAK,CAAC,OAAO,CAAC,CAAC;QAJC,SAAI,GAAJ,IAAI,CAAQ;QACZ,UAAK,GAAL,KAAK,CAAQ;QACb,WAAM,GAAN,MAAM,CAAQ;QAG9B,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAC9D,CAAC;CACF;AAXD,oDAWC;AAeD;;GAEG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,MAAM,GAAG,GAAG,KAAgC,CAAC;IAC7C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,WAAW,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;AACvH,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAa,iB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I,CAAC,MAAM,CAAC,eAAe,EAAE,EACjG,mBAAmB,EACnB,IAAI,CAAC,MAAM,CAAC,eAAe,EAC3B,aAAa,CACd,CAAC;QACJ,CAAC;QAED,OAAO;YACL,MAAM,EAAE,WAAW;YACnB,WAAW,EAAE,QAAQ;YACrB,OAAO,EAAE,KAAK;YACd,eAAe,EAAE,aAAa;SAC/B,CAAC;IACJ,CAAC;CACF;AAlPD,8CAkPC","sourcesContent":["/**\n * Reference Resolver - Resolves reference IDs at callTool boundary\n *\n * The Reference Resolver scans callTool arguments for reference IDs\n * and replaces them with actual data from the sidecar. It includes\n * predictive expansion checking to prevent memory exhaustion attacks.\n *\n * @packageDocumentation\n */\n\nimport { ReferenceSidecar } from './reference-sidecar';\nimport { ReferenceConfig, isReferenceId } from './reference-config';\n\n/**\n * Error thrown when resolution limits are exceeded\n */\nexport class ResolutionLimitError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly limit: number,\n public readonly actual: number,\n ) {\n super(message);\n this.name = 'ResolutionLimitError';\n Object.setPrototypeOf(this, ResolutionLimitError.prototype);\n }\n}\n\n/**\n * Composite handle structure\n *\n * When allowComposites is true, concatenating references produces\n * a composite handle instead of materializing the data.\n */\nexport interface CompositeHandle {\n __type: 'composite';\n __operation: 'concat';\n __parts: string[];\n __estimatedSize: number;\n}\n\n/**\n * Check if a value is a composite handle\n */\nexport function isCompositeHandle(value: unknown): value is CompositeHandle {\n const obj = value as Record<string, unknown>;\n return typeof value === 'object' && value !== null && obj['__type'] === 'composite' && Array.isArray(obj['__parts']);\n}\n\n/**\n * Reference Resolver\n *\n * Resolves reference IDs to actual data at the callTool boundary.\n * Performs predictive expansion checking before allocation.\n *\n * @example\n * ```typescript\n * const resolver = new ReferenceResolver(sidecar, config);\n *\n * // Check if resolution would exceed limits\n * const size = resolver.predictExpandedSize(args);\n * if (size > config.maxResolvedSize) {\n * throw new Error('Arguments too large');\n * }\n *\n * // Resolve all references\n * const resolvedArgs = resolver.resolve(args);\n * ```\n */\nexport class ReferenceResolver {\n constructor(\n private readonly sidecar: ReferenceSidecar,\n private readonly config: ReferenceConfig,\n ) {}\n\n /**\n * Predict the expanded size of a value WITHOUT allocating memory\n *\n * This calculates the total size if all references were resolved,\n * enabling fail-fast before any memory allocation occurs.\n *\n * @param value - The value to analyze\n * @param depth - Current recursion depth (internal)\n * @returns Estimated size in bytes\n * @throws ResolutionLimitError if depth limit exceeded\n */\n predictExpandedSize(value: unknown, depth = 0): number {\n // Check depth limit\n if (depth > this.config.maxResolutionDepth) {\n throw new ResolutionLimitError(\n `Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,\n 'MAX_RESOLUTION_DEPTH',\n this.config.maxResolutionDepth,\n depth,\n );\n }\n\n // Handle reference IDs\n if (isReferenceId(value)) {\n const size = this.sidecar.getSize(value);\n if (size === undefined) {\n // Reference not found - use ID length as fallback\n return value.length;\n }\n return size;\n }\n\n // Handle composite handles\n if (isCompositeHandle(value)) {\n return value.__parts.reduce((sum, part) => {\n return sum + this.predictExpandedSize(part, depth + 1);\n }, 0);\n }\n\n // Handle strings (not references)\n if (typeof value === 'string') {\n return Buffer.byteLength(value, 'utf-8');\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n return value.reduce((sum, item) => {\n return sum + this.predictExpandedSize(item, depth + 1);\n }, 0);\n }\n\n // Handle objects\n if (value !== null && typeof value === 'object') {\n return Object.values(value).reduce((sum: number, val) => {\n return sum + this.predictExpandedSize(val, depth + 1);\n }, 0);\n }\n\n // Primitives have minimal size\n if (typeof value === 'number') return 8;\n if (typeof value === 'boolean') return 1;\n if (value === null || value === undefined) return 0;\n\n return 0;\n }\n\n /**\n * Check if resolution would exceed size limits\n *\n * @param value - The value to check\n * @returns true if resolution would exceed maxResolvedSize\n */\n wouldExceedLimit(value: unknown): boolean {\n try {\n const size = this.predictExpandedSize(value);\n return size > this.config.maxResolvedSize;\n } catch {\n return true; // Treat errors as exceeding limit\n }\n }\n\n /**\n * Resolve all reference IDs in a value tree\n *\n * Recursively walks the value and replaces reference IDs with\n * their actual data from the sidecar.\n *\n * @param value - The value to resolve\n * @param depth - Current recursion depth (internal)\n * @returns The resolved value with references replaced\n * @throws ResolutionLimitError if limits exceeded\n * @throws ReferenceNotFoundError if a reference doesn't exist\n */\n resolve(value: unknown, depth = 0): unknown {\n // Check depth limit\n if (depth > this.config.maxResolutionDepth) {\n throw new ResolutionLimitError(\n `Maximum resolution depth exceeded during resolution (${this.config.maxResolutionDepth})`,\n 'MAX_RESOLUTION_DEPTH',\n this.config.maxResolutionDepth,\n depth,\n );\n }\n\n // Handle reference IDs\n if (isReferenceId(value)) {\n const data = this.sidecar.retrieveString(value);\n if (data === undefined) {\n throw new Error(`Unknown reference: ${value}`);\n }\n return data;\n }\n\n // Handle composite handles\n if (isCompositeHandle(value)) {\n return this.resolveComposite(value, depth);\n }\n\n // Handle strings (not references) - pass through\n if (typeof value === 'string') {\n return value;\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n return value.map((item) => this.resolve(item, depth + 1));\n }\n\n // Handle objects\n if (value !== null && typeof value === 'object') {\n const resolved: Record<string, unknown> = Object.create(null);\n for (const [key, val] of Object.entries(value)) {\n resolved[key] = this.resolve(val, depth + 1);\n }\n return resolved;\n }\n\n // Primitives pass through\n return value;\n }\n\n /**\n * Resolve a composite handle by concatenating its parts\n */\n private resolveComposite(handle: CompositeHandle, depth: number): string {\n const parts: string[] = [];\n\n for (const part of handle.__parts) {\n const resolved = this.resolve(part, depth + 1);\n if (typeof resolved !== 'string') {\n throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);\n }\n parts.push(resolved);\n }\n\n return parts.join('');\n }\n\n /**\n * Check if a value contains any reference IDs\n *\n * @param value - The value to check\n * @param depth - Current recursion depth (internal)\n * @returns true if the value or any nested value is a reference\n */\n containsReferences(value: unknown, depth = 0): boolean {\n if (depth > this.config.maxResolutionDepth) {\n return false;\n }\n\n if (isReferenceId(value) || isCompositeHandle(value)) {\n return true;\n }\n\n if (Array.isArray(value)) {\n return value.some((item) => this.containsReferences(item, depth + 1));\n }\n\n if (value !== null && typeof value === 'object') {\n return Object.values(value).some((val) => this.containsReferences(val, depth + 1));\n }\n\n return false;\n }\n\n /**\n * Create a composite handle from multiple reference parts\n *\n * Used by __safe_concat__ when allowComposites is true.\n *\n * @param parts - Reference IDs or strings to combine\n * @returns A composite handle or the concatenated string\n * @throws Error if composites not allowed or limits exceeded\n */\n createComposite(parts: string[]): CompositeHandle | string {\n // Check if any parts are references\n const hasReferences = parts.some((p) => isReferenceId(p));\n\n if (!hasReferences) {\n // No references - just concatenate normally\n return parts.join('');\n }\n\n // Check if composites are allowed\n if (!this.config.allowComposites) {\n throw new Error(\n 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +\n 'Composite handles are disabled in the current security configuration.',\n );\n }\n\n // Calculate estimated size\n const estimatedSize = parts.reduce((sum, part) => {\n if (isReferenceId(part)) {\n return sum + (this.sidecar.getSize(part) ?? part.length);\n }\n return sum + Buffer.byteLength(part, 'utf-8');\n }, 0);\n\n // Check against limits\n if (estimatedSize > this.config.maxResolvedSize) {\n throw new ResolutionLimitError(\n `Composite would exceed maximum resolved size: ${estimatedSize} > ${this.config.maxResolvedSize}`,\n 'MAX_RESOLVED_SIZE',\n this.config.maxResolvedSize,\n estimatedSize,\n );\n }\n\n return {\n __type: 'composite',\n __operation: 'concat',\n __parts: parts,\n __estimatedSize: estimatedSize,\n };\n }\n}\n"]}
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Reference Sidecar - Request-scoped storage for lifted data
3
+ *
4
+ * The Reference Sidecar is a key-value store that holds large data
5
+ * outside the JavaScript sandbox. Scripts interact with reference IDs
6
+ * instead of actual data, and references are resolved at the callTool boundary.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import { ReferenceConfig } from './reference-config';
11
+ /**
12
+ * Source of a stored reference
13
+ */
14
+ export type ReferenceSource = 'extraction' | 'tool-result';
15
+ /**
16
+ * Metadata for a stored reference
17
+ */
18
+ export interface ReferenceMetadata {
19
+ /**
20
+ * When the reference was created
21
+ */
22
+ createdAt: number;
23
+ /**
24
+ * Size of the data in bytes
25
+ */
26
+ size: number;
27
+ /**
28
+ * Source of the reference (extraction from code or tool result)
29
+ */
30
+ source: ReferenceSource;
31
+ /**
32
+ * Optional MIME type hint
33
+ */
34
+ mimeType?: string;
35
+ /**
36
+ * Optional origin (tool name that created it)
37
+ */
38
+ origin?: string;
39
+ }
40
+ /**
41
+ * Error thrown when sidecar limits are exceeded
42
+ */
43
+ export declare class SidecarLimitError extends Error {
44
+ readonly code: string;
45
+ readonly limit: number;
46
+ readonly current: number;
47
+ constructor(message: string, code: string, limit: number, current: number);
48
+ }
49
+ /**
50
+ * Error thrown when a reference is not found
51
+ */
52
+ export declare class ReferenceNotFoundError extends Error {
53
+ readonly refId: string;
54
+ constructor(refId: string);
55
+ }
56
+ /**
57
+ * Request-scoped reference storage
58
+ *
59
+ * Stores large data outside the sandbox and provides opaque reference IDs.
60
+ * Must be disposed after each execution to prevent memory leaks.
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * const sidecar = new ReferenceSidecar(REFERENCE_CONFIGS.STRICT);
65
+ *
66
+ * // Store large data
67
+ * const refId = sidecar.store(largeBuffer, 'extraction');
68
+ *
69
+ * // Later, retrieve it
70
+ * const data = sidecar.retrieve(refId);
71
+ *
72
+ * // Always dispose after execution
73
+ * sidecar.dispose();
74
+ * ```
75
+ */
76
+ export declare class ReferenceSidecar {
77
+ private readonly config;
78
+ private readonly storage;
79
+ private readonly metadata;
80
+ private totalSize;
81
+ private disposed;
82
+ constructor(config: ReferenceConfig);
83
+ /**
84
+ * Store data and return a reference ID
85
+ *
86
+ * @param data - The data to store (string or Buffer)
87
+ * @param source - Where this data came from
88
+ * @param options - Optional metadata
89
+ * @returns The reference ID (format: __REF_uuid__)
90
+ * @throws SidecarLimitError if limits are exceeded
91
+ */
92
+ store(data: string | Buffer, source: ReferenceSource, options?: {
93
+ mimeType?: string;
94
+ origin?: string;
95
+ }): string;
96
+ /**
97
+ * Retrieve data by reference ID
98
+ *
99
+ * @param refId - The reference ID to look up
100
+ * @returns The stored data or undefined if not found
101
+ */
102
+ retrieve(refId: string): Buffer | undefined;
103
+ /**
104
+ * Retrieve data as a string
105
+ *
106
+ * @param refId - The reference ID to look up
107
+ * @param encoding - String encoding (default: utf-8)
108
+ * @returns The stored data as a string or undefined
109
+ */
110
+ retrieveString(refId: string, encoding?: BufferEncoding): string | undefined;
111
+ /**
112
+ * Check if a reference ID exists
113
+ */
114
+ has(refId: string): boolean;
115
+ /**
116
+ * Get metadata for a reference
117
+ */
118
+ getMetadata(refId: string): ReferenceMetadata | undefined;
119
+ /**
120
+ * Get the size of a reference without retrieving data
121
+ */
122
+ getSize(refId: string): number | undefined;
123
+ /**
124
+ * Get total size of all stored references
125
+ */
126
+ getTotalSize(): number;
127
+ /**
128
+ * Get number of stored references
129
+ */
130
+ getCount(): number;
131
+ /**
132
+ * Get the configuration
133
+ */
134
+ getConfig(): ReferenceConfig;
135
+ /**
136
+ * Check if a value is a reference ID
137
+ */
138
+ isReference(value: unknown): value is string;
139
+ /**
140
+ * Get all reference IDs (for debugging/auditing)
141
+ */
142
+ getAllReferenceIds(): string[];
143
+ /**
144
+ * Get audit log of all stored references
145
+ */
146
+ getAuditLog(): Array<{
147
+ refId: string;
148
+ metadata: ReferenceMetadata;
149
+ }>;
150
+ /**
151
+ * Check if the sidecar has been disposed
152
+ */
153
+ isDisposed(): boolean;
154
+ /**
155
+ * Dispose the sidecar and release all memory
156
+ *
157
+ * MUST be called after each execution to prevent memory leaks.
158
+ * After disposal, the sidecar cannot be used.
159
+ */
160
+ dispose(): void;
161
+ }