@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.
Files changed (169) hide show
  1. package/esm/index.mjs +11172 -0
  2. package/esm/package.json +6 -0
  3. package/index.js +11268 -0
  4. package/package.json +11 -10
  5. package/src/adapters/vm-adapter.js +0 -1140
  6. package/src/adapters/vm-adapter.js.map +0 -1
  7. package/src/adapters/worker-pool/config.js +0 -129
  8. package/src/adapters/worker-pool/config.js.map +0 -1
  9. package/src/adapters/worker-pool/errors.js +0 -181
  10. package/src/adapters/worker-pool/errors.js.map +0 -1
  11. package/src/adapters/worker-pool/execution-queue.js +0 -179
  12. package/src/adapters/worker-pool/execution-queue.js.map +0 -1
  13. package/src/adapters/worker-pool/index.js +0 -73
  14. package/src/adapters/worker-pool/index.js.map +0 -1
  15. package/src/adapters/worker-pool/memory-monitor.js +0 -184
  16. package/src/adapters/worker-pool/memory-monitor.js.map +0 -1
  17. package/src/adapters/worker-pool/protocol.js +0 -143
  18. package/src/adapters/worker-pool/protocol.js.map +0 -1
  19. package/src/adapters/worker-pool/rate-limiter.js +0 -101
  20. package/src/adapters/worker-pool/rate-limiter.js.map +0 -1
  21. package/src/adapters/worker-pool/safe-deserialize.js +0 -141
  22. package/src/adapters/worker-pool/safe-deserialize.js.map +0 -1
  23. package/src/adapters/worker-pool/worker-pool-adapter.js +0 -506
  24. package/src/adapters/worker-pool/worker-pool-adapter.js.map +0 -1
  25. package/src/adapters/worker-pool/worker-script.js +0 -770
  26. package/src/adapters/worker-pool/worker-script.js.map +0 -1
  27. package/src/adapters/worker-pool/worker-slot.js +0 -301
  28. package/src/adapters/worker-pool/worker-slot.js.map +0 -1
  29. package/src/babel/babel-wrapper.js +0 -395
  30. package/src/babel/babel-wrapper.js.map +0 -1
  31. package/src/babel/index.js +0 -17
  32. package/src/babel/index.js.map +0 -1
  33. package/src/babel/multi-file-transform.js +0 -344
  34. package/src/babel/multi-file-transform.js.map +0 -1
  35. package/src/double-vm/double-vm-wrapper.js +0 -523
  36. package/src/double-vm/double-vm-wrapper.js.map +0 -1
  37. package/src/double-vm/index.js +0 -34
  38. package/src/double-vm/index.js.map +0 -1
  39. package/src/double-vm/parent-vm-bootstrap.js +0 -1695
  40. package/src/double-vm/parent-vm-bootstrap.js.map +0 -1
  41. package/src/double-vm/suspicious-patterns.js +0 -304
  42. package/src/double-vm/suspicious-patterns.js.map +0 -1
  43. package/src/double-vm/types.js +0 -11
  44. package/src/double-vm/types.js.map +0 -1
  45. package/src/double-vm/wrap-adapter.js +0 -59
  46. package/src/double-vm/wrap-adapter.js.map +0 -1
  47. package/src/enclave.js +0 -671
  48. package/src/enclave.js.map +0 -1
  49. package/src/globals-validator.js +0 -206
  50. package/src/globals-validator.js.map +0 -1
  51. package/src/index.js +0 -130
  52. package/src/index.js.map +0 -1
  53. package/src/memory-proxy.js +0 -310
  54. package/src/memory-proxy.js.map +0 -1
  55. package/src/memory-tracker.js +0 -230
  56. package/src/memory-tracker.js.map +0 -1
  57. package/src/safe-error.js +0 -76
  58. package/src/safe-error.js.map +0 -1
  59. package/src/safe-runtime.js +0 -656
  60. package/src/safe-runtime.js.map +0 -1
  61. package/src/scoring/cache.js +0 -158
  62. package/src/scoring/cache.js.map +0 -1
  63. package/src/scoring/feature-extractor.js +0 -366
  64. package/src/scoring/feature-extractor.js.map +0 -1
  65. package/src/scoring/index.js +0 -53
  66. package/src/scoring/index.js.map +0 -1
  67. package/src/scoring/scorer.interface.js +0 -49
  68. package/src/scoring/scorer.interface.js.map +0 -1
  69. package/src/scoring/scorers/disabled.scorer.js +0 -34
  70. package/src/scoring/scorers/disabled.scorer.js.map +0 -1
  71. package/src/scoring/scorers/external-api.scorer.js +0 -141
  72. package/src/scoring/scorers/external-api.scorer.js.map +0 -1
  73. package/src/scoring/scorers/index.js +0 -22
  74. package/src/scoring/scorers/index.js.map +0 -1
  75. package/src/scoring/scorers/local-llm.scorer.js +0 -474
  76. package/src/scoring/scorers/local-llm.scorer.js.map +0 -1
  77. package/src/scoring/scorers/progressive.scorer.js +0 -199
  78. package/src/scoring/scorers/progressive.scorer.js.map +0 -1
  79. package/src/scoring/scorers/rule-based.scorer.js +0 -316
  80. package/src/scoring/scorers/rule-based.scorer.js.map +0 -1
  81. package/src/scoring/scoring-gate.js +0 -246
  82. package/src/scoring/scoring-gate.js.map +0 -1
  83. package/src/scoring/types.js +0 -107
  84. package/src/scoring/types.js.map +0 -1
  85. package/src/secure-proxy.js +0 -609
  86. package/src/secure-proxy.js.map +0 -1
  87. package/src/session/channels/embedded-channel.js +0 -130
  88. package/src/session/channels/embedded-channel.js.map +0 -1
  89. package/src/session/channels/index.js +0 -14
  90. package/src/session/channels/index.js.map +0 -1
  91. package/src/session/index.js +0 -27
  92. package/src/session/index.js.map +0 -1
  93. package/src/session/session-emitter.js +0 -253
  94. package/src/session/session-emitter.js.map +0 -1
  95. package/src/session/session-state-machine.js +0 -182
  96. package/src/session/session-state-machine.js.map +0 -1
  97. package/src/session/session.js +0 -398
  98. package/src/session/session.js.map +0 -1
  99. package/src/session-types.js +0 -39
  100. package/src/session-types.js.map +0 -1
  101. package/src/sidecar/index.js +0 -31
  102. package/src/sidecar/index.js.map +0 -1
  103. package/src/sidecar/reference-config.js +0 -118
  104. package/src/sidecar/reference-config.js.map +0 -1
  105. package/src/sidecar/reference-resolver.js +0 -262
  106. package/src/sidecar/reference-resolver.js.map +0 -1
  107. package/src/sidecar/reference-sidecar.js +0 -226
  108. package/src/sidecar/reference-sidecar.js.map +0 -1
  109. package/src/tool-bridge.js +0 -306
  110. package/src/tool-bridge.js.map +0 -1
  111. package/src/types.js +0 -187
  112. package/src/types.js.map +0 -1
  113. package/src/value-sanitizer.js +0 -421
  114. package/src/value-sanitizer.js.map +0 -1
  115. /package/{src/adapters → adapters}/vm-adapter.d.ts +0 -0
  116. /package/{src/adapters → adapters}/worker-pool/config.d.ts +0 -0
  117. /package/{src/adapters → adapters}/worker-pool/errors.d.ts +0 -0
  118. /package/{src/adapters → adapters}/worker-pool/execution-queue.d.ts +0 -0
  119. /package/{src/adapters → adapters}/worker-pool/index.d.ts +0 -0
  120. /package/{src/adapters → adapters}/worker-pool/memory-monitor.d.ts +0 -0
  121. /package/{src/adapters → adapters}/worker-pool/protocol.d.ts +0 -0
  122. /package/{src/adapters → adapters}/worker-pool/rate-limiter.d.ts +0 -0
  123. /package/{src/adapters → adapters}/worker-pool/safe-deserialize.d.ts +0 -0
  124. /package/{src/adapters → adapters}/worker-pool/worker-pool-adapter.d.ts +0 -0
  125. /package/{src/adapters → adapters}/worker-pool/worker-script.d.ts +0 -0
  126. /package/{src/adapters → adapters}/worker-pool/worker-slot.d.ts +0 -0
  127. /package/{src/babel → babel}/babel-wrapper.d.ts +0 -0
  128. /package/{src/babel → babel}/index.d.ts +0 -0
  129. /package/{src/babel → babel}/multi-file-transform.d.ts +0 -0
  130. /package/{src/double-vm → double-vm}/double-vm-wrapper.d.ts +0 -0
  131. /package/{src/double-vm → double-vm}/index.d.ts +0 -0
  132. /package/{src/double-vm → double-vm}/parent-vm-bootstrap.d.ts +0 -0
  133. /package/{src/double-vm → double-vm}/suspicious-patterns.d.ts +0 -0
  134. /package/{src/double-vm → double-vm}/types.d.ts +0 -0
  135. /package/{src/double-vm → double-vm}/wrap-adapter.d.ts +0 -0
  136. /package/{src/enclave.d.ts → enclave.d.ts} +0 -0
  137. /package/{src/globals-validator.d.ts → globals-validator.d.ts} +0 -0
  138. /package/{src/index.d.ts → index.d.ts} +0 -0
  139. /package/{src/memory-proxy.d.ts → memory-proxy.d.ts} +0 -0
  140. /package/{src/memory-tracker.d.ts → memory-tracker.d.ts} +0 -0
  141. /package/{src/safe-error.d.ts → safe-error.d.ts} +0 -0
  142. /package/{src/safe-runtime.d.ts → safe-runtime.d.ts} +0 -0
  143. /package/{src/scoring → scoring}/cache.d.ts +0 -0
  144. /package/{src/scoring → scoring}/feature-extractor.d.ts +0 -0
  145. /package/{src/scoring → scoring}/index.d.ts +0 -0
  146. /package/{src/scoring → scoring}/scorer.interface.d.ts +0 -0
  147. /package/{src/scoring → scoring}/scorers/disabled.scorer.d.ts +0 -0
  148. /package/{src/scoring → scoring}/scorers/external-api.scorer.d.ts +0 -0
  149. /package/{src/scoring → scoring}/scorers/index.d.ts +0 -0
  150. /package/{src/scoring → scoring}/scorers/local-llm.scorer.d.ts +0 -0
  151. /package/{src/scoring → scoring}/scorers/progressive.scorer.d.ts +0 -0
  152. /package/{src/scoring → scoring}/scorers/rule-based.scorer.d.ts +0 -0
  153. /package/{src/scoring → scoring}/scoring-gate.d.ts +0 -0
  154. /package/{src/scoring → scoring}/types.d.ts +0 -0
  155. /package/{src/secure-proxy.d.ts → secure-proxy.d.ts} +0 -0
  156. /package/{src/session → session}/channels/embedded-channel.d.ts +0 -0
  157. /package/{src/session → session}/channels/index.d.ts +0 -0
  158. /package/{src/session → session}/index.d.ts +0 -0
  159. /package/{src/session → session}/session-emitter.d.ts +0 -0
  160. /package/{src/session → session}/session-state-machine.d.ts +0 -0
  161. /package/{src/session → session}/session.d.ts +0 -0
  162. /package/{src/session-types.d.ts → session-types.d.ts} +0 -0
  163. /package/{src/sidecar → sidecar}/index.d.ts +0 -0
  164. /package/{src/sidecar → sidecar}/reference-config.d.ts +0 -0
  165. /package/{src/sidecar → sidecar}/reference-resolver.d.ts +0 -0
  166. /package/{src/sidecar → sidecar}/reference-sidecar.d.ts +0 -0
  167. /package/{src/tool-bridge.d.ts → tool-bridge.d.ts} +0 -0
  168. /package/{src/types.d.ts → types.d.ts} +0 -0
  169. /package/{src/value-sanitizer.d.ts → value-sanitizer.d.ts} +0 -0
@@ -1,39 +0,0 @@
1
- "use strict";
2
- /**
3
- * Session Types for Streaming Runtime
4
- *
5
- * Types for running Enclave in session mode, which supports:
6
- * - Continuous execution with streaming events
7
- * - Async tool calls with "waiting for tool" state
8
- * - Session lifecycle management
9
- *
10
- * @packageDocumentation
11
- */
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.isSession = isSession;
14
- exports.isWaitingForTool = isWaitingForTool;
15
- exports.isTerminalState = isTerminalState;
16
- /**
17
- * Type guard for checking if an object is a Session
18
- */
19
- function isSession(obj) {
20
- return (typeof obj === 'object' &&
21
- obj !== null &&
22
- 'sessionId' in obj &&
23
- 'state' in obj &&
24
- 'submitToolResult' in obj &&
25
- typeof obj.submitToolResult === 'function');
26
- }
27
- /**
28
- * Type guard for waiting_for_tool state
29
- */
30
- function isWaitingForTool(session) {
31
- return session.state === 'waiting_for_tool' && session.pendingToolCall !== null;
32
- }
33
- /**
34
- * Type guard for terminal states
35
- */
36
- function isTerminalState(state) {
37
- return state === 'completed' || state === 'cancelled' || state === 'failed';
38
- }
39
- //# sourceMappingURL=session-types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"session-types.js","sourceRoot":"","sources":["../../src/session-types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;AAkWH,8BASC;AAKD,4CAEC;AAKD,0CAEC;AA1BD;;GAEG;AACH,SAAgB,SAAS,CAAC,GAAY;IACpC,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,GAAG,KAAK,IAAI;QACZ,WAAW,IAAI,GAAG;QAClB,OAAO,IAAI,GAAG;QACd,kBAAkB,IAAI,GAAG;QACzB,OAAQ,GAAe,CAAC,gBAAgB,KAAK,UAAU,CACxD,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,OAAgB;IAC/C,OAAO,OAAO,CAAC,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC,eAAe,KAAK,IAAI,CAAC;AAClF,CAAC;AAED;;GAEG;AACH,SAAgB,eAAe,CAAC,KAAwB;IACtD,OAAO,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,QAAQ,CAAC;AAC9E,CAAC","sourcesContent":["/**\n * Session Types for Streaming Runtime\n *\n * Types for running Enclave in session mode, which supports:\n * - Continuous execution with streaming events\n * - Async tool calls with \"waiting for tool\" state\n * - Session lifecycle management\n *\n * @packageDocumentation\n */\n\nimport type {\n SessionId,\n CallId,\n SessionLimits,\n StreamEvent,\n ToolCallPayload,\n RuntimeChannelMessage,\n} from '@enclave-vm/types';\nimport type { CreateEnclaveOptions, ExecutionStats } from './types';\n\n/**\n * Session state machine states\n *\n * The session progresses through these states:\n * - starting: Session created, runtime initializing\n * - running: Code is executing\n * - waiting_for_tool: Blocked on async tool call\n * - completed: Execution finished successfully\n * - cancelled: Session was cancelled externally\n * - failed: Execution failed with error\n */\nexport type SessionStateValue = 'starting' | 'running' | 'waiting_for_tool' | 'completed' | 'cancelled' | 'failed';\n\n/**\n * Session configuration\n *\n * Extends standard Enclave options with session-specific settings.\n */\nexport interface SessionConfig extends CreateEnclaveOptions {\n /**\n * Session resource limits\n * Overrides individual config values when provided\n */\n limits?: Partial<SessionLimits>;\n\n /**\n * Heartbeat interval in milliseconds\n * Set to 0 to disable heartbeats\n * @default 15000\n */\n heartbeatIntervalMs?: number;\n\n /**\n * Enable encryption for streaming events\n * @default false\n */\n encryption?: boolean;\n}\n\n/**\n * Pending tool call information\n *\n * Represents a tool call that the runtime is waiting for.\n */\nexport interface PendingToolCall {\n /**\n * Unique call identifier\n */\n callId: CallId;\n\n /**\n * Name of the tool being called\n */\n toolName: string;\n\n /**\n * Arguments passed to the tool (may contain refs)\n */\n args: Record<string, unknown>;\n\n /**\n * Timestamp when the call was initiated\n */\n timestamp: number;\n}\n\n/**\n * Async tool handler for session mode\n *\n * Unlike the synchronous ToolHandler, this returns void and the result\n * is submitted separately via the session's submitToolResult method.\n * This allows for long-running tool calls that don't block the session.\n */\nexport type AsyncToolHandler = (\n callId: CallId,\n toolName: string,\n args: Record<string, unknown>,\n) => void | Promise<void>;\n\n/**\n * Tool result to submit back to the session\n */\nexport interface ToolResult {\n /**\n * The call ID this result is for\n */\n callId: CallId;\n\n /**\n * Whether the tool call succeeded\n */\n success: boolean;\n\n /**\n * Result value (if successful)\n */\n value?: unknown;\n\n /**\n * Error information (if failed)\n */\n error?: {\n message: string;\n code?: string;\n data?: Record<string, unknown>;\n };\n}\n\n/**\n * Session event emitter interface\n *\n * Provides typed event emission for session lifecycle.\n */\nexport interface SessionEventEmitter {\n /**\n * Emit a stream event\n */\n emit(event: StreamEvent): void;\n\n /**\n * Subscribe to stream events\n */\n on(handler: (event: StreamEvent) => void): () => void;\n\n /**\n * Get all emitted events (for testing/debugging)\n */\n getEmittedEvents(): StreamEvent[];\n}\n\n/**\n * Session instance interface\n *\n * Represents an active execution session that can receive tool results\n * and emit streaming events.\n */\nexport interface Session {\n /**\n * Unique session identifier\n */\n readonly sessionId: SessionId;\n\n /**\n * Current session state\n */\n readonly state: SessionStateValue;\n\n /**\n * Current sequence number for events\n */\n readonly seq: number;\n\n /**\n * Pending tool call (when in waiting_for_tool state)\n */\n readonly pendingToolCall: PendingToolCall | null;\n\n /**\n * Session creation timestamp\n */\n readonly createdAt: number;\n\n /**\n * Session expiration timestamp\n */\n readonly expiresAt: number;\n\n /**\n * Event emitter for this session\n */\n readonly events: SessionEventEmitter;\n\n /**\n * Submit a tool result to resume execution\n *\n * @param result - The tool result to submit\n * @throws Error if session is not in waiting_for_tool state\n * @throws Error if result callId doesn't match pending call\n */\n submitToolResult(result: ToolResult): Promise<void>;\n\n /**\n * Cancel the session\n *\n * @param reason - Optional cancellation reason\n */\n cancel(reason?: string): Promise<void>;\n\n /**\n * Wait for the session to complete\n *\n * @returns Final execution result\n */\n wait(): Promise<SessionFinalResult>;\n\n /**\n * Get current execution statistics\n */\n getStats(): ExecutionStats;\n}\n\n/**\n * Final result when session completes\n */\nexport interface SessionFinalResult {\n /**\n * Whether execution was successful\n */\n success: boolean;\n\n /**\n * Return value from the script (if successful)\n */\n value?: unknown;\n\n /**\n * Error that occurred (if failed)\n */\n error?: {\n message: string;\n name: string;\n code?: string;\n data?: Record<string, unknown>;\n };\n\n /**\n * Execution statistics\n */\n stats: ExecutionStats;\n\n /**\n * Final session state\n */\n finalState: 'completed' | 'cancelled' | 'failed';\n}\n\n/**\n * Runtime channel abstraction\n *\n * Provides bidirectional communication between the broker and runtime.\n * Different implementations support embedded (in-process) and remote\n * (WebSocket) runtime execution.\n */\nexport interface RuntimeChannel {\n /**\n * Send a message to the runtime\n */\n send(message: RuntimeChannelMessage): void;\n\n /**\n * Subscribe to messages from the runtime\n */\n onMessage(handler: (event: StreamEvent) => void): () => void;\n\n /**\n * Close the channel\n */\n close(): void;\n\n /**\n * Whether the channel is open\n */\n readonly isOpen: boolean;\n}\n\n/**\n * Embedded runtime channel configuration\n *\n * For in-process execution where the Enclave runs in the same process.\n */\nexport interface EmbeddedChannelConfig {\n type: 'embedded';\n}\n\n/**\n * WebSocket runtime channel configuration\n *\n * For remote execution where the runtime is in a separate process/worker.\n */\nexport interface WebSocketChannelConfig {\n type: 'websocket';\n\n /**\n * WebSocket URL to connect to\n */\n url: string;\n\n /**\n * Reconnection options\n */\n reconnect?: {\n maxRetries?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n };\n}\n\n/**\n * Runtime channel configuration union\n */\nexport type RuntimeChannelConfig = EmbeddedChannelConfig | WebSocketChannelConfig;\n\n/**\n * Session manager interface\n *\n * Manages multiple concurrent sessions.\n */\nexport interface SessionManager {\n /**\n * Create a new session\n *\n * @param code - Code to execute\n * @param config - Session configuration\n * @param toolHandler - Handler for tool calls\n * @returns Created session\n */\n createSession(code: string, config?: SessionConfig, toolHandler?: AsyncToolHandler): Promise<Session>;\n\n /**\n * Get an existing session by ID\n */\n getSession(sessionId: SessionId): Session | undefined;\n\n /**\n * List all active sessions\n */\n listSessions(): Session[];\n\n /**\n * Terminate a session\n */\n terminateSession(sessionId: SessionId, reason?: string): Promise<void>;\n\n /**\n * Dispose of the manager and all sessions\n */\n dispose(): Promise<void>;\n}\n\n/**\n * Type guard for checking if an object is a Session\n */\nexport function isSession(obj: unknown): obj is Session {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'sessionId' in obj &&\n 'state' in obj &&\n 'submitToolResult' in obj &&\n typeof (obj as Session).submitToolResult === 'function'\n );\n}\n\n/**\n * Type guard for waiting_for_tool state\n */\nexport function isWaitingForTool(session: Session): boolean {\n return session.state === 'waiting_for_tool' && session.pendingToolCall !== null;\n}\n\n/**\n * Type guard for terminal states\n */\nexport function isTerminalState(state: SessionStateValue): boolean {\n return state === 'completed' || state === 'cancelled' || state === 'failed';\n}\n"]}
@@ -1,31 +0,0 @@
1
- "use strict";
2
- /**
3
- * Reference Sidecar Module
4
- *
5
- * Provides pass-by-reference support for the enclave execution environment.
6
- * Large data is stored in the sidecar with opaque reference IDs, and
7
- * references are resolved at the callTool boundary.
8
- *
9
- * @packageDocumentation
10
- */
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.isCompositeHandle = exports.ResolutionLimitError = exports.ReferenceResolver = exports.ReferenceNotFoundError = exports.SidecarLimitError = exports.ReferenceSidecar = exports.getReferenceConfig = exports.isReferenceId = exports.REF_ID_PATTERN = exports.REF_ID_SUFFIX = exports.REF_ID_PREFIX = exports.REFERENCE_CONFIGS = void 0;
13
- // Configuration
14
- var reference_config_1 = require("./reference-config");
15
- Object.defineProperty(exports, "REFERENCE_CONFIGS", { enumerable: true, get: function () { return reference_config_1.REFERENCE_CONFIGS; } });
16
- Object.defineProperty(exports, "REF_ID_PREFIX", { enumerable: true, get: function () { return reference_config_1.REF_ID_PREFIX; } });
17
- Object.defineProperty(exports, "REF_ID_SUFFIX", { enumerable: true, get: function () { return reference_config_1.REF_ID_SUFFIX; } });
18
- Object.defineProperty(exports, "REF_ID_PATTERN", { enumerable: true, get: function () { return reference_config_1.REF_ID_PATTERN; } });
19
- Object.defineProperty(exports, "isReferenceId", { enumerable: true, get: function () { return reference_config_1.isReferenceId; } });
20
- Object.defineProperty(exports, "getReferenceConfig", { enumerable: true, get: function () { return reference_config_1.getReferenceConfig; } });
21
- // Sidecar
22
- var reference_sidecar_1 = require("./reference-sidecar");
23
- Object.defineProperty(exports, "ReferenceSidecar", { enumerable: true, get: function () { return reference_sidecar_1.ReferenceSidecar; } });
24
- Object.defineProperty(exports, "SidecarLimitError", { enumerable: true, get: function () { return reference_sidecar_1.SidecarLimitError; } });
25
- Object.defineProperty(exports, "ReferenceNotFoundError", { enumerable: true, get: function () { return reference_sidecar_1.ReferenceNotFoundError; } });
26
- // Resolver
27
- var reference_resolver_1 = require("./reference-resolver");
28
- Object.defineProperty(exports, "ReferenceResolver", { enumerable: true, get: function () { return reference_resolver_1.ReferenceResolver; } });
29
- Object.defineProperty(exports, "ResolutionLimitError", { enumerable: true, get: function () { return reference_resolver_1.ResolutionLimitError; } });
30
- Object.defineProperty(exports, "isCompositeHandle", { enumerable: true, get: function () { return reference_resolver_1.isCompositeHandle; } });
31
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/sidecar/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAEH,gBAAgB;AAChB,uDAQ4B;AAN1B,qHAAA,iBAAiB,OAAA;AACjB,iHAAA,aAAa,OAAA;AACb,iHAAA,aAAa,OAAA;AACb,kHAAA,cAAc,OAAA;AACd,iHAAA,aAAa,OAAA;AACb,sHAAA,kBAAkB,OAAA;AAGpB,UAAU;AACV,yDAM6B;AAL3B,qHAAA,gBAAgB,OAAA;AAGhB,sHAAA,iBAAiB,OAAA;AACjB,2HAAA,sBAAsB,OAAA;AAGxB,WAAW;AACX,2DAAmH;AAA1G,uHAAA,iBAAiB,OAAA;AAAE,0HAAA,oBAAoB,OAAA;AAAmB,uHAAA,iBAAiB,OAAA","sourcesContent":["/**\n * Reference Sidecar Module\n *\n * Provides pass-by-reference support for the enclave execution environment.\n * Large data is stored in the sidecar with opaque reference IDs, and\n * references are resolved at the callTool boundary.\n *\n * @packageDocumentation\n */\n\n// Configuration\nexport {\n ReferenceConfig,\n REFERENCE_CONFIGS,\n REF_ID_PREFIX,\n REF_ID_SUFFIX,\n REF_ID_PATTERN,\n isReferenceId,\n getReferenceConfig,\n} from './reference-config';\n\n// Sidecar\nexport {\n ReferenceSidecar,\n ReferenceSource,\n ReferenceMetadata,\n SidecarLimitError,\n ReferenceNotFoundError,\n} from './reference-sidecar';\n\n// Resolver\nexport { ReferenceResolver, ResolutionLimitError, CompositeHandle, isCompositeHandle } from './reference-resolver';\n"]}
@@ -1,118 +0,0 @@
1
- "use strict";
2
- /**
3
- * Reference Sidecar Configuration
4
- *
5
- * Defines security-level-specific configurations for the reference sidecar.
6
- * These settings control how large data is handled in the pass-by-reference system.
7
- *
8
- * @packageDocumentation
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.REF_ID_PATTERN = exports.REF_ID_SUFFIX = exports.REF_ID_PREFIX = exports.REFERENCE_CONFIGS = void 0;
12
- exports.isReferenceId = isReferenceId;
13
- exports.getReferenceConfig = getReferenceConfig;
14
- /**
15
- * Reference configurations per security level
16
- *
17
- * These configurations align with the enclave's security levels
18
- * and provide appropriate limits for different trust scenarios.
19
- */
20
- exports.REFERENCE_CONFIGS = {
21
- /**
22
- * STRICT: Maximum security for untrusted code
23
- *
24
- * - Very small limits to prevent any memory-based attacks
25
- * - No composite handles (references cannot be concatenated)
26
- * - Aggressive extraction threshold
27
- */
28
- STRICT: {
29
- maxTotalSize: 16 * 1024 * 1024, // 16MB total
30
- maxReferenceSize: 4 * 1024 * 1024, // 4MB per reference
31
- extractionThreshold: 64 * 1024, // 64KB extraction threshold
32
- maxResolvedSize: 8 * 1024 * 1024, // 8MB max resolved
33
- allowComposites: false, // No concatenation of references
34
- maxReferenceCount: 50, // Max 50 references
35
- maxResolutionDepth: 5, // Shallow resolution
36
- },
37
- /**
38
- * SECURE: High security with more headroom
39
- *
40
- * - Moderate limits for trusted AI code
41
- * - No composite handles by default
42
- * - Standard extraction threshold
43
- */
44
- SECURE: {
45
- maxTotalSize: 64 * 1024 * 1024, // 64MB total
46
- maxReferenceSize: 16 * 1024 * 1024, // 16MB per reference
47
- extractionThreshold: 256 * 1024, // 256KB extraction threshold
48
- maxResolvedSize: 32 * 1024 * 1024, // 32MB max resolved
49
- allowComposites: false, // No concatenation of references
50
- maxReferenceCount: 100, // Max 100 references
51
- maxResolutionDepth: 10, // Moderate resolution depth
52
- },
53
- /**
54
- * STANDARD: Balanced security and functionality
55
- *
56
- * - Standard limits for internal tools
57
- * - Composite handles allowed
58
- * - Larger extraction threshold
59
- */
60
- STANDARD: {
61
- maxTotalSize: 256 * 1024 * 1024, // 256MB total
62
- maxReferenceSize: 64 * 1024 * 1024, // 64MB per reference
63
- extractionThreshold: 1024 * 1024, // 1MB extraction threshold
64
- maxResolvedSize: 128 * 1024 * 1024, // 128MB max resolved
65
- allowComposites: true, // Allow concatenation
66
- maxReferenceCount: 500, // Max 500 references
67
- maxResolutionDepth: 20, // Deep resolution
68
- },
69
- /**
70
- * PERMISSIVE: Minimal restrictions
71
- *
72
- * - Large limits for development/debugging
73
- * - All features enabled
74
- * - High extraction threshold
75
- */
76
- PERMISSIVE: {
77
- maxTotalSize: 1024 * 1024 * 1024, // 1GB total
78
- maxReferenceSize: 256 * 1024 * 1024, // 256MB per reference
79
- extractionThreshold: 4 * 1024 * 1024, // 4MB extraction threshold
80
- maxResolvedSize: 512 * 1024 * 1024, // 512MB max resolved
81
- allowComposites: true, // Allow concatenation
82
- maxReferenceCount: 1000, // Max 1000 references
83
- maxResolutionDepth: 50, // Very deep resolution
84
- },
85
- };
86
- /**
87
- * Reference ID prefix constant
88
- *
89
- * Reference IDs follow the format: __REF_[UUIDv4]__
90
- * The __REF_ prefix is protected by ReservedPrefixRule in ast-guard
91
- */
92
- exports.REF_ID_PREFIX = '__REF_';
93
- /**
94
- * Reference ID suffix constant
95
- *
96
- * Used with REF_ID_PREFIX to form complete reference IDs: __REF_[UUIDv4]__
97
- */
98
- exports.REF_ID_SUFFIX = '__';
99
- /**
100
- * Regular expression to match reference IDs
101
- */
102
- exports.REF_ID_PATTERN = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
103
- /**
104
- * Check if a string is a reference ID
105
- */
106
- function isReferenceId(value) {
107
- return typeof value === 'string' && exports.REF_ID_PATTERN.test(value);
108
- }
109
- /**
110
- * Get reference config for a security level, with optional overrides
111
- */
112
- function getReferenceConfig(securityLevel, overrides) {
113
- return {
114
- ...exports.REFERENCE_CONFIGS[securityLevel],
115
- ...overrides,
116
- };
117
- }
118
- //# sourceMappingURL=reference-config.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"reference-config.js","sourceRoot":"","sources":["../../../src/sidecar/reference-config.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAsJH,sCAEC;AAKD,gDAQC;AAlHD;;;;;GAKG;AACU,QAAA,iBAAiB,GAA2C;IACvE;;;;;;OAMG;IACH,MAAM,EAAE;QACN,YAAY,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,aAAa;QAC7C,gBAAgB,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,oBAAoB;QACvD,mBAAmB,EAAE,EAAE,GAAG,IAAI,EAAE,4BAA4B;QAC5D,eAAe,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,mBAAmB;QACrD,eAAe,EAAE,KAAK,EAAE,iCAAiC;QACzD,iBAAiB,EAAE,EAAE,EAAE,oBAAoB;QAC3C,kBAAkB,EAAE,CAAC,EAAE,qBAAqB;KAC7C;IAED;;;;;;OAMG;IACH,MAAM,EAAE;QACN,YAAY,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,aAAa;QAC7C,gBAAgB,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,qBAAqB;QACzD,mBAAmB,EAAE,GAAG,GAAG,IAAI,EAAE,6BAA6B;QAC9D,eAAe,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,oBAAoB;QACvD,eAAe,EAAE,KAAK,EAAE,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ED;;GAEG;AACH,SAAgB,kBAAkB,CAChC,aAA4B,EAC5B,SAAoC;IAEpC,OAAO;QACL,GAAG,yBAAiB,CAAC,aAAa,CAAC;QACnC,GAAG,SAAS;KACb,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Reference Sidecar Configuration\n *\n * Defines security-level-specific configurations for the reference sidecar.\n * These settings control how large data is handled in the pass-by-reference system.\n *\n * @packageDocumentation\n */\n\nimport type { SecurityLevel } from '../types';\n\n/**\n * Configuration for the reference sidecar system\n */\nexport interface ReferenceConfig {\n /**\n * Maximum total size of all stored references in bytes\n * Prevents memory exhaustion from excessive data storage\n */\n maxTotalSize: number;\n\n /**\n * Maximum size of a single reference in bytes\n * Prevents individual large allocations\n */\n maxReferenceSize: number;\n\n /**\n * Threshold in bytes to trigger extraction from source code\n * Strings larger than this are lifted to the sidecar\n */\n extractionThreshold: number;\n\n /**\n * Maximum expanded size when resolving references for tool calls\n * Prevents predictive expansion attacks\n */\n maxResolvedSize: number;\n\n /**\n * Whether to allow composite handles from concatenation\n * If false, __safe_concat__ throws when references are detected\n */\n allowComposites: boolean;\n\n /**\n * Maximum number of references in a single execution\n * Prevents reference flooding attacks\n */\n maxReferenceCount: number;\n\n /**\n * Maximum depth when resolving nested references\n * Prevents recursive reference bombs\n */\n maxResolutionDepth: number;\n}\n\n/**\n * Reference configurations per security level\n *\n * These configurations align with the enclave's security levels\n * and provide appropriate limits for different trust scenarios.\n */\nexport const REFERENCE_CONFIGS: Record<SecurityLevel, ReferenceConfig> = {\n /**\n * STRICT: Maximum security for untrusted code\n *\n * - Very small limits to prevent any memory-based attacks\n * - No composite handles (references cannot be concatenated)\n * - Aggressive extraction threshold\n */\n STRICT: {\n maxTotalSize: 16 * 1024 * 1024, // 16MB total\n maxReferenceSize: 4 * 1024 * 1024, // 4MB per reference\n extractionThreshold: 64 * 1024, // 64KB extraction threshold\n maxResolvedSize: 8 * 1024 * 1024, // 8MB max resolved\n allowComposites: false, // No concatenation of references\n maxReferenceCount: 50, // Max 50 references\n maxResolutionDepth: 5, // Shallow resolution\n },\n\n /**\n * SECURE: High security with more headroom\n *\n * - Moderate limits for trusted AI code\n * - No composite handles by default\n * - Standard extraction threshold\n */\n SECURE: {\n maxTotalSize: 64 * 1024 * 1024, // 64MB total\n maxReferenceSize: 16 * 1024 * 1024, // 16MB per reference\n extractionThreshold: 256 * 1024, // 256KB extraction threshold\n maxResolvedSize: 32 * 1024 * 1024, // 32MB max resolved\n allowComposites: false, // No concatenation of references\n maxReferenceCount: 100, // Max 100 references\n maxResolutionDepth: 10, // Moderate resolution depth\n },\n\n /**\n * STANDARD: Balanced security and functionality\n *\n * - Standard limits for internal tools\n * - Composite handles allowed\n * - Larger extraction threshold\n */\n STANDARD: {\n maxTotalSize: 256 * 1024 * 1024, // 256MB total\n maxReferenceSize: 64 * 1024 * 1024, // 64MB per reference\n extractionThreshold: 1024 * 1024, // 1MB extraction threshold\n maxResolvedSize: 128 * 1024 * 1024, // 128MB max resolved\n allowComposites: true, // Allow concatenation\n maxReferenceCount: 500, // Max 500 references\n maxResolutionDepth: 20, // Deep resolution\n },\n\n /**\n * PERMISSIVE: Minimal restrictions\n *\n * - Large limits for development/debugging\n * - All features enabled\n * - High extraction threshold\n */\n PERMISSIVE: {\n maxTotalSize: 1024 * 1024 * 1024, // 1GB total\n maxReferenceSize: 256 * 1024 * 1024, // 256MB per reference\n extractionThreshold: 4 * 1024 * 1024, // 4MB extraction threshold\n maxResolvedSize: 512 * 1024 * 1024, // 512MB max resolved\n allowComposites: true, // Allow concatenation\n maxReferenceCount: 1000, // Max 1000 references\n maxResolutionDepth: 50, // Very deep resolution\n },\n};\n\n/**\n * Reference ID prefix constant\n *\n * Reference IDs follow the format: __REF_[UUIDv4]__\n * The __REF_ prefix is protected by ReservedPrefixRule in ast-guard\n */\nexport const REF_ID_PREFIX = '__REF_';\n\n/**\n * Reference ID suffix constant\n *\n * Used with REF_ID_PREFIX to form complete reference IDs: __REF_[UUIDv4]__\n */\nexport const REF_ID_SUFFIX = '__';\n\n/**\n * Regular expression to match reference IDs\n */\nexport const REF_ID_PATTERN = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;\n\n/**\n * Check if a string is a reference ID\n */\nexport function isReferenceId(value: unknown): value is string {\n return typeof value === 'string' && REF_ID_PATTERN.test(value);\n}\n\n/**\n * Get reference config for a security level, with optional overrides\n */\nexport function getReferenceConfig(\n securityLevel: SecurityLevel,\n overrides?: Partial<ReferenceConfig>,\n): ReferenceConfig {\n return {\n ...REFERENCE_CONFIGS[securityLevel],\n ...overrides,\n };\n}\n"]}
@@ -1,262 +0,0 @@
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
@@ -1 +0,0 @@
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,iBAAiB;IAET;IACA;IAFnB,YACmB,OAAyB,EACzB,MAAuB;QADvB,YAAO,GAAP,OAAO,CA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,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"]}